abs_task.py 71 KB

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