File size: 6,451 Bytes
751b5ac | 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 | #!/usr/bin/env python3
"""Apply / revert source patches on an installed vLLM package.
Each patch step lives in ``steps/<name>.py`` and returns a list of file
operations (see ``steps/_ops.py``). The runner applies them to the target
vLLM package directory, keeps a backup of every touched file, and can
restore that backup with ``--revert``.
Usage:
python apply_patch.py --dry-run # print the unified diff only
python apply_patch.py # apply all steps
python apply_patch.py --steps ergo_nvfp4 # apply selected steps
python apply_patch.py --revert # restore backed-up files
python apply_patch.py --vllm-dir /path/to/site-packages/vllm ...
Without --vllm-dir the target is the ``vllm`` package found by the python
interpreter that runs this script (run it with the venv's python).
"""
from __future__ import annotations
import argparse
import difflib
import importlib
import importlib.util
import json
import re
import shutil
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from steps._ops import Copy, Edit # noqa: E402
# Order matters: later steps may edit files that earlier steps created.
ALL_STEPS = [
"ergo_nvfp4",
]
SUPPORTED_VLLM = "0.1.dev26190+g7fd7b0f93.d20261201"
BACKUP_DIRNAME = ".nota_patch_backup"
def find_vllm_dir() -> Path:
spec = importlib.util.find_spec("vllm")
if spec is None or spec.origin is None:
sys.exit("vllm not found; pass --vllm-dir or run with the venv python")
return Path(spec.origin).parent
def read_vllm_version(vllm_dir: Path) -> str:
# Read version without importing vllm (importing is slow and needs CUDA).
for dist in vllm_dir.parent.glob("vllm-*.dist-info"):
m = re.match(r"vllm-(.+)\.dist-info", dist.name)
if m:
return m.group(1)
v = vllm_dir / "_version.py"
if v.exists():
m = re.search(r"version = .*?['\"]([^'\"]+)", v.read_text())
if m:
return m.group(1)
return "unknown"
def render(ops, vllm_dir: Path) -> dict[str, tuple[str | None, str]]:
"""Return {relpath: (old_text or None, new_text)} after all ops."""
state: dict[str, tuple[str | None, str]] = {}
def current(rel: str) -> str:
if rel in state:
return state[rel][1]
p = vllm_dir / rel
if not p.exists():
raise FileNotFoundError(f"{rel}: target file does not exist")
return p.read_text()
def original(rel: str) -> str | None:
if rel in state:
return state[rel][0]
p = vllm_dir / rel
return p.read_text() if p.exists() else None
for op in ops:
if isinstance(op, Copy):
state[op.dst] = (original(op.dst), op.text)
elif isinstance(op, Edit):
text = current(op.path)
n = text.count(op.old)
if n != op.count:
raise RuntimeError(
f"{op.path}: anchor found {n} times (expected {op.count}).\n"
f" reason: {op.reason}\n anchor:\n{op.old}"
)
state[op.path] = (original(op.path), text.replace(op.old, op.new))
else:
raise TypeError(op)
return state
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--vllm-dir", type=Path)
ap.add_argument("--steps", nargs="+", default=ALL_STEPS, choices=ALL_STEPS)
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--revert", action="store_true")
ap.add_argument("--force", action="store_true", help="skip version check")
ap.add_argument("--diff-out", type=Path, help="also write the diff here")
args = ap.parse_args()
vllm_dir = (args.vllm_dir or find_vllm_dir()).resolve()
backup_dir = vllm_dir / BACKUP_DIRNAME
manifest_path = backup_dir / "manifest.json"
print(f"target vllm: {vllm_dir}")
if args.revert:
if not manifest_path.exists():
sys.exit("no backup manifest; nothing to revert")
manifest = json.loads(manifest_path.read_text())
for rel, existed in manifest["files"].items():
dst = vllm_dir / rel
if existed:
shutil.copy2(backup_dir / rel, dst)
print(f" restored {rel}")
else:
dst.unlink(missing_ok=True)
print(f" removed {rel}")
shutil.rmtree(backup_dir)
return
version = read_vllm_version(vllm_dir)
print(f"vllm version: {version}")
if version != SUPPORTED_VLLM and not args.force:
sys.exit(f"this patch targets vllm {SUPPORTED_VLLM}; use --force to try")
if manifest_path.exists():
steps = json.loads(manifest_path.read_text())["steps"]
sys.exit(f"already patched with steps {steps} (backup at {backup_dir}); "
"run --revert first")
ops = []
for name in args.steps:
mod = importlib.import_module(f"steps.{name}")
step_ops = mod.ops()
print(f"step {name}: {len(step_ops)} ops - {mod.DESCRIPTION}")
ops.extend(step_ops)
state = render(ops, vllm_dir)
diff = []
for rel, (old, new) in state.items():
diff.extend(
difflib.unified_diff(
(old or "").splitlines(keepends=True),
new.splitlines(keepends=True),
fromfile=f"a/vllm/{rel}" if old is not None else "/dev/null",
tofile=f"b/vllm/{rel}",
)
)
diff_text = "".join(diff)
if args.diff_out:
args.diff_out.write_text(diff_text)
print(f"diff written to {args.diff_out}")
if args.dry_run:
print(diff_text)
return
files = {}
for rel, (old, new) in state.items():
dst = vllm_dir / rel
files[rel] = old is not None
if old is not None:
(backup_dir / rel).parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(dst, backup_dir / rel)
dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_text(new)
print(f" {'patched' if old is not None else 'created'} {rel}")
manifest_path.parent.mkdir(parents=True, exist_ok=True)
manifest_path.write_text(
json.dumps({"steps": args.steps, "vllm": version, "files": files}, indent=2)
)
print(f"backup: {backup_dir}")
if __name__ == "__main__":
main()
|