program.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. dist_strategy.qat = args.qat
  160. optimizer = fleet.distributed_optimizer(optimizer, strategy=dist_strategy)
  161. return optimizer
  162. def build(args, main_prog, startup_prog, step_each_epoch, is_train=True):
  163. """
  164. Build a executable paddle.static.Program via following four steps:
  165. 1. Create feeds.
  166. 2. Create a model.
  167. 3. Create fetchs.
  168. 4. Create an optimizer if is_train==True.
  169. Args:
  170. args(Namespace): Arguments obtained from ArgumentParser.
  171. main_prog(paddle.static.Program):The main program.
  172. startup_prog(paddle.static.Program):The startup program.
  173. step_each_epoch(int): The number of steps in each epoch.
  174. is_train(bool, optional): Whether the main programe created is for training. Default: True.
  175. Returns:
  176. fetchs(dict): A dict of outputs from Program execution (included loss and measures).
  177. lr_scheduler(paddle.optimizer.lr.LRScheduler): A learning rate scheduler.
  178. feeds(dict): A dict to map variables'name to their values.
  179. optimizer(Optimizer): An optimizer with distributed/AMP/ASP strategy.
  180. """
  181. with paddle.static.program_guard(main_prog, startup_prog):
  182. with paddle.utils.unique_name.guard():
  183. mode = Mode.TRAIN if is_train else Mode.EVAL
  184. feeds = create_feeds(args.image_shape)
  185. model_name = args.model_arch_name
  186. class_num = args.num_of_class
  187. input_image_channel = args.image_channel
  188. data_format = args.data_layout
  189. use_pure_fp16 = args.use_pure_fp16
  190. bn_weight_decay = args.bn_weight_decay
  191. model = models.__dict__[model_name](
  192. class_num=class_num,
  193. input_image_channel=input_image_channel,
  194. data_format=data_format,
  195. use_pure_fp16=use_pure_fp16,
  196. bn_weight_decay=bn_weight_decay,
  197. )
  198. out = model(feeds["data"])
  199. fetchs = create_fetchs(
  200. out, feeds, class_num, args.label_smoothing, mode=mode
  201. )
  202. if args.asp:
  203. sparsity.set_excluded_layers(main_program=main_prog, param_names=[model.fc.weight.name])
  204. lr_scheduler = None
  205. optimizer = None
  206. if is_train:
  207. lr_scheduler = build_lr_scheduler(args, step_each_epoch)
  208. optimizer = build_optimizer(args, lr_scheduler)
  209. optimizer = dist_optimizer(args, optimizer)
  210. optimizer.minimize(fetchs['loss'][0], startup_prog)
  211. # This is a workaround to "Communicator of ring id 0 has not been initialized.".
  212. # Since Paddle's design, the initialization would be done inside train program,
  213. # eval_only need to manually call initialization.
  214. if (
  215. args.run_scope == RunScope.EVAL_ONLY
  216. and paddle.distributed.get_world_size() > 1
  217. ):
  218. collective_helper = CollectiveHelper(
  219. role_maker=fleet.PaddleCloudRoleMaker(is_collective=True)
  220. )
  221. collective_helper.update_startup_program(startup_prog)
  222. return fetchs, lr_scheduler, feeds, optimizer
  223. def compile_prog(args, program, loss_name=None, is_train=True):
  224. """
  225. Compile the given program, which would fuse computing ops or optimize memory footprint
  226. based building strategy in config.
  227. Args:
  228. args(Namespace): Arguments obtained from ArgumentParser.
  229. program(paddle.static.Program): The main program to be compiled.
  230. loss_name(str, optional): The name of loss variable. Default: None.
  231. is_train(bool, optional): Indicate the prupose of strategy is for
  232. training of not. Default is True.
  233. Returns:
  234. compiled_program(paddle.static.CompiledProgram): A compiled program.
  235. """
  236. build_strategy, exec_strategy = create_strategy(args, is_train)
  237. compiled_program = paddle.static.CompiledProgram(
  238. program, build_strategy=build_strategy
  239. )
  240. return compiled_program
  241. def run(
  242. args,
  243. dataloader,
  244. exe,
  245. program,
  246. fetchs,
  247. epoch,
  248. mode=Mode.TRAIN,
  249. lr_scheduler=None,
  250. ):
  251. """
  252. Execute program.
  253. Args:
  254. args(Namespace): Arguments obtained from ArgumentParser.
  255. dataloader(nvidia.dali.plugin.paddle.DALIGenericIterator):
  256. Iteratable output of NVIDIA DALI pipeline,
  257. please refer to dali_dataloader in dali.py for details.
  258. exe(paddle.static.Executor): A executor to run program.
  259. program(paddle.static.Program): The program to be executed.
  260. fetchs(dict): A dict of outputs from Program execution (included loss and measures).
  261. epoch(int): Current epoch id to run.
  262. mode(utils.Mode, optional): Train or eval mode. Default: Mode.TRAIN.
  263. lr_scheduler(paddle.optimizer.lr.LRScheduler, optional): A learning rate scheduler.
  264. Default: None.
  265. Returns:
  266. metrics (dict): A dictionary to collect values of metrics.
  267. """
  268. num_trainers = get_num_trainers()
  269. fetch_list = [f[0] for f in fetchs.values()]
  270. metric_dict = {"lr": AverageMeter('lr', 'f', postfix=",", need_avg=False)}
  271. for k in fetchs:
  272. if fetchs[k][1] is not None:
  273. metric_dict[k] = fetchs[k][1]
  274. metric_dict["batch_time"] = AverageMeter('batch_time', '.5f', postfix=" s,")
  275. metric_dict["data_time"] = AverageMeter('data_time', '.5f', postfix=" s,")
  276. metric_dict["compute_time"] = AverageMeter(
  277. 'compute_time', '.5f', postfix=" s,"
  278. )
  279. for m in metric_dict.values():
  280. m.reset()
  281. profiler = Profiler()
  282. tic = time.perf_counter()
  283. idx = 0
  284. batch_size = None
  285. latency = []
  286. total_benchmark_steps = args.benchmark_steps + args.benchmark_warmup_steps
  287. dataloader.reset()
  288. while True:
  289. # profiler.profile_setup return True only when
  290. # profile is enable and idx == stop steps
  291. if profiler.profile_setup(idx):
  292. break
  293. idx += 1
  294. try:
  295. batch = next(dataloader)
  296. except StopIteration:
  297. # Reset dataloader when run benchmark to fill required steps.
  298. if args.benchmark and (idx < total_benchmark_steps):
  299. dataloader.reset()
  300. # Reset tic timestamp to ignore exception handling time.
  301. tic = time.perf_counter()
  302. continue
  303. break
  304. except RuntimeError:
  305. logging.warning(
  306. "Except RuntimeError when reading data from dataloader, try to read once again..."
  307. )
  308. continue
  309. reader_toc = time.perf_counter()
  310. metric_dict['data_time'].update(reader_toc - tic)
  311. batch_size = batch[0]["data"].shape()[0]
  312. feed_dict = batch[0]
  313. with profiler.profile_tag(
  314. idx, "Training" if mode == Mode.TRAIN else "Evaluation"
  315. ):
  316. results = exe.run(
  317. program=program, feed=feed_dict, fetch_list=fetch_list
  318. )
  319. for name, m in zip(fetchs.keys(), results):
  320. if name in metric_dict:
  321. metric_dict[name].update(np.mean(m), batch_size)
  322. metric_dict["compute_time"].update(time.perf_counter() - reader_toc)
  323. metric_dict["batch_time"].update(time.perf_counter() - tic)
  324. if mode == Mode.TRAIN:
  325. metric_dict['lr'].update(lr_scheduler.get_lr())
  326. if lr_scheduler is not None:
  327. with profiler.profile_tag(idx, "LR Step"):
  328. lr_scheduler.step()
  329. tic = time.perf_counter()
  330. if idx % args.print_interval == 0:
  331. log_msg = {}
  332. log_msg['loss'] = metric_dict['loss'].val.item()
  333. log_msg['top1'] = metric_dict['top1'].val.item()
  334. log_msg['top5'] = metric_dict['top5'].val.item()
  335. log_msg['data_time'] = metric_dict['data_time'].val
  336. log_msg['compute_time'] = metric_dict['compute_time'].val
  337. log_msg['batch_time'] = metric_dict['batch_time'].val
  338. log_msg['ips'] = (
  339. batch_size * num_trainers / metric_dict['batch_time'].val
  340. )
  341. if mode == Mode.TRAIN:
  342. log_msg['lr'] = metric_dict['lr'].val
  343. log_info((epoch, idx), log_msg, mode)
  344. if args.benchmark:
  345. latency.append(metric_dict['batch_time'].val)
  346. # Ignore the warmup iters
  347. if idx == args.benchmark_warmup_steps:
  348. metric_dict["compute_time"].reset()
  349. metric_dict["data_time"].reset()
  350. metric_dict["batch_time"].reset()
  351. latency.clear()
  352. logging.info("Begin benchmark at step %d", idx + 1)
  353. if idx == total_benchmark_steps:
  354. benchmark_data = {}
  355. benchmark_data['ips'] = (
  356. batch_size * num_trainers / metric_dict['batch_time'].avg
  357. )
  358. if mode == mode.EVAL:
  359. latency = np.array(latency) * 1000
  360. quantile = np.quantile(latency, [0.9, 0.95, 0.99])
  361. benchmark_data['latency_avg'] = np.mean(latency)
  362. benchmark_data['latency_p90'] = quantile[0]
  363. benchmark_data['latency_p95'] = quantile[1]
  364. benchmark_data['latency_p99'] = quantile[2]
  365. logging.info("End benchmark at epoch step %d", idx)
  366. return benchmark_data
  367. epoch_data = {}
  368. epoch_data['loss'] = metric_dict['loss'].avg.item()
  369. epoch_data['epoch_time'] = metric_dict['batch_time'].total
  370. epoch_data['ips'] = (
  371. batch_size
  372. * num_trainers
  373. * metric_dict["batch_time"].count
  374. / metric_dict["batch_time"].sum
  375. )
  376. if mode == Mode.EVAL:
  377. epoch_data['top1'] = metric_dict['top1'].avg.item()
  378. epoch_data['top5'] = metric_dict['top5'].avg.item()
  379. log_info((epoch,), epoch_data, mode)
  380. return epoch_data
  381. def log_info(step, metrics, mode):
  382. """
  383. Log metrics with step and mode information.
  384. Args:
  385. step(tuple): Step, coulbe (epoch-id, iter-id). Use tuple() for summary.
  386. metrics(dict): A dictionary collected values of metrics.
  387. mode(utils.Mode): Train or eval mode.
  388. """
  389. prefix = 'train' if mode == Mode.TRAIN else 'val'
  390. dllogger_iter_data = {}
  391. for key in metrics:
  392. dllogger_iter_data[f"{prefix}.{key}"] = metrics[key]
  393. dllogger.log(step=step, data=dllogger_iter_data)