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.

conv.py 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """conv"""
  16. from mindspore import log as logger
  17. from mindspore.ops import operations as P
  18. from mindspore.common.parameter import Parameter
  19. from mindspore.common.initializer import initializer
  20. from mindspore._checkparam import check_bool, twice, check_int_positive, check_int_non_negative
  21. from mindspore._extends import cell_attr_register
  22. from ..cell import Cell
  23. class _Conv(Cell):
  24. """
  25. Applies a N-D convolution over an input signal composed of several input planes.
  26. """
  27. def __init__(self,
  28. in_channels,
  29. out_channels,
  30. kernel_size,
  31. stride,
  32. pad_mode,
  33. padding,
  34. dilation,
  35. group,
  36. has_bias,
  37. weight_init,
  38. bias_init):
  39. super(_Conv, self).__init__()
  40. self.in_channels = check_int_positive(in_channels)
  41. self.out_channels = check_int_positive(out_channels)
  42. self.kernel_size = kernel_size
  43. self.stride = stride
  44. self.pad_mode = pad_mode
  45. self.padding = check_int_non_negative(padding)
  46. self.dilation = dilation
  47. self.group = check_int_positive(group)
  48. self.has_bias = has_bias
  49. if (not isinstance(kernel_size[0], int)) or (not isinstance(kernel_size[1], int)) or \
  50. kernel_size[0] < 1 or kernel_size[1] < 1:
  51. raise ValueError("Attr 'kernel_size' of 'Conv2D' Op passed "
  52. + str(self.kernel_size) + ", should be a int or tuple and equal to or greater than 1.")
  53. if (not isinstance(stride[0], int)) or (not isinstance(stride[1], int)) or stride[0] < 1 or stride[1] < 1:
  54. raise ValueError("Attr 'stride' of 'Conv2D' Op passed "
  55. + str(self.stride) + ", should be a int or tuple and equal to or greater than 1.")
  56. if (not isinstance(dilation[0], int)) or (not isinstance(dilation[1], int)) or \
  57. dilation[0] < 1 or dilation[1] < 1:
  58. raise ValueError("Attr 'dilation' of 'Conv2D' Op passed "
  59. + str(self.dilation) + ", should equal to or greater than 1.")
  60. if in_channels % group != 0:
  61. raise ValueError("Attr 'in_channels' of 'Conv2D' Op must be divisible by "
  62. "attr 'group' of 'Conv2D' Op.")
  63. if out_channels % group != 0:
  64. raise ValueError("Attr 'out_channels' of 'Conv2D' Op must be divisible by "
  65. "attr 'group' of 'Conv2D' Op.")
  66. self.weight = Parameter(initializer(weight_init, [out_channels, in_channels // group, *kernel_size]),
  67. name='weight')
  68. if check_bool(has_bias):
  69. self.bias = Parameter(initializer(bias_init, [out_channels]), name='bias')
  70. else:
  71. if bias_init != 'zeros':
  72. logger.warning("Value of 'has_bias' is False, value of 'bias_init' will be ignored.")
  73. self.bias = None
  74. def construct(self, *inputs):
  75. """Must be overridden by all subclasses."""
  76. raise NotImplementedError
  77. class Conv2d(_Conv):
  78. r"""
  79. 2D convolution layer.
  80. Applies a 2D convolution over an input tensor which is typically of shape :math:`(N, C_{in}, H_{in}, W_{in})`,
  81. where :math:`N` is batch size and :math:`C_{in}` is channel number. For each batch of shape
  82. :math:`(C_{in}, H_{in}, W_{in})`, the formula is defined as:
  83. .. math::
  84. out_j = \sum_{i=0}^{C_{in} - 1} ccor(W_{ij}, X_i) + b_j,
  85. where :math:`ccor` is cross correlation operator, :math:`C_{in}` is the input channel number, :math:`j` ranges
  86. from :math:`0` to :math:`C_{out} - 1`, :math:`W_{ij}` corresponds to :math:`i`-th channel of the :math:`j`-th
  87. filter and :math:`out_{j}` corresponds to the :math:`j`-th channel of the output. :math:`W_{ij}` is a slice
  88. of kernel and it has shape :math:`(\text{ks_h}, \text{ks_w})`, where :math:`\text{ks_h}` and
  89. :math:`\text{ks_w}` are height and width of the convolution kernel. The full kernel has shape
  90. :math:`(C_{out}, C_{in} // \text{group}, \text{ks_h}, \text{ks_w})`, where group is the group number
  91. to split the input in the channel dimension.
  92. If the 'pad_mode' is set to be "valid", the output height and width will be
  93. :math:`\left \lfloor{1 + \frac{H_{in} + 2 \times \text{padding} - \text{ks_h} -
  94. (\text{ks_h} - 1) \times (\text{dilation} - 1) }{\text{stride}}} \right \rfloor` and
  95. :math:`\left \lfloor{1 + \frac{W_{in} + 2 \times \text{padding} - \text{ks_w} -
  96. (\text{ks_w} - 1) \times (\text{dilation} - 1) }{\text{stride}}} \right \rfloor` respectively.
  97. The first introduction can be found in paper `Gradient Based Learning Applied to Document Recognition
  98. <http://vision.stanford.edu/cs598_spring07/papers/Lecun98.pdf>`_.
  99. Args:
  100. in_channels (int): The number of input channel :math:`C_{in}`.
  101. out_channels (int): The number of output channel :math:`C_{out}`.
  102. kernel_size (Union[int, tuple[int]]): The data type is int or tuple with 2 integers. Specifies the height
  103. and width of the 2D convolution window. Single int means the value if for both height and width of
  104. the kernel. A tuple of 2 ints means the first value is for the height and the other is for the
  105. width of the kernel.
  106. stride (Union[int, tuple[int]]): The distance of kernel moving, an int number that represents
  107. the height and width of movement are both strides, or a tuple of two int numbers that
  108. represent height and width of movement respectively. Default: 1.
  109. pad_mode (str): Specifies padding mode. The optional values are
  110. "same", "valid", "pad". Default: "same".
  111. - same: Adopts the way of completion. Output height and width will be the same as the input.
  112. Total number of padding will be calculated for horizontal and vertical
  113. direction and evenly distributed to top and bottom, left and right if possible. Otherwise, the
  114. last extra padding will be done from the bottom and the right side. If this mode is set, `padding`
  115. must be 0.
  116. - valid: Adopts the way of discarding. The possibly largest height and width of output will be return
  117. without padding. Extra pixels will be discarded. If this mode is set, `padding`
  118. must be 0.
  119. - pad: Implicit paddings on both sides of the input. The number of `padding` will be padded to the input
  120. Tensor borders. `padding` should be greater than or equal to 0.
  121. padding (int): Implicit paddings on both sides of the input. Default: 0.
  122. dilation (Union[int, tuple[int]]): The data type is int or tuple with 2 integers. Specifies the dilation rate
  123. to use for dilated convolution. If set to be :math:`k > 1`, there will
  124. be :math:`k - 1` pixels skipped for each sampling location. Its value should
  125. be greater or equal to 1 and bounded by the height and width of the
  126. input. Default: 1.
  127. group (int): Split filter into groups, `in_ channels` and `out_channels` should be
  128. divisible by the number of groups. Default: 1.
  129. has_bias (bool): Specifies whether the layer uses a bias vector. Default: False.
  130. weight_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the convolution kernel.
  131. It can be a Tensor, a string, an Initializer or a numbers.Number. When a string is specified,
  132. values from 'TruncatedNormal', 'Normal', 'Uniform', 'HeUniform' and 'XavierUniform' distributions as well
  133. as constant 'One' and 'Zero' distributions are possible. Alias 'xavier_uniform', 'he_uniform', 'ones'
  134. and 'zeros' are acceptable. Uppercase and lowercase are both acceptable. Refer to the values of
  135. Initializer for more details. Default: 'normal'.
  136. bias_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the bias vector. Possible
  137. Initializer and string are the same as 'weight_init'. Refer to the values of
  138. Initializer for more details. Default: 'zeros'.
  139. Inputs:
  140. - **input** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.
  141. Outputs:
  142. Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`.
  143. Examples:
  144. >>> net = nn.Conv2d(120, 240, 4, has_bias=False, weight_init='normal')
  145. >>> input = Tensor(np.ones([1, 120, 1024, 640]), mindspore.float32)
  146. >>> net(input).shape()
  147. (1, 240, 1024, 640)
  148. """
  149. @cell_attr_register
  150. def __init__(self,
  151. in_channels,
  152. out_channels,
  153. kernel_size,
  154. stride=1,
  155. pad_mode='same',
  156. padding=0,
  157. dilation=1,
  158. group=1,
  159. has_bias=False,
  160. weight_init='normal',
  161. bias_init='zeros'):
  162. kernel_size = twice(kernel_size)
  163. stride = twice(stride)
  164. dilation = twice(dilation)
  165. super(Conv2d, self).__init__(
  166. in_channels,
  167. out_channels,
  168. kernel_size,
  169. stride,
  170. pad_mode,
  171. padding,
  172. dilation,
  173. group,
  174. has_bias,
  175. weight_init,
  176. bias_init)
  177. self.conv2d = P.Conv2D(out_channel=self.out_channels,
  178. kernel_size=self.kernel_size,
  179. mode=1,
  180. pad_mode=self.pad_mode,
  181. pad=self.padding,
  182. stride=self.stride,
  183. dilation=self.dilation,
  184. group=self.group)
  185. self.bias_add = P.BiasAdd()
  186. if pad_mode not in ('valid', 'same', 'pad'):
  187. raise ValueError('Attr \'pad_mode\' of \'Conv2d\' Op passed '
  188. + str(pad_mode) + ', should be one of values in \'valid\', \'same\', \'pad\'.')
  189. def construct(self, x):
  190. output = self.conv2d(x, self.weight)
  191. if self.has_bias:
  192. output = self.bias_add(output, self.bias)
  193. return output
  194. def extend_repr(self):
  195. s = 'input_channels={}, output_channels={}, kernel_size={},' \
  196. 'stride={}, pad_mode={}, padding={}, dilation={}, ' \
  197. 'group={}, has_bias={},' \
  198. 'weight_init={}, bias_init={}'.format(
  199. self.in_channels,
  200. self.out_channels,
  201. self.kernel_size,
  202. self.stride,
  203. self.pad_mode,
  204. self.padding,
  205. self.dilation,
  206. self.group,
  207. self.has_bias,
  208. self.weight,
  209. self.bias)
  210. if self.has_bias:
  211. s += ', bias={}'.format(self.bias)
  212. return s
  213. class Conv2dTranspose(_Conv):
  214. r"""
  215. 2D transposed convolution layer.
  216. Compute a 2D transposed convolution, which is also know as a deconvolution
  217. (although it is not actual deconvolution).
  218. Input is typically of shape :math:`(N, C, H, W)`, where :math:`N` is batch size and :math:`C` is channel number.
  219. Args:
  220. in_channels (int): The number of channels in the input space.
  221. out_channels (int): The number of channels in the output space.
  222. kernel_size (Union[int, tuple]): int or tuple with 2 integers, which specifies the height
  223. and width of the 2D convolution window. Single int means the value is for both height and width of
  224. the kernel. A tuple of 2 ints means the first value is for the height and the other is for the
  225. width of the kernel.
  226. stride (Union[int, tuple[int]]): The distance of kernel moving, an int number that represents
  227. the height and width of movement are both strides, or a tuple of two int numbers that
  228. represent height and width of movement respectively. Default: 1.
  229. pad_mode (str): Select the mode of the pad. The optional values are
  230. "pad", "same", "valid". Default: "same".
  231. - pad: Implicit paddings on both sides of the input.
  232. - same: Adopted the way of completion.
  233. - valid: Adopted the way of discarding.
  234. padding (int): Implicit paddings on both sides of the input. Default: 0.
  235. dilation (Union[int, tuple[int]]): The data type is int or tuple with 2 integers. Specifies the dilation rate
  236. to use for dilated convolution. If set to be :math:`k > 1`, there will
  237. be :math:`k - 1` pixels skipped for each sampling location. Its value should
  238. be greater or equal to 1 and bounded by the height and width of the
  239. input. Default: 1.
  240. group (int): Split filter into groups, `in_channels` and `out_channels` should be
  241. divisible by the number of groups. Default: 1.
  242. has_bias (bool): Specifies whether the layer uses a bias vector. Default: False.
  243. weight_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the convolution kernel.
  244. It can be a Tensor, a string, an Initializer or a numbers.Number. When a string is specified,
  245. values from 'TruncatedNormal', 'Normal', 'Uniform', 'HeUniform' and 'XavierUniform' distributions as well
  246. as constant 'One' and 'Zero' distributions are possible. Alias 'xavier_uniform', 'he_uniform', 'ones'
  247. and 'zeros' are acceptable. Uppercase and lowercase are both acceptable. Refer to the values of
  248. Initializer for more details. Default: 'normal'.
  249. bias_init (Union[Tensor, str, Initializer, numbers.Number]): Initializer for the bias vector. Possible
  250. Initializer and string are the same as 'weight_init'. Refer to the values of
  251. Initializer for more details. Default: 'zeros'.
  252. Inputs:
  253. - **input** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.
  254. Outputs:
  255. Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`.
  256. Examples:
  257. >>> net = nn.Conv2dTranspose(3, 64, 4, has_bias=False, weight_init='normal')
  258. >>> input = Tensor(np.ones([1, 3, 16, 50]), mindspore.float32)
  259. >>> net(input)
  260. """
  261. def __init__(self,
  262. in_channels,
  263. out_channels,
  264. kernel_size,
  265. stride=1,
  266. pad_mode='same',
  267. padding=0,
  268. dilation=1,
  269. group=1,
  270. has_bias=False,
  271. weight_init='normal',
  272. bias_init='zeros'):
  273. kernel_size = twice(kernel_size)
  274. stride = twice(stride)
  275. dilation = twice(dilation)
  276. # out_channels and in_channels swap.
  277. # cause Conv2DBackpropInput's out_channel refers to Conv2D's out_channel,
  278. # then Conv2dTranspose's out_channel refers to Conv2DBackpropInput's in_channel.
  279. super(Conv2dTranspose, self).__init__(
  280. out_channels,
  281. in_channels,
  282. kernel_size,
  283. stride,
  284. pad_mode,
  285. padding,
  286. dilation,
  287. group,
  288. has_bias,
  289. weight_init,
  290. bias_init)
  291. self.out_channels = out_channels
  292. self.in_channels = in_channels
  293. self.shape = P.Shape()
  294. if pad_mode not in ('valid', 'same', 'pad'):
  295. raise ValueError('Attr \'pad_mode\' of \'Conv2dTranspose\' Op passed '
  296. + str(pad_mode) + ', should be one of values in \'valid\', \'same\', \'pad\'.')
  297. self.is_valid = self.pad_mode == 'valid'
  298. self.is_same = self.pad_mode == 'same'
  299. self.is_pad = self.pad_mode == 'pad'
  300. if check_bool(has_bias):
  301. self.bias = Parameter(initializer(bias_init, [out_channels]), name='bias')
  302. # cause Conv2DBackpropInput's out_channel refers to Conv2D's out_channel.
  303. self.conv2d_transpose = P.Conv2DBackpropInput(out_channel=in_channels,
  304. kernel_size=kernel_size,
  305. mode=1,
  306. pad_mode=pad_mode,
  307. pad=padding,
  308. stride=stride,
  309. dilation=dilation,
  310. group=group)
  311. self.bias_add = P.BiasAdd()
  312. def set_strategy(self, strategy):
  313. self.conv2d_transpose.set_strategy(strategy)
  314. return self
  315. def _deconv_output_length(self, input_length, filter_size, stride_size, dilation_size):
  316. """Calculate the width and height of output."""
  317. length = 0
  318. if self.is_valid:
  319. if filter_size - stride_size > 0:
  320. length = input_length * stride_size + filter_size - stride_size
  321. else:
  322. length = input_length * stride_size
  323. elif self.is_same:
  324. length = input_length * stride_size
  325. elif self.is_pad:
  326. length = input_length * stride_size - 2 * self.padding + filter_size + \
  327. (filter_size - 1) * (dilation_size - 1) - stride_size
  328. return length
  329. def construct(self, x):
  330. n, _, h, w = self.shape(x)
  331. h_out = self._deconv_output_length(h, self.kernel_size[0], self.stride[0], self.dilation[0])
  332. w_out = self._deconv_output_length(w, self.kernel_size[1], self.stride[1], self.dilation[1])
  333. if self.has_bias:
  334. return self.bias_add(self.conv2d_transpose(x, self.weight, (n, self.out_channels, h_out, w_out)),
  335. self.bias)
  336. return self.conv2d_transpose(x, self.weight, (n, self.out_channels, h_out, w_out))
  337. def extend_repr(self):
  338. s = 'input_channels={}, output_channels={}, kernel_size={},' \
  339. 'stride={}, pad_mode={}, padding={}, dilation={}, ' \
  340. 'group={}, has_bias={},' \
  341. 'weight_init={}, bias_init={}'.format(self.in_channels,
  342. self.out_channels,
  343. self.kernel_size,
  344. self.stride,
  345. self.pad_mode,
  346. self.padding,
  347. self.dilation,
  348. self.group,
  349. self.has_bias,
  350. self.weight,
  351. self.bias)
  352. return s