servediff 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
servediff/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """servediff: diff what an LLM inference server actually ran with."""
2
+
3
+ from servediff.cli import diff, main, parse
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["diff", "main", "parse", "__version__"]
servediff/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from servediff.cli import main
4
+
5
+ sys.exit(main())
servediff/cli.py ADDED
@@ -0,0 +1,302 @@
1
+ """servediff: what did the inference server actually run with? Diff two server logs.
2
+
3
+ Benchmark result files record the client side only. The server's effective
4
+ configuration -- auto-selected attention/MoE backends, CUDA graph and compile
5
+ mode, the arguments it resolved -- is only printed in its startup log. This tool
6
+ extracts those facts from vLLM and SGLang logs and diffs two of them.
7
+
8
+ Every fact keeps the line it came from. A fact that is not in the log is reported
9
+ as absent, never filled with a default.
10
+
11
+ Usage:
12
+ servediff show <log>
13
+ servediff diff <baseline.log> <candidate.log> [--raw-args] [--json] [--all]
14
+ servediff env [--python /path/to/server/venv/bin/python] [-o env.json]
15
+ servediff diff <baseline-env.json> <candidate-env.json>
16
+ Exit codes: 0 no differences, 1 differences found, 2 nothing recognised in an input.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import ast
23
+ import json
24
+ import re
25
+ import sys
26
+ from dataclasses import dataclass, field
27
+ from pathlib import Path
28
+
29
+ from servediff import env as envsnap
30
+
31
+ ANSI = re.compile(r"\x1b\[[0-9;]*m")
32
+
33
+
34
+ @dataclass
35
+ class Fact:
36
+ values: list = field(default_factory=list) # distinct values in order seen
37
+ evidence: list = field(default_factory=list) # (line number, line text)
38
+
39
+ def add(self, value, lineno: int, line: str) -> None:
40
+ if value not in self.values:
41
+ self.values.append(value)
42
+ self.evidence.append((lineno, line.strip()[:300]))
43
+
44
+ @property
45
+ def value(self):
46
+ return self.values[0] if len(self.values) == 1 else self.values
47
+
48
+
49
+ # Patterns over one log line. Each yields (fact key, value) pairs.
50
+ LINE_RULES: list[tuple[re.Pattern, callable]] = [
51
+ # vLLM banner and engine init.
52
+ (re.compile(r"\bversion (\d+\.\d+\.\d+\S*)"), lambda m: [("engine.version", m[1])]),
53
+ (re.compile(r"Initializing a V1 LLM engine \(v([^)]+)\)"), lambda m: [("engine.version", m[1])]),
54
+ # vLLM: "Using FLASH_ATTN attention backend out of potential backends: [...]".
55
+ (re.compile(r"Using (\S+) attention backend"), lambda m: [("backend.attention", m[1])]),
56
+ (re.compile(r"Using FlashAttention version (\d+)"), lambda m: [("backend.flash_attn_version", m[1])]),
57
+ # vLLM MoE selection, three formats seen in the wild:
58
+ # Using 'VLLM_CUTLASS' NvFp4 MoE backend
59
+ # Using FlashInfer CUTLASS Unquantized MoE backend out of potential backends: [...]
60
+ # Using TrtLlmBf16ExpertsMonolithic MoE backend
61
+ (re.compile(r"Using '?([^']+?)'? (?:(NvFp4|Fp8|Unquantized|Mxfp4|Int4|W4A16) )?MoE backend"),
62
+ lambda m: [("backend.moe", m[1] if m[2] is None else f"{m[1]} ({m[2]})")]),
63
+ (re.compile(r"Using (MoEPrepareAndFinalize\w+)"), lambda m: [("backend.moe_prepare_finalize", m[1])]),
64
+ (re.compile(r"Enforce eager set"), lambda m: [("cuda_graph", "disabled (enforce_eager)"),
65
+ ("compile", "disabled (enforce_eager)")]),
66
+ (re.compile(r"cudagraph_mode[=:] ?'?(\w+)"), lambda m: [("cuda_graph.mode", m[1])]),
67
+ (re.compile(r"Enabled custom fusions: (.+)$"), lambda m: [("compile.fusions", m[1].strip())]),
68
+ # tqdm bars: "Capturing CUDA graphs (decode, FULL): 0%| 0/35"; one value per mode and size.
69
+ (re.compile(r"Capturing CUDA graphs \(([^)]+)\):\s+\d+%\|[^|]*\|\s*\d+/(\d+)"),
70
+ lambda m: [("cuda_graph.captures", f"{m[1]} x{m[2]}")]),
71
+ (re.compile(r"CUDA graph pool memory: ([\d.]+) GiB \(actual\)"),
72
+ lambda m: [("cuda_graph.pool_gib", float(m[1]))]),
73
+ (re.compile(r"FlashInfer top-p/top-k sampling (disabled|enabled)"),
74
+ lambda m: [("backend.sampling_flashinfer", m[1])]),
75
+ (re.compile(r"Using (V\d) Model Runner"), lambda m: [("model_runner", m[1])]),
76
+ (re.compile(r"Pinned memory is not available.*falling back to (.+?) for UVA buffers"),
77
+ lambda m: [("uva_buffers", f"fallback: {m[1]}")]),
78
+ # Startup outcome. Without it, facts missing after a crash look like "not printed".
79
+ (re.compile(r"Application startup complete"), lambda m: [("startup", "ready")]),
80
+ (re.compile(r"EngineCore failed to start|Engine core initialization failed"),
81
+ lambda m: [("startup", "failed")]),
82
+ (re.compile(r"^(?:\(\w+ pid=\d+\) )?(?:ERROR .*?\] )?((?:RuntimeError|ValueError|torch\.OutOfMemoryError|AssertionError): .+)$"),
83
+ lambda m: [("startup.error", m[1].strip())]),
84
+ # SGLang.
85
+ (re.compile(r"Disable prefill CUDA graph because"), lambda m: [("cuda_graph.prefill", "disabled")]),
86
+ (re.compile(r"The server is fired up and ready to roll"), lambda m: [("startup", "ready")]),
87
+ (re.compile(r"KV Cache is allocated\. dtype: (\S+?),"), lambda m: [("kv_cache.dtype", m[1])]),
88
+ ]
89
+
90
+ # Arguments that mean the same thing in both engines, mapped to one name.
91
+ # value: (vLLM non-default arg, SGLang server_arg, transform for SGLang value)
92
+ SHARED_ARGS = {
93
+ "model": ("model", "model_path", None),
94
+ "dtype": ("dtype", "dtype", None),
95
+ "max_model_len": ("max_model_len", "context_length", None),
96
+ "gpu_memory_fraction": ("gpu_memory_utilization", "mem_fraction_static", None),
97
+ "prefix_cache": ("enable_prefix_caching", "disable_radix_cache", lambda v: not v),
98
+ "cuda_graph.disabled": ("enforce_eager", "disable_cuda_graph", None),
99
+ "tensor_parallel_size": ("tensor_parallel_size", "tp_size", None),
100
+ "kv_cache_dtype": ("kv_cache_dtype", "kv_cache_dtype", None),
101
+ "backend.attention_arg": ("attention_backend", "attention_backend", None),
102
+ "backend.moe_arg": ("moe_backend", "moe_runner_backend", None),
103
+ "backend.sampling_arg": (None, "sampling_backend", None),
104
+ }
105
+
106
+
107
+ def _literal_dict(text: str) -> dict | None:
108
+ """Parse the `{...}` that starts `text`, tolerating trailing log text."""
109
+ depth, quote = 0, None
110
+ for i, ch in enumerate(text):
111
+ if quote:
112
+ if ch == quote and text[i - 1] != "\\":
113
+ quote = None
114
+ elif ch in "'\"":
115
+ quote = ch
116
+ elif ch in "{[(":
117
+ depth += 1
118
+ elif ch in "}])":
119
+ depth -= 1
120
+ if depth == 0:
121
+ try:
122
+ value = ast.literal_eval(text[: i + 1])
123
+ except (ValueError, SyntaxError):
124
+ return None
125
+ return value if isinstance(value, dict) else None
126
+ return None
127
+
128
+
129
+ def parse(text: str) -> dict:
130
+ facts: dict[str, Fact] = {}
131
+ args: dict = {}
132
+ engine = None
133
+
134
+ def put(key, value, lineno, line):
135
+ facts.setdefault(key, Fact()).add(value, lineno, line)
136
+
137
+ for lineno, raw in enumerate(text.splitlines(), 1):
138
+ line = ANSI.sub("", raw)
139
+ if "non-default args:" in line:
140
+ engine = engine or "vllm"
141
+ parsed = _literal_dict(line.split("non-default args:", 1)[1].strip())
142
+ if parsed is not None:
143
+ args.update(parsed)
144
+ put("args.source", "vllm non-default args", lineno, line)
145
+ elif "server_args=" in line:
146
+ engine = engine or "sglang"
147
+ parsed = _literal_dict(line.split("server_args=", 1)[1].strip())
148
+ if parsed is not None:
149
+ args.update(parsed)
150
+ put("args.source", "sglang server_args (all args)", lineno, line)
151
+ if engine is None and ("vllm" in line.lower() and "[" in line and ".py:" in line):
152
+ engine = "vllm"
153
+ for pattern, emit in LINE_RULES:
154
+ match = pattern.search(line)
155
+ if match:
156
+ for key, value in emit(match):
157
+ # Errors after the server reported ready (e.g. during shutdown) say
158
+ # nothing about how it started.
159
+ if key == "startup.error" and "ready" in (facts.get("startup") or Fact()).values:
160
+ key = "after_ready.error"
161
+ put(key, value, lineno, line)
162
+
163
+ if engine:
164
+ facts.setdefault("engine", Fact()).add(engine, 0, "(detected from log format)")
165
+ for name, (vllm_key, sglang_key, transform) in SHARED_ARGS.items():
166
+ key = vllm_key if engine == "vllm" else sglang_key
167
+ if key and key in args:
168
+ value = args[key]
169
+ if engine == "sglang" and transform:
170
+ value = transform(value)
171
+ if isinstance(value, list) and len(value) == 1:
172
+ value = value[0]
173
+ put(f"arg.{name}", value, 0, f"{'non-default args' if engine == 'vllm' else 'server_args'}[{key!r}]")
174
+ return {"engine": engine, "facts": facts, "args": args}
175
+
176
+
177
+ def _shown(fact: Fact | None):
178
+ return "<absent>" if fact is None else fact.value
179
+
180
+
181
+ def diff(a: dict, b: dict, raw_args: bool = False) -> list[dict]:
182
+ rows = []
183
+ for key in sorted(set(a["facts"]) | set(b["facts"])):
184
+ fa, fb = a["facts"].get(key), b["facts"].get(key)
185
+ va, vb = _shown(fa), _shown(fb)
186
+ if fa is None or fb is None:
187
+ status = "only_baseline" if fb is None else "only_candidate"
188
+ else:
189
+ status = "same" if va == vb else "changed"
190
+ rows.append({"key": key, "baseline": va, "candidate": vb, "status": status,
191
+ "evidence": {"baseline": fa.evidence if fa else [],
192
+ "candidate": fb.evidence if fb else []}})
193
+ if raw_args and a["engine"] == b["engine"]:
194
+ for key in sorted(set(a["args"]) | set(b["args"])):
195
+ va, vb = a["args"].get(key, "<absent>"), b["args"].get(key, "<absent>")
196
+ if va != vb:
197
+ rows.append({"key": f"raw_arg.{key}", "baseline": va, "candidate": vb,
198
+ "status": "changed", "evidence": {}})
199
+ return rows
200
+
201
+
202
+ def _fmt(value) -> str:
203
+ text = json.dumps(value, ensure_ascii=False) if not isinstance(value, str) else value
204
+ return text if len(text) <= 60 else text[:57] + "..."
205
+
206
+
207
+ def main(argv=None) -> int:
208
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
209
+ sub = parser.add_subparsers(dest="command", required=True)
210
+ show = sub.add_parser("show", help="effective config facts in one log")
211
+ show.add_argument("log", type=Path)
212
+ show.add_argument("--json", action="store_true")
213
+ d = sub.add_parser("diff", help="diff two server logs, or two `servediff env` snapshots")
214
+ d.add_argument("baseline", type=Path)
215
+ d.add_argument("candidate", type=Path)
216
+ d.add_argument("--raw-args", action="store_true", help="also diff every raw argument (same engine only)")
217
+ d.add_argument("--json", action="store_true")
218
+ d.add_argument("--all", action="store_true", help="also print unchanged facts")
219
+ e = sub.add_parser("env", help="snapshot package versions, GPU and engine env vars of a server environment")
220
+ e.add_argument("--python", help="interpreter of the server's environment (default: this one)")
221
+ e.add_argument("-o", "--output", type=Path, help="write JSON here instead of stdout")
222
+ args = parser.parse_args(argv)
223
+
224
+ if args.command == "env":
225
+ try:
226
+ snap = envsnap.snapshot(args.python)
227
+ except (RuntimeError, OSError) as exc:
228
+ print(f"servediff env: {exc}", file=sys.stderr)
229
+ return 2
230
+ text = json.dumps(snap, indent=2, ensure_ascii=False, sort_keys=True)
231
+ if args.output:
232
+ args.output.write_text(text + "\n", encoding="utf-8")
233
+ print(f"wrote {args.output}: {len(snap['packages'])} packages, {len(snap['env'])} env vars", file=sys.stderr)
234
+ else:
235
+ print(text)
236
+ return 0
237
+
238
+ if args.command == "show":
239
+ parsed = parse(args.log.read_text(encoding="utf-8", errors="replace"))
240
+ if not parsed["facts"]:
241
+ print(f"{args.log}: no vLLM or SGLang configuration lines recognised", file=sys.stderr)
242
+ return 2
243
+ if args.json:
244
+ print(json.dumps({k: {"value": f.value, "evidence": f.evidence} for k, f in parsed["facts"].items()},
245
+ indent=2, ensure_ascii=False))
246
+ else:
247
+ for key, fact in sorted(parsed["facts"].items()):
248
+ where = fact.evidence[0][0]
249
+ print(f"{key:32s} {_fmt(fact.value):60s} line {where if where else '-'}")
250
+ return 0
251
+
252
+ text_a = args.baseline.read_text(encoding="utf-8", errors="replace")
253
+ text_b = args.candidate.read_text(encoding="utf-8", errors="replace")
254
+ snaps = envsnap.is_snapshot(text_a), envsnap.is_snapshot(text_b)
255
+ if any(snaps):
256
+ if not all(snaps):
257
+ print("diff: give two server logs or two `servediff env` snapshots, not one of each", file=sys.stderr)
258
+ return 2
259
+ rows = envsnap.ranked(envsnap.diff(json.loads(text_a), json.loads(text_b)))
260
+ if args.json:
261
+ print(json.dumps({"differences": len(rows), "rows": rows}, indent=2, ensure_ascii=False))
262
+ else:
263
+ key = [r for r in rows if envsnap.is_key(r)]
264
+ shown = rows if args.all else key
265
+ print(f"{'fact':32s} {'baseline':40s} {'candidate':40s} status")
266
+ for r in shown:
267
+ print(f"{r['key']:32s} {_fmt(r['baseline'])[:40]:40s} {_fmt(r['candidate'])[:40]:40s} {r['status']}")
268
+ print(f"\n{len(key)} difference(s) in Python, GPU, inference packages and engine env vars;"
269
+ f" {len(rows) - len(key)} in other packages{'' if args.all else ' (--all to list them)'}.")
270
+ return 1 if rows else 0
271
+
272
+ a = parse(text_a)
273
+ b = parse(text_b)
274
+ for path, parsed in ((args.baseline, a), (args.candidate, b)):
275
+ if not parsed["facts"]:
276
+ print(f"{path}: no vLLM or SGLang configuration lines recognised", file=sys.stderr)
277
+ return 2
278
+ rows = diff(a, b, raw_args=args.raw_args)
279
+ if not args.all: # errors after "ready" (e.g. on shutdown) say nothing about the config
280
+ rows = [r for r in rows if not r["key"].startswith("after_ready.")]
281
+ differing = [r for r in rows if r["status"] != "same"]
282
+ if args.json:
283
+ print(json.dumps({"differences": len(differing), "rows": rows}, indent=2, ensure_ascii=False, default=str))
284
+ else:
285
+ if a["engine"] != b["engine"]:
286
+ print(f"note: comparing {a['engine']} with {b['engine']}; only shared facts line up\n")
287
+ for side, parsed in (("baseline", a), ("candidate", b)):
288
+ if "failed" in (parsed["facts"].get("startup") or Fact()).values:
289
+ error = parsed["facts"].get("startup.error")
290
+ print(f"warning: {side} server failed to start"
291
+ f"{': ' + _fmt(error.values[0]) if error else ''}; facts after the failure" # first = root cause
292
+ " are absent because startup stopped, not because they were off\n")
293
+ print(f"{'fact':32s} {'baseline':40s} {'candidate':40s} status")
294
+ for r in rows if args.all else differing:
295
+ print(f"{r['key']:32s} {_fmt(r['baseline'])[:40]:40s} {_fmt(r['candidate'])[:40]:40s} {r['status']}")
296
+ print(f"\n{len(differing)} difference(s); {len(rows) - len(differing)} fact(s) identical."
297
+ " Absent means the log did not print it, not that it was off.")
298
+ return 1 if differing else 0
299
+
300
+
301
+ if __name__ == "__main__":
302
+ sys.exit(main())
servediff/env.py ADDED
@@ -0,0 +1,111 @@
1
+ """Snapshot the environment a server runs in: package versions, GPU, relevant env vars.
2
+
3
+ Logs do not show dependency versions (torch, triton, flashinfer...), yet upgrades of
4
+ those change server behaviour. `snapshot()` runs a small stdlib-only probe under the
5
+ server's own interpreter, so nothing has to be installed into that environment.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+
17
+ SCHEMA = "servediff-env/1"
18
+
19
+ # Variables that steer inference engines. Values of names that look secret are redacted.
20
+ ENV_PREFIXES = ("VLLM_", "SGLANG_", "SGL_", "CUDA_", "NCCL_", "TORCH_", "PYTORCH_", "FLASHINFER_",
21
+ "TRITON_", "HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE")
22
+ SECRET = re.compile(r"TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH", re.I)
23
+
24
+ # Runs under the target interpreter: standard library only.
25
+ PROBE = r"""
26
+ import importlib.metadata as m, json, os, platform, sys
27
+ prefixes = tuple(json.loads(sys.argv[1])); secret = __import__("re").compile(sys.argv[2], 2)
28
+ pkgs = {}
29
+ for d in m.distributions():
30
+ name = (d.metadata["Name"] or "").lower().replace("_", "-")
31
+ if name:
32
+ pkgs[name] = d.version
33
+ env = {k: ("<redacted>" if secret.search(k) else v) for k, v in os.environ.items() if k.startswith(prefixes)}
34
+ print(json.dumps({"python": platform.python_version(), "executable": sys.executable,
35
+ "platform": platform.platform(), "packages": pkgs, "env": env}))
36
+ """
37
+
38
+
39
+ def _gpus() -> list[dict] | None:
40
+ if not shutil.which("nvidia-smi"):
41
+ return None
42
+ try:
43
+ out = subprocess.run(
44
+ ["nvidia-smi", "--query-gpu=name,driver_version,memory.total", "--format=csv,noheader,nounits"],
45
+ capture_output=True, text=True, timeout=20, check=True,
46
+ ).stdout
47
+ except (subprocess.SubprocessError, OSError):
48
+ return None
49
+ gpus = []
50
+ for line in out.strip().splitlines():
51
+ name, driver, memory = (part.strip() for part in line.split(","))
52
+ gpus.append({"name": name, "driver": driver, "memory_mib": int(float(memory))})
53
+ return gpus
54
+
55
+
56
+ def snapshot(python: str | None = None) -> dict:
57
+ # Not `-I`: it hides user site-packages, which the server itself would see.
58
+ # A neutral cwd keeps the caller's directory out of sys.path.
59
+ result = subprocess.run(
60
+ [python or sys.executable, "-c", PROBE, json.dumps(ENV_PREFIXES), SECRET.pattern],
61
+ capture_output=True, text=True, timeout=120, cwd=tempfile.gettempdir(),
62
+ )
63
+ if result.returncode != 0:
64
+ raise RuntimeError(f"environment probe failed under {python or sys.executable}: {result.stderr.strip()[-500:]}")
65
+ data = json.loads(result.stdout)
66
+ data["schema"] = SCHEMA
67
+ data["gpus"] = _gpus()
68
+ return data
69
+
70
+
71
+ def is_snapshot(text: str) -> bool:
72
+ try:
73
+ return json.loads(text).get("schema", "").startswith("servediff-env/")
74
+ except (ValueError, AttributeError):
75
+ return False
76
+
77
+
78
+ def diff(a: dict, b: dict) -> list[dict]:
79
+ rows = []
80
+
81
+ def add(key, va, vb):
82
+ if va != vb:
83
+ status = "only_candidate" if va is None else "only_baseline" if vb is None else "changed"
84
+ rows.append({"key": key, "baseline": "<absent>" if va is None else va,
85
+ "candidate": "<absent>" if vb is None else vb, "status": status})
86
+
87
+ add("python", a.get("python"), b.get("python"))
88
+ ga = [(g["name"], g["driver"]) for g in a.get("gpus") or []]
89
+ gb = [(g["name"], g["driver"]) for g in b.get("gpus") or []]
90
+ add("gpus", ga or None, gb or None)
91
+ for name in sorted(set(a["packages"]) | set(b["packages"])):
92
+ add(f"pkg.{name}", a["packages"].get(name), b["packages"].get(name))
93
+ for name in sorted(set(a["env"]) | set(b["env"])):
94
+ add(f"env.{name}", a["env"].get(name), b["env"].get(name))
95
+ return rows
96
+
97
+
98
+ # Packages whose version is most likely to change inference behaviour; shown first.
99
+ KEY_PACKAGES = re.compile(r"^pkg\.(vllm|sglang|sgl-kernel|torch|triton|flashinfer.*|xformers|deep-gemm|transformers|"
100
+ r"tokenizers|nvidia-.*|cuda-python|cuda-bindings|vllm-flash-attn|flash-attn|"
101
+ r"compressed-tensors|llguidance|xgrammar|outlines-core)$")
102
+
103
+
104
+ def is_key(row: dict) -> bool:
105
+ key = row["key"]
106
+ return key in ("python", "gpus") or key.startswith("env.") or bool(KEY_PACKAGES.match(key))
107
+
108
+
109
+ def ranked(rows: list[dict]) -> list[dict]:
110
+ """Python and GPU first, then key inference packages and env vars, then everything else."""
111
+ return sorted(rows, key=lambda r: (0 if r["key"] in ("python", "gpus") else 1 if is_key(r) else 2, r["key"]))
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.4
2
+ Name: servediff
3
+ Version: 0.1.0
4
+ Summary: Diff what your vLLM / SGLang server actually ran with: auto-selected backends, CUDA graphs, startup failures, dependency versions.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/apex-mochen/servediff
7
+ Project-URL: Issues, https://github.com/apex-mochen/servediff/issues
8
+ Project-URL: Changelog, https://github.com/apex-mochen/servediff/blob/main/CHANGELOG.md
9
+ Keywords: vllm,sglang,llm-inference,performance-regression,debugging
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Software Development :: Debuggers
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=8; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # servediff
23
+
24
+ **Same flags, different server.** `servediff` shows what your vLLM or SGLang server
25
+ *actually* ran with — and what changed between two runs.
26
+
27
+ Benchmark result files only record the client side. After an upgrade, the server can
28
+ silently pick a different MoE or attention backend, change its CUDA graph capture,
29
+ fall back to another code path, or run against different torch / triton / flashinfer
30
+ builds. Today you find that by reading startup logs and bisecting by hand.
31
+ `servediff` does the reading for you.
32
+
33
+ - **Who it is for:** anyone comparing two vLLM / SGLang runs — after an upgrade, a flag
34
+ change, or between machines — who needs to know *what differs on the server side*.
35
+ - **What it reads:** the server's startup log, and optionally a snapshot of the
36
+ server's Python environment. Offline, no GPU, no dependencies.
37
+ - **What it does not do:** it does not say *which* difference caused a performance
38
+ change. That still needs an A/B run. It tells you what to A/B.
39
+
40
+ ## Try it in one minute (no GPU)
41
+
42
+ ```bash
43
+ git clone https://github.com/apex-mochen/servediff && cd servediff
44
+ pip install .
45
+ servediff diff examples/issue-excerpts/vllm-47047-v0.23-default.log examples/issue-excerpts/vllm-47047-v0.23-marlin.log
46
+ ```
47
+
48
+ ```text
49
+ fact baseline candidate status
50
+ backend.moe VLLM_CUTLASS (NvFp4) MARLIN (NvFp4) changed
51
+
52
+ 1 difference(s); 0 fact(s) identical. Absent means the log did not print it, not that it was off.
53
+ ```
54
+
55
+ That is the difference the reporter of
56
+ [vllm#47047](https://github.com/vllm-project/vllm/issues/47047) found by hand after a
57
+ v0.21 → v0.23 throughput drop. The example files are the log lines posted in that
58
+ issue (see [tests/fixtures/README.md](https://github.com/apex-mochen/servediff/blob/main/tests/fixtures/README.md)).
59
+
60
+ ## Real example: same flags, vLLM 0.28.0 vs 0.30.0
61
+
62
+ Two startup logs from one RTX 4060 Laptop under WSL2, identical flags
63
+ (Qwen2.5-0.5B-Instruct, fp16, `--max-model-len 2048`, `--gpu-memory-utilization 0.45`):
64
+
65
+ ```bash
66
+ servediff diff vllm-0.28.0.log vllm-0.30.0.log
67
+ ```
68
+
69
+ ```text
70
+ warning: baseline server failed to start: RuntimeError: UVA is not available; facts after the failure are absent because startup stopped, not because they were off
71
+
72
+ fact baseline candidate status
73
+ backend.attention <absent> FLASH_ATTN only_candidate
74
+ backend.flash_attn_version <absent> 2 only_candidate
75
+ backend.sampling_flashinfer <absent> disabled only_candidate
76
+ cuda_graph.captures <absent> ["PIECEWISE x51", "FULL x2", "FULL x35"] only_candidate
77
+ cuda_graph.pool_gib <absent> 0.17 only_candidate
78
+ engine.version 0.28.0 0.30.0 changed
79
+ startup failed ready changed
80
+ startup.error ["RuntimeError: UVA is not available", " <absent> only_baseline
81
+ uva_buffers <absent> fallback: device memory only_candidate
82
+
83
+ 9 difference(s); 8 fact(s) identical. Absent means the log did not print it, not that it was off.
84
+ ```
85
+
86
+ 0.28.0 does not start on WSL2 with default settings; 0.30.0 does, because it falls
87
+ back to device memory when pinned memory is unavailable. Upstream fixed this in
88
+ [vllm#56908](https://github.com/vllm-project/vllm/pull/56908), first released in
89
+ v0.30.0. Forcing the V1 model runner on 0.28.0 (`VLLM_USE_V2_MODEL_RUNNER=0`) makes it
90
+ start, and the remaining server-side differences are:
91
+
92
+ ```text
93
+ fact baseline candidate status
94
+ cuda_graph.captures ["mixed prefill-decode, PIECEWISE x51", ["PIECEWISE x51", "FULL x2", "FULL x35"] changed
95
+ cuda_graph.pool_gib 0.36 0.17 changed
96
+ engine.version 0.28.0 0.30.0 changed
97
+ model_runner <absent> V2 only_candidate
98
+ uva_buffers <absent> fallback: device memory only_candidate
99
+
100
+ 5 difference(s); 11 fact(s) identical. Absent means the log did not print it, not that it was off.
101
+ ```
102
+
103
+ ## Dependency versions: `servediff env`
104
+
105
+ Logs do not print torch / triton / flashinfer versions, and upgrades of those change
106
+ server behaviour too. Snapshot each server environment with its own interpreter —
107
+ nothing needs to be installed into it:
108
+
109
+ ```bash
110
+ servediff env --python /path/to/old-venv/bin/python -o old.json
111
+ servediff env --python /path/to/new-venv/bin/python -o new.json
112
+ servediff diff old.json new.json
113
+ ```
114
+
115
+ Excerpt from the same two environments (20 inference-relevant rows; 74 other packages
116
+ hidden unless you pass `--all`):
117
+
118
+ ```text
119
+ pkg.flashinfer-python 0.6.16.post3 0.6.18.post1 changed
120
+ pkg.nvidia-cuda-nvcc 13.3.73 13.0.88 changed
121
+ pkg.nvidia-cutlass-dsl 4.6.2 4.7.1 changed
122
+ pkg.torch 2.13.0 2.13.0+cu130 changed
123
+ pkg.transformers 5.16.1 5.17.0 changed
124
+ pkg.vllm 0.28.0 0.30.0 changed
125
+ ```
126
+
127
+ Note the older vLLM environment carries *newer* CUDA toolkit wheels (13.3 vs 13.0).
128
+ Whether that matters for performance is not known — that is what an A/B run is for.
129
+ Versions are read from package metadata, so the same torch build can show as `2.13.0`
130
+ in one environment and `2.13.0+cu130` in another.
131
+
132
+ The snapshot records Python, GPU name and driver (via `nvidia-smi`), all installed
133
+ package versions, and env vars starting with `VLLM_`, `SGLANG_`, `SGL_`, `CUDA_`,
134
+ `NCCL_`, `TORCH_`, `PYTORCH_`, `FLASHINFER_`, `TRITON_`. Values of variables whose name
135
+ contains `TOKEN`, `KEY`, `SECRET`, `PASSWORD`, `CREDENTIAL` or `AUTH` are replaced with
136
+ `<redacted>`. Snapshots and logs contain local paths: review them before sharing.
137
+
138
+ ## What it extracts
139
+
140
+ | Fact | vLLM | SGLang |
141
+ |---|---|---|
142
+ | version | banner / engine init | — (not printed) |
143
+ | arguments | `non-default args` | `server_args` (all args) |
144
+ | attention backend | `Using X attention backend` | `attention_backend` arg |
145
+ | MoE backend | three log formats seen in 0.23–0.30 | `moe_runner_backend` arg |
146
+ | CUDA graph | eager mode, `cudagraph_mode`, capture sets, pool size | prefill CUDA graph disabled |
147
+ | model runner, UVA fallback | `Using V2 Model Runner`, pinned-memory fallback | — |
148
+ | startup outcome | ready / failed + root-cause error | ready |
149
+
150
+ Every fact keeps the log line it came from (`servediff show <log>` or `--json`).
151
+ A fact the log did not print is `<absent>`: servediff never fills in defaults.
152
+ Options shared by both engines (dtype, context length, memory fraction, prefix cache,
153
+ CUDA graph, TP size) are mapped to common names, so a vLLM log and an SGLang log can be
154
+ compared, though the result is noisier than a same-engine diff.
155
+
156
+ Exit codes: `0` no differences, `1` differences, `2` nothing recognised.
157
+
158
+ ## Limits
159
+
160
+ - Tested on: log excerpts posted in vllm#47047 (v0.23) and vllm#53472 (v0.23, v0.26);
161
+ full startup logs of vLLM 0.28.0 and 0.30.0 and one SGLang log, all single-GPU with a
162
+ dense model. TP > 1, MoE models in full logs, and other versions are not yet verified.
163
+ - Parsing is regex-based on log text, which changes between versions. A missed line
164
+ shows up as `<absent>`, never as a wrong value — please report it.
165
+
166
+ ## License
167
+
168
+ Apache-2.0.
@@ -0,0 +1,10 @@
1
+ servediff/__init__.py,sha256=BlZahw9q-J1J_yBDzTlFWb8wWKiMt3a9KqYq1MdPvts,189
2
+ servediff/__main__.py,sha256=C9ZV0To-Mbv-Ko-lwbXvJ68zKJF7Z_6UJp-bVeg_6XM,61
3
+ servediff/cli.py,sha256=y6c6d7YSIZruBElWmm6hzJIGyWhQEKobmC_t0DGuc0Q,15061
4
+ servediff/env.py,sha256=0IMgI8GdXcCs_xNm88SCqs66GsAS2KPezGHENjJJGmc,4644
5
+ servediff-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
6
+ servediff-0.1.0.dist-info/METADATA,sha256=haRGvDvaMjpYOtKh8DbVUnILlq8eb6bwvtKDeiil8F0,9483
7
+ servediff-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ servediff-0.1.0.dist-info/entry_points.txt,sha256=FG1eHJxmZNqphvfSEltaumscJyJq0WGR9kqxChbODUI,49
9
+ servediff-0.1.0.dist-info/top_level.txt,sha256=TADHNtBMOkA7WSJj_wjkF7j8Vw558QWox5gTdIhghQs,10
10
+ servediff-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ servediff = servediff.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ servediff