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 13 kB

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