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_parameter_merge.py 3.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # Copyright 2021 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. import os
  16. import numpy as np
  17. import mindspore as ms
  18. from mindspore import context, Tensor, Parameter
  19. from mindspore.nn import Cell, Momentum
  20. from mindspore.ops import operations as P
  21. from mindspore.train import Model
  22. from mindspore.train.callback import CheckpointConfig, ModelCheckpoint
  23. from tests.dataset_mock import MindData
  24. class Dataset(MindData):
  25. def __init__(self, predict, label, length=3):
  26. super(Dataset, self).__init__(size=length)
  27. self.predict = predict
  28. self.label = label
  29. self.index = 0
  30. self.length = length
  31. def __iter__(self):
  32. return self
  33. def __next__(self):
  34. if self.index >= self.length:
  35. raise StopIteration
  36. self.index += 1
  37. return self.predict, self.label
  38. def reset(self):
  39. self.index = 0
  40. class Net(Cell):
  41. def __init__(self, weight, w2, begin, end, strides, strategy1=None, strategy2=None, mask=0):
  42. super().__init__()
  43. self.mul = P.Mul().shard(strategy1)
  44. self.strided_slice = P.StridedSlice(begin_mask=mask).shard(strategy2)
  45. self.weight = Parameter(weight, "w1")
  46. self.mul2 = P.Mul()
  47. self.weight2 = Parameter(w2, "w2")
  48. self.begin = begin
  49. self.end = end
  50. self.strides = strides
  51. def construct(self, x, b):
  52. out = self.strided_slice(
  53. self.weight, self.begin, self.end, self.strides)
  54. out = self.mul(x, out)
  55. out = self.mul2(out, self.weight2)
  56. return out
  57. _x = Tensor(np.ones([16, 64, 1]), dtype=ms.float32)
  58. _b = Tensor(np.ones([16, 64, 32]), dtype=ms.float32)
  59. _w1 = Tensor(np.ones([256, 64, 32]), dtype=ms.float32)
  60. _w2 = Tensor(np.ones([128, 64, 1]), dtype=ms.float32)
  61. def clean_all_ckpt_files(folder_path):
  62. if os.path.exists(folder_path):
  63. for file_name in os.listdir(folder_path):
  64. if file_name.endswith('.ckpt') or file_name.endswith('.meta'):
  65. os.remove(os.path.join(folder_path, file_name))
  66. def compile_net(net):
  67. context.set_context(save_graphs=True)
  68. learning_rate = 0.1
  69. momentum = 0.9
  70. epoch_size = 2
  71. dataset = Dataset(_x, _b)
  72. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  73. model = Model(net, optimizer=opt)
  74. ckpt_config = CheckpointConfig(keep_checkpoint_max=1)
  75. ckpt_path = "./parallel_ckpt"
  76. ckpt_cb = ModelCheckpoint(prefix="parallel", directory=ckpt_path, config=ckpt_config)
  77. model.train(epoch_size, dataset, dataset_sink_mode=False, callbacks=[ckpt_cb])
  78. assert len(model._train_network.parallel_parameter_merge_net_dict) == 4
  79. clean_all_ckpt_files(ckpt_path)
  80. context.reset_auto_parallel_context()
  81. def test_stridedslice_parameter():
  82. context.set_auto_parallel_context(
  83. parallel_mode="semi_auto_parallel", device_num=8, global_rank=0)
  84. strategy1 = ((1, 4, 1), (1, 4, 2))
  85. strategy2 = ((1, 4, 2),)
  86. net = Net(_w1, _w2, (0, 0, 0), (128, 64, 32), (1, 1, 1),
  87. strategy1, strategy2)
  88. compile_net(net)