#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/muse_spark/modular_muse_spark.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_muse_spark.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 the HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections.abc import Callable
from dataclasses import dataclass
from functools import cached_property

import torch
import torch.nn.functional as F
from torch import nn

from ... import initialization as init
from ...activations import ACT2FN
from ...cache_utils import Cache, DynamicCache
from ...generation import GenerationMixin
from ...integrations import use_experts_implementation, use_kernel_forward_from_hub, use_kernelized_func
from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
from ...modeling_layers import GradientCheckpointingLayer
from ...modeling_outputs import (
    BaseModelOutput,
    BaseModelOutputWithPast,
    BaseModelOutputWithPooling,
    MoeModelOutputWithPast,
)
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep
from ...processing_utils import Unpack
from ...utils import ModelOutput, TransformersKwargs, auto_docstring, is_torchdynamo_compiling, torch_compilable_check
from ...utils.generic import can_return_tuple, get_max_seqlen, is_flash_attention_requested, merge_with_config_defaults
from ...utils.output_capturing import OutputRecorder, capture_outputs
from ...vision_utils import (
    get_vision_cu_seqlens,
    get_vision_interpolation_indices_and_weights,
    get_vision_position_ids,
    get_vision_window_index,
)
from ..auto import AutoModel
from .configuration_muse_spark import MuseSparkAudioConfig, MuseSparkConfig, MuseSparkTextConfig, MuseSparkVisionConfig


@auto_docstring(
    custom_intro="""
    Base class for MuseSpark outputs, with hidden states and attentions.
    """
)
@dataclass
class MuseSparkModelOutputWithPast(BaseModelOutputWithPast):
    r"""
    image_hidden_states (`torch.Tensor`, *optional*):
        A `torch.Tensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
        image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
    """

    image_hidden_states: torch.Tensor | None = None
    router_logits: tuple[torch.Tensor] | None = None


@auto_docstring(
    custom_intro="""
    Base class for MuseSpark causal language model (or autoregressive) outputs.
    """
)
@dataclass
class MuseSparkCausalLMOutputWithPast(ModelOutput):
    r"""
    loss (`torch.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Language modeling loss (for next-token prediction).
    logits (`torch.Tensor` of shape `(batch_size, sequence_length, config.text_config.vocab_size)`):
        Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
    past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
        It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

        Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
        `past_key_values` input) to speed up sequential decoding.
    image_hidden_states (`torch.Tensor`, *optional*):
        A `torch.Tensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
        image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
    """

    loss: torch.Tensor | None = None
    logits: torch.Tensor | None = None
    past_key_values: Cache | None = None
    hidden_states: tuple[torch.Tensor] | None = None
    attentions: tuple[torch.Tensor] | None = None
    image_hidden_states: torch.Tensor | None = None
    router_logits: tuple[torch.Tensor] | None = None


class MuseSparkRMSNorm(nn.Module):
    def __init__(self, dim: int | None = None, eps: float = 1e-6, with_scale: bool = True):
        super().__init__()
        self.eps = eps
        self.with_scale = with_scale

        if self.with_scale:
            self.weight = nn.Parameter(torch.ones(dim), requires_grad=True)

    def _norm(self, hidden_states: torch.Tensor):
        mean_squared = hidden_states.pow(2).mean(-1, keepdim=True) + self.eps
        # Use torch.pow() (over torch.sqrt() or torch.rsqrt()) to address compiler differences between Torch and JAX
        return hidden_states * torch.pow(mean_squared, -0.5)

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        normed_output = self._norm(hidden_states.float())
        if self.with_scale:
            normed_output = normed_output * self.weight.float()
        return normed_output.type_as(hidden_states)


class MuseSparkTextCenteredRMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.zeros(dim))

    def _norm(self, x):
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

    def forward(self, x):
        output = self._norm(x.float())
        # (x * w).to(bfloat16) instead of x.to(bfloat16) * w
        # See https://github.com/huggingface/transformers/pull/29402
        output = output * (1.0 + self.weight).float()
        return output.type_as(x)

    def extra_repr(self):
        return f"{tuple(self.weight.shape)}, eps={self.eps}"


class MuseSparkTextInputScaledRMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.zeros(dim))

    def _norm(self, x):
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

    def forward(self, x):
        # Different order from MuseSparkTextCenteredRMSNorm: first scale, then normalize.
        output = x.float() * (1.0 + self.weight).float()
        output = self._norm(output.type_as(x).float())  # round with fp32->bf16->f32 before norm
        return output.type_as(x)

    def extra_repr(self):
        return f"{tuple(self.weight.shape)}, eps={self.eps}"


class MuseSparkTextMLP(nn.Module):
    def __init__(self, config: MuseSparkTextConfig):
        super().__init__()
        self.config = config
        self.hidden_size = config.hidden_size
        self.intermediate_size = config.intermediate_size
        self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
        self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
        self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
        self.act_fn = ACT2FN[config.hidden_act]

    def forward(self, x):
        down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
        return down_proj


class MuseSparkTopkRouter(nn.Module):
    def __init__(self, config: MuseSparkTextConfig):
        super().__init__()
        self.top_k = config.num_experts_per_tok
        self.num_experts = config.num_local_experts
        self.hidden_dim = config.hidden_size
        self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim))
        self.output_multiplier = config.output_multiplier
        self.scoring_function = ACT2FN["sigmoid"]
        self.e_score_correction_bias = nn.Buffer(torch.zeros(self.num_experts))
        self.norm_topk_prob_eps = 1e-15
        self.routed_scaling_factor = config.routed_scaling_factor

    def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        hidden_states = hidden_states.view(-1, self.hidden_dim)
        # Different from MiniMaxM2: convert to float32 before linear projection and scale by output multiplier.
        router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
        router_logits = router_logits * self.output_multiplier
        routing_weights = self.scoring_function(router_logits)
        scores_for_choice = routing_weights + self.e_score_correction_bias
        topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
        top_k_weights = routing_weights.gather(1, topk_indices)
        # Different from MiniMaxM2: add topk prob eps and scale by routed scaling factor.
        top_k_weights = top_k_weights / (top_k_weights.sum(dim=-1, keepdim=True) + self.norm_topk_prob_eps)
        top_k_weights = top_k_weights * self.routed_scaling_factor
        return router_logits, top_k_weights, topk_indices


