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.

lenet_broadcast_auto_parallel.py 2.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. # ============================================================================
  15. import os
  16. import numpy as np
  17. import mindspore.communication.management as distributedTool
  18. import mindspore.nn as nn
  19. from mindspore import context
  20. from mindspore.nn.metrics import Accuracy
  21. from mindspore.train import Model
  22. from mindspore.train.callback import LossMonitor, TimeMonitor
  23. from model_zoo.official.cv.lenet.src.dataset import create_dataset
  24. from model_zoo.official.cv.lenet.src.lenet import LeNet5
  25. np.set_printoptions(threshold=np.inf)
  26. device_num = 2
  27. device_id = int(os.getenv('DEVICE_ID'))
  28. rank_id = 0
  29. def setup_module():
  30. global device_num
  31. global rank_id
  32. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  33. context.set_context(device_id=device_id)
  34. distributedTool.init()
  35. rank_id = distributedTool.get_rank()
  36. device_num = distributedTool.get_group_size()
  37. context.set_auto_parallel_context(device_num=device_num, global_rank=device_id, parameter_broadcast=True)
  38. def teardown_module():
  39. distributedTool.release()
  40. def test_all_trains():
  41. ds_train = create_dataset(os.path.join('/home/workspace/mindspore_dataset/mnist', "train"), 32, 1)
  42. network = LeNet5(10)
  43. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  44. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  45. time_cb = TimeMonitor(data_size=ds_train.get_dataset_size())
  46. model = Model(network, net_loss, net_opt, metrics={"Accuracy": Accuracy()})
  47. print("============== Starting Training ==============")
  48. model.train(1, ds_train, callbacks=[time_cb, LossMonitor()])