model.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. import time
  2. import torch
  3. from torch import nn
  4. import torch.nn.functional as F
  5. from typing import Iterable, Optional
  6. from funasr.register import tables
  7. from funasr.models.ctc.ctc import CTC
  8. from funasr.utils.datadir_writer import DatadirWriter
  9. from funasr.models.paraformer.search import Hypothesis
  10. from funasr.train_utils.device_funcs import force_gatherable
  11. from funasr.losses.label_smoothing_loss import LabelSmoothingLoss
  12. from funasr.metrics.compute_acc import compute_accuracy, th_accuracy
  13. from funasr.utils.load_utils import load_audio_text_image_video, extract_fbank
  14. from utils.ctc_alignment import ctc_forced_align
  15. class SinusoidalPositionEncoder(torch.nn.Module):
  16. """ """
  17. def __int__(self, d_model=80, dropout_rate=0.1):
  18. pass
  19. def encode(
  20. self, positions: torch.Tensor = None, depth: int = None, dtype: torch.dtype = torch.float32
  21. ):
  22. batch_size = positions.size(0)
  23. positions = positions.type(dtype)
  24. device = positions.device
  25. log_timescale_increment = torch.log(torch.tensor([10000], dtype=dtype, device=device)) / (
  26. depth / 2 - 1
  27. )
  28. inv_timescales = torch.exp(
  29. torch.arange(depth / 2, device=device).type(dtype) * (-log_timescale_increment)
  30. )
  31. inv_timescales = torch.reshape(inv_timescales, [batch_size, -1])
  32. scaled_time = torch.reshape(positions, [1, -1, 1]) * torch.reshape(
  33. inv_timescales, [1, 1, -1]
  34. )
  35. encoding = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=2)
  36. return encoding.type(dtype)
  37. def forward(self, x):
  38. batch_size, timesteps, input_dim = x.size()
  39. positions = torch.arange(1, timesteps + 1, device=x.device)[None, :]
  40. position_encoding = self.encode(positions, input_dim, x.dtype).to(x.device)
  41. return x + position_encoding
  42. class PositionwiseFeedForward(torch.nn.Module):
  43. """Positionwise feed forward layer.
  44. Args:
  45. idim (int): Input dimenstion.
  46. hidden_units (int): The number of hidden units.
  47. dropout_rate (float): Dropout rate.
  48. """
  49. def __init__(self, idim, hidden_units, dropout_rate, activation=torch.nn.ReLU()):
  50. """Construct an PositionwiseFeedForward object."""
  51. super(PositionwiseFeedForward, self).__init__()
  52. self.w_1 = torch.nn.Linear(idim, hidden_units)
  53. self.w_2 = torch.nn.Linear(hidden_units, idim)
  54. self.dropout = torch.nn.Dropout(dropout_rate)
  55. self.activation = activation
  56. def forward(self, x):
  57. """Forward function."""
  58. return self.w_2(self.dropout(self.activation(self.w_1(x))))
  59. class MultiHeadedAttentionSANM(nn.Module):
  60. """Multi-Head Attention layer.
  61. Args:
  62. n_head (int): The number of heads.
  63. n_feat (int): The number of features.
  64. dropout_rate (float): Dropout rate.
  65. """
  66. def __init__(
  67. self,
  68. n_head,
  69. in_feat,
  70. n_feat,
  71. dropout_rate,
  72. kernel_size,
  73. sanm_shfit=0,
  74. lora_list=None,
  75. lora_rank=8,
  76. lora_alpha=16,
  77. lora_dropout=0.1,
  78. ):
  79. """Construct an MultiHeadedAttention object."""
  80. super().__init__()
  81. assert n_feat % n_head == 0
  82. # We assume d_v always equals d_k
  83. self.d_k = n_feat // n_head
  84. self.h = n_head
  85. # self.linear_q = nn.Linear(n_feat, n_feat)
  86. # self.linear_k = nn.Linear(n_feat, n_feat)
  87. # self.linear_v = nn.Linear(n_feat, n_feat)
  88. self.linear_out = nn.Linear(n_feat, n_feat)
  89. self.linear_q_k_v = nn.Linear(in_feat, n_feat * 3)
  90. self.attn = None
  91. self.dropout = nn.Dropout(p=dropout_rate)
  92. self.fsmn_block = nn.Conv1d(
  93. n_feat, n_feat, kernel_size, stride=1, padding=0, groups=n_feat, bias=False
  94. )
  95. # padding
  96. left_padding = (kernel_size - 1) // 2
  97. if sanm_shfit > 0:
  98. left_padding = left_padding + sanm_shfit
  99. right_padding = kernel_size - 1 - left_padding
  100. self.pad_fn = nn.ConstantPad1d((left_padding, right_padding), 0.0)
  101. def forward_fsmn(self, inputs, mask, mask_shfit_chunk=None):
  102. b, t, d = inputs.size()
  103. if mask is not None:
  104. mask = torch.reshape(mask, (b, -1, 1))
  105. if mask_shfit_chunk is not None:
  106. mask = mask * mask_shfit_chunk
  107. inputs = inputs * mask
  108. x = inputs.transpose(1, 2)
  109. x = self.pad_fn(x)
  110. x = self.fsmn_block(x)
  111. x = x.transpose(1, 2)
  112. x += inputs
  113. x = self.dropout(x)
  114. if mask is not None:
  115. x = x * mask
  116. return x
  117. def forward_qkv(self, x):
  118. """Transform query, key and value.
  119. Args:
  120. query (torch.Tensor): Query tensor (#batch, time1, size).
  121. key (torch.Tensor): Key tensor (#batch, time2, size).
  122. value (torch.Tensor): Value tensor (#batch, time2, size).
  123. Returns:
  124. torch.Tensor: Transformed query tensor (#batch, n_head, time1, d_k).
  125. torch.Tensor: Transformed key tensor (#batch, n_head, time2, d_k).
  126. torch.Tensor: Transformed value tensor (#batch, n_head, time2, d_k).
  127. """
  128. b, t, d = x.size()
  129. q_k_v = self.linear_q_k_v(x)
  130. q, k, v = torch.split(q_k_v, int(self.h * self.d_k), dim=-1)
  131. q_h = torch.reshape(q, (b, t, self.h, self.d_k)).transpose(
  132. 1, 2
  133. ) # (batch, head, time1, d_k)
  134. k_h = torch.reshape(k, (b, t, self.h, self.d_k)).transpose(
  135. 1, 2
  136. ) # (batch, head, time2, d_k)
  137. v_h = torch.reshape(v, (b, t, self.h, self.d_k)).transpose(
  138. 1, 2
  139. ) # (batch, head, time2, d_k)
  140. return q_h, k_h, v_h, v
  141. def forward_attention(self, value, scores, mask, mask_att_chunk_encoder=None):
  142. """Compute attention context vector.
  143. Args:
  144. value (torch.Tensor): Transformed value (#batch, n_head, time2, d_k).
  145. scores (torch.Tensor): Attention score (#batch, n_head, time1, time2).
  146. mask (torch.Tensor): Mask (#batch, 1, time2) or (#batch, time1, time2).
  147. Returns:
  148. torch.Tensor: Transformed value (#batch, time1, d_model)
  149. weighted by the attention score (#batch, time1, time2).
  150. """
  151. n_batch = value.size(0)
  152. if mask is not None:
  153. if mask_att_chunk_encoder is not None:
  154. mask = mask * mask_att_chunk_encoder
  155. mask = mask.unsqueeze(1).eq(0) # (batch, 1, *, time2)
  156. min_value = -float(
  157. "inf"
  158. ) # float(numpy.finfo(torch.tensor(0, dtype=scores.dtype).numpy().dtype).min)
  159. scores = scores.masked_fill(mask, min_value)
  160. attn = torch.softmax(scores, dim=-1).masked_fill(
  161. mask, 0.0
  162. ) # (batch, head, time1, time2)
  163. else:
  164. attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2)
  165. p_attn = self.dropout(attn)
  166. x = torch.matmul(p_attn, value) # (batch, head, time1, d_k)
  167. x = (
  168. x.transpose(1, 2).contiguous().view(n_batch, -1, self.h * self.d_k)
  169. ) # (batch, time1, d_model)
  170. return self.linear_out(x) # (batch, time1, d_model)
  171. def forward(self, x, mask, mask_shfit_chunk=None, mask_att_chunk_encoder=None):
  172. """Compute scaled dot product attention.
  173. Args:
  174. query (torch.Tensor): Query tensor (#batch, time1, size).
  175. key (torch.Tensor): Key tensor (#batch, time2, size).
  176. value (torch.Tensor): Value tensor (#batch, time2, size).
  177. mask (torch.Tensor): Mask tensor (#batch, 1, time2) or
  178. (#batch, time1, time2).
  179. Returns:
  180. torch.Tensor: Output tensor (#batch, time1, d_model).
  181. """
  182. q_h, k_h, v_h, v = self.forward_qkv(x)
  183. fsmn_memory = self.forward_fsmn(v, mask, mask_shfit_chunk)
  184. q_h = q_h * self.d_k ** (-0.5)
  185. scores = torch.matmul(q_h, k_h.transpose(-2, -1))
  186. att_outs = self.forward_attention(v_h, scores, mask, mask_att_chunk_encoder)
  187. return att_outs + fsmn_memory
  188. def forward_chunk(self, x, cache=None, chunk_size=None, look_back=0):
  189. """Compute scaled dot product attention.
  190. Args:
  191. query (torch.Tensor): Query tensor (#batch, time1, size).
  192. key (torch.Tensor): Key tensor (#batch, time2, size).
  193. value (torch.Tensor): Value tensor (#batch, time2, size).
  194. mask (torch.Tensor): Mask tensor (#batch, 1, time2) or
  195. (#batch, time1, time2).
  196. Returns:
  197. torch.Tensor: Output tensor (#batch, time1, d_model).
  198. """
  199. q_h, k_h, v_h, v = self.forward_qkv(x)
  200. if chunk_size is not None and look_back > 0 or look_back == -1:
  201. if cache is not None:
  202. k_h_stride = k_h[:, :, : -(chunk_size[2]), :]
  203. v_h_stride = v_h[:, :, : -(chunk_size[2]), :]
  204. k_h = torch.cat((cache["k"], k_h), dim=2)
  205. v_h = torch.cat((cache["v"], v_h), dim=2)
  206. cache["k"] = torch.cat((cache["k"], k_h_stride), dim=2)
  207. cache["v"] = torch.cat((cache["v"], v_h_stride), dim=2)
  208. if look_back != -1:
  209. cache["k"] = cache["k"][:, :, -(look_back * chunk_size[1]) :, :]
  210. cache["v"] = cache["v"][:, :, -(look_back * chunk_size[1]) :, :]
  211. else:
  212. cache_tmp = {
  213. "k": k_h[:, :, : -(chunk_size[2]), :],
  214. "v": v_h[:, :, : -(chunk_size[2]), :],
  215. }
  216. cache = cache_tmp
  217. fsmn_memory = self.forward_fsmn(v, None)
  218. q_h = q_h * self.d_k ** (-0.5)
  219. scores = torch.matmul(q_h, k_h.transpose(-2, -1))
  220. att_outs = self.forward_attention(v_h, scores, None)
  221. return att_outs + fsmn_memory, cache
  222. class LayerNorm(nn.LayerNorm):
  223. def __init__(self, *args, **kwargs):
  224. super().__init__(*args, **kwargs)
  225. def forward(self, input):
  226. output = F.layer_norm(
  227. input.float(),
  228. self.normalized_shape,
  229. self.weight.float() if self.weight is not None else None,
  230. self.bias.float() if self.bias is not None else None,
  231. self.eps,
  232. )
  233. return output.type_as(input)
  234. def sequence_mask(lengths, maxlen=None, dtype=torch.float32, device=None):
  235. if maxlen is None:
  236. maxlen = lengths.max()
  237. row_vector = torch.arange(0, maxlen, 1).to(lengths.device)
  238. matrix = torch.unsqueeze(lengths, dim=-1)
  239. mask = row_vector < matrix
  240. mask = mask.detach()
  241. return mask.type(dtype).to(device) if device is not None else mask.type(dtype)
  242. class EncoderLayerSANM(nn.Module):
  243. def __init__(
  244. self,
  245. in_size,
  246. size,
  247. self_attn,
  248. feed_forward,
  249. dropout_rate,
  250. normalize_before=True,
  251. concat_after=False,
  252. stochastic_depth_rate=0.0,
  253. ):
  254. """Construct an EncoderLayer object."""
  255. super(EncoderLayerSANM, self).__init__()
  256. self.self_attn = self_attn
  257. self.feed_forward = feed_forward
  258. self.norm1 = LayerNorm(in_size)
  259. self.norm2 = LayerNorm(size)
  260. self.dropout = nn.Dropout(dropout_rate)
  261. self.in_size = in_size
  262. self.size = size
  263. self.normalize_before = normalize_before
  264. self.concat_after = concat_after
  265. if self.concat_after:
  266. self.concat_linear = nn.Linear(size + size, size)
  267. self.stochastic_depth_rate = stochastic_depth_rate
  268. self.dropout_rate = dropout_rate
  269. def forward(self, x, mask, cache=None, mask_shfit_chunk=None, mask_att_chunk_encoder=None):
  270. """Compute encoded features.
  271. Args:
  272. x_input (torch.Tensor): Input tensor (#batch, time, size).
  273. mask (torch.Tensor): Mask tensor for the input (#batch, time).
  274. cache (torch.Tensor): Cache tensor of the input (#batch, time - 1, size).
  275. Returns:
  276. torch.Tensor: Output tensor (#batch, time, size).
  277. torch.Tensor: Mask tensor (#batch, time).
  278. """
  279. skip_layer = False
  280. # with stochastic depth, residual connection `x + f(x)` becomes
  281. # `x <- x + 1 / (1 - p) * f(x)` at training time.
  282. stoch_layer_coeff = 1.0
  283. if self.training and self.stochastic_depth_rate > 0:
  284. skip_layer = torch.rand(1).item() < self.stochastic_depth_rate
  285. stoch_layer_coeff = 1.0 / (1 - self.stochastic_depth_rate)
  286. if skip_layer:
  287. if cache is not None:
  288. x = torch.cat([cache, x], dim=1)
  289. return x, mask
  290. residual = x
  291. if self.normalize_before:
  292. x = self.norm1(x)
  293. if self.concat_after:
  294. x_concat = torch.cat(
  295. (
  296. x,
  297. self.self_attn(
  298. x,
  299. mask,
  300. mask_shfit_chunk=mask_shfit_chunk,
  301. mask_att_chunk_encoder=mask_att_chunk_encoder,
  302. ),
  303. ),
  304. dim=-1,
  305. )
  306. if self.in_size == self.size:
  307. x = residual + stoch_layer_coeff * self.concat_linear(x_concat)
  308. else:
  309. x = stoch_layer_coeff * self.concat_linear(x_concat)
  310. else:
  311. if self.in_size == self.size:
  312. x = residual + stoch_layer_coeff * self.dropout(
  313. self.self_attn(
  314. x,
  315. mask,
  316. mask_shfit_chunk=mask_shfit_chunk,
  317. mask_att_chunk_encoder=mask_att_chunk_encoder,
  318. )
  319. )
  320. else:
  321. x = stoch_layer_coeff * self.dropout(
  322. self.self_attn(
  323. x,
  324. mask,
  325. mask_shfit_chunk=mask_shfit_chunk,
  326. mask_att_chunk_encoder=mask_att_chunk_encoder,
  327. )
  328. )
  329. if not self.normalize_before:
  330. x = self.norm1(x)
  331. residual = x
  332. if self.normalize_before:
  333. x = self.norm2(x)
  334. x = residual + stoch_layer_coeff * self.dropout(self.feed_forward(x))
  335. if not self.normalize_before:
  336. x = self.norm2(x)
  337. return x, mask, cache, mask_shfit_chunk, mask_att_chunk_encoder
  338. def forward_chunk(self, x, cache=None, chunk_size=None, look_back=0):
  339. """Compute encoded features.
  340. Args:
  341. x_input (torch.Tensor): Input tensor (#batch, time, size).
  342. mask (torch.Tensor): Mask tensor for the input (#batch, time).
  343. cache (torch.Tensor): Cache tensor of the input (#batch, time - 1, size).
  344. Returns:
  345. torch.Tensor: Output tensor (#batch, time, size).
  346. torch.Tensor: Mask tensor (#batch, time).
  347. """
  348. residual = x
  349. if self.normalize_before:
  350. x = self.norm1(x)
  351. if self.in_size == self.size:
  352. attn, cache = self.self_attn.forward_chunk(x, cache, chunk_size, look_back)
  353. x = residual + attn
  354. else:
  355. x, cache = self.self_attn.forward_chunk(x, cache, chunk_size, look_back)
  356. if not self.normalize_before:
  357. x = self.norm1(x)
  358. residual = x
  359. if self.normalize_before:
  360. x = self.norm2(x)
  361. x = residual + self.feed_forward(x)
  362. if not self.normalize_before:
  363. x = self.norm2(x)
  364. return x, cache
  365. @tables.register("encoder_classes", "SenseVoiceEncoderSmall")
  366. class SenseVoiceEncoderSmall(nn.Module):
  367. """
  368. Author: Speech Lab of DAMO Academy, Alibaba Group
  369. SCAMA: Streaming chunk-aware multihead attention for online end-to-end speech recognition
  370. https://arxiv.org/abs/2006.01713
  371. """
  372. def __init__(
  373. self,
  374. input_size: int,
  375. output_size: int = 256,
  376. attention_heads: int = 4,
  377. linear_units: int = 2048,
  378. num_blocks: int = 6,
  379. tp_blocks: int = 0,
  380. dropout_rate: float = 0.1,
  381. positional_dropout_rate: float = 0.1,
  382. attention_dropout_rate: float = 0.0,
  383. stochastic_depth_rate: float = 0.0,
  384. input_layer: Optional[str] = "conv2d",
  385. pos_enc_class=SinusoidalPositionEncoder,
  386. normalize_before: bool = True,
  387. concat_after: bool = False,
  388. positionwise_layer_type: str = "linear",
  389. positionwise_conv_kernel_size: int = 1,
  390. padding_idx: int = -1,
  391. kernel_size: int = 11,
  392. sanm_shfit: int = 0,
  393. selfattention_layer_type: str = "sanm",
  394. **kwargs,
  395. ):
  396. super().__init__()
  397. self._output_size = output_size
  398. self.embed = SinusoidalPositionEncoder()
  399. self.normalize_before = normalize_before
  400. positionwise_layer = PositionwiseFeedForward
  401. positionwise_layer_args = (
  402. output_size,
  403. linear_units,
  404. dropout_rate,
  405. )
  406. encoder_selfattn_layer = MultiHeadedAttentionSANM
  407. encoder_selfattn_layer_args0 = (
  408. attention_heads,
  409. input_size,
  410. output_size,
  411. attention_dropout_rate,
  412. kernel_size,
  413. sanm_shfit,
  414. )
  415. encoder_selfattn_layer_args = (
  416. attention_heads,
  417. output_size,
  418. output_size,
  419. attention_dropout_rate,
  420. kernel_size,
  421. sanm_shfit,
  422. )
  423. self.encoders0 = nn.ModuleList(
  424. [
  425. EncoderLayerSANM(
  426. input_size,
  427. output_size,
  428. encoder_selfattn_layer(*encoder_selfattn_layer_args0),
  429. positionwise_layer(*positionwise_layer_args),
  430. dropout_rate,
  431. )
  432. for i in range(1)
  433. ]
  434. )
  435. self.encoders = nn.ModuleList(
  436. [
  437. EncoderLayerSANM(
  438. output_size,
  439. output_size,
  440. encoder_selfattn_layer(*encoder_selfattn_layer_args),
  441. positionwise_layer(*positionwise_layer_args),
  442. dropout_rate,
  443. )
  444. for i in range(num_blocks - 1)
  445. ]
  446. )
  447. self.tp_encoders = nn.ModuleList(
  448. [
  449. EncoderLayerSANM(
  450. output_size,
  451. output_size,
  452. encoder_selfattn_layer(*encoder_selfattn_layer_args),
  453. positionwise_layer(*positionwise_layer_args),
  454. dropout_rate,
  455. )
  456. for i in range(tp_blocks)
  457. ]
  458. )
  459. self.after_norm = LayerNorm(output_size)
  460. self.tp_norm = LayerNorm(output_size)
  461. def output_size(self) -> int:
  462. return self._output_size
  463. def forward(
  464. self,
  465. xs_pad: torch.Tensor,
  466. ilens: torch.Tensor,
  467. ):
  468. """Embed positions in tensor."""
  469. masks = sequence_mask(ilens, device=ilens.device)[:, None, :]
  470. xs_pad *= self.output_size() ** 0.5
  471. xs_pad = self.embed(xs_pad)
  472. # forward encoder1
  473. for layer_idx, encoder_layer in enumerate(self.encoders0):
  474. encoder_outs = encoder_layer(xs_pad, masks)
  475. xs_pad, masks = encoder_outs[0], encoder_outs[1]
  476. for layer_idx, encoder_layer in enumerate(self.encoders):
  477. encoder_outs = encoder_layer(xs_pad, masks)
  478. xs_pad, masks = encoder_outs[0], encoder_outs[1]
  479. xs_pad = self.after_norm(xs_pad)
  480. # forward encoder2
  481. olens = masks.squeeze(1).sum(1).int()
  482. for layer_idx, encoder_layer in enumerate(self.tp_encoders):
  483. encoder_outs = encoder_layer(xs_pad, masks)
  484. xs_pad, masks = encoder_outs[0], encoder_outs[1]
  485. xs_pad = self.tp_norm(xs_pad)
  486. return xs_pad, olens
  487. @tables.register("model_classes", "SenseVoiceSmall")
  488. class SenseVoiceSmall(nn.Module):
  489. """CTC-attention hybrid Encoder-Decoder model"""
  490. def __init__(
  491. self,
  492. specaug: str = None,
  493. specaug_conf: dict = None,
  494. normalize: str = None,
  495. normalize_conf: dict = None,
  496. encoder: str = None,
  497. encoder_conf: dict = None,
  498. ctc_conf: dict = None,
  499. input_size: int = 80,
  500. vocab_size: int = -1,
  501. ignore_id: int = -1,
  502. blank_id: int = 0,
  503. sos: int = 1,
  504. eos: int = 2,
  505. length_normalized_loss: bool = False,
  506. **kwargs,
  507. ):
  508. super().__init__()
  509. if specaug is not None:
  510. specaug_class = tables.specaug_classes.get(specaug)
  511. specaug = specaug_class(**specaug_conf)
  512. if normalize is not None:
  513. normalize_class = tables.normalize_classes.get(normalize)
  514. normalize = normalize_class(**normalize_conf)
  515. encoder_class = tables.encoder_classes.get(encoder)
  516. encoder = encoder_class(input_size=input_size, **encoder_conf)
  517. encoder_output_size = encoder.output_size()
  518. if ctc_conf is None:
  519. ctc_conf = {}
  520. ctc = CTC(odim=vocab_size, encoder_output_size=encoder_output_size, **ctc_conf)
  521. self.blank_id = blank_id
  522. self.sos = sos if sos is not None else vocab_size - 1
  523. self.eos = eos if eos is not None else vocab_size - 1
  524. self.vocab_size = vocab_size
  525. self.ignore_id = ignore_id
  526. self.specaug = specaug
  527. self.normalize = normalize
  528. self.encoder = encoder
  529. self.error_calculator = None
  530. self.ctc = ctc
  531. self.length_normalized_loss = length_normalized_loss
  532. self.encoder_output_size = encoder_output_size
  533. self.lid_dict = {"auto": 0, "zh": 3, "en": 4, "yue": 7, "ja": 11, "ko": 12, "nospeech": 13}
  534. self.lid_int_dict = {24884: 3, 24885: 4, 24888: 7, 24892: 11, 24896: 12, 24992: 13}
  535. self.textnorm_dict = {"withitn": 14, "woitn": 15}
  536. self.textnorm_int_dict = {25016: 14, 25017: 15}
  537. self.embed = torch.nn.Embedding(7 + len(self.lid_dict) + len(self.textnorm_dict), input_size)
  538. self.emo_dict = {"unk": 25009, "happy": 25001, "sad": 25002, "angry": 25003, "neutral": 25004}
  539. self.criterion_att = LabelSmoothingLoss(
  540. size=self.vocab_size,
  541. padding_idx=self.ignore_id,
  542. smoothing=kwargs.get("lsm_weight", 0.0),
  543. normalize_length=self.length_normalized_loss,
  544. )
  545. @staticmethod
  546. def from_pretrained(model:str=None, **kwargs):
  547. from funasr import AutoModel
  548. model, kwargs = AutoModel.build_model(model=model, trust_remote_code=True, **kwargs)
  549. return model, kwargs
  550. def forward(
  551. self,
  552. speech: torch.Tensor,
  553. speech_lengths: torch.Tensor,
  554. text: torch.Tensor,
  555. text_lengths: torch.Tensor,
  556. **kwargs,
  557. ):
  558. """Encoder + Decoder + Calc loss
  559. Args:
  560. speech: (Batch, Length, ...)
  561. speech_lengths: (Batch, )
  562. text: (Batch, Length)
  563. text_lengths: (Batch,)
  564. """
  565. # import pdb;
  566. # pdb.set_trace()
  567. if len(text_lengths.size()) > 1:
  568. text_lengths = text_lengths[:, 0]
  569. if len(speech_lengths.size()) > 1:
  570. speech_lengths = speech_lengths[:, 0]
  571. batch_size = speech.shape[0]
  572. # 1. Encoder
  573. encoder_out, encoder_out_lens = self.encode(speech, speech_lengths, text)
  574. loss_ctc, cer_ctc = None, None
  575. loss_rich, acc_rich = None, None
  576. stats = dict()
  577. loss_ctc, cer_ctc = self._calc_ctc_loss(
  578. encoder_out[:, 4:, :], encoder_out_lens - 4, text[:, 4:], text_lengths - 4
  579. )
  580. loss_rich, acc_rich = self._calc_rich_ce_loss(
  581. encoder_out[:, :4, :], text[:, :4]
  582. )
  583. loss = loss_ctc + loss_rich
  584. # Collect total loss stats
  585. stats["loss_ctc"] = torch.clone(loss_ctc.detach()) if loss_ctc is not None else None
  586. stats["loss_rich"] = torch.clone(loss_rich.detach()) if loss_rich is not None else None
  587. stats["loss"] = torch.clone(loss.detach()) if loss is not None else None
  588. stats["acc_rich"] = acc_rich
  589. # force_gatherable: to-device and to-tensor if scalar for DataParallel
  590. if self.length_normalized_loss:
  591. batch_size = int((text_lengths + 1).sum())
  592. loss, stats, weight = force_gatherable((loss, stats, batch_size), loss.device)
  593. return loss, stats, weight
  594. def encode(
  595. self,
  596. speech: torch.Tensor,
  597. speech_lengths: torch.Tensor,
  598. text: torch.Tensor,
  599. **kwargs,
  600. ):
  601. """Frontend + Encoder. Note that this method is used by asr_inference.py
  602. Args:
  603. speech: (Batch, Length, ...)
  604. speech_lengths: (Batch, )
  605. ind: int
  606. """
  607. # Data augmentation
  608. if self.specaug is not None and self.training:
  609. speech, speech_lengths = self.specaug(speech, speech_lengths)
  610. # Normalization for feature: e.g. Global-CMVN, Utterance-CMVN
  611. if self.normalize is not None:
  612. speech, speech_lengths = self.normalize(speech, speech_lengths)
  613. lids = torch.LongTensor([[self.lid_int_dict[int(lid)] if torch.rand(1) > 0.2 and int(lid) in self.lid_int_dict else 0 ] for lid in text[:, 0]]).to(speech.device)
  614. language_query = self.embed(lids)
  615. styles = torch.LongTensor([[self.textnorm_int_dict[int(style)]] for style in text[:, 3]]).to(speech.device)
  616. style_query = self.embed(styles)
  617. speech = torch.cat((style_query, speech), dim=1)
  618. speech_lengths += 1
  619. event_emo_query = self.embed(torch.LongTensor([[1, 2]]).to(speech.device)).repeat(speech.size(0), 1, 1)
  620. input_query = torch.cat((language_query, event_emo_query), dim=1)
  621. speech = torch.cat((input_query, speech), dim=1)
  622. speech_lengths += 3
  623. encoder_out, encoder_out_lens = self.encoder(speech, speech_lengths)
  624. return encoder_out, encoder_out_lens
  625. def _calc_ctc_loss(
  626. self,
  627. encoder_out: torch.Tensor,
  628. encoder_out_lens: torch.Tensor,
  629. ys_pad: torch.Tensor,
  630. ys_pad_lens: torch.Tensor,
  631. ):
  632. # Calc CTC loss
  633. loss_ctc = self.ctc(encoder_out, encoder_out_lens, ys_pad, ys_pad_lens)
  634. # Calc CER using CTC
  635. cer_ctc = None
  636. if not self.training and self.error_calculator is not None:
  637. ys_hat = self.ctc.argmax(encoder_out).data
  638. cer_ctc = self.error_calculator(ys_hat.cpu(), ys_pad.cpu(), is_ctc=True)
  639. return loss_ctc, cer_ctc
  640. def _calc_rich_ce_loss(
  641. self,
  642. encoder_out: torch.Tensor,
  643. ys_pad: torch.Tensor,
  644. ):
  645. decoder_out = self.ctc.ctc_lo(encoder_out)
  646. # 2. Compute attention loss
  647. loss_rich = self.criterion_att(decoder_out, ys_pad.contiguous())
  648. acc_rich = th_accuracy(
  649. decoder_out.view(-1, self.vocab_size),
  650. ys_pad.contiguous(),
  651. ignore_label=self.ignore_id,
  652. )
  653. return loss_rich, acc_rich
  654. def inference(
  655. self,
  656. data_in,
  657. data_lengths=None,
  658. key: list = ["wav_file_tmp_name"],
  659. tokenizer=None,
  660. frontend=None,
  661. **kwargs,
  662. ):
  663. meta_data = {}
  664. if (
  665. isinstance(data_in, torch.Tensor) and kwargs.get("data_type", "sound") == "fbank"
  666. ): # fbank
  667. speech, speech_lengths = data_in, data_lengths
  668. if len(speech.shape) < 3:
  669. speech = speech[None, :, :]
  670. if speech_lengths is None:
  671. speech_lengths = speech.shape[1]
  672. else:
  673. # extract fbank feats
  674. time1 = time.perf_counter()
  675. audio_sample_list = load_audio_text_image_video(
  676. data_in,
  677. fs=frontend.fs,
  678. audio_fs=kwargs.get("fs", 16000),
  679. data_type=kwargs.get("data_type", "sound"),
  680. tokenizer=tokenizer,
  681. )
  682. time2 = time.perf_counter()
  683. meta_data["load_data"] = f"{time2 - time1:0.3f}"
  684. speech, speech_lengths = extract_fbank(
  685. audio_sample_list, data_type=kwargs.get("data_type", "sound"), frontend=frontend
  686. )
  687. time3 = time.perf_counter()
  688. meta_data["extract_feat"] = f"{time3 - time2:0.3f}"
  689. meta_data["batch_data_time"] = (
  690. speech_lengths.sum().item() * frontend.frame_shift * frontend.lfr_n / 1000
  691. )
  692. speech = speech.to(device=kwargs["device"])
  693. speech_lengths = speech_lengths.to(device=kwargs["device"])
  694. language = kwargs.get("language", "auto")
  695. language_query = self.embed(
  696. torch.LongTensor(
  697. [[self.lid_dict[language] if language in self.lid_dict else 0]]
  698. ).to(speech.device)
  699. ).repeat(speech.size(0), 1, 1)
  700. use_itn = kwargs.get("use_itn", False)
  701. output_timestamp = kwargs.get("output_timestamp", False)
  702. textnorm = kwargs.get("text_norm", None)
  703. if textnorm is None:
  704. textnorm = "withitn" if use_itn else "woitn"
  705. textnorm_query = self.embed(
  706. torch.LongTensor([[self.textnorm_dict[textnorm]]]).to(speech.device)
  707. ).repeat(speech.size(0), 1, 1)
  708. speech = torch.cat((textnorm_query, speech), dim=1)
  709. speech_lengths += 1
  710. event_emo_query = self.embed(torch.LongTensor([[1, 2]]).to(speech.device)).repeat(
  711. speech.size(0), 1, 1
  712. )
  713. input_query = torch.cat((language_query, event_emo_query), dim=1)
  714. speech = torch.cat((input_query, speech), dim=1)
  715. speech_lengths += 3
  716. # Encoder
  717. encoder_out, encoder_out_lens = self.encoder(speech, speech_lengths)
  718. if isinstance(encoder_out, tuple):
  719. encoder_out = encoder_out[0]
  720. # c. Passed the encoder result and the beam search
  721. ctc_logits = self.ctc.log_softmax(encoder_out)
  722. if kwargs.get("ban_emo_unk", False):
  723. ctc_logits[:, :, self.emo_dict["unk"]] = -float("inf")
  724. results = []
  725. b, n, d = encoder_out.size()
  726. if isinstance(key[0], (list, tuple)):
  727. key = key[0]
  728. if len(key) < b:
  729. key = key * b
  730. for i in range(b):
  731. x = ctc_logits[i, : encoder_out_lens[i].item(), :]
  732. yseq = x.argmax(dim=-1)
  733. yseq = torch.unique_consecutive(yseq, dim=-1)
  734. ibest_writer = None
  735. if kwargs.get("output_dir") is not None:
  736. if not hasattr(self, "writer"):
  737. self.writer = DatadirWriter(kwargs.get("output_dir"))
  738. ibest_writer = self.writer[f"1best_recog"]
  739. mask = yseq != self.blank_id
  740. token_int = yseq[mask].tolist()
  741. # Change integer-ids to tokens
  742. text = tokenizer.decode(token_int)
  743. if ibest_writer is not None:
  744. ibest_writer["text"][key[i]] = text
  745. if output_timestamp:
  746. from itertools import groupby
  747. timestamp = []
  748. tokens = tokenizer.text2tokens(text)[4:]
  749. logits_speech = self.ctc.softmax(encoder_out)[i, 4:encoder_out_lens[i].item(), :]
  750. pred = logits_speech.argmax(-1).cpu()
  751. logits_speech[pred==self.blank_id, self.blank_id] = 0
  752. align = ctc_forced_align(
  753. logits_speech.unsqueeze(0).float(),
  754. torch.Tensor(token_int[4:]).unsqueeze(0).long().to(logits_speech.device),
  755. (encoder_out_lens-4).long(),
  756. torch.tensor(len(token_int)-4).unsqueeze(0).long().to(logits_speech.device),
  757. ignore_id=self.ignore_id,
  758. )
  759. pred = groupby(align[0, :encoder_out_lens[0]])
  760. _start = 0
  761. token_id = 0
  762. ts_max = encoder_out_lens[i] - 4
  763. for pred_token, pred_frame in pred:
  764. _end = _start + len(list(pred_frame))
  765. if pred_token != 0:
  766. ts_left = max((_start*60-30)/1000, 0)
  767. ts_right = min((_end*60-30)/1000, (ts_max*60-30)/1000)
  768. timestamp.append([tokens[token_id], ts_left, ts_right])
  769. token_id += 1
  770. _start = _end
  771. result_i = {"key": key[i], "text": text, "timestamp": timestamp}
  772. results.append(result_i)
  773. else:
  774. result_i = {"key": key[i], "text": text}
  775. results.append(result_i)
  776. return results, meta_data
  777. def export(self, **kwargs):
  778. from export_meta import export_rebuild_model
  779. if "max_seq_len" not in kwargs:
  780. kwargs["max_seq_len"] = 512
  781. models = export_rebuild_model(model=self, **kwargs)
  782. return models