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_pynative_model.py 4.9 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. """ test_pynative_model """
  16. import numpy as np
  17. import mindspore.nn as nn
  18. from mindspore import Parameter, ParameterTuple, Tensor
  19. from mindspore import context
  20. from mindspore.nn.optim import Momentum
  21. from mindspore.ops import composite as C
  22. from mindspore.ops import operations as P
  23. from ..ut_filter import non_graph_engine
  24. grad_by_list = C.GradOperation(get_by_list=True)
  25. def setup_module(module):
  26. context.set_context(mode=context.PYNATIVE_MODE)
  27. class GradWrap(nn.Cell):
  28. """ GradWrap definition """
  29. def __init__(self, network):
  30. super(GradWrap, self).__init__()
  31. self.network = network
  32. self.weights = ParameterTuple(network.get_parameters())
  33. def construct(self, x, label):
  34. weights = self.weights
  35. return grad_by_list(self.network, weights)(x, label)
  36. @non_graph_engine
  37. def test_softmaxloss_grad():
  38. """ test_softmaxloss_grad """
  39. class NetWithLossClass(nn.Cell):
  40. """ NetWithLossClass definition """
  41. def __init__(self, network):
  42. super(NetWithLossClass, self).__init__()
  43. self.loss = nn.SoftmaxCrossEntropyWithLogits()
  44. self.network = network
  45. def construct(self, x, label):
  46. predict = self.network(x)
  47. return self.loss(predict, label)
  48. class Net(nn.Cell):
  49. """ Net definition """
  50. def __init__(self):
  51. super(Net, self).__init__()
  52. self.weight = Parameter(Tensor(np.ones([64, 10]).astype(np.float32)), name="weight")
  53. self.bias = Parameter(Tensor(np.ones([10]).astype(np.float32)), name="bias")
  54. self.fc = P.MatMul()
  55. self.biasAdd = P.BiasAdd()
  56. def construct(self, x):
  57. x = self.biasAdd(self.fc(x, self.weight), self.bias)
  58. return x
  59. net = GradWrap(NetWithLossClass(Net()))
  60. predict = Tensor(np.ones([1, 64]).astype(np.float32))
  61. label = Tensor(np.zeros([1, 10]).astype(np.float32))
  62. print("pynative run")
  63. out = net.construct(predict, label)
  64. print("out:", out)
  65. print(out[0], (out[0]).asnumpy(), ":result")
  66. @non_graph_engine
  67. def test_lenet_grad():
  68. """ test_lenet_grad """
  69. class NetWithLossClass(nn.Cell):
  70. """ NetWithLossClass definition """
  71. def __init__(self, network):
  72. super(NetWithLossClass, self).__init__()
  73. self.loss = nn.SoftmaxCrossEntropyWithLogits()
  74. self.network = network
  75. def construct(self, x, label):
  76. predict = self.network(x)
  77. return self.loss(predict, label)
  78. class LeNet5(nn.Cell):
  79. """ LeNet5 definition """
  80. def __init__(self):
  81. super(LeNet5, self).__init__()
  82. self.conv1 = nn.Conv2d(1, 6, 5, pad_mode='valid')
  83. self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid')
  84. self.fc1 = nn.Dense(16 * 5 * 5, 120)
  85. self.fc2 = nn.Dense(120, 84)
  86. self.fc3 = nn.Dense(84, 10)
  87. self.relu = nn.ReLU()
  88. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  89. self.flatten = P.Flatten()
  90. def construct(self, x):
  91. x = self.max_pool2d(self.relu(self.conv1(x)))
  92. x = self.max_pool2d(self.relu(self.conv2(x)))
  93. x = self.flatten(x)
  94. x = self.relu(self.fc1(x))
  95. x = self.relu(self.fc2(x))
  96. x = self.fc3(x)
  97. return x
  98. input_data = Tensor(np.ones([1, 1, 32, 32]).astype(np.float32) * 0.01)
  99. label = Tensor(np.ones([1, 10]).astype(np.float32))
  100. iteration_num = 1
  101. verification_step = 0
  102. net = LeNet5()
  103. loss = nn.SoftmaxCrossEntropyWithLogits()
  104. momen_opti = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  105. train_net = GradWrap(NetWithLossClass(net))
  106. train_net.set_train()
  107. for i in range(0, iteration_num):
  108. # get the gradients
  109. grads = train_net(input_data, label)
  110. # update parameters
  111. success = momen_opti(grads)
  112. if success is False:
  113. print("fail to run optimizer")
  114. # verification
  115. if i == verification_step:
  116. fw_output = net(input_data)
  117. loss_output = loss(fw_output, label)
  118. print("The loss of %s-th iteration is %s" % (i, loss_output.asnumpy()))