abs_task.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  1. # Copyright ESPnet (https://github.com/espnet/espnet). All Rights Reserved.
  2. # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
  3. """Abstract task module."""
  4. import argparse
  5. import functools
  6. import logging
  7. import os
  8. import sys
  9. from abc import ABC
  10. from abc import abstractmethod
  11. from dataclasses import dataclass
  12. from distutils.version import LooseVersion
  13. from io import BytesIO
  14. from pathlib import Path
  15. from typing import Any
  16. from typing import Callable
  17. from typing import Dict
  18. from typing import List
  19. from typing import Optional
  20. from typing import Sequence
  21. from typing import Tuple
  22. from typing import Union
  23. import humanfriendly
  24. import numpy as np
  25. import torch
  26. import torch.distributed as dist
  27. import torch.multiprocessing
  28. import torch.nn
  29. import torch.optim
  30. import yaml
  31. from torch.utils.data import DataLoader
  32. from typeguard import check_argument_types
  33. from typeguard import check_return_type
  34. from funasr import __version__
  35. from funasr.datasets.dataset import AbsDataset
  36. from funasr.datasets.dataset import DATA_TYPES
  37. from funasr.datasets.dataset import ESPnetDataset
  38. from funasr.datasets.iterable_dataset import IterableESPnetDataset
  39. from funasr.iterators.abs_iter_factory import AbsIterFactory
  40. from funasr.iterators.chunk_iter_factory import ChunkIterFactory
  41. from funasr.iterators.multiple_iter_factory import MultipleIterFactory
  42. from funasr.iterators.sequence_iter_factory import SequenceIterFactory
  43. from funasr.optimizers.sgd import SGD
  44. from funasr.optimizers.fairseq_adam import FairseqAdam
  45. from funasr.samplers.build_batch_sampler import BATCH_TYPES
  46. from funasr.samplers.build_batch_sampler import build_batch_sampler
  47. from funasr.samplers.unsorted_batch_sampler import UnsortedBatchSampler
  48. from funasr.schedulers.noam_lr import NoamLR
  49. from funasr.schedulers.warmup_lr import WarmupLR
  50. from funasr.schedulers.tri_stage_scheduler import TriStageLR
  51. from funasr.torch_utils.load_pretrained_model import load_pretrained_model
  52. from funasr.torch_utils.model_summary import model_summary
  53. from funasr.torch_utils.pytorch_version import pytorch_cudnn_version
  54. from funasr.torch_utils.set_all_random_seed import set_all_random_seed
  55. from funasr.train.abs_espnet_model import AbsESPnetModel
  56. from funasr.train.class_choices import ClassChoices
  57. from funasr.train.distributed_utils import DistributedOption
  58. from funasr.train.trainer import Trainer
  59. from funasr.utils import config_argparse
  60. from funasr.utils.build_dataclass import build_dataclass
  61. from funasr.utils.cli_utils import get_commandline_args
  62. from funasr.utils.get_default_kwargs import get_default_kwargs
  63. from funasr.utils.nested_dict_action import NestedDictAction
  64. from funasr.utils.types import humanfriendly_parse_size_or_none
  65. from funasr.utils.types import int_or_none
  66. from funasr.utils.types import str2bool
  67. from funasr.utils.types import str2triple_str
  68. from funasr.utils.types import str_or_int
  69. from funasr.utils.types import str_or_none
  70. from funasr.utils.wav_utils import calc_shape, generate_data_list
  71. from funasr.utils.yaml_no_alias_safe_dump import yaml_no_alias_safe_dump
  72. try:
  73. import wandb
  74. except Exception:
  75. wandb = None
  76. if LooseVersion(torch.__version__) >= LooseVersion("1.5.0"):
  77. pass
  78. else:
  79. pass
  80. optim_classes = dict(
  81. adam=torch.optim.Adam,
  82. fairseq_adam=FairseqAdam,
  83. adamw=torch.optim.AdamW,
  84. sgd=SGD,
  85. adadelta=torch.optim.Adadelta,
  86. adagrad=torch.optim.Adagrad,
  87. adamax=torch.optim.Adamax,
  88. asgd=torch.optim.ASGD,
  89. lbfgs=torch.optim.LBFGS,
  90. rmsprop=torch.optim.RMSprop,
  91. rprop=torch.optim.Rprop,
  92. )
  93. if LooseVersion(torch.__version__) >= LooseVersion("1.10.0"):
  94. # From 1.10.0, RAdam is officially supported
  95. optim_classes.update(
  96. radam=torch.optim.RAdam,
  97. )
  98. try:
  99. import torch_optimizer
  100. optim_classes.update(
  101. accagd=torch_optimizer.AccSGD,
  102. adabound=torch_optimizer.AdaBound,
  103. adamod=torch_optimizer.AdaMod,
  104. diffgrad=torch_optimizer.DiffGrad,
  105. lamb=torch_optimizer.Lamb,
  106. novograd=torch_optimizer.NovoGrad,
  107. pid=torch_optimizer.PID,
  108. # torch_optimizer<=0.0.1a10 doesn't support
  109. # qhadam=torch_optimizer.QHAdam,
  110. qhm=torch_optimizer.QHM,
  111. sgdw=torch_optimizer.SGDW,
  112. yogi=torch_optimizer.Yogi,
  113. )
  114. if LooseVersion(torch_optimizer.__version__) < LooseVersion("0.2.0"):
  115. # From 0.2.0, RAdam is dropped
  116. optim_classes.update(
  117. radam=torch_optimizer.RAdam,
  118. )
  119. del torch_optimizer
  120. except ImportError:
  121. pass
  122. try:
  123. import apex
  124. optim_classes.update(
  125. fusedadam=apex.optimizers.FusedAdam,
  126. fusedlamb=apex.optimizers.FusedLAMB,
  127. fusednovograd=apex.optimizers.FusedNovoGrad,
  128. fusedsgd=apex.optimizers.FusedSGD,
  129. )
  130. del apex
  131. except ImportError:
  132. pass
  133. try:
  134. import fairscale
  135. except ImportError:
  136. fairscale = None
  137. scheduler_classes = dict(
  138. ReduceLROnPlateau=torch.optim.lr_scheduler.ReduceLROnPlateau,
  139. lambdalr=torch.optim.lr_scheduler.LambdaLR,
  140. steplr=torch.optim.lr_scheduler.StepLR,
  141. multisteplr=torch.optim.lr_scheduler.MultiStepLR,
  142. exponentiallr=torch.optim.lr_scheduler.ExponentialLR,
  143. CosineAnnealingLR=torch.optim.lr_scheduler.CosineAnnealingLR,
  144. noamlr=NoamLR,
  145. warmuplr=WarmupLR,
  146. tri_stage=TriStageLR,
  147. cycliclr=torch.optim.lr_scheduler.CyclicLR,
  148. onecyclelr=torch.optim.lr_scheduler.OneCycleLR,
  149. CosineAnnealingWarmRestarts=torch.optim.lr_scheduler.CosineAnnealingWarmRestarts,
  150. )
  151. # To lower keys
  152. optim_classes = {k.lower(): v for k, v in optim_classes.items()}
  153. scheduler_classes = {k.lower(): v for k, v in scheduler_classes.items()}
  154. @dataclass
  155. class IteratorOptions:
  156. preprocess_fn: callable
  157. collate_fn: callable
  158. data_path_and_name_and_type: list
  159. shape_files: list
  160. batch_size: int
  161. batch_bins: int
  162. batch_type: str
  163. max_cache_size: float
  164. max_cache_fd: int
  165. distributed: bool
  166. num_batches: Optional[int]
  167. num_iters_per_epoch: Optional[int]
  168. train: bool
  169. class AbsTask(ABC):
  170. # Use @staticmethod, or @classmethod,
  171. # instead of instance method to avoid God classes
  172. # If you need more than one optimizers, change this value in inheritance
  173. num_optimizers: int = 1
  174. trainer = Trainer
  175. class_choices_list: List[ClassChoices] = []
  176. finetune_args: None
  177. def __init__(self):
  178. raise RuntimeError("This class can't be instantiated.")
  179. @classmethod
  180. @abstractmethod
  181. def add_task_arguments(cls, parser: argparse.ArgumentParser):
  182. pass
  183. @classmethod
  184. @abstractmethod
  185. def build_collate_fn(
  186. cls, args: argparse.Namespace, train: bool
  187. ) -> Callable[[Sequence[Dict[str, np.ndarray]]], Dict[str, torch.Tensor]]:
  188. """Return "collate_fn", which is a callable object and given to DataLoader.
  189. >>> from torch.utils.data import DataLoader
  190. >>> loader = DataLoader(collate_fn=cls.build_collate_fn(args, train=True), ...)
  191. In many cases, you can use our common collate_fn.
  192. """
  193. raise NotImplementedError
  194. @classmethod
  195. @abstractmethod
  196. def build_preprocess_fn(
  197. cls, args: argparse.Namespace, train: bool
  198. ) -> Optional[Callable[[str, Dict[str, np.array]], Dict[str, np.ndarray]]]:
  199. raise NotImplementedError
  200. @classmethod
  201. @abstractmethod
  202. def required_data_names(
  203. cls, train: bool = True, inference: bool = False
  204. ) -> Tuple[str, ...]:
  205. """Define the required names by Task
  206. This function is used by
  207. >>> cls.check_task_requirements()
  208. If your model is defined as following,
  209. >>> from funasr.train.abs_espnet_model import AbsESPnetModel
  210. >>> class Model(AbsESPnetModel):
  211. ... def forward(self, input, output, opt=None): pass
  212. then "required_data_names" should be as
  213. >>> required_data_names = ('input', 'output')
  214. """
  215. raise NotImplementedError
  216. @classmethod
  217. @abstractmethod
  218. def optional_data_names(
  219. cls, train: bool = True, inference: bool = False
  220. ) -> Tuple[str, ...]:
  221. """Define the optional names by Task
  222. This function is used by
  223. >>> cls.check_task_requirements()
  224. If your model is defined as follows,
  225. >>> from funasr.train.abs_espnet_model import AbsESPnetModel
  226. >>> class Model(AbsESPnetModel):
  227. ... def forward(self, input, output, opt=None): pass
  228. then "optional_data_names" should be as
  229. >>> optional_data_names = ('opt',)
  230. """
  231. raise NotImplementedError
  232. @classmethod
  233. @abstractmethod
  234. def build_model(cls, args: argparse.Namespace) -> AbsESPnetModel:
  235. raise NotImplementedError
  236. @classmethod
  237. def get_parser(cls) -> config_argparse.ArgumentParser:
  238. assert check_argument_types()
  239. class ArgumentDefaultsRawTextHelpFormatter(
  240. argparse.RawTextHelpFormatter,
  241. argparse.ArgumentDefaultsHelpFormatter,
  242. ):
  243. pass
  244. parser = config_argparse.ArgumentParser(
  245. description="base parser",
  246. formatter_class=ArgumentDefaultsRawTextHelpFormatter,
  247. )
  248. # NOTE(kamo): Use '_' instead of '-' to avoid confusion.
  249. # I think '-' looks really confusing if it's written in yaml.
  250. # NOTE(kamo): add_arguments(..., required=True) can't be used
  251. # to provide --print_config mode. Instead of it, do as
  252. # parser.set_defaults(required=["output_dir"])
  253. group = parser.add_argument_group("Common configuration")
  254. group.add_argument(
  255. "--print_config",
  256. action="store_true",
  257. help="Print the config file and exit",
  258. )
  259. group.add_argument(
  260. "--log_level",
  261. type=lambda x: x.upper(),
  262. default="INFO",
  263. choices=("ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"),
  264. help="The verbose level of logging",
  265. )
  266. group.add_argument(
  267. "--dry_run",
  268. type=str2bool,
  269. default=False,
  270. help="Perform process without training",
  271. )
  272. group.add_argument(
  273. "--iterator_type",
  274. type=str,
  275. choices=["sequence", "chunk", "task", "none"],
  276. default="sequence",
  277. help="Specify iterator type",
  278. )
  279. group.add_argument("--output_dir", type=str_or_none, default=None)
  280. group.add_argument(
  281. "--ngpu",
  282. type=int,
  283. default=0,
  284. help="The number of gpus. 0 indicates CPU mode",
  285. )
  286. group.add_argument("--seed", type=int, default=0, help="Random seed")
  287. group.add_argument(
  288. "--num_workers",
  289. type=int,
  290. default=1,
  291. help="The number of workers used for DataLoader",
  292. )
  293. group.add_argument(
  294. "--num_att_plot",
  295. type=int,
  296. default=3,
  297. help="The number images to plot the outputs from attention. "
  298. "This option makes sense only when attention-based model. "
  299. "We can also disable the attention plot by setting it 0",
  300. )
  301. group = parser.add_argument_group("distributed training related")
  302. group.add_argument(
  303. "--dist_backend",
  304. default="nccl",
  305. type=str,
  306. help="distributed backend",
  307. )
  308. group.add_argument(
  309. "--dist_init_method",
  310. type=str,
  311. default="env://",
  312. help='if init_method="env://", env values of "MASTER_PORT", "MASTER_ADDR", '
  313. '"WORLD_SIZE", and "RANK" are referred.',
  314. )
  315. group.add_argument(
  316. "--dist_world_size",
  317. default=None,
  318. type=int_or_none,
  319. help="number of nodes for distributed training",
  320. )
  321. group.add_argument(
  322. "--dist_rank",
  323. type=int_or_none,
  324. default=None,
  325. help="node rank for distributed training",
  326. )
  327. group.add_argument(
  328. # Not starting with "dist_" for compatibility to launch.py
  329. "--local_rank",
  330. type=int_or_none,
  331. default=None,
  332. help="local rank for distributed training. This option is used if "
  333. "--multiprocessing_distributed=false",
  334. )
  335. group.add_argument(
  336. "--dist_master_addr",
  337. default=None,
  338. type=str_or_none,
  339. help="The master address for distributed training. "
  340. "This value is used when dist_init_method == 'env://'",
  341. )
  342. group.add_argument(
  343. "--dist_master_port",
  344. default=None,
  345. type=int_or_none,
  346. help="The master port for distributed training"
  347. "This value is used when dist_init_method == 'env://'",
  348. )
  349. group.add_argument(
  350. "--dist_launcher",
  351. default=None,
  352. type=str_or_none,
  353. choices=["slurm", "mpi", None],
  354. help="The launcher type for distributed training",
  355. )
  356. group.add_argument(
  357. "--multiprocessing_distributed",
  358. default=False,
  359. type=str2bool,
  360. help="Use multi-processing distributed training to launch "
  361. "N processes per node, which has N GPUs. This is the "
  362. "fastest way to use PyTorch for either single node or "
  363. "multi node data parallel training",
  364. )
  365. group.add_argument(
  366. "--unused_parameters",
  367. type=str2bool,
  368. default=False,
  369. help="Whether to use the find_unused_parameters in "
  370. "torch.nn.parallel.DistributedDataParallel ",
  371. )
  372. group.add_argument(
  373. "--sharded_ddp",
  374. default=False,
  375. type=str2bool,
  376. help="Enable sharded training provided by fairscale",
  377. )
  378. group = parser.add_argument_group("cudnn mode related")
  379. group.add_argument(
  380. "--cudnn_enabled",
  381. type=str2bool,
  382. default=torch.backends.cudnn.enabled,
  383. help="Enable CUDNN",
  384. )
  385. group.add_argument(
  386. "--cudnn_benchmark",
  387. type=str2bool,
  388. default=torch.backends.cudnn.benchmark,
  389. help="Enable cudnn-benchmark mode",
  390. )
  391. group.add_argument(
  392. "--cudnn_deterministic",
  393. type=str2bool,
  394. default=True,
  395. help="Enable cudnn-deterministic mode",
  396. )
  397. group = parser.add_argument_group("collect stats mode related")
  398. group.add_argument(
  399. "--collect_stats",
  400. type=str2bool,
  401. default=False,
  402. help='Perform on "collect stats" mode',
  403. )
  404. group.add_argument(
  405. "--write_collected_feats",
  406. type=str2bool,
  407. default=False,
  408. help='Write the output features from the model when "collect stats" mode',
  409. )
  410. group = parser.add_argument_group("Trainer related")
  411. group.add_argument(
  412. "--max_epoch",
  413. type=int,
  414. default=40,
  415. help="The maximum number epoch to train",
  416. )
  417. group.add_argument(
  418. "--max_update",
  419. type=int,
  420. default=sys.maxsize,
  421. help="The maximum number update step to train",
  422. )
  423. group.add_argument(
  424. "--patience",
  425. type=int_or_none,
  426. default=None,
  427. help="Number of epochs to wait without improvement "
  428. "before stopping the training",
  429. )
  430. group.add_argument(
  431. "--val_scheduler_criterion",
  432. type=str,
  433. nargs=2,
  434. default=("valid", "loss"),
  435. help="The criterion used for the value given to the lr scheduler. "
  436. 'Give a pair referring the phase, "train" or "valid",'
  437. 'and the criterion name. The mode specifying "min" or "max" can '
  438. "be changed by --scheduler_conf",
  439. )
  440. group.add_argument(
  441. "--early_stopping_criterion",
  442. type=str,
  443. nargs=3,
  444. default=("valid", "loss", "min"),
  445. help="The criterion used for judging of early stopping. "
  446. 'Give a pair referring the phase, "train" or "valid",'
  447. 'the criterion name and the mode, "min" or "max", e.g. "acc,max".',
  448. )
  449. group.add_argument(
  450. "--best_model_criterion",
  451. type=str2triple_str,
  452. nargs="+",
  453. default=[
  454. ("train", "loss", "min"),
  455. ("valid", "loss", "min"),
  456. ("train", "acc", "max"),
  457. ("valid", "acc", "max"),
  458. ],
  459. help="The criterion used for judging of the best model. "
  460. 'Give a pair referring the phase, "train" or "valid",'
  461. 'the criterion name, and the mode, "min" or "max", e.g. "acc,max".',
  462. )
  463. group.add_argument(
  464. "--keep_nbest_models",
  465. type=int,
  466. nargs="+",
  467. default=[10],
  468. help="Remove previous snapshots excluding the n-best scored epochs",
  469. )
  470. group.add_argument(
  471. "--nbest_averaging_interval",
  472. type=int,
  473. default=0,
  474. help="The epoch interval to apply model averaging and save nbest models",
  475. )
  476. group.add_argument(
  477. "--grad_clip",
  478. type=float,
  479. default=5.0,
  480. help="Gradient norm threshold to clip",
  481. )
  482. group.add_argument(
  483. "--grad_clip_type",
  484. type=float,
  485. default=2.0,
  486. help="The type of the used p-norm for gradient clip. Can be inf",
  487. )
  488. group.add_argument(
  489. "--grad_noise",
  490. type=str2bool,
  491. default=False,
  492. help="The flag to switch to use noise injection to "
  493. "gradients during training",
  494. )
  495. group.add_argument(
  496. "--accum_grad",
  497. type=int,
  498. default=1,
  499. help="The number of gradient accumulation",
  500. )
  501. group.add_argument(
  502. "--no_forward_run",
  503. type=str2bool,
  504. default=False,
  505. help="Just only iterating data loading without "
  506. "model forwarding and training",
  507. )
  508. group.add_argument(
  509. "--resume",
  510. type=str2bool,
  511. default=False,
  512. help="Enable resuming if checkpoint is existing",
  513. )
  514. group.add_argument(
  515. "--train_dtype",
  516. default="float32",
  517. choices=["float16", "float32", "float64"],
  518. help="Data type for training.",
  519. )
  520. group.add_argument(
  521. "--use_amp",
  522. type=str2bool,
  523. default=False,
  524. help="Enable Automatic Mixed Precision. This feature requires pytorch>=1.6",
  525. )
  526. group.add_argument(
  527. "--log_interval",
  528. type=int_or_none,
  529. default=None,
  530. help="Show the logs every the number iterations in each epochs at the "
  531. "training phase. If None is given, it is decided according the number "
  532. "of training samples automatically .",
  533. )
  534. group.add_argument(
  535. "--use_tensorboard",
  536. type=str2bool,
  537. default=True,
  538. help="Enable tensorboard logging",
  539. )
  540. group.add_argument(
  541. "--use_wandb",
  542. type=str2bool,
  543. default=False,
  544. help="Enable wandb logging",
  545. )
  546. group.add_argument(
  547. "--wandb_project",
  548. type=str,
  549. default=None,
  550. help="Specify wandb project",
  551. )
  552. group.add_argument(
  553. "--wandb_id",
  554. type=str,
  555. default=None,
  556. help="Specify wandb id",
  557. )
  558. group.add_argument(
  559. "--wandb_entity",
  560. type=str,
  561. default=None,
  562. help="Specify wandb entity",
  563. )
  564. group.add_argument(
  565. "--wandb_name",
  566. type=str,
  567. default=None,
  568. help="Specify wandb run name",
  569. )
  570. group.add_argument(
  571. "--wandb_model_log_interval",
  572. type=int,
  573. default=-1,
  574. help="Set the model log period",
  575. )
  576. group.add_argument(
  577. "--detect_anomaly",
  578. type=str2bool,
  579. default=False,
  580. help="Set torch.autograd.set_detect_anomaly",
  581. )
  582. group = parser.add_argument_group("Pretraining model related")
  583. group.add_argument("--pretrain_path", help="This option is obsoleted")
  584. group.add_argument(
  585. "--init_param",
  586. type=str,
  587. default=[],
  588. nargs="*",
  589. help="Specify the file path used for initialization of parameters. "
  590. "The format is '<file_path>:<src_key>:<dst_key>:<exclude_keys>', "
  591. "where file_path is the model file path, "
  592. "src_key specifies the key of model states to be used in the model file, "
  593. "dst_key specifies the attribute of the model to be initialized, "
  594. "and exclude_keys excludes keys of model states for the initialization."
  595. "e.g.\n"
  596. " # Load all parameters"
  597. " --init_param some/where/model.pth\n"
  598. " # Load only decoder parameters"
  599. " --init_param some/where/model.pth:decoder:decoder\n"
  600. " # Load only decoder parameters excluding decoder.embed"
  601. " --init_param some/where/model.pth:decoder:decoder:decoder.embed\n"
  602. " --init_param some/where/model.pth:decoder:decoder:decoder.embed\n",
  603. )
  604. group.add_argument(
  605. "--ignore_init_mismatch",
  606. type=str2bool,
  607. default=False,
  608. help="Ignore size mismatch when loading pre-trained model",
  609. )
  610. group.add_argument(
  611. "--freeze_param",
  612. type=str,
  613. default=[],
  614. nargs="*",
  615. help="Freeze parameters",
  616. )
  617. group = parser.add_argument_group("BatchSampler related")
  618. group.add_argument(
  619. "--num_iters_per_epoch",
  620. type=int_or_none,
  621. default=None,
  622. help="Restrict the number of iterations for training per epoch",
  623. )
  624. group.add_argument(
  625. "--batch_size",
  626. type=int,
  627. default=20,
  628. help="The mini-batch size used for training. Used if batch_type='unsorted',"
  629. " 'sorted', or 'folded'.",
  630. )
  631. group.add_argument(
  632. "--valid_batch_size",
  633. type=int_or_none,
  634. default=None,
  635. help="If not given, the value of --batch_size is used",
  636. )
  637. group.add_argument(
  638. "--batch_bins",
  639. type=int,
  640. default=1000000,
  641. help="The number of batch bins. Used if batch_type='length' or 'numel'",
  642. )
  643. group.add_argument(
  644. "--valid_batch_bins",
  645. type=int_or_none,
  646. default=None,
  647. help="If not given, the value of --batch_bins is used",
  648. )
  649. group.add_argument("--train_shape_file", type=str, action="append", default=[])
  650. group.add_argument("--valid_shape_file", type=str, action="append", default=[])
  651. group = parser.add_argument_group("Sequence iterator related")
  652. _batch_type_help = ""
  653. for key, value in BATCH_TYPES.items():
  654. _batch_type_help += f'"{key}":\n{value}\n'
  655. group.add_argument(
  656. "--batch_type",
  657. type=str,
  658. default="length",
  659. choices=list(BATCH_TYPES),
  660. help=_batch_type_help,
  661. )
  662. group.add_argument(
  663. "--valid_batch_type",
  664. type=str_or_none,
  665. default=None,
  666. choices=list(BATCH_TYPES) + [None],
  667. help="If not given, the value of --batch_type is used",
  668. )
  669. group.add_argument(
  670. "--speech_length_min",
  671. type=int,
  672. default=-1,
  673. help="speech length min",
  674. )
  675. group.add_argument(
  676. "--speech_length_max",
  677. type=int,
  678. default=-1,
  679. help="speech length max",
  680. )
  681. group.add_argument("--fold_length", type=int, action="append", default=[])
  682. group.add_argument(
  683. "--sort_in_batch",
  684. type=str,
  685. default="descending",
  686. choices=["descending", "ascending"],
  687. help="Sort the samples in each mini-batches by the sample "
  688. 'lengths. To enable this, "shape_file" must have the length information.',
  689. )
  690. group.add_argument(
  691. "--sort_batch",
  692. type=str,
  693. default="descending",
  694. choices=["descending", "ascending"],
  695. help="Sort mini-batches by the sample lengths",
  696. )
  697. group.add_argument(
  698. "--multiple_iterator",
  699. type=str2bool,
  700. default=False,
  701. help="Use multiple iterator mode",
  702. )
  703. group = parser.add_argument_group("Chunk iterator related")
  704. group.add_argument(
  705. "--chunk_length",
  706. type=str_or_int,
  707. default=500,
  708. help="Specify chunk length. e.g. '300', '300,400,500', or '300-400'."
  709. "If multiple numbers separated by command are given, "
  710. "one of them is selected randomly for each samples. "
  711. "If two numbers are given with '-', it indicates the range of the choices. "
  712. "Note that if the sequence length is shorter than the all chunk_lengths, "
  713. "the sample is discarded. ",
  714. )
  715. group.add_argument(
  716. "--chunk_shift_ratio",
  717. type=float,
  718. default=0.5,
  719. help="Specify the shift width of chunks. If it's less than 1, "
  720. "allows the overlapping and if bigger than 1, there are some gaps "
  721. "between each chunk.",
  722. )
  723. group.add_argument(
  724. "--num_cache_chunks",
  725. type=int,
  726. default=1024,
  727. help="Shuffle in the specified number of chunks and generate mini-batches "
  728. "More larger this value, more randomness can be obtained.",
  729. )
  730. group = parser.add_argument_group("Dataset related")
  731. _data_path_and_name_and_type_help = (
  732. "Give three words splitted by comma. It's used for the training data. "
  733. "e.g. '--train_data_path_and_name_and_type some/path/a.scp,foo,sound'. "
  734. "The first value, some/path/a.scp, indicates the file path, "
  735. "and the second, foo, is the key name used for the mini-batch data, "
  736. "and the last, sound, decides the file type. "
  737. "This option is repeatable, so you can input any number of features "
  738. "for your task. Supported file types are as follows:\n\n"
  739. )
  740. for key, dic in DATA_TYPES.items():
  741. _data_path_and_name_and_type_help += f'"{key}":\n{dic["help"]}\n\n'
  742. # for large dataset
  743. group.add_argument(
  744. "--dataset_type",
  745. type=str,
  746. default="small",
  747. help="whether to use dataloader for large dataset",
  748. )
  749. parser.add_argument(
  750. "--dataset_conf",
  751. action=NestedDictAction,
  752. default=dict(),
  753. help=f"The keyword arguments for dataset",
  754. )
  755. group.add_argument(
  756. "--train_data_file",
  757. type=str,
  758. default=None,
  759. help="train_list for large dataset",
  760. )
  761. group.add_argument(
  762. "--valid_data_file",
  763. type=str,
  764. default=None,
  765. help="valid_list for large dataset",
  766. )
  767. group.add_argument(
  768. "--train_data_path_and_name_and_type",
  769. type=str2triple_str,
  770. action="append",
  771. default=[],
  772. help=_data_path_and_name_and_type_help,
  773. )
  774. group.add_argument(
  775. "--valid_data_path_and_name_and_type",
  776. type=str2triple_str,
  777. action="append",
  778. default=[],
  779. )
  780. group.add_argument(
  781. "--allow_variable_data_keys",
  782. type=str2bool,
  783. default=False,
  784. help="Allow the arbitrary keys for mini-batch with ignoring "
  785. "the task requirements",
  786. )
  787. group.add_argument(
  788. "--max_cache_size",
  789. type=humanfriendly.parse_size,
  790. default=0.0,
  791. help="The maximum cache size for data loader. e.g. 10MB, 20GB.",
  792. )
  793. group.add_argument(
  794. "--max_cache_fd",
  795. type=int,
  796. default=32,
  797. help="The maximum number of file descriptors to be kept "
  798. "as opened for ark files. "
  799. "This feature is only valid when data type is 'kaldi_ark'.",
  800. )
  801. group.add_argument(
  802. "--valid_max_cache_size",
  803. type=humanfriendly_parse_size_or_none,
  804. default=None,
  805. help="The maximum cache size for validation data loader. e.g. 10MB, 20GB. "
  806. "If None, the 5 percent size of --max_cache_size",
  807. )
  808. group = parser.add_argument_group("Optimizer related")
  809. for i in range(1, cls.num_optimizers + 1):
  810. suf = "" if i == 1 else str(i)
  811. group.add_argument(
  812. f"--optim{suf}",
  813. type=lambda x: x.lower(),
  814. default="adadelta",
  815. choices=list(optim_classes),
  816. help="The optimizer type",
  817. )
  818. group.add_argument(
  819. f"--optim{suf}_conf",
  820. action=NestedDictAction,
  821. default=dict(),
  822. help="The keyword arguments for optimizer",
  823. )
  824. group.add_argument(
  825. f"--scheduler{suf}",
  826. type=lambda x: str_or_none(x.lower()),
  827. default=None,
  828. choices=list(scheduler_classes) + [None],
  829. help="The lr scheduler type",
  830. )
  831. group.add_argument(
  832. f"--scheduler{suf}_conf",
  833. action=NestedDictAction,
  834. default=dict(),
  835. help="The keyword arguments for lr scheduler",
  836. )
  837. # for training on PAI
  838. group = parser.add_argument_group("PAI training related")
  839. group.add_argument(
  840. "--use_pai",
  841. type=str2bool,
  842. default=False,
  843. help="flag to indicate whether training on PAI",
  844. )
  845. group.add_argument(
  846. "--simple_ddp",
  847. type=str2bool,
  848. default=False,
  849. )
  850. group.add_argument(
  851. "--num_worker_count",
  852. type=int,
  853. default=1,
  854. help="The number of machines on PAI.",
  855. )
  856. group.add_argument(
  857. "--access_key_id",
  858. type=str,
  859. default=None,
  860. help="The username for oss.",
  861. )
  862. group.add_argument(
  863. "--access_key_secret",
  864. type=str,
  865. default=None,
  866. help="The password for oss.",
  867. )
  868. group.add_argument(
  869. "--endpoint",
  870. type=str,
  871. default=None,
  872. help="The endpoint for oss.",
  873. )
  874. group.add_argument(
  875. "--bucket_name",
  876. type=str,
  877. default=None,
  878. help="The bucket name for oss.",
  879. )
  880. group.add_argument(
  881. "--oss_bucket",
  882. default=None,
  883. help="oss bucket.",
  884. )
  885. cls.trainer.add_arguments(parser)
  886. cls.add_task_arguments(parser)
  887. assert check_return_type(parser)
  888. return parser
  889. @classmethod
  890. def build_optimizers(
  891. cls,
  892. args: argparse.Namespace,
  893. model: torch.nn.Module,
  894. ) -> List[torch.optim.Optimizer]:
  895. if cls.num_optimizers != 1:
  896. raise RuntimeError(
  897. "build_optimizers() must be overridden if num_optimizers != 1"
  898. )
  899. optim_class = optim_classes.get(args.optim)
  900. if optim_class is None:
  901. raise ValueError(f"must be one of {list(optim_classes)}: {args.optim}")
  902. if args.sharded_ddp:
  903. if fairscale is None:
  904. raise RuntimeError("Requiring fairscale. Do 'pip install fairscale'")
  905. optim = fairscale.optim.oss.OSS(
  906. params=model.parameters(), optim=optim_class, **args.optim_conf
  907. )
  908. else:
  909. optim = optim_class(model.parameters(), **args.optim_conf)
  910. optimizers = [optim]
  911. return optimizers
  912. @classmethod
  913. def exclude_opts(cls) -> Tuple[str, ...]:
  914. """The options not to be shown by --print_config"""
  915. return "required", "print_config", "config", "ngpu"
  916. @classmethod
  917. def get_default_config(cls) -> Dict[str, Any]:
  918. """Return the configuration as dict.
  919. This method is used by print_config()
  920. """
  921. def get_class_type(name: str, classes: dict):
  922. _cls = classes.get(name)
  923. if _cls is None:
  924. raise ValueError(f"must be one of {list(classes)}: {name}")
  925. return _cls
  926. # This method is used only for --print_config
  927. assert check_argument_types()
  928. parser = cls.get_parser()
  929. args, _ = parser.parse_known_args()
  930. config = vars(args)
  931. # Excludes the options not to be shown
  932. for k in AbsTask.exclude_opts():
  933. config.pop(k)
  934. for i in range(1, cls.num_optimizers + 1):
  935. suf = "" if i == 1 else str(i)
  936. name = config[f"optim{suf}"]
  937. optim_class = get_class_type(name, optim_classes)
  938. conf = get_default_kwargs(optim_class)
  939. # Overwrite the default by the arguments,
  940. conf.update(config[f"optim{suf}_conf"])
  941. # and set it again
  942. config[f"optim{suf}_conf"] = conf
  943. name = config[f"scheduler{suf}"]
  944. if name is not None:
  945. scheduler_class = get_class_type(name, scheduler_classes)
  946. conf = get_default_kwargs(scheduler_class)
  947. # Overwrite the default by the arguments,
  948. conf.update(config[f"scheduler{suf}_conf"])
  949. # and set it again
  950. config[f"scheduler{suf}_conf"] = conf
  951. for class_choices in cls.class_choices_list:
  952. if getattr(args, class_choices.name) is not None:
  953. class_obj = class_choices.get_class(getattr(args, class_choices.name))
  954. conf = get_default_kwargs(class_obj)
  955. name = class_choices.name
  956. # Overwrite the default by the arguments,
  957. conf.update(config[f"{name}_conf"])
  958. # and set it again
  959. config[f"{name}_conf"] = conf
  960. return config
  961. @classmethod
  962. def check_required_command_args(cls, args: argparse.Namespace):
  963. assert check_argument_types()
  964. if hasattr(args, "required"):
  965. for k in vars(args):
  966. if "-" in k:
  967. raise RuntimeError(f'Use "_" instead of "-": parser.get_parser("{k}")')
  968. required = ", ".join(
  969. f"--{a}" for a in args.required if getattr(args, a) is None
  970. )
  971. if len(required) != 0:
  972. parser = cls.get_parser()
  973. parser.print_help(file=sys.stderr)
  974. p = Path(sys.argv[0]).name
  975. print(file=sys.stderr)
  976. print(
  977. f"{p}: error: the following arguments are required: " f"{required}",
  978. file=sys.stderr,
  979. )
  980. sys.exit(2)
  981. @classmethod
  982. def check_task_requirements(
  983. cls,
  984. dataset: Union[AbsDataset, IterableESPnetDataset],
  985. allow_variable_data_keys: bool,
  986. train: bool,
  987. inference: bool = False,
  988. ) -> None:
  989. """Check if the dataset satisfy the requirement of current Task"""
  990. assert check_argument_types()
  991. mes = (
  992. f"If you intend to use an additional input, modify "
  993. f'"{cls.__name__}.required_data_names()" or '
  994. f'"{cls.__name__}.optional_data_names()". '
  995. f"Otherwise you need to set --allow_variable_data_keys true "
  996. )
  997. for k in cls.required_data_names(train, inference):
  998. if not dataset.has_name(k):
  999. raise RuntimeError(
  1000. f'"{cls.required_data_names(train, inference)}" are required for'
  1001. f' {cls.__name__}. but "{dataset.names()}" are input.\n{mes}'
  1002. )
  1003. if not allow_variable_data_keys:
  1004. task_keys = cls.required_data_names(
  1005. train, inference
  1006. ) + cls.optional_data_names(train, inference)
  1007. for k in dataset.names():
  1008. if k not in task_keys:
  1009. raise RuntimeError(
  1010. f"The data-name must be one of {task_keys} "
  1011. f'for {cls.__name__}: "{k}" is not allowed.\n{mes}'
  1012. )
  1013. @classmethod
  1014. def print_config(cls, file=sys.stdout) -> None:
  1015. assert check_argument_types()
  1016. # Shows the config: e.g. python train.py asr --print_config
  1017. config = cls.get_default_config()
  1018. file.write(yaml_no_alias_safe_dump(config, indent=4, sort_keys=False))
  1019. @classmethod
  1020. def main(cls, args: argparse.Namespace = None, cmd: Sequence[str] = None):
  1021. assert check_argument_types()
  1022. print(get_commandline_args(), file=sys.stderr)
  1023. if args is None:
  1024. parser = cls.get_parser()
  1025. args = parser.parse_args(cmd)
  1026. args.version = __version__
  1027. if args.pretrain_path is not None:
  1028. raise RuntimeError("--pretrain_path is deprecated. Use --init_param")
  1029. if args.print_config:
  1030. cls.print_config()
  1031. sys.exit(0)
  1032. cls.check_required_command_args(args)
  1033. if not args.distributed or not args.multiprocessing_distributed:
  1034. cls.main_worker(args)
  1035. else:
  1036. assert args.ngpu > 1
  1037. cls.main_worker(args)
  1038. @classmethod
  1039. def run(cls):
  1040. assert hasattr(cls, "finetune_args")
  1041. args = cls.finetune_args
  1042. args.train_shape_file = None
  1043. if args.distributed:
  1044. args.simple_ddp = True
  1045. else:
  1046. args.simple_ddp = False
  1047. args.ngpu = 1
  1048. args.use_pai = False
  1049. args.batch_type = "length"
  1050. args.oss_bucket = None
  1051. args.input_size = None
  1052. cls.main_worker(args)
  1053. @classmethod
  1054. def main_worker(cls, args: argparse.Namespace):
  1055. assert check_argument_types()
  1056. # 0. Init distributed process
  1057. distributed_option = build_dataclass(DistributedOption, args)
  1058. # Setting distributed_option.dist_rank, etc.
  1059. if args.use_pai:
  1060. distributed_option.init_options_pai()
  1061. elif not args.simple_ddp:
  1062. distributed_option.init_options()
  1063. # Invoking torch.distributed.init_process_group
  1064. if args.use_pai:
  1065. distributed_option.init_torch_distributed_pai(args)
  1066. elif not args.simple_ddp:
  1067. distributed_option.init_torch_distributed(args)
  1068. elif args.distributed and args.simple_ddp:
  1069. distributed_option.init_torch_distributed_pai(args)
  1070. args.ngpu = dist.get_world_size()
  1071. if args.dataset_type == "small":
  1072. if args.batch_size is not None:
  1073. args.batch_size = args.batch_size * args.ngpu
  1074. if args.batch_bins is not None:
  1075. args.batch_bins = args.batch_bins * args.ngpu
  1076. if args.train_shape_file is None and args.dataset_type == "small":
  1077. if not args.simple_ddp or distributed_option.dist_rank == 0:
  1078. calc_shape(args.data_dir, args.train_set, args.frontend_conf, args.speech_length_min, args.speech_length_max)
  1079. calc_shape(args.data_dir, args.dev_set, args.frontend_conf, args.speech_length_min, args.speech_length_max)
  1080. if args.simple_ddp:
  1081. dist.barrier()
  1082. args.train_shape_file = [os.path.join(args.data_dir, args.train_set, "speech_shape")]
  1083. args.valid_shape_file = [os.path.join(args.data_dir, args.dev_set, "speech_shape")]
  1084. if args.train_data_file is None and args.dataset_type == "large":
  1085. if not args.simple_ddp or distributed_option.dist_rank == 0:
  1086. generate_data_list(args.data_dir, args.train_set)
  1087. generate_data_list(args.data_dir, args.dev_set)
  1088. if args.simple_ddp:
  1089. dist.barrier()
  1090. args.train_data_file = os.path.join(args.data_dir, args.train_set, "data.list")
  1091. args.valid_data_file = os.path.join(args.data_dir, args.dev_set, "data.list")
  1092. # NOTE(kamo): Don't use logging before invoking logging.basicConfig()
  1093. if not distributed_option.distributed or distributed_option.dist_rank == 0:
  1094. if not distributed_option.distributed:
  1095. _rank = ""
  1096. else:
  1097. _rank = (
  1098. f":{distributed_option.dist_rank}/"
  1099. f"{distributed_option.dist_world_size}"
  1100. )
  1101. # NOTE(kamo):
  1102. # logging.basicConfig() is invoked in main_worker() instead of main()
  1103. # because it can be invoked only once in a process.
  1104. # FIXME(kamo): Should we use logging.getLogger()?
  1105. logging.basicConfig(
  1106. level=args.log_level,
  1107. format=f"[{os.uname()[1].split('.')[0]}]"
  1108. f" %(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
  1109. )
  1110. else:
  1111. # Suppress logging if RANK != 0
  1112. logging.basicConfig(
  1113. level="ERROR",
  1114. format=f"[{os.uname()[1].split('.')[0]}]"
  1115. f" %(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
  1116. )
  1117. logging.info("world size: {}, rank: {}, local_rank: {}".format(distributed_option.dist_world_size,
  1118. distributed_option.dist_rank,
  1119. distributed_option.local_rank))
  1120. # 1. Set random-seed
  1121. set_all_random_seed(args.seed)
  1122. torch.backends.cudnn.enabled = args.cudnn_enabled
  1123. torch.backends.cudnn.benchmark = args.cudnn_benchmark
  1124. torch.backends.cudnn.deterministic = args.cudnn_deterministic
  1125. if args.detect_anomaly:
  1126. logging.info("Invoking torch.autograd.set_detect_anomaly(True)")
  1127. torch.autograd.set_detect_anomaly(args.detect_anomaly)
  1128. # 2. Build model
  1129. model = cls.build_model(args=args)
  1130. if not isinstance(model, AbsESPnetModel):
  1131. raise RuntimeError(
  1132. f"model must inherit {AbsESPnetModel.__name__}, but got {type(model)}"
  1133. )
  1134. model = model.to(
  1135. dtype=getattr(torch, args.train_dtype),
  1136. device="cuda" if args.ngpu > 0 else "cpu",
  1137. )
  1138. for t in args.freeze_param:
  1139. for k, p in model.named_parameters():
  1140. if k.startswith(t + ".") or k == t:
  1141. logging.info(f"Setting {k}.requires_grad = False")
  1142. p.requires_grad = False
  1143. # 3. Build optimizer
  1144. optimizers = cls.build_optimizers(args, model=model)
  1145. # 4. Build schedulers
  1146. schedulers = []
  1147. for i, optim in enumerate(optimizers, 1):
  1148. suf = "" if i == 1 else str(i)
  1149. name = getattr(args, f"scheduler{suf}")
  1150. conf = getattr(args, f"scheduler{suf}_conf")
  1151. if name is not None:
  1152. cls_ = scheduler_classes.get(name)
  1153. if cls_ is None:
  1154. raise ValueError(
  1155. f"must be one of {list(scheduler_classes)}: {name}"
  1156. )
  1157. scheduler = cls_(optim, **conf)
  1158. else:
  1159. scheduler = None
  1160. schedulers.append(scheduler)
  1161. logging.info(pytorch_cudnn_version())
  1162. logging.info(model_summary(model))
  1163. for i, (o, s) in enumerate(zip(optimizers, schedulers), 1):
  1164. suf = "" if i == 1 else str(i)
  1165. logging.info(f"Optimizer{suf}:\n{o}")
  1166. logging.info(f"Scheduler{suf}: {s}")
  1167. # 5. Dump "args" to config.yaml
  1168. # NOTE(kamo): "args" should be saved after object-buildings are done
  1169. # because they are allowed to modify "args".
  1170. output_dir = Path(args.output_dir)
  1171. if not distributed_option.distributed or distributed_option.dist_rank == 0:
  1172. output_dir.mkdir(parents=True, exist_ok=True)
  1173. with (output_dir / "config.yaml").open("w", encoding="utf-8") as f:
  1174. logging.info(
  1175. f'Saving the configuration in {output_dir / "config.yaml"}'
  1176. )
  1177. if args.use_pai:
  1178. buffer = BytesIO()
  1179. torch.save({"config": vars(args)}, buffer)
  1180. args.oss_bucket.put_object(os.path.join(args.output_dir, "config.dict"), buffer.getvalue())
  1181. else:
  1182. yaml_no_alias_safe_dump(vars(args), f, indent=4, sort_keys=False)
  1183. if args.dry_run:
  1184. pass
  1185. else:
  1186. logging.info("Training args: {}".format(args))
  1187. # 6. Loads pre-trained model
  1188. for p in args.init_param:
  1189. logging.info(f"Loading pretrained params from {p}")
  1190. load_pretrained_model(
  1191. model=model,
  1192. init_param=p,
  1193. ignore_init_mismatch=args.ignore_init_mismatch,
  1194. # NOTE(kamo): "cuda" for torch.load always indicates cuda:0
  1195. # in PyTorch<=1.4
  1196. map_location=f"cuda:{torch.cuda.current_device()}"
  1197. if args.ngpu > 0
  1198. else "cpu",
  1199. oss_bucket=args.oss_bucket,
  1200. )
  1201. # 7. Build iterator factories
  1202. if args.dataset_type == "large":
  1203. from funasr.datasets.large_datasets.build_dataloader import ArkDataLoader
  1204. train_iter_factory = ArkDataLoader(args.train_data_file, args.token_list, args.dataset_conf,
  1205. seg_dict_file=args.seg_dict_file if hasattr(args,
  1206. "seg_dict_file") else None,
  1207. mode="train")
  1208. valid_iter_factory = ArkDataLoader(args.valid_data_file, args.token_list, args.dataset_conf,
  1209. seg_dict_file=args.seg_dict_file if hasattr(args,
  1210. "seg_dict_file") else None,
  1211. mode="eval")
  1212. elif args.dataset_type == "small":
  1213. train_iter_factory = cls.build_iter_factory(
  1214. args=args,
  1215. distributed_option=distributed_option,
  1216. mode="train",
  1217. )
  1218. valid_iter_factory = cls.build_iter_factory(
  1219. args=args,
  1220. distributed_option=distributed_option,
  1221. mode="valid",
  1222. )
  1223. else:
  1224. raise ValueError(f"Not supported dataset_type={args.dataset_type}")
  1225. if args.scheduler == "tri_stage":
  1226. for scheduler in schedulers:
  1227. scheduler.init_tri_stage_scheudler(max_update=args.max_update)
  1228. # 8. Start training
  1229. if args.use_wandb:
  1230. if wandb is None:
  1231. raise RuntimeError("Please install wandb")
  1232. try:
  1233. wandb.login()
  1234. except wandb.errors.UsageError:
  1235. logging.info("wandb not configured! run `wandb login` to enable")
  1236. args.use_wandb = False
  1237. if args.use_wandb:
  1238. if (
  1239. not distributed_option.distributed
  1240. or distributed_option.dist_rank == 0
  1241. ):
  1242. if args.wandb_project is None:
  1243. project = "FunASR_" + cls.__name__
  1244. else:
  1245. project = args.wandb_project
  1246. if args.wandb_name is None:
  1247. name = str(Path(".").resolve()).replace("/", "_")
  1248. else:
  1249. name = args.wandb_name
  1250. wandb.init(
  1251. entity=args.wandb_entity,
  1252. project=project,
  1253. name=name,
  1254. dir=output_dir,
  1255. id=args.wandb_id,
  1256. resume="allow",
  1257. )
  1258. wandb.config.update(args)
  1259. else:
  1260. # wandb also supports grouping for distributed training,
  1261. # but we only logs aggregated data,
  1262. # so it's enough to perform on rank0 node.
  1263. args.use_wandb = False
  1264. # Don't give args to trainer.run() directly!!!
  1265. # Instead of it, define "Options" object and build here.
  1266. trainer_options = cls.trainer.build_options(args)
  1267. cls.trainer.run(
  1268. model=model,
  1269. optimizers=optimizers,
  1270. schedulers=schedulers,
  1271. train_iter_factory=train_iter_factory,
  1272. valid_iter_factory=valid_iter_factory,
  1273. trainer_options=trainer_options,
  1274. distributed_option=distributed_option,
  1275. )
  1276. if args.use_wandb and wandb.run:
  1277. wandb.finish()
  1278. @classmethod
  1279. def build_iter_options(
  1280. cls,
  1281. args: argparse.Namespace,
  1282. distributed_option: DistributedOption,
  1283. mode: str,
  1284. ):
  1285. if mode == "train":
  1286. preprocess_fn = cls.build_preprocess_fn(args, train=True)
  1287. collate_fn = cls.build_collate_fn(args, train=True)
  1288. data_path_and_name_and_type = args.train_data_path_and_name_and_type
  1289. shape_files = args.train_shape_file
  1290. batch_size = args.batch_size
  1291. batch_bins = args.batch_bins
  1292. batch_type = args.batch_type
  1293. max_cache_size = args.max_cache_size
  1294. max_cache_fd = args.max_cache_fd
  1295. distributed = distributed_option.distributed
  1296. num_batches = None
  1297. num_iters_per_epoch = args.num_iters_per_epoch
  1298. train = True
  1299. elif mode == "valid":
  1300. preprocess_fn = cls.build_preprocess_fn(args, train=False)
  1301. collate_fn = cls.build_collate_fn(args, train=False)
  1302. data_path_and_name_and_type = args.valid_data_path_and_name_and_type
  1303. shape_files = args.valid_shape_file
  1304. if args.valid_batch_type is None:
  1305. batch_type = args.batch_type
  1306. else:
  1307. batch_type = args.valid_batch_type
  1308. if args.valid_batch_size is None:
  1309. batch_size = args.batch_size
  1310. else:
  1311. batch_size = args.valid_batch_size
  1312. if args.valid_batch_bins is None:
  1313. batch_bins = args.batch_bins
  1314. else:
  1315. batch_bins = args.valid_batch_bins
  1316. if args.valid_max_cache_size is None:
  1317. # Cache 5% of maximum size for validation loader
  1318. max_cache_size = 0.05 * args.max_cache_size
  1319. else:
  1320. max_cache_size = args.valid_max_cache_size
  1321. max_cache_fd = args.max_cache_fd
  1322. distributed = distributed_option.distributed
  1323. num_batches = None
  1324. num_iters_per_epoch = None
  1325. train = False
  1326. else:
  1327. raise NotImplementedError(f"mode={mode}")
  1328. return IteratorOptions(
  1329. preprocess_fn=preprocess_fn,
  1330. collate_fn=collate_fn,
  1331. data_path_and_name_and_type=data_path_and_name_and_type,
  1332. shape_files=shape_files,
  1333. batch_type=batch_type,
  1334. batch_size=batch_size,
  1335. batch_bins=batch_bins,
  1336. num_batches=num_batches,
  1337. max_cache_size=max_cache_size,
  1338. max_cache_fd=max_cache_fd,
  1339. distributed=distributed,
  1340. num_iters_per_epoch=num_iters_per_epoch,
  1341. train=train,
  1342. )
  1343. @classmethod
  1344. def build_iter_factory(
  1345. cls,
  1346. args: argparse.Namespace,
  1347. distributed_option: DistributedOption,
  1348. mode: str,
  1349. kwargs: dict = None,
  1350. ) -> AbsIterFactory:
  1351. """Build a factory object of mini-batch iterator.
  1352. This object is invoked at every epochs to build the iterator for each epoch
  1353. as following:
  1354. >>> iter_factory = cls.build_iter_factory(...)
  1355. >>> for epoch in range(1, max_epoch):
  1356. ... for keys, batch in iter_fatory.build_iter(epoch):
  1357. ... model(**batch)
  1358. The mini-batches for each epochs are fully controlled by this class.
  1359. Note that the random seed used for shuffling is decided as "seed + epoch" and
  1360. the generated mini-batches can be reproduces when resuming.
  1361. Note that the definition of "epoch" doesn't always indicate
  1362. to run out of the whole training corpus.
  1363. "--num_iters_per_epoch" option restricts the number of iterations for each epoch
  1364. and the rest of samples for the originally epoch are left for the next epoch.
  1365. e.g. If The number of mini-batches equals to 4, the following two are same:
  1366. - 1 epoch without "--num_iters_per_epoch"
  1367. - 4 epoch with "--num_iters_per_epoch" == 4
  1368. """
  1369. assert check_argument_types()
  1370. iter_options = cls.build_iter_options(args, distributed_option, mode)
  1371. # Overwrite iter_options if any kwargs is given
  1372. if kwargs is not None:
  1373. for k, v in kwargs.items():
  1374. setattr(iter_options, k, v)
  1375. if args.iterator_type == "sequence":
  1376. return cls.build_sequence_iter_factory(
  1377. args=args,
  1378. iter_options=iter_options,
  1379. mode=mode,
  1380. )
  1381. elif args.iterator_type == "chunk":
  1382. return cls.build_chunk_iter_factory(
  1383. args=args,
  1384. iter_options=iter_options,
  1385. mode=mode,
  1386. )
  1387. elif args.iterator_type == "task":
  1388. return cls.build_task_iter_factory(
  1389. args=args,
  1390. iter_options=iter_options,
  1391. mode=mode,
  1392. )
  1393. else:
  1394. raise RuntimeError(f"Not supported: iterator_type={args.iterator_type}")
  1395. @classmethod
  1396. def build_sequence_iter_factory(
  1397. cls, args: argparse.Namespace, iter_options: IteratorOptions, mode: str
  1398. ) -> AbsIterFactory:
  1399. assert check_argument_types()
  1400. dataset = ESPnetDataset(
  1401. iter_options.data_path_and_name_and_type,
  1402. float_dtype=args.train_dtype,
  1403. preprocess=iter_options.preprocess_fn,
  1404. max_cache_size=iter_options.max_cache_size,
  1405. max_cache_fd=iter_options.max_cache_fd,
  1406. )
  1407. cls.check_task_requirements(
  1408. dataset, args.allow_variable_data_keys, train=iter_options.train
  1409. )
  1410. if Path(
  1411. Path(iter_options.data_path_and_name_and_type[0][0]).parent, "utt2category"
  1412. ).exists():
  1413. utt2category_file = str(
  1414. Path(
  1415. Path(iter_options.data_path_and_name_and_type[0][0]).parent,
  1416. "utt2category",
  1417. )
  1418. )
  1419. else:
  1420. utt2category_file = None
  1421. batch_sampler = build_batch_sampler(
  1422. type=iter_options.batch_type,
  1423. shape_files=iter_options.shape_files,
  1424. fold_lengths=args.fold_length,
  1425. batch_size=iter_options.batch_size,
  1426. batch_bins=iter_options.batch_bins,
  1427. sort_in_batch=args.sort_in_batch,
  1428. sort_batch=args.sort_batch,
  1429. drop_last=False,
  1430. min_batch_size=torch.distributed.get_world_size()
  1431. if iter_options.distributed
  1432. else 1,
  1433. utt2category_file=utt2category_file,
  1434. )
  1435. batches = list(batch_sampler)
  1436. if iter_options.num_batches is not None:
  1437. batches = batches[: iter_options.num_batches]
  1438. bs_list = [len(batch) for batch in batches]
  1439. logging.info(f"[{mode}] dataset:\n{dataset}")
  1440. logging.info(f"[{mode}] Batch sampler: {batch_sampler}")
  1441. logging.info(
  1442. f"[{mode}] mini-batch sizes summary: N-batch={len(bs_list)}, "
  1443. f"mean={np.mean(bs_list):.1f}, min={np.min(bs_list)}, max={np.max(bs_list)}"
  1444. )
  1445. if args.scheduler == "tri_stage" and mode == "train":
  1446. args.max_update = len(bs_list) * args.max_epoch
  1447. logging.info("Max update: {}".format(args.max_update))
  1448. if iter_options.distributed:
  1449. world_size = torch.distributed.get_world_size()
  1450. rank = torch.distributed.get_rank()
  1451. for batch in batches:
  1452. if len(batch) < world_size:
  1453. raise RuntimeError(
  1454. f"The batch-size must be equal or more than world_size: "
  1455. f"{len(batch)} < {world_size}"
  1456. )
  1457. batches = [batch[rank::world_size] for batch in batches]
  1458. return SequenceIterFactory(
  1459. dataset=dataset,
  1460. batches=batches,
  1461. seed=args.seed,
  1462. num_iters_per_epoch=iter_options.num_iters_per_epoch,
  1463. shuffle=iter_options.train,
  1464. num_workers=args.num_workers,
  1465. collate_fn=iter_options.collate_fn,
  1466. pin_memory=args.ngpu > 0,
  1467. )
  1468. @classmethod
  1469. def build_chunk_iter_factory(
  1470. cls,
  1471. args: argparse.Namespace,
  1472. iter_options: IteratorOptions,
  1473. mode: str,
  1474. ) -> AbsIterFactory:
  1475. assert check_argument_types()
  1476. dataset = ESPnetDataset(
  1477. iter_options.data_path_and_name_and_type,
  1478. float_dtype=args.train_dtype,
  1479. preprocess=iter_options.preprocess_fn,
  1480. max_cache_size=iter_options.max_cache_size,
  1481. max_cache_fd=iter_options.max_cache_fd,
  1482. )
  1483. cls.check_task_requirements(
  1484. dataset, args.allow_variable_data_keys, train=iter_options.train
  1485. )
  1486. if len(iter_options.shape_files) == 0:
  1487. key_file = iter_options.data_path_and_name_and_type[0][0]
  1488. else:
  1489. key_file = iter_options.shape_files[0]
  1490. batch_sampler = UnsortedBatchSampler(batch_size=1, key_file=key_file)
  1491. batches = list(batch_sampler)
  1492. if iter_options.num_batches is not None:
  1493. batches = batches[: iter_options.num_batches]
  1494. logging.info(f"[{mode}] dataset:\n{dataset}")
  1495. if iter_options.distributed:
  1496. world_size = torch.distributed.get_world_size()
  1497. rank = torch.distributed.get_rank()
  1498. if len(batches) < world_size:
  1499. raise RuntimeError("Number of samples is smaller than world_size")
  1500. if iter_options.batch_size < world_size:
  1501. raise RuntimeError("batch_size must be equal or more than world_size")
  1502. if rank < iter_options.batch_size % world_size:
  1503. batch_size = iter_options.batch_size // world_size + 1
  1504. else:
  1505. batch_size = iter_options.batch_size // world_size
  1506. num_cache_chunks = args.num_cache_chunks // world_size
  1507. # NOTE(kamo): Split whole corpus by sample numbers without considering
  1508. # each of the lengths, therefore the number of iteration counts are not
  1509. # always equal to each other and the iterations are limitted
  1510. # by the fewest iterations.
  1511. # i.e. the samples over the counts are discarded.
  1512. batches = batches[rank::world_size]
  1513. else:
  1514. batch_size = iter_options.batch_size
  1515. num_cache_chunks = args.num_cache_chunks
  1516. return ChunkIterFactory(
  1517. dataset=dataset,
  1518. batches=batches,
  1519. seed=args.seed,
  1520. batch_size=batch_size,
  1521. # For chunk iterator,
  1522. # --num_iters_per_epoch doesn't indicate the number of iterations,
  1523. # but indicates the number of samples.
  1524. num_samples_per_epoch=iter_options.num_iters_per_epoch,
  1525. shuffle=iter_options.train,
  1526. num_workers=args.num_workers,
  1527. collate_fn=iter_options.collate_fn,
  1528. pin_memory=args.ngpu > 0,
  1529. chunk_length=args.chunk_length,
  1530. chunk_shift_ratio=args.chunk_shift_ratio,
  1531. num_cache_chunks=num_cache_chunks,
  1532. )
  1533. # NOTE(kamo): Not abstract class
  1534. @classmethod
  1535. def build_task_iter_factory(
  1536. cls,
  1537. args: argparse.Namespace,
  1538. iter_options: IteratorOptions,
  1539. mode: str,
  1540. ) -> AbsIterFactory:
  1541. """Build task specific iterator factory
  1542. Example:
  1543. >>> class YourTask(AbsTask):
  1544. ... @classmethod
  1545. ... def add_task_arguments(cls, parser: argparse.ArgumentParser):
  1546. ... parser.set_defaults(iterator_type="task")
  1547. ...
  1548. ... @classmethod
  1549. ... def build_task_iter_factory(
  1550. ... cls,
  1551. ... args: argparse.Namespace,
  1552. ... iter_options: IteratorOptions,
  1553. ... mode: str,
  1554. ... ):
  1555. ... return FooIterFactory(...)
  1556. ...
  1557. ... @classmethod
  1558. ... def build_iter_options(
  1559. .... args: argparse.Namespace,
  1560. ... distributed_option: DistributedOption,
  1561. ... mode: str
  1562. ... ):
  1563. ... # if you need to customize options object
  1564. """
  1565. raise NotImplementedError
  1566. @classmethod
  1567. def build_multiple_iter_factory(
  1568. cls, args: argparse.Namespace, distributed_option: DistributedOption, mode: str
  1569. ):
  1570. assert check_argument_types()
  1571. iter_options = cls.build_iter_options(args, distributed_option, mode)
  1572. assert len(iter_options.data_path_and_name_and_type) > 0, len(
  1573. iter_options.data_path_and_name_and_type
  1574. )
  1575. # 1. Sanity check
  1576. num_splits = None
  1577. for path in [
  1578. path for path, _, _ in iter_options.data_path_and_name_and_type
  1579. ] + list(iter_options.shape_files):
  1580. if not Path(path).is_dir():
  1581. raise RuntimeError(f"{path} is not a directory")
  1582. p = Path(path) / "num_splits"
  1583. if not p.exists():
  1584. raise FileNotFoundError(f"{p} is not found")
  1585. with p.open() as f:
  1586. _num_splits = int(f.read())
  1587. if num_splits is not None and num_splits != _num_splits:
  1588. raise RuntimeError(
  1589. f"Number of splits are mismathed: "
  1590. f"{iter_options.data_path_and_name_and_type[0][0]} and {path}"
  1591. )
  1592. num_splits = _num_splits
  1593. for i in range(num_splits):
  1594. p = Path(path) / f"split.{i}"
  1595. if not p.exists():
  1596. raise FileNotFoundError(f"{p} is not found")
  1597. # 2. Create functions to build an iter factory for each splits
  1598. data_path_and_name_and_type_list = [
  1599. [
  1600. (str(Path(p) / f"split.{i}"), n, t)
  1601. for p, n, t in iter_options.data_path_and_name_and_type
  1602. ]
  1603. for i in range(num_splits)
  1604. ]
  1605. shape_files_list = [
  1606. [str(Path(s) / f"split.{i}") for s in iter_options.shape_files]
  1607. for i in range(num_splits)
  1608. ]
  1609. num_iters_per_epoch_list = [
  1610. (iter_options.num_iters_per_epoch + i) // num_splits
  1611. if iter_options.num_iters_per_epoch is not None
  1612. else None
  1613. for i in range(num_splits)
  1614. ]
  1615. max_cache_size = iter_options.max_cache_size / num_splits
  1616. # Note that iter-factories are built for each epoch at runtime lazily.
  1617. build_funcs = [
  1618. functools.partial(
  1619. cls.build_iter_factory,
  1620. args,
  1621. distributed_option,
  1622. mode,
  1623. kwargs=dict(
  1624. data_path_and_name_and_type=_data_path_and_name_and_type,
  1625. shape_files=_shape_files,
  1626. num_iters_per_epoch=_num_iters_per_epoch,
  1627. max_cache_size=max_cache_size,
  1628. ),
  1629. )
  1630. for (
  1631. _data_path_and_name_and_type,
  1632. _shape_files,
  1633. _num_iters_per_epoch,
  1634. ) in zip(
  1635. data_path_and_name_and_type_list,
  1636. shape_files_list,
  1637. num_iters_per_epoch_list,
  1638. )
  1639. ]
  1640. # 3. Build MultipleIterFactory
  1641. return MultipleIterFactory(
  1642. build_funcs=build_funcs, shuffle=iter_options.train, seed=args.seed
  1643. )
  1644. @classmethod
  1645. def build_streaming_iterator(
  1646. cls,
  1647. data_path_and_name_and_type,
  1648. preprocess_fn,
  1649. collate_fn,
  1650. key_file: str = None,
  1651. batch_size: int = 1,
  1652. dtype: str = np.float32,
  1653. num_workers: int = 1,
  1654. allow_variable_data_keys: bool = False,
  1655. ngpu: int = 0,
  1656. inference: bool = False,
  1657. ) -> DataLoader:
  1658. """Build DataLoader using iterable dataset"""
  1659. assert check_argument_types()
  1660. # For backward compatibility for pytorch DataLoader
  1661. if collate_fn is not None:
  1662. kwargs = dict(collate_fn=collate_fn)
  1663. else:
  1664. kwargs = {}
  1665. dataset = IterableESPnetDataset(
  1666. data_path_and_name_and_type,
  1667. float_dtype=dtype,
  1668. preprocess=preprocess_fn,
  1669. key_file=key_file,
  1670. )
  1671. if dataset.apply_utt2category:
  1672. kwargs.update(batch_size=1)
  1673. else:
  1674. kwargs.update(batch_size=batch_size)
  1675. cls.check_task_requirements(
  1676. dataset, allow_variable_data_keys, train=False, inference=inference
  1677. )
  1678. return DataLoader(
  1679. dataset=dataset,
  1680. pin_memory=ngpu > 0,
  1681. num_workers=num_workers,
  1682. **kwargs,
  1683. )
  1684. # ~~~~~~~~~ The methods below are mainly used for inference ~~~~~~~~~
  1685. @classmethod
  1686. def build_model_from_file(
  1687. cls,
  1688. config_file: Union[Path, str] = None,
  1689. model_file: Union[Path, str] = None,
  1690. cmvn_file: Union[Path, str] = None,
  1691. device: str = "cpu",
  1692. ) -> Tuple[AbsESPnetModel, argparse.Namespace]:
  1693. """Build model from the files.
  1694. This method is used for inference or fine-tuning.
  1695. Args:
  1696. config_file: The yaml file saved when training.
  1697. model_file: The model file saved when training.
  1698. device: Device type, "cpu", "cuda", or "cuda:N".
  1699. """
  1700. assert check_argument_types()
  1701. if config_file is None:
  1702. assert model_file is not None, (
  1703. "The argument 'model_file' must be provided "
  1704. "if the argument 'config_file' is not specified."
  1705. )
  1706. config_file = Path(model_file).parent / "config.yaml"
  1707. else:
  1708. config_file = Path(config_file)
  1709. with config_file.open("r", encoding="utf-8") as f:
  1710. args = yaml.safe_load(f)
  1711. if cmvn_file is not None:
  1712. args["cmvn_file"] = cmvn_file
  1713. args = argparse.Namespace(**args)
  1714. model = cls.build_model(args)
  1715. if not isinstance(model, AbsESPnetModel):
  1716. raise RuntimeError(
  1717. f"model must inherit {AbsESPnetModel.__name__}, but got {type(model)}"
  1718. )
  1719. model.to(device)
  1720. if model_file is not None:
  1721. if device == "cuda":
  1722. # NOTE(kamo): "cuda" for torch.load always indicates cuda:0
  1723. # in PyTorch<=1.4
  1724. device = f"cuda:{torch.cuda.current_device()}"
  1725. model.load_state_dict(torch.load(model_file, map_location=device))
  1726. model.to(device)
  1727. return model, args