data2vec.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import argparse
  2. from typing import Callable
  3. from typing import Collection
  4. from typing import Dict
  5. from typing import List
  6. from typing import Optional
  7. from typing import Tuple
  8. import numpy as np
  9. import torch
  10. from typeguard import check_argument_types
  11. from typeguard import check_return_type
  12. from funasr.datasets.collate_fn import CommonCollateFn
  13. from funasr.datasets.preprocessor import CommonPreprocessor
  14. from funasr.layers.abs_normalize import AbsNormalize
  15. from funasr.layers.global_mvn import GlobalMVN
  16. from funasr.layers.utterance_mvn import UtteranceMVN
  17. from funasr.models.data2vec import Data2VecPretrainModel
  18. from funasr.models.encoder.abs_encoder import AbsEncoder
  19. from funasr.models.encoder.data2vec_encoder import Data2VecEncoder
  20. from funasr.models.frontend.abs_frontend import AbsFrontend
  21. from funasr.models.frontend.default import DefaultFrontend
  22. from funasr.models.frontend.windowing import SlidingWindow
  23. from funasr.models.preencoder.abs_preencoder import AbsPreEncoder
  24. from funasr.models.preencoder.sinc import LightweightSincConvs
  25. from funasr.models.specaug.abs_specaug import AbsSpecAug
  26. from funasr.models.specaug.specaug import SpecAug
  27. from funasr.tasks.abs_task import AbsTask
  28. from funasr.text.phoneme_tokenizer import g2p_choices
  29. from funasr.torch_utils.initialize import initialize
  30. from funasr.train.class_choices import ClassChoices
  31. from funasr.train.trainer import Trainer
  32. from funasr.utils.types import float_or_none
  33. from funasr.utils.types import int_or_none
  34. from funasr.utils.types import str2bool
  35. from funasr.utils.types import str_or_none
  36. frontend_choices = ClassChoices(
  37. name="frontend",
  38. classes=dict(default=DefaultFrontend, sliding_window=SlidingWindow),
  39. type_check=AbsFrontend,
  40. default="default",
  41. )
  42. specaug_choices = ClassChoices(
  43. name="specaug",
  44. classes=dict(specaug=SpecAug),
  45. type_check=AbsSpecAug,
  46. default=None,
  47. optional=True,
  48. )
  49. normalize_choices = ClassChoices(
  50. "normalize",
  51. classes=dict(
  52. global_mvn=GlobalMVN,
  53. utterance_mvn=UtteranceMVN,
  54. ),
  55. type_check=AbsNormalize,
  56. default=None,
  57. optional=True,
  58. )
  59. preencoder_choices = ClassChoices(
  60. name="preencoder",
  61. classes=dict(
  62. sinc=LightweightSincConvs,
  63. ),
  64. type_check=AbsPreEncoder,
  65. default=None,
  66. optional=True,
  67. )
  68. encoder_choices = ClassChoices(
  69. "encoder",
  70. classes=dict(
  71. data2vec_encoder=Data2VecEncoder,
  72. ),
  73. type_check=AbsEncoder,
  74. default="data2vec_encoder",
  75. )
  76. model_choices = ClassChoices(
  77. "model",
  78. classes=dict(
  79. data2vec=Data2VecPretrainModel,
  80. ),
  81. default="data2vec",
  82. )
  83. class Data2VecTask(AbsTask):
  84. # If you need more than one optimizers, change this value
  85. num_optimizers: int = 1
  86. # Add variable objects configurations
  87. class_choices_list = [
  88. # --frontend and --frontend_conf
  89. frontend_choices,
  90. # --specaug and --specaug_conf
  91. specaug_choices,
  92. # --normalize and --normalize_conf
  93. normalize_choices,
  94. # --preencoder and --preencoder_conf
  95. preencoder_choices,
  96. # --encoder and --encoder_conf
  97. encoder_choices,
  98. # --model and --model_conf
  99. model_choices,
  100. ]
  101. # If you need to modify train() or eval() procedures, change Trainer class here
  102. trainer = Trainer
  103. @classmethod
  104. def add_task_arguments(cls, parser: argparse.ArgumentParser):
  105. group = parser.add_argument_group(description="Task related")
  106. # NOTE(kamo): add_arguments(..., required=True) can't be used
  107. # to provide --print_config mode. Instead of it, do as
  108. group.add_argument(
  109. "--token_list",
  110. type=str_or_none,
  111. default=None,
  112. help="A text mapping int-id to token",
  113. )
  114. group.add_argument(
  115. "--init",
  116. type=lambda x: str_or_none(x.lower()),
  117. default=None,
  118. help="The initialization method",
  119. choices=[
  120. "chainer",
  121. "xavier_uniform",
  122. "xavier_normal",
  123. "kaiming_uniform",
  124. "kaiming_normal",
  125. None,
  126. ],
  127. )
  128. group.add_argument(
  129. "--input_size",
  130. type=int_or_none,
  131. default=None,
  132. help="The number of input dimension of the feature",
  133. )
  134. group = parser.add_argument_group(description="Preprocess related")
  135. group.add_argument(
  136. "--use_preprocessor",
  137. type=str2bool,
  138. default=True,
  139. help="Apply preprocessing to data or not",
  140. )
  141. group.add_argument(
  142. "--token_type",
  143. type=str,
  144. default=None,
  145. choices=["bpe", "char", "word", "phn"],
  146. help="The text will be tokenized " "in the specified level token",
  147. )
  148. group.add_argument(
  149. "--feats_type",
  150. type=str,
  151. default='fbank',
  152. help="feats type, e.g. fbank, wav, ark_wav(needed to be scale normalization)",
  153. )
  154. group.add_argument(
  155. "--bpemodel",
  156. type=str_or_none,
  157. default=None,
  158. help="The model file of sentencepiece",
  159. )
  160. parser.add_argument(
  161. "--non_linguistic_symbols",
  162. type=str_or_none,
  163. help="non_linguistic_symbols file path",
  164. )
  165. parser.add_argument(
  166. "--cleaner",
  167. type=str_or_none,
  168. choices=[None, "tacotron", "jaconv", "vietnamese"],
  169. default=None,
  170. help="Apply text cleaning",
  171. )
  172. parser.add_argument(
  173. "--g2p",
  174. type=str_or_none,
  175. choices=g2p_choices,
  176. default=None,
  177. help="Specify g2p method if --token_type=phn",
  178. )
  179. parser.add_argument(
  180. "--speech_volume_normalize",
  181. type=float_or_none,
  182. default=None,
  183. help="Scale the maximum amplitude to the given value.",
  184. )
  185. parser.add_argument(
  186. "--rir_scp",
  187. type=str_or_none,
  188. default=None,
  189. help="The file path of rir scp file.",
  190. )
  191. parser.add_argument(
  192. "--rir_apply_prob",
  193. type=float,
  194. default=1.0,
  195. help="THe probability for applying RIR convolution.",
  196. )
  197. parser.add_argument(
  198. "--noise_scp",
  199. type=str_or_none,
  200. default=None,
  201. help="The file path of noise scp file.",
  202. )
  203. parser.add_argument(
  204. "--noise_apply_prob",
  205. type=float,
  206. default=1.0,
  207. help="The probability applying Noise adding.",
  208. )
  209. parser.add_argument(
  210. "--noise_db_range",
  211. type=str,
  212. default="13_15",
  213. help="The range of noise decibel level.",
  214. )
  215. parser.add_argument(
  216. "--pred_masked_weight",
  217. type=float,
  218. default=1.0,
  219. help="weight for predictive loss for masked frames",
  220. )
  221. parser.add_argument(
  222. "--pred_nomask_weight",
  223. type=float,
  224. default=0.0,
  225. help="weight for predictive loss for unmasked frames",
  226. )
  227. parser.add_argument(
  228. "--loss_weights",
  229. type=float,
  230. default=0.0,
  231. help="weights for additional loss terms (not first one)",
  232. )
  233. for class_choices in cls.class_choices_list:
  234. # Append --<name> and --<name>_conf.
  235. # e.g. --encoder and --encoder_conf
  236. class_choices.add_arguments(group)
  237. @classmethod
  238. def build_collate_fn(
  239. cls, args: argparse.Namespace, train: bool
  240. ) -> Callable[
  241. [Collection[Tuple[str, Dict[str, np.ndarray]]]],
  242. Tuple[List[str], Dict[str, torch.Tensor]],
  243. ]:
  244. assert check_argument_types()
  245. return CommonCollateFn(clipping=True)
  246. @classmethod
  247. def build_preprocess_fn(
  248. cls, args: argparse.Namespace, train: bool
  249. ) -> Optional[Callable[[str, Dict[str, np.array]], Dict[str, np.ndarray]]]:
  250. assert check_argument_types()
  251. if args.use_preprocessor:
  252. retval = CommonPreprocessor(
  253. train=train,
  254. bpemodel=args.bpemodel,
  255. non_linguistic_symbols=args.non_linguistic_symbols,
  256. text_cleaner=args.cleaner,
  257. g2p_type=args.g2p,
  258. # NOTE(kamo): Check attribute existence for backward compatibility
  259. rir_scp=args.rir_scp if hasattr(args, "rir_scp") else None,
  260. rir_apply_prob=args.rir_apply_prob
  261. if hasattr(args, "rir_apply_prob")
  262. else 1.0,
  263. noise_scp=args.noise_scp if hasattr(args, "noise_scp") else None,
  264. noise_apply_prob=args.noise_apply_prob
  265. if hasattr(args, "noise_apply_prob")
  266. else 1.0,
  267. noise_db_range=args.noise_db_range
  268. if hasattr(args, "noise_db_range")
  269. else "13_15",
  270. speech_volume_normalize=args.speech_volume_normalize
  271. if hasattr(args, "rir_scp")
  272. else None,
  273. )
  274. else:
  275. retval = None
  276. assert check_return_type(retval)
  277. return retval
  278. @classmethod
  279. def required_data_names(
  280. cls, train: bool = True, inference: bool = False
  281. ) -> Tuple[str, ...]:
  282. # for pre-training
  283. retval = ("speech",)
  284. return retval
  285. @classmethod
  286. def optional_data_names(
  287. cls, train: bool = True, inference: bool = False
  288. ) -> Tuple[str, ...]:
  289. retval = ()
  290. assert check_return_type(retval)
  291. return retval
  292. @classmethod
  293. def build_model(cls, args: argparse.Namespace):
  294. assert check_argument_types()
  295. # 1. frontend
  296. if args.input_size is None:
  297. # Extract features in the model
  298. frontend_class = frontend_choices.get_class(args.frontend)
  299. frontend = frontend_class(**args.frontend_conf)
  300. input_size = frontend.output_size()
  301. else:
  302. # Give features from data-loader
  303. args.frontend = None
  304. args.frontend_conf = {}
  305. frontend = None
  306. input_size = args.input_size
  307. # 2. Data augmentation for spectrogram
  308. if args.specaug is not None:
  309. specaug_class = specaug_choices.get_class(args.specaug)
  310. specaug = specaug_class(**args.specaug_conf)
  311. else:
  312. specaug = None
  313. # 3. Normalization layer
  314. if args.normalize is not None:
  315. normalize_class = normalize_choices.get_class(args.normalize)
  316. normalize = normalize_class(**args.normalize_conf)
  317. else:
  318. normalize = None
  319. # 4. Pre-encoder input block
  320. # NOTE(kan-bayashi): Use getattr to keep the compatibility
  321. if getattr(args, "preencoder", None) is not None:
  322. preencoder_class = preencoder_choices.get_class(args.preencoder)
  323. preencoder = preencoder_class(**args.preencoder_conf)
  324. input_size = preencoder.output_size()
  325. else:
  326. preencoder = None
  327. # 5. Encoder
  328. encoder_class = encoder_choices.get_class(args.encoder)
  329. encoder = encoder_class(
  330. input_size=input_size,
  331. **args.encoder_conf,
  332. )
  333. # 6. Build model
  334. try:
  335. model_class = model_choices.get_class(args.model)
  336. except AttributeError:
  337. model_class = model_choices.get_class("data2vec")
  338. model = model_class(
  339. frontend=frontend,
  340. specaug=specaug,
  341. normalize=normalize,
  342. preencoder=preencoder,
  343. encoder=encoder,
  344. )
  345. # 7. Initialize
  346. if args.init is not None:
  347. initialize(model, args.init)
  348. assert check_return_type(model)
  349. return model