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_alltoall.py 4.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. from mindspore.train import Model, ParallelMode
  15. from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
  16. from mindspore.nn.optim.momentum import Momentum
  17. from mindspore import Tensor
  18. import mindspore as ms
  19. import numpy as np
  20. from mindspore.ops import operations as P
  21. import mindspore.nn as nn
  22. from mindspore.common.parameter import Parameter
  23. from tests.dataset_mock import MindData
  24. from mindspore import context
  25. from mindspore.parallel._utils import _reset_op_id
  26. from mindspore.common.api import _executor
  27. class Dataset(MindData):
  28. def __init__(self, predict, label, length=3):
  29. super(Dataset, self).__init__(size=length)
  30. self.predict = predict
  31. self.label = label
  32. self.index = 0
  33. self.length = length
  34. def __iter__(self):
  35. return self
  36. def __next__(self):
  37. if self.index >= self.length:
  38. raise StopIteration
  39. self.index += 1
  40. return self.predict, self.label
  41. def reset(self):
  42. self.index = 0
  43. class AllToAllNet(nn.Cell):
  44. def __init__(self, strategy1):
  45. super(AllToAllNet, self).__init__()
  46. self.matmul = P.MatMul().set_strategy(((1, 1), (1, 8)))
  47. self.matmul_weight = Parameter(Tensor(np.ones([128, 256]), dtype=ms.float32), name="weight")
  48. self.transpose1 = P.Transpose().set_strategy(strategy1)
  49. def construct(self, x):
  50. x = self.matmul(x, self.matmul_weight)
  51. x = self.transpose1(x, (1, 0))
  52. return x
  53. def all_to_all_net(strategy1):
  54. return AllToAllNet(strategy1=strategy1)
  55. def all_to_all_common(strategy1):
  56. batch_size = 32
  57. learning_rate = 0.1
  58. momentum = 0.9
  59. epoch_size = 2
  60. context.reset_auto_parallel_context()
  61. context.set_auto_parallel_context(parallel_mode=ParallelMode.SEMI_AUTO_PARALLEL, device_num=8)
  62. predict = Tensor(np.ones([32, 128]), dtype=ms.float32)
  63. label = Tensor(np.ones([32]), dtype=ms.int32)
  64. dataset = Dataset(predict, label, 2)
  65. net = all_to_all_net(strategy1)
  66. loss = SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  67. loss.softmax_cross_entropy.set_strategy(((8, 1), (8, 1)))
  68. loss.one_hot.set_strategy(((8,1), (), ()))
  69. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  70. model = Model(net, loss, opt)
  71. model.train(epoch_size, dataset, dataset_sink_mode=False)
  72. strategys = _executor._get_strategy(model._train_network)
  73. return strategys
  74. def test_all_to_all():
  75. strategy1 = ((8, 1), )
  76. context.set_context(mode=context.GRAPH_MODE, save_graphs=False)
  77. _reset_op_id()
  78. strategys = all_to_all_common(strategy1)
  79. print(strategys)
  80. expect_dict = {'Default/network-_VirtualDatasetCell/_backbone-WithLossCell/_loss_fn-SoftmaxCrossEntropyWithLogits'
  81. '/SoftmaxCrossEntropyWithLogits-op43': [[8, 1], [8, 1]],
  82. 'Default/network-_VirtualDatasetCell/_backbone-WithLossCell/_loss_fn-SoftmaxCrossEntropyWithLogits'
  83. '/OneHot-op44': [[8, 1], [], []],
  84. 'Default/network-_VirtualDatasetCell/_backbone-WithLossCell/_backbone-AllToAllNet/Transpose-op1':
  85. [[8, 1]],
  86. 'Default/network-_VirtualDatasetCell/_backbone-WithLossCell/_backbone-AllToAllNet/MatMul-op0':
  87. [[1, 1], [1, 8]]}
  88. assert (strategys == expect_dict)
  89. context.set_context(save_graphs=False)
  90. if __name__ == '__main__':
  91. test_all_to_all()