@use_experts_implementation(has_post_expert_norm=True)
class MuseSparkExperts(nn.Module):
    """Collection of expert weights stored as 3D tensors."""

    def __init__(self, config: MuseSparkTextConfig):
        super().__init__()
        self.num_experts = config.num_local_experts
        self.hidden_dim = config.moe_hidden_size
        self.intermediate_dim = config.moe_intermediate_size
        self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
        self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
        self.act_fn = ACT2FN[config.hidden_act]
        self.post_expert_norm = MuseSparkTextInputScaledRMSNorm(self.hidden_dim, eps=config.post_norm_eps)

    def forward(
        self,
        hidden_states: torch.Tensor,
        top_k_index: torch.Tensor,
        top_k_weights: torch.Tensor,
    ) -> torch.Tensor:
        final_hidden_states = torch.zeros_like(hidden_states)
        with torch.no_grad():
            expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts + 1)
            expert_mask = expert_mask.permute(2, 1, 0)
            expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()

        for expert_idx in expert_hit:
            expert_idx = expert_idx[0]
            if expert_idx == self.num_experts:
                continue
            top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
            current_state = hidden_states[token_idx]
            gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
            current_hidden_states = self.act_fn(gate) * up
            current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
            # Different from DeepseekV3 which has no post expert norm
            current_hidden_states = self.post_expert_norm(current_hidden_states)
            current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
            final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))

        return final_hidden_states


class MuseSparkMoE(nn.Module):
    def __init__(self, config: MuseSparkTextConfig):
        super().__init__()
        self.config = config
        self.gate = MuseSparkTopkRouter(config)
        self.pre_expert_proj = nn.Linear(config.hidden_size, config.moe_hidden_size, bias=False)
        self.pre_expert_norm = MuseSparkTextCenteredRMSNorm(config.moe_hidden_size, eps=config.rms_norm_eps)
        self.experts = MuseSparkExperts(config)
        self.post_expert_proj = nn.Linear(config.moe_hidden_size, config.hidden_size, bias=False)

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        orig_shape = hidden_states.shape
        _, topk_weights, topk_indices = self.gate(hidden_states)
        hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
        hidden_states = self.pre_expert_proj(hidden_states)
        hidden_states = self.pre_expert_norm(hidden_states)
        hidden_states = self.experts(hidden_states, topk_indices, topk_weights)
        hidden_states = self.post_expert_proj(hidden_states).view(*orig_shape)
        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 MuseSparkTextAttention(nn.Module):
    """
    Multi-headed attention module with optional sliding window and gating.

    This attention mechanism supports both full attention and sliding window attention,
    and includes Q/K normalization and gating of the output. It inherits from [`LlamaAttention`] to minimize the amount
    of custom logic we need to maintain.
    """

    def __init__(self, config: MuseSparkTextConfig, 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
        )
        # Parent LlamaAttention already sets: layer_idx, num_heads, num_key_value_heads, num_key_value_groups, head_dim
        # We only add MuseSparkText-specific attributes
        self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
        self.sliding_window = config.sliding_window if self.is_local_attention else None
        self.gate_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
        self.qk_norm = MuseSparkRMSNorm(eps=config.rms_norm_eps, with_scale=False)
        self.qk_scale_factor = config.qk_scale_factor
        self.o_norm = MuseSparkRMSNorm(eps=config.rms_norm_eps, with_scale=False)

    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 | None]:
        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)

        query_states = self.qk_norm(query_states) * self.qk_scale_factor
        key_states = self.qk_norm(key_states)

        # NoPE layers receive `position_embeddings=None` from the model.
        if position_embeddings is not None:
            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=self.attention_dropout if self.training else 0.0,
            scaling=self.scaling,
            sliding_window=self.sliding_window,
            **kwargs,
        )

        attn_output = self.o_norm(attn_output).reshape(*input_shape, -1).contiguous()
        attn_output = attn_output * torch.sigmoid(self.gate_proj(hidden_states))
        attn_output = self.o_proj(attn_output)
        return attn_output, attn_weights


class MuseSparkResidualGate(nn.Module):
    def __init__(self, config: MuseSparkTextConfig, residual_gate_eps: float = 1e-3):
        super().__init__()
        self.gate = nn.Parameter(torch.empty(config.hidden_size))
        self.temperature = config.residual_gate_temperature
        self.eps = residual_gate_eps

    def forward(self, residual: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
        w = self.gate / self.temperature
        beta = torch.sigmoid(w)
        alpha = torch.sqrt(torch.clamp(torch.sigmoid(-w) * (1.0 + beta), min=self.eps))
        return (alpha * residual + beta * hidden_states).to(residual.dtype)


class MuseSparkTextDecoderLayer(GradientCheckpointingLayer):
    def __init__(self, config: MuseSparkTextConfig, layer_idx: int):
        super().__init__()
        self.hidden_size = config.hidden_size
        self.config = config
        self.self_attn = MuseSparkTextAttention(config=config, layer_idx=layer_idx)
        self.mlp = MuseSparkMoE(config) if config.mlp_layer_types[layer_idx] == "sparse" else MuseSparkTextMLP(config)
        self.input_layernorm = MuseSparkTextCenteredRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.post_attention_layernorm = MuseSparkRMSNorm(
            config.hidden_size, eps=config.post_norm_eps, with_scale=False
        )
        self.pre_feedforward_layernorm = MuseSparkTextCenteredRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.post_feedforward_layernorm = MuseSparkTextInputScaledRMSNorm(config.hidden_size, eps=config.post_norm_eps)
        self.post_attention_residual_gate = MuseSparkResidualGate(config)
        self.post_feedforward_residual_gate = MuseSparkResidualGate(config)

    def forward(
        self,
        hidden_states: torch.Tensor,
        position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
        attention_mask: torch.Tensor | None = None,
        position_ids: torch.LongTensor | None = None,
        past_key_values: Cache | None = None,
        **kwargs,
    ) -> torch.Tensor:
        residual = hidden_states
        hidden_states = self.input_layernorm(hidden_states)
        hidden_states, _ = self.self_attn(
            hidden_states=hidden_states,
            position_embeddings=position_embeddings,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            **kwargs,
        )
        hidden_states = self.post_attention_layernorm(hidden_states)
        hidden_states = self.post_attention_residual_gate(residual, hidden_states)

        residual = hidden_states
        hidden_states = self.pre_feedforward_layernorm(hidden_states)
        hidden_states = self.mlp(hidden_states)
        hidden_states = self.post_feedforward_layernorm(hidden_states)
        hidden_states = self.post_feedforward_residual_gate(residual, hidden_states)

        return hidden_states


@auto_docstring
class MuseSparkPreTrainedModel(PreTrainedModel):
    config: MuseSparkConfig
    base_model_prefix = "model"
    supports_gradient_checkpointing = True
    _no_split_modules = ["MuseSparkTextDecoderLayer", "MuseSparkVisionEncoderLayer"]
    _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 = None  # set on children directly as they are different for text and vision
    _keep_in_fp32_modules_strict = [
        "post_attention_residual_gate",
        "post_feedforward_residual_gate",
        "mlp.gate.weight",
        "e_score_correction_bias",
    ]

    def _init_weights(self, module):
        super()._init_weights(module)
        if isinstance(module, MuseSparkTopkRouter):
            init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
            init.zeros_(module.e_score_correction_bias)
        elif isinstance(module, MuseSparkExperts):
            init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range)
            init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range)
        elif isinstance(module, (MuseSparkTextCenteredRMSNorm, MuseSparkTextInputScaledRMSNorm)):
            init.zeros_(module.weight)
        elif isinstance(module, MuseSparkResidualGate):
            init.normal_(module.gate, mean=0.0, std=self.config.initializer_range)


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


