#!/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). Getting
Megatron-matching outputs needs more than registering the model, so the patch
has 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). All
edits are built before any file is written; after writing, a fresh interpreter
checks 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
# patch a vllm package dir
python hotpatch_vllm.py --model-url # fetch eka_v1.py instead of the local copy
"""
from __future__ import annotations
import argparse
import re
import subprocess
import sys
from pathlib import Path
from 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().parent
LOCAL_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 ModelRegistry
from vllm.model_executor.models.config import MODELS_CONFIG_MAP
from vllm.transformers_utils.model_arch_config_convertor import MODEL_ARCH_CONFIG_CONVERTORS
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig
import vllm.model_executor.layers.mamba.ops.causal_conv1d as conv
assert "{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()