You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ternary_conv.py 5.9 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import tensorlayer as tl
  4. from tensorlayer import logging
  5. from tensorlayer.layers.core import Module
  6. from tensorlayer.layers.utils import compute_alpha, ternary_operation
  7. __all__ = ['TernaryConv2d']
  8. class TernaryConv2d(Module):
  9. """
  10. The :class:`TernaryConv2d` class is a 2D ternary CNN layer, which weights are either -1 or 1 or 0 while inference.
  11. Note that, the bias vector would not be tenarized.
  12. Parameters
  13. ----------
  14. n_filter : int
  15. The number of filters.
  16. filter_size : tuple of int
  17. The filter size (height, width).
  18. strides : tuple of int
  19. The sliding window strides of corresponding input dimensions.
  20. It must be in the same order as the ``shape`` parameter.
  21. act : activation function
  22. The activation function of this layer.
  23. padding : str
  24. The padding algorithm type: "SAME" or "VALID".
  25. use_gemm : boolean
  26. If True, use gemm instead of ``tf.matmul`` for inference.
  27. TODO: support gemm
  28. data_format : str
  29. "channels_last" (NHWC, default) or "channels_first" (NCHW).
  30. dilation_rate : tuple of int
  31. Specifying the dilation rate to use for dilated convolution.
  32. W_init : initializer
  33. The initializer for the the weight matrix.
  34. b_init : initializer or None
  35. The initializer for the the bias vector. If None, skip biases.
  36. in_channels : int
  37. The number of in channels.
  38. name : None or str
  39. A unique layer name.
  40. Examples
  41. ---------
  42. With TensorLayer
  43. >>> net = tl.layers.Input([8, 12, 12, 32], name='input')
  44. >>> ternaryconv2d = tl.layers.TernaryConv2d(
  45. ... n_filter=64, filter_size=(5, 5), strides=(1, 1), act=tl.ReLU, padding='SAME', name='ternaryconv2d'
  46. ... )(net)
  47. >>> print(ternaryconv2d)
  48. >>> output shape : (8, 12, 12, 64)
  49. """
  50. def __init__(
  51. self,
  52. n_filter=32,
  53. filter_size=(3, 3),
  54. strides=(1, 1),
  55. act=None,
  56. padding='SAME',
  57. use_gemm=False,
  58. data_format="channels_last",
  59. dilation_rate=(1, 1),
  60. W_init=tl.initializers.truncated_normal(stddev=0.02),
  61. b_init=tl.initializers.constant(value=0.0),
  62. in_channels=None,
  63. name=None # 'ternary_cnn2d',
  64. ):
  65. super().__init__(name, act=act)
  66. self.n_filter = n_filter
  67. self.filter_size = filter_size
  68. self.strides = self._strides = strides
  69. self.padding = padding
  70. self.use_gemm = use_gemm
  71. self.data_format = data_format
  72. self.dilation_rate = self._dilation_rate = dilation_rate
  73. self.W_init = W_init
  74. self.b_init = b_init
  75. self.in_channels = in_channels
  76. if self.in_channels:
  77. self.build(None)
  78. self._built = True
  79. logging.info(
  80. "TernaryConv2d %s: n_filter: %d filter_size: %s strides: %s pad: %s act: %s" % (
  81. self.name, n_filter, str(filter_size), str(strides), padding,
  82. self.act.__class__.__name__ if self.act is not None else 'No Activation'
  83. )
  84. )
  85. if use_gemm:
  86. raise Exception("TODO. The current version use tf.matmul for inferencing.")
  87. if len(self.strides) != 2:
  88. raise ValueError("len(strides) should be 2.")
  89. def __repr__(self):
  90. actstr = self.act.__name__ if self.act is not None else 'No Activation'
  91. s = (
  92. '{classname}(in_channels={in_channels}, out_channels={n_filter}, kernel_size={filter_size}'
  93. ', strides={strides}, padding={padding}'
  94. )
  95. if self.dilation_rate != (1, ) * len(self.dilation_rate):
  96. s += ', dilation={dilation_rate}'
  97. if self.b_init is None:
  98. s += ', bias=False'
  99. s += (', ' + actstr)
  100. if self.name is not None:
  101. s += ', name=\'{name}\''
  102. s += ')'
  103. return s.format(classname=self.__class__.__name__, **self.__dict__)
  104. def build(self, inputs_shape):
  105. if self.data_format == 'channels_last':
  106. self.data_format = 'NHWC'
  107. if self.in_channels is None:
  108. self.in_channels = inputs_shape[-1]
  109. self._strides = [1, self._strides[0], self._strides[1], 1]
  110. self._dilation_rate = [1, self._dilation_rate[0], self._dilation_rate[1], 1]
  111. elif self.data_format == 'channels_first':
  112. self.data_format = 'NCHW'
  113. if self.in_channels is None:
  114. self.in_channels = inputs_shape[1]
  115. self._strides = [1, 1, self._strides[0], self._strides[1]]
  116. self._dilation_rate = [1, 1, self._dilation_rate[0], self._dilation_rate[1]]
  117. else:
  118. raise Exception("data_format should be either channels_last or channels_first")
  119. self.filter_shape = (self.filter_size[0], self.filter_size[1], self.in_channels, self.n_filter)
  120. self.W = self._get_weights("filters", shape=self.filter_shape, init=self.W_init)
  121. if self.b_init:
  122. self.b = self._get_weights("biases", shape=(self.n_filter, ), init=self.b_init)
  123. self.bias_add = tl.ops.BiasAdd(data_format=self.data_format)
  124. self.conv2d = tl.ops.Conv2D(
  125. strides=self._strides, padding=self.padding, data_format=self.data_format, dilations=self._dilation_rate
  126. )
  127. def forward(self, inputs):
  128. if self._forward_state == False:
  129. if self._built == False:
  130. self.build(tl.get_tensor_shape(inputs))
  131. self._built = True
  132. self._forward_state = True
  133. alpha = compute_alpha(self.W)
  134. W_ = ternary_operation(self.W)
  135. W_ = tl.ops.multiply(alpha, W_)
  136. outputs = self.conv2d(inputs, W_)
  137. if self.b_init:
  138. outputs = self.bias_add(outputs, self.b)
  139. if self.act:
  140. outputs = self.act(outputs)
  141. return outputs

TensorLayer3.0 是一款兼容多种深度学习框架为计算后端的深度学习库。计划兼容TensorFlow, Pytorch, MindSpore, Paddle.