# Not a pass-through wrapper: this *is* the embedding (nn.Embedding subclass) and forward does the
# lookup via super().forward() before the norm, so there is no inner module to hoist out.
# trf-ignore: TRF026
class MuseSparkTextNormedEmbedding(nn.Embedding):
    def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, norm_eps: float = 1e-6):
        super().__init__(num_embeddings, embedding_dim, padding_idx)
        # Weight-less norm applied on top of the embeddings - cannot be merged to the embedding matrix, as Dflash implem needs
        # to embed without the norm
        self.embed_norm = MuseSparkRMSNorm(eps=norm_eps, with_scale=False)

    def forward(self, input_ids: torch.Tensor):
        return self.embed_norm(super().forward(input_ids))


@auto_docstring
class MuseSparkTextModel(MuseSparkPreTrainedModel):
    config: MuseSparkTextConfig
    _can_record_outputs = {
        "hidden_states": MuseSparkTextDecoderLayer,
        "attentions": MuseSparkTextAttention,
        "router_logits": OutputRecorder(MuseSparkTopkRouter, index=0),
    }

    def __init__(self, config: MuseSparkTextConfig):
        super().__init__(config)
        self.padding_idx = config.pad_token_id
        self.vocab_size = config.vocab_size
        self.embed_tokens = MuseSparkTextNormedEmbedding(
            config.vocab_size, config.hidden_size, self.padding_idx, config.rms_norm_eps
        )
        self.layers = nn.ModuleList(
            [MuseSparkTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
        )
        self.norm = MuseSparkRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.rotary_emb = MuseSparkTextRotaryEmbedding(config)
        self.gradient_checkpointing = 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,
        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],
    ) -> MoeModelOutputWithPast:
        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)

        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)

        if not isinstance(causal_mask_mapping := attention_mask, dict):
            mask_kwargs = {
                "config": self.config,
                "inputs_embeds": inputs_embeds,
                "attention_mask": attention_mask,
                "past_key_values": past_key_values,
                "position_ids": position_ids,
            }
            causal_mask_mapping = {
                "full_attention": create_causal_mask(**mask_kwargs),
                "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
            }

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

        for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
            hidden_states = decoder_layer(
                hidden_states,
                attention_mask=causal_mask_mapping[self.config.layer_types[i]],
                # NoPE layers (layer_rope_theta == 0) get no position embeddings.
                position_embeddings=position_embeddings if self.config.layer_rope_theta[i] else None,
                position_ids=position_ids,
                past_key_values=past_key_values,
                **kwargs,
            )

        hidden_states = self.norm(hidden_states)

        return MoeModelOutputWithPast(
            last_hidden_state=hidden_states,
            past_key_values=past_key_values,
        )


class MuseSparkVisionPatchEmbedder(nn.Module):
    def __init__(self, config: MuseSparkVisionConfig):
        super().__init__()
        self.config = config
        self.hidden_size = config.hidden_size
        self.patch_embedding = nn.Linear(
            config.patch_temporal * 3 * config.patch_size**2, self.hidden_size, bias=False
        )
        self.position_embedding_table = nn.Embedding(config.pos_emb_height * config.pos_emb_width, self.hidden_size)
        # FIXME: only if square images - vision utils don't yet support non-square
        # For now assume pos_emb_height == pos_emb_width always, i.e. as in shared ckpt
        self.num_grid_per_side = config.pos_emb_height
        # muse_spark resamples its position grid with `F.grid_sample(align_corners=False, padding_mode="zeros")`
        self.interpolation_mode = "bilinear"
        self.interpolation_align_corners = False
        self.interpolation_padding = "zeros"

    def forward(
        self,
        pixel_values: torch.Tensor,
        grid_thw: torch.LongTensor | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> torch.Tensor:
        """
        Args:
            pixel_values (`torch.Tensor` of shape `(batch_size, sequence_length, image_channels, patch_size, patch_size)`):
                The tensors corresponding to the input images.
            grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
                The temporal, height and width of feature shape of each image in LLM.
        """
        embeddings = self.patch_embedding(pixel_values.to(dtype=self.patch_embedding.weight.dtype))

        # Patch (h, w) reads the position table at (w, h): ref code passes
        # `meshgrid(pos_h, pos_w, indexing="xy")` to `grid_sample` which takes first coord as width.
        interp_indices, interp_weights = get_vision_interpolation_indices_and_weights(
            grid_thw[:, [0, 2, 1]],
            num_grid_per_side=self.num_grid_per_side,
            mode=self.interpolation_mode,
            align_corners=self.interpolation_align_corners,
            spatial_merge_size=1,
            padding=self.interpolation_padding,
            kwargs=kwargs,
        )
        pos_embeds = (self.position_embedding_table(interp_indices) * interp_weights[:, :, None]).sum(1)
        return embeddings + pos_embeds.to(embeddings.dtype)


def apply_rotary_pos_emb_vision(
    q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    orig_q_dtype = q.dtype
    orig_k_dtype = k.dtype
    q, k = q.float(), k.float()
    cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
    q_embed = (q * cos) + (rotate_half(q) * sin)
    k_embed = (k * cos) + (rotate_half(k) * sin)
    q_embed = q_embed.to(orig_q_dtype)
    k_embed = k_embed.to(orig_k_dtype)
    return q_embed, k_embed


class MuseSparkVisionAttention(nn.Module):
    def __init__(self, config: MuseSparkVisionConfig) -> None:
        super().__init__()
        self.dim = config.hidden_size
        self.num_heads = config.num_attention_heads
        self.head_dim = self.dim // self.num_heads
        self.num_key_value_groups = 1  # needed for eager attention
        self.proj = nn.Linear(self.dim, self.dim)
        self.scaling = self.head_dim**-0.5
        self.config = config
        self.attention_dropout = 0.0
        self.is_causal = False
        self.q_proj = nn.Linear(self.dim, self.dim, bias=True)
        self.k_proj = nn.Linear(self.dim, self.dim, bias=True)
        self.v_proj = nn.Linear(self.dim, self.dim, bias=True)

    def forward(
        self,
        hidden_states: torch.Tensor,
        cu_seqlens: torch.Tensor,
        position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
        max_seqlen: int | None = None,
        **kwargs,
    ) -> torch.Tensor:
        seq_length = hidden_states.shape[0]

        query_states = self.q_proj(hidden_states).reshape(1, seq_length, -1, self.head_dim)
        key_states = self.k_proj(hidden_states).reshape(1, seq_length, -1, self.head_dim)
        value_states = self.v_proj(hidden_states).reshape(1, seq_length, -1, self.head_dim)

        cos, sin = position_embeddings
        query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)

        query_states = query_states.transpose(2, 1)
        key_states = key_states.transpose(2, 1)
        value_states = value_states.transpose(2, 1)

        attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
            self.config._attn_implementation, eager_attention_forward
        )

        if is_flash_attention_requested(self.config):
            # Flash Attention: Use cu_seqlens for variable length attention
            max_seqlen = get_max_seqlen(cu_seqlens, self.config, kwargs={"max_seqlen": max_seqlen})
            attn_output, _ = attention_interface(
                self,
                query_states,
                key_states,
                value_states,
                attention_mask=None,
                scaling=self.scaling,
                dropout=0.0 if not self.training else self.attention_dropout,
                cu_seq_lens_q=cu_seqlens,
                cu_seq_lens_k=cu_seqlens,
                max_length_q=max_seqlen,
                max_length_k=max_seqlen,
                is_causal=False,
                **kwargs,
            )
        else:
            # Other implementations: Process each chunk separately
            lengths = cu_seqlens[1:] - cu_seqlens[:-1]
            splits = [
                torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states)
            ]

            attn_outputs = [
                attention_interface(
                    self,
                    q,
                    k,
                    v,
                    attention_mask=None,
                    scaling=self.scaling,
                    dropout=0.0 if not self.training else self.attention_dropout,
                    is_causal=False,
                    **kwargs,
                )[0]
                for q, k, v in zip(*splits)
            ]
            attn_output = torch.cat(attn_outputs, dim=1)

        attn_output = attn_output.reshape(seq_length, -1).contiguous()
        attn_output = self.proj(attn_output)
        return attn_output


