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_bias_add.py 3.0 kB

5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # Copyright 2019 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 numpy as np
  15. import mindspore.nn as nn
  16. from mindspore import Tensor
  17. from mindspore import context
  18. from mindspore.ops import operations as P
  19. from mindspore.train.model import Model
  20. class CrossEntropyLoss(nn.Cell):
  21. def __init__(self, reduction='mean'):
  22. super(CrossEntropyLoss, self).__init__()
  23. self.reduce_mean = P.ReduceMean()
  24. self.cross_entropy = nn.SoftmaxCrossEntropyWithLogits()
  25. self.reduction = reduction
  26. def construct(self, logits, label):
  27. loss = self.cross_entropy(logits, label)
  28. if self.reduction == 'mean':
  29. loss = self.reduce_mean(loss, (-1,))
  30. return loss
  31. class DatasetLenet():
  32. def __init__(self, predict, label, length=3):
  33. self.predict = predict
  34. self.label = label
  35. self.index = 0
  36. self.length = length
  37. def __iter__(self):
  38. return self
  39. def __next__(self):
  40. if self.index >= self.length:
  41. raise StopIteration
  42. self.index += 1
  43. return self.predict, self.label
  44. def reset(self):
  45. self.index = 0
  46. def get_dataset_size(self):
  47. return 32
  48. def get_repeat_count(self):
  49. return 1
  50. def create_tuple_iterator(self, num_epochs=-1, do_copy=True):
  51. return self
  52. class Net(nn.Cell):
  53. def __init__(self):
  54. super().__init__()
  55. self.conv = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=1, stride=1, pad_mode='valid',
  56. has_bias=True, weight_init='ones', bias_init='ones')
  57. self.conv.conv2d.shard(((8, 1, 1, 1), (1, 1, 1, 1)))
  58. self.reduce_mean = P.ReduceMean(keep_dims=False).shard(((1, 1, 1, 8),))
  59. self.flat = nn.Flatten()
  60. def construct(self, inputs):
  61. x = self.conv(inputs)
  62. x = self.reduce_mean(x, -1)
  63. x = self.flat(x)
  64. return x
  65. def test_bias_add():
  66. context.set_context(mode=context.GRAPH_MODE)
  67. context.set_auto_parallel_context(parallel_mode="auto_parallel", device_num=8)
  68. input_np = np.ones([16, 3, 32, 32]).astype(np.float32)
  69. label_np = np.zeros([16, 2048]).astype(np.float32)
  70. dataset = DatasetLenet(Tensor(input_np), Tensor(label_np), 1)
  71. net = Net()
  72. loss = CrossEntropyLoss()
  73. opt = nn.Momentum(learning_rate=0.01, momentum=0.9, params=net.get_parameters())
  74. model = Model(network=net, loss_fn=loss, optimizer=opt)
  75. model.train(epoch=1, train_dataset=dataset, dataset_sink_mode=False)