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.

resnet_quant_manual.py 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. """ResNet."""
  16. import numpy as np
  17. import mindspore.nn as nn
  18. import mindspore.common.initializer as weight_init
  19. from mindspore import Tensor
  20. from mindspore.ops import operations as P
  21. from mindspore.nn import FakeQuantWithMinMax, Conv2dBnFoldQuant as Conv2dBatchNormQuant
  22. _ema_decay = 0.999
  23. _symmetric = True
  24. _fake = True
  25. _per_channel = True
  26. def _weight_variable(shape, factor=0.01):
  27. init_value = np.random.randn(*shape).astype(np.float32) * factor
  28. return Tensor(init_value)
  29. def _conv3x3(in_channel, out_channel, stride=1):
  30. weight_shape = (out_channel, in_channel, 3, 3)
  31. weight = _weight_variable(weight_shape)
  32. return nn.Conv2d(in_channel, out_channel,
  33. kernel_size=3, stride=stride, padding=0, pad_mode='same', weight_init=weight)
  34. def _conv1x1(in_channel, out_channel, stride=1):
  35. weight_shape = (out_channel, in_channel, 1, 1)
  36. weight = _weight_variable(weight_shape)
  37. return nn.Conv2d(in_channel, out_channel,
  38. kernel_size=1, stride=stride, padding=0, pad_mode='same', weight_init=weight)
  39. def _conv7x7(in_channel, out_channel, stride=1):
  40. weight_shape = (out_channel, in_channel, 7, 7)
  41. weight = _weight_variable(weight_shape)
  42. return nn.Conv2d(in_channel, out_channel,
  43. kernel_size=7, stride=stride, padding=0, pad_mode='same', weight_init=weight)
  44. def _bn(channel):
  45. return nn.BatchNorm2d(channel, eps=1e-4, momentum=0.9,
  46. gamma_init=1, beta_init=0, moving_mean_init=0, moving_var_init=1)
  47. def _bn_last(channel):
  48. return nn.BatchNorm2d(channel, eps=1e-4, momentum=0.9,
  49. gamma_init=0, beta_init=0, moving_mean_init=0, moving_var_init=1)
  50. def _fc(in_channel, out_channel):
  51. weight_shape = (out_channel, in_channel)
  52. weight = _weight_variable(weight_shape)
  53. return nn.Dense(in_channel, out_channel, has_bias=True, weight_init=weight, bias_init=0)
  54. class ConvBNReLU(nn.Cell):
  55. """
  56. Convolution/Depthwise fused with Batchnorm and ReLU block definition.
  57. Args:
  58. in_planes (int): Input channel.
  59. out_planes (int): Output channel.
  60. kernel_size (int): Input kernel size.
  61. stride (int): Stride size for the first convolutional layer. Default: 1.
  62. groups (int): channel group. Convolution is 1 while Depthiwse is input channel. Default: 1.
  63. Returns:
  64. Tensor, output tensor.
  65. Examples:
  66. >>> ConvBNReLU(16, 256, kernel_size=1, stride=1, groups=1)
  67. """
  68. def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1):
  69. super(ConvBNReLU, self).__init__()
  70. padding = (kernel_size - 1) // 2
  71. conv = Conv2dBatchNormQuant(in_planes, out_planes, kernel_size, stride, pad_mode='pad', padding=padding,
  72. group=groups, fake=_fake, per_channel=_per_channel, symmetric=_symmetric)
  73. layers = [conv, nn.ActQuant(nn.ReLU())] if _fake else [conv, nn.ReLU()]
  74. self.features = nn.SequentialCell(layers)
  75. def construct(self, x):
  76. output = self.features(x)
  77. return output
  78. class ResidualBlock(nn.Cell):
  79. """
  80. ResNet V1 residual block definition.
  81. Args:
  82. in_channel (int): Input channel.
  83. out_channel (int): Output channel.
  84. stride (int): Stride size for the first convolutional layer. Default: 1.
  85. Returns:
  86. Tensor, output tensor.
  87. Examples:
  88. >>> ResidualBlock(3, 256, stride=2)
  89. """
  90. expansion = 4
  91. def __init__(self,
  92. in_channel,
  93. out_channel,
  94. stride=1):
  95. super(ResidualBlock, self).__init__()
  96. channel = out_channel // self.expansion
  97. self.conv1 = ConvBNReLU(in_channel, channel, kernel_size=1, stride=1)
  98. self.conv2 = ConvBNReLU(channel, channel, kernel_size=3, stride=stride)
  99. self.conv3 = nn.SequentialCell([Conv2dBatchNormQuant(channel, out_channel, fake=_fake, per_channel=_per_channel,
  100. symmetric=_symmetric,
  101. kernel_size=1, stride=1, pad_mode='same', padding=0),
  102. FakeQuantWithMinMax(
  103. ema=True, ema_decay=_ema_decay, symmetric=False)
  104. ]) if _fake else Conv2dBatchNormQuant(channel, out_channel, fake=_fake,
  105. per_channel=_per_channel,
  106. symmetric=_symmetric,
  107. kernel_size=1, stride=1,
  108. pad_mode='same', padding=0)
  109. self.down_sample = False
  110. if stride != 1 or in_channel != out_channel:
  111. self.down_sample = True
  112. self.down_sample_layer = None
  113. if self.down_sample:
  114. self.down_sample_layer = nn.SequentialCell([Conv2dBatchNormQuant(in_channel, out_channel,
  115. per_channel=_per_channel,
  116. symmetric=_symmetric,
  117. kernel_size=1, stride=stride,
  118. pad_mode='same', padding=0),
  119. FakeQuantWithMinMax(ema=True, ema_decay=_ema_decay,
  120. symmetric=False)
  121. ]) if _fake else Conv2dBatchNormQuant(in_channel, out_channel,
  122. fake=_fake,
  123. per_channel=_per_channel,
  124. symmetric=_symmetric,
  125. kernel_size=1,
  126. stride=stride,
  127. pad_mode='same',
  128. padding=0)
  129. self.add = nn.TensorAddQuant()
  130. self.relu = P.ReLU()
  131. def construct(self, x):
  132. identity = x
  133. out = self.conv1(x)
  134. out = self.conv2(out)
  135. out = self.conv3(out)
  136. if self.down_sample:
  137. identity = self.down_sample_layer(identity)
  138. out = self.add(out, identity)
  139. out = self.relu(out)
  140. return out
  141. class ResNet(nn.Cell):
  142. """
  143. ResNet architecture.
  144. Args:
  145. block (Cell): Block for network.
  146. layer_nums (list): Numbers of block in different layers.
  147. in_channels (list): Input channel in each layer.
  148. out_channels (list): Output channel in each layer.
  149. strides (list): Stride size in each layer.
  150. num_classes (int): The number of classes that the training images are belonging to.
  151. Returns:
  152. Tensor, output tensor.
  153. Examples:
  154. >>> ResNet(ResidualBlock,
  155. >>> [3, 4, 6, 3],
  156. >>> [64, 256, 512, 1024],
  157. >>> [256, 512, 1024, 2048],
  158. >>> [1, 2, 2, 2],
  159. >>> 10)
  160. """
  161. def __init__(self,
  162. block,
  163. layer_nums,
  164. in_channels,
  165. out_channels,
  166. strides,
  167. num_classes):
  168. super(ResNet, self).__init__()
  169. if not len(layer_nums) == len(in_channels) == len(out_channels) == 4:
  170. raise ValueError(
  171. "the length of layer_num, in_channels, out_channels list must be 4!")
  172. self.conv1 = ConvBNReLU(3, 64, kernel_size=7, stride=2)
  173. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, pad_mode="same")
  174. self.layer1 = self._make_layer(block,
  175. layer_nums[0],
  176. in_channel=in_channels[0],
  177. out_channel=out_channels[0],
  178. stride=strides[0])
  179. self.layer2 = self._make_layer(block,
  180. layer_nums[1],
  181. in_channel=in_channels[1],
  182. out_channel=out_channels[1],
  183. stride=strides[1])
  184. self.layer3 = self._make_layer(block,
  185. layer_nums[2],
  186. in_channel=in_channels[2],
  187. out_channel=out_channels[2],
  188. stride=strides[2])
  189. self.layer4 = self._make_layer(block,
  190. layer_nums[3],
  191. in_channel=in_channels[3],
  192. out_channel=out_channels[3],
  193. stride=strides[3])
  194. self.mean = P.ReduceMean(keep_dims=True)
  195. self.flatten = nn.Flatten()
  196. self.end_point = nn.DenseQuant(out_channels[3], num_classes, has_bias=True, per_channel=_per_channel,
  197. symmetric=_symmetric)
  198. self.output_fake = nn.FakeQuantWithMinMax(
  199. ema=True, ema_decay=_ema_decay)
  200. # init weights
  201. self._initialize_weights()
  202. def _make_layer(self, block, layer_num, in_channel, out_channel, stride):
  203. """
  204. Make stage network of ResNet.
  205. Args:
  206. block (Cell): Resnet block.
  207. layer_num (int): Layer number.
  208. in_channel (int): Input channel.
  209. out_channel (int): Output channel.
  210. stride (int): Stride size for the first convolutional layer.
  211. Returns:
  212. SequentialCell, the output layer.
  213. Examples:
  214. >>> _make_layer(ResidualBlock, 3, 128, 256, 2)
  215. """
  216. layers = []
  217. resnet_block = block(in_channel, out_channel, stride=stride)
  218. layers.append(resnet_block)
  219. for _ in range(1, layer_num):
  220. resnet_block = block(out_channel, out_channel, stride=1)
  221. layers.append(resnet_block)
  222. return nn.SequentialCell(layers)
  223. def construct(self, x):
  224. x = self.conv1(x)
  225. c1 = self.maxpool(x)
  226. c2 = self.layer1(c1)
  227. c3 = self.layer2(c2)
  228. c4 = self.layer3(c3)
  229. c5 = self.layer4(c4)
  230. out = self.mean(c5, (2, 3))
  231. out = self.flatten(out)
  232. out = self.end_point(out)
  233. out = self.output_fake(out)
  234. return out
  235. def _initialize_weights(self):
  236. self.init_parameters_data()
  237. for _, m in self.cells_and_names():
  238. np.random.seed(1)
  239. if isinstance(m, nn.Conv2dBnFoldQuant):
  240. m.weight.set_data(weight_init.initializer(weight_init.Normal(),
  241. m.weight.shape,
  242. m.weight.dtype))
  243. elif isinstance(m, nn.DenseQuant):
  244. m.weight.set_data(weight_init.initializer(weight_init.Normal(),
  245. m.weight.shape,
  246. m.weight.dtype))
  247. elif isinstance(m, nn.Conv2dBnWithoutFoldQuant):
  248. m.weight.set_data(weight_init.initializer(weight_init.Normal(),
  249. m.weight.shape,
  250. m.weight.dtype))
  251. def resnet50_quant(class_num=10):
  252. """
  253. Get ResNet50 neural network.
  254. Args:
  255. class_num (int): Class number.
  256. Returns:
  257. Cell, cell instance of ResNet50 neural network.
  258. Examples:
  259. >>> net = resnet50_quant(10)
  260. """
  261. return ResNet(ResidualBlock,
  262. [3, 4, 6, 3],
  263. [64, 256, 512, 1024],
  264. [256, 512, 1024, 2048],
  265. [1, 2, 2, 2],
  266. class_num)
  267. def resnet101_quant(class_num=1001):
  268. """
  269. Get ResNet101 neural network.
  270. Args:
  271. class_num (int): Class number.
  272. Returns:
  273. Cell, cell instance of ResNet101 neural network.
  274. Examples:
  275. >>> net = resnet101(1001)
  276. """
  277. return ResNet(ResidualBlock,
  278. [3, 4, 23, 3],
  279. [64, 256, 512, 1024],
  280. [256, 512, 1024, 2048],
  281. [1, 2, 2, 2],
  282. class_num)