class MuseSparkVisionMLP(nn.Module):
    def __init__(self, dim: int, hidden_dim: int, hidden_act: str) -> None:
        super().__init__()
        self.fc1 = nn.Linear(dim, hidden_dim)
        self.act = ACT2FN[hidden_act]
        self.fc2 = nn.Linear(hidden_dim, dim)

    def forward(self, x) -> torch.Tensor:
        return self.fc2(self.act(self.fc1(x)))


class MuseSparkVisionEncoderLayer(GradientCheckpointingLayer):
    def __init__(self, config) -> None:
        super().__init__()
        self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-5)
        self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-5)
        self.attn = MuseSparkVisionAttention(config=config)
        self.mlp = MuseSparkVisionMLP(config.hidden_size, config.intermediate_size, config.hidden_act)

    def forward(
        self,
        hidden_states: torch.Tensor,
        cu_seqlens: torch.Tensor,
        position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
        **kwargs,
    ) -> torch.Tensor:
        hidden_states = hidden_states + self.attn(
            self.norm1(hidden_states),
            cu_seqlens=cu_seqlens,
            position_embeddings=position_embeddings,
            **kwargs,
        )
        hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
        return hidden_states


class MuseSparkVisionRotaryEmbedding(nn.Module):
    """
    Simple axial 2D rope with same freqs used for H and W grids. The freqs are
    pre-computed using `head-dim//4` which is later used to concat H and W positions.
    The final angles rotate over the whole head dim, no partial rotation involved.
    """

    def __init__(self, config: MuseSparkVisionConfig):
        super().__init__()
        self.config = config

        self.rope_type = self.config.rope_parameters["rope_type"]
        rope_init_fn: Callable = self.compute_axial_rope_parameters
        if self.rope_type != "axial":
            raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {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_axial_rope_parameters(
        config: MuseSparkVisionConfig, device=None, **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
        spatial_dim = dim // 2

        attention_factor = 1.0  # Unused in this type of RoPE
        inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim))
        return inv_freq.to(device), attention_factor

    @torch.no_grad()
    def forward(self, x, position_ids):
        # position_ids: (2, N) — row 0 = h coords, row 1 = w coords
        freqs = position_ids[..., None].float() * self.inv_freq.to(device=x.device, dtype=torch.float)
        cos = freqs.cos() * self.attention_scaling
        sin = freqs.sin() * self.attention_scaling

        cos = self.recomposition_frequencies(cos)
        sin = self.recomposition_frequencies(sin)
        return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)

    def recomposition_frequencies(self, freq):
        """
        Recompose the frequencies into the final spatial layout used per each grid.
        """
        freq_h, freq_w = freq[:, 0], freq[:, 1]
        freq_hw = torch.cat([freq_h, freq_w], dim=-1)
        return torch.cat([freq_hw, freq_hw], dim=-1)


