CoolFace
Modelpublic

stepfun-ai/Step-3.5-Flash

sourceHugging Faceapache-2.0updated 6mo agoView on Hugging Face
838likes131kdownloads
modeling_step3p5.py901 linesDownload Raw Back to root
1# Copyright 2025 The LLAMA4 and HuggingFace Inc. team. All rights reserved.2#3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15from dataclasses import dataclass16from typing import Callable, Optional, Tuple, Union17 18import torch19import torch.nn as nn20import torch.nn.functional as F21from transformers.activations import ACT2FN22from transformers.cache_utils import Cache, DynamicCache23from transformers.generation import GenerationMixin24from transformers.masking_utils import (create_causal_mask,25                                        create_sliding_window_causal_mask)26from transformers.modeling_flash_attention_utils import FlashAttentionKwargs27from transformers.modeling_layers import GradientCheckpointingLayer28from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput29from transformers.modeling_rope_utils import (ROPE_INIT_FUNCTIONS,30                                              dynamic_rope_update)31from transformers.modeling_utils import (ALL_ATTENTION_FUNCTIONS,32                                         PreTrainedModel)33from transformers.processing_utils import Unpack34from transformers.utils import TransformersKwargs, can_return_tuple, logging35 36from .configuration_step3p5 import Step3p5Config37 38logger = logging.get_logger(__name__)39 40__all__ = ["Step3p5Model", "Step3p5ForCausalLM"]41 42class Step3p5RotaryEmbedding(nn.Module):43 44    def __init__(self, config: Step3p5Config, device=None, layer_idx=None):45        super().__init__()46        # BC: "rope_type" was originally "type"47        self.layer_idx = layer_idx48        if config.rope_parameters is not None:49            self.rope_type = config.rope_parameters.get(50                "rope_type", config.rope_parameters.get("type"))51        else:52            self.rope_type = "default"53        self.max_seq_len_cached = config.max_position_embeddings54        self.original_max_seq_len = config.max_position_embeddings55 56        partial_rotary_factors = getattr(config, "partial_rotary_factors",57                                         None)58        if partial_rotary_factors is not None:59            config.partial_rotary_factor = partial_rotary_factors[60                self.layer_idx]61        else:62            config.partial_rotary_factor = 1.063 64        self.rope_theta = config.rope_theta65        if isinstance(config.rope_theta, list):66            self.rope_theta = config.rope_theta.copy()67            config.rope_theta = self.rope_theta[self.layer_idx]68 69        self.config = config70        self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]71        inv_freq, self.attention_scaling = self.rope_init_fn(72            self.config, device)73 74        self.register_buffer("inv_freq", inv_freq, persistent=False)75        self.original_inv_freq = self.inv_freq76        config.rope_theta = self.rope_theta77 78    @torch.no_grad()79    @dynamic_rope_update  # power user: used with advanced RoPE types (e.g. dynamic rope)80    def forward(self, x, position_ids):81        inv_freq_expanded = self.inv_freq[None, :, None].float().expand(82            position_ids.shape[0], -1, 1).to(x.device)83        position_ids_expanded = position_ids[:, None, :].float().to(x.device)84 85        device_type = x.device.type if isinstance(86            x.device.type, str) and x.device.type != "mps" else "cpu"87        with torch.autocast(device_type=device_type,88                            enabled=False):  # Force float3289            freqs = (inv_freq_expanded.float()90                     @ position_ids_expanded.float()).transpose(1, 2)91            emb = torch.cat((freqs, freqs), dim=-1)92            cos = emb.cos() * self.attention_scaling93            sin = emb.sin() * self.attention_scaling94 95        return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)96 97 98def rotate_half(x):99    """Rotates half the hidden dims of the input."""100    x1 = x[..., :x.shape[-1] // 2]101    x2 = x[..., x.shape[-1] // 2:]102    return torch.cat((-x2, x1), dim=-1)103 104 105def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):106    """Applies Rotary Position Embedding to the query and key tensors.107 108    Args:109        q (`torch.Tensor`): The query tensor.110        k (`torch.Tensor`): The key tensor.111        cos (`torch.Tensor`): The cosine part of the rotary embedding.112        sin (`torch.Tensor`): The sine part of the rotary embedding.113        position_ids (`torch.Tensor`, *optional*):114            Deprecated and unused.115        unsqueeze_dim (`int`, *optional*, defaults to 1):116            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and117            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note118            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and119            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes120            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have121            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.122    Returns:123        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.124    """125    rotary_dim = cos.shape[-1]126    q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]127    k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]128 129    # Apply rotary embeddings on the first half or full tensor130    q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)131    k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)132 133    # Concatenate back to full shape134    q_embed = torch.cat([q_embed, q_pass], dim=-1)135    k_embed = torch.cat([k_embed, k_pass], dim=-1)136    return q_embed, k_embed137 138 139def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:140    """141    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,142    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)143    """144    batch, num_key_value_heads, slen, head_dim = hidden_states.shape145    if n_rep == 1:146        return hidden_states147    hidden_states = hidden_states[:, :,148                                  None, :, :].expand(batch,149                                                     num_key_value_heads,150                                                     n_rep, slen, head_dim)151    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen,152                                 head_dim)153 154 155# Adapted from transformers.models.llama.modeling_llama.eager_attention_forward -> llama4 doesn't cast attn weights to fp32156def eager_attention_forward(157    module: nn.Module,158    query: torch.Tensor,159    key: torch.Tensor,160    value: torch.Tensor,161    attention_mask: Optional[torch.Tensor],162    scaling: float,163    dropout: float = 0.0,164    **kwargs,165):166    key_states = repeat_kv(key, module.num_key_value_groups)167    value_states = repeat_kv(value, module.num_key_value_groups)168    # breakpoint()169    attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling170    if attention_mask is not None:171        causal_mask = attention_mask[:, :, :, :key_states.shape[-2]]172        attn_weights = attn_weights + causal_mask173 174    attn_weights = nn.functional.softmax(attn_weights, dim=-1)175    attn_weights = nn.functional.dropout(attn_weights,176                                         p=dropout,177                                         training=module.training)178    attn_output = torch.matmul(attn_weights, value_states)179    attn_output = attn_output.transpose(1, 2).contiguous()180 181    return attn_output, attn_weights182 183@dataclass184class Step3p5CausalLMOutputWithPast(ModelOutput):185    r"""186    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):187        Language modeling loss (for next-token prediction).188    logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):189        Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).190    past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):191        Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape192        `(batch_size, num_heads, sequence_length, embed_size_per_head)`)193        Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see194        `past_key_values` input) to speed up sequential decoding.195    """196 197    loss: Optional[torch.FloatTensor] = None198    last_hidden_state: Optional[torch.FloatTensor] = None199    logits: torch.FloatTensor = None200    past_key_values: Optional[list[torch.FloatTensor]] = None201    hidden_states: Optional[tuple[torch.FloatTensor]] = None202    attentions: Optional[tuple[torch.FloatTensor]] = None203 204 205class Step3p5MLP(nn.Module):206 207    def __init__(self, config, intermediate_size=None, swiglu_limit=None):208        super().__init__()209        self.config = config210        self.hidden_size = config.hidden_size211        self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size212        self.gate_proj = nn.Linear(self.hidden_size,213                                   self.intermediate_size,214                                   bias=False)215        self.up_proj = nn.Linear(self.hidden_size,216                                 self.intermediate_size,217                                 bias=False)218        self.down_proj = nn.Linear(self.intermediate_size,219                                   self.hidden_size,220                                   bias=False)221        self.act_fn = ACT2FN["silu"]222        self.limit = swiglu_limit223 224    def forward(self, x):225        up = self.up_proj(x)226        gate = self.act_fn(self.gate_proj(x))227        if self.limit is not None:228            gate = gate.clamp(min=None, max=self.limit)229            up = up.clamp(min=-self.limit, max=self.limit)230 231        return self.down_proj(gate * up)232 233 234def sigmoid_routing_function(gating_output: torch.Tensor, topk: int,235                             renormalize: bool):236    gating_output = gating_output.float()237    gate_prob = torch.sigmoid(gating_output)238    gate_prob = gate_prob / gate_prob.sum(dim=-1, keepdim=True)239    topk_prob, indices = torch.topk(gate_prob, k=topk, dim=1)240    expert_topk_weight = topk_prob241    if renormalize:242        expert_topk_weight = expert_topk_weight / torch.sum(243            expert_topk_weight, dim=-1, keepdim=True)244    return expert_topk_weight, indices245 246 247def softmax_routing_function(gating_output: torch.Tensor, top_k: int,248                             renormalize: bool):249    gating_output = gating_output.float()250    gate_prob = torch.softmax(gating_output, dim=-1)251    gate_prob = gate_prob / gate_prob.sum(dim=-1, keepdim=True)252    topk_prob, indices = torch.topk(gate_prob, k=top_k, dim=1)253    expert_topk_weight = topk_prob254    if renormalize:255        expert_topk_weight = expert_topk_weight / torch.sum(256            expert_topk_weight, dim=-1, keepdim=True)257    return expert_topk_weight, indices.to(torch.int32)258 259 260class MoELinear(nn.Module):261 262    def __init__(self, num_experts, in_features, out_features):263        super().__init__()264        self.num_experts = num_experts265        self.in_features = in_features266        self.out_features = out_features267        self.weight = nn.Parameter(268            torch.empty(num_experts, out_features, in_features))269 270    def forward(self, x, expert_id):271        x = F.linear(x.float(), self.weight[expert_id].float())272        return x273 274 275class Step3p5MoEMLP(nn.Module):276 277    def __init__(self, config, swiglu_limit=None):278        super().__init__()279        self.num_experts = config.moe_num_experts280        self.top_k = config.moe_top_k281        self.hidden_size = config.hidden_size282        self.moe_intermediate_size = config.moe_intermediate_size283 284        self.use_moe_router_bias = config.use_moe_router_bias285        if self.use_moe_router_bias:286            self.router_bias = nn.Parameter(torch.zeros(config.moe_num_experts,287                                                        dtype=torch.float32),288                                            requires_grad=False)289            self.custom_routing_function = self.router_bias_func290        elif config.moe_router_activation == "sigmoid":291            self.custom_routing_function = sigmoid_routing_function292        else:293            self.custom_routing_function = None294        self.need_fp32_gate = config.need_fp32_gate295        self.routed_scaling_factor = getattr(config,296                                             "moe_router_scaling_factor", 1.0)297        298        # gating299        self.gate = nn.Linear(self.hidden_size, self.num_experts, bias=False)300            301        self.act_fn = ACT2FN["silu"]302        self.limit = swiglu_limit303 304        self.up_proj = MoELinear(self.num_experts, self.hidden_size,305                                 self.moe_intermediate_size)306        self.gate_proj = MoELinear(self.num_experts, self.hidden_size,307                                   self.moe_intermediate_size)308        self.down_proj = MoELinear(self.num_experts,309                                   self.moe_intermediate_size,310                                   self.hidden_size)311 312    def router_bias_func(self, gating_output: torch.Tensor, topk: int,313                         renormalize: bool):314        gate_prob = torch.sigmoid(gating_output.float())315        gate_prob_with_bias = gate_prob + self.router_bias.unsqueeze(0)316        _, indices = torch.topk(gate_prob_with_bias, k=topk, dim=1)317        topk_prob = torch.gather(gate_prob, 1, indices)318        expert_topk_weight = topk_prob319        if renormalize:320            expert_topk_weight = expert_topk_weight / (321                torch.sum(expert_topk_weight, dim=-1, keepdim=True) + 1e-20)322        return expert_topk_weight, indices323 324    def get_expert_output(self, inputs: torch.Tensor, expert_id):325        #if self.limit is None:326        up = self.up_proj(inputs, expert_id)327        gate = self.act_fn(self.gate_proj(inputs, expert_id))328        if self.limit is not None:329            gate = gate.clamp(min=None, max=self.limit)330            up = up.clamp(min=-self.limit, max=self.limit)331 332        return self.down_proj(gate * up, expert_id)333 334    def forward(self, hidden_states):335        """ """336        batch_size, sequence_length, hidden_dim = hidden_states.shape337        hidden_states = hidden_states.view(-1, hidden_dim)338        if self.need_fp32_gate:339            router_logits = torch.matmul(hidden_states.to(torch.float32), self.gate.weight.t().to(torch.float32))340        else:341            # router_logits: (batch * sequence_length, n_experts)342            router_logits = self.gate(hidden_states)343        344        if self.custom_routing_function:345            routing_weights, selected_experts = self.custom_routing_function(346                router_logits, self.top_k, renormalize=True)347        else:348            routing_weights = F.softmax(router_logits,349                                        dim=1,350                                        dtype=torch.float)351            routing_weights, selected_experts = torch.topk(routing_weights,352                                                           self.top_k,353                                                           dim=-1)354 355        routing_weights = routing_weights * self.routed_scaling_factor356 357        final_hidden_states = torch.zeros(358            (batch_size * sequence_length, hidden_dim),359            dtype=hidden_states.dtype,360            device=hidden_states.device)361 362        # One hot encode the selected experts to create an expert mask363        # this will be used to easily index which expert is going to be sollicitated364        expert_mask = torch.nn.functional.one_hot(365            selected_experts, num_classes=self.num_experts).permute(2, 1, 0)366 367        # Loop over all available experts in the model and perform the computation on each expert368        for expert_idx in range(self.num_experts):369            idx, top_x = torch.where(expert_mask[expert_idx])370 371            # Index the correct hidden states and compute the expert hidden state for372            # the current expert. We need to make sure to multiply the output hidden373            # states by `routing_weights` on the corresponding tokens (top-1 and top-2)374            current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)375            current_hidden_states = (376                self.get_expert_output(current_state, expert_idx) *377                routing_weights[top_x, idx, None])378 379            # However `index_add_` only support torch tensors for indexing so we'll use380            # the `top_x` tensor here.381            final_hidden_states.index_add_(382                0, top_x, current_hidden_states.to(hidden_states.dtype))383        final_hidden_states = final_hidden_states.reshape(384            batch_size, sequence_length, hidden_dim)385        return final_hidden_states386 387 388class Step3p5RMSNorm(nn.Module):389 390    def __init__(391        self,392        hidden_size: int,393        eps: float = 1e-5,394    ) -> None:395        super().__init__()396        self.weight = nn.Parameter(torch.ones(hidden_size))397        self.variance_epsilon = eps398 399    def forward(self, x: torch.Tensor) -> torch.Tensor:400        dtype = x.dtype401        x = x.float()402        variance = x.pow(2).mean(dim=-1, keepdim=True)403        normed = x * torch.rsqrt(variance + self.variance_epsilon)404        normed = normed * (self.weight.float() + 1)405        return normed.to(dtype)406class Step3p5Attention(nn.Module):407 408    def __init__(self, config: Step3p5Config, layer_idx):409        super().__init__()410        self.config = config411        self.layer_idx = layer_idx412        self.num_attention_heads = config.num_attention_heads413        self.num_key_value_heads = config.num_attention_groups414 415        layer_types = getattr(config, "layer_types", [])416        if layer_types:417            enable_sliding_window = layer_types[418                self.layer_idx] == "sliding_attention"419        else:420            enable_sliding_window = self.layer_idx % 2 == 0421        422        if hasattr(config, "yarn_only_types") and layer_types[423                self.layer_idx] not in config.yarn_only_types:424            config.rope_parameters = None425        else:426            config.rope_parameters = getattr(config, "rope_scaling", None)427 428        self.sliding_window = config.sliding_window429        if enable_sliding_window:430            self.num_attention_heads = config.attention_other_setting[431                "num_attention_heads"]432            self.num_key_value_heads = config.attention_other_setting[433                "num_attention_groups"]434 435        if self.sliding_window is not None and enable_sliding_window:436            self.sliding_window = (self.sliding_window)437        else:438            self.sliding_window = None439        self.head_dim = getattr(config, "head_dim",440                        config.hidden_size // self.num_attention_heads)441        self.num_key_value_groups = self.num_attention_heads // self.num_key_value_heads442 443        self.rotary_emb = Step3p5RotaryEmbedding(config, layer_idx=layer_idx)444 445        self.q_size = self.num_attention_heads * self.head_dim446        self.kv_size = self.num_key_value_heads * self.head_dim447        self.scaling = self.head_dim**-0.5448 449        self.q_proj = nn.Linear(config.hidden_size, self.q_size, bias=False)450        self.k_proj = nn.Linear(config.hidden_size, self.kv_size, bias=False)451        self.v_proj = nn.Linear(config.hidden_size, self.kv_size, bias=False)452        self.o_proj = nn.Linear(self.q_size, config.hidden_size, bias=False)453        self.q_norm = Step3p5RMSNorm(self.head_dim,454                                    eps=config.rms_norm_eps)455        self.k_norm = Step3p5RMSNorm(self.head_dim,456                                    eps=config.rms_norm_eps)457 458        self.use_head_wise_attn_gate = config.use_head_wise_attn_gate459        if self.use_head_wise_attn_gate:460            self.g_proj = nn.Linear(config.hidden_size,461                                    self.num_attention_heads,462                                    bias=False)463 464        self.use_rope = True465        use_rope_layers = getattr(config, "use_rope_layers", None)466        if use_rope_layers:467            self.use_rope = use_rope_layers[self.layer_idx]468 469    def forward(470        self,471        hidden_states: torch.Tensor,472        attention_mask: Optional[torch.Tensor],473        past_key_value: Optional[Cache] = None,474        cache_position: Optional[torch.LongTensor] = None,475        position_ids: Optional[torch.LongTensor] = None,476        **kwargs: Unpack[FlashAttentionKwargs],477    ) -> Tuple[torch.Tensor, Optional[torch.Tensor],478               Optional[Tuple[torch.Tensor]]]:479        input_shape = hidden_states.shape[:-1]480        hidden_shape = (*input_shape, -1, self.head_dim)481 482        query_states = self.q_norm(483            self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)484        key_states = self.k_norm(485            self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)486        value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(487            1, 2)488        if self.use_head_wise_attn_gate:489            gate_states = self.g_proj(hidden_states)490        cos, sin = self.rotary_emb(hidden_states, position_ids)491 492        # cos, sin = position_embeddings493        query_states, key_states = apply_rotary_pos_emb(494            query_states, key_states, cos, sin)495 496        # query_states, key_states = apply_rotary_pos_emb(query_norm_states, key_norm_states, cos, sin)497        if past_key_value is not None:498            # sin and cos are specific to RoPE models; position_ids needed for the static cache499            cache_kwargs = {500                "sin": sin,501                "cos": cos,502                "cache_position": cache_position503            }504            key_states, value_states = past_key_value.update(505                key_states, value_states, self.layer_idx, cache_kwargs)506 507        attention_interface: Callable = eager_attention_forward508        # TODO: considering FP8;509        # RuntimeError: Expected attn_mask dtype to be bool or float or to match query dtype,510        # but got attn_mask.dtype: long int and  query.dtype: c10::BFloat16 instead.511        if self.config._attn_implementation != "eager":512            attention_interface = ALL_ATTENTION_FUNCTIONS[513                self.config._attn_implementation]514 515        attn_output, attn_weights = attention_interface(516            self,517            query_states,518            key_states,519            value_states,520            attention_mask,521            dropout=0.0 if not self.training else self.attention_dropout,522            scaling=self.scaling,523            sliding_window=self.sliding_window,  # main diff with Llama524            **kwargs,525        )526        attn_output = attn_output.reshape(*input_shape, -1)527        if self.use_head_wise_attn_gate:528            output = attn_output.view(529                *attn_output.shape[:-1], self.num_attention_heads,530                self.head_dim) * gate_states.unsqueeze(-1).sigmoid()531            attn_output = output.view(*attn_output.shape)532        attn_output = self.o_proj(attn_output)533 534        return attn_output, attn_weights535 536 537class Step3p5DecoderLayer(GradientCheckpointingLayer):538 539    def __init__(self, config, layer_idx):540        super().__init__()541        self.hidden_size = config.hidden_size542        self.layer_idx = layer_idx543        self.self_attn = Step3p5Attention(config, layer_idx)544        self.attention_type = config.layer_types[layer_idx]545 546        moe_layers_enum = getattr(config, "moe_layers_enum", None)547        if moe_layers_enum is not None:548            moe_layers_idx = [549                int(i) for i in moe_layers_enum.strip().split(',')550            ]551        else:552            moe_layers_idx = [i for i in range(1, config.num_hidden_layers)]553        self.is_moe_layer = layer_idx in moe_layers_idx554        self.use_moe = False555 556        if config.swiglu_limits_shared and config.swiglu_limits_shared[557                layer_idx] is not None and config.swiglu_limits_shared[558                    layer_idx] != 0:559            swiglu_limit_shared = config.swiglu_limits_shared[layer_idx]560        else:561            swiglu_limit_shared = None562        if config.swiglu_limits and config.swiglu_limits[563                layer_idx] is not None and config.swiglu_limits[layer_idx] != 0:564            swiglu_limit = config.swiglu_limits[layer_idx]565        else:566            swiglu_limit = None567        if self.is_moe_layer:568            self.moe = Step3p5MoEMLP(config, swiglu_limit=swiglu_limit)  #569            self.share_expert = Step3p5MLP(570                config,571                intermediate_size=config.share_expert_dim,572                swiglu_limit=swiglu_limit_shared)573            self.use_moe = True574        else:575            self.mlp = Step3p5MLP(config,576                                 intermediate_size=config.intermediate_size,577                                 swiglu_limit=swiglu_limit_shared)578 579        self.input_layernorm = Step3p5RMSNorm(580            config.hidden_size,581            eps=config.rms_norm_eps)582        self.post_attention_layernorm = Step3p5RMSNorm(583            config.hidden_size,584            eps=config.rms_norm_eps)585 586    def forward(587        self,588        hidden_states: torch.Tensor,589        attention_mask: Optional[torch.Tensor] = None,590        position_ids: Optional[torch.LongTensor] = None,591        past_key_value: Optional[tuple[torch.Tensor]] = None,592        cache_position: Optional[torch.LongTensor] = None,593        **kwargs: Unpack[FlashAttentionKwargs],594    ) -> torch.FloatTensor:595        residual = hidden_states596        hidden_states = self.input_layernorm(hidden_states)597        hidden_states, _ = self.self_attn(598            hidden_states=hidden_states,599            attention_mask=attention_mask,600            position_ids=position_ids,601            past_key_value=past_key_value,602            cache_position=cache_position,603            **kwargs,604        )605        hidden_states = residual + hidden_states606        607        # Fully Connected608        residual = hidden_states609        hidden_states = self.post_attention_layernorm(hidden_states)610        if self.use_moe:611            share_output = self.share_expert(hidden_states)612            moe_output = self.moe(hidden_states)613            ffn_output = moe_output + share_output614        else:615            ffn_output = self.mlp(hidden_states)616        if isinstance(ffn_output, tuple):617            hidden_states, _ = ffn_output618        else:619            hidden_states = ffn_output620 621        hidden_states = residual + hidden_states622        return hidden_states623 624 625class Step3p5PreTrainedModel(PreTrainedModel):626    # Link this model family to its configuration class so PreTrainedModel.from_pretrained627    # can load the config instead of failing with a NoneType error.628    config_class = Step3p5Config629    supports_gradient_checkpointing = True630    _skip_keys_device_placement = ["past_key_values"]631    _keys_to_ignore_on_load_unexpected = [632        r"model\.layers\.45\.*",633        r"model\.layers\.46\.*",634        r"model\.layers\.47\.*"635    ]636    _supports_flash_attn = False637    _supports_sdpa = True638    _supports_flex_attn = True639    _supports_static_cache = True640    _supports_attention_backend = True641 642 643class Step3p5Model(Step3p5PreTrainedModel, GenerationMixin):644    _no_split_modules = ["Step3p5DecoderLayer"]645    base_model_prefix = "model"646    _tied_weights_keys = ["lm_head.weight"]647    config: Step3p5Config648    def __init__(self, config: Step3p5Config):649        super().__init__(config)650        self.padding_idx = config.pad_token_id651        self.vocab_size = config.vocab_size652 653        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size,654                                         self.padding_idx)655        self.layers = nn.ModuleList([656            Step3p5DecoderLayer(config, layer_idx)657            for layer_idx in range(config.num_hidden_layers)658        ])659        self.norm = Step3p5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)660        self.gradient_checkpointing = False661        self.has_sliding_layers = "sliding_attention" in self.config.layer_types662 663        # Initialize weights and apply final processing664        self.post_init()665 666    def get_input_embeddings(self, input_ids):667        return self.embed_tokens(input_ids)668 669    @can_return_tuple670    def forward(671        self,672        input_ids: torch.LongTensor = None,673        attention_mask: Optional[torch.Tensor] = None,674        position_ids: Optional[torch.LongTensor] = None,675        past_key_values: Optional[Cache] = None,676        inputs_embeds: Optional[torch.FloatTensor] = None,677        use_cache: Optional[bool] = None,678        output_attentions: Optional[bool] = None,679        output_hidden_states: Optional[bool] = None,680        return_dict: Optional[bool] = None,681        cache_position: Optional[torch.LongTensor] = None,682        **kwargs: Unpack[TransformersKwargs],683    ) -> Union[tuple, BaseModelOutputWithPast]:684        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions685        output_hidden_states = (output_hidden_states686                                if output_hidden_states is not None else687                                self.config.output_hidden_states)688        use_cache = use_cache if use_cache is not None else self.config.use_cache689        return_dict = return_dict if return_dict is not None else self.config.use_return_dict690        if (input_ids is None) ^ (inputs_embeds is not None):691            raise ValueError(692                "You must specify exactly one of input_ids or inputs_embeds")693 694        if self.gradient_checkpointing and self.training and use_cache:695            logger.warning_once(696                "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."697            )698            use_cache = False699 700        if inputs_embeds is None:701            inputs_embeds = self.embed_tokens(702                input_ids.to(self.embed_tokens.weight.device))703 704        if use_cache and past_key_values is None:705            past_key_values = DynamicCache()706 707        if cache_position is None:708            past_seen_tokens = past_key_values.get_seq_length(709            ) if past_key_values is not None else 0710            cache_position = torch.arange(past_seen_tokens,711                                          past_seen_tokens +712                                          inputs_embeds.shape[1],713                                          device=inputs_embeds.device)714 715        if position_ids is None:716            position_ids = cache_position.unsqueeze(0)717 718        hidden_states = inputs_embeds719 720        # It may already have been prepared by e.g. `generate`721        if not isinstance(causal_mask_mapping := attention_mask, dict):722            # Prepare mask arguments723            mask_kwargs = {724                "config": self.config,725                "input_embeds": inputs_embeds,726                "attention_mask": attention_mask,727                "cache_position": cache_position,728                "past_key_values": past_key_values,729                "position_ids": position_ids,730            }731            # Create the masks732            causal_mask_mapping = {733                "full_attention": create_causal_mask(**mask_kwargs),734            }735 736            # The sliding window alternating layers are not always activated depending on the config737            if self.has_sliding_layers:738                causal_mask_mapping[739                    "sliding_attention"] = create_sliding_window_causal_mask(740                        **mask_kwargs)741 742        # # create position embeddings to be shared across the decoder layers743        # decoder layers744        all_hidden_states = () if output_hidden_states else None745        all_self_attns = () if output_attentions else None746        for decoder_layer in self.layers[:self.config.num_hidden_layers]:747            if output_hidden_states:748                all_hidden_states += (hidden_states, )749 750            layer_outputs = decoder_layer(751                hidden_states,752                attention_mask=causal_mask_mapping[753                    decoder_layer.attention_type],754                position_ids=position_ids,755                past_key_value=past_key_values,756                output_attentions=output_attentions,757                use_cache=use_cache,758                cache_position=cache_position,759                **kwargs,760            )761 762            hidden_states = layer_outputs763 764        hidden_states = self.norm(hidden_states)765 766        return BaseModelOutputWithPast(767            last_hidden_state=hidden_states,768            past_key_values=past_key_values if use_cache else None,769            hidden_states=all_hidden_states,770            attentions=all_self_attns,771        )772 773 774class Step3p5ForCausalLM(Step3p5PreTrainedModel, GenerationMixin):775    _tied_weights_keys = ["lm_head.weight"]776    config: Step3p5Config777 778    def __init__(self, config: Step3p5Config):779        super().__init__(config)780        self.model = Step3p5Model(config)781        self.lm_head = nn.Linear(config.hidden_size,782                                 config.vocab_size,783                                 bias=False)784 785        self.post_init()786 787    def get_input_embeddings(self):788        return self.model.get_input_embeddings()789 790    def set_input_embeddings(self, value):791        self.model.set_input_embeddings(value)792 793    def get_output_embeddings(self):794        return self.model.get_output_embeddings()795 796    def set_output_embeddings(self, new_embeddings):797        self.model.set_output_embeddings(new_embeddings)798 799    def set_decoder(self, decoder):800        self.model.set_decoder(decoder)801 802    def get_decoder(self):803        return self.model.get_decoder()804    805    def forward(806        self,807        input_ids: torch.LongTensor = None,808        num_patches=None,809        patch_pixel_values=None,810        patch_newline_mask=None,811        attention_mask: Optional[torch.Tensor] = None,812        position_ids: Optional[torch.LongTensor] = None,813        past_key_values: Optional[Cache] = None,814        inputs_embeds: Optional[torch.FloatTensor] = None,815        labels: Optional[torch.LongTensor] = None,816        use_cache: Optional[bool] = None,817        output_attentions: Optional[bool] = None,818        output_hidden_states: Optional[bool] = None,819        return_dict: Optional[bool] = None,820        cache_position: Optional[torch.LongTensor] = None,821        **kwargs: Unpack[TransformersKwargs],822    ) -> Union[tuple, Step3p5CausalLMOutputWithPast]:823        r"""824        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):825            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,826            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored827            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.828        Example:829        ```python830        >>> from transformers import AutoTokenizer, Llama4ForCausalLM831        >>> model = Llama4ForCausalLM.from_pretrained("meta-llama4/Llama4-2-7b-hf")832        >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama4/Llama4-2-7b-hf")833        >>> prompt = "Hey, are you conscious? Can you talk to me?"834        >>> inputs = tokenizer(prompt, return_tensors="pt")835        >>> # Generate836        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)837        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]838        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."839        ```"""840 841        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions842        output_hidden_states = (output_hidden_states843                                if output_hidden_states is not None else844                                self.config.output_hidden_states)845        # breakpoint()846        outputs = self.model(847            input_ids=input_ids,848            num_patches=num_patches,849            patch_pixel_values=patch_pixel_values,850            patch_newline_mask=patch_newline_mask,851            position_ids=position_ids,852            attention_mask=attention_mask,853            past_key_values=past_key_values,854            inputs_embeds=inputs_embeds,855            use_cache=use_cache,856            output_attentions=output_attentions,857            output_hidden_states=output_hidden_states,858            return_dict=return_dict,859            cache_position=cache_position,860            **kwargs,861        )862        hidden_states = outputs.last_hidden_state863        logits = self.lm_head(hidden_states)864 865        return Step3p5CausalLMOutputWithPast(logits=logits, )866 867    def prepare_inputs_for_generation(868        self,869        input_ids,870        past_key_values=None,871        inputs_embeds=None,872        pixel_values=None,873        attention_mask=None,874        cache_position=None,875        logits_to_keep=None,876        **kwargs,877    ):878 879        model_inputs = super().prepare_inputs_for_generation(880            input_ids,881            past_key_values=past_key_values,882            inputs_embeds=inputs_embeds,883            attention_mask=attention_mask,884            cache_position=cache_position,885            logits_to_keep=logits_to_keep,886            **kwargs,887        )888 889        if cache_position[0] == 0:890            # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore891            # Otherwise we need pixel values to be passed to model892            model_inputs["pixel_values"] = pixel_values893 894        return model_inputs895 896    def _fix_state_dict_key_on_load(self, key: str) -> tuple[str, bool]:897        if key.startswith("language_model."):898            return key[len("language_model."):], True899 900        return key, False901