#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/nemotron3_diarization/modular_nemotron3_diarization.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_nemotron3_diarization.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 ...masking_utils import create_bidirectional_mask
from ...modeling_layers import GradientCheckpointingLayer
from ...modeling_outputs import BaseModelOutput
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 (
    ModelOutput,
    TransformersKwargs,
    auto_docstring,
    can_return_tuple,
    is_torchdynamo_compiling,
)
from ...utils.generic import merge_with_config_defaults
from ...utils.output_capturing import capture_outputs
from .configuration_nemotron3_diarization import (
    Nemotron3DiarizationAudioConfig,
    Nemotron3DiarizationConfig,
    Nemotron3DiarizationHeadConfig,
    Nemotron3DiarizationStreamingConfig,
)


class Nemotron3DiarizationSpeakerCache:
    """
    Streaming state of [`Nemotron3DiarizationForAudioFrameClassification`]: the Arrival-Order Speaker Cache and the
    FIFO queue of the most recent encoder frames, that every chunk attends to.

    Args:
        config (`Nemotron3DiarizationStreamingConfig`):
            Speaker-cache policy, and the FIFO sizes of streaming mode.
        fifo_length (`int`, *optional*):
            Capacity of the FIFO queue of the most recent encoder frames. Defaults to `config.fifo_length`.
        speaker_cache_update_period (`int`, *optional*):
            Number of encoder frames moved from the FIFO queue to the speaker cache when the queue overflows. Defaults
            to `config.speaker_cache_update_period`.
    """

    def __init__(
        self,
        config: Nemotron3DiarizationStreamingConfig,
        fifo_length: int | None = None,
        speaker_cache_update_period: int | None = None,
    ):
        self.fifo_length = fifo_length if fifo_length is not None else config.fifo_length
        self.speaker_cache_update_period = (
            speaker_cache_update_period
            if speaker_cache_update_period is not None
            else config.speaker_cache_update_period
        )
        self.speaker_cache_length = config.speaker_cache_length
        self.num_silence_frames = config.speaker_cache_silence_frames_per_speaker
        self.prediction_score_threshold = config.prediction_score_threshold
        self.latest_frames_score_boost = config.latest_frames_score_boost
        self.num_speakers = config.num_speakers
        self.subsampling_factor = config.subsampling_factor

        # share of the speaker cache every speaker is budgeted, excluding its reserved silence slots, and the frame
        # counts the score policy spends it on when the cache is compressed
        budget = self.speaker_cache_length // self.num_speakers - self.num_silence_frames
        self.min_positive_scores = math.floor(budget * config.min_positive_scores_rate)
        self.num_strong_boosted_frames = math.floor(budget * config.strong_boost_rate)
        self.num_weak_boosted_frames = math.floor(budget * config.weak_boost_rate)

        self.embeds: torch.Tensor | None = None
        self.probs: torch.Tensor | None = None
        self.fifo: torch.Tensor | None = None
        self.num_cache_frames = 0
        self.num_fifo_frames = 0
        self.is_compressed: bool = False
        self.is_initialized: bool = False

    def lazy_initialization(self, chunk_embeds: torch.Tensor):
        batch_size, _, hidden_size = chunk_embeds.shape
        tensor_kwargs = {"device": chunk_embeds.device, "dtype": chunk_embeds.dtype}
        self.embeds = torch.zeros(batch_size, self.speaker_cache_length, hidden_size, **tensor_kwargs)
        self.probs = torch.zeros(batch_size, self.speaker_cache_length, self.num_speakers, **tensor_kwargs)
        self.fifo = torch.zeros(batch_size, self.fifo_length, hidden_size, **tensor_kwargs)
        if not is_torchdynamo_compiling():
            torch._dynamo.mark_static_address(self.embeds)
            torch._dynamo.mark_static_address(self.probs)
            torch._dynamo.mark_static_address(self.fifo)
        self.is_initialized = True

    def get_embeds(self, chunk_embeds: torch.Tensor) -> torch.Tensor:
        if not self.is_initialized:
            self.lazy_initialization(chunk_embeds)
        return torch.cat([self.embeds[:, : self.num_cache_frames], self.fifo[:, : self.num_fifo_frames]], dim=1)

    def _pool_probs(self, logits: torch.Tensor, mask: torch.Tensor | None) -> torch.Tensor:
        """Speaker probabilities at the encoder frame rate, zeroed on the padding frames."""
        factor = self.subsampling_factor
        probs = nn.functional.avg_pool1d(logits.sigmoid().transpose(1, 2), factor, factor).transpose(1, 2)
        if mask is not None:
            probs = probs * mask.to(device=probs.device, dtype=probs.dtype)[..., None]
        return probs.to(self.probs)

    def _num_popped_frames(self, num_fifo_frames: int) -> int:
        """
        No frames move to the speaker cache until the FIFO overflows, then at least `speaker_cache_update_period`
        oldest frames are moved, plus any additional frames needed to restore fifo capacity.
        """
        if num_fifo_frames <= self.fifo_length:
            return 0

        num_popped = max(self.speaker_cache_update_period, num_fifo_frames - self.fifo_length)
        return min(num_popped, num_fifo_frames)

    def update(
        self,
        chunk_input_embeds: torch.Tensor,
        chunk_logits: torch.Tensor,
        silence_embeds: torch.Tensor,
        num_chunk_frames: int,
        mask: torch.Tensor | None = None,
    ):
        """
        Pushes a processed chunk to the FIFO queue, moving its oldest frames to the speaker cache when it overflows.

        Args:
            chunk_input_embeds (`torch.Tensor` of shape `(batch_size, num_input_frames, hidden_size)`):
                Encoder input of the step: the cached frames returned by `get_embeds`, the chunk and its look-ahead.
            chunk_logits (`torch.Tensor` of shape `(batch_size, num_input_frames * subsampling_factor, num_speakers)`):
                Speaker logits of the step, used to score the frames when the speaker cache is compressed.
            silence_embeds (`torch.Tensor` of shape `(hidden_size,)`):
                Learned silence embedding filling the reserved silence slots of a compressed cache.
            num_chunk_frames (`int`):
                Number of chunk frames following the cached frames in `chunk_input_embeds`. Only those join the
                FIFO queue: the look-ahead frames after them are fed again at the next step.
            mask (`torch.Tensor` of shape `(batch_size, num_input_frames)`, *optional*):
                Valid frames of `chunk_input_embeds`, whose padding frames are given zero speaker probabilities.
        """
        if not self.is_initialized:
            self.lazy_initialization(chunk_input_embeds)

        num_cache_frames, num_fifo_frames = self.num_cache_frames, self.num_fifo_frames
        probs = self._pool_probs(chunk_logits, mask)

        chunk_start = num_cache_frames + num_fifo_frames
        chunk_embeds = chunk_input_embeds[:, chunk_start : chunk_start + num_chunk_frames]
        fifo_embeds = torch.cat([self.fifo[:, :num_fifo_frames], chunk_embeds], dim=1)

        num_popped = self._num_popped_frames(fifo_embeds.shape[1])
        if num_popped:
            fifo_probs = probs[:, num_cache_frames : num_cache_frames + fifo_embeds.shape[1]]
            # an uncompressed cache still holds plain chunk frames, whose probabilities this step re-estimates
            # a compressed one is out of order, so the probs stored alongside its frames are the only ones
            stored_probs = self.probs[:, :num_cache_frames] if self.is_compressed else probs[:, :num_cache_frames]
            cache_embeds = torch.cat([self.embeds[:, :num_cache_frames], fifo_embeds[:, :num_popped]], dim=1)
            cache_probs = torch.cat([stored_probs, fifo_probs[:, :num_popped]], dim=1)
            fifo_embeds = fifo_embeds[:, num_popped:]

            if cache_embeds.shape[1] > self.speaker_cache_length:
                cache_embeds, cache_probs = self._compress(cache_embeds, cache_probs, silence_embeds)
                self.is_compressed = True
            self.num_cache_frames = cache_embeds.shape[1]

            cache_indices = torch.arange(self.num_cache_frames, device=self.embeds.device)
            self.embeds.index_copy_(1, cache_indices, cache_embeds)
            self.probs.index_copy_(1, cache_indices, cache_probs)

        self.num_fifo_frames = fifo_embeds.shape[1]
        self.fifo.index_copy_(1, torch.arange(self.num_fifo_frames, device=self.fifo.device), fifo_embeds)

    def _get_frame_scores(self, probs: torch.Tensor) -> torch.Tensor:
        threshold = self.prediction_score_threshold
        log_probs = torch.log(probs.clamp(min=threshold))
        log_complements = torch.log((1.0 - probs).clamp(min=threshold))

        scores = log_probs - log_complements + log_complements.sum(dim=-1, keepdim=True) - math.log(0.5)

        is_speech = probs > 0.5
        scores = scores.masked_fill(~is_speech, float("-inf"))
        is_positive = scores > 0
        has_enough_positive = is_positive.sum(dim=1, keepdim=True) >= self.min_positive_scores

        scores = scores.masked_fill(~is_positive & is_speech & has_enough_positive, float("-inf"))
        return scores

    def _boost_scores(self, scores: torch.Tensor, num_boosted: int, boost: float) -> torch.Tensor:
        _, topk_indices = torch.topk(scores, num_boosted, dim=1, sorted=False)
        scores = scores.scatter_add(1, topk_indices, scores.new_full(topk_indices.shape, boost))
        return scores

    def _compress(self, embeds: torch.Tensor, probs: torch.Tensor, silence_embeds: torch.Tensor):
        """
        Keeps the `speaker_cache_length` most important frames, grouped by speaker and in their original order within
        a speaker. `speaker_cache_silence_frames_per_speaker` slots per speaker are filled with `silence_embeds`.
        """
        batch_size, num_frames, num_speakers = probs.shape

        scores = self._get_frame_scores(probs)
        # frames beyond the cache capacity are the ones popped from fifo
        scores[:, self.speaker_cache_length :] += self.latest_frames_score_boost

        scores = self._boost_scores(scores, self.num_strong_boosted_frames, boost=-2.0 * math.log(0.5))
        scores = self._boost_scores(scores, self.num_weak_boosted_frames, boost=-math.log(0.5))
        scores = nn.functional.pad(scores, (0, 0, 0, self.num_silence_frames), value=float("inf"))
        embeds = torch.cat([embeds, silence_embeds.to(embeds).view(1, 1, -1).expand(batch_size, 1, -1)], dim=1)
        probs = nn.functional.pad(probs, (0, 0, 0, 1))

        num_scored_frames = num_frames + self.num_silence_frames
        sentinel = num_scored_frames * num_speakers
        flat_scores = scores.transpose(1, 2).reshape(batch_size, -1)

        topk_scores, topk_indices = torch.topk(flat_scores, self.speaker_cache_length, dim=1, sorted=False)
        topk_indices = topk_indices.masked_fill(topk_scores == float("-inf"), sentinel)
        topk_indices, _ = torch.sort(topk_indices, dim=1)
        frame_indices = torch.where(
            topk_indices == sentinel, num_frames, (topk_indices % num_scored_frames).clamp(max=num_frames)
        )

        batch_indices = torch.arange(batch_size, device=probs.device)[:, None]
        return (
            embeds[batch_indices.to(embeds.device), frame_indices.to(embeds.device)],
            probs[batch_indices, frame_indices],
        )


