# 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 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 ...masking_utils import create_causal_mask
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from ...modeling_utils import 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 ..jais2.modeling_jais2 import Jais2DecoderLayer
from ..llama.modeling_llama import (
    LlamaModel,
    LlamaPreTrainedModel,
)
from ..mimi.modeling_mimi import MimiMLP
from .configuration_pocket_tts import PocketTTSConfig, PocketTTSFlowHeadConfig
from .generation_pocket_tts import PocketTTSGenerationMixin


@auto_docstring(custom_intro="""Outputs of `PocketTTSForConditionalGeneration`.""")
@dataclass
class PocketTTSOutputWithPast(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 PocketTTSMLP(MimiMLP): ...


class PocketTTSDecoderLayer(Jais2DecoderLayer): ...


class PocketTTSTimestepNorm(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:
        variance = hidden_states.var(-1, keepdim=True) + self.variance_epsilon
        return hidden_states * (self.weight * torch.rsqrt(variance))


class PocketTTSFlowLayerNorm(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 PocketTTSTimestepEmbedding(nn.Module):
    """Sinusoidal embedding of a flow time followed by a two-layer MLP and `PocketTTSTimestepNorm`."""

    def __init__(self, config: PocketTTSFlowHeadConfig):
        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 = PocketTTSTimestepNorm(config.hidden_size, eps=config.rms_norm_eps)

    @staticmethod
    def compute_default_freqs(config: PocketTTSFlowHeadConfig) -> 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 PocketTTSFlowResBlock(nn.Module):
    """Residual MLP block modulated by adaptive layer norm (shift, scale and gate from the conditioning)."""

    def __init__(self, config: PocketTTSFlowHeadConfig):
        super().__init__()
        self.num_chunks = 3
        self.norm = PocketTTSFlowLayerNorm(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 PocketTTSFlowFinalLayer(nn.Module):
    """Adaptive layer norm (shift and scale, no learnt affine) followed by the projection to the latent dimension."""

    def __init__(self, config: PocketTTSFlowHeadConfig):
        super().__init__()
        self.num_chunks = 2
        self.norm = PocketTTSFlowLayerNorm(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 PocketTTSFlowHead(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: PocketTTSFlowHeadConfig):
        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(
            [PocketTTSTimestepEmbedding(config) for _ in range(config.num_time_conditions)]
        )
        self.layers = nn.ModuleList([PocketTTSFlowResBlock(config) for _ in range(config.num_hidden_layers)])
        self.final_layer = PocketTTSFlowFinalLayer(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)


class PocketTTSFlowLossWeighting(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: PocketTTSFlowHeadConfig):
        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 PocketTTSPreTrainedModel(LlamaPreTrainedModel):
    config: PocketTTSConfig
    # the flow head runs as one unit per step: split across devices, its blocks would mix devices mid-computation
    _no_split_modules = ["PocketTTSDecoderLayer", "PocketTTSFlowHead"]
    input_modalities = ("text", "audio")

    @torch.no_grad()
    def _init_weights(self, module):
        PreTrainedModel._init_weights(self, module)
        if isinstance(module, PocketTTSTimestepNorm):
            init.ones_(module.weight)
        elif isinstance(module, PocketTTSTimestepEmbedding):
            init.copy_(module.freqs, module.compute_default_freqs(self.config.flow_head_config))
        elif isinstance(module, PocketTTSModel):
            init.zeros_(module.bos_latent)
        elif isinstance(module, PocketTTSFlowLossWeighting):
            for parameter in module.parameters():
                init.zeros_(parameter)
        elif isinstance(module, PocketTTSForConditionalGeneration):
            init.zeros_(module.latent_mean)
            init.ones_(module.latent_std)
            init.zeros_(module.latent_stats_num_updates)


@auto_docstring(
    custom_intro="""
    The Pocket TTS backbone: a causal transformer over one stream made of the voice prompt, the text tokens and the audio
    latents, returning the normalised hidden states. The voice prompt and the audio latents are latents of the audio
    tokenizer, which the processor holds.
    """
)
class PocketTTSModel(LlamaModel):
    def __init__(self, config: PocketTTSConfig):
        super().__init__(config)
        self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.audio_prompt_proj = nn.Linear(config.latent_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))

    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."""
        # the generated latents are fp32 whatever the model's dtype
        return self.audio_latent_proj(audio_latents.to(self.audio_latent_proj.weight.dtype))

    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

    @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,
        )


@auto_docstring(
    custom_intro="""
    The Pocket 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 PocketTTSForConditionalGeneration(PocketTTSPreTrainedModel, PocketTTSGenerationMixin):
    # 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

    def __init__(self, config: PocketTTSConfig):
        super().__init__(config)
        self.model = PocketTTSModel(config)
        self.flow_head = PocketTTSFlowHead(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 = PocketTTSFlowLossWeighting(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],
    ) -> PocketTTSOutputWithPast:
        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 PocketTTSOutputWithPast(
            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__ = [
    "PocketTTSPreTrainedModel",
    "PocketTTSModel",
    "PocketTTSForConditionalGeneration",
]
