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_one_dev.py 4.5 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
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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 re
  15. import numpy as np
  16. import mindspore as ms
  17. import mindspore.nn as nn
  18. from mindspore import Tensor
  19. from mindspore import context
  20. import mindspore.common.dtype as mstype
  21. from mindspore.common.api import _executor
  22. from mindspore.common.parameter import Parameter
  23. from mindspore.nn.loss.loss import _Loss
  24. from mindspore.nn.optim.momentum import Momentum
  25. from mindspore.ops import operations as P
  26. from mindspore.ops import functional as F
  27. from mindspore.ops import _selected_ops
  28. from mindspore.parallel._utils import _reset_op_id
  29. from mindspore.train import Model
  30. from mindspore.context import ParallelMode
  31. from tests.dataset_mock import MindData
  32. context.set_context(mode=context.GRAPH_MODE)
  33. class Dataset(MindData):
  34. def __init__(self, predict, label, length=3):
  35. super(Dataset, self).__init__(size=length)
  36. self.predict = predict
  37. self.label = label
  38. self.index = 0
  39. self.length = length
  40. def __iter__(self):
  41. return self
  42. def __next__(self):
  43. if self.index >= self.length:
  44. raise StopIteration
  45. self.index += 1
  46. return self.predict, self.label
  47. def reset(self):
  48. self.index = 0
  49. class AllToAllNet(nn.Cell):
  50. def __init__(self):
  51. super(AllToAllNet, self).__init__()
  52. self.matmul = P.MatMul()
  53. self.matmul_weight = Parameter(Tensor(np.ones([128, 32]), dtype=ms.float32), name="weight")
  54. self.transpose1 = P.Transpose()
  55. def construct(self, x):
  56. x = self.matmul(x, self.matmul_weight)
  57. x = self.transpose1(x, (1, 0))
  58. return x
  59. class SoftmaxCrossEntropyWithLogits(_Loss):
  60. def __init__(self,
  61. sparse=False,
  62. reduction='none'):
  63. super(SoftmaxCrossEntropyWithLogits, self).__init__(reduction)
  64. self.sparse = sparse
  65. self.reduction = reduction
  66. self.softmax_cross_entropy = _selected_ops.SoftmaxCrossEntropyWithLogits()
  67. self.one_hot = P.OneHot()
  68. self.on_value = Tensor(1.0, mstype.float32)
  69. self.off_value = Tensor(0., mstype.float32)
  70. self.is_cpugpu = context.get_context('device_target') in ["CPU", "GPU"]
  71. if self.is_cpugpu:
  72. self.sparse_softmax_cross_entropy = P.SparseSoftmaxCrossEntropyWithLogits()
  73. def construct(self, logits, labels):
  74. if self.is_cpugpu and self.sparse and self.reduction == 'mean':
  75. x = self.sparse_softmax_cross_entropy(logits, labels)
  76. return x
  77. if self.sparse:
  78. labels = self.one_hot(labels, F.shape(logits)[-1], self.on_value, self.off_value)
  79. x = self.softmax_cross_entropy(logits, labels)[0]
  80. return self.get_loss(x)
  81. def all_to_all_net():
  82. return AllToAllNet()
  83. def all_to_all_common():
  84. learning_rate = 0.1
  85. momentum = 0.9
  86. epoch_size = 2
  87. context.reset_auto_parallel_context()
  88. context.set_auto_parallel_context(parallel_mode=ParallelMode.AUTO_PARALLEL, device_num=1, global_rank=0)
  89. predict = Tensor(np.ones([32, 128]), dtype=ms.float32)
  90. label = Tensor(np.ones([32]), dtype=ms.int32)
  91. dataset = Dataset(predict, label, 2)
  92. net = all_to_all_net()
  93. loss = SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  94. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  95. model = Model(net, loss, opt)
  96. model.train(epoch_size, dataset, dataset_sink_mode=False)
  97. strategys = _executor._get_shard_strategy(model._train_network)
  98. return strategys
  99. def test_one_dev():
  100. _reset_op_id()
  101. strategies = all_to_all_common()
  102. for (k, v) in strategies.items():
  103. if re.search('SoftmaxCrossEntropyWithLogits-op', k) is not None:
  104. assert v == [[1, 1], [1, 1]]
  105. elif re.search('Transpose-op', k) is not None:
  106. assert v == [[1, 1]]
  107. elif re.search('MatMul-op', k) is not None:
  108. assert v == [[1, 1], [1, 1]]