@auto_docstring(
    custom_intro="""
    Output of [`Nemotron3DiarizationForAudioFrameClassification`].
    """
)
@dataclass
class Nemotron3DiarizationOutput(ModelOutput):
    r"""
    logits (`torch.FloatTensor` of shape `(batch_size, num_frames, config.head_config.num_speakers)`):
        Per-frame speaker activity logits at the spectrogram frame rate. `logits.sigmoid()` gives the probability
        that each speaker is active in each frame; speakers are ordered by their first arrival in the audio.
    hidden_states (`tuple[torch.FloatTensor, ...]`, *optional*, returned when `output_hidden_states=True`):
        Encoder hidden states of every chunk, in chunk order: the encoder runs once per chunk, so the tuple holds
        `config.audio_config.num_hidden_layers + 1` tensors per chunk. Their sequence length is the chunk's, cache
        and look-ahead frames included.
    attentions (`tuple[torch.FloatTensor, ...]`, *optional*, returned when `output_attentions=True`):
        Encoder attention weights of every chunk, in chunk order, `config.audio_config.num_hidden_layers` tensors
        per chunk.
    speaker_cache (`Nemotron3DiarizationSpeakerCache`, *optional*, returned in streaming mode):
        Updated streaming state, to pass to the forward of the next audio chunk of the same streams.
    """

    logits: torch.Tensor | None = None
    hidden_states: tuple[torch.Tensor, ...] | None = None
    attentions: tuple[torch.Tensor, ...] | None = None
    speaker_cache: Nemotron3DiarizationSpeakerCache | None = None


