program.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. # Copyright (c) 2022 NVIDIA Corporation. All rights reserved.
  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 logging
  15. import time
  16. from profile import Profiler
  17. import dllogger
  18. import models
  19. import numpy as np
  20. from lr_scheduler import build_lr_scheduler
  21. from optimizer import build_optimizer
  22. from utils.misc import AverageMeter
  23. from utils.mode import Mode, RunScope
  24. from utils.utility import get_num_trainers
  25. import paddle
  26. import paddle.nn.functional as F
  27. from paddle.distributed import fleet
  28. from paddle.distributed.fleet import DistributedStrategy
  29. from paddle.distributed.fleet.meta_optimizers.common import CollectiveHelper
  30. from paddle.incubate import asp as sparsity
  31. def create_feeds(image_shape):
  32. """
  33. Create feeds mapping for the inputs of Pragrm execution.
  34. Args:
  35. image_shape(list[int]): Model input shape, such as [4, 224, 224].
  36. Returns:
  37. feeds(dict): A dict to map variables'name to their values.
  38. key (string): Name of variable to feed.
  39. Value (tuple): paddle.static.data.
  40. """
  41. feeds = {}
  42. feeds['data'] = paddle.static.data(
  43. name="data", shape=[None] + image_shape, dtype="float32"
  44. )
  45. feeds['label'] = paddle.static.data(
  46. name="label", shape=[None, 1], dtype="int64"
  47. )
  48. return feeds
  49. def create_fetchs(out, feeds, class_num, label_smoothing=0, mode=Mode.TRAIN):
  50. """
  51. Create fetchs to obtain specific outputs from Pragrm execution (included loss and measures).
  52. Args:
  53. out(variable): The model output variable.
  54. feeds(dict): A dict of mapping variables'name to their values
  55. (The input of Program execution).
  56. class_num(int): The number of classes.
  57. label_smoothing(float, optional): Epsilon of label smoothing. Default: 0.
  58. mode(utils.Mode, optional): Train or eval mode. Default: Mode.TRAIN
  59. Returns:
  60. fetchs(dict): A dict of outputs from Program execution (included loss and measures).
  61. key (string): Name of variable to fetch.
  62. Value (tuple): (variable, AverageMeter).
  63. """
  64. fetchs = {}
  65. target = paddle.reshape(feeds['label'], [-1, 1])
  66. if mode == Mode.TRAIN:
  67. if label_smoothing == 0:
  68. loss = F.cross_entropy(out, target)
  69. else:
  70. label_one_hot = F.one_hot(target, class_num)
  71. soft_target = F.label_smooth(label_one_hot, epsilon=label_smoothing)
  72. soft_target = paddle.reshape(soft_target, shape=[-1, class_num])
  73. log_softmax = -F.log_softmax(out, axis=-1)
  74. loss = paddle.sum(log_softmax * soft_target, axis=-1)
  75. else:
  76. loss = F.cross_entropy(out, target)
  77. label = paddle.argmax(out, axis=-1, dtype='int32')
  78. fetchs['label'] = (label, None)
  79. loss = loss.mean()
  80. fetchs['loss'] = (loss, AverageMeter('loss', '7.4f', need_avg=True))
  81. acc_top1 = paddle.metric.accuracy(input=out, label=target, k=1)
  82. acc_top5 = paddle.metric.accuracy(input=out, label=target, k=5)
  83. metric_dict = {}
  84. metric_dict["top1"] = acc_top1
  85. metric_dict["top5"] = acc_top5
  86. for key in metric_dict:
  87. if mode != Mode.TRAIN and paddle.distributed.get_world_size() > 1:
  88. paddle.distributed.all_reduce(
  89. metric_dict[key], op=paddle.distributed.ReduceOp.SUM
  90. )
  91. metric_dict[key] = (
  92. metric_dict[key] / paddle.distributed.get_world_size()
  93. )
  94. fetchs[key] = (
  95. metric_dict[key],
  96. AverageMeter(key, '7.4f', need_avg=True),
  97. )
  98. return fetchs
  99. def create_strategy(args, is_train=True):
  100. """
  101. Create paddle.static.BuildStrategy and paddle.static.ExecutionStrategy with arguments.
  102. Args:
  103. args(Namespace): Arguments obtained from ArgumentParser.
  104. is_train(bool, optional): Indicate the prupose of strategy is for training
  105. of not. Default is True.
  106. Returns:
  107. build_strategy(paddle.static.BuildStrategy): A instance of BuildStrategy.
  108. exec_strategy(paddle.static.ExecutionStrategy): A instance of ExecutionStrategy.
  109. """
  110. build_strategy = paddle.static.BuildStrategy()
  111. exec_strategy = paddle.static.ExecutionStrategy()
  112. exec_strategy.num_threads = 1
  113. exec_strategy.num_iteration_per_drop_scope = (
  114. 10000 if args.amp and args.use_pure_fp16 else 10
  115. )
  116. paddle.set_flags(
  117. {
  118. 'FLAGS_cudnn_exhaustive_search': True,
  119. 'FLAGS_conv_workspace_size_limit': 4096,
  120. }
  121. )
  122. if not is_train:
  123. build_strategy.fix_op_run_order = True
  124. if args.amp:
  125. build_strategy.fuse_bn_act_ops = True
  126. build_strategy.fuse_elewise_add_act_ops = True
  127. build_strategy.fuse_bn_add_act_ops = True
  128. build_strategy.enable_addto = True
  129. if args.fuse_resunit and is_train:
  130. build_strategy.fuse_resunit = True
  131. return build_strategy, exec_strategy
  132. def dist_optimizer(args, optimizer):
  133. """
  134. Create a distributed optimizer based on a given optimizer.
  135. Args:
  136. args(Namespace): Arguments obtained from ArgumentParser.
  137. optimizer(paddle.optimizer): A normal optimizer.
  138. Returns:
  139. optimizer(fleet.distributed_optimizer): A distributed optimizer.
  140. """
  141. build_strategy, exec_strategy = create_strategy(args)
  142. dist_strategy = DistributedStrategy()
  143. dist_strategy.execution_strategy = exec_strategy
  144. dist_strategy.build_strategy = build_strategy
  145. dist_strategy.fuse_all_reduce_ops = True
  146. all_reduce_size = 16
  147. dist_strategy.fuse_grad_size_in_MB = all_reduce_size
  148. dist_strategy.nccl_comm_num = 1
  149. dist_strategy.sync_nccl_allreduce = True
  150. if args.amp:
  151. dist_strategy.cudnn_batchnorm_spatial_persistent = True
  152. dist_strategy.amp = True
  153. dist_strategy.amp_configs = {
  154. "init_loss_scaling": args.scale_loss,
  155. "use_dynamic_loss_scaling": args.use_dynamic_loss_scaling,
  156. "use_pure_fp16": args.use_pure_fp16,
  157. }
  158. dist_strategy.asp = args.asp
  159. optimizer = fleet.distributed_optimizer(optimizer, strategy=dist_strategy)
  160. return optimizer
  161. def build(args, main_prog, startup_prog, step_each_epoch, is_train=True):
  162. """
  163. Build a executable paddle.static.Program via following four steps:
  164. 1. Create feeds.
  165. 2. Create a model.
  166. 3. Create fetchs.
  167. 4. Create an optimizer if is_train==True.
  168. Args:
  169. args(Namespace): Arguments obtained from ArgumentParser.
  170. main_prog(paddle.static.Program):The main program.
  171. startup_prog(paddle.static.Program):The startup program.
  172. step_each_epoch(int): The number of steps in each epoch.
  173. is_train(bool, optional): Whether the main programe created is for training. Default: True.
  174. Returns:
  175. fetchs(dict): A dict of outputs from Program execution (included loss and measures).
  176. lr_scheduler(paddle.optimizer.lr.LRScheduler): A learning rate scheduler.
  177. feeds(dict): A dict to map variables'name to their values.
  178. optimizer(Optimizer): An optimizer with distributed/AMP/ASP strategy.
  179. """
  180. with paddle.static.program_guard(main_prog, startup_prog):
  181. with paddle.utils.unique_name.guard():
  182. mode = Mode.TRAIN if is_train else Mode.EVAL
  183. feeds = create_feeds(args.image_shape)
  184. model_name = args.model_arch_name
  185. class_num = args.num_of_class
  186. input_image_channel = args.image_channel
  187. data_format = args.data_layout
  188. use_pure_fp16 = args.use_pure_fp16
  189. bn_weight_decay = args.bn_weight_decay
  190. model = models.__dict__[model_name](
  191. class_num=class_num,
  192. input_image_channel=input_image_channel,
  193. data_format=data_format,
  194. use_pure_fp16=use_pure_fp16,
  195. bn_weight_decay=bn_weight_decay,
  196. )
  197. out = model(feeds["data"])
  198. fetchs = create_fetchs(
  199. out, feeds, class_num, args.label_smoothing, mode=mode
  200. )
  201. if args.asp:
  202. sparsity.set_excluded_layers(main_program=main_prog, param_names=[model.fc.weight.name])
  203. lr_scheduler = None
  204. optimizer = None
  205. if is_train:
  206. lr_scheduler = build_lr_scheduler(args, step_each_epoch)
  207. optimizer = build_optimizer(args, lr_scheduler)
  208. optimizer = dist_optimizer(args, optimizer)
  209. optimizer.minimize(fetchs['loss'][0], startup_prog)
  210. # This is a workaround to "Communicator of ring id 0 has not been initialized.".
  211. # Since Paddle's design, the initialization would be done inside train program,
  212. # eval_only need to manually call initialization.
  213. if (
  214. args.run_scope == RunScope.EVAL_ONLY
  215. and paddle.distributed.get_world_size() > 1
  216. ):
  217. collective_helper = CollectiveHelper(
  218. role_maker=fleet.PaddleCloudRoleMaker(is_collective=True)
  219. )
  220. collective_helper.update_startup_program(startup_prog)
  221. return fetchs, lr_scheduler, feeds, optimizer
  222. def compile_prog(args, program, loss_name=None, is_train=True):
  223. """
  224. Compile the given program, which would fuse computing ops or optimize memory footprint
  225. based building strategy in config.
  226. Args:
  227. args(Namespace): Arguments obtained from ArgumentParser.
  228. program(paddle.static.Program): The main program to be compiled.
  229. loss_name(str, optional): The name of loss variable. Default: None.
  230. is_train(bool, optional): Indicate the prupose of strategy is for
  231. training of not. Default is True.
  232. Returns:
  233. compiled_program(paddle.static.CompiledProgram): A compiled program.
  234. """
  235. build_strategy, exec_strategy = create_strategy(args, is_train)
  236. compiled_program = paddle.static.CompiledProgram(
  237. program, build_strategy=build_strategy
  238. )
  239. return compiled_program
  240. def run(
  241. args,
  242. dataloader,
  243. exe,
  244. program,
  245. fetchs,
  246. epoch,
  247. mode=Mode.TRAIN,
  248. lr_scheduler=None,
  249. ):
  250. """
  251. Execute program.
  252. Args:
  253. args(Namespace): Arguments obtained from ArgumentParser.
  254. dataloader(nvidia.dali.plugin.paddle.DALIGenericIterator):
  255. Iteratable output of NVIDIA DALI pipeline,
  256. please refer to dali_dataloader in dali.py for details.
  257. exe(paddle.static.Executor): A executor to run program.
  258. program(paddle.static.Program): The program to be executed.
  259. fetchs(dict): A dict of outputs from Program execution (included loss and measures).
  260. epoch(int): Current epoch id to run.
  261. mode(utils.Mode, optional): Train or eval mode. Default: Mode.TRAIN.
  262. lr_scheduler(paddle.optimizer.lr.LRScheduler, optional): A learning rate scheduler.
  263. Default: None.
  264. Returns:
  265. metrics (dict): A dictionary to collect values of metrics.
  266. """
  267. num_trainers = get_num_trainers()
  268. fetch_list = [f[0] for f in fetchs.values()]
  269. metric_dict = {"lr": AverageMeter('lr', 'f', postfix=",", need_avg=False)}
  270. for k in fetchs:
  271. if fetchs[k][1] is not None:
  272. metric_dict[k] = fetchs[k][1]
  273. metric_dict["batch_time"] = AverageMeter('batch_time', '.5f', postfix=" s,")
  274. metric_dict["data_time"] = AverageMeter('data_time', '.5f', postfix=" s,")
  275. metric_dict["compute_time"] = AverageMeter(
  276. 'compute_time', '.5f', postfix=" s,"
  277. )
  278. for m in metric_dict.values():
  279. m.reset()
  280. profiler = Profiler()
  281. tic = time.perf_counter()
  282. idx = 0
  283. batch_size = None
  284. latency = []
  285. total_benchmark_steps = args.benchmark_steps + args.benchmark_warmup_steps
  286. dataloader.reset()
  287. while True:
  288. # profiler.profile_setup return True only when
  289. # profile is enable and idx == stop steps
  290. if profiler.profile_setup(idx):
  291. break
  292. idx += 1
  293. try:
  294. batch = next(dataloader)
  295. except StopIteration:
  296. # Reset dataloader when run benchmark to fill required steps.
  297. if args.benchmark and (idx < total_benchmark_steps):
  298. dataloader.reset()
  299. # Reset tic timestamp to ignore exception handling time.
  300. tic = time.perf_counter()
  301. continue
  302. break
  303. except RuntimeError:
  304. logging.warning(
  305. "Except RuntimeError when reading data from dataloader, try to read once again..."
  306. )
  307. continue
  308. reader_toc = time.perf_counter()
  309. metric_dict['data_time'].update(reader_toc - tic)
  310. batch_size = batch[0]["data"].shape()[0]
  311. feed_dict = batch[0]
  312. with profiler.profile_tag(
  313. idx, "Training" if mode == Mode.TRAIN else "Evaluation"
  314. ):
  315. results = exe.run(
  316. program=program, feed=feed_dict, fetch_list=fetch_list
  317. )
  318. for name, m in zip(fetchs.keys(), results):
  319. if name in metric_dict:
  320. metric_dict[name].update(np.mean(m), batch_size)
  321. metric_dict["compute_time"].update(time.perf_counter() - reader_toc)
  322. metric_dict["batch_time"].update(time.perf_counter() - tic)
  323. if mode == Mode.TRAIN:
  324. metric_dict['lr'].update(lr_scheduler.get_lr())
  325. if lr_scheduler is not None:
  326. with profiler.profile_tag(idx, "LR Step"):
  327. lr_scheduler.step()
  328. tic = time.perf_counter()
  329. if idx % args.print_interval == 0:
  330. log_msg = {}
  331. log_msg['loss'] = metric_dict['loss'].val.item()
  332. log_msg['top1'] = metric_dict['top1'].val.item()
  333. log_msg['top5'] = metric_dict['top5'].val.item()
  334. log_msg['data_time'] = metric_dict['data_time'].val
  335. log_msg['compute_time'] = metric_dict['compute_time'].val
  336. log_msg['batch_time'] = metric_dict['batch_time'].val
  337. log_msg['ips'] = (
  338. batch_size * num_trainers / metric_dict['batch_time'].val
  339. )
  340. if mode == Mode.TRAIN:
  341. log_msg['lr'] = metric_dict['lr'].val
  342. log_info((epoch, idx), log_msg, mode)
  343. if args.benchmark:
  344. latency.append(metric_dict['batch_time'].val)
  345. # Ignore the warmup iters
  346. if idx == args.benchmark_warmup_steps:
  347. metric_dict["compute_time"].reset()
  348. metric_dict["data_time"].reset()
  349. metric_dict["batch_time"].reset()
  350. latency.clear()
  351. logging.info("Begin benchmark at step %d", idx + 1)
  352. if idx == total_benchmark_steps:
  353. benchmark_data = {}
  354. benchmark_data['ips'] = (
  355. batch_size * num_trainers / metric_dict['batch_time'].avg
  356. )
  357. if mode == mode.EVAL:
  358. latency = np.array(latency) * 1000
  359. quantile = np.quantile(latency, [0.9, 0.95, 0.99])
  360. benchmark_data['latency_avg'] = np.mean(latency)
  361. benchmark_data['latency_p90'] = quantile[0]
  362. benchmark_data['latency_p95'] = quantile[1]
  363. benchmark_data['latency_p99'] = quantile[2]
  364. logging.info("End benchmark at epoch step %d", idx)
  365. return benchmark_data
  366. epoch_data = {}
  367. epoch_data['loss'] = metric_dict['loss'].avg.item()
  368. epoch_data['epoch_time'] = metric_dict['batch_time'].total
  369. epoch_data['ips'] = (
  370. batch_size
  371. * num_trainers
  372. * metric_dict["batch_time"].count
  373. / metric_dict["batch_time"].sum
  374. )
  375. if mode == Mode.EVAL:
  376. epoch_data['top1'] = metric_dict['top1'].avg.item()
  377. epoch_data['top5'] = metric_dict['top5'].avg.item()
  378. log_info((epoch,), epoch_data, mode)
  379. return epoch_data
  380. def log_info(step, metrics, mode):
  381. """
  382. Log metrics with step and mode information.
  383. Args:
  384. step(tuple): Step, coulbe (epoch-id, iter-id). Use tuple() for summary.
  385. metrics(dict): A dictionary collected values of metrics.
  386. mode(utils.Mode): Train or eval mode.
  387. """
  388. prefix = 'train' if mode == Mode.TRAIN else 'val'
  389. dllogger_iter_data = {}
  390. for key in metrics:
  391. dllogger_iter_data[f"{prefix}.{key}"] = metrics[key]
  392. dllogger.log(step=step, data=dllogger_iter_data)