# coding=utf-8 # Copyright 2025 Upstage AI. # Copyright 2025 The GLM4 & ZhipuAI team and HuggingFace Inc. team. # # 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. # # This file has been modified by Upstage AI including: # - Hybrid MoE Architecture: Replaced the standard dense structure with a depth-dependent Hybrid MoE, adding `SolarOpen2MoE` and `SolarOpen2TopkRouter` classes. # - RoPE Strategy: Changed the rotary position embedding strategy from GLM4's interleaved rotation to Llama-style block rotation (via modified `rotate_half`). # - Normalization Logic: Simplified the layer normalization structure by removing GLM4's extra post-operation norms and adding optional Query-Key Normalization (`use_qk_norm`). # # Based on code from: https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm4/modeling_glm4.py from typing import Callable, Optional, Union, Any import torch import torch.nn.functional as F from torch import nn from einops import rearrange from transformers.activations import ACT2FN from transformers.cache_utils import Cache, DynamicCache from transformers.generation import GenerationMixin from transformers.integrations import use_kernel_forward_from_hub from transformers.masking_utils import create_causal_mask from transformers.modeling_flash_attention_utils import FlashAttentionKwargs from transformers.modeling_layers import GradientCheckpointingLayer from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from transformers.processing_utils import Unpack from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple from transformers.utils.deprecation import deprecate_kwarg from transformers.utils.generic import check_model_inputs from .configuration_solar_open2 import SolarOpen2Config try: from fla.modules import FusedRMSNormGated, ShortConvolution from fla.ops.kda import chunk_kda, fused_recurrent_kda from fla.ops.kda.gate import fused_kda_gate from fla.layers.utils import get_unpad_data, index_first_axis, pad_input except ImportError: raise ImportError("Plese run `pip install -U fla-core`") 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 repeat_kv_linear(x: torch.Tensor, n_rep: int) -> torch.Tensor: """torch.repeat_interleave(x, dim=-2, repeats=n_rep) for (..., n_kv_heads, head_dim) layout.""" if n_rep == 1: return x shape = x.shape return ( x.unsqueeze(-2) .expand(*shape[:-1], n_rep, shape[-1]) .reshape(*shape[:-2], shape[-2] * n_rep, shape[-1]) ) def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], 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: causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, 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. position_ids (`torch.Tensor`, *optional*): Deprecated and unused. 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) # Keep half or full tensor for later concatenation rotary_dim = cos.shape[-1] q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:] k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:] # Apply rotary embeddings on the first half or full tensor q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin) k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin) # Concatenate back to full shape q_embed = torch.cat([q_embed, q_pass], dim=-1) k_embed = torch.cat([k_embed, k_pass], dim=-1) return q_embed, k_embed class SolarOpen2DynamicCache: """ Dynamic cache for SolarOpen2 model. Inspired by Kimi-Linear """ is_compileable = False def __init__(self, config: SolarOpen2Config): super().__init__() self.config = config if config.linear_attn_config is not None: self.layer_types = [] for i in range(config.num_hidden_layers): # Determine if this layer uses GQA: gqa_layers takes priority over gqa_interval if config.gqa_layers is not None: use_gqa = i in config.gqa_layers else: use_gqa = (i + 1) % config.gqa_interval == 0 if use_gqa: self.layer_types.append("full_attention") else: self.layer_types.append("linear_attention") else: self.layer_types = ["full_attention"] * config.num_hidden_layers self.transformer_layers = [ i for i in range(config.num_hidden_layers) if self.layer_types[i] == "full_attention" ] linear_layers = [i for i in range( config.num_hidden_layers) if self.layer_types[i] == "linear_attention"] self.last_linear_layer = linear_layers[-1] if linear_layers else -1 self.conv_states = [None for _ in range(config.num_hidden_layers)] self.recurrent_states = [None for _ in range(config.num_hidden_layers)] self.key_cache = [None for _ in range(config.num_hidden_layers)] self.value_cache = [None for _ in range(config.num_hidden_layers)] def __len__(self): return len(self.layer_types) def update( self, key_states: torch.Tensor, value_states: torch.Tensor, layer_idx: int, cache_kwargs: dict[str, Any] | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: if self.key_cache[layer_idx] is None: self.key_cache[layer_idx] = key_states self.value_cache[layer_idx] = value_states else: self.key_cache[layer_idx] = torch.cat( [self.key_cache[layer_idx], key_states], dim=2) self.value_cache[layer_idx] = torch.cat( [self.value_cache[layer_idx], value_states], dim=2) return self.key_cache[layer_idx], self.value_cache[layer_idx] def reorder_cache(self, beam_idx: torch.LongTensor): """Reorders the cache for beam search, given the selected beam indices.""" for layer_idx in range(len(self.key_cache)): if self.key_cache[layer_idx] is not None: device = self.key_cache[layer_idx].device beam_idx = beam_idx.to(device) self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select( 0, beam_idx) self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select( 0, beam_idx) if self.conv_states[layer_idx] is not None: device = self.conv_states[layer_idx][0].device beam_idx = beam_idx.to(device) q_conv, k_conv, v_conv = self.conv_states[layer_idx] self.conv_states[layer_idx] = ( q_conv.index_select(0, beam_idx), k_conv.index_select(0, beam_idx), v_conv.index_select(0, beam_idx), ) self.recurrent_states[layer_idx] = self.recurrent_states[layer_idx].index_select( 0, beam_idx) def get_seq_length(self, layer_idx: int | None = 0) -> int: """Returns the sequence length of the cached states. A layer index can be optionally passed.""" # take any layer that contains cache and not empty tensor layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx] is None: return 0 return self.key_cache[layer_idx].shape[-2] def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]: """ Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for the given layer at `layer_idx`. The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns for each layer. """ kv_offset = 0 query_length = cache_position.shape[0] past_seen_tokens = self.get_seq_length(layer_idx) kv_length = query_length + past_seen_tokens return kv_length, kv_offset @property def has_previous_state(self): """We have a previous state if the last linear (conv) layer was already updated.""" if self.last_linear_layer == -1: return False return self.conv_states[self.last_linear_layer] is not None class SolarOpen2LinearAttention(nn.Module): def __init__(self, config: SolarOpen2Config, layer_idx: int): super().__init__() self.config = config self.mode = "chunk" self.hidden_size = config.hidden_size self.conv_size = config.linear_attn_config["short_conv_kernel_size"] self.head_dim = config.linear_attn_config["head_dim"] self.num_heads = config.linear_attn_config["num_heads"] self.num_kv_heads = config.linear_attn_config.get("num_kv_heads", None) or self.num_heads self.n_rep = self.num_heads // self.num_kv_heads self.head_k_dim = self.head_dim self.num_k_heads = self.num_heads self.layer_idx = layer_idx self.use_full_proj = getattr(config, 'kda_use_full_proj', False) self.gate_lower_bound = getattr(config, 'kda_gate_lower_bound', -5.0) self.allow_neg_eigval = getattr(config, 'kda_allow_neg_eigval', False) assert self.mode in [ 'chunk', 'fused_recurrent'], f"Not suppoerted mode `{self.mode}`." projection_k_size = self.head_k_dim * self.num_k_heads projection_size = self.head_dim * self.num_heads kv_projection_size = self.head_dim * self.num_kv_heads self.q_proj = nn.Linear( self.hidden_size, projection_k_size, bias=False) self.k_proj = nn.Linear( self.hidden_size, kv_projection_size, bias=False) self.v_proj = nn.Linear(self.hidden_size, kv_projection_size, bias=False) self.q_conv1d = ShortConvolution( hidden_size=projection_k_size, kernel_size=self.conv_size, activation='silu', ) self.k_conv1d = ShortConvolution( hidden_size=kv_projection_size, kernel_size=self.conv_size, activation='silu', ) self.v_conv1d = ShortConvolution( hidden_size=kv_projection_size, kernel_size=self.conv_size, activation='silu', ) self.A_log = torch.nn.Parameter(torch.log(torch.empty( self.num_heads, dtype=torch.float32).uniform_(1, 16)).view(1, 1, -1, 1)) if self.use_full_proj: self.f_proj = nn.Linear(self.hidden_size, projection_size, bias=False) else: self.f_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False) self.f_b_proj = nn.Linear(self.head_dim, projection_size, bias=False) self.dt_bias = nn.Parameter( torch.empty(projection_size, dtype=torch.float32)) self.b_proj = nn.Linear(self.hidden_size, self.num_heads, bias=False) if self.use_full_proj: self.g_proj = nn.Linear(self.hidden_size, projection_size, bias=False) else: self.g_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False) self.g_b_proj = nn.Linear(self.head_dim, projection_size, bias=False) self.o_norm = FusedRMSNormGated( self.head_dim, eps=config.rms_norm_eps, activation='sigmoid') self.o_proj = nn.Linear(projection_size, self.hidden_size, bias=False) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, past_key_values: SolarOpen2DynamicCache | None = None, **kwargs: Unpack[dict], ) -> tuple[torch.Tensor, torch.Tensor | None, Cache | None]: if attention_mask is not None: if attention_mask.dim() != 2: attention_mask = kwargs.get("padding_mask") if attention_mask is not None and attention_mask.dim() != 2: raise ValueError( "attention_mask must be a 0-1 matrix of shape [batch_size, seq_len] " "(0 = padding). 3D masks are not supported here.", ) use_cache = past_key_values is not None batch_size, q_len, _ = hidden_states.shape mode = 'fused_recurrent' if q_len <= 64 else self.mode if self.training: assert mode == 'chunk', "Only chunk mode is supported in training." cu_seqlens = kwargs.get('cu_seqlens') indices = None if attention_mask is not None: indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) hidden_states = index_first_axis( rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) conv_state_q, conv_state_k, conv_state_v = None, None, None recurrent_state = None if past_key_values is not None: if past_key_values.conv_states[self.layer_idx] is not None: conv_state_q, conv_state_k, conv_state_v = past_key_values.conv_states[ self.layer_idx] recurrent_state = past_key_values.recurrent_states[self.layer_idx] q, conv_state_q = self.q_conv1d( x=self.q_proj(hidden_states), cache=conv_state_q, output_final_state=use_cache, cu_seqlens=cu_seqlens, ) k, conv_state_k = self.k_conv1d( x=self.k_proj(hidden_states), cache=conv_state_k, output_final_state=use_cache, cu_seqlens=cu_seqlens, ) v, conv_state_v = self.v_conv1d( x=self.v_proj(hidden_states), cache=conv_state_v, output_final_state=use_cache, cu_seqlens=cu_seqlens, ) if self.use_full_proj: g = self.f_proj(hidden_states) else: g = self.f_b_proj(self.f_a_proj(hidden_states)) q, k, g = (rearrange(x, "... (h d) -> ... h d", d=self.head_k_dim) for x in (q, k, g)) v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim) # repeat k/v heads if num_kv_heads < num_heads (GQA) k = repeat_kv_linear(k, self.n_rep) v = repeat_kv_linear(v, self.n_rep) g = fused_kda_gate(g, self.A_log, dt_bias=self.dt_bias, lower_bound=self.gate_lower_bound) beta = self.b_proj(hidden_states).sigmoid() if self.allow_neg_eigval: beta = beta * 2.0 if mode == 'chunk': o, recurrent_state = chunk_kda( q=q, k=k, v=v, g=g, beta=beta, initial_state=recurrent_state, output_final_state=True, use_qk_l2norm_in_kernel=True, cu_seqlens=cu_seqlens, ) else: o, recurrent_state = fused_recurrent_kda( q=q, k=k, v=v, g=g, beta=beta, initial_state=recurrent_state, output_final_state=True, use_qk_l2norm_in_kernel=True, cu_seqlens=cu_seqlens, ) if past_key_values is not None: past_key_values.recurrent_states[self.layer_idx] = recurrent_state past_key_values.conv_states[self.layer_idx] = ( conv_state_q, conv_state_k, conv_state_v) if self.use_full_proj: g = self.g_proj(hidden_states) else: g = self.g_b_proj(self.g_a_proj(hidden_states)) g = rearrange(g, '... (h d) -> ... h d', d=self.head_dim) o = self.o_norm(o, g) o = rearrange(o, 'b t h d -> b t (h d)') o = self.o_proj(o) if attention_mask is not None: o = pad_input(o.squeeze(0), indices, batch_size, q_len) return o, _ class SolarOpen2Attention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: SolarOpen2Config, layer_idx: Optional[int] = None): 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.rope_scaling = config.rope_scaling 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=False) self.use_qk_norm = config.use_qk_norm if self.use_qk_norm: self.q_norm = SolarOpen2RMSNorm(self.head_dim, eps=config.rms_norm_eps) self.k_norm = SolarOpen2RMSNorm(self.head_dim, eps=config.rms_norm_eps) self.use_gqa_gate = config.use_gqa_gate if self.use_gqa_gate: self.g_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.use_gqa_gate_bias) @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58") def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_values: Optional[SolarOpen2DynamicCache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, Optional[torch.Tensor]]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape) key_states = self.k_proj(hidden_states).view(hidden_shape) value_states = self.v_proj(hidden_states).view(hidden_shape) if self.use_qk_norm: # main diff from Llama query_states = self.q_norm(query_states) key_states = self.k_norm(key_states) query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) cos, sin = position_embeddings if self.config.use_rope: query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: # sin and cos are specific to RoPE models; position_ids needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() if self.use_gqa_gate: gate = self.g_proj(hidden_states) attn_output = attn_output * torch.sigmoid(gate) attn_output = self.o_proj(attn_output) return attn_output, attn_weights class SolarOpen2MLP(nn.Module): def __init__(self, config, hidden_size=None, intermediate_size=None): super().__init__() self.config = config self.hidden_size = config.hidden_size if hidden_size is None else hidden_size self.intermediate_size = config.intermediate_size if intermediate_size is None else 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 SolarOpen2TopkRouter(nn.Module): def __init__(self, config: SolarOpen2Config): super().__init__() self.config = config self.top_k = config.num_experts_per_tok self.n_routed_experts = config.n_routed_experts self.routed_scaling_factor = config.routed_scaling_factor self.n_group = config.n_group self.topk_group = config.topk_group self.norm_topk_prob = config.norm_topk_prob self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size))) self.e_score_correction_bias = nn.Parameter( torch.zeros((self.n_routed_experts), dtype=torch.float32)) @torch.no_grad() def get_topk_indices(self, scores): scores_for_choice = scores.view(-1, self.n_routed_experts) + self.e_score_correction_bias.unsqueeze(0) group_scores = ( scores_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group) .topk(2, dim=-1)[0] .sum(dim=-1) ) group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1] group_mask = torch.zeros_like(group_scores) group_mask.scatter_(1, group_idx, 1) score_mask = ( group_mask.unsqueeze(-1) .expand(-1, self.n_group, self.n_routed_experts // self.n_group) .reshape(-1, self.n_routed_experts) ) scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1] return topk_indices def forward(self, hidden_states): hidden_states = hidden_states.view(-1, self.config.hidden_size) router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32)) scores = router_logits.sigmoid() topk_indices = self.get_topk_indices(scores) topk_weights = scores.gather(1, topk_indices) if self.norm_topk_prob: denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20 topk_weights /= denominator topk_weights = topk_weights * self.routed_scaling_factor return topk_indices, topk_weights @use_kernel_forward_from_hub("RMSNorm") class SolarOpen2RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ SolarOpen2RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype) def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" class SolarOpen2MoE(nn.Module): """ A mixed expert module containing shared experts. """ def __init__(self, config): super().__init__() self.config = config self.experts = nn.ModuleList( [ SolarOpen2MLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.n_routed_experts) ] ) self.gate = SolarOpen2TopkRouter(config) self.shared_experts = SolarOpen2MLP( config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts ) @torch.compiler.disable() def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor): r""" MoE forward pass that only executes selected experts. Uses @torch.compiler.disable() to allow dynamic shape operations. Requires --enforce-eager flag when serving with vLLM. """ final_hidden_states = torch.zeros_like(hidden_states) for expert_idx in range(len(self.experts)): expert = self.experts[expert_idx] # Find positions where this expert was selected batch_idx, topk_pos = torch.where(topk_indices == expert_idx) if batch_idx.numel() == 0: continue # Extract only the tokens routed to this expert expert_input = hidden_states[batch_idx] expert_output = expert(expert_input) # Apply weights and accumulate results weights = topk_weights[batch_idx, topk_pos].unsqueeze(-1) final_hidden_states.index_add_(0, batch_idx, (expert_output * weights).to(hidden_states.dtype)) return final_hidden_states def forward(self, hidden_states): residuals = hidden_states orig_shape = hidden_states.shape topk_indices, topk_weights = self.gate(hidden_states) hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape) hidden_states = hidden_states + self.shared_experts(residuals) return hidden_states class SolarOpen2HyperConnection(nn.Module): """Hyper-Connections module for SolarOpen2 (pure PyTorch, no Triton). Learnable replacement for residual connections that expands the hidden state to N copies and uses learned mixing (width) and combining (depth) connections. Reference: https://arxiv.org/abs/2409.19606 """ def __init__(self, config: SolarOpen2Config, layer_idx: int): super().__init__() dim = config.hidden_size rate = config.hc_rate self.rate = rate self.dynamic = config.hc_dynamic self.use_tanh = config.hc_use_tanh self.use_sigmoid = getattr(config, "hc_use_sigmoid", False) self.static_alpha = nn.Parameter(torch.zeros(rate, rate + 1)) self.static_beta = nn.Parameter(torch.ones(rate)) if self.dynamic: self.dynamic_alpha_fn = nn.Parameter(torch.zeros(dim, rate + 1)) self.dynamic_alpha_scale = nn.Parameter(torch.ones(1) * 0.01) self.dynamic_beta_fn = nn.Parameter(torch.zeros(dim)) self.dynamic_beta_scale = nn.Parameter(torch.ones(1) * 0.01) self.norm = SolarOpen2RMSNorm(dim, eps=config.rms_norm_eps) def width_connection(self, h: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Split h into (h_in, h_res, beta) via learned width mixing. Args: h: (..., N, D) hidden states with N copies. Returns: h_in: (..., D) input for the sublayer. h_res: (..., N, D) residual for depth connection. beta: (N,) or (..., N) depth connection weights. """ if self.dynamic: norm_h = self.norm(h) # norm_h: (..., N, D), dynamic_alpha_fn: (D, rate+1) wc_weight = norm_h @ self.dynamic_alpha_fn # (..., N, rate+1) if self.use_tanh: wc_weight = torch.tanh(wc_weight) alpha = wc_weight * self.dynamic_alpha_scale + self.static_alpha # dc_weight: (..., N) dc_weight = (norm_h * self.dynamic_beta_fn).sum(-1) if self.use_tanh: dc_weight = torch.tanh(dc_weight) beta = dc_weight * self.dynamic_beta_scale + self.static_beta else: alpha = self.static_alpha beta = self.static_beta if self.use_sigmoid: alpha = torch.sigmoid(alpha) beta = 2.0 * torch.sigmoid(beta) # Mix: alpha^T @ h → (..., N+1, D) — float32 accumulators to match # the Triton kernels in TorchTitan which compute in fp32 internally. orig_dtype = h.dtype alpha_t = alpha.float().transpose(-2, -1) # (..., N+1, N) or (N+1, N) mix_h = torch.matmul(alpha_t, h.float()) # (..., N+1, D) h_in = mix_h[..., 0, :].to(orig_dtype) # (..., D) h_res = mix_h[..., 1:, :].to(orig_dtype) # (..., N, D) return h_in, h_res, beta def depth_connection(self, h_res: torch.Tensor, h_out: torch.Tensor, beta: torch.Tensor) -> torch.Tensor: """Combine sublayer output with residual via learned depth connection. Args: h_res: (..., N, D) residual from width connection. h_out: (..., D) sublayer output. beta: (N,) or (..., N) depth connection weights. Returns: h: (..., N, D) combined hidden states. """ # float32 accumulators to match Triton kernels in TorchTitan. return (h_out.float().unsqueeze(-2) * beta.float().unsqueeze(-1) + h_res.float()).to(h_out.dtype) class SolarOpen2DecoderLayer(GradientCheckpointingLayer): def __init__(self, config: SolarOpen2Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size # Hyper-Connections self.use_hc = getattr(config, "hc_rate", 0) > 0 if self.use_hc: self.attn_hc = SolarOpen2HyperConnection(config, layer_idx=2 * layer_idx) self.ffn_hc = SolarOpen2HyperConnection(config, layer_idx=2 * layer_idx + 1) # Determine if this layer uses GQA: gqa_layers takes priority over gqa_interval if config.gqa_layers is not None: use_gqa = layer_idx in config.gqa_layers else: use_gqa = (layer_idx + 1) % config.gqa_interval == 0 if use_gqa: self.is_linear_attn = False self.self_attn = SolarOpen2Attention(config=config, layer_idx=layer_idx) else: self.is_linear_attn = True self.self_attn = SolarOpen2LinearAttention(config=config, layer_idx=layer_idx) if layer_idx >= config.first_k_dense_replace: self.mlp = SolarOpen2MoE(config) else: self.mlp = SolarOpen2MLP(config) self.input_layernorm = SolarOpen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = SolarOpen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58") def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[SolarOpen2DynamicCache] = None, use_cache: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC **kwargs: Unpack[TransformersKwargs], ) -> torch.Tensor: if self.use_hc: # ═══ Attention with Hyper-Connections ═══ h_in, h_res, attn_beta = self.attn_hc.width_connection(hidden_states) h_in = self.input_layernorm(h_in) h_in, _ = self.self_attn( hidden_states=h_in, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = self.attn_hc.depth_connection(h_res, h_in, attn_beta) # ═══ FFN/MoE with Hyper-Connections ═══ ffn_h_in, ffn_h_res, ffn_beta = self.ffn_hc.width_connection(hidden_states) ffn_h_in = self.post_attention_layernorm(ffn_h_in) ffn_h_in = self.mlp(ffn_h_in) hidden_states = self.ffn_hc.depth_connection(ffn_h_res, ffn_h_in, ffn_beta) return hidden_states else: residual = hidden_states hidden_states = self.input_layernorm(hidden_states) # Self Attention hidden_states, _ = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states return hidden_states @auto_docstring class SolarOpen2PreTrainedModel(PreTrainedModel): config: SolarOpen2Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["SolarOpen2DecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _can_compile_fullgraph = False _supports_attention_backend = True _can_record_outputs = { "hidden_states": SolarOpen2DecoderLayer, "attentions": SolarOpen2Attention, } def _init_weights(self, module): super()._init_weights(module) if isinstance(module, SolarOpen2TopkRouter): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) class SolarOpen2RotaryEmbedding(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: SolarOpen2Config, device=None): super().__init__() # BC: "rope_type" was originally "type" if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict): self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type")) else: self.rope_type = "default" self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.config = config self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device) self.register_buffer("inv_freq", inv_freq, persistent=False) self.original_inv_freq = self.inv_freq @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) position_ids_expanded = position_ids[:, None, :].float() device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) @auto_docstring class SolarOpen2Model(SolarOpen2PreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"model\.layers\.92.*", r"model\.layers\.46.*"] def __init__(self, config: SolarOpen2Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.hc_rate = getattr(config, "hc_rate", 0) self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [SolarOpen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = SolarOpen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = SolarOpen2RotaryEmbedding(config=config) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def _update_linear_attn_mask(self, attention_mask, cache_position): """ NOTE: Left-padding is used for linear attention mask. No need for zeroing states when 1. Cached forward 2. Attending to all inputs """ linear_attn_mask = attention_mask if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)): linear_attn_mask = None return linear_attn_mask @check_model_inputs @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[SolarOpen2DynamicCache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, cache_position: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPast: 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: torch.Tensor = self.embed_tokens(input_ids) if use_cache and not isinstance(past_key_values, SolarOpen2DynamicCache): past_key_values = SolarOpen2DynamicCache(config=self.config) if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position: torch.Tensor = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) if position_ids is None: position_ids = cache_position.unsqueeze(0) causal_mask = create_causal_mask( config=self.config, input_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, position_ids=position_ids, ) linear_attn_mask = self._update_linear_attn_mask(attention_mask, cache_position) hidden_states = inputs_embeds position_embeddings = self.rotary_emb(hidden_states, position_ids) # Hyper-Connections: expand (B, L, D) → (B, L, N, D) by replicating N times if self.hc_rate > 0: hidden_states = hidden_states.unsqueeze(-2).expand( *hidden_states.shape[:-1], self.hc_rate, hidden_states.shape[-1] ).contiguous() for decoder_layer in self.layers[: self.config.num_hidden_layers]: layer_mask = linear_attn_mask if decoder_layer.is_linear_attn else causal_mask hidden_states = decoder_layer( hidden_states, attention_mask=layer_mask, position_ids=position_ids, past_key_values=past_key_values, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) # Hyper-Connections: contract (B, L, N, D) → (B, L, D) by summing N copies if self.hc_rate > 0: hidden_states = hidden_states.sum(dim=-2) hidden_states = self.norm(hidden_states) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values, ) @auto_docstring class SolarOpen2ForCausalLM(SolarOpen2PreTrainedModel, GenerationMixin): _tied_weights_keys = ["lm_head.weight"] _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = SolarOpen2Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[SolarOpen2DynamicCache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, cache_position=cache_position, **kwargs, ) hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = ["SolarOpen2PreTrainedModel", "SolarOpen2Model", "SolarOpen2ForCausalLM"]