class Nemotron3DiarizationFeatureStacking(nn.Module):
    """Stacks `subsampling_factor` consecutive spectrogram frames and projects them to the encoder hidden size."""

    def __init__(self, config: Nemotron3DiarizationAudioConfig):
        super().__init__()
        self.subsampling_factor = config.subsampling_factor
        self.projection = nn.Linear(config.subsampling_factor * config.num_mel_bins, config.hidden_size, bias=False)

    def forward(self, input_features: torch.Tensor) -> torch.Tensor:
        batch_size, num_frames, num_mel_bins = input_features.shape
        # The original zero-pads the last incomplete group of frames.
        padding = -num_frames % self.subsampling_factor
        input_features = nn.functional.pad(input_features, (0, 0, 0, padding))
        stacked = input_features.reshape(
            batch_size, (num_frames + padding) // self.subsampling_factor, num_mel_bins * self.subsampling_factor
        )
        return self.projection(stacked)


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


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)


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


def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
    cos = cos.unsqueeze(unsqueeze_dim)
    sin = sin.unsqueeze(unsqueeze_dim)

    rotary_dim = cos.shape[-1]
    q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
    k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]

    # Apply rotary embeddings on the first half or full tensor
    q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
    k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)

    # Concatenate back to full shape
    q_embed = torch.cat([q_embed, q_pass], dim=-1)
    k_embed = torch.cat([k_embed, k_pass], dim=-1)
    return q_embed, k_embed


