# coding=utf-8 # Copyright 2023 Soket AI and The HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # 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. """PyTorch Eka-V1 model for HF export and inference. Module names mirror Megatron ``MambaModel`` (``embedding``, ``decoder``, ``output_layer``, ``MambaLayer``, ``TransformerLayer``, etc.) under the ``EkaV1Model`` / ``EkaV1ForCausalLM`` wrappers. Weight paths use ``model.decoder.layers..*`` to match Megatron ``decoder.layers..*``. """ import math import os import warnings from typing import List, Optional, Tuple, Union import numpy as np import torch import torch.distributed as dist import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.cache_utils import Cache, DynamicCache # Transformers >=5.10 split the per-layer cache into typed classes; older builds # (e.g. the NeMo 26.02 container) still use the monolithic ``DynamicCache`` with # no ``CacheLayerMixin`` / ``DynamicLayer`` / ``LinearAttentionLayer``. Provide # thin stubs so the rest of this file works on both. try: from transformers.cache_utils import CacheLayerMixin, DynamicLayer, LinearAttentionLayer except ImportError: # --- Minimal stubs for transformers <5.10 --- # CacheLayerMixin: used only in isinstance() checks to tell KV-attention slots # apart from Mamba/MoE slots. The old DynamicCache has no per-layer objects at # all, so nothing will ever be an instance of this stub — which is the correct # answer ("no typed attention layers found → fall through to legacy path"). class CacheLayerMixin: # type: ignore[no-redef] """Stub: transformers <5.10 has no typed cache layers.""" pass class DynamicLayer(CacheLayerMixin): # type: ignore[no-redef] """Stub: growing key/value cache slot (transformers <5.10 fallback).""" def __init__(self): self.keys = None self.values = None def get_seq_length(self) -> int: if self.keys is None: return 0 return self.keys.shape[-2] def update(self, key_states, value_states, *args, **kwargs): import torch if self.keys is None: self.keys = key_states self.values = value_states else: self.keys = torch.cat([self.keys, key_states], dim=-2) self.values = torch.cat([self.values, value_states], dim=-2) return self.keys, self.values def reorder_cache(self, beam_idx): if self.keys is not None: device = self.keys.device self.keys = self.keys.index_select(0, beam_idx.to(device)) self.values = self.values.index_select(0, beam_idx.to(device)) def reset(self): self.keys = None self.values = None def crop(self, max_length: int) -> None: """Truncate cached KV to ``max_length`` tokens (negative = drop that many).""" if self.keys is None: return if max_length < 0: max_length = self.get_seq_length() - abs(max_length) if max_length <= 0: self.reset() return if self.get_seq_length() <= max_length: return self.keys = self.keys[..., :max_length, :].contiguous() self.values = self.values[..., :max_length, :].contiguous() class _LinearAttentionCacheStub: """Stub: Mamba conv-window + SSM state slot (transformers <5.10 fallback).""" def __init__(self): self.conv_states = None self.recurrent_states = None self.has_previous_state = False self._is_conv_init = False self._is_rec_init = False def get_seq_length(self, layer_idx=0): return 0 def get_max_cache_shape(self): return None @property def is_compileable(self): return False @property def is_sliding(self): return False def update_conv_state(self, conv_states, **kwargs): import torch if not self._is_conv_init: self.conv_states = torch.zeros_like(conv_states) self._is_conv_init = True if not self.has_previous_state: self.conv_states.copy_(conv_states) self.has_previous_state = True else: n = conv_states.shape[-1] k = self.conv_states.shape[-1] if n >= k: self.conv_states.copy_(conv_states[..., -k:]) else: new = self.conv_states.roll(shifts=-n, dims=-1) new[..., -n:] = conv_states self.conv_states.copy_(new) return self.conv_states def update_recurrent_state(self, recurrent_states, **kwargs): import torch if not self._is_rec_init: self.recurrent_states = torch.zeros_like(recurrent_states) self._is_rec_init = True self.recurrent_states.copy_(recurrent_states) return self.recurrent_states def reorder_cache(self, beam_idx): if self._is_conv_init and self.conv_states is not None: self.conv_states = self.conv_states.index_select(0, beam_idx.to(self.conv_states.device)) if self._is_rec_init and self.recurrent_states is not None: self.recurrent_states = self.recurrent_states.index_select(0, beam_idx.to(self.recurrent_states.device)) def reset(self): if self._is_conv_init and self.conv_states is not None: self.conv_states.zero_() if self._is_rec_init and self.recurrent_states is not None: self.recurrent_states.zero_() self.has_previous_state = False LinearAttentionLayer = _LinearAttentionCacheStub # type: ignore[misc,assignment] from transformers.generation import GenerationMixin from transformers.modeling_attn_mask_utils import ( AttentionMaskConverter, _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask, ) from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast, ) from transformers.modeling_utils import PreTrainedModel from transformers.pytorch_utils import ( ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13, ) from transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10, logging, replace_return_docstrings, ) try: from transformers.utils.import_utils import is_torch_fx_available except ImportError: def is_torch_fx_available() -> bool: return False from .configuration_eka import EkaV1Config if is_flash_attn_2_available(): from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa try: from causal_conv1d import causal_conv1d_fn, causal_conv1d_update except ImportError: causal_conv1d_fn = None causal_conv1d_update = None try: from mamba_ssm.ops.triton.selective_state_update import selective_state_update except ImportError: selective_state_update = None try: from mamba_ssm.ops.triton.ssd_combined import ( mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined, ) except ImportError: mamba_chunk_scan_combined = None mamba_split_conv1d_scan_combined = None # Megatron ``ExtendedRMSNorm`` subclasses this Triton op when mamba_ssm is present. try: from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn as _mamba_rmsnorm_fn except ImportError: _mamba_rmsnorm_fn = None # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph. # It means that the function will not be traced through and simply appear as a node in the graph. if is_torch_fx_available(): if not is_torch_greater_or_equal_than_1_13: import torch.fx _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask) logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "EkaV1Config" def _attention_layer_indices(past_key_values: Cache) -> List[int]: """Indices of the KV-holding slots of a hybrid cache (Mamba/MoE slots hold no KV).""" layers = getattr(past_key_values, "layers", None) or [] return [idx for idx, layer in enumerate(layers) if isinstance(layer, CacheLayerMixin)] def _cache_seq_length(past_key_values: Optional[Cache], layer_idx: Optional[int] = None) -> int: """Cached attention length, tolerant of the hybrid (Mamba + MLA) cache layout. Mamba and MoE slots are ``LinearAttentionLayer``s that track no sequence length, so ``Cache.get_seq_length`` raises when handed their index. Resolve to a real attention slot instead, and report 0 for a cache that holds no attention slot at all. """ if past_key_values is None: return 0 attention_indices = _attention_layer_indices(past_key_values) if attention_indices: if layer_idx is None or layer_idx not in attention_indices: layer_idx = attention_indices[0] elif getattr(past_key_values, "layers", None): # Mamba-only stack: nothing tracks a KV length. return 0 else: # Lazily-built cache with no layers yet. return 0 return past_key_values.get_seq_length(layer_idx) def _eka_cache_slot_is_stateful_attention(config: EkaV1Config, layer_idx: int) -> bool: """Whether the decoder layer at ``layer_idx`` stores growing key/value tensors.""" return _resolve_hybrid_layer_kind(config, layer_idx) not in ("mamba", "moe_only") def build_eka_cache(config: EkaV1Config) -> Cache: """Build a cache with one slot per decoder layer, matching the hybrid pattern. MLA slots get a growing-KV ``DynamicLayer``; Mamba slots get a ``LinearAttentionLayer`` that holds the conv window plus the SSM recurrent state. MoE-only slots are stateless but still get a placeholder so that the ``layer_idx`` each layer passes to ``Cache.update*`` stays aligned with the decoder stack. Built from ``_resolve_hybrid_layer_kind`` (the same resolver ``_build_decoder_layer`` uses) rather than from ``config.layer_types``, so the cache layout cannot drift from the module layout. """ layers = [ DynamicLayer() if _eka_cache_slot_is_stateful_attention(config, layer_idx) else LinearAttentionLayer() for layer_idx in range(config.num_hidden_layers) ] # Transformers >=5.10 ``Cache(layers=...)`` vs older ``DynamicCache()`` that has no # typed-layer constructor. Fall back to monkey-patching ``.layers`` on a DynamicCache. try: cache = Cache(layers=layers) except TypeError: cache = DynamicCache() cache.layers = layers # Older DynamicCache lacks the Mamba-state delegation methods that # ``MambaMixer`` calls through the cache object. Wire them up here. def _update_conv_state(conv_states, layer_idx, **kw): return cache.layers[layer_idx].update_conv_state(conv_states, **kw) def _update_recurrent_state(recurrent_states, layer_idx, **kw): return cache.layers[layer_idx].update_recurrent_state(recurrent_states, **kw) def _has_previous_state(layer_idx): if layer_idx >= len(cache.layers): return False layer = cache.layers[layer_idx] return getattr(layer, "has_previous_state", False) def _get_seq_length(layer_idx=0): # Walk to the first KV-holding slot. for i, layer in enumerate(cache.layers): if isinstance(layer, DynamicLayer) and hasattr(layer, "get_seq_length"): if layer_idx == 0 or i == layer_idx: return layer.get_seq_length() return 0 def _update(key_states, value_states, layer_idx, *args, **kw): while len(cache.layers) <= layer_idx: cache.layers.append(DynamicLayer()) return cache.layers[layer_idx].update(key_states, value_states, *args, **kw) def _reorder(beam_idx): for layer in cache.layers: if hasattr(layer, "reorder_cache"): layer.reorder_cache(beam_idx) cache.update = _update cache.update_conv_state = _update_conv_state cache.update_recurrent_state = _update_recurrent_state cache.has_previous_state = _has_previous_state cache.get_seq_length = _get_seq_length cache.reorder_cache = _reorder return cache def _mtp_num_layers_from_config(config: EkaV1Config) -> int: return int( getattr(config, "mtp_num_layers", None) or getattr(config, "num_nextn_predict_layers", 0) or 0 ) def build_mtp_cache(config: EkaV1Config) -> Cache: """KV cache for MTP transformer depths only (all ``DynamicLayer`` slots). Kept separate from the hybrid trunk cache so MTP ``layer_idx`` values stay in ``0 .. mtp_num_layers-1`` and rejection can rewind MTP state without touching Mamba. """ num_layers = _mtp_num_layers_from_config(config) if num_layers <= 0: raise ValueError("build_mtp_cache requires mtp_num_layers > 0") layers = [DynamicLayer() for _ in range(num_layers)] try: return Cache(layers=layers) except TypeError: cache = DynamicCache() cache.layers = layers def _update(key_states, value_states, layer_idx, *args, **kw): while len(cache.layers) <= layer_idx: cache.layers.append(DynamicLayer()) return cache.layers[layer_idx].update(key_states, value_states, *args, **kw) def _get_seq_length(layer_idx=0): if layer_idx < len(cache.layers) and hasattr(cache.layers[layer_idx], "get_seq_length"): return cache.layers[layer_idx].get_seq_length() return 0 cache.update = _update cache.get_seq_length = _get_seq_length return cache def _mtp_cache_lengths(mtp_cache: Optional[Cache]) -> List[int]: if mtp_cache is None or not getattr(mtp_cache, "layers", None): return [] lengths = [] for layer in mtp_cache.layers: if hasattr(layer, "get_seq_length"): lengths.append(int(layer.get_seq_length())) elif getattr(layer, "keys", None) is not None: lengths.append(int(layer.keys.shape[-2])) else: lengths.append(0) return lengths def _rewind_mtp_cache(mtp_cache: Cache, target_lengths: List[int]) -> None: """Crop each MTP slot back to ``target_lengths[i]`` after a rejected draft suffix. Note: transformers ``DynamicLayer.reset()`` only zero-fills tensors and keeps the sequence length, so rejection must use ``crop`` (or an explicit empty slice). """ for layer_idx, target in enumerate(target_lengths): if layer_idx >= len(mtp_cache.layers): break layer = mtp_cache.layers[layer_idx] cur = ( int(layer.get_seq_length()) if hasattr(layer, "get_seq_length") else (0 if getattr(layer, "keys", None) is None else int(layer.keys.shape[-2])) ) target = max(0, int(target)) if target >= cur: continue if hasattr(layer, "crop"): layer.crop(target) elif target == 0: layer.keys = None layer.values = None else: layer.keys = layer.keys[..., :target, :].contiguous() layer.values = layer.values[..., :target, :].contiguous() def _get_unpad_data(attention_mask): seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = F.pad( torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0) ) return ( indices, cu_seqlens, max_seqlen_in_batch, ) def _eka_prepare_attention_mask( config: EkaV1Config, attention_mask: Optional[torch.Tensor], batch_size: int, seq_length: int, hidden_states: torch.Tensor, past_key_values_length: int = 0, ) -> Optional[torch.Tensor]: """Match ``EkaV1Model`` mask handling for MTP inner blocks.""" if config._attn_implementation == "flash_attention_2": if attention_mask is not None and 0 in attention_mask: return attention_mask return None return _prepare_4d_causal_attention_mask( attention_mask, (batch_size, seq_length), hidden_states, past_key_values_length, ) class RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Megatron ``RMSNorm`` (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) # Match Megatron/TE: scale in fp32, then cast (bf16 weight*bf16-cast loses ULP). return (self.weight.float() * hidden_states).to(input_dtype) ALL_LAYERNORM_LAYERS.append(RMSNorm) class IdentityOp(nn.Module): """Megatron no-op submodule (e.g. unused cross-attn on decoder layers).""" def forward(self, hidden_states, *args, **kwargs): if args or kwargs: return hidden_states, None, None return hidden_states class LanguageModelEmbedding(nn.Module): """Megatron ``LanguageModelEmbedding`` (``word_embeddings`` + dropout).""" def __init__(self, config: EkaV1Config): super().__init__() self.word_embeddings = nn.Embedding( config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id ) dropout_p = getattr(config, "hidden_dropout", 0.0) or 0.0 self.embedding_dropout = nn.Dropout(p=dropout_p) def forward(self, input_ids: torch.LongTensor) -> torch.Tensor: return self.embedding_dropout(self.word_embeddings(input_ids)) def _eka_debug_mlp_enabled() -> bool: """Step-level MoE/MLP I/O dumps when ``EKA_DEBUG_MLP=1`` (parity / diagnosis).""" return os.environ.get("EKA_DEBUG_MLP", "").strip().lower() in ("1", "true", "yes") def _eka_debug_mlp_max_experts() -> int: try: return max(0, int(os.environ.get("EKA_DEBUG_MLP_MAX_EXPERTS", "4"))) except ValueError: return 4 def _eka_log_tensor(tag: str, t: Optional[torch.Tensor], extra: str = "") -> None: """Compact tensor stats for MoE/MLP parity debugging (rank-0 only if distributed).""" if not _eka_debug_mlp_enabled(): return if dist.is_available() and dist.is_initialized() and dist.get_rank() != 0: return if t is None: print(f"[eka-mlp-debug] {tag}: None {extra}", flush=True) return with torch.no_grad(): flat = t.detach().float().reshape(-1) n = min(8, flat.numel()) sample = flat[:n].tolist() if n else [] msg = ( f"[eka-mlp-debug] {tag}: shape={tuple(t.shape)} dtype={t.dtype} " f"mean={flat.mean().item():.6g} absmax={flat.abs().max().item():.6g} " f"sample={sample}" ) if extra: msg = f"{msg} {extra}" print(msg, flush=True) class EkaQuantLinear(nn.Module): """Weight-only INT8 / INT4 linear used by the quantized EKA-1 checkpoints. Weights are stored packed (``weight_q``) with per-row (INT8) or per-group (INT4, symmetric, group_size) scales in ``weight_scale`` and are dequantized lazily on first use (weights are static at inference). Enabled by ``config.quantization_config = {"quant_method": "eka-quant"}``. """ def __init__(self, in_features, out_features, bias=False, bits=8, group_size=64): super().__init__() self.in_features = in_features self.out_features = out_features self.bits = bits self.group_size = group_size if bits == 8: self.register_buffer( "weight_q", torch.empty(out_features, in_features, dtype=torch.int8) ) self.register_buffer( "weight_scale", torch.empty(out_features, 1, dtype=torch.bfloat16) ) elif bits == 4: if in_features % group_size: raise ValueError(f"in_features={in_features} not divisible by {group_size}") self.register_buffer( "weight_q", torch.empty(out_features, in_features // 2, dtype=torch.uint8) ) self.register_buffer( "weight_scale", torch.empty(out_features, in_features // group_size, dtype=torch.bfloat16), ) else: raise ValueError(f"unsupported bits={bits}") self.bias = nn.Parameter(torch.zeros(out_features)) if bias else None self._deq_cache = None def dequantize(self): if self.bits == 8: w = self.weight_q.to(torch.float32) * self.weight_scale.to(torch.float32) return w.to(torch.bfloat16) q = self.weight_q lo = (q & 0x0F).to(torch.float32) - 8.0 hi = (q >> 4).to(torch.float32) - 8.0 w = torch.stack((lo, hi), dim=-1).reshape(q.shape[0], -1) w = w.view(q.shape[0], -1, self.group_size) w = w * self.weight_scale.to(torch.float32).unsqueeze(-1) return w.reshape(q.shape[0], -1).to(torch.bfloat16) def forward(self, x): w = self._deq_cache if w is None or w.device != x.device: w = self.dequantize().to(x.device) self._deq_cache = w return F.linear(x, w.to(x.dtype), self.bias) def _eka_quant_skip(name: str) -> bool: return ( name.endswith(".gate") or name == "gate" or "output_layer" in name or "lm_head" in name or "embedding" in name ) @torch.no_grad() def _eka_make_quant_linear(lin: nn.Linear, bits: int, group_size: int) -> EkaQuantLinear: w = lin.weight.detach().float() out_f, in_f = w.shape q = EkaQuantLinear(in_f, out_f, lin.bias is not None, bits, group_size).to(w.device) if bits == 8: scale = (w.abs().amax(dim=1, keepdim=True).clamp_min(1e-8) / 127.0).to(torch.float32) q.weight_q.copy_(torch.round(w / scale).clamp_(-127, 127).to(torch.int8)) q.weight_scale.copy_(scale.to(torch.bfloat16)) else: g = in_f // group_size wr = w.view(out_f, g, group_size) scale = wr.abs().amax(dim=-1, keepdim=True).clamp_min(1e-8) / 7.0 qq = (torch.round(wr / scale).clamp_(-8, 7).to(torch.int8) + 8).to(torch.uint8) qq = qq.view(out_f, in_f) q.weight_q.copy_((qq[:, 0::2] | (qq[:, 1::2] << 4)).to(torch.uint8)) q.weight_scale.copy_(scale.squeeze(-1).to(torch.bfloat16)) if lin.bias is not None: q.bias.copy_(lin.bias.data) return q @torch.no_grad() def replace_linear_with_quant(module: nn.Module, bits: int, group_size: int = 64, _prefix: str = ""): """Replace every eligible nn.Linear with an EkaQuantLinear (quantizing its weight).""" for name, child in list(module.named_children()): full = f"{_prefix}.{name}" if _prefix else name if isinstance(child, nn.Linear): if _eka_quant_skip(full): continue if child.weight.shape[1] % group_size and bits == 4: continue setattr(module, name, _eka_make_quant_linear(child, bits, group_size)) else: replace_linear_with_quant(child, bits, group_size, full) class LinearFC1(nn.Module): """Megatron gated ``linear_fc1`` (SiLU-gate × up). Checkpoint keeps split ``gate_proj`` / ``up_proj`` (export from fused Megatron ``linear_fc1`` / TE GroupedGEMM). Forward concatenates weights into **one** GEMM then ``silu(gate)*up`` — same algebra as Megatron ``bias_swiglu`` / ``weighted_bias_swiglu`` (job 315506: two separate GEMMs were bit-identical on that input, but the fused path is the Megatron-aligned default). """ def __init__(self, in_features: int, out_features: int, bias: bool = False): super().__init__() self.gate_proj = nn.Linear(in_features, out_features, bias=bias) self.up_proj = nn.Linear(in_features, out_features, bias=bias) def forward(self, x: torch.Tensor, act_fn) -> torch.Tensor: _eka_log_tensor("LinearFC1.in", x) if isinstance(self.gate_proj, EkaQuantLinear): # Quantized path: two projections, concatenated outputs. gate_up = torch.cat([self.gate_proj(x), self.up_proj(x)], dim=-1) else: # Fused fc1 = cat(gate, up) — mirrors Megatron chunk(linear_fc1(x), 2). weight = torch.cat( [self.gate_proj.weight, self.up_proj.weight], dim=0 ).contiguous() bias = None if self.gate_proj.bias is not None or self.up_proj.bias is not None: bias = torch.cat( [ self.gate_proj.bias if self.gate_proj.bias is not None else x.new_zeros(self.gate_proj.out_features), self.up_proj.bias if self.up_proj.bias is not None else x.new_zeros(self.up_proj.out_features), ], dim=0, ) gate_up = F.linear(x, weight, bias) gate, up = gate_up.chunk(2, dim=-1) _eka_log_tensor("LinearFC1.gate", gate) _eka_log_tensor("LinearFC1.up", up) out = act_fn(gate) * up _eka_log_tensor("LinearFC1.out(swiglu_fused)", out) if _eka_debug_mlp_enabled(): # Optional: quantify vs two separate GEMMs (does not change return). gate2 = self.gate_proj(x) up2 = self.up_proj(x) out_two = act_fn(gate2) * up2 diff = (out.float() - out_two.float()).abs() _eka_log_tensor("LinearFC1.out(swiglu_two_gemm)", out_two) _eka_log_tensor( "LinearFC1.diff(fused_vs_two_gemm)", diff, extra=f"rel={(diff.mean() / (out.float().abs().mean() + 1e-8)).item():.6g}", ) return out class RotaryEmbedding(nn.Module): def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): super().__init__() self.dim = dim self.max_position_embeddings = max_position_embeddings self.base = base inv_freq = 1.0 / ( self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim) ) self.register_buffer("inv_freq", inv_freq, persistent=False) # Build here to make `torch.jit.trace` work. self._set_cos_sin_cache( seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype(), ) self.max_seq_len_cached = None def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange( self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype ) freqs = torch.outer(t, self.inv_freq.to(t.device)) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) def forward(self, x, seq_len=None): # x: [bs, num_attention_heads, seq_len, head_size] if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached: self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) return ( self.cos_cached[:seq_len].to(dtype=x.dtype), self.sin_cached[:seq_len].to(dtype=x.dtype), ) # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Eka-v1 class LinearScalingRotaryEmbedding(RotaryEmbedding): """RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev""" def __init__( self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, ): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange( self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype ) t = t / self.scaling_factor freqs = torch.outer(t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) class DynamicNTKScalingRotaryEmbedding(RotaryEmbedding): """RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla""" def __init__( self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, ): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len if seq_len > self.max_position_embeddings: base = self.base * ( (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1) ) ** (self.dim / (self.dim - 2)) inv_freq = 1.0 / ( base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim) ) self.register_buffer("inv_freq", inv_freq, persistent=False) t = torch.arange( self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype ) freqs = torch.outer(t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) # Inverse dim formula to find dim based on number of rotations def yarn_find_correction_dim( num_rotations, dim, base=10000, max_position_embeddings=2048 ): return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / ( 2 * math.log(base) ) # Find dim range bounds based on rotations def yarn_find_correction_range( low_rot, high_rot, dim, base=10000, max_position_embeddings=2048 ): low = math.floor( yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings) ) high = math.ceil( yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings) ) return max(low, 0), min(high, dim - 1) # Clamp values just in case def yarn_get_mscale(scale=1, mscale=1): if scale <= 1: return 1.0 return 0.1 * mscale * math.log(scale) + 1.0 def yarn_linear_ramp_mask(min, max, dim): if min == max: max += 0.001 # Prevent singularity linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min) ramp_func = torch.clamp(linear_func, 0, 1) return ramp_func class YarnRotaryEmbedding(RotaryEmbedding): def __init__( self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, original_max_position_embeddings=4096, beta_fast=32, beta_slow=1, mscale=1, mscale_all_dim=0, ): self.scaling_factor = scaling_factor self.original_max_position_embeddings = original_max_position_embeddings self.beta_fast = beta_fast self.beta_slow = beta_slow self.mscale = mscale self.mscale_all_dim = mscale_all_dim super().__init__(dim, max_position_embeddings, base, device) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len dim = self.dim freq_extra = 1.0 / ( self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim) ) freq_inter = 1.0 / ( self.scaling_factor * self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim) ) low, high = yarn_find_correction_range( self.beta_fast, self.beta_slow, dim, self.base, self.original_max_position_embeddings, ) inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to( device=device, dtype=torch.float32 ) inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask self.register_buffer("inv_freq", inv_freq, persistent=False) t = torch.arange(seq_len, device=device, dtype=torch.float32) freqs = torch.outer(t, inv_freq) _mscale = float( yarn_get_mscale(self.scaling_factor, self.mscale) / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim) ) emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer( "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False ) self.register_buffer( "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False ) # Copied from transformers.models.llama.modeling_llama.rotate_half 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) # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb def apply_rotary_pos_emb( q, k, cos, sin, position_ids, unsqueeze_dim=1, rotary_interleaved: bool = False, multi_latent_attention: bool = False, ): """Applies Rotary Position Embedding to the query and key tensors. Megatron Eka-V1 uses ``rotary_interleaved=False`` (see ``run_config.yaml``). For MLA, Megatron ``rope_utils._apply_rotary_pos_emb_bshd`` first rearranges even/odd elements into contiguous halves before ``rotate_half`` — set ``multi_latent_attention=True`` to match that path. """ cos = cos[position_ids].unsqueeze(unsqueeze_dim) sin = sin[position_ids].unsqueeze(unsqueeze_dim) if multi_latent_attention: # Megatron MLA: [e0, o0, e1, o1, ...] -> [e0, e1, ..., o0, o1, ...] def _mla_even_odd_to_halves(x: torch.Tensor) -> torch.Tensor: x1 = x[..., 0::2] x2 = x[..., 1::2] return torch.cat((x1, x2), dim=-1) q = _mla_even_odd_to_halves(q) k = _mla_even_odd_to_halves(k) elif rotary_interleaved: b, h, s, d = q.shape q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d) b, h, s, d = k.shape k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed class MLP(nn.Module): """Dense MLP block (Megatron ``mlp.linear_fc1`` / ``linear_fc2``).""" 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.act_fn = ACT2FN[config.hidden_act] self.linear_fc1 = LinearFC1(self.hidden_size, self.intermediate_size, bias=False) self.linear_fc2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) def forward(self, x, token_probs: Optional[torch.Tensor] = None): # Megatron ``weighted_swiglu``: swiglu(fc1(x)) * probs, then cast back to x.dtype # before fc2 (``bias_activation_fusion`` path in TEGroupedMLP). _eka_log_tensor("MLP.in", x) _eka_log_tensor("MLP.token_probs", token_probs) h = self.linear_fc1(x, self.act_fn) _eka_log_tensor("MLP.after_fc1_swiglu", h) if token_probs is not None: dtype = h.dtype # Router probs stay fp32 when moe_router_dtype=fp32; multiply promotes then cast. # Match TE weighted_swiglu: scale in higher precision, return activation dtype. h = (h.float() * token_probs.unsqueeze(-1).float()).to(dtype) _eka_log_tensor("MLP.after_weighted_swiglu", h) out = self.linear_fc2(h) _eka_log_tensor("MLP.out", out) return out class SharedExpertMLP(MLP): """Megatron ``SharedExpertMLP`` (wider intermediate for shared experts). Uses the same fused ``LinearFC1`` + SwiGLU path as routed experts / TE; shared experts are never router-weighted. """ def forward(self, x, token_probs: Optional[torch.Tensor] = None): if token_probs is not None: # Shared experts are never router-weighted in Megatron. raise ValueError("SharedExpertMLP does not take token_probs") _eka_log_tensor("SharedExpertMLP.in", x) out = super().forward(x, token_probs=None) _eka_log_tensor("SharedExpertMLP.out", out) return out class TopKRouter(nn.Module): def __init__(self, config): 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.scoring_func = config.scoring_func self.topk_method = config.topk_method self.n_group = config.n_group self.topk_group = config.topk_group # topk selection algorithm self.norm_topk_prob = config.norm_topk_prob self.gating_dim = config.hidden_size self.weight = nn.Parameter( torch.empty((self.n_routed_experts, self.gating_dim)) ) # Megatron keeps expert_bias in float32; bf16 (ULP~0.25 near 38) collapses # per-expert deltas and completely changes top-k routing. if self.topk_method == "noaux_tc": self.register_buffer( "e_score_correction_bias", torch.zeros(self.n_routed_experts, dtype=torch.float32), ) self.reset_parameters() @property def expert_bias(self): return self.e_score_correction_bias def _maintain_float32_expert_bias(self) -> None: """Keep routing bias in float32 after dtype casts (matches Megatron).""" if ( hasattr(self, "e_score_correction_bias") and self.e_score_correction_bias is not None and self.e_score_correction_bias.dtype != torch.float32 ): self.e_score_correction_bias.data = self.e_score_correction_bias.data.to( torch.float32 ) def reset_parameters(self) -> None: import torch.nn.init as init init.kaiming_uniform_(self.weight, a=math.sqrt(5)) def forward(self, hidden_states): bsz, seq_len, h = hidden_states.shape self._maintain_float32_expert_bias() ### compute gating score hidden_states = hidden_states.view(-1, h) logits = F.linear( hidden_states.type(torch.float32), self.weight.type(torch.float32), None ) if self.scoring_func == "sigmoid": # Megatron: sigmoid in fp32 then type_as(logits); with moe_router_dtype=fp32 # logits stay fp32 so scores remain fp32 through gather/normalize. scores = torch.sigmoid(logits) else: raise NotImplementedError( f"insupportable scoring function for MoE gating: {self.scoring_func}" ) ### select top-k experts if self.topk_method == "noaux_tc": assert not self.training # Bias is selection-only (Megatron sigmoid path); keep fp32 for ranking. scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.to( dtype=torch.float32 ).unsqueeze(0) # Match Megatron group_limited_topk: topk(topk // group_topk) per group. group_inner_k = max(self.top_k // max(self.topk_group, 1), 1) group_scores = ( scores_for_choice.view(bsz * seq_len, self.n_group, -1) .topk(group_inner_k, dim=-1)[0] .sum(dim=-1) ) # [n, n_group] # Megatron ``torch.topk`` defaults to sorted=True — same order for bf16 sum. group_idx = torch.topk( group_scores, k=self.topk_group, dim=-1, sorted=True )[1] # [n, top_k_group] group_mask = torch.zeros_like(group_scores) # [n, n_group] group_mask.scatter_(1, group_idx, 1) # [n, n_group] score_mask = ( group_mask.unsqueeze(-1) .expand( bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group ) .reshape(bsz * seq_len, -1) ) # [n, e] tmp_scores = scores_for_choice.masked_fill( ~score_mask.bool(), float("-inf") ) # [n, e] _, topk_idx = torch.topk(tmp_scores, k=self.top_k, dim=-1, sorted=True) topk_weight = scores.gather(1, topk_idx) else: raise NotImplementedError( f"insupportable TopK function for MoE gating: {self.topk_method}" ) ### norm gate to sum 1 if self.top_k > 1 and self.norm_topk_prob: denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20 topk_weight = topk_weight / denominator topk_weight = ( topk_weight * self.routed_scaling_factor ) # must multiply the scaling factor if _eka_debug_mlp_enabled(): _eka_log_tensor("TopKRouter.logits", logits) _eka_log_tensor("TopKRouter.scores", scores) _eka_log_tensor("TopKRouter.topk_idx", topk_idx) _eka_log_tensor("TopKRouter.topk_weight", topk_weight) if dist.is_available() and dist.is_initialized() and dist.get_rank() != 0: pass else: print( f"[eka-mlp-debug] TopKRouter.topk_idx[0]={topk_idx[0].tolist()} " f"topk_weight[0]={topk_weight[0].detach().float().tolist()}", flush=True, ) return topk_idx, topk_weight class MoELayer(nn.Module): """Megatron ``MoELayer`` (router + latent proj + experts + shared experts).""" def __init__(self, config): super().__init__() self.config = config self.num_experts_per_tok = config.num_experts_per_tok self.moe_latent_size = getattr(config, "moe_latent_size", None) if self.moe_latent_size: self.fc1_latent_proj = nn.Linear(config.hidden_size, self.moe_latent_size, bias=False) self.fc2_latent_proj = nn.Linear(self.moe_latent_size, config.hidden_size, bias=False) # Megatron ``TENorm`` on latent dim (pre-dispatch / pre-up-proj). self.fc1_latent_norm = RMSNorm(self.moe_latent_size, eps=config.rms_norm_eps) self.fc2_latent_norm = RMSNorm(self.moe_latent_size, eps=config.rms_norm_eps) expert_hidden = self.moe_latent_size else: expert_hidden = config.hidden_size if hasattr(config, "ep_size") and config.ep_size > 1: assert config.ep_size == dist.get_world_size() self.ep_size = config.ep_size self.experts_per_rank = config.n_routed_experts // config.ep_size self.ep_rank = dist.get_rank() self.experts = nn.ModuleList( [ ( MLP( config, hidden_size=expert_hidden, intermediate_size=config.moe_intermediate_size, ) if i >= self.ep_rank * self.experts_per_rank and i < (self.ep_rank + 1) * self.experts_per_rank else None ) for i in range(config.n_routed_experts) ] ) else: self.ep_size = 1 self.experts_per_rank = config.n_routed_experts self.ep_rank = 0 self.experts = nn.ModuleList( [ MLP( config, hidden_size=expert_hidden, intermediate_size=config.moe_intermediate_size, ) for i in range(config.n_routed_experts) ] ) self.router = TopKRouter(config) if config.n_shared_experts is not None: intermediate_size = config.moe_intermediate_size * config.n_shared_experts self.shared_experts = SharedExpertMLP( config=config, intermediate_size=intermediate_size ) def forward(self, hidden_states): identity = hidden_states orig_shape = hidden_states.shape out_dtype = hidden_states.dtype _eka_log_tensor("MoELayer.in", hidden_states) topk_idx, topk_weight = self.router(hidden_states) routed = hidden_states if self.moe_latent_size: routed = self.fc1_latent_proj(routed) _eka_log_tensor("MoELayer.after_fc1_latent_proj", routed) routed = self.fc1_latent_norm(routed) _eka_log_tensor("MoELayer.after_fc1_latent_norm", routed) hidden_states = routed.view(-1, routed.shape[-1]) y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape[:-1], -1) _eka_log_tensor("MoELayer.after_routed_experts", y) if self.moe_latent_size: y = self.fc2_latent_norm(y) _eka_log_tensor("MoELayer.after_fc2_latent_norm", y) y = self.fc2_latent_proj(y) _eka_log_tensor("MoELayer.after_fc2_latent_proj", y) if self.config.n_shared_experts is not None: # Megatron postprocess: add shared expert on the pre-latent identity. # fp32 add reduces bf16 ULP noise when combining large routed + shared outs. shared = self.shared_experts(identity) _eka_log_tensor("MoELayer.shared_experts_out", shared) y = (y.float() + shared.float()).to(out_dtype) _eka_log_tensor("MoELayer.out", y) return y @torch.no_grad() def moe_infer(self, x, topk_ids, topk_weight): """Permute tokens by expert id, run experts, unpermute and sum top-k slots. Matches the HF path that best tracked Megatron EP=8 TEGroupedMLP on full ``MoETransformerLayer`` parity (job 315452: max_abs=8, mean_abs≈0.97). Router probs are applied inside each expert before fc2 (``weighted_swiglu``). """ _eka_log_tensor("moe_infer.in", x) cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts))) cnts.scatter_(1, topk_ids, 1) tokens_per_expert = cnts.sum(dim=0) idxs = topk_ids.view(-1).argsort() sorted_tokens = x[idxs // topk_ids.shape[1]] permuted_probs = topk_weight.view(-1)[idxs] sorted_tokens_shape = sorted_tokens.shape _eka_log_tensor("moe_infer.sorted_tokens", sorted_tokens) _eka_log_tensor("moe_infer.permuted_probs", permuted_probs) if _eka_debug_mlp_enabled() and ( not dist.is_available() or not dist.is_initialized() or dist.get_rank() == 0 ): nz = (tokens_per_expert > 0).nonzero(as_tuple=False).view(-1)[:16].tolist() print( f"[eka-mlp-debug] moe_infer.tokens_per_expert nonzero[:16]={nz} " f"counts={[int(tokens_per_expert[i]) for i in nz]}", flush=True, ) if self.ep_size > 1: tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1) tokens_per_expert_group = tokens_per_expert.new_empty( tokens_per_expert.shape[0] ) dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert) output_splits = ( tokens_per_expert_group.view(self.ep_size, -1) .sum(1) .cpu() .numpy() .tolist() ) gathered_tokens = sorted_tokens.new_empty( int(tokens_per_expert_group.sum().item()), sorted_tokens.shape[1] ) input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist() dist.all_to_all( list(gathered_tokens.split(output_splits)), list(sorted_tokens.split(input_split_sizes)), ) tokens_per_expert_post_gather = tokens_per_expert_group.view( self.ep_size, self.experts_per_rank ).sum(dim=0) gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32) s = 0 for i, k in enumerate(tokens_per_expert_group.cpu().numpy()): gatherd_idxs[s : s + k] = i % self.experts_per_rank s += k gatherd_idxs = gatherd_idxs.argsort() sorted_tokens = gathered_tokens[gatherd_idxs] permuted_probs = permuted_probs[gatherd_idxs] tokens_per_expert = tokens_per_expert_post_gather _eka_log_tensor("moe_infer.after_ep_gather.sorted_tokens", sorted_tokens) tokens_per_expert_list = tokens_per_expert.cpu().tolist() outputs = [] start_idx = 0 logged_experts = 0 max_experts_log = _eka_debug_mlp_max_experts() for i, num_tok in enumerate(tokens_per_expert_list): num_tok = int(num_tok) end_idx = start_idx + num_tok if num_tok == 0: continue expert_id = i + self.ep_rank * self.experts_per_rank expert = self.experts[expert_id] if logged_experts < max_experts_log: _eka_log_tensor( f"moe_infer.expert[{expert_id}].in", sorted_tokens[start_idx:end_idx], extra=f"n_tok={num_tok}", ) _eka_log_tensor( f"moe_infer.expert[{expert_id}].probs", permuted_probs[start_idx:end_idx], ) expert_out = expert( sorted_tokens[start_idx:end_idx], token_probs=permuted_probs[start_idx:end_idx], ) if logged_experts < max_experts_log: _eka_log_tensor(f"moe_infer.expert[{expert_id}].out", expert_out) logged_experts += 1 outputs.append(expert_out) start_idx = end_idx outs = ( torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0, x.shape[-1]) ) _eka_log_tensor("moe_infer.cat_expert_outs", outs) if self.ep_size > 1: new_x = torch.empty_like(outs) new_x[gatherd_idxs] = outs gathered_tokens = new_x.new_empty(*sorted_tokens_shape) dist.all_to_all( list(gathered_tokens.split(input_split_sizes)), list(new_x.split(output_splits)), ) outs = gathered_tokens new_x = torch.empty_like(outs) new_x[idxs] = outs # Probs already applied inside experts; sum the top-k slots. # fp32 reduce matches numerical stability of combining many large expert outs # (Megatron TEGroupedMLP combine) better than summing in bf16 alone. final_out = new_x.view(*topk_ids.shape, -1).float().sum(dim=1).to(x.dtype) _eka_log_tensor("moe_infer.out", final_out) return final_out def _vrs_subtract_projection(y: torch.Tensor, v: torch.Tensor) -> torch.Tensor: """Value Residual Subtraction: z = y - proj_v(y), orthogonalizing attn output to value.""" dot = (y * v).sum(dim=-1, keepdim=True) v_sq = (v * v).sum(dim=-1, keepdim=True).clamp(min=1e-8) return y - (dot / v_sq) * v def _maybe_apply_vrs( config: EkaV1Config, attn_output: torch.Tensor, value_states: torch.Tensor, v_head_dim: int, ) -> torch.Tensor: """Optional VRS; no-op when ``value_residual_subtraction`` is False (default / MLASelfAttention).""" if not getattr(config, "value_residual_subtraction", False): return attn_output y = attn_output[..., :v_head_dim] v = value_states[..., :v_head_dim] if y.shape != v.shape: # Match Megatron: trim value along the sequence axis if lengths differ (decode edge cases). for dim in range(y.dim()): if y.shape[dim] != v.shape[dim]: min_len = min(y.shape[dim], v.shape[dim]) y = y.narrow(dim, 0, min_len) v = v.narrow(dim, 0, min_len) break z = _vrs_subtract_projection(y, v) if attn_output.shape[-1] == v_head_dim: return z out = attn_output.clone() out[..., :v_head_dim] = z return out # Copied from transformers.models.llama.modeling_llama.repeat_kv 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) # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->Eka-v1 class MLASelfAttention(nn.Module): """Megatron ``MLASelfAttention`` (``self_attention``). Yarn/RoPE is applied **inside** this module (same as Megatron MLA). Callers must not inject external ``rotary_pos_emb`` — Megatron asserts that argument is None. Matches training when ``value_residual_subtraction=False`` (default). If that flag is True, optionally applies VRS on the attention output. """ def __init__(self, config: EkaV1Config, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx if layer_idx is None: logger.warning_once( f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will " "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " "when creating this class." ) self.attention_dropout = config.attention_dropout self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.max_position_embeddings = config.max_position_embeddings self.rope_theta = config.rope_theta self.q_lora_rank = config.q_lora_rank self.qk_rope_head_dim = config.qk_rope_head_dim self.kv_lora_rank = config.kv_lora_rank self.v_head_dim = config.v_head_dim self.qk_nope_head_dim = config.qk_nope_head_dim self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim self.is_causal = True if self.q_lora_rank is None: self.linear_q_proj = nn.Linear( self.hidden_size, self.num_heads * self.q_head_dim, bias=False ) else: self.linear_q_down_proj = nn.Linear( self.hidden_size, config.q_lora_rank, bias=config.attention_bias ) self.q_layernorm = RMSNorm(config.q_lora_rank) self.linear_q_up_proj = nn.Linear( config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False ) self.linear_kv_down_proj = nn.Linear( self.hidden_size, config.kv_lora_rank + config.qk_rope_head_dim, bias=config.attention_bias, ) self.kv_layernorm = RMSNorm(config.kv_lora_rank) self.linear_kv_up_proj = nn.Linear( config.kv_lora_rank, self.num_heads * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim), bias=False, ) self.linear_proj = nn.Linear( self.num_heads * self.v_head_dim, self.hidden_size, bias=config.attention_bias, ) self._init_rope() self.softmax_scale = self.q_head_dim ** (-0.5) if self.config.rope_scaling is not None: mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0) scaling_factor = self.config.rope_scaling["factor"] if mscale_all_dim: mscale = yarn_get_mscale(scaling_factor, mscale_all_dim) self.softmax_scale = self.softmax_scale * mscale * mscale def _init_rope(self): if self.config.rope_scaling is None: self.rotary_pos_emb = RotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, base=self.rope_theta, ) else: scaling_type = self.config.rope_scaling["type"] scaling_factor = self.config.rope_scaling["factor"] if scaling_type == "linear": self.rotary_pos_emb = LinearScalingRotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, ) elif scaling_type == "dynamic": self.rotary_pos_emb = DynamicNTKScalingRotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, ) elif scaling_type == "yarn": kwargs = { key: self.config.rope_scaling[key] for key in [ "original_max_position_embeddings", "beta_fast", "beta_slow", "mscale", "mscale_all_dim", ] if key in self.config.rope_scaling } self.rotary_pos_emb = YarnRotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, **kwargs, ) else: raise ValueError(f"Unknown RoPE scaling type {scaling_type}") def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return ( tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim) .transpose(1, 2) .contiguous() ) def _default_position_ids( self, hidden_states: torch.Tensor, past_key_value: Optional[Cache], q_len: int, ) -> torch.LongTensor: """Megatron MLA derives positions from the sequence; offset by any cached prefix.""" past_length = _cache_seq_length(past_key_value, self.layer_idx) positions = torch.arange( past_length, past_length + q_len, device=hidden_states.device, dtype=torch.long, ) return positions.unsqueeze(0).expand(hidden_states.shape[0], -1) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" ) bsz, q_len, _ = hidden_states.size() # Megatron MLA applies Yarn internally from sequence length; default positions match that. if position_ids is None: position_ids = self._default_position_ids(hidden_states, past_key_value, q_len) if self.q_lora_rank is None: q = self.linear_q_proj(hidden_states) else: q = self.linear_q_up_proj(self.q_layernorm(self.linear_q_down_proj(hidden_states))) q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2) q_nope, q_pe = torch.split( q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1 ) compressed_kv = self.linear_kv_down_proj(hidden_states) compressed_kv, k_pe = torch.split( compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1 ) k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2) kv = ( self.linear_kv_up_proj(self.kv_layernorm(compressed_kv)) .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim) .transpose(1, 2) ) k_nope, value_states = torch.split( kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1 ) # VRS uses the current query token(s) value projection, not the full KV cache. vrs_value_states = value_states kv_seq_len = value_states.shape[-2] if past_key_value is not None: if self.layer_idx is None: raise ValueError( f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} " "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class " "with a layer index." ) kv_seq_len += _cache_seq_length(past_key_value, self.layer_idx) cos, sin = self.rotary_pos_emb(value_states, seq_len=kv_seq_len) q_pe, k_pe = apply_rotary_pos_emb( q_pe, k_pe, cos, sin, position_ids, rotary_interleaved=getattr(self.config, "rotary_interleaved", False), multi_latent_attention=True, ) query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim) query_states[:, :, :, : self.qk_nope_head_dim] = q_nope query_states[:, :, :, self.qk_nope_head_dim :] = q_pe key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim) key_states[:, :, :, : self.qk_nope_head_dim] = k_nope key_states[:, :, :, self.qk_nope_head_dim :] = k_pe if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, cache_kwargs ) attn_weights = torch.matmul( query_states.float(), key_states.transpose(2, 3).float() ) * float(self.softmax_scale) if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): raise ValueError( f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" f" {attn_weights.size()}" ) # Megatron core attention uses causal masking when no additive mask is supplied. # Transformers >=5.x often leaves the prepared mask as None (SDPA/FA path), so this # fallback must be correct for both prefill and incremental decode, and for bsz>1. if attention_mask is None: # The q_len queries are the *last* q_len positions of the kv_seq_len keys, so the # diagonal must be offset by the cached prefix. With diagonal=1 a decode step # (q_len=1, kv_seq_len=1+past) would mask every cached key except the first. causal = torch.triu( torch.full( (q_len, kv_seq_len), torch.finfo(torch.float32).min, device=attn_weights.device, dtype=torch.float32, ), diagonal=1 + kv_seq_len - q_len, ) attention_mask = causal.view(1, 1, q_len, kv_seq_len).expand(bsz, 1, q_len, kv_seq_len) elif attention_mask.size() != (bsz, 1, q_len, kv_seq_len): if attention_mask.size() == (1, 1, q_len, kv_seq_len) and bsz > 1: attention_mask = attention_mask.expand(bsz, 1, q_len, kv_seq_len) else: raise ValueError( f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" ) attn_weights = attn_weights + attention_mask.to(dtype=attn_weights.dtype) # upcast attention to fp32 attn_weights = nn.functional.softmax( attn_weights, dim=-1, dtype=torch.float32 ).to(query_states.dtype) attn_weights = nn.functional.dropout( attn_weights, p=self.attention_dropout, training=self.training ) attn_output = torch.matmul(attn_weights, value_states) attn_output = _maybe_apply_vrs( self.config, attn_output, vrs_value_states, self.v_head_dim ) if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is" f" {attn_output.size()}" ) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim) attn_output = self.linear_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->Eka-v1 class FlashAttention2(MLASelfAttention): """ Eka-v1 flash attention module. Inherits MLA weights from ``MLASelfAttention``; only the forward path changes to call FlashAttention. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: # FlashAttention2 attention does not support output_attentions if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" ) # overwrite attention_mask with padding_mask attention_mask = kwargs.pop("padding_mask") output_attentions = False bsz, q_len, _ = hidden_states.size() if position_ids is None: position_ids = self._default_position_ids(hidden_states, past_key_value, q_len) if self.q_lora_rank is None: q = self.linear_q_proj(hidden_states) else: q = self.linear_q_up_proj(self.q_layernorm(self.linear_q_down_proj(hidden_states))) q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2) q_nope, q_pe = torch.split( q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1 ) # Flash attention requires the input to have the shape # batch_size x seq_length x head_dim x hidden_dim # therefore we just need to keep the original shape compressed_kv = self.linear_kv_down_proj(hidden_states) compressed_kv, k_pe = torch.split( compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1 ) k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2) kv = ( self.linear_kv_up_proj(self.kv_layernorm(compressed_kv)) .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim) .transpose(1, 2) ) k_nope, value_states = torch.split( kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1 ) vrs_value_states = value_states kv_seq_len = value_states.shape[-2] if past_key_value is not None: kv_seq_len += _cache_seq_length(past_key_value, self.layer_idx) cos, sin = self.rotary_pos_emb(value_states, seq_len=kv_seq_len) q_pe, k_pe = apply_rotary_pos_emb( q_pe, k_pe, cos, sin, position_ids, rotary_interleaved=getattr(self.config, "rotary_interleaved", False), multi_latent_attention=True, ) query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim) query_states[:, :, :, : self.qk_nope_head_dim] = q_nope query_states[:, :, :, self.qk_nope_head_dim :] = q_pe key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim) key_states[:, :, :, : self.qk_nope_head_dim] = k_nope key_states[:, :, :, self.qk_nope_head_dim :] = k_pe if self.q_head_dim != self.v_head_dim: value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim]) if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, cache_kwargs ) # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache # to be able to avoid many of these transpose/reshape/view. query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) dropout_rate = self.attention_dropout if self.training else 0.0 # In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in the correct dtype just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (RMSNorm handles it correctly) input_dtype = query_states.dtype if input_dtype == torch.float32: # Handle the case where the model is quantized if hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype elif torch.is_autocast_enabled(): target_dtype = torch.get_autocast_gpu_dtype() else: target_dtype = ( self.linear_q_proj.weight.dtype if self.q_lora_rank is None else self.linear_q_down_proj.weight.dtype ) logger.warning_once( f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." ) query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype) attn_output = self._flash_attention_forward( query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate, softmax_scale=self.softmax_scale, ) if self.q_head_dim != self.v_head_dim: attn_output = attn_output[:, :, :, : self.v_head_dim] attn_output = _maybe_apply_vrs( self.config, attn_output, vrs_value_states.transpose(1, 2), self.v_head_dim, ) attn_output = attn_output.reshape( bsz, q_len, self.num_heads * self.v_head_dim ).contiguous() attn_output = self.linear_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value def _flash_attention_forward( self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None, ): """ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores. Args: query_states (`torch.Tensor`): Input query states to be passed to Flash Attention API key_states (`torch.Tensor`): Input key states to be passed to Flash Attention API value_states (`torch.Tensor`): Input value states to be passed to Flash Attention API attention_mask (`torch.Tensor`): The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the position of padding tokens and 1 for the position of non-padding tokens. dropout (`int`, *optional*): Attention dropout softmax_scale (`float`, *optional*): The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) """ if not self._flash_attn_uses_top_left_mask: causal = self.is_causal else: # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in FlashAttention2 __init__. causal = self.is_causal and query_length != 1 # Contains at least one padding token in the sequence if attention_mask is not None: batch_size = query_states.shape[0] ( query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens, ) = self._upad_input( query_states, key_states, value_states, attention_mask, query_length ) cu_seqlens_q, cu_seqlens_k = cu_seq_lens max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens attn_output_unpad = flash_attn_varlen_func( query_states, key_states, value_states, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_in_batch_q, max_seqlen_k=max_seqlen_in_batch_k, dropout_p=dropout, softmax_scale=softmax_scale, causal=causal, ) attn_output = pad_input( attn_output_unpad, indices_q, batch_size, query_length ) else: attn_output = flash_attn_func( query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal, ) return attn_output def _upad_input( self, query_layer, key_layer, value_layer, attention_mask, query_length ): indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape key_layer = index_first_axis( key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k, ) value_layer = index_first_axis( value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k, ) if query_length == kv_seq_len: query_layer = index_first_axis( query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k, ) cu_seqlens_q = cu_seqlens_k max_seqlen_in_batch_q = max_seqlen_in_batch_k indices_q = indices_k elif query_length == 1: max_seqlen_in_batch_q = 1 cu_seqlens_q = torch.arange( batch_size + 1, dtype=torch.int32, device=query_layer.device ) # There is a memcpy here, that is very bad. indices_q = cu_seqlens_q[:-1] query_layer = query_layer.squeeze(1) else: # The -q_len: slice assumes left padding. attention_mask = attention_mask[:, -query_length:] query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input( query_layer, attention_mask ) return ( query_layer, key_layer, value_layer, indices_q, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_in_batch_q, max_seqlen_in_batch_k), ) ATTENTION_CLASSES = { "eager": MLASelfAttention, "flash_attention_2": FlashAttention2, } # Deprecated alias (older export trees named the MLA module after optional VRS). VRSMLASelfAttention = MLASelfAttention def _resolve_hybrid_layer_kind(config: EkaV1Config, layer_idx: int) -> str: """Map layer index to Megatron hybrid slot. Nano / Eka hybrid (``get_mamba_hybrid_attention_stack_spec``): - ``M`` → Mamba - ``E`` → MoE-only - ``*`` → MLA attention only (MLP is ``IdentityOp`` on non-MTP trunk layers) - ``-`` → dense MLP-only (HF: attention path unused; rare) """ pattern = getattr(config, "hybrid_override_pattern", None) or "" if config.enable_mamba and pattern and layer_idx < len(pattern): slot = pattern[layer_idx] if slot == "M": return "mamba" if slot == "E": return "moe_only" if slot == "*": # Match megatron_core: * trunk layers strip FFN (IdentityOp), MoE lives in E. return "attention_only" if slot == "-": return "attention" if _layer_uses_moe(config, layer_idx): return "moe" return "attention" def _layer_uses_moe(config: EkaV1Config, layer_idx: int) -> bool: if config.n_routed_experts is None: return False if layer_idx < config.first_k_dense_replace: return False freq = config.moe_layer_freq if isinstance(freq, list): if layer_idx >= len(freq): return False return bool(freq[layer_idx]) return layer_idx % freq == 0 class TERowParallelLinear(nn.Linear): """HF stand-in for Megatron ``TERowParallelLinear`` (single-GPU, TP=1).""" def extra_repr(self) -> str: return ( f"in_features={self.in_features}, out_features={self.out_features}, " f"bias={self.bias is not None}, TP=1" ) class ColumnParallelLinear(nn.Linear): """HF stand-in for Megatron ``ColumnParallelLinear`` (single-GPU, TP=1).""" def extra_repr(self) -> str: return ( f"in_features={self.in_features}, out_features={self.out_features}, " f"bias={self.bias is not None}, TP=1" ) class ExtendedRMSNorm(nn.Module): """Grouped RMSNorm + SiLU gate (Megatron ``ExtendedRMSNorm`` / ``RMSNormGated``). Prefer the mamba_ssm Triton kernel (same as Megatron) when CUDA + mamba_ssm are available; otherwise a fp32 PyTorch reference matching ``rms_norm_ref``. """ def __init__(self, hidden_size: int, eps: float, group_size: int, norm_before_gate: bool = False): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.eps = eps self.group_size = group_size self.norm_before_gate = norm_before_gate def _grouped_rms(self, x: torch.Tensor) -> torch.Tensor: input_dtype = x.dtype *lead, width = x.shape x_f = x.float() x_g = x_f.reshape(*lead, width // self.group_size, self.group_size) x_g = x_g * torch.rsqrt(x_g.pow(2).mean(-1, keepdim=True) + self.eps) x_g = x_g.reshape(*lead, width) return (x_g * self.weight.float()).to(input_dtype) def forward(self, y: torch.Tensor, z: Optional[torch.Tensor] = None) -> torch.Tensor: # Match Megatron ``RMSNormGated``: ``z=None`` → plain grouped RMS (mem-eff fused # path already applied ``silu(z)`` inside ``mamba_split_conv1d_scan_combined``). # Use the same Triton op Megatron subclasses (``rmsnorm_fn``) when available. if _mamba_rmsnorm_fn is not None and y.is_cuda: y_c = y.contiguous() z_c = z.contiguous() if z is not None else None w = self.weight.contiguous() return _mamba_rmsnorm_fn( y_c, w, None, z=z_c, eps=self.eps, group_size=self.group_size, norm_before_gate=self.norm_before_gate, ) if z is None: return self._grouped_rms(y) gate = F.silu(z) if self.norm_before_gate: return self._grouped_rms(y) * gate return self._grouped_rms(y * gate) def _eka_mamba_rms_norm(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: """Megatron/TE fused pre-norm for Mamba in_proj: variance in fp32.""" input_dtype = x.dtype x_f = x.float() x_f = x_f * torch.rsqrt(x_f.pow(2).mean(-1, keepdim=True) + eps) return (x_f * weight.float()).to(input_dtype) def _eka_causal_conv1d( x: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor], activation: str = "silu", left_context: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Depthwise causal conv1d. ``x``: (B, D, L), ``weight``: (D, W). ``left_context`` (B, D, W-1) supplies the tokens preceding ``x`` when continuing from a cached conv window; without it the receptive field is zero-padded as for a fresh sequence. """ if left_context is None and causal_conv1d_fn is not None and activation in ("silu", "swish"): return causal_conv1d_fn( x=x, weight=weight, bias=bias, activation=activation, ) w = weight.unsqueeze(1) seq_len = x.shape[-1] if left_context is None: x = F.pad(x, (w.shape[-1] - 1, 0)) else: x = torch.cat([left_context, x], dim=-1) out = F.conv1d(x, w, bias, groups=x.shape[1]) out = out[..., -seq_len:] if activation in ("silu", "swish"): out = F.silu(out) return out def _eka_selective_scan_ref( x: torch.Tensor, dt: torch.Tensor, A: torch.Tensor, B: torch.Tensor, C: torch.Tensor, D: torch.Tensor, dt_bias: Optional[torch.Tensor] = None, return_final_state: bool = False, initial_state: Optional[torch.Tensor] = None, ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Reference Mamba-2 selective scan (no Triton). Shapes match ``mamba_chunk_scan_combined`` I/O. x: (B, L, H, P), dt: (B, L, H), A: (H,), B/C: (B, L, G, N), D: (H,) ``initial_state`` (B, H, P, N) continues an earlier chunk instead of starting from zero. """ if dt_bias is not None: dt = F.softplus(dt + dt_bias) batch, seqlen, nheads, headdim = x.shape dstate = B.shape[-1] n_groups = B.shape[2] heads_per_group = nheads // n_groups y = torch.zeros_like(x) if initial_state is None: h = x.new_zeros(batch, nheads, headdim, dstate) else: h = initial_state.to(dtype=x.dtype).clone() for t in range(seqlen): dt_t = dt[:, t].unsqueeze(-1).unsqueeze(-1) B_t = B[:, t] C_t = C[:, t] x_t = x[:, t] for g in range(n_groups): hidx = slice(g * heads_per_group, (g + 1) * heads_per_group) # (B, N) -> (B, 1, 1, N): explicit head and head-dim axes, so this broadcasts # against (B, H, P, N) for any batch size rather than only for batch size 1. B_g = B_t[:, g].unsqueeze(1).unsqueeze(1) C_g = C_t[:, g].unsqueeze(1).unsqueeze(1) dA = torch.exp(dt_t[:, hidx] * A[hidx].view(1, -1, 1, 1)) dB = dt_t[:, hidx] * B_g h[:, hidx] = dA * h[:, hidx] + dB * x_t[:, hidx].unsqueeze(-1) y[:, t, hidx] = (h[:, hidx] * C_g).sum(-1) y[:, t] = y[:, t] + x_t * D.view(1, -1, 1) if return_final_state: return y, h return y def _eka_ssm_decode_ref( x: torch.Tensor, dt: torch.Tensor, A: torch.Tensor, B: torch.Tensor, C: torch.Tensor, D: torch.Tensor, ssm_state: torch.Tensor, dt_bias: torch.Tensor, headdim: int, n_groups: int, ) -> Tuple[torch.Tensor, torch.Tensor]: """Single-token SSM decode without Triton (matches Megatron ``_ssm_decode``).""" dt = F.softplus(dt + dt_bias.to(dtype=dt.dtype)) dA = torch.exp(dt.unsqueeze(-1).unsqueeze(-1) * A.view(1, -1, 1, 1)) x = x.view(x.shape[0], -1, headdim) B = B.view(x.shape[0], n_groups, -1) C = C.view(x.shape[0], n_groups, -1) heads_per_group = x.shape[1] // n_groups for g in range(n_groups): hidx = slice(g * heads_per_group, (g + 1) * heads_per_group) # (B, N) -> (B, 1, 1, N) so the group state broadcasts over heads and head dim # for any batch size (a trailing (B, 1, N) only lines up when batch size is 1). B_g = B[:, g].unsqueeze(1).unsqueeze(1) dBx = dt[:, hidx].unsqueeze(-1).unsqueeze(-1) * B_g * x[:, hidx].unsqueeze(-1) ssm_state[:, hidx] = ssm_state[:, hidx] * dA[:, hidx] + dBx y = torch.zeros(x.shape[0], x.shape[1], headdim, device=x.device, dtype=x.dtype) for g in range(n_groups): hidx = slice(g * heads_per_group, (g + 1) * heads_per_group) C_g = C[:, g].unsqueeze(1).unsqueeze(1) y[:, hidx] = (ssm_state[:, hidx] * C_g).sum(-1) y = y + D.view(1, -1, 1) * x return y.reshape(x.shape[0], -1), ssm_state class _MambaInProjWeight(nn.Module): """TE-split in_proj weights (``.weight.z/x/B/C/dt``).""" def __init__(self, config: EkaV1Config): super().__init__() d_inner = config.mamba_num_heads * config.mamba_head_dim d_tot_ssm = config.mamba_state_dim * config.mamba_num_groups hidden = config.hidden_size self.z = nn.Parameter(torch.empty(d_inner, hidden)) self.x = nn.Parameter(torch.empty(d_inner, hidden)) self.B = nn.Parameter(torch.empty(d_tot_ssm, hidden)) self.C = nn.Parameter(torch.empty(d_tot_ssm, hidden)) self.dt = nn.Parameter(torch.empty(config.mamba_num_heads, hidden)) class _MambaConv1dWeight(nn.Module): """TE-split conv1d weight (``.weight.x/B/C``).""" def __init__(self, config: EkaV1Config): super().__init__() d_inner = config.mamba_num_heads * config.mamba_head_dim d_tot_ssm = config.mamba_state_dim * config.mamba_num_groups kernel = 4 self.x = nn.Parameter(torch.empty(d_inner, 1, kernel)) self.B = nn.Parameter(torch.empty(d_tot_ssm, 1, kernel)) self.C = nn.Parameter(torch.empty(d_tot_ssm, 1, kernel)) class _MambaConv1dBias(nn.Module): """TE-split conv1d bias (``.bias.x/B/C``).""" def __init__(self, config: EkaV1Config): super().__init__() d_inner = config.mamba_num_heads * config.mamba_head_dim d_tot_ssm = config.mamba_state_dim * config.mamba_num_groups self.x = nn.Parameter(torch.empty(d_inner)) self.B = nn.Parameter(torch.empty(d_tot_ssm)) self.C = nn.Parameter(torch.empty(d_tot_ssm)) class TELayerNormColumnParallelLinear(nn.Module): """HF stand-in for Megatron ``TELayerNormColumnParallelLinear`` (single-GPU, TP=1).""" def __init__(self, config: EkaV1Config): super().__init__() self.layer_norm_weight = nn.Parameter(torch.ones(config.hidden_size)) self.weight = _MambaInProjWeight(config) d_inner = config.mamba_num_heads * config.mamba_head_dim d_tot_ssm = config.mamba_state_dim * config.mamba_num_groups self._in_features = config.hidden_size self._out_features = d_inner * 2 + d_tot_ssm * 2 + config.mamba_num_heads def extra_repr(self) -> str: return ( f"in_features={self._in_features}, out_features={self._out_features}, " f"bias=False, TP=1" ) class Conv1d(nn.Module): """HF stand-in for Megatron grouped depthwise ``Conv1d`` (single-GPU, TP=1).""" def __init__(self, config: EkaV1Config): super().__init__() d_inner = config.mamba_num_heads * config.mamba_head_dim d_tot_ssm = config.mamba_state_dim * config.mamba_num_groups self._channels = d_inner + 2 * d_tot_ssm self._kernel = getattr(config, "mamba_d_conv", 4) self.weight = _MambaConv1dWeight(config) self.bias = _MambaConv1dBias(config) def extra_repr(self) -> str: k = self._kernel c = self._channels return ( f"{c}, {c}, kernel_size=({k},), stride=(1,), " f"padding=({k - 1},), groups={c}" ) class MambaMixer(nn.Module): """Megatron ``MambaMixer`` (Mamba-2 SSM block).""" def __init__(self, config: EkaV1Config, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.hidden_size = config.hidden_size self.d_inner = config.mamba_num_heads * config.mamba_head_dim self.d_state = config.mamba_state_dim self.n_groups = config.mamba_num_groups self.nheads = config.mamba_num_heads self.headdim = config.mamba_head_dim self.d_conv = getattr(config, "mamba_d_conv", 4) self.chunk_size = getattr(config, "mamba_chunk_size", 128) self.d_ssm = self.d_inner + 2 * self.n_groups * self.d_state self.in_proj = TELayerNormColumnParallelLinear(config) self.out_proj = TERowParallelLinear(self.d_inner, self.hidden_size, bias=False) self.conv1d = Conv1d(config) self.A_log = nn.Parameter(torch.empty(self.nheads)) self.D = nn.Parameter(torch.ones(self.nheads)) self.dt_bias = nn.Parameter(torch.empty(self.nheads)) group_size = self.d_inner // self.n_groups # Megatron ``MambaMixer`` hardcodes ``eps=1e-5`` for ExtendedRMSNorm (not # ``config.layernorm_epsilon`` / HF ``rms_norm_eps``). self.norm = ExtendedRMSNorm( self.d_inner, eps=1e-5, group_size=group_size, norm_before_gate=False ) def _in_proj_weight(self) -> torch.Tensor: """Packed ``[z; x; B; C; dt]`` weight — Megatron TE column-parallel layout.""" w = self.in_proj.weight return torch.cat([w.z, w.x, w.B, w.C, w.dt], dim=0).contiguous() def _in_proj(self, hidden_states: torch.Tensor, layer_norm_weight: Optional[torch.Tensor] = None) -> torch.Tensor: # Match Megatron ``TELayerNormColumnParallelLinear``: FP32 RMS stats/scale, then # **one** packed GEMM (TE column-parallel ``[z;x;B;C;dt]``), not five ``F.linear``s. ln_weight = layer_norm_weight if layer_norm_weight is not None else self.in_proj.layer_norm_weight # Eka maps HF ``rms_norm_eps`` → Megatron ``layernorm_epsilon`` (both 1e-6). normed = _eka_mamba_rms_norm( hidden_states, ln_weight, self.config.rms_norm_eps ) return F.linear(normed, self._in_proj_weight()) def _conv1d_weight(self) -> torch.Tensor: cw = self.conv1d.weight return torch.cat([cw.x.squeeze(1), cw.B.squeeze(1), cw.C.squeeze(1)], dim=0).contiguous() def _conv1d_bias(self) -> torch.Tensor: cb = self.conv1d.bias return torch.cat([cb.x, cb.B, cb.C], dim=0).contiguous() def _out_proj(self, y: torch.Tensor) -> torch.Tensor: """TE ``TERowParallelLinear`` stand-in (TP=1, no bias).""" return self.out_proj(y.contiguous()) def _ssm_training(self, zxbcdt: torch.Tensor) -> torch.Tensor: """Megatron ``MambaMixer._ssm_training`` without importing Megatron. Default (``EKA_MAMBA_FUSED_RMS=1``): fold post-RMS into ``mamba_split_conv1d_scan_combined`` via ``rmsnorm_weight`` / ``eps=1e-5`` / ``norm_before_gate=False`` — same Triton ``_layer_norm_fwd`` Megatron's ``ExtendedRMSNorm`` uses, composed as ``RMS(x * silu(z))``. ``EKA_MAMBA_FUSED_RMS=0``: literal Megatron two-step (gate in kernel, then ``self.norm(y)`` with z=None). """ A = -torch.exp(self.A_log.float()) zxbcdt = zxbcdt.contiguous() conv_w = self._conv1d_weight() conv_b = self._conv1d_bias() dt_bias = self.dt_bias.float() use_fused_rms = os.environ.get("EKA_MAMBA_FUSED_RMS", "1").strip().lower() not in ( "0", "false", "no", "off", ) common = dict( chunk_size=self.chunk_size, activation="silu", headdim=self.headdim, ngroups=self.n_groups, norm_before_gate=False, ) if use_fused_rms: # Official mamba2 mem-eff + Megatron-equivalent math for # ``norm_before_gate=False``: Triton ``RMS(x * silu(z))`` inside the # kernel (same ``_layer_norm_fwd`` Megatron's ExtendedRMSNorm uses). # Megatron splits this as (gate-in-scan) + ``norm(y)``; folding RMS here # tracks that Triton op more closely in bf16 (job 315524: split+external # stayed at max_abs=6.375). Set ``EKA_MAMBA_FUSED_RMS=0`` for the literal # Megatron two-step. y = mamba_split_conv1d_scan_combined( zxbcdt, conv_w, conv_b, dt_bias, A, D=self.D, rmsnorm_weight=self.norm.weight, rmsnorm_eps=self.norm.eps, **common, ) print("[eka-mamba] path=training_fused_rms", flush=True) return self._out_proj(y) # Literal Megatron ``_ssm_training``: gate in kernel, plain RMS after. y = mamba_split_conv1d_scan_combined( zxbcdt, conv_w, conv_b, dt_bias, A, D=self.D, **common, ) print( f"[eka-mamba] path=training_split+norm rmsnorm_fn={_mamba_rmsnorm_fn is not None}", flush=True, ) return self._out_proj(self.norm(y.contiguous())) def _split_zxbcdt(self, zxbcdt: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: return torch.split( zxbcdt, [self.d_inner, self.d_ssm, self.nheads], dim=-1, ) def _ssm_decode( self, zxbcdt: torch.Tensor, cache_params: Cache, ) -> torch.Tensor: zxbcdt = zxbcdt.squeeze(1) z, xbc, dt = self._split_zxbcdt(zxbcdt) conv_state = cache_params.layers[self.layer_idx].conv_states if causal_conv1d_update is not None: xbc = causal_conv1d_update( xbc, conv_state, self._conv1d_weight(), self._conv1d_bias(), "silu", ) else: weight = self._conv1d_weight() # (C, W) conv_state.copy_(torch.roll(conv_state, shifts=-1, dims=-1)) conv_state[..., -1] = xbc xbc = (conv_state * weight.unsqueeze(0)).sum(dim=-1) + self._conv1d_bias() xbc = F.silu(xbc) x, B, C = torch.split( xbc, [self.d_inner, self.n_groups * self.d_state, self.n_groups * self.d_state], dim=-1, ) A = -torch.exp(self.A_log.float()) ssm_state = cache_params.layers[self.layer_idx].recurrent_states if ssm_state is None: ssm_state = x.new_zeros(x.shape[0], self.nheads, self.headdim, self.d_state) cache_params.update_recurrent_state(ssm_state, layer_idx=self.layer_idx) if selective_state_update is not None: A_exp = A[:, None, None].expand(-1, self.headdim, self.d_state).to(dtype=torch.float32) dt_h = dt[:, :, None].expand(-1, -1, self.headdim) dt_bias_h = self.dt_bias[:, None].expand(-1, self.headdim) D_h = self.D[:, None].expand(-1, self.headdim) B_g = B.view(x.shape[0], self.n_groups, self.d_state) C_g = C.view(x.shape[0], self.n_groups, self.d_state) x_h = x.view(x.shape[0], self.nheads, self.headdim) y = selective_state_update( ssm_state, x_h, dt_h, A_exp, B_g, C_g, D_h, z=None, dt_bias=dt_bias_h, dt_softplus=True, ) y = y.reshape(x.shape[0], self.d_inner) cache_params.update_recurrent_state(ssm_state, layer_idx=self.layer_idx) else: y, ssm_state = _eka_ssm_decode_ref( x, dt, A, B, C, self.D, ssm_state, self.dt_bias, self.headdim, self.n_groups ) cache_params.update_recurrent_state(ssm_state, layer_idx=self.layer_idx) y = self.norm(y, z) return self._out_proj(y).unsqueeze(1) def _ssm_prefill( self, zxbcdt: torch.Tensor, cache_params: Optional[Cache] = None, ) -> torch.Tensor: batch, seqlen, _ = zxbcdt.shape z, xbc, dt = self._split_zxbcdt(zxbcdt) A = -torch.exp(self.A_log.float()) # Continuing an already-populated cache (chunked prefill, speculative verification): # the conv receptive field and the SSM recurrence must pick up where they left off. continuing = ( cache_params is not None and self.layer_idx < len(cache_params.layers) and cache_params.has_previous_state(self.layer_idx) ) xbc_t = xbc.transpose(1, 2) # (B, C, L) left_context = None if continuing: cached_window = cache_params.layers[self.layer_idx].conv_states # Must be a copy: `update_conv_state` below rewrites `conv_states` in place. left_context = cached_window[..., -(self.d_conv - 1) :].to(dtype=xbc_t.dtype).clone() if cache_params is not None: if continuing: # Let the cache layer roll the window itself; it needs the raw new tokens. cache_params.update_conv_state(xbc_t, layer_idx=self.layer_idx) else: window = ( xbc_t[..., -self.d_conv :] if seqlen >= self.d_conv else F.pad(xbc_t, (self.d_conv - seqlen, 0)) ) cache_params.update_conv_state(window, layer_idx=self.layer_idx) xbc = _eka_causal_conv1d( xbc_t, self._conv1d_weight(), self._conv1d_bias(), activation="silu", left_context=left_context, ).transpose(1, 2) x, B, C = torch.split( xbc, [self.d_inner, self.n_groups * self.d_state, self.n_groups * self.d_state], dim=-1, ) x = x.view(batch, seqlen, self.nheads, self.headdim) B = B.view(batch, seqlen, self.n_groups, self.d_state) C = C.view(batch, seqlen, self.n_groups, self.d_state) return_final_states = cache_params is not None initial_state = ( cache_params.layers[self.layer_idx].recurrent_states if continuing else None ) if mamba_chunk_scan_combined is not None and x.is_cuda: scan_out = mamba_chunk_scan_combined( x, dt, A, B, C, self.chunk_size, D=self.D, z=None, dt_bias=self.dt_bias.float(), dt_softplus=True, initial_states=initial_state, return_final_states=return_final_states, ) if return_final_states: y, ssm_state = scan_out cache_params.update_recurrent_state(ssm_state, layer_idx=self.layer_idx) else: y = scan_out else: if return_final_states: y, ssm_state = _eka_selective_scan_ref( x, dt, A, B, C, self.D, dt_bias=self.dt_bias, return_final_state=True, initial_state=initial_state, ) cache_params.update_recurrent_state(ssm_state, layer_idx=self.layer_idx) else: y = _eka_selective_scan_ref( x, dt, A, B, C, self.D, dt_bias=self.dt_bias, initial_state=initial_state ) y = y.reshape(batch, seqlen, self.d_inner) y = self.norm(y, z) return self._out_proj(y) def forward( self, hidden_states: torch.Tensor, cache_params: Optional[Cache] = None, attention_mask: Optional[torch.Tensor] = None, layer_norm_weight: Optional[torch.Tensor] = None, ) -> torch.Tensor: del attention_mask # MambaMixer has no attention mask (unlike MLA) zxbcdt = self._in_proj(hidden_states, layer_norm_weight) if ( cache_params is not None and cache_params.has_previous_state(self.layer_idx) and hidden_states.shape[1] == 1 ): return self._ssm_decode(zxbcdt, cache_params) # Megatron training / parity (``inference_context is None``): mem-eff fused path. if ( cache_params is None and hidden_states.shape[1] > 1 and hidden_states.is_cuda ): # Lazy import — transformers remote-code load can miss mamba_ssm on first import. global mamba_split_conv1d_scan_combined if mamba_split_conv1d_scan_combined is None: try: from mamba_ssm.ops.triton.ssd_combined import ( mamba_split_conv1d_scan_combined as _fn, ) mamba_split_conv1d_scan_combined = _fn except ImportError: pass if mamba_split_conv1d_scan_combined is not None: return self._ssm_training(zxbcdt) if os.environ.get("EKA_DEBUG_MAMBA", "").strip() in ("1", "true", "yes"): print( "[eka-mamba] path=prefill_fallback " "(mamba_split_conv1d_scan_combined unavailable)", flush=True, ) return self._ssm_prefill(zxbcdt, cache_params=cache_params) class MambaLayer(nn.Module): """Megatron ``MambaLayer`` (``mixer`` + ``norm`` Identity).""" def __init__(self, config: EkaV1Config, layer_idx: int): super().__init__() self.layer_idx = layer_idx self.mixer = MambaMixer(config, layer_idx) self.norm = IdentityOp() def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, **kwargs, ): # Megatron ``bias_dropout_add`` (eval, no bias, dropout=0): # cast residual to mixer dtype then residual + mixer_out. residual = hidden_states mixer_out = self.mixer( hidden_states, cache_params=past_key_value if use_cache else None, attention_mask=attention_mask, ) if residual.dtype != mixer_out.dtype: residual = residual.to(dtype=mixer_out.dtype) hidden_states = residual + mixer_out outputs = (hidden_states,) if output_attentions: outputs += (None,) if use_cache: outputs += (past_key_value,) return outputs class MoETransformerLayer(nn.Module): """Megatron ``MoETransformerLayer`` (MoE-only slot, no attention).""" def __init__(self, config: EkaV1Config, layer_idx: int): super().__init__() self.layer_idx = layer_idx self.input_layernorm = IdentityOp() self.self_attention = IdentityOp() self.pre_mlp_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.mlp = MoELayer(config) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, **kwargs, ): residual = hidden_states hidden_states = self.pre_mlp_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (None,) if use_cache: outputs += (past_key_value,) return outputs class TransformerLayer(nn.Module): """Megatron ``TransformerLayer`` (MLA attention ± dense/MoE MLP). When ``include_mlp=False`` (hybrid ``*`` trunk slots), the FFN path is omitted to match megatron_core ``IdentityOp`` MLP — no MoE/dense params are registered. """ def __init__( self, config: EkaV1Config, layer_idx: int, force_moe: bool = False, include_mlp: bool = True, ): super().__init__() self.hidden_size = config.hidden_size self.layer_idx = layer_idx self.include_mlp = include_mlp self.self_attention = ATTENTION_CLASSES[config._attn_implementation]( config=config, layer_idx=layer_idx ) self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) if include_mlp: use_moe = force_moe or _layer_uses_moe(config, layer_idx) self.mlp = MoELayer(config) if use_moe else MLP(config) self.pre_mlp_layernorm = RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) else: # No Parameter submodules — matches ckpt (attention weights only). self.mlp = None self.pre_mlp_layernorm = None def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, **kwargs, ) -> Tuple[ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] ]: if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" ) residual = hidden_states hidden_states = self.input_layernorm(hidden_states) hidden_states, self_attn_weights, present_key_value = self.self_attention( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, **kwargs, ) hidden_states = residual + hidden_states if self.include_mlp: residual = hidden_states hidden_states = self.pre_mlp_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights,) if use_cache: outputs += (present_key_value,) return outputs def _build_decoder_layer(config: EkaV1Config, layer_idx: int) -> nn.Module: kind = _resolve_hybrid_layer_kind(config, layer_idx) if kind == "mamba": return MambaLayer(config, layer_idx) if kind == "moe_only": return MoETransformerLayer(config, layer_idx) if kind == "attention_only": return TransformerLayer(config, layer_idx, include_mlp=False) if kind == "attention_moe": return TransformerLayer(config, layer_idx, force_moe=True) return TransformerLayer(config, layer_idx, force_moe=(kind == "moe")) class MambaStack(nn.Module): """Megatron ``MambaStack`` (decoder layer stack + ``final_norm``).""" def __init__(self, config: EkaV1Config): super().__init__() self.layers = nn.ModuleList( [_build_decoder_layer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.final_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) EkaV1_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`EkaV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ @add_start_docstrings( "The bare EkaV1 Model outputting raw hidden-states without any specific head on top.", EkaV1_START_DOCSTRING, ) class EkaV1PreTrainedModel(PreTrainedModel): config_class = EkaV1Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["TransformerLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = True _supports_cache_class = True @classmethod def _supports_default_dynamic_cache(cls) -> bool: """Prevent transformers generate() from pre-creating a plain DynamicCache. Eka-V1 is a Mamba+MLA hybrid: the cache needs DynamicLayer slots for attention layers and LinearAttentionLayer slots for Mamba layers. A bare DynamicCache() built by ``_prepare_cache_for_generation`` has the wrong layout and is rejected by ``EkaV1Model._prepare_cache``. Returning False here makes generate() skip its default cache init, so the model's own ``_prepare_cache`` in forward() builds the correct hybrid cache via ``build_eka_cache(config)``. """ return False # Do not set `_keep_in_fp32_modules[_strict]` to buffer names: this transformers # build requires those entries to be real submodule names and raises in post_init. # Router bias stays float32 via register_buffer(dtype=fp32) + _reload_router_expert_bias_fp32. def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, TopKRouter): if hasattr(module, "e_score_correction_bias"): module.e_score_correction_bias.data.zero_() module._maintain_float32_expert_bias() @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): model = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) model._reload_router_expert_bias_fp32(pretrained_model_name_or_path) return model def to(self, *args, **kwargs): result = super().to(*args, **kwargs) for module in result.modules(): if isinstance(module, TopKRouter): module._maintain_float32_expert_bias() return result def _reload_router_expert_bias_fp32(self, model_path) -> None: """Re-load router biases as float32 from disk after bf16 ``from_pretrained`` casts. Megatron ``expert_bias`` is float32 (~38.02 with small per-expert deltas). Casting to bf16 rounds them all to 38.0 and destroys top-k routing. Prefer values from safetensors / bin (exported as float32) over the already-rounded in-memory copy. """ from pathlib import Path path = Path(model_path) if model_path is not None else None if path is None or not path.exists(): for module in self.modules(): if isinstance(module, TopKRouter): module._maintain_float32_expert_bias() return bias_tensors: dict = {} st_files = sorted(path.glob("*.safetensors")) if st_files: from safetensors import safe_open for st_path in st_files: with safe_open(st_path, framework="pt", device="cpu") as f: for key in f.keys(): if key.endswith("e_score_correction_bias"): bias_tensors[key] = f.get_tensor(key).to(torch.float32) else: bin_path = path / "pytorch_model.bin" if bin_path.exists(): raw = torch.load(bin_path, map_location="cpu") for key, tensor in raw.items(): if key.endswith("e_score_correction_bias"): bias_tensors[key] = tensor.to(torch.float32) if not bias_tensors: for module in self.modules(): if isinstance(module, TopKRouter): module._maintain_float32_expert_bias() return name_to_module = dict(self.named_modules()) for key, tensor in bias_tensors.items(): # key: model.decoder.layers.N.mlp.router.e_score_correction_bias module_name, _, attr = key.rpartition(".") module = name_to_module.get(module_name) if module is None or not hasattr(module, attr): continue buf = getattr(module, attr) device = buf.device if isinstance(buf, torch.Tensor) else tensor.device with torch.no_grad(): if attr in getattr(module, "_parameters", {}): del module._parameters[attr] module.register_buffer( attr, tensor.to(device=device, dtype=torch.float32) ) if isinstance(module, TopKRouter): module._maintain_float32_expert_bias() EkaV1_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. If `past_key_values` is used, optionally only the last `input_ids` have to be input (see `past_key_values`). If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy. - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids) past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`. Two formats are allowed: - a [`~cache_utils.Cache`] instance; - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy cache format. The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the legacy cache format will be returned. If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare Eka-v1 Model outputting raw hidden-states without any specific head on top.", EkaV1_START_DOCSTRING, ) class EkaV1Model(EkaV1PreTrainedModel): """ Megatron-style backbone: ``embedding`` + ``decoder`` (``MambaStack``). Args: config: EkaV1Config """ def __init__(self, config: EkaV1Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embedding = LanguageModelEmbedding(config) self.decoder = MambaStack(config) self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2" self.gradient_checkpointing = False self.post_init() @property def embed_tokens(self) -> nn.Embedding: """HF API alias for ``embedding.word_embeddings``.""" return self.embedding.word_embeddings @embed_tokens.setter def embed_tokens(self, value: nn.Embedding) -> None: self.embedding.word_embeddings = value def get_input_embeddings(self): return self.embedding.word_embeddings def set_input_embeddings(self, value): self.embedding.word_embeddings = value def _prepare_cache(self, past_key_values: Optional[Cache]) -> Cache: """Return a cache whose per-layer slots match this model's hybrid stack. A generic ``DynamicCache()`` has no layers until its first ``update``, and grows KV-only slots; the Mamba layers here need ``LinearAttentionLayer`` slots at their own indices. An empty cache is therefore replaced, and a populated but incompatible one is rejected rather than silently dropping the SSM state. """ if past_key_values is None or len(getattr(past_key_values, "layers", [])) == 0: return build_eka_cache(self.config) expected_attention = { idx for idx in range(self.config.num_hidden_layers) if _eka_cache_slot_is_stateful_attention(self.config, idx) } if set(_attention_layer_indices(past_key_values)) != expected_attention: raise ValueError( f"{type(past_key_values).__name__} does not match the Eka-V1 hybrid layout: " "Mamba layers need linear-attention slots and MLA layers need key/value slots. " "Pass `past_key_values=None` to let the model build one, or build it explicitly " "with `modeling_eka.build_eka_cache(model.config)`." ) return past_key_values @add_start_docstrings_to_model_forward(EkaV1_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> Union[Tuple, BaseModelOutputWithPast]: output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) # retrieve input_ids and inputs_embeds if input_ids is not None and inputs_embeds is not None: raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: batch_size, seq_length = input_ids.shape[:2] elif inputs_embeds is not None: batch_size, seq_length = inputs_embeds.shape[:2] else: raise ValueError("You have to specify either input_ids or inputs_embeds") past_key_values_length = 0 if use_cache: past_key_values = self._prepare_cache(past_key_values) past_key_values_length = _cache_seq_length(past_key_values) if position_ids is None: device = input_ids.device if input_ids is not None else inputs_embeds.device position_ids = torch.arange( past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device, ) position_ids = position_ids.unsqueeze(0) if inputs_embeds is None: inputs_embeds = self.embedding(input_ids) attention_mask = _eka_prepare_attention_mask( self.config, attention_mask, batch_size, seq_length, inputs_embeds, past_key_values_length, ) # embed positions hidden_states = inputs_embeds # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None next_decoder_cache = None for decoder_layer in self.decoder.layers: if output_hidden_states: all_hidden_states += (hidden_states,) layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_values, output_attentions=output_attentions, use_cache=use_cache, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache = layer_outputs[2 if output_attentions else 1] if output_attentions: all_self_attns += (layer_outputs[1],) hidden_states = self.decoder.final_norm(hidden_states) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) next_cache = next_decoder_cache if use_cache else None if not return_dict: return tuple( v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None ) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, ) def _roll_mtp_tensor(tensor: torch.Tensor, shifts: int = -1, pad_value: int = 0) -> torch.Tensor: """Roll along the sequence dimension and zero/pad the exposed tail (Megatron ``roll_tensor``).""" rolled = torch.roll(tensor, shifts=shifts, dims=-1) if shifts < 0: rolled[..., shifts:] = pad_value return rolled class MultiTokenPredictionLayer(nn.Module): """One Megatron ``mtp.layers.*`` block (DeepSeek-V3 style MTP depth). Training uses the full-sequence ``forward`` (roll + causal self-attention, no cache). Speculative decoding uses ``draft_step`` with a dedicated MTP KV cache so each depth can attend to previously accepted draft positions (MTP Vanilla / Eagle decode form). """ def __init__(self, config: EkaV1Config, layer_idx: int = 0): super().__init__() self.config = config self.mtp_layer_idx = layer_idx self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False) self.enorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.hnorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) # Index into the *MTP* cache (``build_mtp_cache``), not the hybrid trunk cache. self.transformer_layer = TransformerLayer( config, layer_idx=layer_idx, force_moe=True, ) def _combine_and_transform( self, hidden_states: torch.Tensor, token_embeds: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, use_cache: bool = False, **kwargs, ) -> torch.Tensor: """Shared core: norm → concat → project → transformer → final RMSNorm.""" decoder_input = self.enorm(token_embeds) hidden_states = self.hnorm(hidden_states) hidden_states = self.eh_proj(torch.cat([decoder_input, hidden_states], dim=-1)) bsz, seq_len = hidden_states.shape[:2] past_len = 0 cache_for_attn = past_key_value if use_cache else None if cache_for_attn is not None: past_len = _cache_seq_length(cache_for_attn, self.transformer_layer.layer_idx) if position_ids is None and past_len > 0: position_ids = ( torch.arange( past_len, past_len + seq_len, device=hidden_states.device, dtype=torch.long, ) .unsqueeze(0) .expand(bsz, -1) ) layer_attention_mask = _eka_prepare_attention_mask( self.config, attention_mask, bsz, seq_len, hidden_states, past_key_values_length=past_len, ) hidden_states = self.transformer_layer( hidden_states, attention_mask=layer_attention_mask, position_ids=position_ids, past_key_value=cache_for_attn, use_cache=use_cache, **kwargs, )[0] return self.final_layernorm(hidden_states) def forward( self, hidden_states: torch.Tensor, input_ids: torch.LongTensor, embed_tokens: nn.Embedding, position_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, **kwargs, ) -> Tuple[torch.Tensor, torch.LongTensor, Optional[torch.LongTensor]]: # Megatron ``roll_tensor`` always zero-fills the exposed tail (not pad_token_id). rolled_ids = _roll_mtp_tensor(input_ids, pad_value=0) rolled_position_ids = ( _roll_mtp_tensor(position_ids, pad_value=0) if position_ids is not None else None ) # Training / parity path: full sequence, no MTP cache. # Megatron MLA Yarn is applied from sequence length (positions 0..S-1), not from # the rolled position_ids used only for the shared embedding path. kwargs.pop("past_key_value", None) kwargs.pop("use_cache", None) hidden_states = self._combine_and_transform( hidden_states, embed_tokens(rolled_ids), attention_mask=attention_mask, position_ids=None, past_key_value=None, use_cache=False, **kwargs, ) return hidden_states, rolled_ids, rolled_position_ids def draft_step( self, hidden_states: torch.Tensor, next_token_ids: torch.LongTensor, embed_tokens: nn.Embedding, past_key_value: Optional[Cache] = None, use_cache: bool = True, **kwargs, ) -> torch.Tensor: """Single-position speculative draft step with optional MTP KV cache. ``hidden_states`` is ``(batch, 1, hidden)`` from the previous depth (trunk at depth 0). ``next_token_ids`` is ``(batch,)`` or ``(batch, 1)`` — the already-predicted token whose embedding plays the role of the training-time rolled input at this position. """ if next_token_ids.dim() == 1: next_token_ids = next_token_ids.unsqueeze(-1) elif next_token_ids.dim() != 2: raise ValueError( f"next_token_ids must be (batch,) or (batch, 1), got {tuple(next_token_ids.shape)}" ) if hidden_states.shape[1] != 1: raise ValueError( f"draft_step expects a single position, got seq_len={hidden_states.shape[1]}" ) return self._combine_and_transform( hidden_states, embed_tokens(next_token_ids), attention_mask=None, position_ids=None, past_key_value=past_key_value, use_cache=use_cache, **kwargs, ) class MultiTokenPredictionBlock(nn.Module): """Megatron ``MultiTokenPredictionBlock`` (batch-first: concat on ``seq`` dim).""" def __init__(self, config: EkaV1Config): super().__init__() num_layers = _mtp_num_layers_from_config(config) self.layers = nn.ModuleList( [MultiTokenPredictionLayer(config, layer_idx=i) for i in range(num_layers)] ) def forward( self, hidden_states: torch.Tensor, input_ids: torch.LongTensor, embed_tokens: nn.Embedding, position_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, **kwargs, ) -> torch.Tensor: hidden_states_list = [hidden_states] cur_hidden = hidden_states cur_ids = input_ids cur_pos = position_ids for layer in self.layers: cur_hidden, cur_ids, cur_pos = layer( cur_hidden, cur_ids, embed_tokens, position_ids=cur_pos, attention_mask=attention_mask, **kwargs, ) hidden_states_list.append(cur_hidden) return torch.cat(hidden_states_list, dim=1) def draft_tokens( self, last_hidden: torch.Tensor, first_next_token: torch.LongTensor, embed_tokens: nn.Embedding, output_layer: nn.Module, mtp_cache: Optional[Cache] = None, use_cache: bool = True, ) -> List[int]: """Greedy draft chain from MTP depths (batch size 1), updating ``mtp_cache``. Depth 0 combines ``last_hidden`` with ``Emb(first_next_token)`` and predicts the first draft; each subsequent depth feeds the previous draft's embedding. Each depth writes one new KV entry into its MTP cache slot when ``use_cache`` is set. """ if last_hidden.shape[0] != 1: raise ValueError("MTP draft_tokens currently supports batch_size=1 only") if last_hidden.dim() == 2: last_hidden = last_hidden.unsqueeze(1) elif last_hidden.shape[1] != 1: last_hidden = last_hidden[:, -1:, :] if isinstance(first_next_token, int): next_ids = torch.tensor([first_next_token], device=last_hidden.device, dtype=torch.long) else: next_ids = first_next_token.view(-1).to(device=last_hidden.device, dtype=torch.long) drafts: List[int] = [] cur_hidden = last_hidden for layer in self.layers: cur_hidden = layer.draft_step( cur_hidden, next_ids, embed_tokens, past_key_value=mtp_cache, use_cache=use_cache and mtp_cache is not None, ) draft_id = int(output_layer(cur_hidden[:, -1, :]).float().argmax(dim=-1).item()) drafts.append(draft_id) next_ids = torch.tensor([draft_id], device=last_hidden.device, dtype=torch.long) return drafts class EkaV1ForCausalLM(EkaV1PreTrainedModel, GenerationMixin): """Causal LM with root-level ``mtp`` / ``output_layer`` (Megatron + bridge key layout). Bridge weight keys are ``mtp.layers.*`` / ``output_layer.*``, not ``model.mtp.*``. Keep MTP beside ``self.model`` so export/parity match Megatron without remapping. """ _tied_weights_keys = {} # transformers>=5 expects a mapping; embeddings are untied @classmethod def _supports_default_dynamic_cache(cls): # EKA builds its own hybrid cache (build_eka_cache); a stock DynamicCache # lacks has_previous_state and the Mamba conv/ssm state buffers. return False def __init__(self, config, **kwargs): super().__init__(config, **kwargs) self.model = EkaV1Model(config) self.vocab_size = config.vocab_size self.output_layer = ColumnParallelLinear(config.hidden_size, config.vocab_size, bias=False) mtp_layers = getattr(config, "mtp_num_layers", None) or getattr( config, "num_nextn_predict_layers", 0 ) if mtp_layers: self.mtp = MultiTokenPredictionBlock(config) qcfg = getattr(config, "eka_quantization", None) if isinstance(qcfg, dict): replace_linear_with_quant(self, int(qcfg["bits"]), int(qcfg.get("group_size", 64))) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.model.embedding.word_embeddings def set_input_embeddings(self, value): self.model.embedding.word_embeddings = value def get_output_embeddings(self): return self.output_layer def set_output_embeddings(self, new_embeddings): self.output_layer = new_embeddings @property def lm_head(self) -> nn.Linear: """HF API alias for ``output_layer``.""" return self.output_layer @lm_head.setter def lm_head(self, value: nn.Linear) -> None: self.output_layer = value def set_decoder(self, decoder): self.model = decoder def get_decoder(self): return self.model @add_start_docstrings_to_model_forward(EkaV1_INPUTS_DOCSTRING) @replace_return_docstrings( output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC ) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> Union[Tuple, CausalLMOutputWithPast]: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`. Returns: Example: ```python >>> from transformers import AutoTokenizer, EkaV1ForCausalLM >>> model = EkaV1ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) 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, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = outputs[0] run_mtp = ( labels is not None and input_ids is not None and hasattr(self, "mtp") and self.mtp is not None and len(self.mtp.layers) > 0 ) if run_mtp: mtp_hidden = self.mtp( hidden_states, input_ids=input_ids, embed_tokens=self.model.embed_tokens, position_ids=position_ids, attention_mask=attention_mask, ) num_mtp = len(self.mtp.layers) hidden_states_list = torch.chunk(mtp_hidden, 1 + num_mtp, dim=1) hidden_states = hidden_states_list[0] logits = self.output_layer(hidden_states) logits = logits.float() loss = None if labels is not None: shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() loss_fct = CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels) if run_mtp: mtp_scale = getattr(self.config, "mtp_loss_scaling_factor", 0.1) / num_mtp mtp_labels = labels.clone() for mtp_idx in range(num_mtp): mtp_logits = self.output_layer(hidden_states_list[mtp_idx + 1]).float() mtp_shift_logits = mtp_logits[..., :-1, :].contiguous() mtp_shift_labels = mtp_labels[..., 1:].contiguous() mtp_shift_logits = mtp_shift_logits.view(-1, self.config.vocab_size) mtp_shift_labels = mtp_shift_labels.view(-1).to(mtp_shift_logits.device) loss = loss + mtp_scale * loss_fct(mtp_shift_logits, mtp_shift_labels) mtp_labels = _roll_mtp_tensor(mtp_labels, pad_value=-100) if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def _mtp_num_layers(self) -> int: if not hasattr(self, "mtp") or self.mtp is None: return 0 return len(self.mtp.layers) def _greedy_argmax_last(self, hidden_states: torch.Tensor) -> int: return int(self.output_layer(hidden_states[:, -1, :]).float().argmax(dim=-1).item()) def _mtp_forward_cached( self, past_key_values: Optional[Cache], attention_mask: Optional[torch.Tensor], new_token_ids: List[int], device: torch.device, ) -> Tuple[Cache, torch.Tensor, Optional[torch.Tensor]]: """Extend the trunk KV/SSM cache with ``new_token_ids``; return cache + last hidden.""" if not new_token_ids: raise ValueError("new_token_ids must be non-empty") input_ids = torch.tensor([new_token_ids], dtype=torch.long, device=device) if past_key_values is None: step_attention_mask = torch.ones_like(input_ids) else: past_len = _cache_seq_length(past_key_values) step_attention_mask = torch.ones( (1, past_len + input_ids.shape[1]), dtype=torch.long, device=device, ) outputs = self.model( input_ids=input_ids, attention_mask=step_attention_mask, past_key_values=past_key_values, use_cache=True, return_dict=True, ) # ``step_attention_mask`` already spans the full cached prefix + new tokens. return outputs.past_key_values, outputs.last_hidden_state, step_attention_mask def _mtp_draft_ids( self, last_hidden: torch.Tensor, main_next: int, mtp_cache: Optional[Cache] = None, ) -> List[int]: """Run the MTP tower once to draft ``mtp_num_layers`` tokens after ``main_next``.""" return self.mtp.draft_tokens( last_hidden[:, -1:, :], first_next_token=main_next, embed_tokens=self.model.embed_tokens, output_layer=self.output_layer, mtp_cache=mtp_cache, use_cache=mtp_cache is not None, ) @torch.inference_mode() def mtp_speculative_generate( self, input_ids: torch.LongTensor, max_new_tokens: int = 128, do_sample: bool = False, eos_token_id: Optional[int] = None, pad_token_id: Optional[int] = None, **kwargs, ) -> torch.LongTensor: """Greedy generation with DeepSeek MTP draft-and-verify + MTP KV cache. Algorithm (batch size 1, greedy only): 1. Prefill the prompt into the hybrid **trunk** cache. 2. Sample the next token from the trunk (always accepted). 3. Draft up to ``mtp_num_layers`` further tokens via MTP ``draft_step``, writing each depth into a dedicated **MTP KV cache** (separate from the trunk). 4. Verify drafts against the trunk one token at a time. On mismatch, accept the trunk's bonus token and **rewind** the MTP cache to drop rejected draft KVs. Because every emitted token is trunk-verified, the output matches plain greedy decoding; MTP cache only improves draft quality / cost across steps. """ if do_sample: raise ValueError( "mtp_speculative_generate only supports greedy decoding (do_sample=False)." ) if input_ids.shape[0] != 1: raise ValueError( "mtp_speculative_generate currently supports batch_size=1 only; " "use generate() for batched decoding." ) num_mtp = self._mtp_num_layers() if num_mtp == 0: return self.generate( input_ids=input_ids, max_new_tokens=max_new_tokens, do_sample=False, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs, ) device = input_ids.device tokens = input_ids[0].tolist() generated = 0 mtp_cache = build_mtp_cache(self.config) past_key_values, last_hidden, attention_mask = self._mtp_forward_cached( None, None, tokens, device, ) while generated < max_new_tokens: main_next = self._greedy_argmax_last(last_hidden) # Snapshot MTP lengths before speculative writes so we can rewind rejects. mtp_lens_before = _mtp_cache_lengths(mtp_cache) draft_ids = self._mtp_draft_ids(last_hidden, main_next, mtp_cache=mtp_cache) candidates = [main_next] + draft_ids # How many MTP draft tokens (not counting main_next) were accepted this round. accepted_drafts = 0 for i, cand in enumerate(candidates): if generated >= max_new_tokens: break if i > 0: verify_next = self._greedy_argmax_last(last_hidden) if verify_next != cand: # Bonus token from the verifier; stop this draft round. past_key_values, last_hidden, attention_mask = self._mtp_forward_cached( past_key_values, attention_mask, [verify_next], device, ) tokens.append(verify_next) generated += 1 if eos_token_id is not None and verify_next == eos_token_id: return torch.tensor([tokens], dtype=torch.long, device=device) break accepted_drafts += 1 past_key_values, last_hidden, attention_mask = self._mtp_forward_cached( past_key_values, attention_mask, [cand], device, ) tokens.append(cand) generated += 1 if eos_token_id is not None and cand == eos_token_id: return torch.tensor([tokens], dtype=torch.long, device=device) # Keep MTP KV only for accepted draft depths; drop the rejected suffix. # Depth i wrote one entry during drafting; retain the first ``accepted_drafts``. target_lens = [ mtp_lens_before[depth] + (1 if depth < accepted_drafts else 0) for depth in range(num_mtp) ] _rewind_mtp_cache(mtp_cache, target_lens) return torch.tensor([tokens], dtype=torch.long, device=device) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs, ): # Transformers 5.x generate() passes full-length position_ids in model_kwargs and # relies on the base implementation to slice them to next_sequence_length. return super().prepare_inputs_for_generation( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs, ) @staticmethod def _reorder_cache(past_key_values, beam_idx): # Beam search must reorder the Mamba conv/SSM state as well as the MLA key/values; # `Cache.reorder_cache` dispatches to the right routine per slot. Iterating the # cache as legacy `(key, value)` tuples would drop the SSM state entirely. past_key_values.reorder_cache(beam_idx) return past_key_values @add_start_docstrings( """ The Eka-v1 Model transformer with a sequence classification head on top (linear layer). [`EkaV1ForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). """, EkaV1_START_DOCSTRING, ) class EkaV1ForSequenceClassification(EkaV1PreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.model = EkaV1Model(config) self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.model.embed_tokens def set_input_embeddings(self, value): self.model.embed_tokens = value @add_start_docstrings_to_model_forward(EkaV1_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, SequenceClassifierOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) transformer_outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = transformer_outputs[0] logits = self.score(hidden_states) if input_ids is not None: batch_size = input_ids.shape[0] else: batch_size = inputs_embeds.shape[0] if self.config.pad_token_id is None and batch_size != 1: raise ValueError( "Cannot handle batch sizes > 1 if no padding token is defined." ) if self.config.pad_token_id is None: sequence_lengths = -1 else: if input_ids is not None: sequence_lengths = ( torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1 ).to(logits.device) else: sequence_lengths = -1 pooled_logits = logits[ torch.arange(batch_size, device=logits.device), sequence_lengths ] loss = None if labels is not None: labels = labels.to(logits.device) if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and ( labels.dtype == torch.long or labels.dtype == torch.int ): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) else: loss = loss_fct(pooled_logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct( pooled_logits.view(-1, self.num_labels), labels.view(-1) ) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(pooled_logits, labels) if not return_dict: output = (pooled_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) # Backward-compatible aliases (only top-level wrappers keep the EkaV1 prefix). # EkaV1RMSNorm = RMSNorm # EkaV1RotaryEmbedding = RotaryEmbedding # Ekav1LinearScalingRotaryEmbedding = LinearScalingRotaryEmbedding # EkaV1DynamicNTKScalingRotaryEmbedding = DynamicNTKScalingRotaryEmbedding # EkaV1YarnRotaryEmbedding = YarnRotaryEmbedding # EkaV1FlashAttention2 = FlashAttention2 # EkaV1MambaDecoderLayer = MambaLayer # EkaV1MoEOnlyDecoderLayer = MoETransformerLayer # EkaV1DecoderLayer = TransformerLayer # EkaV1MambaMixer = MambaMixer # EkaV1MoE = MoELayer # EkaV1MLP = MLP # EkaV1MTP = MultiTokenPredictionBlock # EkaV1MTPLayer = MultiTokenPredictionLayer # EkaV1MTPTransformerLayer = TransformerLayer