#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/gradium_phonon_tts/modular_gradium_phonon_tts.py.
#               Do NOT edit this file manually as any edits will be overwritten by the generation of
#             the file from the modular. If any change should be done, please apply the change to the
#                          modular_gradium_phonon_tts.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 The HuggingFace Inc. 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

import torch
from torch import nn

from ... import initialization as init
from ...activations import ACT2FN
from ...cache_utils import Cache, DynamicCache
from ...integrations import use_kernel_forward_from_hub, use_kernelized_func
from ...masking_utils import create_causal_mask
from ...modeling_layers import GradientCheckpointingLayer
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
from ...processing_utils import Unpack
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
from ...utils.generic import merge_with_config_defaults
from ...utils.output_capturing import capture_outputs
from .configuration_gradium_phonon_tts import GradiumPhononTTSConfig, GradiumPhononTTSFlowHeadConfig
from .generation_gradium_phonon_tts import GradiumPhononTTSGenerationMixin


class GradiumPhononTTSTimestepNorm(nn.Module):
    """
    The normalization closing the time embeddings: the input divided by its standard deviation (unbiased variance, no
    centring), scaled by a learnt weight. Neither a LayerNorm (no centring) nor an RMSNorm (variance, not mean square).
    """

    def __init__(self, hidden_size: int, eps: float = 1e-5):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(hidden_size))
        self.variance_epsilon = eps

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        mean_square = hidden_states.pow(2).mean(-1, keepdim=True)
        return self.weight * hidden_states * torch.rsqrt(mean_square + self.variance_epsilon)


class GradiumPhononTTSMLP(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.activation_fn = ACT2FN[config.hidden_act]
        self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
        self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        hidden_states = self.fc1(hidden_states)
        hidden_states = self.activation_fn(hidden_states)
        hidden_states = self.fc2(hidden_states)
        return hidden_states


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_forward_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 GradiumPhononTTSAttention(nn.Module):
    """Multi-headed attention from 'Attention Is All You Need' paper"""

    def __init__(self, config: GradiumPhononTTSConfig, layer_idx: int):
        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 = self.head_dim**-0.5
        self.attention_dropout = config.attention_dropout
        self.is_causal = True

        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


class GradiumPhononTTSDecoderLayer(GradientCheckpointingLayer):
    def __init__(self, config: GradiumPhononTTSConfig, layer_idx: int):
        super().__init__()
        self.hidden_size = config.hidden_size

        self.self_attn = GradiumPhononTTSAttention(config=config, layer_idx=layer_idx)

        self.mlp = GradiumPhononTTSMLP(config)
        self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)

    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:
        residual = hidden_states
        hidden_states = self.input_layernorm(hidden_states)
        # Self Attention
        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

        # Fully Connected
        residual = hidden_states
        hidden_states = self.post_attention_layernorm(hidden_states)
        hidden_states = self.mlp(hidden_states)
        hidden_states = residual + hidden_states
        return hidden_states


class GradiumPhononTTSTimestepEmbedding(nn.Module):
    """Sinusoidal embedding of a flow time followed by a two-layer MLP and `GradiumPhononTTSTimestepNorm`."""

    def __init__(self, config: GradiumPhononTTSFlowHeadConfig):
        super().__init__()
        self.freqs = nn.Buffer(self.compute_default_freqs(config))
        self.fc1 = nn.Linear(config.frequency_embedding_size, config.hidden_size)
        self.fc2 = nn.Linear(config.hidden_size, config.hidden_size)
        self.act_fn = ACT2FN[config.hidden_act]
        self.norm = GradiumPhononTTSTimestepNorm(config.hidden_size, eps=config.rms_norm_eps)

    @staticmethod
    def compute_default_freqs(config: GradiumPhononTTSFlowHeadConfig) -> torch.Tensor:
        half_dim = config.frequency_embedding_size // 2
        return torch.exp(-math.log(config.max_period) * torch.arange(half_dim, dtype=torch.float32) / half_dim)

    def forward(self, times: torch.Tensor) -> torch.Tensor:
        # times: (batch_size, 1)
        angles = times * self.freqs.to(times.dtype)
        embedding = torch.cat([torch.cos(angles), torch.sin(angles)], dim=-1)
        hidden_states = self.fc2(self.act_fn(self.fc1(embedding)))
        return self.norm(hidden_states)