class Nemotron3DiarizationAttention(nn.Module):
    """Multi-headed attention from 'Attention Is All You Need' paper"""

    def __init__(self, config: Nemotron3DiarizationAudioConfig, 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 = False
        # The original fused query/key/value projection has no bias while the output projection has one.
        self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
        self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
        self.v_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
        self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)

    def forward(
        self,
        hidden_states: torch.Tensor,
        position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
        attention_mask: torch.Tensor | 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)

        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=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 Nemotron3DiarizationMLP(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)
        self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)

    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


class Nemotron3DiarizationAudioLayer(GradientCheckpointingLayer):
    def __init__(self, config: Nemotron3DiarizationAudioConfig, layer_idx: int):
        super().__init__()
        self.embed_dim = config.hidden_size
        self.self_attn = Nemotron3DiarizationAttention(config, layer_idx)
        self.layer_norm1 = nn.LayerNorm(config.hidden_size)
        self.mlp = Nemotron3DiarizationMLP(config)
        self.layer_norm2 = nn.LayerNorm(config.hidden_size)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: torch.Tensor,
        **kwargs: Unpack[TransformersKwargs],
    ) -> torch.FloatTensor:
        residual = hidden_states

        hidden_states = self.layer_norm1(hidden_states)
        hidden_states, _ = self.self_attn(
            hidden_states=hidden_states,
            attention_mask=attention_mask,
            **kwargs,
        )
        hidden_states = residual + hidden_states

        residual = hidden_states
        hidden_states = self.layer_norm2(hidden_states)
        hidden_states = self.mlp(hidden_states)
        hidden_states = residual + hidden_states

        return hidden_states


@auto_docstring
class Nemotron3DiarizationPreTrainedModel(PreTrainedModel):
    config: Nemotron3DiarizationConfig
    base_model_prefix = "model"
    supports_gradient_checkpointing = True
    _no_split_modules = ["Nemotron3DiarizationAudioLayer"]
    _skip_keys_device_placement = ["speaker_cache"]
    _supports_flash_attn = True
    _supports_sdpa = True
    _supports_flex_attn = True

    _can_compile_fullgraph = True
    _supports_attention_backend = True
    _can_record_outputs = {
        "hidden_states": Nemotron3DiarizationAudioLayer,
        "attentions": Nemotron3DiarizationAttention,
    }
    main_input_name = "input_features"
    input_modalities = "audio"

    @torch.no_grad()
    def _init_weights(self, module):
        super()._init_weights(module)
        if isinstance(module, Nemotron3DiarizationForAudioFrameClassification):
            init.zeros_(module.silence_embeds)
        elif isinstance(module, Nemotron3DiarizationSubpixelUpsampler):
            # The original initializes the sub-pixel convolution as nearest-neighbour upsampling: zero weights except
            # a repeated identity on the center tap, zero bias.
            weight = torch.zeros_like(module.conv.weight)
            hidden_size = module.conv.in_channels
            weight[:, :, 1] = torch.eye(hidden_size, device=weight.device, dtype=weight.dtype).repeat(
                module.upsample_factor, 1
            )
            init.copy_(module.conv.weight, weight)
            init.zeros_(module.conv.bias)


