abs_task.py 72 KB

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