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.

test_data_parallel_resnet.py 9.5 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. resnet50 example
  16. """
  17. import numpy as np
  18. import mindspore.context as context
  19. import mindspore.nn as nn
  20. from mindspore import Tensor, Model
  21. from mindspore.context import ParallelMode
  22. from mindspore.nn.optim import Momentum
  23. from mindspore.ops.operations import Add
  24. from ....dataset_mock import MindData
  25. def conv3x3(in_channels, out_channels, stride=1, padding=1, pad_mode='pad'):
  26. """3x3 convolution """
  27. return nn.Conv2d(in_channels, out_channels,
  28. kernel_size=3, stride=stride, padding=padding, pad_mode=pad_mode)
  29. def conv1x1(in_channels, out_channels, stride=1, padding=0, pad_mode='pad'):
  30. """1x1 convolution"""
  31. return nn.Conv2d(in_channels, out_channels,
  32. kernel_size=1, stride=stride, padding=padding, pad_mode=pad_mode)
  33. class ResidualBlock(nn.Cell):
  34. """
  35. residual Block
  36. """
  37. expansion = 4
  38. def __init__(self,
  39. in_channels,
  40. out_channels,
  41. stride=1,
  42. down_sample=False):
  43. super(ResidualBlock, self).__init__()
  44. out_chls = out_channels // self.expansion
  45. self.conv1 = conv1x1(in_channels, out_chls, stride=1, padding=0)
  46. self.bn1 = nn.BatchNorm2d(out_chls)
  47. self.conv2 = conv3x3(out_chls, out_chls, stride=stride, padding=1)
  48. self.bn2 = nn.BatchNorm2d(out_chls)
  49. self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
  50. self.bn3 = nn.BatchNorm2d(out_channels)
  51. self.relu = nn.ReLU()
  52. self.downsample = down_sample
  53. self.conv_down_sample = conv1x1(in_channels, out_channels,
  54. stride=stride, padding=0)
  55. self.bn_down_sample = nn.BatchNorm2d(out_channels)
  56. self.add = Add()
  57. def construct(self, x):
  58. """
  59. :param x:
  60. :return:
  61. """
  62. identity = x
  63. out = self.conv1(x)
  64. out = self.bn1(out)
  65. out = self.relu(out)
  66. out = self.conv2(out)
  67. out = self.bn2(out)
  68. out = self.relu(out)
  69. out = self.conv3(out)
  70. out = self.bn3(out)
  71. if self.downsample:
  72. identity = self.conv_down_sample(identity)
  73. identity = self.bn_down_sample(identity)
  74. out = self.add(out, identity)
  75. out = self.relu(out)
  76. return out
  77. class ResNet18(nn.Cell):
  78. """
  79. resnet nn.Cell
  80. """
  81. def __init__(self, block, num_classes=100):
  82. super(ResNet18, self).__init__()
  83. self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, pad_mode='pad')
  84. self.bn1 = nn.BatchNorm2d(64)
  85. self.relu = nn.ReLU()
  86. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, pad_mode='same')
  87. self.layer1 = self.MakeLayer(
  88. block, 2, in_channels=64, out_channels=256, stride=1)
  89. self.layer2 = self.MakeLayer(
  90. block, 2, in_channels=256, out_channels=512, stride=2)
  91. self.layer3 = self.MakeLayer(
  92. block, 2, in_channels=512, out_channels=1024, stride=2)
  93. self.layer4 = self.MakeLayer(
  94. block, 2, in_channels=1024, out_channels=2048, stride=2)
  95. self.avgpool = nn.AvgPool2d(7, 1)
  96. self.flatten = nn.Flatten()
  97. self.fc = nn.Dense(512 * block.expansion, num_classes)
  98. def MakeLayer(self, block, layer_num, in_channels, out_channels, stride):
  99. """
  100. make block layer
  101. :param block:
  102. :param layer_num:
  103. :param in_channels:
  104. :param out_channels:
  105. :param stride:
  106. :return:
  107. """
  108. layers = []
  109. resblk = block(in_channels, out_channels,
  110. stride=stride, down_sample=True)
  111. layers.append(resblk)
  112. for _ in range(1, layer_num):
  113. resblk = block(out_channels, out_channels, stride=1)
  114. layers.append(resblk)
  115. return nn.SequentialCell(layers)
  116. def construct(self, x):
  117. """
  118. :param x:
  119. :return:
  120. """
  121. x = self.conv1(x)
  122. x = self.bn1(x)
  123. x = self.relu(x)
  124. x = self.maxpool(x)
  125. x = self.layer1(x)
  126. x = self.layer2(x)
  127. x = self.layer3(x)
  128. x = self.layer4(x)
  129. x = self.avgpool(x)
  130. x = self.flatten(x)
  131. x = self.fc(x)
  132. return x
  133. class ResNet9(nn.Cell):
  134. """
  135. resnet nn.Cell
  136. """
  137. def __init__(self, block, num_classes=100):
  138. super(ResNet9, self).__init__()
  139. self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, pad_mode='pad')
  140. self.bn1 = nn.BatchNorm2d(64)
  141. self.relu = nn.ReLU()
  142. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, pad_mode='same')
  143. self.layer1 = self.MakeLayer(
  144. block, 1, in_channels=64, out_channels=256, stride=1)
  145. self.layer2 = self.MakeLayer(
  146. block, 1, in_channels=256, out_channels=512, stride=2)
  147. self.layer3 = self.MakeLayer(
  148. block, 1, in_channels=512, out_channels=1024, stride=2)
  149. self.layer4 = self.MakeLayer(
  150. block, 1, in_channels=1024, out_channels=2048, stride=2)
  151. self.avgpool = nn.AvgPool2d(7, 1)
  152. self.flatten = nn.Flatten()
  153. self.fc = nn.Dense(512 * block.expansion, num_classes)
  154. def MakeLayer(self, block, layer_num, in_channels, out_channels, stride):
  155. """
  156. make block layer
  157. :param block:
  158. :param layer_num:
  159. :param in_channels:
  160. :param out_channels:
  161. :param stride:
  162. :return:
  163. """
  164. layers = []
  165. resblk = block(in_channels, out_channels,
  166. stride=stride, down_sample=True)
  167. layers.append(resblk)
  168. for _ in range(1, layer_num):
  169. resblk = block(out_channels, out_channels, stride=1)
  170. layers.append(resblk)
  171. return nn.SequentialCell(layers)
  172. def construct(self, x):
  173. """
  174. :param x:
  175. :return:
  176. """
  177. x = self.conv1(x)
  178. x = self.bn1(x)
  179. x = self.relu(x)
  180. x = self.maxpool(x)
  181. x = self.layer1(x)
  182. x = self.layer2(x)
  183. x = self.layer3(x)
  184. x = self.layer4(x)
  185. x = self.avgpool(x)
  186. x = self.flatten(x)
  187. x = self.fc(x)
  188. return x
  189. def resnet9(classnum):
  190. return ResNet9(ResidualBlock, classnum)
  191. class DatasetLenet(MindData):
  192. """DatasetLenet definition"""
  193. def __init__(self, predict, label, length=3, size=None, batch_size=None,
  194. np_types=None, output_shapes=None, input_indexs=()):
  195. super(DatasetLenet, self).__init__(size=size, batch_size=batch_size,
  196. np_types=np_types, output_shapes=output_shapes,
  197. input_indexs=input_indexs)
  198. self.predict = predict
  199. self.label = label
  200. self.index = 0
  201. self.length = length
  202. def __iter__(self):
  203. return self
  204. def __next__(self):
  205. if self.index >= self.length:
  206. raise StopIteration
  207. self.index += 1
  208. return self.predict, self.label
  209. def reset(self):
  210. self.index = 0
  211. def test_resnet_train_tensor():
  212. """test_resnet_train_tensor"""
  213. batch_size = 1
  214. size = 2
  215. context.set_context(mode=context.GRAPH_MODE)
  216. context.reset_auto_parallel_context()
  217. context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, device_num=size,
  218. parameter_broadcast=True)
  219. one_hot_len = 10
  220. dataset_types = (np.float32, np.float32)
  221. dataset_shapes = [[batch_size, 3, 224, 224], [batch_size, one_hot_len]]
  222. predict = Tensor(np.ones([batch_size, 3, 224, 224]).astype(np.float32) * 0.01)
  223. label = Tensor(np.zeros([batch_size, one_hot_len]).astype(np.float32))
  224. dataset = DatasetLenet(predict, label, 2,
  225. size=2, batch_size=2,
  226. np_types=dataset_types,
  227. output_shapes=dataset_shapes,
  228. input_indexs=(0, 1))
  229. dataset.reset()
  230. network = resnet9(one_hot_len)
  231. network.set_train()
  232. loss_fn = nn.SoftmaxCrossEntropyWithLogits()
  233. optimizer = Momentum(filter(lambda x: x.requires_grad, network.get_parameters()), learning_rate=0.1, momentum=0.9)
  234. model = Model(network=network, loss_fn=loss_fn, optimizer=optimizer)
  235. model.train(epoch=2, train_dataset=dataset, dataset_sink_mode=False)
  236. context.set_context(mode=context.GRAPH_MODE)
  237. context.reset_auto_parallel_context()
  238. class_num = 10
  239. def get_dataset():
  240. dataset_types = (np.float32, np.float32)
  241. dataset_shapes = ((32, 3, 224, 224), (32, class_num))
  242. dataset = MindData(size=2, batch_size=1,
  243. np_types=dataset_types,
  244. output_shapes=dataset_shapes,
  245. input_indexs=(0, 1))
  246. return dataset