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_train_mindir.py 3.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. import os
  15. import numpy as np
  16. import pytest
  17. import mindspore.nn as nn
  18. from mindspore import context
  19. from mindspore.common.tensor import Tensor
  20. from mindspore.common.initializer import TruncatedNormal
  21. from mindspore.common.parameter import ParameterTuple
  22. from mindspore.ops import operations as P
  23. from mindspore.ops import composite as C
  24. from mindspore.train.serialization import export
  25. def weight_variable():
  26. return TruncatedNormal(0.02)
  27. def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
  28. weight = weight_variable()
  29. return nn.Conv2d(in_channels, out_channels,
  30. kernel_size=kernel_size, stride=stride, padding=padding,
  31. weight_init=weight, has_bias=False, pad_mode="valid")
  32. def fc_with_initialize(input_channels, out_channels):
  33. weight = weight_variable()
  34. bias = weight_variable()
  35. return nn.Dense(input_channels, out_channels, weight, bias)
  36. class LeNet5(nn.Cell):
  37. def __init__(self):
  38. super(LeNet5, self).__init__()
  39. self.batch_size = 32
  40. self.conv1 = conv(1, 6, 5)
  41. self.conv2 = conv(6, 16, 5)
  42. self.fc1 = fc_with_initialize(16 * 5 * 5, 120)
  43. self.fc2 = fc_with_initialize(120, 84)
  44. self.fc3 = fc_with_initialize(84, 10)
  45. self.relu = nn.ReLU()
  46. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  47. self.reshape = P.Reshape()
  48. def construct(self, x):
  49. x = self.conv1(x)
  50. x = self.relu(x)
  51. x = self.max_pool2d(x)
  52. x = self.conv2(x)
  53. x = self.relu(x)
  54. x = self.max_pool2d(x)
  55. x = self.reshape(x, (self.batch_size, -1))
  56. x = self.fc1(x)
  57. x = self.relu(x)
  58. x = self.fc2(x)
  59. x = self.relu(x)
  60. x = self.fc3(x)
  61. return x
  62. class WithLossCell(nn.Cell):
  63. def __init__(self, network):
  64. super(WithLossCell, self).__init__(auto_prefix=False)
  65. self.loss = nn.SoftmaxCrossEntropyWithLogits()
  66. self.network = network
  67. def construct(self, x, label):
  68. predict = self.network(x)
  69. return self.loss(predict, label)
  70. class TrainOneStepCell(nn.Cell):
  71. def __init__(self, network):
  72. super(TrainOneStepCell, self).__init__(auto_prefix=False)
  73. self.network = network
  74. self.network.set_train()
  75. self.weights = ParameterTuple(network.trainable_params())
  76. self.optimizer = nn.Momentum(self.weights, 0.1, 0.9)
  77. self.hyper_map = C.HyperMap()
  78. self.grad = C.GradOperation(get_by_list=True)
  79. def construct(self, x, label):
  80. weights = self.weights
  81. grads = self.grad(self.network, weights)(x, label)
  82. return self.optimizer(grads)
  83. @pytest.mark.level0
  84. @pytest.mark.platform_x86_ascend_training
  85. @pytest.mark.platform_arm_ascend_training
  86. @pytest.mark.env_onecard
  87. def test_export_lenet_grad_mindir():
  88. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  89. network = LeNet5()
  90. network.set_train()
  91. predict = Tensor(np.ones([32, 1, 32, 32]).astype(np.float32) * 0.01)
  92. label = Tensor(np.zeros([32, 10]).astype(np.float32))
  93. net = TrainOneStepCell(WithLossCell(network))
  94. export(net, predict, label, file_name="lenet_grad", file_format='MINDIR')
  95. verify_name = "lenet_grad.mindir"
  96. assert os.path.exists(verify_name)