class GradiumPhononTTSFlowLossWeighting(nn.Module):
    """
    Learnt uncertainty weighting of the LSD loss terms (training only): an MLP mapping the start and end times of a
    term to its log-variance `w`, the term `L` becoming `L * exp(w) / latent_dim - w`. Zero-initialised, as in the
    original, and absent from the released checkpoints.
    """

    def __init__(self, config: GradiumPhononTTSFlowHeadConfig):
        super().__init__()
        sizes = [2] + [config.loss_weighting_hidden_size] * config.loss_weighting_num_layers
        self.layers = nn.ModuleList([nn.Linear(in_size, out_size) for in_size, out_size in zip(sizes[:-1], sizes[1:])])
        self.act = nn.ReLU()
        self.proj = nn.Linear(sizes[-1], 1)

    def forward(self, start_times: torch.Tensor, end_times: torch.Tensor) -> torch.Tensor:
        hidden_states = torch.cat([start_times, end_times], dim=-1)
        for layer in self.layers:
            hidden_states = self.act(layer(hidden_states))
        return self.proj(hidden_states)


@auto_docstring
class GradiumPhononTTSPreTrainedModel(PreTrainedModel):
    config: GradiumPhononTTSConfig
    base_model_prefix = "model"
    supports_gradient_checkpointing = True
    # the flow head runs as one unit per step: split across devices, its blocks would mix devices mid-computation
    _no_split_modules = ["GradiumPhononTTSDecoderLayer", "GradiumPhononTTSFlowHead"]
    _skip_keys_device_placement = ["past_key_values"]
    _supports_flash_attn = True
    _supports_sdpa = True
    _supports_flex_attn = True

    _can_compile_fullgraph = True
    _supports_attention_backend = True
    _can_record_outputs = {
        "hidden_states": GradiumPhononTTSDecoderLayer,
        "attentions": GradiumPhononTTSAttention,
    }
    input_modalities = ("text", "audio")

    @torch.no_grad()
    def _init_weights(self, module):
        super()._init_weights(module)
        if isinstance(module, GradiumPhononTTSTimestepNorm):
            init.ones_(module.weight)
        elif isinstance(module, GradiumPhononTTSTimestepEmbedding):
            init.copy_(module.freqs, module.compute_default_freqs(self.config.flow_head_config))
        elif isinstance(module, GradiumPhononTTSModel):
            init.zeros_(module.bos_latent)
        elif isinstance(module, GradiumPhononTTSFlowLossWeighting):
            for parameter in module.parameters():
                init.zeros_(parameter)
        elif isinstance(module, GradiumPhononTTSForConditionalGeneration):
            init.zeros_(module.latent_mean)
            init.ones_(module.latent_std)
            init.zeros_(module.latent_stats_num_updates)


