program.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. # Copyright (c) 2021 PaddlePaddle Authors. 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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import os
  18. import sys
  19. import platform
  20. import yaml
  21. import time
  22. import datetime
  23. import paddle
  24. import paddle.distributed as dist
  25. from tqdm import tqdm
  26. import cv2
  27. import numpy as np
  28. from argparse import ArgumentParser, RawDescriptionHelpFormatter
  29. from ppocr.utils.stats import TrainingStats
  30. from ppocr.utils.save_load import save_model
  31. from ppocr.utils.utility import print_dict, AverageMeter
  32. from ppocr.utils.logging import get_logger
  33. from ppocr.utils.loggers import VDLLogger, WandbLogger, Loggers
  34. from ppocr.utils import profiler
  35. from ppocr.data import build_dataloader
  36. class ArgsParser(ArgumentParser):
  37. def __init__(self):
  38. super(ArgsParser, self).__init__(
  39. formatter_class=RawDescriptionHelpFormatter)
  40. self.add_argument("-c", "--config", help="configuration file to use")
  41. self.add_argument(
  42. "-o", "--opt", nargs='+', help="set configuration options")
  43. self.add_argument(
  44. '-p',
  45. '--profiler_options',
  46. type=str,
  47. default=None,
  48. help='The option of profiler, which should be in format ' \
  49. '\"key1=value1;key2=value2;key3=value3\".'
  50. )
  51. def parse_args(self, argv=None):
  52. args = super(ArgsParser, self).parse_args(argv)
  53. assert args.config is not None, \
  54. "Please specify --config=configure_file_path."
  55. args.opt = self._parse_opt(args.opt)
  56. return args
  57. def _parse_opt(self, opts):
  58. config = {}
  59. if not opts:
  60. return config
  61. for s in opts:
  62. s = s.strip()
  63. k, v = s.split('=')
  64. config[k] = yaml.load(v, Loader=yaml.Loader)
  65. return config
  66. def load_config(file_path):
  67. """
  68. Load config from yml/yaml file.
  69. Args:
  70. file_path (str): Path of the config file to be loaded.
  71. Returns: global config
  72. """
  73. _, ext = os.path.splitext(file_path)
  74. assert ext in ['.yml', '.yaml'], "only support yaml files for now"
  75. config = yaml.load(open(file_path, 'rb'), Loader=yaml.Loader)
  76. return config
  77. def merge_config(config, opts):
  78. """
  79. Merge config into global config.
  80. Args:
  81. config (dict): Config to be merged.
  82. Returns: global config
  83. """
  84. for key, value in opts.items():
  85. if "." not in key:
  86. if isinstance(value, dict) and key in config:
  87. config[key].update(value)
  88. else:
  89. config[key] = value
  90. else:
  91. sub_keys = key.split('.')
  92. assert (
  93. sub_keys[0] in config
  94. ), "the sub_keys can only be one of global_config: {}, but get: " \
  95. "{}, please check your running command".format(
  96. config.keys(), sub_keys[0])
  97. cur = config[sub_keys[0]]
  98. for idx, sub_key in enumerate(sub_keys[1:]):
  99. if idx == len(sub_keys) - 2:
  100. cur[sub_key] = value
  101. else:
  102. cur = cur[sub_key]
  103. return config
  104. def check_device(use_gpu, use_xpu=False, use_npu=False, use_mlu=False):
  105. """
  106. Log error and exit when set use_gpu=true in paddlepaddle
  107. cpu version.
  108. """
  109. err = "Config {} cannot be set as true while your paddle " \
  110. "is not compiled with {} ! \nPlease try: \n" \
  111. "\t1. Install paddlepaddle to run model on {} \n" \
  112. "\t2. Set {} as false in config file to run " \
  113. "model on CPU"
  114. try:
  115. if use_gpu and use_xpu:
  116. print("use_xpu and use_gpu can not both be ture.")
  117. if use_gpu and not paddle.is_compiled_with_cuda():
  118. print(err.format("use_gpu", "cuda", "gpu", "use_gpu"))
  119. sys.exit(1)
  120. if use_xpu and not paddle.device.is_compiled_with_xpu():
  121. print(err.format("use_xpu", "xpu", "xpu", "use_xpu"))
  122. sys.exit(1)
  123. if use_npu:
  124. if int(paddle.version.major) != 0 and int(
  125. paddle.version.major) <= 2 and int(
  126. paddle.version.minor) <= 4:
  127. if not paddle.device.is_compiled_with_npu():
  128. print(err.format("use_npu", "npu", "npu", "use_npu"))
  129. sys.exit(1)
  130. # is_compiled_with_npu() has been updated after paddle-2.4
  131. else:
  132. if not paddle.device.is_compiled_with_custom_device("npu"):
  133. print(err.format("use_npu", "npu", "npu", "use_npu"))
  134. sys.exit(1)
  135. if use_mlu and not paddle.device.is_compiled_with_mlu():
  136. print(err.format("use_mlu", "mlu", "mlu", "use_mlu"))
  137. sys.exit(1)
  138. except Exception as e:
  139. pass
  140. def to_float32(preds):
  141. if isinstance(preds, dict):
  142. for k in preds:
  143. if isinstance(preds[k], dict) or isinstance(preds[k], list):
  144. preds[k] = to_float32(preds[k])
  145. elif isinstance(preds[k], paddle.Tensor):
  146. preds[k] = preds[k].astype(paddle.float32)
  147. elif isinstance(preds, list):
  148. for k in range(len(preds)):
  149. if isinstance(preds[k], dict):
  150. preds[k] = to_float32(preds[k])
  151. elif isinstance(preds[k], list):
  152. preds[k] = to_float32(preds[k])
  153. elif isinstance(preds[k], paddle.Tensor):
  154. preds[k] = preds[k].astype(paddle.float32)
  155. elif isinstance(preds, paddle.Tensor):
  156. preds = preds.astype(paddle.float32)
  157. return preds
  158. def train(config,
  159. train_dataloader,
  160. valid_dataloader,
  161. device,
  162. model,
  163. loss_class,
  164. optimizer,
  165. lr_scheduler,
  166. post_process_class,
  167. eval_class,
  168. pre_best_model_dict,
  169. logger,
  170. log_writer=None,
  171. scaler=None,
  172. amp_level='O2',
  173. amp_custom_black_list=[]):
  174. cal_metric_during_train = config['Global'].get('cal_metric_during_train',
  175. False)
  176. calc_epoch_interval = config['Global'].get('calc_epoch_interval', 1)
  177. log_smooth_window = config['Global']['log_smooth_window']
  178. epoch_num = config['Global']['epoch_num']
  179. print_batch_step = config['Global']['print_batch_step']
  180. eval_batch_step = config['Global']['eval_batch_step']
  181. profiler_options = config['profiler_options']
  182. global_step = 0
  183. if 'global_step' in pre_best_model_dict:
  184. global_step = pre_best_model_dict['global_step']
  185. start_eval_step = 0
  186. if type(eval_batch_step) == list and len(eval_batch_step) >= 2:
  187. start_eval_step = eval_batch_step[0]
  188. eval_batch_step = eval_batch_step[1]
  189. if len(valid_dataloader) == 0:
  190. logger.info(
  191. 'No Images in eval dataset, evaluation during training ' \
  192. 'will be disabled'
  193. )
  194. start_eval_step = 1e111
  195. logger.info(
  196. "During the training process, after the {}th iteration, " \
  197. "an evaluation is run every {} iterations".
  198. format(start_eval_step, eval_batch_step))
  199. save_epoch_step = config['Global']['save_epoch_step']
  200. save_model_dir = config['Global']['save_model_dir']
  201. if not os.path.exists(save_model_dir):
  202. os.makedirs(save_model_dir)
  203. main_indicator = eval_class.main_indicator
  204. best_model_dict = {main_indicator: 0}
  205. best_model_dict.update(pre_best_model_dict)
  206. train_stats = TrainingStats(log_smooth_window, ['lr'])
  207. model_average = False
  208. model.train()
  209. use_srn = config['Architecture']['algorithm'] == "SRN"
  210. extra_input_models = [
  211. "SRN", "NRTR", "SAR", "SEED", "SVTR", "SPIN", "VisionLAN",
  212. "RobustScanner", "RFL", 'DRRG'
  213. ]
  214. extra_input = False
  215. if config['Architecture']['algorithm'] == 'Distillation':
  216. for key in config['Architecture']["Models"]:
  217. extra_input = extra_input or config['Architecture']['Models'][key][
  218. 'algorithm'] in extra_input_models
  219. else:
  220. extra_input = config['Architecture']['algorithm'] in extra_input_models
  221. try:
  222. model_type = config['Architecture']['model_type']
  223. except:
  224. model_type = None
  225. algorithm = config['Architecture']['algorithm']
  226. start_epoch = best_model_dict[
  227. 'start_epoch'] if 'start_epoch' in best_model_dict else 1
  228. total_samples = 0
  229. train_reader_cost = 0.0
  230. train_batch_cost = 0.0
  231. reader_start = time.time()
  232. eta_meter = AverageMeter()
  233. max_iter = len(train_dataloader) - 1 if platform.system(
  234. ) == "Windows" else len(train_dataloader)
  235. for epoch in range(start_epoch, epoch_num + 1):
  236. if train_dataloader.dataset.need_reset:
  237. train_dataloader = build_dataloader(
  238. config, 'Train', device, logger, seed=epoch)
  239. max_iter = len(train_dataloader) - 1 if platform.system(
  240. ) == "Windows" else len(train_dataloader)
  241. for idx, batch in enumerate(train_dataloader):
  242. profiler.add_profiler_step(profiler_options)
  243. train_reader_cost += time.time() - reader_start
  244. if idx >= max_iter:
  245. break
  246. lr = optimizer.get_lr()
  247. images = batch[0]
  248. if use_srn:
  249. model_average = True
  250. # use amp
  251. if scaler:
  252. with paddle.amp.auto_cast(
  253. level=amp_level,
  254. custom_black_list=amp_custom_black_list):
  255. if model_type == 'table' or extra_input:
  256. preds = model(images, data=batch[1:])
  257. elif model_type in ["kie"]:
  258. preds = model(batch)
  259. elif algorithm in ['CAN']:
  260. preds = model(batch[:3])
  261. else:
  262. preds = model(images)
  263. preds = to_float32(preds)
  264. loss = loss_class(preds, batch)
  265. avg_loss = loss['loss']
  266. scaled_avg_loss = scaler.scale(avg_loss)
  267. scaled_avg_loss.backward()
  268. scaler.minimize(optimizer, scaled_avg_loss)
  269. else:
  270. if model_type == 'table' or extra_input:
  271. preds = model(images, data=batch[1:])
  272. elif model_type in ["kie", 'sr']:
  273. preds = model(batch)
  274. elif algorithm in ['CAN']:
  275. preds = model(batch[:3])
  276. else:
  277. preds = model(images)
  278. loss = loss_class(preds, batch)
  279. avg_loss = loss['loss']
  280. avg_loss.backward()
  281. optimizer.step()
  282. optimizer.clear_grad()
  283. if cal_metric_during_train and epoch % calc_epoch_interval == 0: # only rec and cls need
  284. batch = [item.numpy() for item in batch]
  285. if model_type in ['kie', 'sr']:
  286. eval_class(preds, batch)
  287. elif model_type in ['table']:
  288. post_result = post_process_class(preds, batch)
  289. eval_class(post_result, batch)
  290. elif algorithm in ['CAN']:
  291. model_type = 'can'
  292. eval_class(preds[0], batch[2:], epoch_reset=(idx == 0))
  293. else:
  294. if config['Loss']['name'] in ['MultiLoss', 'MultiLoss_v2'
  295. ]: # for multi head loss
  296. post_result = post_process_class(
  297. preds['ctc'], batch[1]) # for CTC head out
  298. elif config['Loss']['name'] in ['VLLoss']:
  299. post_result = post_process_class(preds, batch[1],
  300. batch[-1])
  301. else:
  302. post_result = post_process_class(preds, batch[1])
  303. eval_class(post_result, batch)
  304. metric = eval_class.get_metric()
  305. train_stats.update(metric)
  306. train_batch_time = time.time() - reader_start
  307. train_batch_cost += train_batch_time
  308. eta_meter.update(train_batch_time)
  309. global_step += 1
  310. total_samples += len(images)
  311. if not isinstance(lr_scheduler, float):
  312. lr_scheduler.step()
  313. # logger and visualdl
  314. stats = {k: v.numpy().mean() for k, v in loss.items()}
  315. stats['lr'] = lr
  316. train_stats.update(stats)
  317. if log_writer is not None and dist.get_rank() == 0:
  318. log_writer.log_metrics(
  319. metrics=train_stats.get(), prefix="TRAIN", step=global_step)
  320. if dist.get_rank() == 0 and (
  321. (global_step > 0 and global_step % print_batch_step == 0) or
  322. (idx >= len(train_dataloader) - 1)):
  323. logs = train_stats.log()
  324. eta_sec = ((epoch_num + 1 - epoch) * \
  325. len(train_dataloader) - idx - 1) * eta_meter.avg
  326. eta_sec_format = str(datetime.timedelta(seconds=int(eta_sec)))
  327. strs = 'epoch: [{}/{}], global_step: {}, {}, avg_reader_cost: ' \
  328. '{:.5f} s, avg_batch_cost: {:.5f} s, avg_samples: {}, ' \
  329. 'ips: {:.5f} samples/s, eta: {}'.format(
  330. epoch, epoch_num, global_step, logs,
  331. train_reader_cost / print_batch_step,
  332. train_batch_cost / print_batch_step,
  333. total_samples / print_batch_step,
  334. total_samples / train_batch_cost, eta_sec_format)
  335. logger.info(strs)
  336. total_samples = 0
  337. train_reader_cost = 0.0
  338. train_batch_cost = 0.0
  339. # eval
  340. if global_step > start_eval_step and \
  341. (global_step - start_eval_step) % eval_batch_step == 0 \
  342. and dist.get_rank() == 0:
  343. if model_average:
  344. Model_Average = paddle.incubate.optimizer.ModelAverage(
  345. 0.15,
  346. parameters=model.parameters(),
  347. min_average_window=10000,
  348. max_average_window=15625)
  349. Model_Average.apply()
  350. cur_metric = eval(
  351. model,
  352. valid_dataloader,
  353. post_process_class,
  354. eval_class,
  355. model_type,
  356. extra_input=extra_input,
  357. scaler=scaler,
  358. amp_level=amp_level,
  359. amp_custom_black_list=amp_custom_black_list)
  360. cur_metric_str = 'cur metric, {}'.format(', '.join(
  361. ['{}: {}'.format(k, v) for k, v in cur_metric.items()]))
  362. logger.info(cur_metric_str)
  363. # logger metric
  364. if log_writer is not None:
  365. log_writer.log_metrics(
  366. metrics=cur_metric, prefix="EVAL", step=global_step)
  367. if cur_metric[main_indicator] >= best_model_dict[
  368. main_indicator]:
  369. best_model_dict.update(cur_metric)
  370. best_model_dict['best_epoch'] = epoch
  371. save_model(
  372. model,
  373. optimizer,
  374. save_model_dir,
  375. logger,
  376. config,
  377. is_best=True,
  378. prefix='best_accuracy',
  379. best_model_dict=best_model_dict,
  380. epoch=epoch,
  381. global_step=global_step)
  382. best_str = 'best metric, {}'.format(', '.join([
  383. '{}: {}'.format(k, v) for k, v in best_model_dict.items()
  384. ]))
  385. logger.info(best_str)
  386. # logger best metric
  387. if log_writer is not None:
  388. log_writer.log_metrics(
  389. metrics={
  390. "best_{}".format(main_indicator):
  391. best_model_dict[main_indicator]
  392. },
  393. prefix="EVAL",
  394. step=global_step)
  395. log_writer.log_model(
  396. is_best=True,
  397. prefix="best_accuracy",
  398. metadata=best_model_dict)
  399. reader_start = time.time()
  400. if dist.get_rank() == 0:
  401. save_model(
  402. model,
  403. optimizer,
  404. save_model_dir,
  405. logger,
  406. config,
  407. is_best=False,
  408. prefix='latest',
  409. best_model_dict=best_model_dict,
  410. epoch=epoch,
  411. global_step=global_step)
  412. if log_writer is not None:
  413. log_writer.log_model(is_best=False, prefix="latest")
  414. if dist.get_rank() == 0 and epoch > 0 and epoch % save_epoch_step == 0:
  415. save_model(
  416. model,
  417. optimizer,
  418. save_model_dir,
  419. logger,
  420. config,
  421. is_best=False,
  422. prefix='iter_epoch_{}'.format(epoch),
  423. best_model_dict=best_model_dict,
  424. epoch=epoch,
  425. global_step=global_step)
  426. if log_writer is not None:
  427. log_writer.log_model(
  428. is_best=False, prefix='iter_epoch_{}'.format(epoch))
  429. best_str = 'best metric, {}'.format(', '.join(
  430. ['{}: {}'.format(k, v) for k, v in best_model_dict.items()]))
  431. logger.info(best_str)
  432. if dist.get_rank() == 0 and log_writer is not None:
  433. log_writer.close()
  434. return
  435. def eval(model,
  436. valid_dataloader,
  437. post_process_class,
  438. eval_class,
  439. model_type=None,
  440. extra_input=False,
  441. scaler=None,
  442. amp_level='O2',
  443. amp_custom_black_list=[]):
  444. model.eval()
  445. with paddle.no_grad():
  446. total_frame = 0.0
  447. total_time = 0.0
  448. pbar = tqdm(
  449. total=len(valid_dataloader),
  450. desc='eval model:',
  451. position=0,
  452. leave=True)
  453. max_iter = len(valid_dataloader) - 1 if platform.system(
  454. ) == "Windows" else len(valid_dataloader)
  455. sum_images = 0
  456. for idx, batch in enumerate(valid_dataloader):
  457. if idx >= max_iter:
  458. break
  459. images = batch[0]
  460. start = time.time()
  461. # use amp
  462. if scaler:
  463. with paddle.amp.auto_cast(
  464. level=amp_level,
  465. custom_black_list=amp_custom_black_list):
  466. if model_type == 'table' or extra_input:
  467. preds = model(images, data=batch[1:])
  468. elif model_type in ["kie"]:
  469. preds = model(batch)
  470. elif model_type in ['can']:
  471. preds = model(batch[:3])
  472. elif model_type in ['sr']:
  473. preds = model(batch)
  474. sr_img = preds["sr_img"]
  475. lr_img = preds["lr_img"]
  476. else:
  477. preds = model(images)
  478. preds = to_float32(preds)
  479. else:
  480. if model_type == 'table' or extra_input:
  481. preds = model(images, data=batch[1:])
  482. elif model_type in ["kie"]:
  483. preds = model(batch)
  484. elif model_type in ['can']:
  485. preds = model(batch[:3])
  486. elif model_type in ['sr']:
  487. preds = model(batch)
  488. sr_img = preds["sr_img"]
  489. lr_img = preds["lr_img"]
  490. else:
  491. preds = model(images)
  492. batch_numpy = []
  493. for item in batch:
  494. if isinstance(item, paddle.Tensor):
  495. batch_numpy.append(item.numpy())
  496. else:
  497. batch_numpy.append(item)
  498. # Obtain usable results from post-processing methods
  499. total_time += time.time() - start
  500. # Evaluate the results of the current batch
  501. if model_type in ['table', 'kie']:
  502. if post_process_class is None:
  503. eval_class(preds, batch_numpy)
  504. else:
  505. post_result = post_process_class(preds, batch_numpy)
  506. eval_class(post_result, batch_numpy)
  507. elif model_type in ['sr']:
  508. eval_class(preds, batch_numpy)
  509. elif model_type in ['can']:
  510. eval_class(preds[0], batch_numpy[2:], epoch_reset=(idx == 0))
  511. else:
  512. post_result = post_process_class(preds, batch_numpy[1])
  513. eval_class(post_result, batch_numpy)
  514. pbar.update(1)
  515. total_frame += len(images)
  516. sum_images += 1
  517. # Get final metric,eg. acc or hmean
  518. metric = eval_class.get_metric()
  519. pbar.close()
  520. model.train()
  521. metric['fps'] = total_frame / total_time
  522. return metric
  523. def update_center(char_center, post_result, preds):
  524. result, label = post_result
  525. feats, logits = preds
  526. logits = paddle.argmax(logits, axis=-1)
  527. feats = feats.numpy()
  528. logits = logits.numpy()
  529. for idx_sample in range(len(label)):
  530. if result[idx_sample][0] == label[idx_sample][0]:
  531. feat = feats[idx_sample]
  532. logit = logits[idx_sample]
  533. for idx_time in range(len(logit)):
  534. index = logit[idx_time]
  535. if index in char_center.keys():
  536. char_center[index][0] = (
  537. char_center[index][0] * char_center[index][1] +
  538. feat[idx_time]) / (char_center[index][1] + 1)
  539. char_center[index][1] += 1
  540. else:
  541. char_center[index] = [feat[idx_time], 1]
  542. return char_center
  543. def get_center(model, eval_dataloader, post_process_class):
  544. pbar = tqdm(total=len(eval_dataloader), desc='get center:')
  545. max_iter = len(eval_dataloader) - 1 if platform.system(
  546. ) == "Windows" else len(eval_dataloader)
  547. char_center = dict()
  548. for idx, batch in enumerate(eval_dataloader):
  549. if idx >= max_iter:
  550. break
  551. images = batch[0]
  552. start = time.time()
  553. preds = model(images)
  554. batch = [item.numpy() for item in batch]
  555. # Obtain usable results from post-processing methods
  556. post_result = post_process_class(preds, batch[1])
  557. #update char_center
  558. char_center = update_center(char_center, post_result, preds)
  559. pbar.update(1)
  560. pbar.close()
  561. for key in char_center.keys():
  562. char_center[key] = char_center[key][0]
  563. return char_center
  564. def preprocess(is_train=False):
  565. FLAGS = ArgsParser().parse_args()
  566. profiler_options = FLAGS.profiler_options
  567. config = load_config(FLAGS.config)
  568. config = merge_config(config, FLAGS.opt)
  569. profile_dic = {"profiler_options": FLAGS.profiler_options}
  570. config = merge_config(config, profile_dic)
  571. if is_train:
  572. # save_config
  573. save_model_dir = config['Global']['save_model_dir']
  574. os.makedirs(save_model_dir, exist_ok=True)
  575. with open(os.path.join(save_model_dir, 'config.yml'), 'w') as f:
  576. yaml.dump(
  577. dict(config), f, default_flow_style=False, sort_keys=False)
  578. log_file = '{}/train.log'.format(save_model_dir)
  579. else:
  580. log_file = None
  581. logger = get_logger(log_file=log_file)
  582. # check if set use_gpu=True in paddlepaddle cpu version
  583. use_gpu = config['Global'].get('use_gpu', False)
  584. use_xpu = config['Global'].get('use_xpu', False)
  585. use_npu = config['Global'].get('use_npu', False)
  586. use_mlu = config['Global'].get('use_mlu', False)
  587. alg = config['Architecture']['algorithm']
  588. assert alg in [
  589. 'EAST', 'DB', 'SAST', 'Rosetta', 'CRNN', 'STARNet', 'RARE', 'SRN',
  590. 'CLS', 'PGNet', 'Distillation', 'NRTR', 'TableAttn', 'SAR', 'PSE',
  591. 'SEED', 'SDMGR', 'LayoutXLM', 'LayoutLM', 'LayoutLMv2', 'PREN', 'FCE',
  592. 'SVTR', 'ViTSTR', 'ABINet', 'DB++', 'TableMaster', 'SPIN', 'VisionLAN',
  593. 'Gestalt', 'SLANet', 'RobustScanner', 'CT', 'RFL', 'DRRG', 'CAN',
  594. 'Telescope'
  595. ]
  596. if use_xpu:
  597. device = 'xpu:{0}'.format(os.getenv('FLAGS_selected_xpus', 0))
  598. elif use_npu:
  599. device = 'npu:{0}'.format(os.getenv('FLAGS_selected_npus', 0))
  600. elif use_mlu:
  601. device = 'mlu:{0}'.format(os.getenv('FLAGS_selected_mlus', 0))
  602. else:
  603. device = 'gpu:{}'.format(dist.ParallelEnv()
  604. .dev_id) if use_gpu else 'cpu'
  605. check_device(use_gpu, use_xpu, use_npu, use_mlu)
  606. device = paddle.set_device(device)
  607. config['Global']['distributed'] = dist.get_world_size() != 1
  608. loggers = []
  609. if 'use_visualdl' in config['Global'] and config['Global']['use_visualdl']:
  610. save_model_dir = config['Global']['save_model_dir']
  611. vdl_writer_path = '{}/vdl/'.format(save_model_dir)
  612. log_writer = VDLLogger(vdl_writer_path)
  613. loggers.append(log_writer)
  614. if ('use_wandb' in config['Global'] and
  615. config['Global']['use_wandb']) or 'wandb' in config:
  616. save_dir = config['Global']['save_model_dir']
  617. wandb_writer_path = "{}/wandb".format(save_dir)
  618. if "wandb" in config:
  619. wandb_params = config['wandb']
  620. else:
  621. wandb_params = dict()
  622. wandb_params.update({'save_dir': save_model_dir})
  623. log_writer = WandbLogger(**wandb_params, config=config)
  624. loggers.append(log_writer)
  625. else:
  626. log_writer = None
  627. print_dict(config, logger)
  628. if loggers:
  629. log_writer = Loggers(loggers)
  630. else:
  631. log_writer = None
  632. logger.info('train with paddle {} and device {}'.format(paddle.__version__,
  633. device))
  634. return config, device, logger, log_writer