File size: 8,651 Bytes
536285f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/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 argparse
import json
import sys
from 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()