class GradiumPhononTTSRotaryEmbedding(nn.Module):
    def __init__(self, config: GradiumPhononTTSConfig):
        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)

        self.inv_freq = nn.Buffer(inv_freq, persistent=False)
        self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False)

    @staticmethod
    def compute_default_rope_parameters(config: GradiumPhononTTSConfig, **kwargs) -> tuple[torch.Tensor, float]:
        """
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
        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.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):
        freqs = position_ids[..., None].float() * self.inv_freq.to(device=x.device, dtype=torch.float)
        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)


@auto_docstring(
    custom_intro="""
    The Gradium Phonon TTS backbone: a causal transformer over one stream made of the voice prompt (speaker-codec
    latents), the text tokens and the audio latents, returning the normalised hidden states.
    """
)
class GradiumPhononTTSModel(GradiumPhononTTSPreTrainedModel):
    def __init__(self, config: GradiumPhononTTSConfig):
        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(
            [GradiumPhononTTSDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
        )
        self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.rotary_emb = GradiumPhononTTSRotaryEmbedding(config=config)
        self.gradient_checkpointing = False
        self.audio_prompt_proj = nn.Linear(config.audio_prompt_dim, config.hidden_size, bias=False)
        self.audio_latent_proj = nn.Linear(config.latent_dim, config.hidden_size, bias=False)
        self.bos_latent = nn.Parameter(torch.zeros(config.latent_dim))

        self.num_speakers_embed = nn.Embedding(config.num_speakers_vocab_size, config.num_speakers_embedding_dim)
        self.num_speakers_proj = nn.Linear(config.num_speakers_embedding_dim, config.hidden_size, bias=False)
        self.duration_delta_proj = nn.Linear(config.duration_delta_embedding_dim, config.hidden_size, bias=False)

        # Initialize weights and apply final processing
        self.post_init()

    @merge_with_config_defaults
    @capture_outputs
    @auto_docstring
    def forward(
        self,
        input_ids: torch.LongTensor | None = None,
        audio_prompt_latents: torch.Tensor | None = None,
        audio_prompt_latents_mask: torch.Tensor | None = None,
        audio_latents: torch.Tensor | None = None,
        audio_latents_mask: torch.Tensor | None = None,
        attention_mask: torch.Tensor | None = None,
        position_ids: torch.LongTensor | None = None,
        past_key_values: Cache | None = None,
        inputs_embeds: torch.Tensor | None = None,
        use_cache: bool | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> BaseModelOutputWithPast:
        r"""
        audio_prompt_latents (`torch.Tensor` of shape `(batch_size, num_prompt_frames, latent_dim)`, *optional*):
            Voice-prompt latents of the audio tokenizer (encoded by the processor, or a checkpoint's `voices/`),
            right-padded to the longest voice of the batch, scattered into the `audio_prompt_token_id` positions.
        audio_prompt_latents_mask (`torch.Tensor` of shape `(batch_size, num_prompt_frames)`, *optional*):
            Mask of the voice frames (`1`) as opposed to padding (`0`) in `audio_prompt_latents`.
        audio_latents (`torch.Tensor` of shape `(batch_size, num_latents, latent_dim)`, *optional*):
            Normalised audio latents, scattered into the `audio_latent_token_id` positions. The `audio_bos_token_id`
            position before them, which closes the prompt and from which the first frame is generated, always gets the
            learnt BOS latent.
        audio_latents_mask (`torch.Tensor` of shape `(batch_size, num_latents)`, *optional*):
            Mask of each row's latents (`1`) as opposed to padding (`0`) in `audio_latents`, when the rows hold different
            numbers of latent positions (training).
        """
        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)

        # The first audio position holds the learnt BOS latent, through the same projection as the audio latents.
        bos_mask = self.get_token_mask(input_ids, inputs_embeds, self.config.audio_bos_token_id)
        bos_embeds = self.embed_audio_latents(self.bos_latent).to(inputs_embeds.device, inputs_embeds.dtype)
        inputs_embeds = torch.where(bos_mask, bos_embeds, inputs_embeds)

        if audio_prompt_latents is not None:
            if audio_prompt_latents_mask is not None:
                audio_prompt_latents = audio_prompt_latents[audio_prompt_latents_mask.bool()]
            # voices come in fp32 whatever the model's dtype
            prompt_embeds = self.audio_prompt_proj(audio_prompt_latents.to(self.audio_prompt_proj.weight.dtype))
            prompt_embeds = prompt_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
            prompt_mask = self.get_placeholder_mask(
                input_ids, inputs_embeds, prompt_embeds, self.config.audio_prompt_token_id
            )
            inputs_embeds = inputs_embeds.masked_scatter(prompt_mask, prompt_embeds)

        if audio_latents is not None:
            if audio_latents_mask is not None:
                audio_latents = audio_latents[audio_latents_mask.bool()]
            latent_embeds = self.embed_audio_latents(audio_latents).to(inputs_embeds.device, inputs_embeds.dtype)
            if latent_embeds.shape[:2] == inputs_embeds.shape[:2]:
                # one latent per position, as in a generation step: placed position-wise, with no data-dependent count
                # check, so that the step compiles with `fullgraph=True`
                latent_mask = self.get_token_mask(input_ids, inputs_embeds, self.config.audio_latent_token_id)
                inputs_embeds = torch.where(latent_mask, latent_embeds, inputs_embeds)
            else:
                latent_mask = self.get_placeholder_mask(
                    input_ids, inputs_embeds, latent_embeds, self.config.audio_latent_token_id
                )
                inputs_embeds = inputs_embeds.masked_scatter(latent_mask, latent_embeds)

        if use_cache and past_key_values is None:
            past_key_values = DynamicCache(config=self.config)

        if position_ids is None:
            past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
            position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
            position_ids = position_ids.unsqueeze(0)

        causal_mask = create_causal_mask(
            config=self.config,
            inputs_embeds=inputs_embeds,
            attention_mask=attention_mask,
            past_key_values=past_key_values,
            position_ids=position_ids,
        )

        hidden_states = inputs_embeds
        position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)

        for decoder_layer in self.layers[: self.config.num_hidden_layers]:
            hidden_states = decoder_layer(
                hidden_states,
                attention_mask=causal_mask,
                position_embeddings=position_embeddings,
                position_ids=position_ids,
                past_key_values=past_key_values,
                use_cache=use_cache,
                **kwargs,
            )

        hidden_states = self.norm(hidden_states)
        return BaseModelOutputWithPast(
            last_hidden_state=hidden_states,
            past_key_values=past_key_values,
        )

    def embed_audio_latents(self, audio_latents: torch.Tensor) -> torch.Tensor:
        """
        Embeds normalised audio latents (the learnt BOS latent or the generated ones) into the backbone stream, with the
        speaker conditioning added to every audio latent position.
        """
        # the generated latents are fp32 whatever the model's dtype
        latent_embeds = self.audio_latent_proj(audio_latents.to(self.audio_latent_proj.weight.dtype))
        return latent_embeds + self.get_condition_embeds(latent_embeds.device).to(latent_embeds.device)

    def get_token_mask(
        self, input_ids: torch.LongTensor | None, inputs_embeds: torch.Tensor, token_id: int
    ) -> torch.BoolTensor:
        """Mask `(batch_size, seq_len, 1)` of the `token_id` positions, from the ids or the embeddings."""
        if input_ids is None:
            token_embedding = self.get_input_embeddings()(
                torch.full((), token_id, dtype=torch.long, device=inputs_embeds.device)
            )
            return (inputs_embeds == token_embedding).all(-1, keepdim=True)
        return (input_ids == token_id).unsqueeze(-1).to(inputs_embeds.device)

    def get_placeholder_mask(
        self,
        input_ids: torch.LongTensor,
        inputs_embeds: torch.Tensor,
        features: torch.Tensor,
        placeholder_token_id: int,
    ) -> torch.BoolTensor:
        """
        Mask of the positions holding `placeholder_token_id`, checked to count as many entries as `features` has vectors.
        """
        if input_ids is None:
            placeholder_mask = inputs_embeds == self.get_input_embeddings()(
                torch.full((), placeholder_token_id, dtype=torch.long, device=inputs_embeds.device)
            )
            placeholder_mask = placeholder_mask.all(-1)
        else:
            placeholder_mask = input_ids == placeholder_token_id
        num_placeholders = placeholder_mask.sum()
        num_features = features.numel() // features.shape[-1]
        placeholder_mask = placeholder_mask.unsqueeze(-1).to(inputs_embeds.device)
        torch_compilable_check(
            num_placeholders * inputs_embeds.shape[-1] == features.numel(),
            f"Placeholder tokens ({num_placeholders}) and features ({num_features}) do not match for token id "
            f"{placeholder_token_id}.",
        )
        return placeholder_mask

    def get_condition_embeds(self, device: torch.device) -> torch.Tensor:
        """The sum of the conditions, one `hidden_size` vector (built on `device`, the modules called for offloading)."""
        num_speakers = torch.full((), self.config.num_speakers, dtype=torch.long, device=device)
        condition_embeds = self.num_speakers_proj(self.num_speakers_embed(num_speakers))
        half_dim = self.config.duration_delta_embedding_dim // 2
        exponents = torch.arange(half_dim, device=device, dtype=torch.float32) / (half_dim - 1)
        phases = self.config.duration_delta_scale * self.config.duration_delta
        phases = phases / self.config.duration_delta_max_period**exponents
        duration_embeds = torch.cat([phases.cos(), phases.sin()]).to(condition_embeds.dtype)
        condition_embeds = condition_embeds + self.duration_delta_proj(duration_embeds).to(condition_embeds.device)
        return condition_embeds


@auto_docstring(custom_intro="""Outputs of `GradiumPhononTTSForConditionalGeneration`.""")
@dataclass
class GradiumPhononTTSOutputWithPast(CausalLMOutputWithPast):
    r"""
    loss (`torch.Tensor` of shape `()`, *optional*, returned when `labels` is passed):
        Training loss: the LSD flow loss of the target latents plus `config.eos_loss_weight` times the end-of-speech loss.
    logits (`torch.Tensor` of shape `(batch_size, sequence_length, 1)`):
        End-of-speech logits, one per position.
    last_hidden_state (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
        Normalised hidden states of the backbone, which condition the flow head.
    """

    # Not in `CausalLMOutputWithPast`: generation conditions the flow head on the last hidden state at every step, and
    # `output_hidden_states=True` (CSM's way) would record every layer's hidden states at every step to read only it.
    last_hidden_state: torch.Tensor | None = None


class GradiumPhononTTSFlowLayerNorm(nn.LayerNorm):
    """
    `nn.LayerNorm` with its computation written out, as in the original's flow head: training backpropagates through a
    forward-mode JVP of the head (the LSD self-distillation term), where torch's fused layer norm returns wrong
    gradients, https://github.com/pytorch/pytorch/issues/196700. Same constructor, parameters and outputs as
    `nn.LayerNorm`.
    """

    # TODO: drop this class for `nn.LayerNorm` (a drop-in replacement, same state dict) once the fix,
    # https://github.com/pytorch/pytorch/pull/199914, is in the supported torch versions.
    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        mean = hidden_states.mean(-1, keepdim=True)
        variance = hidden_states.var(-1, unbiased=False, keepdim=True)
        hidden_states = (hidden_states - mean) * torch.rsqrt(variance + self.eps)
        if self.elementwise_affine:
            hidden_states = hidden_states * self.weight + self.bias
        return hidden_states


class GradiumPhononTTSFlowResBlock(nn.Module):
    """Residual MLP block modulated by adaptive layer norm (shift, scale and gate from the conditioning)."""

    def __init__(self, config: GradiumPhononTTSFlowHeadConfig):
        super().__init__()
        self.num_chunks = 3
        self.norm = GradiumPhononTTSFlowLayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.fc1 = nn.Linear(config.hidden_size, config.hidden_size)
        self.fc2 = nn.Linear(config.hidden_size, config.hidden_size)
        self.act_fn = ACT2FN[config.hidden_act]
        self.adaln_proj = nn.Linear(config.hidden_size, self.num_chunks * config.hidden_size)

    def forward(self, hidden_states: torch.Tensor, condition: torch.Tensor) -> torch.Tensor:
        shift, scale, gate = self.adaln_proj(self.act_fn(condition)).chunk(self.num_chunks, dim=-1)
        modulated = self.norm(hidden_states) * (1 + scale) + shift
        return hidden_states + gate * self.fc2(self.act_fn(self.fc1(modulated)))


class GradiumPhononTTSFlowFinalLayer(nn.Module):
    """Adaptive layer norm (shift and scale, no learnt affine) followed by the projection to the latent dimension."""

    def __init__(self, config: GradiumPhononTTSFlowHeadConfig):
        super().__init__()
        self.num_chunks = 2
        self.norm = GradiumPhononTTSFlowLayerNorm(
            config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False
        )
        self.adaln_proj = nn.Linear(config.hidden_size, self.num_chunks * config.hidden_size)
        self.act_fn = ACT2FN[config.hidden_act]
        self.proj = nn.Linear(config.hidden_size, config.latent_dim)

    def forward(self, hidden_states: torch.Tensor, condition: torch.Tensor) -> torch.Tensor:
        shift, scale = self.adaln_proj(self.act_fn(condition)).chunk(self.num_chunks, dim=-1)
        return self.proj(self.norm(hidden_states) * (1 + scale) + shift)


class GradiumPhononTTSFlowHead(nn.Module):
    """
    The flow head: an MLP with adaptive layer norm conditioned on the backbone hidden state. With `flow_type="lsd"` it
    predicts the velocity of a flow step from the current latent and the step's start and end times; with
    `flow_type="drifting"` it maps Gaussian noise to the latent directly and has no time conditioning.
    """

    def __init__(self, config: GradiumPhononTTSFlowHeadConfig):
        super().__init__()
        self.input_proj = nn.Linear(config.latent_dim, config.hidden_size)
        self.cond_proj = nn.Linear(config.condition_dim, config.hidden_size)
        # One embedding per flow time the head is conditioned on (start and end of the step for LSD), averaged.
        self.timestep_embeddings = nn.ModuleList(
            [GradiumPhononTTSTimestepEmbedding(config) for _ in range(config.num_time_conditions)]
        )
        self.layers = nn.ModuleList([GradiumPhononTTSFlowResBlock(config) for _ in range(config.num_hidden_layers)])
        self.final_layer = GradiumPhononTTSFlowFinalLayer(config)

    def forward(
        self,
        latents: torch.Tensor,
        condition: torch.Tensor,
        times: list[torch.Tensor] | None = None,
    ) -> torch.Tensor:
        hidden_states = self.input_proj(latents)
        condition = self.cond_proj(condition)
        if times:
            time_embedding = sum(embedding(time) for embedding, time in zip(self.timestep_embeddings, times))
            condition = condition + time_embedding / len(times)
        for layer in self.layers:
            hidden_states = layer(hidden_states, condition)
        return self.final_layer(hidden_states, condition)


@auto_docstring(
    custom_intro="""
    The Gradium Phonon TTS text-to-speech model: the backbone, the flow head that samples one audio latent per step and
    the end-of-speech head. It generates audio tokenizer latents, which the processor decodes into 24 kHz audio.
    """
)
class GradiumPhononTTSForConditionalGeneration(GradiumPhononTTSPreTrainedModel, GradiumPhononTTSGenerationMixin):
    # training-only state, absent from the released checkpoints
    _keys_to_ignore_on_load_missing = [r"loss_weighting\.", r"latent_stats_num_updates"]
    # in bf16, the EMA updates of the latent statistics round away; `freqs` is built in fp32 (and saved so)
    _keep_in_fp32_modules_strict = ["latent_mean", "latent_std", "freqs"]
    # the loss is a per-batch mean: the Trainer divides it by the gradient accumulation steps
    accepts_loss_kwargs = False
    # Gradium's runtime checkpoint also holds the codec (the processor's audio tokenizer) and training-only tensors
    _keys_to_ignore_on_load_unexpected = [r"^mimi\.", r"^flow_lm\.flow\.w_s_t\.", r"\.learnt_padding$"]

    def __init__(self, config: GradiumPhononTTSConfig):
        super().__init__(config)
        self.model = GradiumPhononTTSModel(config)
        self.flow_head = GradiumPhononTTSFlowHead(config.flow_head_config)
        self.eos_head = nn.Linear(config.hidden_size, 1)
        self.latent_mean = nn.Buffer(torch.zeros(config.latent_dim))
        self.latent_std = nn.Buffer(torch.ones(config.latent_dim))

        # training only, ~0.003% of the model weights: ok to always carry
        self.loss_weighting = GradiumPhononTTSFlowLossWeighting(config.flow_head_config)
        self.distill_generator = torch.Generator().manual_seed(0)
        self.latent_stats_num_updates = nn.Buffer(torch.zeros((), dtype=torch.long))
        # skips the device sync of `latent_stats_num_updates.item()` once the EMA is over
        self._latent_stats_frozen = False
        self.post_init()

    def get_input_embeddings(self):
        return self.model.embed_tokens

    def set_input_embeddings(self, value):
        self.model.embed_tokens = value

    @can_return_tuple
    @auto_docstring
    def forward(
        self,
        input_ids: torch.LongTensor | None = None,
        audio_prompt_latents: torch.Tensor | None = None,
        audio_prompt_latents_mask: torch.Tensor | None = None,
        audio_latents: torch.Tensor | None = None,
        labels: torch.Tensor | None = None,
        labels_mask: torch.Tensor | None = None,
        attention_mask: torch.Tensor | None = None,
        position_ids: torch.LongTensor | None = None,
        past_key_values: Cache | None = None,
        inputs_embeds: torch.Tensor | None = None,
        use_cache: bool | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> GradiumPhononTTSOutputWithPast:
        r"""
        audio_prompt_latents (`torch.Tensor` of shape `(batch_size, num_prompt_frames, latent_dim)`, *optional*):
            Voice-prompt latents of the audio tokenizer, right-padded, scattered into the `audio_prompt_token_id`
            positions.
        audio_prompt_latents_mask (`torch.Tensor` of shape `(batch_size, num_prompt_frames)`, *optional*):
            Mask of the voice frames (`1`) as opposed to padding (`0`) in `audio_prompt_latents`.
        audio_latents (`torch.Tensor` of shape `(batch_size, num_latents, latent_dim)`, *optional*):
            Normalised audio latents, scattered into the `audio_latent_token_id` positions.
        labels (`torch.Tensor` of shape `(batch_size, num_frames, latent_dim)`, *optional*):
            Target latents of the audio tokenizer (training), right-padded. Each row's prompt ends with the
            `audio_bos_token_id` position followed by one `audio_latent_token_id` position per frame: the model feeds the
            normalised targets (teacher forcing), applies the flow loss to the outputs of the BOS and all but the last
            frame, which predict the frames, and the end-of-speech loss to all of them, the last one being the end of
            speech.
        labels_mask (`torch.Tensor` of shape `(batch_size, num_frames)`, *optional*):
            Mask of each row's target frames (`1`) as opposed to padding (`0`) in `labels`.
        """
        if labels is not None and audio_latents is not None:
            raise ValueError(
                "Pass either `labels` (the model builds the teacher-forced latents from them) or `audio_latents`."
            )
        if labels is not None and self.config.flow_head_config.flow_type != "lsd":
            raise ValueError(
                f"Training supports the LSD flow head only; this one is `{self.config.flow_head_config.flow_type}`: it maps "
                "noise to the latent in one call, with no time conditioning, and needs its own (drifting) objective."
            )
        if labels is not None and input_ids is None:
            raise ValueError("Training needs `input_ids`, whose audio positions locate the frames.")

        audio_latents_mask = None
        if labels is not None:
            if labels_mask is None:
                labels_mask = torch.ones(labels.shape[:2], dtype=torch.long, device=labels.device)
            if self.training:
                self.update_latent_stats(labels, labels_mask)
            # teacher forcing: the normalised targets, after the BOS position
            normalized_labels = ((labels - self.latent_mean) / self.latent_std).to(labels.dtype)
            audio_latents, audio_latents_mask = normalized_labels, labels_mask

        outputs = self.model(
            input_ids=input_ids,
            audio_prompt_latents=audio_prompt_latents,
            audio_prompt_latents_mask=audio_prompt_latents_mask,
            audio_latents=audio_latents,
            audio_latents_mask=audio_latents_mask,
            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
        logits = self.eos_head(hidden_states)

        loss = None
        if labels is not None:
            # The audio positions of each row, in order (the BOS, then the frames): the outputs of all but the last
            # predict the target frames, the last one (whose input is the last frame) is the end of speech.
            latent_positions = (input_ids == self.config.audio_bos_token_id) | (
                input_ids == self.config.audio_latent_token_id
            )
            frame_mask = torch.cat([torch.ones_like(labels_mask[:, :1]), labels_mask], dim=1).bool()
            is_target = torch.cat([labels_mask, torch.zeros_like(labels_mask[:, :1])], dim=1)
            is_target = is_target[frame_mask].bool().to(hidden_states.device)
            latent_hidden_states = hidden_states[latent_positions.to(hidden_states.device)]
            loss = self.loss_function(
                flow_head=self.flow_head,
                conditions=latent_hidden_states[is_target],
                targets=normalized_labels[labels_mask.bool()].to(hidden_states.device),
                eos_logits=logits[latent_positions.to(logits.device)][:, 0],
                eos_labels=~is_target,
                config=self.config,
                loss_weighting=self.loss_weighting,
                distill_generator=self.distill_generator,
                training=self.training,
                **kwargs,
            )

        return GradiumPhononTTSOutputWithPast(
            loss=loss,
            logits=logits,
            last_hidden_state=hidden_states,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
        )

    def sample_latent(self, condition: torch.Tensor, noise: torch.Tensor, num_flow_steps: int) -> torch.Tensor:
        """
        Samples the next latent from `noise` with the flow head.

        Args:
            condition (`torch.Tensor` of shape `(batch_size, hidden_size)`):
                Backbone hidden state of the position being generated.
            noise (`torch.Tensor` of shape `(batch_size, latent_dim)`):
                Gaussian noise scaled by `sqrt(temperature)`, or zeros.
            num_flow_steps (`int`):
                Number of Euler steps of the LSD sampler (ignored by the drifting head, which takes one call).

        Returns:
            `torch.Tensor` of shape `(batch_size, latent_dim)`: the sampled latent, in the normalised space.
        """
        # CODEPATH: english_drifting_26-09 takes this side, every other checkpoint the LSD loop below
        if self.config.flow_head_config.flow_type == "drifting":
            # `.to`: with `device_map`, the flow head can sit on another device than the generation loop
            return self.flow_head(noise, condition).to(noise.device)

        # Lagrangian self-distillation: `num_flow_steps` Euler steps, each conditioned on its start and end times.
        latents = noise
        times = torch.ones((noise.shape[0], 1), device=noise.device, dtype=noise.dtype)
        for step in range(num_flow_steps):
            start_times = times * (step / num_flow_steps)
            end_times = times * ((step + 1) / num_flow_steps)
            velocity = self.flow_head(latents, condition, times=[start_times, end_times])
            latents = latents + velocity.to(latents.device) / num_flow_steps
        return latents

    @torch.no_grad()
    def update_latent_stats(self, labels: torch.Tensor, labels_mask: torch.Tensor):
        """
        Moves `latent_mean` and `latent_std` towards the statistics of the target frames, an exponential moving average
        of decay `config.latent_stats_ema_decay`, for the first `config.latent_stats_ema_steps` training forwards.
        """
        if self._latent_stats_frozen:
            return
        if self.latent_stats_num_updates.item() >= self.config.latent_stats_ema_steps:
            self._latent_stats_frozen = True
            return
        frames = labels[labels_mask.bool()].to(self.latent_mean.dtype)
        decay = self.config.latent_stats_ema_decay
        self.latent_mean.mul_(decay).add_(frames.mean(dim=0), alpha=1 - decay)
        self.latent_std.mul_(decay).add_(frames.std(dim=0), alpha=1 - decay)
        self.latent_stats_num_updates += 1

    def denormalize_latents(self, audio_latents: torch.Tensor) -> torch.Tensor:
        """Maps latents from the flow head's normalised space to the audio tokenizer's."""
        return (audio_latents * self.latent_std + self.latent_mean).to(audio_latents.dtype)


__all__ = ["GradiumPhononTTSPreTrainedModel", "GradiumPhononTTSModel", "GradiumPhononTTSForConditionalGeneration"]
