abs_task.py 71 KB

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