"""Modeling for the Q-50M architecture (replica of q-project/Q-50M-Base). Self-contained implementation of the exact architecture described in the model card: Mistral-shaped 512-wide 10-layer decoder, GQA 8q/2kv, per-head QK-Norm, RoPE in every layer (configurable NoPE), scalar content-dependent gates (gate = multiplier * sigmoid(Wx)) on attention and MLP residual branches, SwiGLU MLP, tied input/output embeddings, final RMSNorm. Follows the transformers v5 modeling pattern (DynamicCache, create_causal_mask, GradientCheckpointingLayer, GenerationMixin). """ from collections.abc import Callable import torch import torch.nn as nn import torch.nn.functional as F from transformers.cache_utils import Cache, DynamicCache from transformers.generation import GenerationMixin from transformers.masking_utils import create_causal_mask from transformers.modeling_layers import GradientCheckpointingLayer from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from transformers.processing_utils import Unpack from transformers.utils import TransformersKwargs try: from .configuration_q50m import Q50MConfig except ImportError: # standalone use inside an HF model directory from configuration_q50m import Q50MConfig def _rotate_half(x: torch.Tensor) -> torch.Tensor: 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): # cos/sin: (batch, seq, head_dim) cos = cos.unsqueeze(1) sin = sin.unsqueeze(1) return q * cos + _rotate_half(q) * sin, k * cos + _rotate_half(k) * sin class Q50MRMSNorm(nn.Module): def __init__(self, hidden_size: int, eps: float = 1e-6) -> None: super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: 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)).to(input_dtype) def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" class Q50MRotaryEmbedding(nn.Module): def __init__(self, config: Q50MConfig, device=None): super().__init__() self.config = config inv_freq = 1.0 / ( config.rope_theta ** (torch.arange(0, config.head_dim, 2, dtype=torch.float32, device=device) / config.head_dim) ) self.inv_freq = nn.Buffer(inv_freq, persistent=True) @torch.no_grad() def forward(self, x, position_ids): inv_freq_expanded = ( self.inv_freq[None, :, None].expand(position_ids.shape[0], -1, 1) .to(dtype=torch.float32, device=x.device) ) position_ids_expanded = position_ids[:, None, :].float() freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) return emb.cos().to(dtype=x.dtype), emb.sin().to(dtype=x.dtype) class Q50MScalarGate(nn.Module): """Content-dependent scalar gate: output = branch * multiplier * sigmoid(W x).""" def __init__(self, hidden_size: int, multiplier: float = 2.0): super().__init__() self.projection = nn.Linear(hidden_size, 1, bias=False) self.multiplier = multiplier def forward(self, branch: torch.Tensor, residual_input: torch.Tensor) -> torch.Tensor: return branch * self.multiplier * torch.sigmoid(self.projection(residual_input)) def reset_parameters(self): nn.init.zeros_(self.projection.weight) def _repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) def _eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor | None, scaling: float, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs], ): key_states = _repeat_kv(key, module.num_key_value_groups) value_states = _repeat_kv(value, module.num_key_value_groups) attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling if attention_mask is not None: attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights def _sdpa_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], ): """Local SDPA wrapper. HF's generic SDPA interface falls back to the math backend for GQA shapes (q heads != kv heads), which materializes (batch, heads, seq, seq) fp32 attention scores. Expanding kv first keeps the fused flash / memory-efficient kernels eligible.""" n_rep = getattr(module, "num_key_value_groups", 1) if n_rep > 1: key = _repeat_kv(key, n_rep) value = _repeat_kv(value, n_rep) is_causal = ( attention_mask is None and getattr(module, "is_causal", False) and query.shape[2] > 1 ) attn_output = nn.functional.scaled_dot_product_attention( query, key, value, attn_mask=attention_mask, dropout_p=dropout, is_causal=is_causal, scale=scaling, ) return attn_output.transpose(1, 2).contiguous(), None class Q50MAttention(nn.Module): def __init__(self, config: Q50MConfig, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = config.head_dim self.num_heads = config.num_attention_heads self.num_kv_heads = config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_kv_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.is_causal = True self.use_rope = layer_idx not in config.nope_layers inner = self.num_heads * self.head_dim kv_inner = self.num_kv_heads * self.head_dim self.q_proj = nn.Linear(config.hidden_size, inner, bias=False) self.k_proj = nn.Linear(config.hidden_size, kv_inner, bias=False) self.v_proj = nn.Linear(config.hidden_size, kv_inner, bias=False) self.o_proj = nn.Linear(inner, config.hidden_size, bias=False) self.q_norm = Q50MRMSNorm(self.head_dim, config.rms_norm_eps) if config.qk_norm else None self.k_norm = Q50MRMSNorm(self.head_dim, config.rms_norm_eps) if config.qk_norm else None self.output_gate = ( Q50MScalarGate(config.hidden_size, config.gate_multiplier) if config.attention_scalar_gate else None ) 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]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) q = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) k = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) v = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) if self.q_norm is not None: q = self.q_norm(q) k = self.k_norm(k) if self.use_rope: cos, sin = position_embeddings q, k = _apply_rotary_pos_emb(q, k, cos, sin) if past_key_values is not None: k, v = past_key_values.update(k, v, self.layer_idx) if self.config._attn_implementation == "sdpa": attention_interface: Callable = _sdpa_attention_forward else: attention_interface = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, _eager_attention_forward ) attn_output, attn_weights = attention_interface( self, q, k, v, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) if self.output_gate is not None: attn_output = self.output_gate(attn_output, hidden_states) return attn_output, attn_weights class Q50MMLP(nn.Module): def __init__(self, config: Q50MConfig): super().__init__() self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False) self.output_gate = ( Q50MScalarGate(config.hidden_size, config.gate_multiplier) if config.mlp_scalar_gate else None ) def forward(self, hidden_states): output = self.down_proj(F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states)) if self.output_gate is not None: output = self.output_gate(output, hidden_states) return output class Q50MDecoderLayer(GradientCheckpointingLayer): def __init__(self, config: Q50MConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = Q50MAttention(config, layer_idx) self.mlp = Q50MMLP(config) self.input_layernorm = Q50MRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = Q50MRMSNorm(config.hidden_size, eps=config.rms_norm_eps) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, use_cache: bool | None = False, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs: Unpack[TransformersKwargs], ) -> torch.Tensor: residual = hidden_states hidden_states = self.input_layernorm(hidden_states) 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, position_embeddings=position_embeddings, **kwargs, ) hidden_states = residual + hidden_states 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 class Q50MPreTrainedModel(PreTrainedModel): config_class = Q50MConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Q50MDecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_sdpa = True _supports_flash_attn = False _supports_flex_attn = False class Q50MModel(Q50MPreTrainedModel): def __init__(self, config: Q50MConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [Q50MDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = Q50MRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = Q50MRotaryEmbedding(config=config) self.gradient_checkpointing = False self.post_init() 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.FloatTensor | None = None, use_cache: bool | None = None, rotary_position_ids: torch.LongTensor | None = 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 = self.embed_tokens(input_ids) if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config) standard_positions = position_ids is None 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) # Unpadded, uncached SDPA can use its native causal flag, including # under torch.compile where HF otherwise materializes a dense mask. causal_mask = None if ( attention_mask is None and past_key_values is None and standard_positions and self.config._attn_implementation == "sdpa" ) else create_causal_mask( config=self.config, inputs_embeds=inputs_embeds, attention_mask=attention_mask, past_key_values=past_key_values, position_ids=position_ids, ) hidden_states = inputs_embeds # Slotted Zarya keeps source positions for RoPE but attends causally in # the permuted sequence order. Never let HF infer packed-sequence masks # from those nonmonotonic rotary positions. position_embeddings = self.rotary_emb( hidden_states, position_ids=position_ids if rotary_position_ids is None else rotary_position_ids) for decoder_layer in self.layers[: self.config.num_hidden_layers]: if self.gradient_checkpointing and self.training: hidden_states = self._gradient_checkpointing_func( decoder_layer.forward, hidden_states, causal_mask, position_ids, past_key_values, use_cache, position_embeddings, ) else: hidden_states = decoder_layer( hidden_states, attention_mask=causal_mask, position_embeddings=position_embeddings, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, **kwargs, ) hidden_states = self.norm(hidden_states) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values, ) class Q50MForCausalLM(Q50MPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} def __init__(self, config: Q50MConfig): super().__init__(config) self.model = Q50MModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init() def get_input_embeddings(self): return self.model.embed_tokens def set_input_embeddings(self, value): self.model.embed_tokens = value def get_output_embeddings(self): return self.lm_head 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.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, logits_to_keep: int | torch.Tensor = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: outputs = 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, **kwargs, ) hidden_states = outputs.last_hidden_state 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: shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() loss = F.cross_entropy( shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), ignore_index=-100, ) return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, )