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.

train.py 9.1 kB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. """
  2. ######################## single-dataset train lenet example ########################
  3. This example is a single-dataset training tutorial. If it is a multi-dataset, please refer to the multi-dataset training
  4. tutorial train_for_multidataset.py. This example cannot be used for multi-datasets!
  5. ######################## Instructions for using the training environment ########################
  6. The image of the debugging environment and the image of the training environment are two different images,
  7. and the working local directories are different. In the training task, you need to pay attention to the following points.
  8. 1、(1)The structure of the dataset uploaded for single dataset training in this example
  9. MNISTData.zip
  10. ├── test
  11. └── train
  12. 2、Single dataset training requires predefined functions
  13. (1)Copy single dataset from obs to training image
  14. function ObsToEnv(obs_data_url, data_dir)
  15. (2)Copy the output to obs
  16. function EnvToObs(train_dir, obs_train_url)
  17. (3)Download the input from Qizhi And Init
  18. function DownloadFromQizhi(obs_data_url, data_dir)
  19. (4)Upload the output to Qizhi
  20. function UploadToQizhi(train_dir, obs_train_url)
  21. 3、3 parameters need to be defined
  22. --data_url is the dataset you selected on the Qizhi platform
  23. --data_url,--train_url,--device_target,These 3 parameters must be defined first in a single dataset task,
  24. otherwise an error will be reported.
  25. There is no need to add these parameters to the running parameters of the Qizhi platform,
  26. because they are predefined in the background, you only need to define them in your code.
  27. 4、How the dataset is used
  28. A single dataset uses data_url as the input, and data_dir (ie:'/cache/data') as the calling method
  29. of the dataset in the image.
  30. For details, please refer to the following sample code.
  31. """
  32. import os
  33. import argparse
  34. import moxing as mox
  35. from config import mnist_cfg as cfg
  36. from dataset import create_dataset
  37. from dataset_distributed import create_dataset_parallel
  38. from lenet import LeNet5
  39. import mindspore.nn as nn
  40. from mindspore import context
  41. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  42. from mindspore.train import Model
  43. from mindspore.nn.metrics import Accuracy
  44. from mindspore.context import ParallelMode
  45. from mindspore.communication.management import init, get_rank, get_group_size
  46. import mindspore.ops as ops
  47. import time
  48. ### Copy single dataset from obs to training image###
  49. def ObsToEnv(obs_data_url, data_dir):
  50. try:
  51. mox.file.copy_parallel(obs_data_url, data_dir)
  52. print("Successfully Download {} to {}".format(obs_data_url, data_dir))
  53. except Exception as e:
  54. print('moxing download {} to {} failed: '.format(obs_data_url, data_dir) + str(e))
  55. #Set a cache file to determine whether the data has been copied to obs.
  56. #If this file exists during multi-card training, there is no need to copy the dataset multiple times.
  57. f = open("/cache/download_input.txt", 'w')
  58. f.close()
  59. try:
  60. if os.path.exists("/cache/download_input.txt"):
  61. print("download_input succeed")
  62. except Exception as e:
  63. print("download_input failed")
  64. return
  65. ### Copy the output to obs###
  66. def EnvToObs(train_dir, obs_train_url):
  67. try:
  68. mox.file.copy_parallel(train_dir, obs_train_url)
  69. print("Successfully Upload {} to {}".format(train_dir,obs_train_url))
  70. except Exception as e:
  71. print('moxing upload {} to {} failed: '.format(train_dir,obs_train_url) + str(e))
  72. return
  73. def DownloadFromQizhi(obs_data_url, data_dir):
  74. device_num = int(os.getenv('RANK_SIZE'))
  75. node_num = get_group_size()
  76. if device_num == 1:
  77. ObsToEnv(obs_data_url,data_dir)
  78. context.set_context(mode=context.GRAPH_MODE,device_target=args.device_target)
  79. if device_num > 1 and node_num == 1:
  80. # set device_id and init for multi-card training
  81. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target, device_id=int(os.getenv('ASCEND_DEVICE_ID')))
  82. context.reset_auto_parallel_context()
  83. context.set_auto_parallel_context(device_num = device_num, parallel_mode=ParallelMode.DATA_PARALLEL, gradients_mean=True, parameter_broadcast=True)
  84. init()
  85. #Copying obs data does not need to be executed multiple times, just let the 0th card copy the data
  86. local_rank=int(os.getenv('RANK_ID'))
  87. if local_rank%8==0:
  88. ObsToEnv(obs_data_url,data_dir)
  89. #If the cache file does not exist, it means that the copy data has not been completed,
  90. #and Wait for 0th card to finish copying data
  91. while not os.path.exists("/cache/download_input.txt"):
  92. time.sleep(1)
  93. if node_num > 1:
  94. ObsToEnv(obs_data_url,data_dir)
  95. return
  96. def UploadToQizhi(train_dir, obs_train_url):
  97. device_num = int(os.getenv('RANK_SIZE'))
  98. local_rank=int(os.getenv('RANK_ID'))
  99. if device_num == 1:
  100. EnvToObs(train_dir, obs_train_url)
  101. if device_num > 1:
  102. if local_rank%8==0:
  103. EnvToObs(train_dir, obs_train_url)
  104. return
  105. ### --data_url,--train_url,--device_target,These 3 parameters must be defined first in a single dataset,
  106. ### otherwise an error will be reported.
  107. ###There is no need to add these parameters to the running parameters of the Qizhi platform,
  108. ###because they are predefined in the background, you only need to define them in your code.
  109. parser = argparse.ArgumentParser(description='MindSpore Lenet Example')
  110. parser.add_argument('--data_url',
  111. help='path to training/inference dataset folder',
  112. default= '/cache/data/')
  113. parser.add_argument('--train_url',
  114. help='output folder to save/load',
  115. default= '/cache/output/')
  116. parser.add_argument(
  117. '--device_target',
  118. type=str,
  119. default="Ascend",
  120. choices=['Ascend', 'CPU'],
  121. help='device where the code will be implemented (default: Ascend),if to use the CPU on the Qizhi platform:device_target=CPU')
  122. parser.add_argument('--epoch_size',
  123. type=int,
  124. default=5,
  125. help='Training epochs.')
  126. parser.add_argument('--distributed',
  127. type=bool,
  128. default=True,
  129. help='Whether to perform distributed training.')
  130. if __name__ == "__main__":
  131. args = parser.parse_args()
  132. data_dir = '/cache/data'
  133. train_dir = '/cache/output'
  134. if not os.path.exists(data_dir):
  135. os.makedirs(data_dir)
  136. if not os.path.exists(train_dir):
  137. os.makedirs(train_dir)
  138. ###Initialize and copy data to training image
  139. if args.distributed:
  140. init()
  141. DownloadFromQizhi(args.data_url, data_dir)
  142. ###The dataset path is used here:data_dir +"/train"
  143. device_num = int(os.getenv('RANK_SIZE'))
  144. if device_num == 1:
  145. ds_train = create_dataset(os.path.join(data_dir, "train"), cfg.batch_size)
  146. if device_num > 1:
  147. ds_train = create_dataset_parallel(os.path.join(data_dir, "train"), cfg.batch_size)
  148. if ds_train.get_dataset_size() == 0:
  149. raise ValueError("Please check dataset size > 0 and batch_size <= dataset size")
  150. network = LeNet5(cfg.num_classes)
  151. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  152. net_opt = nn.Momentum(network.trainable_params(), cfg.lr, cfg.momentum)
  153. time_cb = TimeMonitor(data_size=ds_train.get_dataset_size())
  154. if args.device_target != "Ascend":
  155. model = Model(network,
  156. net_loss,
  157. net_opt,
  158. metrics={"accuracy": Accuracy()})
  159. else:
  160. model = Model(network,
  161. net_loss,
  162. net_opt,
  163. metrics={"accuracy": Accuracy()},
  164. amp_level="O2")
  165. config_ck = CheckpointConfig(
  166. save_checkpoint_steps=cfg.save_checkpoint_steps,
  167. keep_checkpoint_max=cfg.keep_checkpoint_max)
  168. #Note that this method saves the model file on each card. You need to specify the save path on each card.
  169. # In this example, get_rank() is added to distinguish different paths.
  170. if device_num == 1:
  171. outputDirectory = train_dir + "/"
  172. if device_num > 1:
  173. outputDirectory = train_dir + "/" + str(get_rank()) + "/"
  174. ckpoint_cb = ModelCheckpoint(prefix="checkpoint_lenet",
  175. directory=outputDirectory,
  176. config=config_ck)
  177. print("============== Starting Training ==============")
  178. epoch_size = cfg['epoch_size']
  179. if (args.epoch_size):
  180. epoch_size = args.epoch_size
  181. print('epoch_size is: ', epoch_size)
  182. model.train(epoch_size,
  183. ds_train,
  184. callbacks=[time_cb, ckpoint_cb,
  185. LossMonitor()])
  186. ###Copy the trained output data from the local running environment back to obs,
  187. ###and download it in the training task corresponding to the Qizhi platform
  188. UploadToQizhi(train_dir,args.train_url)