modeling_sew.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/sew/modular_sew.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_sew.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2021 ASAPP Inc. and the HuggingFace Inc. team. All rights reserved.
  9. #
  10. # Licensed under the Apache License, Version 2.0 (the "License");
  11. # you may not use this file except in compliance with the License.
  12. # You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing, software
  17. # distributed under the License is distributed on an "AS IS" BASIS,
  18. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. # See the License for the specific language governing permissions and
  20. # limitations under the License.
  21. import math
  22. import warnings
  23. from typing import Callable, Optional, Union
  24. import numpy as np
  25. import torch
  26. from torch import nn
  27. from torch.nn import CrossEntropyLoss
  28. from ...activations import ACT2FN
  29. from ...integrations.deepspeed import is_deepspeed_zero3_enabled
  30. from ...integrations.fsdp import is_fsdp_managed_module
  31. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  32. from ...modeling_layers import GradientCheckpointingLayer
  33. from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput
  34. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  35. from ...processing_utils import Unpack
  36. from ...utils import auto_docstring, logging
  37. from .configuration_sew import SEWConfig
  38. logger = logging.get_logger(__name__)
  39. class SEWNoLayerNormConvLayer(GradientCheckpointingLayer):
  40. def __init__(self, config, layer_id=0):
  41. super().__init__()
  42. self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
  43. self.out_conv_dim = config.conv_dim[layer_id]
  44. self.conv = nn.Conv1d(
  45. self.in_conv_dim,
  46. self.out_conv_dim,
  47. kernel_size=config.conv_kernel[layer_id],
  48. stride=config.conv_stride[layer_id],
  49. bias=config.conv_bias,
  50. )
  51. self.activation = ACT2FN[config.feat_extract_activation]
  52. def forward(self, hidden_states):
  53. hidden_states = self.conv(hidden_states)
  54. hidden_states = self.activation(hidden_states)
  55. return hidden_states
  56. class SEWLayerNormConvLayer(GradientCheckpointingLayer):
  57. def __init__(self, config, layer_id=0):
  58. super().__init__()
  59. self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
  60. self.out_conv_dim = config.conv_dim[layer_id]
  61. self.conv = nn.Conv1d(
  62. self.in_conv_dim,
  63. self.out_conv_dim,
  64. kernel_size=config.conv_kernel[layer_id],
  65. stride=config.conv_stride[layer_id],
  66. bias=config.conv_bias,
  67. )
  68. self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
  69. self.activation = ACT2FN[config.feat_extract_activation]
  70. def forward(self, hidden_states):
  71. hidden_states = self.conv(hidden_states)
  72. hidden_states = hidden_states.transpose(-2, -1)
  73. hidden_states = self.layer_norm(hidden_states)
  74. hidden_states = hidden_states.transpose(-2, -1)
  75. hidden_states = self.activation(hidden_states)
  76. return hidden_states
  77. class SEWGroupNormConvLayer(GradientCheckpointingLayer):
  78. def __init__(self, config, layer_id=0):
  79. super().__init__()
  80. self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
  81. self.out_conv_dim = config.conv_dim[layer_id]
  82. self.conv = nn.Conv1d(
  83. self.in_conv_dim,
  84. self.out_conv_dim,
  85. kernel_size=config.conv_kernel[layer_id],
  86. stride=config.conv_stride[layer_id],
  87. bias=config.conv_bias,
  88. )
  89. self.activation = ACT2FN[config.feat_extract_activation]
  90. self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
  91. def forward(self, hidden_states):
  92. hidden_states = self.conv(hidden_states)
  93. hidden_states = self.layer_norm(hidden_states)
  94. hidden_states = self.activation(hidden_states)
  95. return hidden_states
  96. class SEWPositionalConvEmbedding(nn.Module):
  97. def __init__(self, config):
  98. super().__init__()
  99. self.conv = nn.Conv1d(
  100. config.hidden_size,
  101. config.hidden_size,
  102. kernel_size=config.num_conv_pos_embeddings,
  103. padding=config.num_conv_pos_embeddings // 2,
  104. groups=config.num_conv_pos_embedding_groups,
  105. stride=config.squeeze_factor,
  106. )
  107. weight_norm = nn.utils.weight_norm
  108. if hasattr(nn.utils.parametrizations, "weight_norm"):
  109. weight_norm = nn.utils.parametrizations.weight_norm
  110. if is_deepspeed_zero3_enabled():
  111. import deepspeed
  112. with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
  113. self.conv = weight_norm(self.conv, name="weight", dim=2)
  114. if hasattr(self.conv, "parametrizations"):
  115. weight_g = self.conv.parametrizations.weight.original0
  116. weight_v = self.conv.parametrizations.weight.original1
  117. else:
  118. weight_g = self.conv.weight_g
  119. weight_v = self.conv.weight_v
  120. deepspeed.zero.register_external_parameter(self, weight_v)
  121. deepspeed.zero.register_external_parameter(self, weight_g)
  122. else:
  123. self.conv = weight_norm(self.conv, name="weight", dim=2)
  124. self.padding = SEWSamePadLayer(config.num_conv_pos_embeddings)
  125. self.activation = ACT2FN[config.feat_extract_activation]
  126. def forward(self, hidden_states):
  127. hidden_states = self.conv(hidden_states)
  128. hidden_states = self.padding(hidden_states)
  129. hidden_states = self.activation(hidden_states)
  130. return hidden_states
  131. class SEWSamePadLayer(nn.Module):
  132. def __init__(self, num_conv_pos_embeddings):
  133. super().__init__()
  134. self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
  135. def forward(self, hidden_states):
  136. if self.num_pad_remove > 0:
  137. hidden_states = hidden_states[:, :, : -self.num_pad_remove]
  138. return hidden_states
  139. class SEWUpsampling(nn.Module):
  140. def __init__(self, config):
  141. super().__init__()
  142. self.projection = nn.Linear(config.hidden_size, config.hidden_size * config.squeeze_factor)
  143. self.activation = ACT2FN[config.feat_extract_activation]
  144. self.squeeze_factor = config.squeeze_factor
  145. def forward(self, hidden_states):
  146. hidden_states = self.projection(hidden_states)
  147. hidden_states = self.activation(hidden_states)
  148. if self.squeeze_factor > 1:
  149. # transform embedding channels to sequence length
  150. bsz, src_len, src_embed_dim = hidden_states.size()
  151. tgt_len = src_len * self.squeeze_factor
  152. tgt_embed_dim = src_embed_dim // self.squeeze_factor
  153. hidden_states = hidden_states.reshape(bsz, src_len, self.squeeze_factor, tgt_embed_dim)
  154. hidden_states = hidden_states.reshape(bsz, tgt_len, tgt_embed_dim)
  155. return hidden_states
  156. class SEWFeatureEncoder(nn.Module):
  157. """Construct the features from raw audio waveform"""
  158. def __init__(self, config):
  159. super().__init__()
  160. if config.feat_extract_norm == "group":
  161. conv_layers = [SEWGroupNormConvLayer(config, layer_id=0)] + [
  162. SEWNoLayerNormConvLayer(config, layer_id=i + 1) for i in range(config.num_feat_extract_layers - 1)
  163. ]
  164. elif config.feat_extract_norm == "layer":
  165. conv_layers = [SEWLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)]
  166. else:
  167. raise ValueError(
  168. f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
  169. )
  170. self.conv_layers = nn.ModuleList(conv_layers)
  171. self.gradient_checkpointing = False
  172. self._requires_grad = True
  173. def _freeze_parameters(self):
  174. for param in self.parameters():
  175. param.requires_grad = False
  176. self._requires_grad = False
  177. def forward(self, input_values):
  178. hidden_states = input_values[:, None]
  179. # make sure hidden_states require grad for gradient_checkpointing
  180. if self._requires_grad and self.training:
  181. hidden_states.requires_grad = True
  182. for conv_layer in self.conv_layers:
  183. hidden_states = conv_layer(hidden_states)
  184. return hidden_states
  185. def eager_attention_forward(
  186. module: nn.Module,
  187. query: torch.Tensor,
  188. key: torch.Tensor,
  189. value: torch.Tensor,
  190. attention_mask: Optional[torch.Tensor],
  191. scaling: Optional[float] = None,
  192. dropout: float = 0.0,
  193. head_mask: Optional[torch.Tensor] = None,
  194. **kwargs,
  195. ):
  196. if scaling is None:
  197. scaling = query.size(-1) ** -0.5
  198. attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
  199. if attention_mask is not None:
  200. attn_weights = attn_weights + attention_mask
  201. attn_weights = nn.functional.softmax(attn_weights, dim=-1)
  202. if head_mask is not None:
  203. attn_weights = attn_weights * head_mask.view(1, -1, 1, 1)
  204. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  205. attn_output = torch.matmul(attn_weights, value)
  206. attn_output = attn_output.transpose(1, 2).contiguous()
  207. return attn_output, attn_weights
  208. class SEWAttention(nn.Module):
  209. """Multi-headed attention from 'Attention Is All You Need' paper"""
  210. def __init__(
  211. self,
  212. embed_dim: int,
  213. num_heads: int,
  214. dropout: float = 0.0,
  215. is_decoder: bool = False,
  216. bias: bool = True,
  217. is_causal: bool = False,
  218. config: Optional[SEWConfig] = None,
  219. ):
  220. super().__init__()
  221. self.embed_dim = embed_dim
  222. self.num_heads = num_heads
  223. self.dropout = dropout
  224. self.head_dim = embed_dim // num_heads
  225. self.config = config
  226. if (self.head_dim * num_heads) != self.embed_dim:
  227. raise ValueError(
  228. f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
  229. f" and `num_heads`: {num_heads})."
  230. )
  231. self.scaling = self.head_dim**-0.5
  232. self.is_decoder = is_decoder
  233. self.is_causal = is_causal
  234. self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  235. self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  236. self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  237. self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  238. def forward(
  239. self,
  240. hidden_states: torch.Tensor,
  241. key_value_states: Optional[torch.Tensor] = None,
  242. attention_mask: Optional[torch.Tensor] = None,
  243. layer_head_mask: Optional[torch.Tensor] = None,
  244. output_attentions: Optional[bool] = False,
  245. # TODO: we need a refactor so that the different attention modules can get their specific kwargs
  246. # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
  247. **kwargs: Unpack[FlashAttentionKwargs],
  248. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  249. """Input shape: Batch x Time x Channel"""
  250. # if key_value_states are provided this layer is used as a cross-attention layer
  251. # for the decoder
  252. is_cross_attention = key_value_states is not None
  253. # determine input shapes
  254. bsz, tgt_len = hidden_states.shape[:-1]
  255. src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
  256. q_input_shape = (bsz, tgt_len, -1, self.head_dim)
  257. kv_input_shape = (bsz, src_len, -1, self.head_dim)
  258. # get query proj
  259. query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
  260. current_states = key_value_states if is_cross_attention else hidden_states
  261. key_states = self.k_proj(current_states).view(*kv_input_shape).transpose(1, 2)
  262. value_states = self.v_proj(current_states).view(*kv_input_shape).transpose(1, 2)
  263. attention_interface: Callable = eager_attention_forward
  264. if self.config._attn_implementation != "eager":
  265. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  266. attn_output, attn_weights = attention_interface(
  267. self,
  268. query_states,
  269. key_states,
  270. value_states,
  271. attention_mask,
  272. dropout=0.0 if not self.training else self.dropout,
  273. scaling=self.scaling,
  274. output_attentions=output_attentions,
  275. head_mask=layer_head_mask,
  276. **kwargs,
  277. )
  278. attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
  279. attn_output = self.out_proj(attn_output)
  280. return attn_output, attn_weights, None
  281. class SEWFeedForward(nn.Module):
  282. def __init__(self, config):
  283. super().__init__()
  284. self.intermediate_dropout = nn.Dropout(config.activation_dropout)
  285. self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
  286. if isinstance(config.hidden_act, str):
  287. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  288. else:
  289. self.intermediate_act_fn = config.hidden_act
  290. self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
  291. self.output_dropout = nn.Dropout(config.hidden_dropout)
  292. def forward(self, hidden_states):
  293. hidden_states = self.intermediate_dense(hidden_states)
  294. hidden_states = self.intermediate_act_fn(hidden_states)
  295. hidden_states = self.intermediate_dropout(hidden_states)
  296. hidden_states = self.output_dense(hidden_states)
  297. hidden_states = self.output_dropout(hidden_states)
  298. return hidden_states
  299. class SEWEncoderLayer(GradientCheckpointingLayer):
  300. def __init__(self, config):
  301. super().__init__()
  302. self.attention = SEWAttention(
  303. embed_dim=config.hidden_size,
  304. num_heads=config.num_attention_heads,
  305. dropout=config.attention_dropout,
  306. is_decoder=False,
  307. config=config,
  308. )
  309. self.dropout = nn.Dropout(config.hidden_dropout)
  310. self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  311. self.feed_forward = SEWFeedForward(config)
  312. self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  313. def forward(self, hidden_states, attention_mask=None, output_attentions=False):
  314. attn_residual = hidden_states
  315. hidden_states, attn_weights, _ = self.attention(
  316. hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
  317. )
  318. hidden_states = self.dropout(hidden_states)
  319. hidden_states = attn_residual + hidden_states
  320. hidden_states = self.layer_norm(hidden_states)
  321. hidden_states = hidden_states + self.feed_forward(hidden_states)
  322. hidden_states = self.final_layer_norm(hidden_states)
  323. outputs = (hidden_states,)
  324. if output_attentions:
  325. outputs += (attn_weights,)
  326. return outputs
  327. class SEWEncoder(nn.Module):
  328. def __init__(self, config):
  329. super().__init__()
  330. self.config = config
  331. self.pos_conv_embed = SEWPositionalConvEmbedding(config)
  332. self.pool = nn.AvgPool1d(config.squeeze_factor, config.squeeze_factor)
  333. self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  334. self.dropout = nn.Dropout(config.hidden_dropout)
  335. self.layers = nn.ModuleList([SEWEncoderLayer(config) for _ in range(config.num_hidden_layers)])
  336. self.upsample = SEWUpsampling(config)
  337. self.gradient_checkpointing = False
  338. def forward(
  339. self,
  340. hidden_states,
  341. attention_mask=None,
  342. output_attentions=False,
  343. output_hidden_states=False,
  344. return_dict=True,
  345. ):
  346. all_hidden_states = () if output_hidden_states else None
  347. all_self_attentions = () if output_attentions else None
  348. if attention_mask is not None:
  349. expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
  350. if self.config._attn_implementation == "flash_attention_2":
  351. # make sure padded tokens output 0
  352. hidden_states[~expand_attention_mask] = 0.0
  353. # 2d mask is passed through the layers
  354. attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
  355. else:
  356. # make sure padded tokens output 0
  357. hidden_states[~expand_attention_mask] = 0.0
  358. input_lengths = (attention_mask.long()).sum(-1)
  359. # apply pooling formula to get real output_lengths
  360. output_lengths = input_lengths // self.config.squeeze_factor
  361. max_encoder_length = hidden_states.shape[1] // self.config.squeeze_factor
  362. attention_ids = (
  363. torch.arange(0, max_encoder_length, device=output_lengths.device)
  364. .view(1, -1)
  365. .expand(output_lengths.shape[0], -1)
  366. )
  367. attention_mask = (attention_ids < output_lengths.view(-1, 1)).long()
  368. # extend attention_mask
  369. attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
  370. attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
  371. attention_mask = attention_mask.expand(
  372. attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
  373. )
  374. n_input_timesteps = hidden_states.shape[1]
  375. hidden_states = hidden_states.transpose(1, 2)
  376. position_embeddings = self.pos_conv_embed(hidden_states)
  377. pooled_hidden_states = self.pool(hidden_states)
  378. min_length = min(position_embeddings.size(-1), pooled_hidden_states.size(-1))
  379. hidden_states = pooled_hidden_states[..., :min_length] + position_embeddings[..., :min_length]
  380. hidden_states = hidden_states.transpose(1, 2)
  381. hidden_states = self.layer_norm(hidden_states)
  382. hidden_states = self.dropout(hidden_states)
  383. synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
  384. for layer in self.layers:
  385. if output_hidden_states:
  386. all_hidden_states = all_hidden_states + (hidden_states,)
  387. # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
  388. dropout_probability = torch.rand([])
  389. skip_the_layer = self.training and dropout_probability < self.config.layerdrop
  390. if not skip_the_layer or synced_gpus:
  391. # under fsdp or deepspeed zero3 all gpus must run in sync
  392. layer_outputs = layer(
  393. hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
  394. )
  395. hidden_states = layer_outputs[0]
  396. if skip_the_layer:
  397. layer_outputs = (None, None)
  398. if output_attentions:
  399. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  400. if output_hidden_states:
  401. all_hidden_states = all_hidden_states + (hidden_states,)
  402. hidden_states = self.upsample(hidden_states)
  403. if hidden_states.shape[1] < n_input_timesteps:
  404. hidden_states = nn.functional.pad(hidden_states, (0, 0, 0, n_input_timesteps - hidden_states.shape[1]))
  405. if not return_dict:
  406. return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
  407. return BaseModelOutput(
  408. last_hidden_state=hidden_states,
  409. hidden_states=all_hidden_states,
  410. attentions=all_self_attentions,
  411. )
  412. @auto_docstring
  413. class SEWPreTrainedModel(PreTrainedModel):
  414. config: SEWConfig
  415. base_model_prefix = "sew"
  416. main_input_name = "input_values"
  417. supports_gradient_checkpointing = True
  418. _supports_flash_attn = True
  419. _supports_sdpa = True
  420. _supports_flex_attn = False # needs a proper look into the mask creation
  421. def _init_weights(self, module):
  422. """Initialize the weights"""
  423. if isinstance(module, SEWPositionalConvEmbedding):
  424. nn.init.normal_(
  425. module.conv.weight,
  426. mean=0,
  427. std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
  428. )
  429. nn.init.constant_(module.conv.bias, 0)
  430. elif isinstance(module, nn.Linear):
  431. # Slightly different from the TF version which uses truncated_normal for initialization
  432. # cf https://github.com/pytorch/pytorch/pull/5617
  433. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  434. elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
  435. module.bias.data.zero_()
  436. module.weight.data.fill_(1.0)
  437. elif isinstance(module, nn.Conv1d):
  438. if is_deepspeed_zero3_enabled():
  439. import deepspeed
  440. if hasattr(module, "weight_v") and hasattr(module, "weight_g"):
  441. with deepspeed.zero.GatheredParameters([module.weight_v, module.weight_g], modifier_rank=0):
  442. nn.init.kaiming_normal_(module.weight.data)
  443. else:
  444. with deepspeed.zero.GatheredParameters(module.weight, modifier_rank=0):
  445. nn.init.kaiming_normal_(module.weight.data)
  446. else:
  447. nn.init.kaiming_normal_(module.weight.data)
  448. if isinstance(module, (nn.Linear, nn.Conv1d)) and module.bias is not None:
  449. module.bias.data.zero_()
  450. def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
  451. """
  452. Computes the output length of the convolutional layers
  453. """
  454. def _conv_out_length(input_length, kernel_size, stride):
  455. # 1D convolutional layer output length formula taken
  456. # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
  457. return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
  458. for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
  459. input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
  460. return input_lengths
  461. def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
  462. output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
  463. batch_size = attention_mask.shape[0]
  464. attention_mask = torch.zeros(
  465. (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
  466. )
  467. # these two operations makes sure that all values before the output lengths idxs are attended to
  468. attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
  469. attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
  470. return attention_mask
  471. def _compute_mask_indices(
  472. shape: tuple[int, int],
  473. mask_prob: float,
  474. mask_length: int,
  475. attention_mask: Optional[torch.LongTensor] = None,
  476. min_masks: int = 0,
  477. ) -> np.ndarray:
  478. """
  479. Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
  480. ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
  481. CPU as part of the preprocessing during training.
  482. Args:
  483. shape: The shape for which to compute masks. This should be of a tuple of size 2 where
  484. the first element is the batch size and the second element is the length of the axis to span.
  485. mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
  486. independently generated mask spans of length `mask_length` is computed by
  487. `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
  488. actual percentage will be smaller.
  489. mask_length: size of the mask
  490. min_masks: minimum number of masked spans
  491. attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
  492. each batch dimension.
  493. """
  494. batch_size, sequence_length = shape
  495. if mask_length < 1:
  496. raise ValueError("`mask_length` has to be bigger than 0.")
  497. if mask_length > sequence_length:
  498. raise ValueError(
  499. f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
  500. f" and `sequence_length`: {sequence_length}`"
  501. )
  502. # epsilon is used for probabilistic rounding
  503. epsilon = np.random.rand(1).item()
  504. def compute_num_masked_span(input_length):
  505. """Given input length, compute how many spans should be masked"""
  506. num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
  507. num_masked_span = max(num_masked_span, min_masks)
  508. # make sure num masked span <= sequence_length
  509. if num_masked_span * mask_length > sequence_length:
  510. num_masked_span = sequence_length // mask_length
  511. # make sure num_masked span is also <= input_length - (mask_length - 1)
  512. if input_length - (mask_length - 1) < num_masked_span:
  513. num_masked_span = max(input_length - (mask_length - 1), 0)
  514. return num_masked_span
  515. # compute number of masked spans in batch
  516. input_lengths = (
  517. attention_mask.detach().sum(-1).tolist()
  518. if attention_mask is not None
  519. else [sequence_length for _ in range(batch_size)]
  520. )
  521. # SpecAugment mask to fill
  522. spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
  523. spec_aug_mask_idxs = []
  524. max_num_masked_span = compute_num_masked_span(sequence_length)
  525. if max_num_masked_span == 0:
  526. return spec_aug_mask
  527. for input_length in input_lengths:
  528. # compute num of masked spans for this input
  529. num_masked_span = compute_num_masked_span(input_length)
  530. # get random indices to mask
  531. spec_aug_mask_idx = np.random.choice(
  532. np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
  533. )
  534. # pick first sampled index that will serve as a dummy index to pad vector
  535. # to ensure same dimension for all batches due to probabilistic rounding
  536. # Picking first sample just pads those vectors twice.
  537. if len(spec_aug_mask_idx) == 0:
  538. # this case can only happen if `input_length` is strictly smaller then
  539. # `sequence_length` in which case the last token has to be a padding
  540. # token which we can use as a dummy mask id
  541. dummy_mask_idx = sequence_length - 1
  542. else:
  543. dummy_mask_idx = spec_aug_mask_idx[0]
  544. spec_aug_mask_idx = np.concatenate(
  545. [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
  546. )
  547. spec_aug_mask_idxs.append(spec_aug_mask_idx)
  548. spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
  549. # expand masked indices to masked spans
  550. spec_aug_mask_idxs = np.broadcast_to(
  551. spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
  552. )
  553. spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
  554. # add offset to the starting indexes so that indexes now create a span
  555. offsets = np.arange(mask_length)[None, None, :]
  556. offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
  557. batch_size, max_num_masked_span * mask_length
  558. )
  559. spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
  560. # ensure that we cannot have indices larger than sequence_length
  561. if spec_aug_mask_idxs.max() > sequence_length - 1:
  562. spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
  563. # scatter indices to mask
  564. np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
  565. return spec_aug_mask
  566. @auto_docstring
  567. class SEWModel(SEWPreTrainedModel):
  568. def __init__(self, config: SEWConfig):
  569. super().__init__(config)
  570. self.config = config
  571. self.feature_extractor = SEWFeatureEncoder(config)
  572. self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
  573. self.project_features = config.conv_dim[-1] != config.hidden_size
  574. if self.project_features:
  575. self.feature_projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
  576. self.feature_dropout = nn.Dropout(config.feat_proj_dropout)
  577. if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
  578. self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
  579. self.encoder = SEWEncoder(config)
  580. # Initialize weights and apply final processing
  581. self.post_init()
  582. # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Model._mask_hidden_states
  583. def _mask_hidden_states(
  584. self,
  585. hidden_states: torch.FloatTensor,
  586. mask_time_indices: Optional[torch.FloatTensor] = None,
  587. attention_mask: Optional[torch.LongTensor] = None,
  588. ):
  589. """
  590. Masks extracted features along time axis and/or along feature axis according to
  591. [SpecAugment](https://huggingface.co/papers/1904.08779).
  592. """
  593. # `config.apply_spec_augment` can set masking to False
  594. if not getattr(self.config, "apply_spec_augment", True):
  595. return hidden_states
  596. # generate indices & apply SpecAugment along time axis
  597. batch_size, sequence_length, hidden_size = hidden_states.size()
  598. if mask_time_indices is not None:
  599. # apply SpecAugment along time axis with given mask_time_indices
  600. hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
  601. elif self.config.mask_time_prob > 0 and self.training:
  602. mask_time_indices = _compute_mask_indices(
  603. (batch_size, sequence_length),
  604. mask_prob=self.config.mask_time_prob,
  605. mask_length=self.config.mask_time_length,
  606. attention_mask=attention_mask,
  607. min_masks=self.config.mask_time_min_masks,
  608. )
  609. mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
  610. hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
  611. if self.config.mask_feature_prob > 0 and self.training:
  612. # generate indices & apply SpecAugment along feature axis
  613. mask_feature_indices = _compute_mask_indices(
  614. (batch_size, hidden_size),
  615. mask_prob=self.config.mask_feature_prob,
  616. mask_length=self.config.mask_feature_length,
  617. min_masks=self.config.mask_feature_min_masks,
  618. )
  619. mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
  620. mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
  621. hidden_states[mask_feature_indices] = 0
  622. return hidden_states
  623. @auto_docstring
  624. def forward(
  625. self,
  626. input_values: Optional[torch.Tensor],
  627. attention_mask: Optional[torch.Tensor] = None,
  628. mask_time_indices: Optional[torch.FloatTensor] = None,
  629. output_attentions: Optional[bool] = None,
  630. output_hidden_states: Optional[bool] = None,
  631. return_dict: Optional[bool] = None,
  632. ) -> Union[tuple, BaseModelOutput]:
  633. r"""
  634. mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
  635. Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
  636. masked extracted features in *config.proj_codevector_dim* space.
  637. """
  638. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  639. output_hidden_states = (
  640. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  641. )
  642. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  643. extract_features = self.feature_extractor(input_values)
  644. extract_features = extract_features.transpose(1, 2)
  645. extract_features = self.layer_norm(extract_features)
  646. if self.project_features:
  647. extract_features = self.feature_projection(extract_features)
  648. hidden_states = self.feature_dropout(extract_features)
  649. if attention_mask is not None:
  650. # compute reduced attention_mask corresponding to feature vectors
  651. attention_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
  652. hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices)
  653. encoder_outputs = self.encoder(
  654. hidden_states,
  655. attention_mask=attention_mask,
  656. output_attentions=output_attentions,
  657. output_hidden_states=output_hidden_states,
  658. return_dict=return_dict,
  659. )
  660. hidden_states = encoder_outputs[0]
  661. if not return_dict:
  662. return (hidden_states,) + encoder_outputs[1:]
  663. return BaseModelOutput(
  664. last_hidden_state=hidden_states,
  665. hidden_states=encoder_outputs.hidden_states,
  666. attentions=encoder_outputs.attentions,
  667. )
  668. _HIDDEN_STATES_START_POSITION = 1
  669. @auto_docstring(
  670. custom_intro="""
  671. SEW Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
  672. """
  673. )
  674. class SEWForCTC(SEWPreTrainedModel):
  675. def __init__(self, config, target_lang: Optional[str] = None):
  676. r"""
  677. target_lang (`str`, *optional*):
  678. Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
  679. adapter.<lang>.bin. Only relevant when using an instance of [`SEWForCTC`] with adapters. Uses 'eng' by
  680. default.
  681. """
  682. super().__init__(config)
  683. self.sew = SEWModel(config)
  684. self.dropout = nn.Dropout(config.final_dropout)
  685. self.target_lang = target_lang
  686. if config.vocab_size is None:
  687. raise ValueError(
  688. f"You are trying to instantiate {self.__class__} with a configuration that "
  689. "does not define the vocabulary size of the language model head. Please "
  690. "instantiate the model as follows: `SEWForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
  691. "or define `vocab_size` of your model's configuration."
  692. )
  693. output_hidden_size = (
  694. config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
  695. )
  696. self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
  697. # Initialize weights and apply final processing
  698. self.post_init()
  699. def tie_weights(self):
  700. """
  701. This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
  702. passing `target_lang=...` to `from_pretrained(...)`.
  703. This method is **not** supposed to be called by the user and is prone to be changed in the future.
  704. """
  705. # Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to
  706. # correctly load adapter layers for SEW so that we do not have to introduce a new API to
  707. # [`PreTrainedModel`]. While slightly hacky, SEW never has to tie input and output embeddings, so that it is
  708. # ok to repurpose this function here.
  709. target_lang = self.target_lang
  710. if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None:
  711. raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.")
  712. elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None:
  713. logger.info("By default `target_lang` is set to 'eng'.")
  714. elif target_lang is not None:
  715. self.load_adapter(target_lang, force_load=True)
  716. def freeze_feature_extractor(self):
  717. """
  718. Calling this function will disable the gradient computation for the feature encoder so that its parameter will
  719. not be updated during training.
  720. """
  721. warnings.warn(
  722. "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
  723. "Please use the equivalent `freeze_feature_encoder` method instead.",
  724. FutureWarning,
  725. )
  726. self.freeze_feature_encoder()
  727. def freeze_feature_encoder(self):
  728. """
  729. Calling this function will disable the gradient computation for the feature encoder so that its parameter will
  730. not be updated during training.
  731. """
  732. self.sew.feature_extractor._freeze_parameters()
  733. def freeze_base_model(self):
  734. """
  735. Calling this function will disable the gradient computation for the base model so that its parameters will not
  736. be updated during training. Only the classification head will be updated.
  737. """
  738. for param in self.sew.parameters():
  739. param.requires_grad = False
  740. @auto_docstring
  741. def forward(
  742. self,
  743. input_values: Optional[torch.Tensor],
  744. attention_mask: Optional[torch.Tensor] = None,
  745. output_attentions: Optional[bool] = None,
  746. output_hidden_states: Optional[bool] = None,
  747. return_dict: Optional[bool] = None,
  748. labels: Optional[torch.Tensor] = None,
  749. ) -> Union[tuple, CausalLMOutput]:
  750. r"""
  751. labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
  752. Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
  753. the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
  754. All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
  755. config.vocab_size - 1]`.
  756. """
  757. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  758. if labels is not None and labels.max() >= self.config.vocab_size:
  759. raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
  760. outputs = self.sew(
  761. input_values,
  762. attention_mask=attention_mask,
  763. output_attentions=output_attentions,
  764. output_hidden_states=output_hidden_states,
  765. return_dict=return_dict,
  766. )
  767. hidden_states = outputs[0]
  768. hidden_states = self.dropout(hidden_states)
  769. logits = self.lm_head(hidden_states)
  770. loss = None
  771. if labels is not None:
  772. # retrieve loss input_lengths from attention_mask
  773. attention_mask = (
  774. attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
  775. )
  776. input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
  777. # assuming that padded tokens are filled with -100
  778. # when not being attended to
  779. labels_mask = labels >= 0
  780. target_lengths = labels_mask.sum(-1)
  781. flattened_targets = labels.masked_select(labels_mask)
  782. # ctc_loss doesn't support fp16
  783. log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
  784. with torch.backends.cudnn.flags(enabled=False):
  785. loss = nn.functional.ctc_loss(
  786. log_probs,
  787. flattened_targets,
  788. input_lengths,
  789. target_lengths,
  790. blank=self.config.pad_token_id,
  791. reduction=self.config.ctc_loss_reduction,
  792. zero_infinity=self.config.ctc_zero_infinity,
  793. )
  794. if not return_dict:
  795. output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
  796. return ((loss,) + output) if loss is not None else output
  797. return CausalLMOutput(
  798. loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
  799. )
  800. @auto_docstring(
  801. custom_intro="""
  802. SEW Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
  803. SUPERB Keyword Spotting.
  804. """
  805. )
  806. class SEWForSequenceClassification(SEWPreTrainedModel):
  807. def __init__(self, config):
  808. super().__init__(config)
  809. if hasattr(config, "add_adapter") and config.add_adapter:
  810. raise ValueError(
  811. "Sequence classification does not support the use of SEW adapters (config.add_adapter=True)"
  812. )
  813. self.sew = SEWModel(config)
  814. num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
  815. if config.use_weighted_layer_sum:
  816. self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
  817. self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
  818. self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
  819. # Initialize weights and apply final processing
  820. self.post_init()
  821. def freeze_feature_extractor(self):
  822. """
  823. Calling this function will disable the gradient computation for the feature encoder so that its parameters will
  824. not be updated during training.
  825. """
  826. warnings.warn(
  827. "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
  828. "Please use the equivalent `freeze_feature_encoder` method instead.",
  829. FutureWarning,
  830. )
  831. self.freeze_feature_encoder()
  832. def freeze_feature_encoder(self):
  833. """
  834. Calling this function will disable the gradient computation for the feature encoder so that its parameter will
  835. not be updated during training.
  836. """
  837. self.sew.feature_extractor._freeze_parameters()
  838. def freeze_base_model(self):
  839. """
  840. Calling this function will disable the gradient computation for the base model so that its parameters will not
  841. be updated during training. Only the classification head will be updated.
  842. """
  843. for param in self.sew.parameters():
  844. param.requires_grad = False
  845. @auto_docstring
  846. def forward(
  847. self,
  848. input_values: Optional[torch.Tensor],
  849. attention_mask: Optional[torch.Tensor] = None,
  850. output_attentions: Optional[bool] = None,
  851. output_hidden_states: Optional[bool] = None,
  852. return_dict: Optional[bool] = None,
  853. labels: Optional[torch.Tensor] = None,
  854. ) -> Union[tuple, SequenceClassifierOutput]:
  855. r"""
  856. input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
  857. Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
  858. into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
  859. (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
  860. To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
  861. into a tensor of type `torch.FloatTensor`. See [`SEWProcessor.__call__`] for details.
  862. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  863. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  864. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  865. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  866. """
  867. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  868. output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
  869. outputs = self.sew(
  870. input_values,
  871. attention_mask=attention_mask,
  872. output_attentions=output_attentions,
  873. output_hidden_states=output_hidden_states,
  874. return_dict=return_dict,
  875. )
  876. if self.config.use_weighted_layer_sum:
  877. hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
  878. hidden_states = torch.stack(hidden_states, dim=1)
  879. norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
  880. hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
  881. else:
  882. hidden_states = outputs[0]
  883. hidden_states = self.projector(hidden_states)
  884. if attention_mask is None:
  885. pooled_output = hidden_states.mean(dim=1)
  886. else:
  887. padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
  888. expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
  889. hidden_states[~expand_padding_mask] = 0.0
  890. pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
  891. logits = self.classifier(pooled_output)
  892. loss = None
  893. if labels is not None:
  894. loss_fct = CrossEntropyLoss()
  895. loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
  896. if not return_dict:
  897. output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
  898. return ((loss,) + output) if loss is not None else output
  899. return SequenceClassifierOutput(
  900. loss=loss,
  901. logits=logits,
  902. hidden_states=outputs.hidden_states,
  903. attentions=outputs.attentions,
  904. )
  905. __all__ = ["SEWForCTC", "SEWForSequenceClassification", "SEWModel", "SEWPreTrainedModel"]