sv.py 18 KB

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