Instructions to use soketlabs/EKA-1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use soketlabs/EKA-1 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="soketlabs/EKA-1", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("soketlabs/EKA-1", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use soketlabs/EKA-1 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "soketlabs/EKA-1" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "soketlabs/EKA-1", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/soketlabs/EKA-1
- SGLang
How to use soketlabs/EKA-1 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "soketlabs/EKA-1" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "soketlabs/EKA-1", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "soketlabs/EKA-1" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "soketlabs/EKA-1", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use soketlabs/EKA-1 with Docker Model Runner:
docker model run hf.co/soketlabs/EKA-1
Upload folder using huggingface_hub
Browse filesFiles changed (5)
- vllm_patch/eka_v1.pyAdded+1107
- vllm_patch/hotpatch_vllm.pyAdded+324
- vllm_patch/test_hotpatch.pyAdded+195
- vllm_patch/tests/test_eka_v1.pyAdded+86
- vllm_patch/vllm-v0.31.0-eka-kernels.patchAdded+226
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107"""Inference-only Eka-V1 for vLLM.
Ported from the HF reference ``modeling_eka.py`` shipped with the checkpoint.Eka-V1 is a Nemotron-3-Nano-style hybrid stack driven by``hybrid_override_pattern``:
``M`` Mamba-2 mixer (HF ``MambaLayer``) ``E`` latent MoE, no attention (HF ``MoETransformerLayer``) ``*`` MLA attention, no MLP (HF ``TransformerLayer(include_mlp=False)``)
Each layer is pre-norm + residual. The MTP head (``mtp.*``) is not used here."""
import functoolsimport mathimport osfrom collections import defaultdictfrom collections.abc import Iterablefrom itertools import islice
import torchfrom torch import nn
from vllm.compilation.decorators import support_torch_compilefrom vllm.config import CacheConfig, ModelConfig, VllmConfigfrom vllm.distributed import ( get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size,)from vllm.distributed.parallel_state import get_pp_groupfrom vllm.logger import init_loggerfrom vllm.model_executor.layers.activation import SiluAndMulfrom vllm.model_executor.layers.fused_moe import FusedMoEFactoryfrom vllm.model_executor.layers.linear import ( ColumnParallelLinear, MergedColumnParallelLinear, ReplicatedLinear, RowParallelLinear,)from vllm.model_executor.layers.logits_processor import LogitsProcessorfrom vllm.model_executor.layers.mamba.mamba_mixer2 import MambaMixer2from vllm.model_executor.layers.mamba.mamba_utils import ( MambaStateCopyFunc, MambaStateCopyFuncCalculator, MambaStateDtypeCalculator, MambaStateShapeCalculator,)from vllm.model_executor.layers.mla import MLAModules, MultiHeadLatentAttentionWrapperfrom vllm.model_executor.layers.quantization import QuantizationConfigfrom vllm.model_executor.layers.rotary_embedding import get_rope # noqa: F401from vllm.model_executor.layers.rotary_embedding.deepseek_scaling_rope import ( DeepseekScalingRotaryEmbedding,)from vllm.model_executor.layers.vocab_parallel_embedding import ( ParallelLMHead, VocabParallelEmbedding,)from vllm.model_executor.models.deepseek_v2 import yarn_get_mscalefrom vllm.model_executor.models.interfaces import ( HasInnerState, IsHybrid, MambaStateShapes, SupportsPP,)from vllm.model_executor.models.utils import ( AutoWeightsLoader, make_empty_intermediate_tensors_factory, make_layers, maybe_prefix,)from vllm.sequence import IntermediateTensors
from vllm.model_executor.layers.mamba.mamba_mixer2 import Mixer2RMSNormGatedfrom vllm.model_executor.layers.mamba.ops.layernorm_gated import rms_norm_gated
# vLLM only configures handlers for the "vllm" logger tree.logger = init_logger(f"vllm.{__name__}")
# Megatron ``MambaMixer`` hard-codes eps=1e-5 for its gated group-norm; every# other Eka norm uses ``config.rms_norm_eps`` (1e-6).MAMBA_GATED_NORM_EPS = 1e-5MAMBA_CONV_KERNEL = 4
# ---------------------------------------------------------------------------# Mamba (pattern ``M``)# ---------------------------------------------------------------------------
# ---- Norm layers (from vllm_eka/layers.py) ----# Norm layers that reproduce Megatron/HF Eka-V1 numerics.## Megatron (and ``modeling_eka.py``) normalises in fp32, multiplies by# ``weight.float()`` in fp32 and rounds to bf16 once. vLLM's ``RMSNorm`` and# ``Mixer2RMSNormGated`` round the normalised value to bf16 *before* the weight# multiply, i.e. twice. Over ~75 norms that drift is measurable, so Eka uses# these instead.
def _rms_norm_fp32(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor: x_f = x.float() x_f = x_f * torch.rsqrt(x_f.pow(2).mean(-1, keepdim=True) + eps) return (weight.float() * x_f).to(x.dtype)
class EkaRMSNorm(nn.Module): """HF ``RMSNorm``: fp32 statistics and weight scale, one cast at the end.
Mirrors vLLM ``RMSNorm``'s call convention: ``norm(x)`` returns the normed tensor; ``norm(x, residual)`` first adds the residual (a bf16 add, as HF's ``residual + hidden_states``) and returns ``(normed, new_residual)``. """
def __init__(self, hidden_size: int, eps: float): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward( self, x: torch.Tensor, residual: torch.Tensor | None = None ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]: if residual is None: return _rms_norm_fp32(x, self.weight, self.variance_epsilon) x = x + residual return _rms_norm_fp32(x, self.weight, self.variance_epsilon), x
def extra_repr(self) -> str: return f"hidden_size={self.weight.numel()}, eps={self.variance_epsilon}"
class EkaMixer2RMSNormGated(Mixer2RMSNormGated): """HF ``ExtendedRMSNorm`` (mamba_ssm ``rmsnorm_fn``, ``norm_before_gate=False``).
``RMS(y * silu(z))`` per group, weight applied in fp32, one cast. On CUDA this is the same Triton kernel as Megatron; ``forward_native`` is the torch equivalent (equal up to fp32 summation order). Only the TP layouts where every rank owns whole groups are supported (Eka: 8 groups, TP in {1, 2, 4, 8}). """
@classmethod def enabled(cls) -> bool: # Always use forward_cuda (the Triton kernel). With torch.compile vLLM defaults # custom_ops to "none", which would pick forward_native, and this norm runs inside # the opaque vllm::mamba_mixer2 op, so it would execute as uncompiled eager torch # (slower, and not the kernel the parity checks verified in eager mode). return True
def forward_native(self, x: torch.Tensor, gate: torch.Tensor) -> torch.Tensor: assert self.use_rms_norm assert self.n_groups % self.tp_size == 0, ( "Eka gated norm requires TP size to divide mamba_num_groups" ) input_dtype = x.dtype x = x.float() * nn.functional.silu(gate.float()) *prefix_dims, hidden_dim = x.shape x = x.view(*prefix_dims, hidden_dim // self.group_size, self.group_size) x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.variance_epsilon) x = x.view(*prefix_dims, hidden_dim) return (self.weight.float() * x).to(input_dtype)
def forward_cuda(self, x: torch.Tensor, gate: torch.Tensor) -> torch.Tensor: # vLLM's Triton ``rms_norm_gated`` is the mamba_ssm ``rmsnorm_fn`` kernel Megatron # uses: bit-identical output (upstream only calls it for n_groups == 1). assert self.n_groups % self.tp_size == 0, ( "Eka gated norm requires TP size to divide mamba_num_groups" ) return rms_norm_gated( x, self.weight, bias=None, z=gate, eps=self.variance_epsilon, group_size=self.group_size, norm_before_gate=False, )
class EkaV1MambaDecoderLayer(nn.Module): """HF ``MambaLayer``: fused pre-RMSNorm (``in_proj.layer_norm_weight``) + Mamba-2 mixer + residual."""
def __init__( self, config, layer_idx: int, model_config: ModelConfig | None = None, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() intermediate_size = config.mamba_num_heads * config.mamba_head_dim self.norm = EkaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.mixer = MambaMixer2( hidden_size=config.hidden_size, ssm_state_size=config.mamba_state_dim, conv_kernel_size=MAMBA_CONV_KERNEL, intermediate_size=intermediate_size, use_conv_bias=True, use_bias=False, n_groups=config.mamba_num_groups, num_heads=config.mamba_num_heads, head_dim=config.mamba_head_dim, rms_norm_eps=MAMBA_GATED_NORM_EPS, activation="silu", model_config=model_config, cache_config=cache_config, quant_config=quant_config, prefix=f"{prefix}.mixer", ) self.mixer.norm = EkaMixer2RMSNormGated( intermediate_size, config.mamba_num_groups, use_rms_norm=True, eps=MAMBA_GATED_NORM_EPS, )
def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, residual: torch.Tensor | None, ) -> tuple[torch.Tensor, torch.Tensor]: if residual is None: residual = hidden_states hidden_states = self.norm(hidden_states) else: hidden_states, residual = self.norm(hidden_states, residual) return self.mixer(hidden_states), residual
# ---------------------------------------------------------------------------# Latent MoE (pattern ``E``)# ---------------------------------------------------------------------------
class EkaV1SharedExpertMLP(nn.Module): """HF ``SharedExpertMLP``: SwiGLU on the full hidden size, never router-weighted."""
def __init__( self, hidden_size: int, intermediate_size: int, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() self.gate_up_proj = MergedColumnParallelLinear( hidden_size, [intermediate_size] * 2, bias=False, quant_config=quant_config, prefix=f"{prefix}.gate_up_proj", ) self.down_proj = RowParallelLinear( intermediate_size, hidden_size, bias=False, quant_config=quant_config, reduce_results=False, prefix=f"{prefix}.down_proj", ) self.act_fn = SiluAndMul()
def forward(self, x: torch.Tensor) -> torch.Tensor: x, _ = self.gate_up_proj(x) x, _ = self.down_proj(self.act_fn(x)) return x
class _LatentProjThenNorm(nn.Module): """Routed-input transform: ``fc1_latent_proj`` then ``fc1_latent_norm``."""
def __init__(self, proj: nn.Module, norm: nn.Module) -> None: super().__init__() # Held in a tuple so the modules stay owned (and loaded) by EkaV1MoE. self._mods = (proj, norm)
def forward(self, x: torch.Tensor) -> torch.Tensor: proj, norm = self._mods return norm(proj(x)[0])
class _LatentNormThenProj(nn.Module): """Routed-output transform: ``fc2_latent_norm`` then ``fc2_latent_proj``.
The norm is non-linear, so the runner must all-reduce partial expert outputs before applying it (``reduce_commutative`` stays False). """
def __init__(self, norm: nn.Module, proj: nn.Module) -> None: super().__init__() self._mods = (norm, proj)
def forward(self, x: torch.Tensor) -> torch.Tensor: norm, proj = self._mods return proj(norm(x))[0]
def eka_hf_topk( hidden_states: torch.Tensor, gating_output: torch.Tensor, topk: int, renormalize: bool, *, e_score_correction_bias: torch.Tensor, routed_scaling_factor: float,) -> tuple[torch.Tensor, torch.Tensor]: """HF ``TopKRouter`` (n_group = topk_group = 1), same ops in the same order, fp32: sigmoid -> top-k on score + correction bias (sorted, HF's slot order) -> weights = unbiased scores -> / (sum + 1e-20) -> x routed_scaling_factor.""" scores = torch.sigmoid(gating_output.float()) choice = scores + e_score_correction_bias.float().unsqueeze(0) topk_ids = torch.topk(choice, k=topk, dim=-1, sorted=True)[1] topk_weights = scores.gather(1, topk_ids) if renormalize: topk_weights = topk_weights / (topk_weights.sum(dim=-1, keepdim=True) + 1e-20) return topk_weights * routed_scaling_factor, topk_ids
class EkaV1MoE(nn.Module): """HF ``MoELayer`` + ``TopKRouter``.
Router: fp32 logits (fp32 weight and input, as HF ``F.linear(x.float(), W.float())``) -> ``eka_hf_topk``. Routed experts run in the latent space (proj + norm in, norm + proj out); shared experts see the full hidden state and are added unweighted. """
def __init__( self, config, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() assert config.scoring_func == "sigmoid" assert config.topk_method == "noaux_tc" assert config.n_group == 1 and config.topk_group == 1, "eka_hf_topk: no groups" latent_size = config.moe_latent_size
self.gate = ReplicatedLinear( config.hidden_size, config.n_routed_experts, bias=False, params_dtype=torch.float32, quant_config=None, prefix=f"{prefix}.gate", ) # Must stay fp32: in bf16 every bias (~38.0x) rounds to the same value. self.gate.e_score_correction_bias = nn.Parameter( torch.empty(config.n_routed_experts, dtype=torch.float32) )
self.shared_experts = EkaV1SharedExpertMLP( config.hidden_size, config.moe_intermediate_size * config.n_shared_experts, quant_config=quant_config, prefix=f"{prefix}.shared_experts", )
self.fc1_latent_proj = ReplicatedLinear( config.hidden_size, latent_size, bias=False, quant_config=quant_config, prefix=f"{prefix}.fc1_latent_proj", ) self.fc1_latent_norm = EkaRMSNorm(latent_size, eps=config.rms_norm_eps) self.fc2_latent_norm = EkaRMSNorm(latent_size, eps=config.rms_norm_eps) self.fc2_latent_proj = ReplicatedLinear( latent_size, config.hidden_size, bias=False, quant_config=quant_config, prefix=f"{prefix}.fc2_latent_proj", )
self.experts = FusedMoEFactory( shared_experts=self.shared_experts, num_experts=config.n_routed_experts, top_k=config.num_experts_per_tok, hidden_size=latent_size, intermediate_size=config.moe_intermediate_size, renormalize=config.norm_topk_prob, quant_config=quant_config, prefix=f"{prefix}.experts", custom_routing_function=functools.partial( eka_hf_topk, e_score_correction_bias=self.gate.e_score_correction_bias, routed_scaling_factor=config.routed_scaling_factor, ), activation="silu", routed_input_transform=_LatentProjThenNorm( self.fc1_latent_proj, self.fc1_latent_norm ), routed_output_transform=_LatentNormThenProj( self.fc2_latent_norm, self.fc2_latent_proj ), # eka_hf_topk scales the top-k weights (HF), not the output. # HF MLP: router weight on the SwiGLU activation before fc2 (weighted_swiglu). apply_router_weight_on_activation=True, router_logits_dtype=torch.float32, )
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: router_logits, _ = self.gate(hidden_states.float()) return self.experts(hidden_states=hidden_states, router_logits=router_logits)
class EkaV1MoEDecoderLayer(nn.Module): """HF ``MoETransformerLayer``: ``pre_mlp_layernorm`` + latent MoE + residual."""
def __init__( self, config, layer_idx: int, model_config: ModelConfig | None = None, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() self.norm = EkaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.mixer = EkaV1MoE( config, quant_config=quant_config, prefix=f"{prefix}.mixer" )
def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, residual: torch.Tensor | None, ) -> tuple[torch.Tensor, torch.Tensor]: if residual is None: residual = hidden_states hidden_states = self.norm(hidden_states) else: hidden_states, residual = self.norm(hidden_states, residual) return self.mixer(hidden_states), residual
# ---------------------------------------------------------------------------# MLA attention (pattern ``*``)# ---------------------------------------------------------------------------
def _deepseek_yarn_rope_parameters(config) -> dict: """HF ``YarnRotaryEmbedding`` == vLLM ``deepseek_yarn`` (same mscale ratio, correction range and cache length ``original_max * factor``).""" rs = config.rope_scaling rope_type = rs.get("rope_type", rs.get("type")) assert rope_type == "yarn", f"Eka MLA expects yarn RoPE, got {rope_type!r}" return { "rope_type": "deepseek_yarn", "rope_theta": config.rope_theta, "factor": rs["factor"], "original_max_position_embeddings": rs["original_max_position_embeddings"], "beta_fast": rs.get("beta_fast", 32), "beta_slow": rs.get("beta_slow", 1), "mscale": rs.get("mscale", 1), "mscale_all_dim": rs.get("mscale_all_dim", 0), }
# ritwika changed: HF modeling_eka.py YaRN RoPE (yarn_find_correction_dim,# yarn_find_correction_range, yarn_get_mscale, yarn_linear_ramp_mask and# YarnRotaryEmbedding._set_cos_sin_cache) written out here, nothing imported from HF.# vLLM's DeepseekScalingRotaryEmbedding builds the same table a different way# (einsum, its own ramp / mscale helpers, on whatever device is current) and one# bf16 sin/cos entry in the YaRN ramp (frequency 16) comes out one step off,# e.g. position 491.def _hf_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) )
def _hf_yarn_find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048): low = math.floor(_hf_yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)) high = math.ceil(_hf_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 _hf_yarn_get_mscale(scale=1, mscale=1): if scale <= 1: return 1.0 return 0.1 * mscale * math.log(scale) + 1.0
def _hf_yarn_linear_ramp_mask(min, max, dim): if min == max: max += 0.001 # Prevent singularity # HF builds this on the CPU (no device given, default device CPU). vLLM creates the # model under torch.device("cuda"), where the division by a scalar is done as a # multiply by the reciprocal and the frequency-16 ramp value comes out one fp32 ulp # off -> sin(491, 16) rounds to the other bf16 neighbour. Pin it to the CPU like HF. linear_func = (torch.arange(dim, dtype=torch.float32, device="cpu") - min) / (max - min) return torch.clamp(linear_func, 0, 1)
class EkaV1YarnRotaryEmbedding(DeepseekScalingRotaryEmbedding): """vLLM's DeepSeek YaRN RoPE (same forward: GPT-J pairs, bf16 cos/sin lookup, ``q * cos + rotate(q) * sin`` like HF) with HF ``YarnRotaryEmbedding``'s table: inverse frequencies and ``outer(t, inv_freq)`` in fp32 on the GPU, ``cos / sin * mscale``, then one cast to the model dtype."""
def __init__( self, head_size: int, rotary_dim: int, max_position_embeddings: int, base: float, is_neox_style: bool, scaling_factor: float, dtype: torch.dtype, *, beta_fast: int = 32, beta_slow: int = 1, mscale: float = 1, mscale_all_dim: float = 0, ) -> None: # HF: _mscale = yarn_get_mscale(factor, mscale) / yarn_get_mscale(factor, mscale_all_dim) self.hf_mscale = float( _hf_yarn_get_mscale(scaling_factor, mscale) / _hf_yarn_get_mscale(scaling_factor, mscale_all_dim) ) super().__init__( head_size, rotary_dim, max_position_embeddings, base, is_neox_style, scaling_factor, dtype, beta_fast=beta_fast, beta_slow=beta_slow, mscale=mscale, mscale_all_dim=mscale_all_dim, ) if self.use_flashinfer: # FlashInfer keeps an fp32 table and rotates in fp32; HF rotates in bf16. self.use_flashinfer = False self.cos_sin_cache = self.cos_sin_cache.to(dtype)
def _compute_cos_sin_cache(self) -> torch.Tensor: # HF YarnRotaryEmbedding._set_cos_sin_cache, on the GPU like HF (device=x.device) dim = self.rotary_dim device = torch.device("cuda", torch.cuda.current_device()) if torch.cuda.is_available() else None 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 = _hf_yarn_find_correction_range( self.beta_fast, self.beta_slow, dim, self.base, self.max_position_embeddings ) inv_freq_mask = 1.0 - _hf_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 # HF builds up to the running kv length; every position's row is the same, so # build all of original_max_position_embeddings * factor once. t = torch.arange( int(self.max_position_embeddings * self.scaling_factor), device=device, dtype=torch.float32 ) freqs = torch.outer(t, inv_freq) # HF: emb = cat(freqs, freqs); cos/sin(emb) * _mscale. vLLM keeps one half of each. return torch.cat((freqs.cos() * self.hf_mscale, freqs.sin() * self.hf_mscale), dim=-1)
class EkaV1FusedQkvAProjLinear(MergedColumnParallelLinear): """HF ``linear_q_down_proj`` + ``linear_kv_down_proj`` as one replicated GEMM (shard 0 = q_lora_rank, shard 1 = kv_lora_rank + qk_rope_head_dim).
Same as vLLM's ``DeepSeekV2FusedQkvAProjLinear`` minus its DeepSeek-V3-only min-latency GEMM (gated on a 2112x7168 weight, never taken for Eka). """
def __init__( self, input_size: int, output_size: list[int], quant_config: QuantizationConfig | None = None, prefix: str = "", ): super().__init__( input_size, output_size, bias=False, quant_config=quant_config, disable_tp=True, prefix=prefix, )
class EkaV1MLAAttention(nn.Module): """HF ``MLASelfAttention`` on vLLM's MLA wrapper.
RoPE: HF de-interleaves the rope dims (even/odd -> halves) and applies rotate_half; vLLM's GPT-J style (``is_neox_style=False``) rotates the same (2i, 2i+1) pairs in place. q and k get the same permutation, so q.k is identical. """
def __init__( self, config, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() assert not config.rotary_interleaved assert not getattr(config, "value_residual_subtraction", False), ( "VRS is not implemented" ) hidden_size = config.hidden_size num_heads = config.num_attention_heads self.q_lora_rank = config.q_lora_rank self.kv_lora_rank = config.kv_lora_rank self.qk_nope_head_dim = config.qk_nope_head_dim self.qk_rope_head_dim = config.qk_rope_head_dim self.v_head_dim = config.v_head_dim qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim assert self.q_lora_rank is not None
tp_size = get_tensor_model_parallel_world_size() assert num_heads % tp_size == 0 num_local_heads = num_heads // tp_size
# Order matters: shard 0 = linear_q_down_proj, shard 1 = linear_kv_down_proj. self.fused_qkv_a_proj = EkaV1FusedQkvAProjLinear( hidden_size, [self.q_lora_rank, self.kv_lora_rank + self.qk_rope_head_dim], quant_config=quant_config, prefix=f"{prefix}.fused_qkv_a_proj", ) # HF: RMSNorm(q_lora_rank) / RMSNorm(kv_lora_rank) with the class default # eps=1e-6 (not read from config). self.q_a_layernorm = EkaRMSNorm(self.q_lora_rank, eps=1e-6) self.q_b_proj = ColumnParallelLinear( self.q_lora_rank, num_heads * qk_head_dim, bias=False, quant_config=quant_config, prefix=f"{prefix}.q_b_proj", ) self.kv_a_layernorm = EkaRMSNorm(self.kv_lora_rank, eps=1e-6) self.kv_b_proj = ColumnParallelLinear( self.kv_lora_rank, num_heads * (self.qk_nope_head_dim + self.v_head_dim), bias=False, quant_config=quant_config, prefix=f"{prefix}.kv_b_proj", ) self.o_proj = RowParallelLinear( num_heads * self.v_head_dim, hidden_size, bias=False, quant_config=quant_config, prefix=f"{prefix}.o_proj", )
# rope_parameters = _deepseek_yarn_rope_parameters(config) # self.rotary_emb = get_rope( # self.qk_rope_head_dim, # max_position=config.max_position_embeddings, # is_neox_style=False, # rope_parameters=rope_parameters, # ) # ritwika changed: HF YarnRotaryEmbedding table (EkaV1YarnRotaryEmbedding above) rope_parameters = _deepseek_yarn_rope_parameters(config) self.rotary_emb = EkaV1YarnRotaryEmbedding( self.qk_rope_head_dim, self.qk_rope_head_dim, rope_parameters["original_max_position_embeddings"], rope_parameters["rope_theta"], False, rope_parameters["factor"], torch.get_default_dtype(), beta_fast=rope_parameters["beta_fast"], beta_slow=rope_parameters["beta_slow"], mscale=rope_parameters["mscale"], mscale_all_dim=rope_parameters["mscale_all_dim"], )
# HF: softmax_scale = q_head_dim**-0.5 * mscale(factor, mscale_all_dim)**2 scaling = qk_head_dim**-0.5 if rope_parameters["mscale_all_dim"]: mscale = yarn_get_mscale( rope_parameters["factor"], float(rope_parameters["mscale_all_dim"]) ) scaling = scaling * mscale * mscale
self.mla_attn = MultiHeadLatentAttentionWrapper( hidden_size, num_local_heads, scaling, self.qk_nope_head_dim, self.qk_rope_head_dim, self.v_head_dim, self.q_lora_rank, self.kv_lora_rank, MLAModules( kv_a_layernorm=self.kv_a_layernorm, kv_b_proj=self.kv_b_proj, rotary_emb=self.rotary_emb, o_proj=self.o_proj, fused_qkv_a_proj=self.fused_qkv_a_proj, kv_a_proj_with_mqa=None, q_a_layernorm=self.q_a_layernorm, q_b_proj=self.q_b_proj, q_proj=None, indexer=None, is_sparse=False, topk_indices_buffer=None, ), cache_config, quant_config, prefix, )
# ritwika changed: EKA_MLA_REFERENCE=1 runs HF's eager MLASelfAttention math # (_forward_reference) instead of vLLM's MLA kernels. Parity checks only: # one sequence, --enforce-eager, TP=1; K/V kept on this module like HF's cache. self.reference = os.environ.get("EKA_MLA_REFERENCE", "0") == "1" if self.reference: assert tp_size == 1, "EKA_MLA_REFERENCE needs TP=1" self.num_local_heads = num_local_heads # HF: softmax_scale = q_head_dim**-0.5 * yarn_get_mscale(factor, mscale_all_dim)**2 self.hf_softmax_scale = qk_head_dim ** (-0.5) if rope_parameters["mscale_all_dim"]: m = _hf_yarn_get_mscale(rope_parameters["factor"], rope_parameters["mscale_all_dim"]) self.hf_softmax_scale = self.hf_softmax_scale * m * m self._ref_k: torch.Tensor | None = None self._ref_v: torch.Tensor | None = None
def forward(self, positions: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor: if self.reference: return self._forward_reference(positions, hidden_states) return self.mla_attn(positions, hidden_states)
@staticmethod def _hf_rope_order(x: torch.Tensor) -> torch.Tensor: # vLLM rotates GPT-J pairs (2i, 2i+1) in place; HF rotates after moving them to # [evens, odds]. Same values per element, HF's order for the q.k sum. return torch.cat((x[..., 0::2], x[..., 1::2]), dim=-1)
def _forward_reference(self, positions: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor: """HF modeling_eka MLASelfAttention.forward (eager) for one sequence.""" assert not torch.compiler.is_compiling(), "EKA_MLA_REFERENCE needs --enforce-eager" T, H = hidden_states.shape[0], self.num_local_heads nope, rope, v_dim = self.qk_nope_head_dim, self.qk_rope_head_dim, self.v_head_dim qkv_lora = self.fused_qkv_a_proj(hidden_states)[0] q_c, kv_lora = qkv_lora.split([self.q_lora_rank, self.kv_lora_rank + rope], dim=-1) q = self.q_b_proj(self.q_a_layernorm(q_c))[0].view(T, H, nope + rope) kv_c, k_pe = kv_lora.split([self.kv_lora_rank, rope], dim=-1) # HF linear_kv_up_proj(kv_layernorm(compressed_kv)) -> per head [k_nope | value] kv = self.kv_b_proj(self.kv_a_layernorm(kv_c))[0].view(T, H, nope + v_dim) k_nope, value = kv.split([nope, v_dim], dim=-1) q_pe, k_pe = self.rotary_emb(positions, q[..., nope:], k_pe.unsqueeze(1))
# HF layout (bsz=1, heads, q_len, dim); rope part in HF's order query = torch.cat((q[..., :nope], self._hf_rope_order(q_pe)), dim=-1).transpose(0, 1).unsqueeze(0) key = torch.cat( (k_nope, self._hf_rope_order(k_pe).expand(T, H, rope)), dim=-1 ).transpose(0, 1).unsqueeze(0) value = value.transpose(0, 1).unsqueeze(0) # HF DynamicLayer.update: torch.cat along the sequence; a pass at position 0 starts over if int(positions[0]) == 0 or self._ref_k is None: self._ref_k, self._ref_v = key, value else: assert int(positions[0]) == self._ref_k.shape[2], "EKA_MLA_REFERENCE: one sequence only" self._ref_k = torch.cat([self._ref_k, key], dim=-2) self._ref_v = torch.cat([self._ref_v, value], dim=-2) key_states, value_states = self._ref_k, self._ref_v kv_len = key_states.shape[-2]
attn_weights = torch.matmul(query.float(), key_states.transpose(2, 3).float()) * float( self.hf_softmax_scale ) causal = torch.triu( torch.full((T, kv_len), torch.finfo(torch.float32).min, device=attn_weights.device, dtype=torch.float32), diagonal=1 + kv_len - T, ) attn_weights = attn_weights + causal.view(1, 1, T, kv_len) attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous().reshape(T, H * v_dim) return self.o_proj(attn_output)[0]
class EkaV1AttentionDecoderLayer(nn.Module): """HF ``TransformerLayer(include_mlp=False)``: ``input_layernorm`` + MLA + residual."""
def __init__( self, config, layer_idx: int, model_config: ModelConfig | None = None, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", ) -> None: super().__init__() self.norm = EkaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.mixer = EkaV1MLAAttention( config, cache_config=cache_config, quant_config=quant_config, prefix=f"{prefix}.mixer", )
def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, residual: torch.Tensor | None, ) -> tuple[torch.Tensor, torch.Tensor]: if residual is None: residual = hidden_states hidden_states = self.norm(hidden_states) else: hidden_states, residual = self.norm(hidden_states, residual) return self.mixer(positions, hidden_states), residual
LAYER_TYPES: dict[str, type[nn.Module]] = { "M": EkaV1MambaDecoderLayer, "E": EkaV1MoEDecoderLayer, "*": EkaV1AttentionDecoderLayer,}
# ---------------------------------------------------------------------------# Model# ---------------------------------------------------------------------------
@support_torch_compile( dynamic_arg_dims={ "input_ids": 0, "positions": -1, "intermediate_tensors": 0, "inputs_embeds": 0, })class EkaV1Model(nn.Module): def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: super().__init__() config = vllm_config.model_config.hf_config model_config = vllm_config.model_config cache_config = vllm_config.cache_config quant_config = vllm_config.quant_config self.config = config
pattern = config.hybrid_override_pattern assert len(pattern) == config.num_hidden_layers, ( f"hybrid_override_pattern has {len(pattern)} slots, " f"num_hidden_layers is {config.num_hidden_layers}" ) unsupported = set(pattern) - set(LAYER_TYPES) if unsupported: raise ValueError(f"Unsupported Eka layer types: {sorted(unsupported)}")
self.embed_tokens = VocabParallelEmbedding(config.vocab_size, config.hidden_size)
def get_layer(prefix: str) -> nn.Module: layer_idx = int(prefix.rsplit(".", 1)[1]) return LAYER_TYPES[pattern[layer_idx]]( config=config, layer_idx=layer_idx, model_config=model_config, cache_config=cache_config, quant_config=quant_config, prefix=prefix, )
self.start_layer, self.end_layer, self.layers = make_layers( len(pattern), get_layer, prefix=f"{prefix}.layers" ) self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( ["hidden_states", "residual"], config.hidden_size ) self.norm_f = EkaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.embed_tokens(input_ids)
def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, ) -> torch.Tensor | IntermediateTensors: if get_pp_group().is_first_rank: hidden_states = ( inputs_embeds if inputs_embeds is not None else self.embed_input_ids(input_ids) ) residual = None else: assert intermediate_tensors is not None hidden_states = intermediate_tensors["hidden_states"] residual = intermediate_tensors["residual"]
for layer in islice(self.layers, self.start_layer, self.end_layer): hidden_states, residual = layer( positions=positions, hidden_states=hidden_states, residual=residual )
if not get_pp_group().is_last_rank: return IntermediateTensors( {"hidden_states": hidden_states, "residual": residual} ) hidden_states, _ = self.norm_f(hidden_states, residual) return hidden_states
# Megatron checkpoint -> vLLM parameter names._TOP_LEVEL_RENAMES = { "model.embedding.word_embeddings.weight": "model.embed_tokens.weight", "model.decoder.final_norm.weight": "model.norm_f.weight", "output_layer.weight": "lm_head.weight",}_LAYER_PREFIX = "model.decoder.layers."# (checkpoint suffix inside a layer, vLLM suffix, merged-linear shard id)_LAYER_RENAMES: list[tuple[str, str, int | None]] = [ # M: the TE fused pre-norm weight is the layer norm. ("mixer.in_proj.layer_norm_weight", "norm.weight", None), ("mixer.in_proj.weight.z", "mixer.in_proj.weight", 0), ("mixer.in_proj.weight.x", "mixer.in_proj.weight", 1), ("mixer.in_proj.weight.B", "mixer.in_proj.weight", 2), ("mixer.in_proj.weight.C", "mixer.in_proj.weight", 3), ("mixer.in_proj.weight.dt", "mixer.in_proj.weight", 4), ("mixer.conv1d.weight.x", "mixer.conv1d.weight", 0), ("mixer.conv1d.weight.B", "mixer.conv1d.weight", 1), ("mixer.conv1d.weight.C", "mixer.conv1d.weight", 2), ("mixer.conv1d.bias.x", "mixer.conv1d.bias", 0), ("mixer.conv1d.bias.B", "mixer.conv1d.bias", 1), ("mixer.conv1d.bias.C", "mixer.conv1d.bias", 2), ("mixer.A_log", "mixer.A", None), # loader applies -exp(A_log.float()) # E ("pre_mlp_layernorm.weight", "norm.weight", None), ("mlp.router.weight", "mixer.gate.weight", None), ("mlp.router.e_score_correction_bias", "mixer.gate.e_score_correction_bias", None), ("mlp.shared_experts.linear_fc1.gate_proj.weight", "mixer.shared_experts.gate_up_proj.weight", 0), ("mlp.shared_experts.linear_fc1.up_proj.weight", "mixer.shared_experts.gate_up_proj.weight", 1), ("mlp.shared_experts.linear_fc2.weight", "mixer.shared_experts.down_proj.weight", None), # * ("input_layernorm.weight", "norm.weight", None), ("self_attention.linear_q_down_proj.weight", "mixer.fused_qkv_a_proj.weight", 0), ("self_attention.linear_kv_down_proj.weight", "mixer.fused_qkv_a_proj.weight", 1), ("self_attention.q_layernorm.weight", "mixer.q_a_layernorm.weight", None), ("self_attention.kv_layernorm.weight", "mixer.kv_a_layernorm.weight", None), ("self_attention.linear_q_up_proj.weight", "mixer.q_b_proj.weight", None), ("self_attention.linear_kv_up_proj.weight", "mixer.kv_b_proj.weight", None), ("self_attention.linear_proj.weight", "mixer.o_proj.weight", None),]# Substring renames for everything else under ``mlp.`` (latent proj/norm, experts)._MLP_SUBSTR_RENAMES = [ ("mlp.", "mixer."), ("linear_fc1.gate_proj", "gate_proj"), ("linear_fc1.up_proj", "up_proj"), ("linear_fc2", "down_proj"),]
def remap_checkpoint_name(name: str) -> tuple[str, int | None] | None: """Map a Megatron/HF-export Eka weight name to ``(vllm_name, shard_id)``.
Returns None for weights vLLM does not load (the MTP head). """ if name.startswith("mtp."): return None if name in _TOP_LEVEL_RENAMES: return _TOP_LEVEL_RENAMES[name], None if not name.startswith(_LAYER_PREFIX): raise ValueError(f"Unexpected Eka checkpoint weight: {name}")
layer_idx, _, rest = name[len(_LAYER_PREFIX) :].partition(".") out_prefix = f"model.layers.{layer_idx}." for ckpt_suffix, vllm_suffix, shard_id in _LAYER_RENAMES: if rest == ckpt_suffix: return out_prefix + vllm_suffix, shard_id if rest.startswith("mlp."): for old, new in _MLP_SUBSTR_RENAMES: rest = rest.replace(old, new, 1) return out_prefix + rest, None # Remaining Mamba params keep their names: D, dt_bias, norm.weight, out_proj.weight. if rest.startswith("mixer."): return out_prefix + rest, None raise ValueError(f"Unexpected Eka checkpoint weight: {name}")
class EkaV1ForCausalLM(nn.Module, HasInnerState, IsHybrid, SupportsPP): @classmethod def get_mamba_state_dtype_from_config( cls, vllm_config: VllmConfig ) -> tuple[torch.dtype, ...]: cache_config = vllm_config.cache_config if cache_config.use_replayssm: raise NotImplementedError("Eka-V1 does not support ReplaySSM") return MambaStateDtypeCalculator.mamba2_state_dtype( vllm_config.model_config.dtype, cache_config.mamba_cache_dtype, cache_config.mamba_ssm_cache_dtype, )
@classmethod def get_mamba_state_shape_from_config(cls, vllm_config: VllmConfig) -> MambaStateShapes: hf_config = vllm_config.model_config.hf_config return MambaStateShapeCalculator.mamba2_state_shape( intermediate_size=hf_config.mamba_num_heads * hf_config.mamba_head_dim, tp_world_size=vllm_config.parallel_config.tensor_parallel_size, n_groups=hf_config.mamba_num_groups, num_heads=hf_config.mamba_num_heads, head_dim=hf_config.mamba_head_dim, state_size=hf_config.mamba_state_dim, conv_kernel=MAMBA_CONV_KERNEL, num_spec=vllm_config.num_speculative_tokens, )
@classmethod def get_mamba_state_copy_func(cls) -> tuple[MambaStateCopyFunc, MambaStateCopyFunc]: return MambaStateCopyFuncCalculator.mamba2_state_copy_func()
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: super().__init__() config = vllm_config.model_config.hf_config self.config = config self.vllm_config = vllm_config self.model_config = vllm_config.model_config self.model = EkaV1Model( vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") ) self.lm_head = ParallelLMHead( config.vocab_size, config.hidden_size, quant_config=vllm_config.quant_config, prefix=maybe_prefix(prefix, "lm_head"), ) self.logits_processor = LogitsProcessor(config.vocab_size) self.make_empty_intermediate_tensors = self.model.make_empty_intermediate_tensors
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.model.embed_input_ids(input_ids)
def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, **kwargs, ) -> torch.Tensor | IntermediateTensors: return self.model(input_ids, positions, intermediate_tensors, inputs_embeds)
def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None: return self.logits_processor(self.lm_head, hidden_states)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: def remapped() -> Iterable[tuple[str, torch.Tensor]]: for name, tensor in weights: mapped = remap_checkpoint_name(name) if mapped is None: continue new_name, shard_id = mapped if shard_id is not None: # Merged linears read the shard id off the tensor. tensor.shard_id = shard_id yield new_name, tensor
loaded = AutoWeightsLoader(self).load_weights(remapped()) if os.environ.get("EKA_PRINT_ARCH", "1") != "0" and get_tensor_model_parallel_rank() == 0: log_architecture(self) return loaded
def log_architecture(model: nn.Module) -> None: """Log the module tree and a per-class parameter table (``EKA_PRINT_ARCH=0`` disables).
Counts are for this rank's shards: with TP>1 multiply sharded weights by the TP size. """ own: dict[str, list[int]] = defaultdict(lambda: [0, 0]) # class -> [instances, own params] for module in model.modules(): entry = own[type(module).__name__] entry[0] += 1 entry[1] += sum(p.numel() for p in module.parameters(recurse=False)) rows = sorted(own.items(), key=lambda kv: -kv[1][1]) total = sum(p.numel() for p in model.parameters()) lines = [f"{'class':<40} {'count':>6} {'params':>16}", "-" * 64] lines += [f"{name:<40} {n:>6} {p:>16,}" for name, (n, p) in rows if p] lines += ["-" * 64, f"{'total':<40} {'':>6} {total:>16,}"] tp, pp = get_tensor_model_parallel_world_size(), get_pp_group().rank_in_group text = ( f"Eka-V1 architecture (TP={tp}, PP rank {pp}):\n{model}\n\nParameters by class " f"(own parameters, excluding children):\n" + "\n".join(lines) ) logger.info("%s", text) # EKA_ARCH_FILE=path also writes the tree there without log prefixes (chat/serve_vllm.sh sets it). arch_file = os.environ.get("EKA_ARCH_FILE") if arch_file: try: os.makedirs(os.path.dirname(os.path.abspath(arch_file)), exist_ok=True) with open(arch_file, "w") as f: f.write(text + "\n") logger.info("Eka-V1 architecture written to %s", arch_file) except OSError as e: logger.warning("Could not write EKA_ARCH_FILE=%s: %s", arch_file, e)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324#!/usr/bin/env python3"""Hot-patch stock vLLM so it serves Eka-V1 with the Eka inference stack.
Frozen to vLLM 0.31.0, the release the Eka stack is built and validated on.Eka-V1 is a hybrid model (Mamba2 + latent MoE + MLA attention). GettingMegatron-matching outputs needs more than registering the model, so the patchhas two parts:
A. Kernel fixes (vllm-v0.31.0-eka-kernels.patch, next to this script): - fused_moe: router weight applied to the activation before w2 (fp32, one rounding), as Megatron's weighted_swiglu does - mamba causal_conv1d: fp32 FMA per tap + fast-math SiLU, as Megatron's causal_conv1d CUDA kernel - mamba ssd_chunk_state: drop the BLOCK_SIZE_H=2 autotune config, which rounds the dt cumsum differently and made outputs vary run to run B. Model registration: - eka_v1.py -> vllm/model_executor/models/eka_v1.py - registry.py -> ModelRegistry.register_model("EkaV1ForCausalLM") - config.py -> MODELS_CONFIG_MAP (mamba_chunk_size 128, not 2048) - model_arch_config_convertor.py -> eka_v1 uses MLA attention + MLA KV cache
The kernel diff is applied exactly: every hunk's context must match, no fuzz.Re-running is safe (applied hunks and blocks are detected and skipped). Alledits are built before any file is written; after writing, a fresh interpreterchecks vLLM imports and sees Eka-V1, and on failure every file is restored.
Usage: python hotpatch_vllm.py # install vllm 0.31.0+cu129 (Eka stack build), then patch python hotpatch_vllm.py --skip-install # patch the vllm 0.31.0+cu129 already installed python hotpatch_vllm.py --vllm-dir <dir> # patch a vllm package dir python hotpatch_vllm.py --model-url <url> # fetch eka_v1.py instead of the local copy"""from __future__ import annotations
import argparseimport reimport subprocessimport sysfrom pathlib import Pathfrom urllib.request import Request, urlopen
VLLM_VERSION = "0.31.0"# The exact build the Eka stack runs: vLLM's CUDA 12.9 release wheel + cu129 torch.# PyPI's vllm==0.31.0 is a CUDA 13 build; same source, but its CUDA libraries round# differently and greedy outputs drift from the Eka stack. CUDA 12.9 also runs on# 12.8 drivers (570.x) via minor-version compatibility.VLLM_BUILD = "0.31.0+cu129"VLLM_WHEEL = ("https://github.com/vllm-project/vllm/releases/download/v0.31.0/" "vllm-0.31.0%2Bcu129-cp38-abi3-manylinux_2_28_x86_64.whl")TORCH_INDEX = "https://download.pytorch.org/whl/cu129"# PyPI torchcodec needs libcudart.so.13, and vLLM imports it unconditionally.TORCHCODEC = "torchcodec==0.17.0+cu126"TORCHCODEC_INDEX = "https://download.pytorch.org/whl/cu126"
HERE = Path(__file__).resolve().parentLOCAL_MODEL_FILE = HERE / "eka_v1.py"KERNEL_PATCH = HERE / "vllm-v0.31.0-eka-kernels.patch"
ARCH = "EkaV1ForCausalLM"MODEL_TYPE = "eka_v1"
BEGIN = "# >>> eka-v1 hotpatch >>>"END = "# <<< eka-v1 hotpatch <<<"
REGISTRY_BLOCK = f'''ModelRegistry.register_model( "{ARCH}", "vllm.model_executor.models.eka_v1:{ARCH}")'''
CONFIG_BLOCK = f'''class EkaV1ForCausalLMConfig(VerifyAndUpdateConfig): @staticmethod def verify_and_update_model_config(model_config: "ModelConfig") -> None: # HF MambaMixer uses getattr(config, "mamba_chunk_size", 128); the # checkpoint config has no chunk size and vLLM would default to 2048. hf_config = model_config.hf_config if getattr(hf_config, "mamba_chunk_size", None) is None: hf_config.mamba_chunk_size = 128
MODELS_CONFIG_MAP["{ARCH}"] = EkaV1ForCausalLMConfig'''
CONVERTOR_BLOCK = f'''class EkaV1ModelArchConfigConvertor(ModelArchConfigConvertorBase): # vLLM recognises MLA by a hard-coded model_type list; without this the KV # cache is sized as full heads instead of one latent head. def is_deepseek_mla(self) -> bool: return getattr(self.hf_text_config, "kv_lora_rank", None) is not None
MODEL_ARCH_CONFIG_CONVERTORS["{MODEL_TYPE}"] = EkaV1ModelArchConfigConvertor'''
# (path relative to the vllm package dir, block)REGISTRATIONS = [ ("model_executor/models/registry.py", REGISTRY_BLOCK), ("model_executor/models/config.py", CONFIG_BLOCK), ("transformers_utils/model_arch_config_convertor.py", CONVERTOR_BLOCK),]
VERIFY = f'''from vllm.model_executor.models.registry import ModelRegistryfrom vllm.model_executor.models.config import MODELS_CONFIG_MAPfrom vllm.transformers_utils.model_arch_config_convertor import MODEL_ARCH_CONFIG_CONVERTORSfrom vllm.model_executor.layers.fused_moe.config import FusedMoEConfigimport vllm.model_executor.layers.mamba.ops.causal_conv1d as convassert "{ARCH}" in ModelRegistry.get_supported_archs(), "{ARCH} not registered"assert MODELS_CONFIG_MAP["{ARCH}"].__name__ == "EkaV1ForCausalLMConfig"assert MODEL_ARCH_CONFIG_CONVERTORS["{MODEL_TYPE}"].__name__ == "EkaV1ModelArchConfigConvertor"assert "apply_router_weight_on_activation" in FusedMoEConfig.__dataclass_fields__assert hasattr(conv, "_megatron_fma")'''
# ---------------------------------------------------------------- helpers
def run(cmd: list[str]) -> None: print(f"+ {' '.join(cmd)}") subprocess.check_call(cmd)
def installed_vllm_version() -> str | None: # Ask a fresh interpreter, so a vllm installed by this script is seen. try: return subprocess.check_output( [sys.executable, "-c", "from importlib.metadata import version; print(version('vllm'))"], text=True, stderr=subprocess.DEVNULL, ).strip() except subprocess.CalledProcessError: return None
def install_stack() -> None: pip = [sys.executable, "-m", "pip", "install"] run(pip + [f"vllm @ {VLLM_WHEEL}", "--extra-index-url", TORCH_INDEX]) run(pip + ["--no-deps", "--force-reinstall", "--index-url", TORCHCODEC_INDEX, TORCHCODEC]) cuda = subprocess.check_output( [sys.executable, "-c", "import torch; print(torch.version.cuda)"], text=True).strip() if cuda != "12.9": sys.exit(f"torch was installed for CUDA {cuda}, expected 12.9 (the Eka stack build).")
def find_vllm_dir() -> Path: try: out = subprocess.check_output( [sys.executable, "-c", "import vllm, os; print(os.path.dirname(vllm.__file__))"], text=True, ) except subprocess.CalledProcessError: sys.exit("vllm is not importable here. Run without --skip-install.") return Path(out.strip().splitlines()[-1]).resolve()
# ------------------------------------------------- A. kernel diff (exact)
def parse_diff(text: str) -> dict[str, list[tuple[int, list[str], list[str]]]]: """{path: [(old_start, old_lines, new_lines), ...]} from a unified diff.""" files: dict[str, list] = {} cur = None lines = text.splitlines(keepends=True) i = 0 while i < len(lines): line = lines[i] if line.startswith("+++ "): path = line[4:].strip().split("\t")[0] cur = files.setdefault(path[2:] if path.startswith("b/") else path, []) elif line.startswith("@@") and cur is not None: m = re.match(r"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", line) n_old = int(m.group(2) or 1) n_new = int(m.group(4) or 1) old, new = [], [] i += 1 while (n_old or n_new) and i < len(lines): l = lines[i] tag, body = l[:1], l[1:] if tag == " ": old.append(body); new.append(body); n_old -= 1; n_new -= 1 elif tag == "-": old.append(body); n_old -= 1 elif tag == "+": new.append(body); n_new -= 1 elif l.startswith("\\"): pass else: raise RuntimeError(f"Malformed hunk near: {l!r}") i += 1 cur.append((int(m.group(1)), old, new)) continue i += 1 return files
def find_block(lines: list[str], block: list[str], hint: int) -> list[int]: n = len(block) hits = [j for j in range(len(lines) - n + 1) if lines[j:j + n] == block] return sorted(hits, key=lambda j: abs(j - hint))
def apply_hunks(path: Path, hunks) -> tuple[str | None, int, int]: """Returns (new text or None if unchanged, applied, already_applied).""" lines = path.read_text(encoding="utf-8").splitlines(keepends=True) applied = skipped = 0 # Apply bottom-up so earlier hunks' line numbers stay valid. # The same edit can occur twice in a file (causal_conv1d's fwd and update # kernels), so like `patch` take the exact match nearest the hunk's line. def nearest(hits: list[int], hint: int) -> int | None: if len(hits) > 1 and abs(hits[0] - hint) == abs(hits[1] - hint): return None # tie: ambiguous return hits[0] if hits else None
for start, old, new in sorted(hunks, key=lambda h: -h[0]): hint = start - 1 j = nearest(find_block(lines, old, hint), hint) done = nearest(find_block(lines, new, hint), hint) if j is not None and (done is None or abs(j - hint) <= abs(done - hint)): lines[j:j + len(old)] = new applied += 1 elif done is not None: skipped += 1 # already applied by an earlier run else: why = "is ambiguous" if find_block(lines, old, hint) else "context does not match" raise RuntimeError( f"{path}: hunk at line {start} {why}. This is not stock " f"vLLM {VLLM_VERSION}; the patch is frozen to that release." ) return ("".join(lines) if applied else None), applied, skipped
# ----------------------------------------------- B. registration blocks
def strip_block(text: str) -> str: return re.sub(rf"\n*{re.escape(BEGIN)}.*?{re.escape(END)}\n?", "\n", text, flags=re.S)
def build_registration(path: Path, block: str) -> str | None: original = path.read_text(encoding="utf-8") text = strip_block(original).rstrip("\n") + "\n" wrapped = (f"\n\n{BEGIN}\n# Added by Eka-V1 hotpatch_vllm.py (vLLM {VLLM_VERSION})." f"{block}{END}\n") m = re.search(r'^if __name__ == ["\']__main__["\']:', text, flags=re.M) if m: # keep a trailing __main__ block last new = text[: m.start()].rstrip("\n") + wrapped + "\n\n" + text[m.start():] else: new = text.rstrip("\n") + wrapped return None if new == original else new
def load_model_file(url: str | None) -> bytes: if url: raw_url = url.replace("/blob/", "/raw/") print(f"Downloading eka_v1.py from: {raw_url}") req = Request(raw_url, headers={"User-Agent": "vllm-hotpatch-script"}) with urlopen(req) as resp: return resp.read() if not LOCAL_MODEL_FILE.exists(): raise FileNotFoundError(f"{LOCAL_MODEL_FILE} not found. Put eka_v1.py " "next to this script or pass --model-url.") return LOCAL_MODEL_FILE.read_bytes()
# ------------------------------------------------------------------ main
def main() -> None: ap = argparse.ArgumentParser(description="Hot-patch vLLM 0.31.0 to serve Eka-V1.") ap.add_argument("--skip-install", action="store_true", help="don't pip install vllm") ap.add_argument("--vllm-dir", type=Path, help="vllm package dir (default: auto-detect)") ap.add_argument("--model-url", help="URL to download eka_v1.py from") args = ap.parse_args()
if args.vllm_dir: vllm_dir = args.vllm_dir.resolve() else: if not args.skip_install and installed_vllm_version() != VLLM_BUILD: install_stack() found = installed_vllm_version() if found is None or found.split("+")[0] != VLLM_VERSION: sys.exit(f"vllm {found} is installed; this patch is frozen to vLLM " f"{VLLM_BUILD}. Run without --skip-install.") if found != VLLM_BUILD: print(f"WARNING: vllm {found} is not the Eka stack build ({VLLM_BUILD}). " "It will run, but outputs can drift from the reference.") vllm_dir = find_vllm_dir() print(f"Patching vLLM at: {vllm_dir}")
# Build every edit before writing any. edits: dict[Path, str] = {} for rel, hunks in parse_diff(KERNEL_PATCH.read_text(encoding="utf-8")).items(): path = vllm_dir.parent / rel # diff paths start with vllm/ text, n_new, n_old = apply_hunks(path, hunks) print(f" kernel {rel}: {n_new} hunk(s) applied, {n_old} already applied") if text is not None: edits[path] = text for rel, block in REGISTRATIONS: path = vllm_dir / rel text = build_registration(path, block) print(f" register {rel}: {'updated' if text else 'already registered'}") if text is not None: edits[path] = text model_path = vllm_dir / "model_executor" / "models" / "eka_v1.py" edits[model_path] = load_model_file(args.model_url).decode("utf-8")
backups = {p: (p.read_bytes() if p.exists() else None) for p in edits} for path, text in edits.items(): path.write_bytes(text.encode("utf-8")) # keep LF line endings
if not args.vllm_dir: r = subprocess.run([sys.executable, "-c", VERIFY], capture_output=True, text=True) if r.returncode != 0: for p, data in backups.items(): if data is None: p.unlink(missing_ok=True) else: p.write_bytes(data) sys.exit("Verification failed; restored vLLM to how it was.\n" + r.stderr[-3000:]) print("Verified: vLLM imports, kernel fixes are in, Eka-V1 is registered.")
print(f"\nDone. Eka-V1 is ready on vLLM {VLLM_VERSION}. ")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195#!/usr/bin/env python3"""Test the Eka-V1 vLLM hotpatch.
python test_hotpatch.py check No GPU or checkpoint needed. Confirms the kernel fixes and the model registration took effect in the installed vLLM and that eka_v1.py imports.
python test_hotpatch.py generate --model /path/to/Eka-V1 --out patched.json [--chat] Needs GPUs. Loads the checkpoint, confirms vLLM picked the Eka class, MLA and mamba_chunk_size=128, then greedy-decodes fixed prompts to a JSON file.
python test_hotpatch.py compare fork.json patched.json Compares two `generate` outputs, e.g. our Eka stack (~/vllm_eka) vs the hotpatched stock vLLM. Run `generate` in each environment first."""from __future__ import annotations
import argparseimport jsonimport sysfrom types import SimpleNamespace
ARCH = "EkaV1ForCausalLM"
PROMPTS = [ "The capital of France is", "भारत की राजधानी", "def fibonacci(n):", "Explain why the sky is blue in two sentences.", "Translate to Kannada: Good morning, how are you?", "12 * 17 =",]
failures: list[str] = []
def ok(cond: bool, msg: str) -> None: print((" PASS " if cond else " FAIL ") + msg) if not cond: failures.append(msg)
def cmd_check(_args) -> None: import vllm
print(f"vllm {vllm.__version__} at {vllm.__file__}")
print("1. registry.py") from vllm.model_executor.models.registry import ModelRegistry
ok(ARCH in ModelRegistry.get_supported_archs(), f"{ARCH} is a supported architecture") from vllm.model_executor.models.eka_v1 import EkaV1ForCausalLM # Use vLLM's helpers, not issubclass(): on some releases these protocols # have data members and issubclass() raises TypeError. from vllm.model_executor.models.interfaces import is_hybrid, supports_pp
ok(True, "vllm.model_executor.models.eka_v1 imports") ok(is_hybrid(EkaV1ForCausalLM), f"{ARCH} is a hybrid (Mamba) model") ok(supports_pp(EkaV1ForCausalLM), f"{ARCH} supports pipeline parallel")
print("2. config.py") from vllm.model_executor.models.config import MODELS_CONFIG_MAP
hook = MODELS_CONFIG_MAP.get(ARCH) ok(hook is not None and hook.__name__ == "EkaV1ForCausalLMConfig", f"MODELS_CONFIG_MAP[{ARCH!r}] is EkaV1ForCausalLMConfig") if hook is not None: mc = SimpleNamespace(hf_config=SimpleNamespace()) hook.verify_and_update_model_config(mc) ok(getattr(mc.hf_config, "mamba_chunk_size", None) == 128, "missing mamba_chunk_size defaults to 128") mc = SimpleNamespace(hf_config=SimpleNamespace(mamba_chunk_size=256)) hook.verify_and_update_model_config(mc) ok(mc.hf_config.mamba_chunk_size == 256, "an explicit mamba_chunk_size is kept")
print("3. model_arch_config_convertor.py") from vllm.transformers_utils.model_arch_config_convertor import ( MODEL_ARCH_CONFIG_CONVERTORS, ModelArchConfigConvertorBase, )
ok("eka_v1" in MODEL_ARCH_CONFIG_CONVERTORS, "eka_v1 has its own arch config convertor")
def mla(**cfg) -> bool: # Same lookup ModelConfig.get_model_arch_config() does. c = SimpleNamespace(**cfg) cls = MODEL_ARCH_CONFIG_CONVERTORS.get(cfg["model_type"], ModelArchConfigConvertorBase) return cls(c, c).is_deepseek_mla()
ok(mla(model_type="eka_v1", kv_lora_rank=512), "eka_v1 with kv_lora_rank uses MLA") ok(not mla(model_type="eka_v1", kv_lora_rank=None), "eka_v1 without kv_lora_rank does not") ok(not mla(model_type="llama", kv_lora_rank=512), "unrelated models are unchanged")
print("4. kernel fixes (vllm-v0.31.0-eka-kernels.patch)") from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig from vllm.model_executor.layers.fused_moe.experts.triton_moe import TritonExperts from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEExperts import vllm.model_executor.layers.mamba.ops.causal_conv1d as conv import vllm.model_executor.layers.mamba.ops.ssd_chunk_state as ssd
ok("apply_router_weight_on_activation" in FusedMoEConfig.__dataclass_fields__, "FusedMoEConfig has apply_router_weight_on_activation") ok(TritonExperts._supports_router_weight_on_activation() and not FusedMoEExperts._supports_router_weight_on_activation(), "only the Triton experts claim router-weight-on-activation") ok(hasattr(conv, "_megatron_fma") and hasattr(conv, "_megatron_silu"), "causal_conv1d uses the Megatron fp32 FMA / fast-math SiLU") sizes = sorted(c.kwargs["BLOCK_SIZE_H"] for c in ssd._chunk_cumsum_fwd_kernel.configs) ok(2 not in sizes, f"SSD chunk-cumsum autotune has no BLOCK_SIZE_H=2 (got {sizes})")
def cmd_generate(args) -> None: from vllm import LLM, SamplingParams
llm = LLM( model=args.model, trust_remote_code=True, tensor_parallel_size=args.tp, max_model_len=args.max_model_len, enforce_eager=args.eager, ) mc = llm.llm_engine.model_config print("Load checks") ok(ARCH in mc.architectures, f"architecture is {ARCH} (got {mc.architectures})") ok(mc.use_mla, "MLA attention is enabled") chunk = getattr(mc.hf_config, "mamba_chunk_size", None) ok(chunk is not None, f"mamba_chunk_size is set (= {chunk}; 128 unless the checkpoint sets it)")
sp = SamplingParams(temperature=0.0, max_tokens=args.max_tokens, logprobs=1) if args.chat: # Chat/reasoning checkpoints: send each prompt as a user turn through the # checkpoint's chat template (base checkpoints: leave --chat off). outs = llm.chat([[{"role": "user", "content": p}] for p in PROMPTS], sp) else: outs = llm.generate(PROMPTS, sp) results = [] for p, o in zip(PROMPTS, outs): c = o.outputs[0] lps = [next(iter(d.values())).logprob if d else None for d in (c.logprobs or [])] results.append({"prompt": p, "text": c.text, "token_ids": list(c.token_ids), "logprobs": lps}) print(f"\n>>> {p}\n{c.text}") ok(len(c.token_ids) > 0 and c.text.strip() != "", f"non-empty output for {p!r}") with open(args.out, "w", encoding="utf-8") as f: json.dump({"vllm": __import__("vllm").__version__, "results": results}, f, ensure_ascii=False, indent=1) print(f"\nWrote {args.out}")
def cmd_compare(args) -> None: a = json.load(open(args.a, encoding="utf-8")) b = json.load(open(args.b, encoding="utf-8")) print(f"{args.a}: vllm {a['vllm']} {args.b}: vllm {b['vllm']}") for ra, rb in zip(a["results"], b["results"]): ta, tb = ra["token_ids"], rb["token_ids"] n = next((i for i, (x, y) in enumerate(zip(ta, tb)) if x != y), min(len(ta), len(tb))) same = ta == tb # Greedy decoding on different vLLM builds can legitimately diverge # late; diverging in the first few tokens points at a real bug. ok(same or n >= args.min_match, f"{ra['prompt']!r}: " + ("identical" if same else f"first {n} tokens match")) if not same: la, lb = ra["logprobs"][:n], rb["logprobs"][:n] d = max((abs(x - y) for x, y in zip(la, lb) if x is not None and y is not None), default=0.0) print(f" max logprob diff on matching prefix: {d:.4f}")
def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = ap.add_subparsers(dest="cmd", required=True) sub.add_parser("check") g = sub.add_parser("generate") g.add_argument("--model", required=True, help="checkpoint dir or HF repo id") g.add_argument("--out", required=True) g.add_argument("--tp", type=int, default=1, help="tensor parallel size") g.add_argument("--max-model-len", type=int, default=4096) g.add_argument("--max-tokens", type=int, default=64) g.add_argument("--eager", action="store_true", help="disable CUDA graphs / compile") g.add_argument("--chat", action="store_true", help="apply the chat template (for chat / reasoning checkpoints)") c = sub.add_parser("compare") c.add_argument("a") c.add_argument("b") c.add_argument("--min-match", type=int, default=16, help="tokens that must match before a divergence counts as OK") args = ap.parse_args() {"check": cmd_check, "generate": cmd_generate, "compare": cmd_compare}[args.cmd](args)
print(f"\n{'ALL PASSED' if not failures else f'{len(failures)} FAILED'}") sys.exit(1 if failures else 0)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# SPDX-License-Identifier: Apache-2.0# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytestimport torch
from vllm.model_executor.models.eka_v1 import ( EkaRMSNorm, eka_hf_topk, remap_checkpoint_name,)
L = "model.decoder.layers.3."
@pytest.mark.cpu_test@pytest.mark.parametrize( ("ckpt_name", "expected"), [ ("model.embedding.word_embeddings.weight", ("model.embed_tokens.weight", None)), ("output_layer.weight", ("lm_head.weight", None)), (L + "mixer.in_proj.layer_norm_weight", ("model.layers.3.norm.weight", None)), (L + "mixer.in_proj.weight.dt", ("model.layers.3.mixer.in_proj.weight", 4)), (L + "mixer.conv1d.bias.C", ("model.layers.3.mixer.conv1d.bias", 2)), (L + "mixer.A_log", ("model.layers.3.mixer.A", None)), (L + "mixer.dt_bias", ("model.layers.3.mixer.dt_bias", None)), ( L + "mlp.shared_experts.linear_fc1.up_proj.weight", ("model.layers.3.mixer.shared_experts.gate_up_proj.weight", 1), ), ( L + "mlp.fc1_latent_proj.weight", ("model.layers.3.mixer.fc1_latent_proj.weight", None), ), ( L + "self_attention.linear_kv_down_proj.weight", ("model.layers.3.mixer.fused_qkv_a_proj.weight", 1), ), ("mtp.layers.0.enorm.weight", None), ],)def test_remap_checkpoint_name(ckpt_name, expected): assert remap_checkpoint_name(ckpt_name) == expected
@pytest.mark.cpu_testdef test_remap_rejects_unknown_weight(): with pytest.raises(ValueError): remap_checkpoint_name("model.unknown.weight")
@pytest.mark.cpu_testdef test_rms_norm_rounds_once(): torch.manual_seed(0) x = torch.randn(4, 64, dtype=torch.bfloat16) residual = torch.randn(4, 64, dtype=torch.bfloat16) norm = EkaRMSNorm(64, eps=1e-6) norm.weight.data = torch.randn(64, dtype=torch.bfloat16)
out, new_residual = norm(x, residual)
h = (x + residual).float() ref = norm.weight.float() * h * torch.rsqrt(h.pow(2).mean(-1, keepdim=True) + 1e-6) torch.testing.assert_close(out, ref.to(torch.bfloat16), atol=0, rtol=0) torch.testing.assert_close(new_residual, x + residual, atol=0, rtol=0)
@pytest.mark.cpu_testdef test_topk_bias_only_selects(): logits = torch.tensor([[2.0, 1.0, 0.0, -1.0]]) bias = torch.tensor([0.0, 0.0, 10.0, 10.0])
weights, ids = eka_hf_topk( logits, logits, topk=2, renormalize=True, e_score_correction_bias=bias, routed_scaling_factor=2.5, )
assert sorted(ids[0].tolist()) == [2, 3] scores = torch.sigmoid(logits[0, [2, 3]]) torch.testing.assert_close( weights[0].sort().values, (2.5 * scores / scores.sum()).sort().values )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226# Eka changes to vLLM, base: v0.31.0 (db9527a46873454610df6dbedf79a36d6bf1a7f6)diff --git a/vllm/model_executor/layers/fused_moe/config.py b/vllm/model_executor/layers/fused_moe/config.pyindex 11e2a57520..03c8949330 100644--- a/vllm/model_executor/layers/fused_moe/config.py+++ b/vllm/model_executor/layers/fused_moe/config.py@@ -1306,6 +1306,12 @@ class FusedMoEConfig: activation_situ_beta: float | None = None activation_situ_linear_beta: float | None = None + # Multiply the gated activation by the router weight (fp32, one rounding to+ # the activation dtype) before w2 instead of scaling the w2 output, as+ # Megatron's weighted_swiglu does. Backends that do not implement it are+ # filtered out by `FusedMoEExperts.is_supported_config`.+ apply_router_weight_on_activation: bool = False+ max_capture_size: int = 0 # Set by __post_init__diff --git a/vllm/model_executor/layers/fused_moe/experts/triton_moe.py b/vllm/model_executor/layers/fused_moe/experts/triton_moe.pyindex ee3b9b3f4b..c325988977 100644--- a/vllm/model_executor/layers/fused_moe/experts/triton_moe.py+++ b/vllm/model_executor/layers/fused_moe/experts/triton_moe.py@@ -192,6 +192,10 @@ class TritonExperts(LoRAExpertsMixin, mk.FusedMoEExpertsModular): def _supports_batch_invariance(): return True + @staticmethod+ def _supports_router_weight_on_activation() -> bool:+ return True+ def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce: return TopKWeightAndReduceNoOP() @@ -390,6 +394,10 @@ class TritonExperts(LoRAExpertsMixin, mk.FusedMoEExpertsModular): num_tokens_post_padded_lora = None token_lora_mapping = None lora_context = self._lora_context+ weight_on_activation = self.moe_config.apply_router_weight_on_activation+ if weight_on_activation:+ assert not apply_router_weight_on_input+ assert self.quant_dtype is None and lora_context is None if lora_unquantized_hidden_states is not None: lora_x = lora_unquantized_hidden_states elif (@@ -518,6 +526,13 @@ class TritonExperts(LoRAExpertsMixin, mk.FusedMoEExpertsModular): self.activation( activation, intermediate_cache2, intermediate_cache1.view(-1, N) )+ if weight_on_activation:+ # Megatron weighted_swiglu: act * prob in fp32, one rounding, then w2.+ # Rows are (token, k), the layout of topk_weights.+ act = intermediate_cache2.view(num_tokens, top_k_num, -1)+ act.copy_(+ act.float() * topk_weights.view(num_tokens, top_k_num, 1).float()+ ) qintermediate_cache2, a2q_scale = moe_kernel_quantize_input( intermediate_cache2,@@ -544,7 +559,7 @@ class TritonExperts(LoRAExpertsMixin, mk.FusedMoEExpertsModular): sorted_token_ids, expert_ids, num_tokens_post_padded,- not apply_router_weight_on_input,+ not apply_router_weight_on_input and not weight_on_activation, 1, config, compute_type=compute_type,diff --git a/vllm/model_executor/layers/fused_moe/layer.py b/vllm/model_executor/layers/fused_moe/layer.pyindex ff620622c1..e93d90d6b6 100644--- a/vllm/model_executor/layers/fused_moe/layer.py+++ b/vllm/model_executor/layers/fused_moe/layer.py@@ -112,6 +112,7 @@ def FusedMoEFactory( activation_situ_linear_beta: float | None = None, e_score_correction_bias: torch.Tensor | None = None, apply_router_weight_on_input: bool = False,+ apply_router_weight_on_activation: bool = False, activation: str = "silu", enable_eplb: bool = False, num_redundant_experts: int = 0,@@ -369,6 +370,7 @@ def FusedMoEFactory( swiglu_beta=swiglu_beta, activation_situ_beta=activation_situ_beta, activation_situ_linear_beta=activation_situ_linear_beta,+ apply_router_weight_on_activation=apply_router_weight_on_activation, max_capture_size=vllm_config.compilation_config.max_cudagraph_capture_size, skip_final_all_reduce=skip_final_all_reduce, )diff --git a/vllm/model_executor/layers/fused_moe/modular_kernel.py b/vllm/model_executor/layers/fused_moe/modular_kernel.pyindex f563c819e4..2f27fbb5d9 100644--- a/vllm/model_executor/layers/fused_moe/modular_kernel.py+++ b/vllm/model_executor/layers/fused_moe/modular_kernel.py@@ -573,6 +573,11 @@ class FusedMoEExperts(ABC): return False, _make_reason("batch invariance") elif moe_config.is_lora_enabled and not cls.supports_lora(): return False, _make_reason("LoRA")+ elif (+ moe_config.apply_router_weight_on_activation+ and not cls._supports_router_weight_on_activation()+ ):+ return False, _make_reason("router weight on activation") return True, None @staticmethod@@ -647,6 +652,12 @@ class FusedMoEExperts(ABC): """ return True + @staticmethod+ def _supports_router_weight_on_activation() -> bool:+ """Whether the kernel implements+ `FusedMoEConfig.apply_router_weight_on_activation`."""+ return False+ @staticmethod def _supports_batch_invariance() -> bool: """Whether the kernel supports batch invariance, i.e. the output does notdiff --git a/vllm/model_executor/layers/mamba/ops/causal_conv1d.py b/vllm/model_executor/layers/mamba/ops/causal_conv1d.pyindex e8254e4f34..a8008c1c13 100644--- a/vllm/model_executor/layers/mamba/ops/causal_conv1d.py+++ b/vllm/model_executor/layers/mamba/ops/causal_conv1d.py@@ -13,6 +13,46 @@ from vllm.triton_utils import tl, triton from vllm.v1.attention.backends.utils import NULL_BLOCK_ID, PAD_SLOT_ID +# Eka: match Megatron's conv kernel (Dao-AILab causal_conv1d CUDA, built with+# --use_fast_math) instruction for instruction. Its per-output math+# out = bias; out += w[k] * x[k] (k = 0..W-1); out = out / (1 + expf(-out))+# compiles (NVRTC, -O3 --use_fast_math, sm_90) to:+# fma.rn.ftz.f32 (per tap), mul.ftz.f32 by -log2(e), ex2.approx.ftz.f32,+# add.ftz.f32 1.0, div.approx.ftz.f32+# Plain Triton gives fma.rn.f32 / ex2.approx.f32 / div.full.f32: same math, but+# div.full and the missing flush-to-zero round differently on rare elements.+@triton.jit+def _megatron_fma(a, b, c):+ """a * b + c as fma.rn.ftz.f32 (causal_conv1d tap accumulation)."""+ return tl.inline_asm_elementwise(+ asm="fma.rn.ftz.f32 $0, $1, $2, $3;",+ constraints="=r,r,r,r",+ args=(a, b, c),+ dtype=tl.float32,+ is_pure=True,+ pack=1,+ )+++@triton.jit+def _megatron_silu(x):+ """x / (1 + exp(-x)) as causal_conv1d's fast-math SiLU."""+ return tl.inline_asm_elementwise(+ asm="""{+.reg .f32 t;+mul.ftz.f32 t, $1, 0fBFB8AA3B;+ex2.approx.ftz.f32 t, t;+add.ftz.f32 t, t, 0f3F800000;+div.approx.ftz.f32 $0, $1, t;+}""",+ constraints="=r,r",+ args=(x,),+ dtype=tl.float32,+ is_pure=True,+ pack=1,+ )++ @triton.jit(do_not_specialize_on_alignment=["num_cache_lines"]) def _causal_conv1d_fwd_kernel( # continuous batching # Pointers to matrices@@ -452,7 +492,11 @@ def _causal_conv1d_fwd_kernel( # continuous batching x_ptrs_1d = x_base_1d + idx_token * stride_x_token # [BLOCK_N] matrix_x = tl.load(x_ptrs_1d, mask=mask_x_1d) - acc += matrix_x * matrix_w # [BLOCK_N]+ # Eka: fp32 FMA per tap, as causal_conv1d CUDA (Megatron). Upstream multiplied+ # bf16 x bf16 (a bf16 rounding per tap before the fp32 add).+ acc = _megatron_fma(+ matrix_x.to(tl.float32), matrix_w.to(tl.float32), acc+ ) # [BLOCK_N] if KERNEL_WIDTH == 2: col0 = matrix_x@@ -465,7 +509,7 @@ def _causal_conv1d_fwd_kernel( # continuous batching col2 = matrix_x if SILU_ACTIVATION:- acc = acc / (1 + tl.exp(-acc))+ acc = _megatron_silu(acc) # Eka: causal_conv1d fast-math SiLU mask_1d = (idx_token < segment_len) & ( idx_feats < dim ) # token-index # feature-index@@ -1058,7 +1102,11 @@ def _causal_conv1d_update_kernel( x_ptrs_1d = x_base_1d + idx_token * stride_x_token # [BLOCK_N] matrix_x = tl.load(x_ptrs_1d, mask=mask_x_1d) - acc += matrix_x * matrix_w # [BLOCK_N]+ # Eka: fp32 FMA per tap, as causal_conv1d CUDA (Megatron). Upstream multiplied+ # bf16 x bf16 (a bf16 rounding per tap before the fp32 add).+ acc = _megatron_fma(+ matrix_x.to(tl.float32), matrix_w.to(tl.float32), acc+ ) # [BLOCK_N] if KERNEL_WIDTH == 2: col0 = matrix_x@@ -1082,7 +1130,7 @@ def _causal_conv1d_update_kernel( col4 = matrix_x if SILU_ACTIVATION:- acc = acc / (1 + tl.exp(-acc))+ acc = _megatron_silu(acc) # Eka: causal_conv1d fast-math SiLU mask_1d = (idx_token < seqlen) & ( idx_feats < dim ) # token-index # feature-indexdiff --git a/vllm/model_executor/layers/mamba/ops/ssd_chunk_state.py b/vllm/model_executor/layers/mamba/ops/ssd_chunk_state.pyindex 79b47985d0..72a4dda1f7 100644--- a/vllm/model_executor/layers/mamba/ops/ssd_chunk_state.py+++ b/vllm/model_executor/layers/mamba/ops/ssd_chunk_state.py@@ -16,7 +16,9 @@ from .mamba_ssm import softplus @triton.autotune( configs=[- triton.Config({"BLOCK_SIZE_H": 2}),+ # Eka: BLOCK_SIZE_H=2 dropped. It rounds the dt cumsum differently from every+ # BLOCK_SIZE_H >= 4 (which are bit-identical to each other and to mamba_ssm /+ # Megatron), and autotune picks by speed, so the scan output changed run to run. triton.Config({"BLOCK_SIZE_H": 4}), triton.Config({"BLOCK_SIZE_H": 8}), triton.Config({"BLOCK_SIZE_H": 16}),vllm_patch/eka_v1.pyAdded+1107
vllm_patch/hotpatch_vllm.pyAdded+324
vllm_patch/test_hotpatch.pyAdded+195
vllm_patch/tests/test_eka_v1.pyAdded+86
vllm_patch/vllm-v0.31.0-eka-kernels.patchAdded+226