File size: 6,270 Bytes
04e6078
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""vllm-patch.py - fixes needed to serve our AutoRound mixed-bit checkpoints on stock vLLM 0.32 / 0.33.

Two bugs in vLLM itself, identified while validating sibling mixed-bit checkpoints; each patch is a few lines,
idempotent, keeps a `<file>.orig` backup, and reports "not applicable" if upstream already fixed it.

  1. inc-routed-experts   quantization/inc/config_parser.py
     INC resolves the bit-width of a fused MoE layer by gathering our per-expert `extra_config` keys, but
     only when the layer's class name contains "fusedmoe". The class is now `RoutedExperts`, so the branch
     is skipped, every MoE layer falls back to the GLOBAL bits (4) and the W3 experts are allocated with
     4-bit containers (+~13 GiB: OOM before the weights are even read).

  2. kda-eager-break      model_executor/models/bailing_moe_v3.py
     `bailing_v3_kda_attention` does host-syncing work (boolean-mask indexing, chunk metadata). With the
     breakable-CUDA-graph capture it must be registered through `eager_break_during_capture`, like the other
     GDN/KDA ops; otherwise graph capture dies with cudaErrorStreamCaptureUnsupported.

Usage (run with the python of the vLLM environment you serve with, or point at its site-packages):

  vllm-patch.py                         # apply to the vLLM importable by this interpreter
  vllm-patch.py --vllm-dir DIR          # DIR = .../site-packages/vllm
  vllm-patch.py --check                 # report status only (exit 1 if a needed patch is missing)
  vllm-patch.py --revert                # restore the .orig backups

Checkpoint side (not a vLLM patch): the exported config.json must carry "model_type": "bailing_hybrid"
(vLLM detects MLA from it). v3/fix_config.py does that in the quantization pipeline.
"""
import argparse
import ast
import importlib.util
import os
import shutil
import sys

PATCHES = [
    {
        "name": "inc-routed-experts",
        "file": "model_executor/layers/quantization/inc/config_parser.py",
        "marker": "routedexperts",
        "edits": [(
            'if self._config.extra_config and "fusedmoe" in layer.__class__.__name__.lower():',
            'if self._config.extra_config and any(\n'
            '            k in layer.__class__.__name__.lower() for k in ("fusedmoe", "routedexperts")\n'
            '        ):  # vLLM renamed FusedMoE -> RoutedExperts; the old check silently skipped per-expert bits',
        )],
    },
    {
        "name": "kda-eager-break",
        "file": "model_executor/models/bailing_moe_v3.py",
        "marker": "eager_break_during_capture",
        "requires": "compilation/breakable_cudagraph.py",
        "edits": [
            (
                "from vllm.utils.torch_utils import direct_register_custom_op\n",
                "from vllm.compilation.breakable_cudagraph import eager_break_during_capture\n"
                "from vllm.utils.torch_utils import direct_register_custom_op\n",
            ),
            (
                'direct_register_custom_op(\n    op_name="bailing_v3_kda_attention",\n    op_func=bailing_v3_kda_attention,',
                "# The KDA state update does host-syncing work (boolean-mask indexing, chunk metadata), which is\n"
                "# illegal inside CUDA graph capture: make it a break point of the breakable-cudagraph capture,\n"
                "# like the other GDN/KDA ops (otherwise: cudaErrorStreamCaptureUnsupported).\n"
                'direct_register_custom_op(\n    op_name="bailing_v3_kda_attention",\n'
                "    op_func=eager_break_during_capture(bailing_v3_kda_attention),",
            ),
        ],
    },
]


def find_vllm_dir():
    spec = importlib.util.find_spec("vllm")          # finds the package without importing it
    if spec is None or not spec.submodule_search_locations:
        sys.exit("vllm not importable by this python; pass --vllm-dir .../site-packages/vllm")
    return list(spec.submodule_search_locations)[0]


def status(root, p):
    path = os.path.join(root, p["file"])
    if not os.path.isfile(path):
        return path, "n/a", "file not present in this vLLM"
    if "requires" in p and not os.path.isfile(os.path.join(root, p["requires"])):
        return path, "n/a", f"{p['requires']} missing (older vLLM without breakable cudagraph)"
    src = open(path).read()
    if p["marker"] in src:
        return path, "applied", "already patched"
    if not all(old in src for old, _ in p["edits"]):
        return path, "n/a", "anchor text not found (fixed upstream or code changed)"
    return path, "pending", "needs patch"


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--vllm-dir", help="path of the vllm package (site-packages/vllm)")
    ap.add_argument("--check", action="store_true", help="only report status")
    ap.add_argument("--revert", action="store_true", help="restore the .orig backups")
    a = ap.parse_args()
    root = os.path.abspath(a.vllm_dir) if a.vllm_dir else find_vllm_dir()
    ver = ""
    for d in os.listdir(os.path.dirname(root)):
        if d.startswith("vllm-") and d.endswith(".dist-info"):
            ver = d[5:-10]
    print(f"vLLM {ver or '?'} at {root}")

    missing = 0
    for p in PATCHES:
        path, st, why = status(root, p)
        if a.revert:
            if os.path.isfile(path + ".orig"):
                shutil.copy2(path + ".orig", path)
                print(f"  [{p['name']}] reverted from {os.path.basename(path)}.orig")
            else:
                print(f"  [{p['name']}] nothing to revert (no .orig)")
            continue
        if st == "pending" and not a.check:
            src = open(path).read()
            for old, new in p["edits"]:
                src = src.replace(old, new, 1)
            ast.parse(src)                                   # never write a file that does not parse
            if not os.path.exists(path + ".orig"):
                shutil.copy2(path, path + ".orig")
            open(path, "w").write(src)
            st, why = "applied", "patched now"
        print(f"  [{p['name']}] {st}: {why}")
        missing += st == "pending"
    if a.check:
        sys.exit(1 if missing else 0)


if __name__ == "__main__":
    main()