modeling_moonshine.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/moonshine/modular_moonshine.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_moonshine.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. from typing import Callable, Optional, Union
  21. import numpy as np
  22. import torch
  23. import torch.nn as nn
  24. from transformers.utils.generic import OutputRecorder, check_model_inputs
  25. from ...activations import ACT2FN
  26. from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
  27. from ...generation import GenerationMixin
  28. from ...masking_utils import create_causal_mask
  29. from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
  30. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  31. from ...modeling_layers import GradientCheckpointingLayer
  32. from ...modeling_outputs import (
  33. BaseModelOutput,
  34. BaseModelOutputWithPast,
  35. BaseModelOutputWithPastAndCrossAttentions,
  36. Seq2SeqLMOutput,
  37. Seq2SeqModelOutput,
  38. )
  39. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  40. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  41. from ...processing_utils import Unpack
  42. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
  43. from ...utils.deprecation import deprecate_kwarg
  44. from .configuration_moonshine import MoonshineConfig
  45. class MoonshineEncoderMLP(nn.Module):
  46. def __init__(self, config, hidden_act):
  47. super().__init__()
  48. self.config = config
  49. self.activation_fn = ACT2FN[hidden_act]
  50. self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
  51. self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
  52. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  53. hidden_states = self.fc1(hidden_states)
  54. hidden_states = self.activation_fn(hidden_states)
  55. hidden_states = self.fc2(hidden_states)
  56. return hidden_states
  57. class MoonshineDecoderMLP(nn.Module):
  58. def __init__(self, config, hidden_act):
  59. super().__init__()
  60. self.config = config
  61. self.activation_fn = ACT2FN[hidden_act]
  62. self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size * 2)
  63. self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
  64. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  65. hidden_states = self.fc1(hidden_states)
  66. hidden_states, gate = hidden_states.chunk(2, dim=-1)
  67. hidden_states = self.activation_fn(gate) * hidden_states
  68. hidden_states = self.fc2(hidden_states)
  69. return hidden_states
  70. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  71. """
  72. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  73. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  74. """
  75. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  76. if n_rep == 1:
  77. return hidden_states
  78. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  79. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  80. def eager_attention_forward(
  81. module: nn.Module,
  82. query: torch.Tensor,
  83. key: torch.Tensor,
  84. value: torch.Tensor,
  85. attention_mask: Optional[torch.Tensor],
  86. scaling: float,
  87. dropout: float = 0.0,
  88. **kwargs: Unpack[TransformersKwargs],
  89. ):
  90. key_states = repeat_kv(key, module.num_key_value_groups)
  91. value_states = repeat_kv(value, module.num_key_value_groups)
  92. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  93. if attention_mask is not None:
  94. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  95. attn_weights = attn_weights + causal_mask
  96. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  97. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  98. attn_output = torch.matmul(attn_weights, value_states)
  99. attn_output = attn_output.transpose(1, 2).contiguous()
  100. return attn_output, attn_weights
  101. def rotate_half(x):
  102. """Rotates half the hidden dims of the input."""
  103. x1 = x[..., 0::2]
  104. x2 = x[..., 1::2]
  105. return torch.stack((-x2, x1), dim=-1).flatten(-2)
  106. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  107. """Applies Rotary Position Embedding to the query and key tensors.
  108. Args:
  109. q (`torch.Tensor`): The query tensor.
  110. k (`torch.Tensor`): The key tensor.
  111. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  112. sin (`torch.Tensor`): The sine part of the rotary embedding.
  113. position_ids (`torch.Tensor`, *optional*):
  114. Deprecated and unused.
  115. unsqueeze_dim (`int`, *optional*, defaults to 1):
  116. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  117. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  118. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  119. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  120. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  121. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  122. Returns:
  123. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  124. """
  125. cos = cos.unsqueeze(unsqueeze_dim)
  126. sin = sin.unsqueeze(unsqueeze_dim)
  127. # Interleave them instead of usual shape
  128. cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
  129. sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
  130. # Keep half or full tensor for later concatenation
  131. rotary_dim = cos.shape[-1]
  132. q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
  133. k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
  134. # Apply rotary embeddings on the first half or full tensor
  135. q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
  136. k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
  137. # Concatenate back to full shape
  138. q_embed = torch.cat([q_embed, q_pass], dim=-1)
  139. k_embed = torch.cat([k_embed, k_pass], dim=-1)
  140. return q_embed, k_embed
  141. class MoonshineAttention(nn.Module):
  142. """Multi-headed attention from 'Attention Is All You Need' paper"""
  143. def __init__(
  144. self,
  145. config: MoonshineConfig,
  146. layer_idx: int,
  147. is_causal: bool,
  148. num_attention_heads: int,
  149. num_key_value_heads: int,
  150. ):
  151. super().__init__()
  152. config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads})
  153. self.config = config
  154. self.layer_idx = layer_idx
  155. self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
  156. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  157. self.scaling = self.head_dim**-0.5
  158. self.attention_dropout = config.attention_dropout
  159. self.is_causal = is_causal
  160. self.q_proj = nn.Linear(
  161. config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
  162. )
  163. self.k_proj = nn.Linear(
  164. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  165. )
  166. self.v_proj = nn.Linear(
  167. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  168. )
  169. self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
  170. # Pad head dimension to the next specified multiple.
  171. if self.config.pad_head_dim_to_multiple_of is not None:
  172. target_multiple = self.config.pad_head_dim_to_multiple_of
  173. target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple)
  174. self.head_dim_padding = target_head_dim - self.head_dim
  175. else:
  176. self.head_dim_padding = 0
  177. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  178. def forward(
  179. self,
  180. hidden_states: torch.Tensor,
  181. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  182. attention_mask: Optional[torch.Tensor] = None,
  183. past_key_values: Optional[Cache] = None,
  184. cache_position: Optional[torch.LongTensor] = None,
  185. key_value_states: Optional[torch.Tensor] = None,
  186. **kwargs: Unpack[FlashAttentionKwargs],
  187. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  188. bsz, q_len = hidden_states.shape[:-1]
  189. query_states = (
  190. self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2)
  191. )
  192. is_cross_attention = key_value_states is not None
  193. if past_key_values is not None:
  194. is_updated = past_key_values.is_updated.get(self.layer_idx)
  195. if is_cross_attention:
  196. # after the first generated id, we can subsequently re-use all key/value_states from cache
  197. past_key_values.is_updated[self.layer_idx] = True
  198. past_key_values = past_key_values.cross_attention_cache
  199. else:
  200. past_key_values = past_key_values.self_attention_cache
  201. # use key_value_states if cross attention
  202. current_states = key_value_states if key_value_states is not None else hidden_states
  203. if is_cross_attention and past_key_values and is_updated:
  204. key_states = past_key_values.layers[self.layer_idx].keys
  205. value_states = past_key_values.layers[self.layer_idx].values
  206. else:
  207. key_states = (
  208. self.k_proj(current_states)
  209. .view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
  210. .transpose(1, 2)
  211. )
  212. value_states = (
  213. self.v_proj(current_states)
  214. .view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
  215. .transpose(1, 2)
  216. )
  217. if is_cross_attention and past_key_values is not None:
  218. key_states, value_states = past_key_values.update(
  219. key_states, value_states, self.layer_idx, {"cache_position": cache_position}
  220. )
  221. if not is_cross_attention:
  222. cos, sin = position_embeddings
  223. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  224. if past_key_values is not None:
  225. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  226. key_states, value_states = past_key_values.update(
  227. key_states, value_states, self.layer_idx, cache_kwargs
  228. )
  229. attention_interface: Callable = eager_attention_forward
  230. if self.config._attn_implementation != "eager":
  231. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  232. is_causal = self.is_causal and attention_mask is None and q_len > 1
  233. if self.head_dim_padding > 0:
  234. query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding))
  235. key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding))
  236. value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding))
  237. attn_output, attn_weights = attention_interface(
  238. self,
  239. query_states,
  240. key_states,
  241. value_states,
  242. attention_mask,
  243. dropout=0.0 if not self.training else self.attention_dropout,
  244. scaling=self.scaling,
  245. is_causal=is_causal,
  246. **kwargs,
  247. )
  248. if self.head_dim_padding > 0:
  249. attn_output = attn_output[..., : -self.head_dim_padding]
  250. attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
  251. attn_output = self.o_proj(attn_output)
  252. return attn_output, attn_weights
  253. class MoonshineRotaryEmbedding(nn.Module):
  254. inv_freq: torch.Tensor # fix linting for `register_buffer`
  255. def __init__(self, config: MoonshineConfig, device=None):
  256. super().__init__()
  257. # BC: "rope_type" was originally "type"
  258. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  259. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  260. else:
  261. self.rope_type = "default"
  262. self.max_seq_len_cached = config.max_position_embeddings
  263. self.original_max_seq_len = config.max_position_embeddings
  264. self.config = config
  265. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  266. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  267. self.register_buffer("inv_freq", inv_freq, persistent=False)
  268. self.original_inv_freq = self.inv_freq
  269. @torch.no_grad()
  270. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  271. def forward(self, x, position_ids):
  272. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  273. position_ids_expanded = position_ids[:, None, :].float()
  274. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  275. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  276. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  277. emb = torch.cat((freqs, freqs), dim=-1)
  278. cos = emb.cos() * self.attention_scaling
  279. sin = emb.sin() * self.attention_scaling
  280. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  281. class MoonshineEncoderLayer(GradientCheckpointingLayer):
  282. def __init__(self, config: MoonshineConfig, layer_idx: int):
  283. super().__init__()
  284. self.hidden_size = config.hidden_size
  285. self.self_attn = MoonshineAttention(
  286. config=config,
  287. layer_idx=layer_idx,
  288. is_causal=False,
  289. num_attention_heads=config.encoder_num_attention_heads,
  290. num_key_value_heads=config.encoder_num_key_value_heads,
  291. )
  292. self.mlp = MoonshineEncoderMLP(config, config.encoder_hidden_act)
  293. self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
  294. self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
  295. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  296. def forward(
  297. self,
  298. hidden_states: torch.Tensor,
  299. attention_mask: Optional[torch.Tensor] = None,
  300. position_ids: Optional[torch.LongTensor] = None,
  301. past_key_values: Optional[Cache] = None,
  302. use_cache: Optional[bool] = False,
  303. cache_position: Optional[torch.LongTensor] = None,
  304. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  305. **kwargs: Unpack[TransformersKwargs],
  306. ) -> torch.Tensor:
  307. residual = hidden_states
  308. hidden_states = self.input_layernorm(hidden_states)
  309. # Self Attention
  310. hidden_states, _ = self.self_attn(
  311. hidden_states=hidden_states,
  312. attention_mask=attention_mask,
  313. position_ids=position_ids,
  314. past_key_values=past_key_values,
  315. use_cache=use_cache,
  316. cache_position=cache_position,
  317. position_embeddings=position_embeddings,
  318. **kwargs,
  319. )
  320. hidden_states = residual + hidden_states
  321. # Fully Connected
  322. residual = hidden_states
  323. hidden_states = self.post_attention_layernorm(hidden_states)
  324. hidden_states = self.mlp(hidden_states)
  325. hidden_states = residual + hidden_states
  326. return hidden_states
  327. class MoonshineDecoderLayer(GradientCheckpointingLayer):
  328. def __init__(self, config: MoonshineConfig, layer_idx: Optional[int] = None):
  329. super().__init__()
  330. self.hidden_size = config.hidden_size
  331. self.self_attn = MoonshineAttention(
  332. config=config,
  333. layer_idx=layer_idx,
  334. is_causal=True,
  335. num_attention_heads=config.decoder_num_attention_heads,
  336. num_key_value_heads=config.decoder_num_key_value_heads,
  337. )
  338. self.encoder_attn = MoonshineAttention(
  339. config=config,
  340. layer_idx=layer_idx,
  341. is_causal=False,
  342. num_attention_heads=config.decoder_num_attention_heads,
  343. num_key_value_heads=config.decoder_num_key_value_heads,
  344. )
  345. self.mlp = MoonshineDecoderMLP(config, config.decoder_hidden_act)
  346. self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
  347. self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
  348. self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
  349. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  350. def forward(
  351. self,
  352. hidden_states: torch.Tensor,
  353. attention_mask: Optional[torch.Tensor] = None,
  354. encoder_hidden_states: Optional[torch.Tensor] = None,
  355. encoder_attention_mask: Optional[torch.Tensor] = None,
  356. position_ids: Optional[torch.LongTensor] = None,
  357. encoder_position_ids: Optional[torch.LongTensor] = None,
  358. past_key_values: Optional[Cache] = None,
  359. use_cache: Optional[bool] = False,
  360. cache_position: Optional[torch.LongTensor] = None,
  361. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  362. encoder_position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  363. **kwargs: Unpack[TransformersKwargs],
  364. ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
  365. residual = hidden_states
  366. hidden_states = self.input_layernorm(hidden_states)
  367. hidden_states, _ = self.self_attn(
  368. hidden_states=hidden_states,
  369. attention_mask=attention_mask,
  370. position_ids=position_ids,
  371. past_key_values=past_key_values,
  372. use_cache=use_cache,
  373. cache_position=cache_position,
  374. position_embeddings=position_embeddings,
  375. **kwargs,
  376. )
  377. hidden_states = residual + hidden_states
  378. if encoder_hidden_states is not None:
  379. residual = hidden_states
  380. hidden_states = self.post_attention_layernorm(hidden_states)
  381. hidden_states, _ = self.encoder_attn(
  382. hidden_states=hidden_states,
  383. key_value_states=encoder_hidden_states,
  384. attention_mask=encoder_attention_mask,
  385. past_key_values=past_key_values,
  386. use_cache=use_cache,
  387. )
  388. hidden_states = residual + hidden_states
  389. residual = hidden_states
  390. hidden_states = self.final_layernorm(hidden_states)
  391. hidden_states = self.mlp(hidden_states)
  392. hidden_states = residual + hidden_states
  393. return hidden_states
  394. @auto_docstring
  395. class MoonshinePreTrainedModel(PreTrainedModel):
  396. config: MoonshineConfig
  397. base_model_prefix = "model"
  398. main_input_name = "input_values"
  399. supports_gradient_checkpointing = True
  400. _no_split_modules = ["MoonshineEncoderLayer", "MoonshineDecoderLayer"]
  401. _supports_flash_attn = True
  402. _supports_sdpa = True
  403. _can_compile_fullgraph = True
  404. # TODO arthur, how do we separate when it cross / self coming from different layer?
  405. def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
  406. """
  407. Computes the output length of the convolutional layers
  408. """
  409. output_conv1_length = int((input_lengths - 127) / 64 + 1)
  410. output_conv2_length = int((output_conv1_length - 7) / 3 + 1)
  411. output_conv3_length = int((output_conv2_length - 3) / 2 + 1)
  412. return output_conv3_length
  413. class MoonshineEncoder(MoonshinePreTrainedModel):
  414. """
  415. Transformer encoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MoonshineEncoderLayer`]
  416. Args:
  417. config: MoonshineConfig
  418. """
  419. main_input_name = "input_values"
  420. _can_record_outputs = {
  421. "attentions": MoonshineAttention,
  422. "hidden_states": MoonshineEncoderLayer,
  423. }
  424. def __init__(self, config: MoonshineConfig):
  425. super().__init__(config)
  426. self.config = config
  427. embed_dim = config.hidden_size
  428. self.conv1 = nn.Conv1d(1, embed_dim, kernel_size=127, stride=64, bias=False)
  429. self.conv2 = nn.Conv1d(embed_dim, 2 * embed_dim, kernel_size=7, stride=3)
  430. self.conv3 = nn.Conv1d(2 * embed_dim, embed_dim, kernel_size=3, stride=2)
  431. self.groupnorm = nn.GroupNorm(num_groups=1, num_channels=embed_dim, eps=1e-5)
  432. self.rotary_emb = MoonshineRotaryEmbedding(config=config)
  433. self.layers = nn.ModuleList(
  434. [MoonshineEncoderLayer(config, idx) for idx in range(config.encoder_num_hidden_layers)]
  435. )
  436. self.layer_norm = nn.LayerNorm(embed_dim, bias=False)
  437. self.gradient_checkpointing = False
  438. self.post_init()
  439. def get_input_embeddings(self) -> nn.Module:
  440. return self.conv1
  441. def set_input_embeddings(self, value: nn.Module):
  442. self.conv1 = value
  443. @check_model_inputs()
  444. def forward(
  445. self,
  446. input_values: torch.FloatTensor,
  447. attention_mask: Optional[torch.Tensor] = None,
  448. **kwargs: Unpack[TransformersKwargs],
  449. ) -> BaseModelOutputWithPast:
  450. r"""
  451. Args:
  452. input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
  453. Float values of the raw speech waveform. Raw speech waveform can be
  454. obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
  455. `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
  456. the soundfile library (`pip install soundfile`). To prepare the array into
  457. `input_values`, the [`AutoFeatureExtractor`] should be used for padding
  458. and conversion into a tensor of type `torch.FloatTensor`.
  459. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  460. Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
  461. - 1 for tokens that are **not masked**,
  462. - 0 for tokens that are **masked**.
  463. [What are attention masks?](../glossary#attention-mask)
  464. """
  465. input_values = input_values.unsqueeze(1)
  466. hidden_states = nn.functional.tanh(self.conv1(input_values))
  467. hidden_states = self.groupnorm(hidden_states)
  468. hidden_states = nn.functional.gelu(self.conv2(hidden_states))
  469. hidden_states = nn.functional.gelu(self.conv3(hidden_states))
  470. hidden_states = hidden_states.permute(0, 2, 1)
  471. # attention mask downsampling
  472. if attention_mask is not None:
  473. mask_len = self._get_feat_extract_output_lengths(attention_mask.shape[-1])
  474. downsample_stride = 64 * 3 * 2 # conv strides
  475. attention_mask = attention_mask[..., ::downsample_stride][..., :mask_len]
  476. if self.config._attn_implementation == "flash_attention_2":
  477. attention_mask = attention_mask if (attention_mask == 0.0).any() else None
  478. elif self.config._attn_implementation == "sdpa":
  479. attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, hidden_states.dtype)
  480. else:
  481. attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
  482. position_ids = torch.arange(0, hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
  483. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  484. for encoder_layer in self.layers:
  485. hidden_states = encoder_layer(
  486. hidden_states,
  487. attention_mask=attention_mask,
  488. position_ids=position_ids,
  489. position_embeddings=position_embeddings,
  490. **kwargs,
  491. )
  492. hidden_states = self.layer_norm(hidden_states)
  493. return BaseModelOutputWithPast(
  494. last_hidden_state=hidden_states,
  495. )
  496. @auto_docstring
  497. class MoonshineDecoder(MoonshinePreTrainedModel):
  498. main_input_name = "input_ids"
  499. _can_record_outputs = {
  500. "attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="self_attn"),
  501. "hidden_states": MoonshineDecoderLayer,
  502. "cross_attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="encoder_attn"),
  503. }
  504. def __init__(self, config: MoonshineConfig):
  505. super().__init__(config)
  506. self.padding_idx = config.pad_token_id
  507. self.vocab_size = config.vocab_size
  508. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  509. self.layers = nn.ModuleList(
  510. [MoonshineDecoderLayer(config, idx) for idx in range(config.decoder_num_hidden_layers)]
  511. )
  512. self.norm = nn.LayerNorm(config.hidden_size, bias=False)
  513. self.rotary_emb = MoonshineRotaryEmbedding(config=config)
  514. self.gradient_checkpointing = False
  515. # Initialize weights and apply final processing
  516. self.post_init()
  517. @check_model_inputs()
  518. def forward(
  519. self,
  520. input_ids: Optional[torch.LongTensor] = None,
  521. attention_mask: Optional[torch.Tensor] = None,
  522. position_ids: Optional[torch.LongTensor] = None,
  523. past_key_values: Optional[Cache] = None,
  524. inputs_embeds: Optional[torch.FloatTensor] = None,
  525. use_cache: Optional[bool] = None,
  526. cache_position: Optional[torch.LongTensor] = None,
  527. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  528. encoder_attention_mask: Optional[torch.Tensor] = None,
  529. **kwargs: Unpack[TransformersKwargs],
  530. ) -> Union[tuple, BaseModelOutputWithPast]:
  531. r"""
  532. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
  533. Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
  534. of the decoder.
  535. encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  536. Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
  537. - 1 for tokens that are **not masked**,
  538. - 0 for tokens that are **masked**.
  539. [What are attention masks?](../glossary#attention-mask)
  540. """
  541. if (input_ids is None) ^ (inputs_embeds is not None):
  542. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  543. if inputs_embeds is None:
  544. inputs_embeds = self.embed_tokens(input_ids)
  545. if use_cache and past_key_values is None:
  546. past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
  547. if cache_position is None:
  548. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  549. cache_position = torch.arange(
  550. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  551. )
  552. if position_ids is None:
  553. position_ids = cache_position.unsqueeze(0)
  554. causal_mask = create_causal_mask(
  555. config=self.config,
  556. input_embeds=inputs_embeds,
  557. attention_mask=attention_mask,
  558. cache_position=cache_position,
  559. past_key_values=past_key_values,
  560. position_ids=position_ids,
  561. )
  562. hidden_states = inputs_embeds
  563. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  564. if encoder_attention_mask is not None:
  565. mask_len = encoder_hidden_states.shape[-2]
  566. downsample_stride = 64 * 3 * 2 # conv strides
  567. encoder_attention_mask = encoder_attention_mask[..., ::downsample_stride][..., :mask_len]
  568. if self.config._attn_implementation == "flash_attention_2":
  569. encoder_attention_mask = encoder_attention_mask if (encoder_attention_mask == 0.0).any() else None
  570. elif self.config._attn_implementation == "sdpa":
  571. encoder_attention_mask = _prepare_4d_attention_mask_for_sdpa(
  572. encoder_attention_mask, hidden_states.dtype, hidden_states.shape[-2]
  573. )
  574. else:
  575. encoder_attention_mask = _prepare_4d_attention_mask(
  576. encoder_attention_mask, hidden_states.dtype, hidden_states.shape[-2]
  577. )
  578. for decoder_layer in self.layers:
  579. hidden_states = decoder_layer(
  580. hidden_states,
  581. causal_mask,
  582. encoder_hidden_states, # as a positional argument for gradient checkpointing
  583. encoder_attention_mask=encoder_attention_mask,
  584. position_ids=position_ids,
  585. past_key_values=past_key_values,
  586. use_cache=use_cache,
  587. cache_position=cache_position,
  588. position_embeddings=position_embeddings,
  589. **kwargs,
  590. )
  591. hidden_states = self.norm(hidden_states)
  592. return BaseModelOutputWithPastAndCrossAttentions(
  593. last_hidden_state=hidden_states,
  594. past_key_values=past_key_values if use_cache else None,
  595. )
  596. def _compute_mask_indices(
  597. shape: tuple[int, int],
  598. mask_prob: float,
  599. mask_length: int,
  600. attention_mask: Optional[torch.LongTensor] = None,
  601. min_masks: int = 0,
  602. ) -> np.ndarray:
  603. """
  604. Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
  605. ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
  606. CPU as part of the preprocessing during training.
  607. Args:
  608. shape: The shape for which to compute masks. This should be of a tuple of size 2 where
  609. the first element is the batch size and the second element is the length of the axis to span.
  610. mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
  611. independently generated mask spans of length `mask_length` is computed by
  612. `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
  613. actual percentage will be smaller.
  614. mask_length: size of the mask
  615. min_masks: minimum number of masked spans
  616. attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
  617. each batch dimension.
  618. """
  619. batch_size, sequence_length = shape
  620. if mask_length < 1:
  621. raise ValueError("`mask_length` has to be bigger than 0.")
  622. if mask_length > sequence_length:
  623. raise ValueError(
  624. f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
  625. f" and `sequence_length`: {sequence_length}`"
  626. )
  627. # epsilon is used for probabilistic rounding
  628. epsilon = np.random.rand(1).item()
  629. def compute_num_masked_span(input_length):
  630. """Given input length, compute how many spans should be masked"""
  631. num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
  632. num_masked_span = max(num_masked_span, min_masks)
  633. # make sure num masked span <= sequence_length
  634. if num_masked_span * mask_length > sequence_length:
  635. num_masked_span = sequence_length // mask_length
  636. # make sure num_masked span is also <= input_length - (mask_length - 1)
  637. if input_length - (mask_length - 1) < num_masked_span:
  638. num_masked_span = max(input_length - (mask_length - 1), 0)
  639. return num_masked_span
  640. # compute number of masked spans in batch
  641. input_lengths = (
  642. attention_mask.detach().sum(-1).tolist()
  643. if attention_mask is not None
  644. else [sequence_length for _ in range(batch_size)]
  645. )
  646. # SpecAugment mask to fill
  647. spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
  648. spec_aug_mask_idxs = []
  649. max_num_masked_span = compute_num_masked_span(sequence_length)
  650. if max_num_masked_span == 0:
  651. return spec_aug_mask
  652. for input_length in input_lengths:
  653. # compute num of masked spans for this input
  654. num_masked_span = compute_num_masked_span(input_length)
  655. # get random indices to mask
  656. spec_aug_mask_idx = np.random.choice(
  657. np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
  658. )
  659. # pick first sampled index that will serve as a dummy index to pad vector
  660. # to ensure same dimension for all batches due to probabilistic rounding
  661. # Picking first sample just pads those vectors twice.
  662. if len(spec_aug_mask_idx) == 0:
  663. # this case can only happen if `input_length` is strictly smaller then
  664. # `sequence_length` in which case the last token has to be a padding
  665. # token which we can use as a dummy mask id
  666. dummy_mask_idx = sequence_length - 1
  667. else:
  668. dummy_mask_idx = spec_aug_mask_idx[0]
  669. spec_aug_mask_idx = np.concatenate(
  670. [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
  671. )
  672. spec_aug_mask_idxs.append(spec_aug_mask_idx)
  673. spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
  674. # expand masked indices to masked spans
  675. spec_aug_mask_idxs = np.broadcast_to(
  676. spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
  677. )
  678. spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
  679. # add offset to the starting indexes so that indexes now create a span
  680. offsets = np.arange(mask_length)[None, None, :]
  681. offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
  682. batch_size, max_num_masked_span * mask_length
  683. )
  684. spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
  685. # ensure that we cannot have indices larger than sequence_length
  686. if spec_aug_mask_idxs.max() > sequence_length - 1:
  687. spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
  688. # scatter indices to mask
  689. np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
  690. return spec_aug_mask
  691. @auto_docstring
  692. class MoonshineModel(MoonshinePreTrainedModel):
  693. def __init__(self, config: MoonshineConfig):
  694. super().__init__(config)
  695. self.encoder = MoonshineEncoder(config)
  696. self.decoder = MoonshineDecoder(config)
  697. # Initialize weights and apply final processing
  698. self.post_init()
  699. def get_input_embeddings(self):
  700. return self.decoder.embed_tokens
  701. def set_input_embeddings(self, value):
  702. self.decoder.embed_tokens = value
  703. def get_encoder(self):
  704. return self.encoder
  705. def freeze_encoder(self):
  706. """
  707. Calling this function will disable the gradient computation for the Moonshine encoder so that its parameters will
  708. not be updated during training.
  709. """
  710. self.encoder._freeze_parameters()
  711. def _mask_input_features(
  712. self,
  713. input_features: torch.FloatTensor,
  714. attention_mask: Optional[torch.LongTensor] = None,
  715. ):
  716. """
  717. Masks extracted features along time axis and/or along feature axis according to
  718. [SpecAugment](https://huggingface.co/papers/1904.08779).
  719. """
  720. # `config.apply_spec_augment` can set masking to False
  721. if not getattr(self.config, "apply_spec_augment", True):
  722. return input_features
  723. # generate indices & apply SpecAugment along time axis
  724. batch_size, hidden_size, sequence_length = input_features.size()
  725. if self.config.mask_time_prob > 0 and self.training:
  726. # generate indices & apply SpecAugment along time axis
  727. mask_time_indices = _compute_mask_indices(
  728. (batch_size, sequence_length),
  729. mask_prob=self.config.mask_time_prob,
  730. mask_length=self.config.mask_time_length,
  731. attention_mask=attention_mask,
  732. min_masks=self.config.mask_time_min_masks,
  733. )
  734. mask_time_indices = torch.tensor(mask_time_indices, device=input_features.device, dtype=torch.bool)
  735. mask_time_indices = mask_time_indices[:, None].expand(-1, hidden_size, -1)
  736. input_features[mask_time_indices] = 0
  737. if self.config.mask_feature_prob > 0 and self.training:
  738. # generate indices & apply SpecAugment along feature axis
  739. mask_feature_indices = _compute_mask_indices(
  740. (batch_size, hidden_size),
  741. mask_prob=self.config.mask_feature_prob,
  742. mask_length=self.config.mask_feature_length,
  743. min_masks=self.config.mask_feature_min_masks,
  744. )
  745. mask_feature_indices = torch.tensor(mask_feature_indices, device=input_features.device, dtype=torch.bool)
  746. input_features[mask_feature_indices] = 0
  747. return input_features
  748. @can_return_tuple
  749. @auto_docstring
  750. def forward(
  751. self,
  752. input_values: Optional[torch.FloatTensor] = None,
  753. attention_mask: Optional[torch.LongTensor] = None,
  754. decoder_input_ids: Optional[torch.LongTensor] = None,
  755. decoder_attention_mask: Optional[torch.LongTensor] = None,
  756. encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None,
  757. past_key_values: Optional[Union[EncoderDecoderCache, tuple[torch.FloatTensor]]] = None,
  758. decoder_inputs_embeds: Optional[tuple[torch.FloatTensor]] = None,
  759. decoder_position_ids: Optional[tuple[torch.LongTensor]] = None,
  760. use_cache: Optional[bool] = None,
  761. cache_position: Optional[torch.LongTensor] = None,
  762. **kwargs: Unpack[TransformersKwargs],
  763. ) -> Seq2SeqModelOutput:
  764. r"""
  765. input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
  766. Float values of the raw speech waveform. Raw speech waveform can be
  767. obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
  768. `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
  769. the soundfile library (`pip install soundfile`). To prepare the array into
  770. `input_values`, the [`AutoFeatureExtractor`] should be used for padding
  771. and conversion into a tensor of type `torch.FloatTensor`.
  772. decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
  773. Indices of positions of each input sequence tokens in the position embeddings.
  774. Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
  775. Example:
  776. ```python
  777. >>> import torch
  778. >>> from transformers import AutoFeatureExtractor, MoonshineModel
  779. >>> from datasets import load_dataset
  780. >>> model = MoonshineModel.from_pretrained("UsefulSensors/moonshine-tiny")
  781. >>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine-tiny")
  782. >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
  783. >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
  784. >>> input_values = inputs.input_values
  785. >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
  786. >>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
  787. >>> list(last_hidden_state.shape)
  788. [1, 2, 288]
  789. ```
  790. """
  791. if encoder_outputs is None:
  792. encoder_outputs: BaseModelOutput = self.encoder(input_values, attention_mask=attention_mask, **kwargs)
  793. decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
  794. input_ids=decoder_input_ids,
  795. attention_mask=decoder_attention_mask,
  796. encoder_attention_mask=attention_mask,
  797. encoder_hidden_states=encoder_outputs.last_hidden_state,
  798. past_key_values=past_key_values,
  799. inputs_embeds=decoder_inputs_embeds,
  800. position_ids=decoder_position_ids,
  801. use_cache=use_cache,
  802. cache_position=cache_position,
  803. **kwargs,
  804. )
  805. return Seq2SeqModelOutput(
  806. last_hidden_state=decoder_outputs.last_hidden_state,
  807. past_key_values=decoder_outputs.past_key_values,
  808. decoder_hidden_states=decoder_outputs.hidden_states,
  809. decoder_attentions=decoder_outputs.attentions,
  810. cross_attentions=decoder_outputs.cross_attentions,
  811. encoder_last_hidden_state=encoder_outputs.last_hidden_state,
  812. encoder_hidden_states=encoder_outputs.hidden_states,
  813. encoder_attentions=encoder_outputs.attentions,
  814. )
  815. def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
  816. """
  817. Shift input ids one token to the right.
  818. """
  819. shifted_input_ids = input_ids.new_zeros(input_ids.shape)
  820. shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
  821. shifted_input_ids[:, 0] = decoder_start_token_id
  822. if pad_token_id is None:
  823. raise ValueError("self.model.config.pad_token_id has to be defined.")
  824. # replace possible -100 values in labels by `pad_token_id`
  825. shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
  826. return shifted_input_ids
  827. @auto_docstring(
  828. custom_intro="""
  829. The Moonshine Model with a language modeling head. Can be used for automatic speech recognition.
  830. """
  831. )
  832. class MoonshineForConditionalGeneration(MoonshinePreTrainedModel, GenerationMixin):
  833. _tied_weights_keys = ["proj_out.weight"]
  834. def __init__(self, config: MoonshineConfig):
  835. super().__init__(config)
  836. self.model = MoonshineModel(config)
  837. self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  838. # Initialize weights and apply final processing
  839. self.post_init()
  840. def get_encoder(self):
  841. return self.model.get_encoder()
  842. def get_decoder(self):
  843. return self.model.get_decoder()
  844. def get_output_embeddings(self):
  845. return self.proj_out
  846. def set_output_embeddings(self, new_embeddings):
  847. self.proj_out = new_embeddings
  848. def get_input_embeddings(self) -> nn.Module:
  849. return self.model.get_input_embeddings()
  850. @can_return_tuple
  851. @auto_docstring
  852. def forward(
  853. self,
  854. input_values: Optional[torch.FloatTensor] = None,
  855. attention_mask: Optional[torch.LongTensor] = None,
  856. decoder_input_ids: Optional[torch.LongTensor] = None,
  857. decoder_attention_mask: Optional[torch.LongTensor] = None,
  858. encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None,
  859. past_key_values: Optional[Union[EncoderDecoderCache, tuple[torch.FloatTensor]]] = None,
  860. decoder_inputs_embeds: Optional[tuple[torch.FloatTensor]] = None,
  861. decoder_position_ids: Optional[tuple[torch.LongTensor]] = None,
  862. use_cache: Optional[bool] = None,
  863. cache_position: Optional[torch.LongTensor] = None,
  864. labels: Optional[torch.LongTensor] = None,
  865. **kwargs: Unpack[TransformersKwargs],
  866. ) -> Seq2SeqLMOutput:
  867. r"""
  868. input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
  869. Float values of the raw speech waveform. Raw speech waveform can be
  870. obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
  871. `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
  872. the soundfile library (`pip install soundfile`). To prepare the array into
  873. `input_values`, the [`AutoFeatureExtractor`] should be used for padding
  874. and conversion into a tensor of type `torch.FloatTensor`.
  875. decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
  876. Indices of positions of each input sequence tokens in the position embeddings.
  877. Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
  878. Example:
  879. ```python
  880. >>> import torch
  881. >>> from transformers import AutoProcessor, MoonshineForConditionalGeneration
  882. >>> from datasets import load_dataset
  883. >>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine-tiny")
  884. >>> model = MoonshineForConditionalGeneration.from_pretrained("UsefulSensors/moonshine-tiny")
  885. >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
  886. >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
  887. >>> input_values = inputs.input_values
  888. >>> generated_ids = model.generate(input_values, max_new_tokens=100)
  889. >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
  890. >>> transcription
  891. 'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
  892. ```"""
  893. if labels is not None:
  894. if decoder_input_ids is None and decoder_inputs_embeds is None:
  895. decoder_input_ids = shift_tokens_right(
  896. labels, self.config.pad_token_id, self.config.decoder_start_token_id
  897. )
  898. outputs: Seq2SeqModelOutput = self.model(
  899. input_values,
  900. attention_mask=attention_mask,
  901. decoder_input_ids=decoder_input_ids,
  902. encoder_outputs=encoder_outputs,
  903. decoder_attention_mask=decoder_attention_mask,
  904. past_key_values=past_key_values,
  905. decoder_inputs_embeds=decoder_inputs_embeds,
  906. decoder_position_ids=decoder_position_ids,
  907. use_cache=use_cache,
  908. cache_position=cache_position,
  909. **kwargs,
  910. )
  911. logits = self.proj_out(outputs.last_hidden_state)
  912. loss = None
  913. if labels is not None:
  914. loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
  915. return Seq2SeqLMOutput(
  916. loss=loss,
  917. logits=logits,
  918. past_key_values=outputs.past_key_values,
  919. decoder_hidden_states=outputs.decoder_hidden_states,
  920. decoder_attentions=outputs.decoder_attentions,
  921. cross_attentions=outputs.cross_attentions,
  922. encoder_last_hidden_state=outputs.encoder_last_hidden_state,
  923. encoder_hidden_states=outputs.encoder_hidden_states,
  924. encoder_attentions=outputs.encoder_attentions,
  925. )
  926. __all__ = ["MoonshineModel", "MoonshinePreTrainedModel", "MoonshineForConditionalGeneration"]