@auto_docstring
class Nemotron3DiarizationAudioModel(Nemotron3DiarizationPreTrainedModel):
    config: Nemotron3DiarizationAudioConfig

    def __init__(self, config: Nemotron3DiarizationAudioConfig):
        super().__init__(config)
        self.embedder = Nemotron3DiarizationFeatureStacking(config)
        self.input_layer_norm = nn.LayerNorm(config.hidden_size)
        self.layers = nn.ModuleList(
            [Nemotron3DiarizationAudioLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
        )
        self.layer_norm = nn.LayerNorm(config.hidden_size)
        self.rotary_emb = Nemotron3DiarizationRotaryEmbedding(config)
        self.post_init()

    @merge_with_config_defaults
    @capture_outputs
    @auto_docstring
    def forward(
        self,
        input_features: torch.Tensor | None = None,
        attention_mask: torch.Tensor | None = None,
        inputs_embeds: torch.Tensor | None = None,
        position_ids: torch.Tensor | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> BaseModelOutput:
        if (input_features is None) == (inputs_embeds is None):
            raise ValueError("Provide exactly one of `input_features` and `inputs_embeds`.")

        if inputs_embeds is None:
            inputs_embeds = self.embedder(input_features)
            # if inputs_embeds is provided, we expect attention_mask already downsampled
            if attention_mask is not None:
                attention_mask = attention_mask[:, :: self.config.subsampling_factor].bool()

        if position_ids is None:
            position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device)[None, :]
        position_embeddings = self.rotary_emb(inputs_embeds, position_ids)

        attention_mask = create_bidirectional_mask(
            config=self.config, inputs_embeds=inputs_embeds, attention_mask=attention_mask
        )
        hidden_states = self.input_layer_norm(inputs_embeds)
        for encoder_layer in self.layers:
            hidden_states = encoder_layer(
                hidden_states,
                attention_mask=attention_mask,
                position_embeddings=position_embeddings,
                **kwargs,
            )
        return BaseModelOutput(last_hidden_state=self.layer_norm(hidden_states))


class Nemotron3DiarizationSubpixelUpsampler(nn.Module):
    """Upsamples the encoder frame rate back to the spectrogram frame rate with a sub-pixel convolution."""

    def __init__(self, config: Nemotron3DiarizationHeadConfig):
        super().__init__()
        self.upsample_factor = config.subsampling_factor
        self.conv = nn.Conv1d(
            config.hidden_size,
            config.hidden_size * config.subsampling_factor,
            kernel_size=3,
            padding=1,
        )

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        batch_size, num_frames, hidden_size = hidden_states.shape
        hidden_states = self.conv(hidden_states.transpose(1, 2)).transpose(1, 2)
        return hidden_states.reshape(batch_size, num_frames * self.upsample_factor, hidden_size)


class Nemotron3DiarizationClassificationHead(nn.Module):
    def __init__(self, config: Nemotron3DiarizationHeadConfig):
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.out_proj = nn.Linear(config.hidden_size, config.num_speakers)
        self.act_fn = ACT2FN["relu"]

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        hidden_states = self.dense(self.act_fn(hidden_states))
        return self.out_proj(self.act_fn(hidden_states))


@auto_docstring(
    custom_intro="""
    The Nemotron3Diarization model without the speaker classifier: encodes one chunk (with its cached frames) and
    upsamples the encoder frames back to the spectrogram frame rate. It holds no streaming state, see
    [`Nemotron3DiarizationForAudioFrameClassification`] for the chunked forward.
    """
)
class Nemotron3DiarizationModel(Nemotron3DiarizationPreTrainedModel):
    def __init__(self, config: Nemotron3DiarizationConfig):
        super().__init__(config)
        self.audio_tower = Nemotron3DiarizationAudioModel(config.audio_config)
        self.proj = nn.Linear(config.head_config.audio_hidden_size, config.head_config.hidden_size)
        self.upsampler = Nemotron3DiarizationSubpixelUpsampler(config.head_config)
        self.post_init()

    @can_return_tuple
    @auto_docstring
    def forward(
        self,
        input_features: torch.Tensor | None = None,
        attention_mask: torch.Tensor | None = None,
        inputs_embeds: torch.Tensor | None = None,
        position_ids: torch.Tensor | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> BaseModelOutput:
        audio_outputs: BaseModelOutput = self.audio_tower(
            input_features=input_features,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            position_ids=position_ids,
            **kwargs,
        )
        hidden_states = self.upsampler(self.proj(audio_outputs.last_hidden_state))
        return BaseModelOutput(
            last_hidden_state=hidden_states,
            hidden_states=audio_outputs.hidden_states,
            attentions=audio_outputs.attentions,
        )


@auto_docstring(
    custom_intro="""
    Streaming Sortformer speaker diarization model: predicts, for every spectrogram frame, the activity of up to
    `config.head_config.num_speakers` speakers ordered by first arrival. Audio is processed chunk by chunk, each
    chunk attending to a few look-ahead frames and to the Arrival-Order Speaker Cache and FIFO queue carried in a
    [`Nemotron3DiarizationSpeakerCache`]. A whole recording is chunked by the forward itself (offline mode); a stream
    is fed one chunk per forward (streaming mode).
    """
)
class Nemotron3DiarizationForAudioFrameClassification(Nemotron3DiarizationPreTrainedModel):
    def __init__(self, config: Nemotron3DiarizationConfig):
        super().__init__(config)
        self.model = Nemotron3DiarizationModel(config)
        self.classifier = Nemotron3DiarizationClassificationHead(config.head_config)
        self.silence_embeds = nn.Parameter(torch.zeros(config.audio_config.hidden_size))
        self.post_init()

    @can_return_tuple
    @auto_docstring
    def forward(
        self,
        input_features: torch.Tensor,
        attention_mask: torch.Tensor | None = None,
        speaker_cache: Nemotron3DiarizationSpeakerCache | None = None,
        num_lookahead_frames: int | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> Nemotron3DiarizationOutput:
        r"""
        speaker_cache (`Nemotron3DiarizationSpeakerCache`, *optional*):
            Streaming state returned by the forward of the previous chunk of the same audio streams.
        num_lookahead_frames (`int`, *optional*):
            Streaming mode: number of trailing encoder frames of the input that are look-ahead only. They are attended
            to, but their logits are not returned and they do not join the FIFO queue, as they open the next chunk.
            [`Nemotron3DiarizationProcessor`] sets it for every chunk but the last one of a session.

            The two arguments select the mode. Streaming mode, one chunk per forward: `num_lookahead_frames` given
            (a first chunk creates the `speaker_cache`, later chunks receive it), or `speaker_cache` given alone (the
            last chunk of the session, no look-ahead). The input minus its look-ahead is one chunk, whatever its
            length, pushed as a whole to the FIFO queue sized by `config.streaming_config`. Offline mode, neither
            given: the input is a whole recording, split by the forward into chunks of `config.chunk_length` encoder
            frames that take up to `config.chunk_right_context` look-ahead frames from the following ones, with a
            FIFO queue sized by `config.fifo_length`; no cache is returned.

        Example:

        ```python
        >>> from transformers import AutoModelForAudioFrameClassification, AutoProcessor
        >>> from transformers.audio_utils import load_audio

        >>> model_id = "nvidia/Nemotron-3-Diarization"
        >>> processor = AutoProcessor.from_pretrained(model_id)
        >>> model = AutoModelForAudioFrameClassification.from_pretrained(model_id, device_map="auto")

        >>> sampling_rate = processor.feature_extractor.sampling_rate
        >>> audio = load_audio(
        ...     "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/en-Alice_woman.wav",
        ...     sampling_rate=sampling_rate,
        ... )
        >>> inputs = processor(audio, sampling_rate=sampling_rate).to(model.device, dtype=model.dtype)
        >>> probabilities = model(**inputs).logits.sigmoid()  # (1, num_frames, 8), one frame every 10 ms
        ```
        """
        is_streaming = num_lookahead_frames is not None or speaker_cache is not None
        if speaker_cache is None:
            # the cache defaults to the streaming FIFO sizes, offline mode overrides them
            offline_sizes = {}
            if not is_streaming:
                offline_sizes = {
                    "fifo_length": self.config.fifo_length,
                    "speaker_cache_update_period": self.config.speaker_cache_update_period,
                }
            speaker_cache = Nemotron3DiarizationSpeakerCache(self.config.streaming_config, **offline_sizes)
        if num_lookahead_frames is None:
            num_lookahead_frames = 0

        batch_size, num_frames, _ = input_features.shape
        inputs_embeds = self.model.audio_tower.embedder(input_features)
        num_embeds = inputs_embeds.shape[1]
        subsampling_factor = self.config.audio_config.subsampling_factor

        num_chunk_embeds = num_embeds - num_lookahead_frames
        if not is_torchdynamo_compiling() and (num_lookahead_frames < 0 or num_chunk_embeds < 1):
            raise ValueError(
                f"`num_lookahead_frames` ({num_lookahead_frames}) must be between 0 and one less than the number of "
                f"encoder frames of the input ({num_embeds})."
            )

        embed_mask = None
        if attention_mask is not None:
            embed_mask = attention_mask[:, ::subsampling_factor].bool()

        if is_streaming:
            chunk_length, chunk_right_context = num_chunk_embeds, num_lookahead_frames
        else:
            chunk_length, chunk_right_context = self.config.chunk_length, self.config.chunk_right_context

        logits = []
        # the encoder runs once per chunk, so its recorded outputs are concatenated in chunk order
        all_hidden_states, all_attentions = (), ()
        for start_idx in range(0, num_chunk_embeds, chunk_length):
            end_idx = min(start_idx + chunk_length, num_chunk_embeds)
            num_chunk_frames = end_idx - start_idx
            chunk_embeds = inputs_embeds[:, start_idx : min(end_idx + chunk_right_context, num_embeds)]

            cached_embeds = speaker_cache.get_embeds(chunk_embeds)
            cached_length = cached_embeds.shape[1]
            chunk_input_embeds = torch.cat([cached_embeds, chunk_embeds], dim=1)

            step_mask = None
            if embed_mask is not None:
                chunk_mask = embed_mask[:, start_idx : start_idx + chunk_embeds.shape[1]]
                step_mask = torch.cat([chunk_mask.new_ones(batch_size, cached_length), chunk_mask], dim=1)

            # positions restart at every chunk
            position_ids = torch.arange(chunk_input_embeds.shape[1], device=chunk_input_embeds.device)[None, :]
            outputs: BaseModelOutput = self.model(
                inputs_embeds=chunk_input_embeds,
                attention_mask=step_mask,
                position_ids=position_ids,
                **kwargs,
            )
            all_hidden_states += outputs.hidden_states or ()
            all_attentions += outputs.attentions or ()
            chunk_logits = self.classifier(outputs.last_hidden_state)
            speaker_cache.update(
                chunk_input_embeds, chunk_logits, self.silence_embeds, num_chunk_frames, mask=step_mask
            )

            start_logit_idx = cached_length * subsampling_factor
            end_logit_idx = (cached_length + num_chunk_frames) * subsampling_factor
            logits.append(chunk_logits[:, start_logit_idx:end_logit_idx])

        # with no look-ahead, the last encoder frame may be the padding added by feature stacking
        logits = torch.cat(logits, dim=1)[:, :num_frames]

        return Nemotron3DiarizationOutput(
            logits=logits,
            hidden_states=all_hidden_states or None,
            attentions=all_attentions or None,
            speaker_cache=speaker_cache if is_streaming else None,
        )


__all__ = [
    "Nemotron3DiarizationAudioModel",
    "Nemotron3DiarizationForAudioFrameClassification",
    "Nemotron3DiarizationModel",
    "Nemotron3DiarizationOutput",
    "Nemotron3DiarizationPreTrainedModel",
    "Nemotron3DiarizationSpeakerCache",
]