def get_vision_pixel_shuffle_index(
    grid_thw: torch.Tensor, merge_size: int, kwargs: dict | None = None
) -> torch.Tensor:
    """Gather index that groups each `merge_size x merge_size` spatial block (per frame/image) into
    `merge_size**2` consecutive rows for `pixel_shuffle` to fold into the channel dim. Popped from
    `kwargs` when precomputed, so the encoder avoids a per-image `grid_thw.tolist()` loop under export.
    """
    if kwargs is not None and (index := kwargs.pop("pixel_shuffle_index", None)) is not None:
        return index
    indices = []
    offset = 0
    for frames, height, width in grid_thw.tolist():
        frames, height, width = int(frames), int(height), int(width)
        permutation = torch.arange(height * width, device=grid_thw.device)
        permutation = permutation.view(height // merge_size, merge_size, width // merge_size, merge_size)
        permutation = permutation.permute(0, 2, 1, 3).reshape(-1)
        if frames > 1:
            # offset the permutation per frame so it indexes into the flattened `(frames*height*width)` sequence
            frame_offsets = (torch.arange(frames, device=grid_thw.device) * height * width).view(frames, 1)
            permutation = (permutation.unsqueeze(0) + frame_offsets).reshape(-1)
        indices.append(permutation + offset)
        offset += frames * height * width
    return torch.cat(indices, dim=0)


@auto_docstring
class MuseSparkVisionModel(MuseSparkPreTrainedModel):
    config: MuseSparkVisionConfig
    main_input_name = "pixel_values"
    input_modalities = ("image", "video")
    _can_record_outputs = {
        "hidden_states": MuseSparkVisionEncoderLayer,
        "attentions": MuseSparkVisionAttention,
    }

    def __init__(self, config: MuseSparkVisionConfig):
        super().__init__(config)
        self.patch_embedder = MuseSparkVisionPatchEmbedder(config)
        self.rotary_emb = MuseSparkVisionRotaryEmbedding(config)
        self.ln_pre = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.layers = nn.ModuleList([MuseSparkVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
        self.ln_post = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        # read by both the forward and the export precompute. `spatial_merge_size` is intentionally 1 (not `config.merge_size`):
        # window/position/interpolation run un-merged, the merge is deferred to `pixel_shuffle`.
        self.spatial_merge_size = 1
        self.patch_size = config.patch_size
        self.window_size = config.pos_emb_height * config.patch_size
        self.merge_size = config.merge_size
        self.post_init()

    def pixel_shuffle(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) -> torch.Tensor:
        factor = self.merge_size
        dim = hidden_states.shape[-1]
        shuffle_index = get_vision_pixel_shuffle_index(grid_thw, factor, kwargs=kwargs)
        hidden_states = hidden_states[shuffle_index.to(hidden_states.device)]
        return hidden_states.view(-1, factor * factor, dim).permute(0, 2, 1).reshape(-1, dim * factor * factor)

    @merge_with_config_defaults
    @capture_outputs
    @auto_docstring
    def forward(
        self,
        pixel_values: torch.Tensor,
        grid_thw: torch.LongTensor,
        **kwargs: Unpack[TransformersKwargs],
    ) -> BaseModelOutputWithPooling:
        r"""
        grid_thw (`torch.LongTensor` of shape `(num_images_or_videos, 3)`):
            The temporal, height and width patch-grid dimensions for each packed image or video.
        """
        cu_seqlens = get_vision_cu_seqlens(grid_thw, kwargs=kwargs)
        # assumes pos_emb_height==pos_emb_width, adapt to non-square if needed
        window_index, cu_window_seqlens = get_vision_window_index(
            grid_thw,
            spatial_merge_size=self.spatial_merge_size,
            window_size=self.window_size,
            patch_size=self.patch_size,
            kwargs=kwargs,
        )

        inputs_embeds = self.patch_embedder(pixel_values, grid_thw, **kwargs)
        hidden_states = self.ln_pre(inputs_embeds)
        hidden_states = hidden_states[window_index, :]

        # Add `1` because ref implementation's position offset is `1`!
        position_ids = get_vision_position_ids(grid_thw, spatial_merge_size=self.spatial_merge_size, kwargs=kwargs)
        position_ids = position_ids.flip(-1) + 1
        position_ids = position_ids[window_index, :]
        position_embeddings = self.rotary_emb(hidden_states, position_ids)

        cu_seqlens_mapping = {
            "full_attention": cu_seqlens,
            "window_attention": cu_window_seqlens,
        }
        for i, block in enumerate(self.layers):
            hidden_states = block(
                hidden_states,
                position_embeddings=position_embeddings,
                cu_seqlens=cu_seqlens_mapping[self.config.layer_types[i]],
            )

        reverse_indices = torch.argsort(window_index)
        hidden_states = hidden_states[reverse_indices, :]

        hidden_states = self.ln_post(hidden_states)
        hidden_states = self.pixel_shuffle(hidden_states, grid_thw, **kwargs)
        return BaseModelOutputWithPooling(last_hidden_state=hidden_states)


class MuseSparkAudioConv1dCacheLayer:
    def __init__(self):
        self.cache: torch.Tensor | None = None
        self.is_initialized: bool = False

    def lazy_initialization(self, hidden_states, conv_module):
        self.left_pad = conv_module.left_pad
        self.in_channels = conv_module.in_channels
        self.cache = torch.zeros(
            hidden_states.shape[0],
            self.in_channels,
            self.left_pad,
            device=hidden_states.device,
            dtype=hidden_states.dtype,
        )

        if not is_torchdynamo_compiling():
            torch._dynamo.mark_static_address(self.cache)

        self.is_initialized = True

    def update(self, hidden_states, conv_module=None):
        if not self.is_initialized and conv_module is not None:
            self.lazy_initialization(hidden_states, conv_module)
        elif not self.is_initialized:
            raise ValueError(
                "MuseSparkAudioConv1dCacheLayer is not initialized. Make sure to provide conv_module to the update method."
            )

        # get the padding states
        if self.left_pad > 0:
            shortfall = max(0, self.left_pad - hidden_states.shape[-1])
            if shortfall > 0:
                padding_states = torch.cat([self.cache[:, :, -shortfall:], hidden_states], dim=-1)
            else:
                padding_states = hidden_states[:, :, -self.left_pad :]
        else:
            padding_states = torch.empty(
                hidden_states.shape[0], self.in_channels, 0, dtype=hidden_states.dtype, device=hidden_states.device
            )

        current_cache = self.cache.clone()
        self.cache.copy_(padding_states)

        return current_cache


class MuseSparkAudioConv1dPaddingCache:
    def __init__(self):
        self.layers = {}

    def update(self, hidden_states, cache_key, conv_module):
        if cache_key not in self.layers:
            self.layers[cache_key] = MuseSparkAudioConv1dCacheLayer()

        padding_states = self.layers[cache_key].update(hidden_states, conv_module)
        padded_hidden_states = torch.cat([padding_states, hidden_states], dim=-1)
        return padded_hidden_states


class MuseSparkAudioCausalConv1d(nn.Conv1d):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        kernel_size: int,
        cache_key: str,
        stride: int = 1,
        dilation: int = 1,
        groups: int = 1,
        bias: bool = True,
    ):
        super().__init__(
            in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, groups=groups, bias=bias
        )
        self.cache_key = cache_key

    @cached_property
    def left_pad(self):
        effective_kernel_size = (self.kernel_size[0] - 1) * self.dilation[0] + 1
        return effective_kernel_size - self.stride[0]

    def forward(
        self,
        x: torch.Tensor,
        padding_cache: MuseSparkAudioConv1dPaddingCache | None = None,
    ) -> torch.Tensor:
        if padding_cache is not None:
            x = padding_cache.update(x, self.cache_key, self)
        else:
            x = nn.functional.pad(x, (self.left_pad, 0))

        return super().forward(x)


class MuseSparkAudioPatchEmbedding(nn.Module):
    def __init__(self, config: MuseSparkAudioConfig, layer_idx: int):
        super().__init__()
        # layer 0 consumes the mono waveform itself, so a single input channel
        in_channels = 1 if layer_idx == 0 else config.hidden_sizes[layer_idx - 1]
        out_channels = config.hidden_sizes[layer_idx]
        self.patch_size = config.patch_sizes[layer_idx]
        self.proj = nn.Linear(in_channels * self.patch_size, out_channels, bias=True)
        self.norm = MuseSparkRMSNorm(out_channels, eps=config.rms_norm_eps)

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        batch_size, seq_len, channels = hidden_states.shape
        torch_compilable_check(
            seq_len % self.patch_size == 0, f"audio length {seq_len} is not divisible by patch size {self.patch_size}"
        )
        hidden_states = hidden_states.reshape(batch_size, seq_len // self.patch_size, self.patch_size * channels)
        return self.norm(self.proj(hidden_states))


class MuseSparkAudioMLP(nn.Module):
    def __init__(self, config: MuseSparkAudioConfig, layer_idx: int):
        super().__init__()
        self.hidden_size = config.hidden_sizes[layer_idx]
        self.intermediate_size = int(self.hidden_size * config.mlp_ratio)
        self.fc1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=True)
        self.fc2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=True)
        self.activation_fn = ACT2FN[config.hidden_act]

    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 MuseSparkAudioConvBlock(nn.Module):
    def __init__(self, config: MuseSparkAudioConfig, layer_idx: int, block_idx: int):
        super().__init__()
        hidden_size = config.hidden_sizes[layer_idx]
        self.conv = MuseSparkAudioCausalConv1d(
            hidden_size,
            hidden_size,
            kernel_size=config.conv_kernel_size,
            cache_key=f"layers.{layer_idx}.conv_blocks.{block_idx}",
            groups=hidden_size,
            bias=True,
        )
        self.norm = MuseSparkRMSNorm(hidden_size, eps=config.rms_norm_eps)
        self.mlp = MuseSparkAudioMLP(config, layer_idx)

    def forward(
        self,
        hidden_states: torch.Tensor,
        padding_cache: MuseSparkAudioConv1dPaddingCache | None = None,
    ) -> torch.Tensor:
        residual = hidden_states
        hidden_states = self.conv(hidden_states.transpose(1, 2), padding_cache).transpose(1, 2)
        hidden_states = self.mlp(self.norm(hidden_states))
        return hidden_states + residual


class MuseSparkAudioLayer(nn.Module):
    def __init__(self, config: MuseSparkAudioConfig, layer_idx: int):
        super().__init__()
        self.patch_embedder = MuseSparkAudioPatchEmbedding(config, layer_idx)
        self.conv_blocks = nn.ModuleList(
            [MuseSparkAudioConvBlock(config, layer_idx, block_idx) for block_idx in range(config.depths[layer_idx])]
        )

    def forward(
        self,
        hidden_states: torch.Tensor,
        padding_cache: MuseSparkAudioConv1dPaddingCache | None = None,
    ) -> torch.Tensor:
        hidden_states = self.patch_embedder(hidden_states)
        for conv_block in self.conv_blocks:
            hidden_states = conv_block(hidden_states, padding_cache)
        return hidden_states


@auto_docstring(
    custom_intro="""
    The Muse Spark Open waveform audio encoder: a fully causal convolutional pyramid that maps raw mono
    24 kHz audio to one embedding per 1920 samples (80 ms, i.e. 12.5 Hz), already in the text model's
    hidden size. It uses no attention and no spectrogram front-end.
    """
)
class MuseSparkAudioModel(MuseSparkPreTrainedModel):
    config: MuseSparkAudioConfig
    main_input_name = "input_values"
    input_modalities = "audio"
    _no_split_modules = ["MuseSparkAudioLayer"]
    _can_record_outputs = {"hidden_states": MuseSparkAudioLayer}

    def __init__(self, config: MuseSparkAudioConfig):
        super().__init__(config)
        self.layers = nn.ModuleList([MuseSparkAudioLayer(config, idx) for idx in range(config.num_hidden_layers)])
        self.norm = MuseSparkRMSNorm(config.hidden_sizes[-1], eps=config.rms_norm_eps)
        self.proj = nn.Linear(config.hidden_sizes[-1], config.out_hidden_size, bias=True)
        self.post_proj_norm = MuseSparkRMSNorm(config.out_hidden_size, eps=config.rms_norm_eps)
        self.post_init()

    @merge_with_config_defaults
    @capture_outputs
    @auto_docstring
    def forward(
        self,
        input_values: torch.Tensor,
        padding_cache: MuseSparkAudioConv1dPaddingCache | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> BaseModelOutput:
        r"""
        padding_cache (`MuseSparkAudioConv1dPaddingCache`, *optional*):
            Cache for padding in convolutional layers to maintain state across streaming chunks.
        """
        torch_compilable_check(
            input_values.shape[1] % self.config.samples_per_token == 0,
            (
                f"`input_values` length {input_values.shape[1]} is not a multiple of "
                f"{self.config.samples_per_token}. Prepare the audio with `MuseSparkFeatureExtractor`, which "
                f"pads up to a multiple of it."
            ),
        )
        hidden_states = input_values.unsqueeze(-1)
        for layer in self.layers:
            hidden_states = layer(hidden_states, padding_cache)

        hidden_states = self.post_proj_norm(self.proj(self.norm(hidden_states)))
        return BaseModelOutput(last_hidden_state=hidden_states)


class MuseSparkVisionAdapter(nn.Module):
    def __init__(self, config: MuseSparkConfig) -> None:
        super().__init__()
        self.fc1 = nn.Linear(config.out_hidden_size, config.projector_hidden_size, bias=False)
        self.act = ACT2FN[config.projector_hidden_act]
        self.fc2 = nn.Linear(config.projector_hidden_size, config.projector_hidden_size, bias=False)

    def forward(self, x) -> torch.Tensor:
        return self.act(self.fc2(self.act(self.fc1(x))))


@auto_docstring
class MuseSparkModel(MuseSparkPreTrainedModel):
    input_modalities = ("image", "video", "text")

    def __init__(self, config: MuseSparkConfig):
        super().__init__(config)
        self.vision_tower = AutoModel.from_config(config.vision_config)
        self.language_model = AutoModel.from_config(config.text_config)
        self.vision_adapter = MuseSparkVisionAdapter(config)
        self.vision_projection = nn.Linear(config.projector_hidden_size, config.text_config.hidden_size, bias=False)
        self.perception_emb_norm = MuseSparkRMSNorm(eps=config.text_config.rms_norm_eps, with_scale=False)
        self.audio_tower = AutoModel.from_config(config.audio_config)
        self.post_init()

    def get_input_embeddings(self):
        return self.language_model.get_input_embeddings()

    def set_input_embeddings(self, value):
        self.language_model.set_input_embeddings(value)

    @can_return_tuple
    @auto_docstring
    def get_image_features(
        self,
        pixel_values: torch.Tensor,
        image_grid_thw: torch.LongTensor,
        **kwargs: Unpack[TransformersKwargs],
    ) -> BaseModelOutputWithPooling:
        vision_outputs = self.vision_tower(
            pixel_values=pixel_values,
            grid_thw=image_grid_thw,
            **kwargs,
        )
        vision_features = self.vision_adapter(vision_outputs.last_hidden_state)
        vision_features = self.vision_projection(vision_features)
        vision_features = self.perception_emb_norm(vision_features)
        split_sizes = (image_grid_thw.prod(-1) // self.config.vision_config.merge_size**2).tolist()
        vision_outputs.pooler_output = torch.split(vision_features, split_sizes)
        return vision_outputs

    @auto_docstring
    def get_video_features(
        self,
        pixel_values_videos: torch.Tensor,
        video_grid_thw: torch.LongTensor | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> tuple | BaseModelOutputWithPooling:
        r"""
        pixel_values_videos (`torch.Tensor` of shape `(batch_size, num_channels, image_size, image_size)`):
            The tensors corresponding to the input videos.
        """
        return self.get_image_features(pixel_values_videos, video_grid_thw, **kwargs)

    def get_placeholder_mask(
        self,
        input_ids: torch.LongTensor,
        inputs_embeds: torch.Tensor,
        image_features: torch.Tensor | None = None,
        video_features: torch.Tensor | None = None,
    ):
        """
        Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
        equal to the length of multimodal features. If the lengths are different, an error is raised.
        """
        if input_ids is None:
            special_image_mask = inputs_embeds == self.get_input_embeddings()(
                torch.full((), self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
            )
            special_image_mask = special_image_mask.all(-1)
            special_video_mask = inputs_embeds == self.get_input_embeddings()(
                torch.full((), self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
            )
            special_video_mask = special_video_mask.all(-1)
        else:
            special_image_mask = input_ids == self.config.image_token_id
            special_video_mask = input_ids == self.config.video_token_id

        n_image_tokens = special_image_mask.sum()
        special_image_mask = special_image_mask.unsqueeze(-1).to(inputs_embeds.device)
        if image_features is not None:
            torch_compilable_check(
                n_image_tokens * inputs_embeds.shape[-1] == image_features.numel(),
                f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {image_features.shape[0]}",
            )

        n_video_tokens = special_video_mask.sum()
        special_video_mask = special_video_mask.unsqueeze(-1).to(inputs_embeds.device)
        if video_features is not None:
            torch_compilable_check(
                n_video_tokens * inputs_embeds.shape[-1] == video_features.numel(),
                f"Video features and video tokens do not match, tokens: {n_video_tokens}, features: {video_features.shape[0]}",
            )
        return special_image_mask, special_video_mask

    @can_return_tuple
    @auto_docstring
    def forward(
        self,
        input_ids: torch.LongTensor | None = None,
        attention_mask: torch.Tensor | None = None,
        position_ids: torch.LongTensor | None = None,
        past_key_values: Cache | None = None,
        inputs_embeds: torch.Tensor | None = None,
        use_cache: bool | None = None,
        pixel_values: torch.Tensor | None = None,
        image_grid_thw: torch.LongTensor | None = None,
        pixel_values_videos: torch.Tensor | None = None,
        video_grid_thw: torch.LongTensor | None = None,
        input_values: torch.Tensor | None = None,
        input_values_mask: torch.Tensor | None = None,
        mm_encoder_outputs: dict[str, BaseModelOutputWithPooling] | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> tuple | MuseSparkModelOutputWithPast:
        r"""
        input_values_mask (`torch.Tensor` of shape `(batch_size, num_samples)`, *optional*):
            Which entries of `input_values` are real audio rather than padding, as produced by
            [`MuseSparkFeatureExtractor`]. Required when batching clips of different lengths.

        Example:

        ```python
        >>> import os

        >>> from transformers import AutoProcessor, DistributedConfig, MuseSparkModel

        >>> distributed_config = DistributedConfig(
        ...     tp_size=int(os.environ["WORLD_SIZE"]),
        ...     ep_size=int(os.environ["WORLD_SIZE"]),
        ... )

        >>> processor = AutoProcessor.from_pretrained("meta-models/Muse-Spark-Open-816B-A42B")
        >>> model = MuseSparkModel.from_pretrained(
        ...     "meta-models/Muse-Spark-Open-816B-A42B",
        ...     dtype="auto",
        ...     distributed_config=distributed_config,
        ... )

        >>> messages = [
        ...     {
        ...         "role": "user",
        ...         "content": [
        ...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
        ...             {"type": "text", "text": "What is shown in this image?"},
        ...         ],
        ...     },
        ... ]

        >>> inputs = processor.apply_chat_template(
        ...     messages,
        ...     reasoning_effort="medium",
        ...     add_generation_prompt=True,
        ...     tokenize=True,
        ...     return_dict=True,
        ...     return_tensors="pt",
        ... ).to(model.device).to(model.dtype)

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        ```
        """
        if (pixel_values is not None or pixel_values_videos is not None) and mm_encoder_outputs is not None:
            raise ValueError(
                "You cannot specify both pixel_values/pixel_values_videos and mm_encoder_outputs at the same time"
            )

        if inputs_embeds is None:
            multimodal_mask = (
                (input_ids == self.config.image_token_id)
                | (input_ids == self.config.video_token_id)
                | (input_ids == self.config.audio_token_id)
            )
            llm_input_ids = input_ids.clone()
            llm_input_ids[multimodal_mask] = 0
            inputs_embeds = self.get_input_embeddings()(llm_input_ids)

        mm_encoder_outputs = mm_encoder_outputs if mm_encoder_outputs is not None else {}
        if mm_encoder_outputs.get("image") is None and pixel_values is not None:
            mm_encoder_outputs["image"] = self.get_image_features(
                pixel_values, image_grid_thw, return_dict=True, **kwargs
            )

        if mm_encoder_outputs.get("video") is None and pixel_values_videos is not None:
            mm_encoder_outputs["video"] = self.get_video_features(
                pixel_values_videos, video_grid_thw, return_dict=True, **kwargs
            )

        if mm_encoder_outputs.get("image") is not None:
            image_embeds = torch.cat(mm_encoder_outputs["image"].pooler_output, dim=0).to(
                inputs_embeds.device, inputs_embeds.dtype
            )
            image_mask, _ = self.get_placeholder_mask(
                input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds
            )
            inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)

        if mm_encoder_outputs.get("video") is not None:
            video_embeds = torch.cat(mm_encoder_outputs["video"].pooler_output, dim=0).to(
                inputs_embeds.device, inputs_embeds.dtype
            )
            _, video_mask = self.get_placeholder_mask(
                input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds
            )
            inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)

        if input_values is not None:
            audio_embeds = self.get_audio_features(input_values, input_values_mask).pooler_output
            audio_embeds = audio_embeds.to(device=inputs_embeds.device, dtype=inputs_embeds.dtype)
            audio_mask = self.get_audio_placeholder_mask(
                input_ids, inputs_embeds=inputs_embeds, audio_features=audio_embeds
            )
            inputs_embeds = inputs_embeds.masked_scatter(audio_mask, audio_embeds)

        outputs = self.language_model(
            input_ids=None,
            position_ids=position_ids,
            attention_mask=attention_mask,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            **kwargs,
        )
        return MuseSparkModelOutputWithPast(
            last_hidden_state=outputs.last_hidden_state,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
            router_logits=outputs.router_logits,
        )

    @can_return_tuple
    @auto_docstring
    def get_audio_features(
        self,
        input_values: torch.Tensor,
        input_values_mask: torch.Tensor | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> BaseModelOutputWithPooling:
        r"""
        input_values_mask (`torch.Tensor` of shape `(batch_size, num_samples)`, *optional*):
            Which entries of `input_values` are real audio rather than padding, as produced by
            [`MuseSparkFeatureExtractor`]. Required when batching clips of different lengths.
        """
        audio_outputs = self.audio_tower(input_values=input_values, **kwargs)
        last_hidden_state = audio_outputs.last_hidden_state
        audio_features = last_hidden_state

        if input_values_mask is not None:
            samples_per_token = self.config.audio_config.samples_per_token
            # right-padding only, which is what MuseSparkFeatureExtractor produces
            lengths = input_values_mask.sum(-1)
            num_tokens = (lengths + samples_per_token - 1) // samples_per_token
            positions = torch.arange(audio_features.shape[1], device=audio_features.device)
            token_mask = positions[None, :] < num_tokens[:, None]
            audio_features = audio_features[token_mask]
        else:
            audio_features = audio_features.reshape(-1, audio_features.shape[-1])

        audio_features = self.get_input_embeddings().embed_norm(audio_features)
        return BaseModelOutputWithPooling(
            last_hidden_state=last_hidden_state,
            pooler_output=audio_features,
            hidden_states=audio_outputs.hidden_states,
        )

    def get_audio_placeholder_mask(self, input_ids, inputs_embeds, audio_features):
        if input_ids is None:
            audio_mask = inputs_embeds == self.get_input_embeddings()(
                torch.full((), self.config.audio_token_id, dtype=torch.long, device=inputs_embeds.device)
            )
            audio_mask = audio_mask.all(-1)
        else:
            audio_mask = input_ids == self.config.audio_token_id

        n_audio_tokens = audio_mask.sum()
        audio_mask = audio_mask.unsqueeze(-1).to(inputs_embeds.device)
        torch_compilable_check(
            n_audio_tokens * inputs_embeds.shape[-1] == audio_features.numel(),
            f"Audio features and audio tokens do not match, tokens: {n_audio_tokens}, "
            f"features: {audio_features.shape[0]}",
        )
        return audio_mask


@auto_docstring
class MuseSparkForConditionalGeneration(MuseSparkPreTrainedModel, GenerationMixin):
    # Reference: fix gemma3 grad acc #37208
    accepts_loss_kwargs = False
    input_modalities = ("image", "video", "text")

    def __init__(self, config: MuseSparkConfig):
        super().__init__(config)
        self.model = MuseSparkModel(config)
        self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)

        self.post_init()

    @auto_docstring
    def get_video_features(
        self,
        pixel_values_videos: torch.Tensor,
        video_grid_thw: torch.LongTensor | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> tuple | BaseModelOutputWithPooling:
        r"""
        pixel_values_videos (`torch.Tensor` of shape `(batch_size, num_channels, image_size, image_size)`):
            The tensors corresponding to the input videos.
        """
        return self.model.get_video_features(pixel_values_videos, video_grid_thw, **kwargs)

    @auto_docstring
    def get_image_features(
        self,
        pixel_values: torch.Tensor,
        image_grid_thw: torch.LongTensor | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> tuple | BaseModelOutputWithPooling:
        r"""
        pixel_values (`torch.Tensor` of shape `(batch_size, num_channels, image_size, image_size)`):
            The tensors corresponding to the input images.
        """
        return self.model.get_image_features(pixel_values, image_grid_thw, **kwargs)

    @can_return_tuple
    @auto_docstring
    def forward(
        self,
        input_ids: torch.LongTensor | None = None,
        pixel_values: torch.Tensor | None = None,
        image_grid_thw: torch.LongTensor | None = None,
        pixel_values_videos: torch.Tensor | None = None,
        video_grid_thw: torch.LongTensor | None = None,
        input_values: torch.Tensor | None = None,
        input_values_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,
        labels: torch.LongTensor | None = None,
        use_cache: bool | None = None,
        logits_to_keep: int | torch.Tensor = 0,
        mm_encoder_outputs: dict[str, BaseModelOutputWithPooling] | None = None,
        **kwargs: Unpack[TransformersKwargs],
    ) -> tuple | MuseSparkCausalLMOutputWithPast:
        r"""
        input_values_mask (`torch.Tensor` of shape `(batch_size, num_samples)`, *optional*):
            Which entries of `input_values` are real audio rather than padding, as produced by
            [`MuseSparkFeatureExtractor`]. Required when batching clips of different lengths.

        Example:

        ```python
        >>> import os

        >>> from transformers import AutoProcessor, DistributedConfig, MuseSparkForConditionalGeneration

        >>> distributed_config = DistributedConfig(
        ...     tp_size=int(os.environ["WORLD_SIZE"]),
        ...     ep_size=int(os.environ["WORLD_SIZE"]),
        ... )

        >>> processor = AutoProcessor.from_pretrained("meta-models/Muse-Spark-Open-816B-A42B")
        >>> model = MuseSparkForConditionalGeneration.from_pretrained(
        ...     "meta-models/Muse-Spark-Open-816B-A42B",
        ...     dtype="auto",
        ...     distributed_config=distributed_config,
        ... )

        >>> messages = [
        ...     {
        ...         "role": "user",
        ...         "content": [
        ...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
        ...             {"type": "text", "text": "What is shown in this image?"},
        ...         ],
        ...     },
        ... ]

        >>> inputs = processor.apply_chat_template(
        ...     messages,
        ...     reasoning_effort="medium",
        ...     add_generation_prompt=True,
        ...     tokenize=True,
        ...     return_dict=True,
        ...     return_tensors="pt",
        ... ).to(model.device).to(model.dtype)
        >>> input_len = inputs["input_ids"].shape[-1]

        >>> outputs = model.generate(**inputs, max_new_tokens=512)

        >>> response = processor.decode(outputs[0][input_len:], skip_special_tokens=False)
        >>> print(response)
        The image shows a **Pallas's cat — also known as a manul, *Otocolobus manul*** — walking through snow.
        ...
        ```
        """
        outputs = self.model(
            input_ids=input_ids,
            pixel_values=pixel_values,
            image_grid_thw=image_grid_thw,
            pixel_values_videos=pixel_values_videos,
            video_grid_thw=video_grid_thw,
            input_values=input_values,
            input_values_mask=input_values_mask,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            mm_encoder_outputs=mm_encoder_outputs,
            **kwargs,
        )

        hidden_states = outputs.last_hidden_state
        hidden_states = slice_logits_to_keep(hidden_states, logits_to_keep)
        logits = self.lm_head(hidden_states)

        # MuseSpark pre-scales logits by `output_multiplier` before the Gemma-style tanh softcap.
        # Together with `final_logit_softcapping = T`, this gives `T * tanh(logits * mult / T)`.
        logits = logits * self.config.text_config.output_multiplier
        logits = logits / self.config.text_config.final_logit_softcapping
        logits = torch.tanh(logits)
        logits = logits * self.config.text_config.final_logit_softcapping

        loss = None
        if labels is not None:
            loss = self.loss_function(logits, labels, self.config.text_config.vocab_size, **kwargs)

        return MuseSparkCausalLMOutputWithPast(
            loss=loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
            image_hidden_states=outputs.image_hidden_states,
            router_logits=outputs.router_logits,
        )


__all__ = [
    "MuseSparkPreTrainedModel",
    "MuseSparkTextModel",
    "MuseSparkVisionModel",
    "MuseSparkAudioModel",
    "MuseSparkModel",
    "MuseSparkForConditionalGeneration",
]
