# Copyright 2026 IBM and The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from collections.abc import Callable from dataclasses import dataclass from typing import Optional import torch import torch.nn.functional as F from torch import nn from transformers.activations import ACT2FN from transformers.cache_utils import Cache from transformers.generation import GenerationMixin from transformers.integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func from transformers.masking_utils import create_bidirectional_mask, find_packed_sequence_indices, packed_sequence_mask_function from transformers.modeling_layers import GradientCheckpointingLayer from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from transformers.processing_utils import Unpack from transformers.utils import ModelOutput, TransformersKwargs from transformers.utils.generic import maybe_autocast from .configuration_granite_speech_nar import ( GraniteSpeechNarConfig, GraniteSpeechNarEncoderConfig, GraniteSpeechNarProjectorConfig, ) @dataclass class GraniteSpeechNarEncoderOutput(ModelOutput): """Output of the GraniteSpeechNar encoder.""" loss: torch.Tensor | None = None logits: torch.FloatTensor | None = None last_hidden_state: torch.FloatTensor | None = None all_hidden_states: tuple[torch.FloatTensor, ...] | None = None @dataclass class GraniteSpeechNarOutput(ModelOutput): """Output of the GraniteSpeechNarForASR model. Attributes: loss: Combined CTC + auxiliary losses (only when labels provided). preds: List of predicted token ID tensors per sample (after CTC collapse, inference only). logits: List of per-sample logit tensors from the LLM head. encoder_logits: Flat BPE CTC logits from the encoder. encoder_preds: List of CTC-collapsed encoder predictions per sample. """ loss: torch.Tensor | None = None preds: list[torch.Tensor] | None = None logits: list[torch.Tensor] | None = None encoder_logits: torch.Tensor | None = None encoder_preds: list[torch.Tensor] | None = None ### Encoder - conformer is adapted from: https://github.com/lucidrains/conformer.git class GraniteSpeechNarConformerFeedForward(nn.Module): """Feedforward module for conformer encoder blocks.""" def __init__(self, config: GraniteSpeechNarEncoderConfig): super().__init__() self.pre_norm = nn.LayerNorm(config.hidden_dim) self.up_proj = nn.Linear(config.hidden_dim, config.hidden_dim * config.feedforward_mult) self.silu = nn.SiLU() self.dropout = nn.Dropout(config.dropout) self.down_proj = nn.Linear(config.hidden_dim * config.feedforward_mult, config.hidden_dim) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.pre_norm(hidden_states) hidden_states = self.up_proj(hidden_states) hidden_states = self.dropout(self.silu(hidden_states)) hidden_states = self.down_proj(hidden_states) hidden_states = self.dropout(hidden_states) return hidden_states class GraniteSpeechNarConformerAttention(nn.Module): """Attention for conformer blocks using Shaw's relative positional embeddings. See the following [paper](https://huggingface.co/papers/1803.02155) for more details. """ def __init__(self, config: GraniteSpeechNarEncoderConfig): super().__init__() inner_dim = config.dim_head * config.num_heads self.max_pos_emb = config.max_pos_emb self.context_size = config.context_size self.num_heads = config.num_heads self.dim_head = config.dim_head self.scale = self.dim_head**-0.5 self.pre_norm = nn.LayerNorm(config.hidden_dim) self.to_q = nn.Linear(config.hidden_dim, inner_dim, bias=False) self.to_kv = nn.Linear(config.hidden_dim, inner_dim * 2, bias=False) self.to_out = nn.Linear(inner_dim, config.hidden_dim) self.rel_pos_emb = nn.Embedding(2 * self.max_pos_emb + 1, self.dim_head) self.dropout = nn.Dropout(config.dropout) if self.context_size <= 0 or self.context_size > self.max_pos_emb: raise ValueError("Context size is either less than 0 or exceeds the max_pos_emb") def forward(self, hidden_states: torch.Tensor, attention_dists: torch.Tensor) -> torch.Tensor: hidden_states = self.pre_norm(hidden_states) bsz, num_features, _ = hidden_states.shape num_blocks = math.ceil(num_features / self.context_size) remainder = num_features % self.context_size if remainder > 0: # right padding to reach block size hidden_states = torch.nn.functional.pad(hidden_states, (0, 0, 0, self.context_size - remainder)) query_states = self.to_q(hidden_states) key_states, value_states = self.to_kv(hidden_states).chunk(2, dim=-1) query_states = query_states.reshape(bsz, num_blocks, self.context_size, self.num_heads, -1).transpose(2, 3) key_states = key_states.reshape(bsz, num_blocks, self.context_size, self.num_heads, -1).transpose(2, 3) value_states = value_states.reshape(bsz, num_blocks, self.context_size, self.num_heads, -1).transpose(2, 3) # shaw's relative positional embedding rel_pos_emb = self.rel_pos_emb(attention_dists) # alternative computation of `pos_attn` - for readability # rel_pos_emb_expanded = rel_pos_emb.view([1, 1, 1] + list(rel_pos_emb.shape)) # pos_attn = torch.sum(query_states.unsqueeze(-2) * rel_pos_emb_expanded, dim=-1) * self.scale # einsum implementation of pos_attn - gives x30 speedup over the alternative # TODO (@avihu111) find a fast alternative to einsum pos_attn = torch.einsum("b m h c d, c r d -> b m h c r", query_states, rel_pos_emb) * self.scale if remainder > 0: # masked attention in the extended block mask = torch.ones(self.context_size, self.context_size, dtype=bool, device=hidden_states.device) mask[:remainder, :remainder] = 0 mask_value = -torch.finfo(pos_attn.dtype).max pos_attn[:, -1, :].masked_fill_(mask, mask_value) with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH): out = F.scaled_dot_product_attention( query_states, key_states, value_states, attn_mask=pos_attn, scale=self.scale ) out = out.transpose(2, 3).reshape(bsz, hidden_states.shape[1], -1) out = self.to_out(out[:, :num_features, :]) return self.dropout(out) class GraniteSpeechNarConformerDepthWiseConv1d(nn.Module): """Wrapper for padded 1D pointwise convolution.""" def __init__(self, chan_in: int, chan_out: int, kernel_size: int): super().__init__() # Padding for the 1D conv is symmetric or close (i.e., offset by one). pad = kernel_size // 2 pad_offset = (kernel_size + 1) % 2 self.padding = (pad, pad - pad_offset) self.conv = nn.Conv1d(chan_in, chan_out, kernel_size, groups=chan_in, bias=False) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = F.pad(hidden_states, self.padding) return self.conv(hidden_states) class GraniteSpeechNarConformerConvModule(nn.Module): """Conformer conv module consisting of several 1D/depthwise 1D convolutional layers.""" def __init__(self, config: GraniteSpeechNarEncoderConfig): super().__init__() inner_dim = config.hidden_dim * config.conv_expansion_factor self.norm = nn.LayerNorm(config.hidden_dim) self.up_conv = nn.Conv1d(config.hidden_dim, inner_dim * 2, 1) self.glu = nn.GLU(dim=1) self.depth_conv = GraniteSpeechNarConformerDepthWiseConv1d( inner_dim, inner_dim, kernel_size=config.conv_kernel_size, ) self.silu = nn.SiLU() self.batch_norm = nn.BatchNorm1d(inner_dim) self.down_conv = nn.Conv1d(inner_dim, config.hidden_dim, 1) self.dropout = nn.Dropout(config.dropout) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.norm(hidden_states) hidden_states = self.up_conv(hidden_states.permute(0, 2, 1)) hidden_states = self.glu(hidden_states) hidden_states = self.depth_conv(hidden_states) hidden_states = self.silu(self.batch_norm(hidden_states)) hidden_states = self.down_conv(hidden_states).permute(0, 2, 1) hidden_states = self.dropout(hidden_states) return hidden_states class GraniteSpeechNarConformerBlock(nn.Module): """Conformer block, consisting largely of linear layers, attention, and convolutional layers.""" def __init__(self, config: GraniteSpeechNarEncoderConfig): super().__init__() self.ff1 = GraniteSpeechNarConformerFeedForward(config) self.attn = GraniteSpeechNarConformerAttention(config) self.conv = GraniteSpeechNarConformerConvModule(config) self.ff2 = GraniteSpeechNarConformerFeedForward(config) self.post_norm = nn.LayerNorm(config.hidden_dim) def forward(self, hidden_states: torch.Tensor, attention_dists: torch.Tensor) -> torch.Tensor: hidden_states = 0.5 * self.ff1(hidden_states) + hidden_states hidden_states = self.attn(hidden_states, attention_dists=attention_dists) + hidden_states hidden_states = self.conv(hidden_states) + hidden_states hidden_states = 0.5 * self.ff2(hidden_states) + hidden_states hidden_states = self.post_norm(hidden_states) return hidden_states class GraniteSpeechNarQFormerCrossAttention(nn.Module): def __init__(self, config: GraniteSpeechNarProjectorConfig): super().__init__() self.num_heads = config.num_heads self.head_dim = config.hidden_size // config.num_heads self.hidden_size = config.hidden_size self.q_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attn_bias) self.k_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attn_bias) self.v_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attn_bias) self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attn_bias) def forward(self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor) -> torch.Tensor: batch_size, query_len, _ = hidden_states.shape encoder_len = encoder_hidden_states.shape[1] query_states = ( self.q_proj(hidden_states).view(batch_size, query_len, self.num_heads, self.head_dim).transpose(1, 2) ) key_states = ( self.k_proj(encoder_hidden_states) .view(batch_size, encoder_len, self.num_heads, self.head_dim) .transpose(1, 2) ) value_states = ( self.v_proj(encoder_hidden_states) .view(batch_size, encoder_len, self.num_heads, self.head_dim) .transpose(1, 2) ) attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, is_causal=False) attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, query_len, self.hidden_size) return self.o_proj(attn_output) class GraniteSpeechNarQFormerMLP(nn.Module): def __init__(self, config: GraniteSpeechNarProjectorConfig): super().__init__() mlp_hidden_size = int(config.hidden_size * config.mlp_ratio) self.fc1 = nn.Linear(config.hidden_size, mlp_hidden_size, bias=config.mlp_bias) self.act = nn.SiLU() self.fc2 = nn.Linear(mlp_hidden_size, config.hidden_size, bias=config.mlp_bias) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return self.fc2(self.act(self.fc1(hidden_states))) class GraniteSpeechNarQFormerLayer(nn.Module): def __init__(self, config: GraniteSpeechNarProjectorConfig): super().__init__() self.attn_norm = nn.LayerNorm(config.hidden_size, eps=config.layernorm_eps) self.cross_attention = GraniteSpeechNarQFormerCrossAttention(config) self.mlp_norm = nn.LayerNorm(config.hidden_size, eps=config.layernorm_eps) self.mlp = GraniteSpeechNarQFormerMLP(config) def forward(self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = hidden_states + self.cross_attention(self.attn_norm(hidden_states), encoder_hidden_states) hidden_states = hidden_states + self.mlp(self.mlp_norm(hidden_states)) return hidden_states class GraniteSpeechNarQFormer(nn.Module): def __init__(self, config: GraniteSpeechNarProjectorConfig): super().__init__() self.layers = nn.ModuleList([GraniteSpeechNarQFormerLayer(config) for _ in range(config.num_layers)]) def forward(self, query_embeds: torch.Tensor, encoder_hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = query_embeds for layer in self.layers: hidden_states = layer(hidden_states, encoder_hidden_states) return hidden_states class GraniteSpeechNarProjector(nn.Module): """Windowed QFormer projector that maps multi-layer encoder features to LLM embedding space.""" def __init__(self, config: GraniteSpeechNarProjectorConfig): super().__init__() self.config = config self.layer_norms = nn.ModuleList( [nn.LayerNorm(config.encoder_dim, eps=config.layernorm_eps) for _ in range(config.num_encoder_layers)] ) self.layer_projector = nn.Linear(config.encoder_dim * config.num_encoder_layers, config.hidden_size) self.dropout = nn.Dropout(config.dropout_prob) self.projector_act = nn.GELU() self.qformer = GraniteSpeechNarQFormer(config) query_length = config.block_size // config.downsample_rate embed_std = config.hidden_size**-0.5 self.query = nn.Parameter(torch.randn(1, query_length, config.hidden_size) * embed_std) self.window_positions = nn.Parameter(torch.randn(1, config.block_size, config.hidden_size) * embed_std) self.out_norm = nn.LayerNorm(config.hidden_size, eps=config.layernorm_eps) self.out_linear = nn.Linear(config.hidden_size, config.llm_dim) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: batch_size, seq_len, dim = hidden_states.size() hidden_states = hidden_states.view( batch_size, seq_len, self.config.num_encoder_layers, self.config.encoder_dim ) normalized_layers = [] for i, layer_norm in enumerate(self.layer_norms): normalized_layers.append(layer_norm(hidden_states[:, :, i])) hidden_states = torch.cat(normalized_layers, dim=-1) hidden_states = self.projector_act(self.layer_projector(hidden_states)) block_size = self.config.block_size nblocks = seq_len // block_size rest = seq_len % block_size if rest > 0: hidden_states = F.pad(hidden_states, (0, 0, 0, block_size - rest), "constant", 0) nblocks += 1 hidden_states = hidden_states.view(batch_size * nblocks, block_size, self.config.hidden_size) query_length = self.query.shape[1] mean_pool = hidden_states.view( batch_size * nblocks, query_length, self.config.downsample_rate, self.config.hidden_size ).mean(dim=-2) hidden_states = self.qformer( query_embeds=self.dropout(self.query + mean_pool), encoder_hidden_states=self.dropout(hidden_states + self.window_positions), ) hidden_states = hidden_states.view(batch_size, nblocks * query_length, -1) hidden_states = self.dropout(self.out_norm(hidden_states)) return self.out_linear(hidden_states) class GraniteSpeechNarPreTrainedModel(PreTrainedModel): config_class = GraniteSpeechNarConfig base_model_prefix = "encoder" supports_gradient_checkpointing = True _supports_flash_attn = True _supports_flash_attn_2 = True _supports_sdpa = True _no_split_modules = ["GraniteSpeechNarConformerBlock", "GraniteDecoderLayer"] input_modalities = ("audio",) def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) @use_kernel_func_from_hub("rotary_pos_emb") def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor | None, scaling: float, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs], ): key_states = repeat_kv(key, module.num_key_value_groups) value_states = repeat_kv(value, module.num_key_value_groups) attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling if attention_mask is not None: attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights @use_kernelized_func(apply_rotary_pos_emb) class GraniteSpeechNarAttention(nn.Module): """GraniteAttention with is_causal=False for bidirectional attention.""" is_causal = False def __init__(self, config, layer_idx=None): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.scaling = config.attention_multiplier self.attention_dropout = config.attention_dropout self.is_causal = False self.q_proj = nn.Linear( config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias ) self.k_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.v_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.o_proj = nn.Linear( config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias ) def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, attention_mask: torch.Tensor | None = None, past_key_values: Cache | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, torch.Tensor]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward ) attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights @use_kernel_forward_from_hub("RMSNorm") class GraniteSpeechNarRMSNorm(nn.Module): def __init__(self, hidden_size, eps: float = 1e-6) -> None: """ GraniteSpeechNarRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype) def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" class GraniteSpeechNarMLP(nn.Module): def __init__(self, config): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias) self.act_fn = ACT2FN[config.hidden_act] def forward(self, x): down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) return down_proj class GraniteSpeechNarDecoderLayer(GradientCheckpointingLayer): """GraniteDecoderLayer using bidirectional attention.""" def __init__(self, config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = GraniteSpeechNarAttention(config=config, layer_idx=layer_idx) self.mlp = GraniteSpeechNarMLP(config) self.input_layernorm = GraniteSpeechNarRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = GraniteSpeechNarRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.residual_multiplier = config.residual_multiplier def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, use_cache: bool | None = False, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs: Unpack[TransformersKwargs], ) -> torch.Tensor: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, query_sequence_length, key_sequence_length)` if default attention is used. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). past_key_values (`Cache`, *optional*): cached past key and value projection states position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*): Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`, with `head_dim` being the embedding dimension of each attention head. kwargs (`dict`, *optional*): Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code into the model """ residual = hidden_states hidden_states = self.input_layernorm(hidden_states) hidden_states, _ = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, position_embeddings=position_embeddings, **kwargs, ) hidden_states = residual + hidden_states * self.residual_multiplier residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states * self.residual_multiplier return hidden_states class GraniteSpeechNarRotaryEmbedding(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: GraniteSpeechNarConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.config = config self.rope_type = self.config.rope_parameters["rope_type"] rope_init_fn: Callable = self.compute_default_rope_parameters if self.rope_type != "default": rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.register_buffer("inv_freq", inv_freq, persistent=False) self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False) @staticmethod def compute_default_rope_parameters( config: GraniteSpeechNarConfig | None = None, device: Optional["torch.device"] = None, seq_len: int | None = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies according to the original RoPE implementation Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length. Unused for this type of RoPE. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ base = config.rope_parameters["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads attention_factor = 1.0 # Unused in this type of RoPE # Compute the inverse frequencies inv_freq = 1.0 / ( base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim) ) return inv_freq, attention_factor @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) position_ids_expanded = position_ids[:, None, :].float() device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) class GraniteSpeechNarModel(GraniteSpeechNarPreTrainedModel): """GraniteModel with bidirectional (non-causal) attention. Uses GraniteSpeechNarDecoderLayer which sets is_causal=False, and replaces create_causal_mask() with create_bidirectional_mask() so all attention backends (SDPA, FA2, eager, flex) get a proper non-causal mask. """ def __init__(self, config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [GraniteSpeechNarDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = GraniteSpeechNarRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = GraniteSpeechNarRotaryEmbedding(config=config) self.gradient_checkpointing = False self.embedding_multiplier = config.embedding_multiplier # Initialize weights and apply final processing self.post_init() def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, inputs_embeds: torch.FloatTensor | None = None, **kwargs, ) -> BaseModelOutputWithPast: if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) inputs_embeds = inputs_embeds * self.embedding_multiplier if position_ids is None: position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0) packed_seq_mask = find_packed_sequence_indices(position_ids) and_mask_fn = packed_sequence_mask_function(packed_seq_mask) if packed_seq_mask is not None else None bidirectional_mask = create_bidirectional_mask( config=self.config, inputs_embeds=inputs_embeds, attention_mask=attention_mask, and_mask_function=and_mask_fn, ) hidden_states = inputs_embeds position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids) # KV cache is not needed in a non-autoregressive model kwargs["use_cache"] = False for decoder_layer in self.layers: hidden_states = decoder_layer( hidden_states, attention_mask=bidirectional_mask, position_ids=position_ids, position_embeddings=position_embeddings, **kwargs, ) hidden_states = self.norm(hidden_states) return BaseModelOutputWithPast(last_hidden_state=hidden_states) def _posterior_weighted_pool(hidden: torch.Tensor, importance: torch.Tensor, window_size: int = 4) -> torch.Tensor: batch_size, seq_len, hidden_dim = hidden.shape pad_len = (window_size - seq_len % window_size) % window_size if pad_len > 0: hidden = F.pad(hidden, (0, 0, 0, pad_len)) importance = F.pad(importance, (0, pad_len)) num_windows = hidden.shape[1] // window_size hidden = hidden.view(batch_size, num_windows, window_size, hidden_dim) importance = importance.view(batch_size, num_windows, window_size) weights = importance / (importance.sum(dim=-1, keepdim=True) + 1e-8) pooled = (hidden * weights.unsqueeze(-1)).sum(dim=2) return pooled class GraniteSpeechNarCTCEncoder(GraniteSpeechNarPreTrainedModel): """Conformer encoder with BPE CTC head and multi-layer output.""" config_class = GraniteSpeechNarEncoderConfig def __init__(self, config: GraniteSpeechNarEncoderConfig): super().__init__(config) self.input_linear = nn.Linear(config.input_dim, config.hidden_dim, bias=True) self.layers = nn.ModuleList([GraniteSpeechNarConformerBlock(config) for _ in range(config.num_layers)]) self.out = nn.Linear(config.hidden_dim, config.output_dim, bias=True) self.out_mid = nn.Linear(config.output_dim, config.hidden_dim, bias=True) self.out_bpe = None if config.bpe_output_dim is not None: self.out_bpe = nn.Linear(config.hidden_dim, config.bpe_output_dim, bias=True) self.dropout = nn.Dropout(config.pred_dropout) self.post_init() def forward( self, input_features: torch.Tensor, attention_mask: torch.Tensor | None = None, output_hidden_states: bool | None = None, labels: torch.Tensor | None = None, label_lengths: torch.Tensor | None = None, **kwargs, ) -> GraniteSpeechNarEncoderOutput: if attention_mask is None: attention_mask = torch.ones(input_features.shape[:-1], dtype=torch.bool, device=input_features.device) hidden_states = self.input_linear(input_features.to(self.dtype)) all_hidden_states = (hidden_states,) if output_hidden_states else None blank_probs = None context_size = self.config.context_size seq = torch.arange(context_size, device=hidden_states.device) relpos_dist = seq.view(-1, 1) - seq.view(1, -1) attention_dists = torch.clamp(relpos_dist, -context_size, context_size) + self.config.max_pos_emb for layer_idx, layer in enumerate(self.layers, start=1): hidden_states = layer(hidden_states, attention_dists=attention_dists) if layer_idx == self.config.self_conditioning_layer: mid_logits = self.out(self.dropout(hidden_states)) mid_probs = torch.softmax(mid_logits.float(), dim=-1) blank_probs = mid_probs[:, :, 0] hidden_states = hidden_states + self.out_mid(mid_probs.to(hidden_states.dtype)) if output_hidden_states: all_hidden_states += (hidden_states,) hidden_states = self.dropout(hidden_states) logits = None loss = None if self.out_bpe is not None and blank_probs is not None: pool_window = self.config.bpe_pooling_window importance = 1.0 - blank_probs pooled = _posterior_weighted_pool(hidden_states.float(), importance, window_size=pool_window).to( hidden_states.dtype ) encoder_lengths = attention_mask.sum(dim=1) lengths = -(encoder_lengths // -pool_window) lengths_list = lengths.tolist() logits = self.out_bpe(torch.cat([pooled[i, :length] for i, length in enumerate(lengths_list)])) if labels is not None: logits_padded = logits.new_zeros(len(lengths_list), max(lengths_list), logits.shape[-1]) offset = 0 for i, length in enumerate(lengths_list): logits_padded[i, :length] = logits[offset : offset + length] offset += length log_probs = torch.log_softmax(logits_padded.float(), dim=-1) loss = ( F.ctc_loss( log_probs.transpose(0, 1), labels, lengths, label_lengths, blank=self.config.blank_token_id, reduction="sum", zero_infinity=True, ) / lengths.sum() ) return GraniteSpeechNarEncoderOutput( loss=loss, logits=logits, last_hidden_state=hidden_states, all_hidden_states=all_hidden_states, ) class GraniteSpeechNarLM(GraniteSpeechNarPreTrainedModel, GenerationMixin): """GraniteForCausalLM with a bidirectional (non-causal) backbone.""" _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_gather_output"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = GraniteSpeechNarModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, logits_to_keep: int | torch.Tensor = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: r""" Example: ```python >>> from transformers import AutoTokenizer, GraniteSpeechNarLM >>> model = GraniteSpeechNarLM.from_pretrained("meta-granite_speech_nar/GraniteSpeechNar-2-7b-hf") >>> tokenizer = AutoTokenizer.from_pretrained("meta-granite_speech_nar/GraniteSpeechNar-2-7b-hf") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, **kwargs, ) hidden_states = outputs.last_hidden_state slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) logits = logits / self.config.logits_scaling # main diff with Llama loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) class GraniteSpeechNarForASR(GraniteSpeechNarPreTrainedModel): def __init__(self, config: GraniteSpeechNarConfig): super().__init__(config) self.encoder = GraniteSpeechNarCTCEncoder(config.encoder_config) self.projector = GraniteSpeechNarProjector(config.projector_config) text_config = config.text_config if hasattr(config, "_attn_implementation"): text_config._attn_implementation = config._attn_implementation self.language_model = GraniteSpeechNarLM._from_config(text_config) self.post_init() def _ctc_collapse_decode( self, bpe_logits_flat: torch.Tensor, bpe_lengths: list[int], ) -> list[torch.Tensor]: """GPU CTC greedy decode: argmax -> unique_consecutive -> remove blank.""" blank_id = self.config.blank_token_id preds_flat = bpe_logits_flat.argmax(dim=-1) per_sample = preds_flat.split(bpe_lengths) return [(collapsed := torch.unique_consecutive(seq))[collapsed != blank_id] for seq in per_sample] def _add_insertion_slots(self, token_ids: torch.Tensor) -> torch.Tensor: """Insert blank tokens between each CTC token as editing slots for the LLM.""" blank_id = self.config.blank_token_id n = token_ids.numel() total_len = max(2 * n + 1, self.config.min_edit_sequence_length) idx = torch.arange(n, device=token_ids.device) out_idx = 2 * idx + 1 out = torch.full((total_len,), fill_value=blank_id, dtype=token_ids.dtype, device=token_ids.device) out[out_idx] = token_ids return out def _build_flat_inputs( self, ctc_token_ids: list[torch.Tensor], audio_embeds: torch.Tensor, audio_lengths: list[int], ) -> tuple[torch.Tensor, torch.Tensor, list[int]]: """Build flat (pad-free) LLM input: [audio_0, text_0, audio_1, text_1, ...]""" embed_tokens = self.language_model.model.embed_tokens embeds_list = [] position_ids_list = [] text_lengths = [] for i, audio_len in enumerate(audio_lengths): audio_emb = audio_embeds[i, :audio_len] text_ids_with_slots = self._add_insertion_slots(ctc_token_ids[i]) text_emb = embed_tokens(text_ids_with_slots) sample_embeds = torch.cat([audio_emb, text_emb], dim=0) embeds_list.append(sample_embeds) position_ids_list.append(torch.arange(sample_embeds.shape[0], device=audio_embeds.device)) text_lengths.append(text_ids_with_slots.shape[0]) flat_embeds = torch.cat(embeds_list, dim=0).unsqueeze(0) flat_position_ids = torch.cat(position_ids_list, dim=0).unsqueeze(0) return flat_embeds, flat_position_ids, text_lengths def forward( self, *, input_features: torch.Tensor, attention_mask: torch.Tensor | None = None, labels: torch.Tensor | None = None, label_lengths: torch.Tensor | None = None, output_encoder_logits: bool = False, **kwargs, ) -> GraniteSpeechNarOutput: r""" Args: input_features (`torch.Tensor` of shape `(batch_size, seq_len, input_dim)`): Mel spectrogram features. attention_mask (`torch.Tensor` of shape `(batch_size, seq_len)`, *optional*): Encoder attention mask (1 for valid frames, 0 for padding). labels (`torch.Tensor` of shape `(batch_size, max_label_len)`, *optional*): Ground truth LLM token IDs for training. label_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*): Number of valid tokens per sample in `labels`. output_encoder_logits (`bool`, *optional*, defaults to `False`): Whether to return encoder BPE logits. When False, the large logits tensor is freed early to reduce peak memory. Returns: [`GraniteSpeechNarOutput`] """ encoder_labels = labels if self.config.encoder_ctc_loss_lambda else None enc_out = self.encoder( input_features=input_features, attention_mask=attention_mask, output_hidden_states=True, labels=encoder_labels, label_lengths=label_lengths if encoder_labels is not None else None, ) if attention_mask is None: attention_mask = torch.ones(input_features.shape[:-1], dtype=torch.bool, device=input_features.device) encoder_lengths = attention_mask.sum(dim=1) pool_window = self.encoder.config.bpe_pooling_window bpe_lengths = (-(encoder_lengths // -pool_window)).tolist() ctc_token_ids = self._ctc_collapse_decode(enc_out.logits, bpe_lengths) multilayer_features = torch.cat( [enc_out.all_hidden_states[idx] for idx in self.config.encoder_layer_indices], dim=-1 ) encoder_loss = enc_out.loss encoder_logits = enc_out.logits if output_encoder_logits else None del enc_out audio_embeds = self.projector(multilayer_features) del multilayer_features if self.config.scale_projected_embeddings: embedding_multiplier = getattr(self.config.text_config, "embedding_multiplier", 1.0) audio_embeds = audio_embeds / embedding_multiplier audio_embeds = audio_embeds.to(self.language_model.model.embed_tokens.weight.dtype) audio_lengths = (encoder_lengths // self.projector.config.downsample_rate).cpu().tolist() flat_embeds, flat_position_ids, text_lengths = self._build_flat_inputs( ctc_token_ids, audio_embeds, audio_lengths ) llm_out = self.language_model( inputs_embeds=flat_embeds, position_ids=flat_position_ids, ) all_logits = llm_out.logits.squeeze(0) segment_lengths = [l for a, t in zip(audio_lengths, text_lengths) for l in (a, t)] text_logits = torch.cat(list(all_logits.split(segment_lengths)[1::2])) logits_per_sample = list(text_logits.split(text_lengths)) loss = None if labels is not None: log_probs = torch.log_softmax(text_logits.float(), dim=-1) log_probs_padded = log_probs.new_zeros(len(text_lengths), max(text_lengths), log_probs.shape[-1]) offset = 0 for i, tl in enumerate(text_lengths): log_probs_padded[i, :tl] = log_probs[offset : offset + tl] offset += tl input_lengths = torch.tensor(text_lengths, device=text_logits.device) loss = ( F.ctc_loss( log_probs_padded.transpose(0, 1), labels, input_lengths, label_lengths, blank=self.config.blank_token_id, reduction="sum", zero_infinity=True, ) / input_lengths.sum() ) if self.config.ce_loss_lambda > 0.0: ce_targets = torch.cat([self._add_insertion_slots(ids) for ids in ctc_token_ids]) ce_loss = F.cross_entropy( text_logits, ce_targets.long(), reduction="mean", ignore_index=-100, ) loss = loss + self.config.ce_loss_lambda * ce_loss if encoder_loss is not None: loss = loss + self.config.encoder_ctc_loss_lambda * encoder_loss return GraniteSpeechNarOutput( loss=loss, logits=logits_per_sample, encoder_logits=encoder_logits, encoder_preds=ctc_token_ids, ) @torch.inference_mode() def transcribe( self, input_features: torch.Tensor, attention_mask: torch.Tensor | None = None, output_encoder_logits: bool = False, ) -> GraniteSpeechNarOutput: """Single-pass non-autoregressive inference: forward + CTC collapse on LLM output. Returns token ID tensors in `preds`. Use `GraniteSpeechNarProcessor.batch_decode()` to convert to strings. """ output = self.forward( input_features=input_features, attention_mask=attention_mask, output_encoder_logits=output_encoder_logits, ) blank_id = self.config.blank_token_id preds = [] for sample_logits in output.logits: pred = torch.unique_consecutive(sample_logits.argmax(-1)) pred = pred[pred != blank_id] preds.append(pred) return GraniteSpeechNarOutput( preds=preds, logits=output.logits, encoder_logits=output.encoder_logits, encoder_preds=output.encoder_preds, ) __all__ = [ "GraniteSpeechNarModel", "GraniteSpeechNarCTCEncoder", "GraniteSpeechNarForASR", "GraniteSpeechNarLM", "GraniteSpeechNarPreTrainedModel", ]