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