sv.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. """
  2. Author: Speech Lab, Alibaba Group, China
  3. """
  4. import argparse
  5. import logging
  6. import os
  7. from pathlib import Path
  8. from typing import Callable
  9. from typing import Collection
  10. from typing import Dict
  11. from typing import List
  12. from typing import Optional
  13. from typing import Tuple
  14. from typing import Union
  15. import numpy as np
  16. import torch
  17. import yaml
  18. from funasr.datasets.collate_fn import CommonCollateFn
  19. from funasr.datasets.preprocessor import CommonPreprocessor
  20. from funasr.layers.abs_normalize import AbsNormalize
  21. from funasr.layers.global_mvn import GlobalMVN
  22. from funasr.layers.utterance_mvn import UtteranceMVN
  23. from funasr.models.e2e_asr import ASRModel
  24. from funasr.models.decoder.abs_decoder import AbsDecoder
  25. from funasr.models.encoder.abs_encoder import AbsEncoder
  26. from funasr.models.encoder.rnn_encoder import RNNEncoder
  27. from funasr.models.encoder.resnet34_encoder import ResNet34, ResNet34_SP_L2Reg
  28. from funasr.models.pooling.statistic_pooling import StatisticPooling
  29. from funasr.models.decoder.sv_decoder import DenseDecoder
  30. from funasr.models.e2e_sv import ESPnetSVModel
  31. from funasr.models.frontend.abs_frontend import AbsFrontend
  32. from funasr.models.frontend.default import DefaultFrontend
  33. from funasr.models.frontend.fused import FusedFrontends
  34. from funasr.models.frontend.s3prl import S3prlFrontend
  35. from funasr.models.frontend.windowing import SlidingWindow
  36. from funasr.models.postencoder.abs_postencoder import AbsPostEncoder
  37. from funasr.models.postencoder.hugging_face_transformers_postencoder import (
  38. HuggingFaceTransformersPostEncoder, # noqa: H301
  39. )
  40. from funasr.models.preencoder.abs_preencoder import AbsPreEncoder
  41. from funasr.models.preencoder.linear import LinearProjection
  42. from funasr.models.preencoder.sinc import LightweightSincConvs
  43. from funasr.models.specaug.abs_specaug import AbsSpecAug
  44. from funasr.models.specaug.specaug import SpecAug
  45. from funasr.tasks.abs_task import AbsTask
  46. from funasr.torch_utils.initialize import initialize
  47. from funasr.models.base_model import FunASRModel
  48. from funasr.train.class_choices import ClassChoices
  49. from funasr.train.trainer import Trainer
  50. from funasr.utils.types import float_or_none
  51. from funasr.utils.types import int_or_none
  52. from funasr.utils.types import str2bool
  53. from funasr.utils.types import str_or_none
  54. from funasr.models.frontend.wav_frontend import WavFrontend
  55. frontend_choices = ClassChoices(
  56. name="frontend",
  57. classes=dict(
  58. default=DefaultFrontend,
  59. sliding_window=SlidingWindow,
  60. s3prl=S3prlFrontend,
  61. fused=FusedFrontends,
  62. wav_frontend=WavFrontend,
  63. ),
  64. type_check=AbsFrontend,
  65. default="default",
  66. )
  67. specaug_choices = ClassChoices(
  68. name="specaug",
  69. classes=dict(
  70. specaug=SpecAug,
  71. ),
  72. type_check=AbsSpecAug,
  73. default=None,
  74. optional=True,
  75. )
  76. normalize_choices = ClassChoices(
  77. "normalize",
  78. classes=dict(
  79. global_mvn=GlobalMVN,
  80. utterance_mvn=UtteranceMVN,
  81. ),
  82. type_check=AbsNormalize,
  83. default=None,
  84. optional=True,
  85. )
  86. model_choices = ClassChoices(
  87. "model",
  88. classes=dict(
  89. espnet=ESPnetSVModel,
  90. ),
  91. type_check=FunASRModel,
  92. default="espnet",
  93. )
  94. preencoder_choices = ClassChoices(
  95. name="preencoder",
  96. classes=dict(
  97. sinc=LightweightSincConvs,
  98. linear=LinearProjection,
  99. ),
  100. type_check=AbsPreEncoder,
  101. default=None,
  102. optional=True,
  103. )
  104. encoder_choices = ClassChoices(
  105. "encoder",
  106. classes=dict(
  107. resnet34=ResNet34,
  108. resnet34_sp_l2reg=ResNet34_SP_L2Reg,
  109. rnn=RNNEncoder,
  110. ),
  111. type_check=AbsEncoder,
  112. default="resnet34",
  113. )
  114. postencoder_choices = ClassChoices(
  115. name="postencoder",
  116. classes=dict(
  117. hugging_face_transformers=HuggingFaceTransformersPostEncoder,
  118. ),
  119. type_check=AbsPostEncoder,
  120. default=None,
  121. optional=True,
  122. )
  123. pooling_choices = ClassChoices(
  124. name="pooling_type",
  125. classes=dict(
  126. statistic=StatisticPooling,
  127. ),
  128. type_check=torch.nn.Module,
  129. default="statistic",
  130. )
  131. decoder_choices = ClassChoices(
  132. "decoder",
  133. classes=dict(
  134. dense=DenseDecoder,
  135. ),
  136. type_check=AbsDecoder,
  137. default="dense",
  138. )
  139. class SVTask(AbsTask):
  140. # If you need more than one optimizers, change this value
  141. num_optimizers: int = 1
  142. # Add variable objects configurations
  143. class_choices_list = [
  144. # --frontend and --frontend_conf
  145. frontend_choices,
  146. # --specaug and --specaug_conf
  147. specaug_choices,
  148. # --normalize and --normalize_conf
  149. normalize_choices,
  150. # --model and --model_conf
  151. model_choices,
  152. # --preencoder and --preencoder_conf
  153. preencoder_choices,
  154. # --encoder and --encoder_conf
  155. encoder_choices,
  156. # --postencoder and --postencoder_conf
  157. postencoder_choices,
  158. # --pooling and --pooling_conf
  159. pooling_choices,
  160. # --decoder and --decoder_conf
  161. decoder_choices,
  162. ]
  163. # If you need to modify train() or eval() procedures, change Trainer class here
  164. trainer = Trainer
  165. @classmethod
  166. def add_task_arguments(cls, parser: argparse.ArgumentParser):
  167. group = parser.add_argument_group(description="Task related")
  168. # NOTE(kamo): add_arguments(..., required=True) can't be used
  169. # to provide --print_config mode. Instead of it, do as
  170. required = parser.get_default("required")
  171. required += ["token_list"]
  172. group.add_argument(
  173. "--token_list",
  174. type=str_or_none,
  175. default=None,
  176. help="A text mapping int-id to speaker name",
  177. )
  178. group.add_argument(
  179. "--init",
  180. type=lambda x: str_or_none(x.lower()),
  181. default=None,
  182. help="The initialization method",
  183. choices=[
  184. "chainer",
  185. "xavier_uniform",
  186. "xavier_normal",
  187. "kaiming_uniform",
  188. "kaiming_normal",
  189. None,
  190. ],
  191. )
  192. group.add_argument(
  193. "--input_size",
  194. type=int_or_none,
  195. default=None,
  196. help="The number of input dimension of the feature",
  197. )
  198. group = parser.add_argument_group(description="Preprocess related")
  199. group.add_argument(
  200. "--use_preprocessor",
  201. type=str2bool,
  202. default=True,
  203. help="Apply preprocessing to data or not",
  204. )
  205. parser.add_argument(
  206. "--cleaner",
  207. type=str_or_none,
  208. choices=[None, "tacotron", "jaconv", "vietnamese"],
  209. default=None,
  210. help="Apply text cleaning",
  211. )
  212. parser.add_argument(
  213. "--speech_volume_normalize",
  214. type=float_or_none,
  215. default=None,
  216. help="Scale the maximum amplitude to the given value.",
  217. )
  218. parser.add_argument(
  219. "--rir_scp",
  220. type=str_or_none,
  221. default=None,
  222. help="The file path of rir scp file.",
  223. )
  224. parser.add_argument(
  225. "--rir_apply_prob",
  226. type=float,
  227. default=1.0,
  228. help="THe probability for applying RIR convolution.",
  229. )
  230. parser.add_argument(
  231. "--noise_scp",
  232. type=str_or_none,
  233. default=None,
  234. help="The file path of noise scp file.",
  235. )
  236. parser.add_argument(
  237. "--noise_apply_prob",
  238. type=float,
  239. default=1.0,
  240. help="The probability applying Noise adding.",
  241. )
  242. parser.add_argument(
  243. "--noise_db_range",
  244. type=str,
  245. default="13_15",
  246. help="The range of noise decibel level.",
  247. )
  248. for class_choices in cls.class_choices_list:
  249. # Append --<name> and --<name>_conf.
  250. # e.g. --encoder and --encoder_conf
  251. class_choices.add_arguments(group)
  252. @classmethod
  253. def build_collate_fn(
  254. cls, args: argparse.Namespace, train: bool
  255. ) -> Callable[
  256. [Collection[Tuple[str, Dict[str, np.ndarray]]]],
  257. Tuple[List[str], Dict[str, torch.Tensor]],
  258. ]:
  259. # NOTE(kamo): int value = 0 is reserved by CTC-blank symbol
  260. return CommonCollateFn(float_pad_value=0.0, int_pad_value=-1)
  261. @classmethod
  262. def build_preprocess_fn(
  263. cls, args: argparse.Namespace, train: bool
  264. ) -> Optional[Callable[[str, Dict[str, np.array]], Dict[str, np.ndarray]]]:
  265. if args.use_preprocessor:
  266. retval = CommonPreprocessor(
  267. train=train,
  268. token_type=None,
  269. token_list=None,
  270. bpemodel=None,
  271. non_linguistic_symbols=None,
  272. text_cleaner=args.cleaner,
  273. g2p_type=None,
  274. # NOTE(kamo): Check attribute existence for backward compatibility
  275. rir_scp=args.rir_scp if hasattr(args, "rir_scp") else None,
  276. rir_apply_prob=args.rir_apply_prob
  277. if hasattr(args, "rir_apply_prob")
  278. else 1.0,
  279. noise_scp=args.noise_scp if hasattr(args, "noise_scp") else None,
  280. noise_apply_prob=args.noise_apply_prob
  281. if hasattr(args, "noise_apply_prob")
  282. else 1.0,
  283. noise_db_range=args.noise_db_range
  284. if hasattr(args, "noise_db_range")
  285. else "13_15",
  286. speech_volume_normalize=args.speech_volume_normalize
  287. if hasattr(args, "rir_scp")
  288. else None,
  289. )
  290. else:
  291. retval = None
  292. return retval
  293. @classmethod
  294. def required_data_names(
  295. cls, train: bool = True, inference: bool = False
  296. ) -> Tuple[str, ...]:
  297. if not inference:
  298. retval = ("speech", "text")
  299. else:
  300. # Recognition mode
  301. retval = ("speech",)
  302. return retval
  303. @classmethod
  304. def optional_data_names(
  305. cls, train: bool = True, inference: bool = False
  306. ) -> Tuple[str, ...]:
  307. retval = ()
  308. if inference:
  309. retval = ("ref_speech",)
  310. return retval
  311. @classmethod
  312. def build_model(cls, args: argparse.Namespace) -> ESPnetSVModel:
  313. if isinstance(args.token_list, str):
  314. with open(args.token_list, encoding="utf-8") as f:
  315. token_list = [line.rstrip() for line in f]
  316. # Overwriting token_list to keep it as "portable".
  317. args.token_list = list(token_list)
  318. elif isinstance(args.token_list, (tuple, list)):
  319. token_list = list(args.token_list)
  320. else:
  321. raise RuntimeError("token_list must be str or list")
  322. vocab_size = len(token_list)
  323. logging.info(f"Speaker number: {vocab_size}")
  324. # 1. frontend
  325. if args.input_size is None:
  326. # Extract features in the model
  327. frontend_class = frontend_choices.get_class(args.frontend)
  328. frontend = frontend_class(**args.frontend_conf)
  329. input_size = frontend.output_size()
  330. else:
  331. # Give features from data-loader
  332. args.frontend = None
  333. args.frontend_conf = {}
  334. frontend = None
  335. input_size = args.input_size
  336. # 2. Data augmentation for spectrogram
  337. if args.specaug is not None:
  338. specaug_class = specaug_choices.get_class(args.specaug)
  339. specaug = specaug_class(**args.specaug_conf)
  340. else:
  341. specaug = None
  342. # 3. Normalization layer
  343. if args.normalize is not None:
  344. normalize_class = normalize_choices.get_class(args.normalize)
  345. normalize = normalize_class(**args.normalize_conf)
  346. else:
  347. normalize = None
  348. # 4. Pre-encoder input block
  349. # NOTE(kan-bayashi): Use getattr to keep the compatibility
  350. if getattr(args, "preencoder", None) is not None:
  351. preencoder_class = preencoder_choices.get_class(args.preencoder)
  352. preencoder = preencoder_class(**args.preencoder_conf)
  353. input_size = preencoder.output_size()
  354. else:
  355. preencoder = None
  356. # 5. Encoder
  357. encoder_class = encoder_choices.get_class(args.encoder)
  358. encoder = encoder_class(input_size=input_size, **args.encoder_conf)
  359. # 6. Post-encoder block
  360. # NOTE(kan-bayashi): Use getattr to keep the compatibility
  361. encoder_output_size = encoder.output_size()
  362. if getattr(args, "postencoder", None) is not None:
  363. postencoder_class = postencoder_choices.get_class(args.postencoder)
  364. postencoder = postencoder_class(
  365. input_size=encoder_output_size, **args.postencoder_conf
  366. )
  367. encoder_output_size = postencoder.output_size()
  368. else:
  369. postencoder = None
  370. # 7. Pooling layer
  371. pooling_class = pooling_choices.get_class(args.pooling_type)
  372. pooling_dim = (2, 3)
  373. eps = 1e-12
  374. if hasattr(args, "pooling_type_conf"):
  375. if "pooling_dim" in args.pooling_type_conf:
  376. pooling_dim = args.pooling_type_conf["pooling_dim"]
  377. if "eps" in args.pooling_type_conf:
  378. eps = args.pooling_type_conf["eps"]
  379. pooling_layer = pooling_class(
  380. pooling_dim=pooling_dim,
  381. eps=eps,
  382. )
  383. if args.pooling_type == "statistic":
  384. encoder_output_size *= 2
  385. # 8. Decoder
  386. decoder_class = decoder_choices.get_class(args.decoder)
  387. decoder = decoder_class(
  388. vocab_size=vocab_size,
  389. encoder_output_size=encoder_output_size,
  390. **args.decoder_conf,
  391. )
  392. # 7. Build model
  393. try:
  394. model_class = model_choices.get_class(args.model)
  395. except AttributeError:
  396. model_class = model_choices.get_class("espnet")
  397. model = model_class(
  398. vocab_size=vocab_size,
  399. token_list=token_list,
  400. frontend=frontend,
  401. specaug=specaug,
  402. normalize=normalize,
  403. preencoder=preencoder,
  404. encoder=encoder,
  405. postencoder=postencoder,
  406. pooling_layer=pooling_layer,
  407. decoder=decoder,
  408. **args.model_conf,
  409. )
  410. # FIXME(kamo): Should be done in model?
  411. # 8. Initialize
  412. if args.init is not None:
  413. initialize(model, args.init)
  414. return model
  415. # ~~~~~~~~~ The methods below are mainly used for inference ~~~~~~~~~
  416. @classmethod
  417. def build_model_from_file(
  418. cls,
  419. config_file: Union[Path, str] = None,
  420. model_file: Union[Path, str] = None,
  421. cmvn_file: Union[Path, str] = None,
  422. device: str = "cpu",
  423. ):
  424. """Build model from the files.
  425. This method is used for inference or fine-tuning.
  426. Args:
  427. config_file: The yaml file saved when training.
  428. model_file: The model file saved when training.
  429. cmvn_file: The cmvn file for front-end
  430. device: Device type, "cpu", "cuda", or "cuda:N".
  431. """
  432. if config_file is None:
  433. assert model_file is not None, (
  434. "The argument 'model_file' must be provided "
  435. "if the argument 'config_file' is not specified."
  436. )
  437. config_file = Path(model_file).parent / "config.yaml"
  438. else:
  439. config_file = Path(config_file)
  440. with config_file.open("r", encoding="utf-8") as f:
  441. args = yaml.safe_load(f)
  442. if cmvn_file is not None:
  443. args["cmvn_file"] = cmvn_file
  444. args = argparse.Namespace(**args)
  445. model = cls.build_model(args)
  446. if not isinstance(model, FunASRModel):
  447. raise RuntimeError(
  448. f"model must inherit {FunASRModel.__name__}, but got {type(model)}"
  449. )
  450. model.to(device)
  451. model_dict = dict()
  452. model_name_pth = None
  453. if model_file is not None:
  454. logging.info("model_file is {}".format(model_file))
  455. if device == "cuda":
  456. device = f"cuda:{torch.cuda.current_device()}"
  457. model_dir = os.path.dirname(model_file)
  458. model_name = os.path.basename(model_file)
  459. if "model.ckpt-" in model_name or ".bin" in model_name:
  460. if ".bin" in model_name:
  461. model_name_pth = os.path.join(model_dir, model_name.replace('.bin', '.pb'))
  462. else:
  463. model_name_pth = os.path.join(model_dir, "{}.pb".format(model_name))
  464. if os.path.exists(model_name_pth):
  465. logging.info("model_file is load from pth: {}".format(model_name_pth))
  466. model_dict = torch.load(model_name_pth, map_location=device)
  467. else:
  468. model_dict = cls.convert_tf2torch(model, model_file)
  469. model.load_state_dict(model_dict)
  470. else:
  471. model_dict = torch.load(model_file, map_location=device)
  472. model.load_state_dict(model_dict)
  473. if model_name_pth is not None and not os.path.exists(model_name_pth):
  474. torch.save(model_dict, model_name_pth)
  475. logging.info("model_file is saved to pth: {}".format(model_name_pth))
  476. return model, args
  477. @classmethod
  478. def convert_tf2torch(
  479. cls,
  480. model,
  481. ckpt,
  482. ):
  483. logging.info("start convert tf model to torch model")
  484. from funasr.modules.streaming_utils.load_fr_tf import load_tf_dict
  485. var_dict_tf = load_tf_dict(ckpt)
  486. var_dict_torch = model.state_dict()
  487. var_dict_torch_update = dict()
  488. # speech encoder
  489. var_dict_torch_update_local = model.encoder.convert_tf2torch(var_dict_tf, var_dict_torch)
  490. var_dict_torch_update.update(var_dict_torch_update_local)
  491. # pooling layer
  492. var_dict_torch_update_local = model.pooling_layer.convert_tf2torch(var_dict_tf, var_dict_torch)
  493. var_dict_torch_update.update(var_dict_torch_update_local)
  494. # decoder
  495. var_dict_torch_update_local = model.decoder.convert_tf2torch(var_dict_tf, var_dict_torch)
  496. var_dict_torch_update.update(var_dict_torch_update_local)
  497. return var_dict_torch_update