From 576f693e56f7c3f16f08de356b991cfd99f1fd05 Mon Sep 17 00:00:00 2001 From: 0chencc <19362246+0Chencc@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:14:37 +0900 Subject: [PATCH] feat: add sampling-path and temperature=0 diagnostics across analyze, diff, and sibyl-audit - Add ledger/sampling.py to classify greedy vs. stochastic sampling kernels, detect lm_head + logits-sized DtoH host-fallback sampling, compare sampling modes across captures, and audit Sibyl deployment profile sampling_policy. - Wire sampling diagnostics and ## Sampling into ledger analyze (and ensure zero-ms Findings notes render even when no >0.5 ms timing finding exists). - Flag greedy vs. stochastic or temperature mismatches in ledger diff. - Add --profile and --fail-on-sampling to ledger sibyl-audit to catch sampling_default_temperature=0 / sampling_thinking_temperature=0 and profile-vs-kernel mismatches. - Add --temperature / --top-p flags and run.json recording to ledger profile, examples/vllm_decode.py, and ledger ascend-import. - Add tests/test_sampling.py covering all diagnostic paths. --- CHANGELOG.md | 8 + examples/vllm_decode.py | 20 ++- ledger/analyze.py | 14 +- ledger/ascend_import.py | 10 ++ ledger/diff.py | 11 +- ledger/profile.py | 9 +- ledger/sampling.py | 366 ++++++++++++++++++++++++++++++++++++++++ ledger/sibyl_audit.py | 75 +++++++- tests/test_sampling.py | 232 +++++++++++++++++++++++++ 9 files changed, 734 insertions(+), 11 deletions(-) create mode 100644 ledger/sampling.py create mode 100644 tests/test_sampling.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ace0af5..5825f66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +- Sampling-path and `temperature=0` diagnostics (`ledger/sampling.py`): `ledger analyze` adds a + `## Sampling` section and flags silent `temp=0` fallback (configured `temperature > 0` with only + greedy sampling kernels), logits-sized `DtoH` host-fallback sampling after `lm_head`, and greedy + `temperature=0` decode runs; `ledger diff` warns on greedy vs. stochastic or temperature + mismatches between runs; `ledger sibyl-audit` audits Sibyl `profile.json` `sampling_policy` for + zero default/thinking temperatures (`--profile`, `--fail-on-sampling`); `ledger profile`, + `examples/vllm_decode.py`, and `ledger ascend-import` accept and record `--temperature` / + `--top-p` in `run.json`. - Multi-GPU `vllm serve` captures (tensor and pipeline parallelism): `ledger report` writes one report per GPU worker under `pid-/`, and the analysis refuses to merge the records of several processes into one set of books. Step markers of pipeline ticks without a forward pass are folded diff --git a/examples/vllm_decode.py b/examples/vllm_decode.py index b75d766..4755b63 100644 --- a/examples/vllm_decode.py +++ b/examples/vllm_decode.py @@ -87,6 +87,9 @@ def main(): own.add_argument("--warmup", type=int, default=8) own.add_argument("--prompt-tokens", type=int, default=0, help="prompt length of every request") own.add_argument("--prefill", type=int, default=0, help="time one step prefilling an N-token prompt") + own.add_argument("--temperature", type=float, default=0.0, help="sampling temperature (0 = greedy)") + own.add_argument("--top-p", type=float, default=1.0, help="nucleus sampling top_p") + own.add_argument("--seed", type=int, default=0, help="sampling RNG seed") own.add_argument("--nvml-ms", type=float, default=10, help="NVML sampling period; 0 turns it off") split = sys.argv.index("--") if "--" in sys.argv else len(sys.argv) opts = own.parse_args(sys.argv[1:split]) @@ -94,7 +97,13 @@ def main(): args = EngineArgs.from_cli_args(parser.parse_args(sys.argv[split + 1 :])) llm = LLM(**{f.name: getattr(args, f.name) for f in dataclasses.fields(args)}) - params = SamplingParams(max_tokens=8 * (opts.steps + opts.warmup) + 64, ignore_eos=True, temperature=0) + params = SamplingParams( + max_tokens=8 * (opts.steps + opts.warmup) + 64, + ignore_eos=True, + temperature=opts.temperature, + top_p=opts.top_p, + seed=opts.seed, + ) llm.generate([PROMPT], SamplingParams(max_tokens=16, ignore_eos=True)) # compile / capture warm-up out_dir = os.environ.get("LEDGER_OUT", "ledger-out") os.makedirs(out_dir, exist_ok=True) @@ -117,7 +126,11 @@ def step(): for _ in range(opts.warmup): step() if opts.prefill: - eng.add_request("ledger-prefill", token_prompt(llm, opts.prefill), SamplingParams(max_tokens=1, temperature=0)) + eng.add_request( + "ledger-prefill", + token_prompt(llm, opts.prefill), + SamplingParams(max_tokens=1, temperature=opts.temperature, top_p=opts.top_p, seed=opts.seed), + ) sampler = Sampler(opts.nvml_ms / 1e3) records = [] torch.cuda.synchronize() @@ -142,7 +155,8 @@ def step(): props = torch.cuda.get_device_properties(torch.cuda.current_device()) run = {"steps": opts.steps, "batch": opts.batch, "ms_per_step": round(ms, 3), "draft_tokens": getattr(spec, "num_speculative_tokens", 0) or 0, "prefill": opts.prefill, - "prompt_tokens": opts.prompt_tokens, "sms": props.multi_processor_count, "device": props.name} + "prompt_tokens": opts.prompt_tokens, "temperature": opts.temperature, "top_p": opts.top_p, + "sms": props.multi_processor_count, "device": props.name} with open(os.path.join(out_dir, "run.json"), "w") as f: json.dump(run, f) with open(os.path.join(out_dir, "steps.jsonl"), "w") as f: diff --git a/ledger/analyze.py b/ledger/analyze.py index d88d645..b51cab5 100644 --- a/ledger/analyze.py +++ b/ledger/analyze.py @@ -38,6 +38,8 @@ import sys from collections import Counter, defaultdict +from ledger import sampling + def read_jsonl(pattern): for path in sorted(glob.glob(pattern)): @@ -571,6 +573,9 @@ def report(capture, ceiling, steps, out, peaks=None, sms=None): + ", ".join(f"`{n}` ×{c / steps:.1f}/step" for n, c in gathered.most_common(5)) + "\n") collectives(rows, steps, pretty, emit) + sampling_info = sampling.inspect_capture(capture, rows, run, steps, pretty) + findings.extend(sampling_info["findings"]) + sampling.format_section(sampling_info, pretty, emit) if sms: for alone_ms, name, grid, gbps in underfilled(rows, steps, sms, pretty, emit): # A launch streaming near the ceiling loses little to idle SMs; otherwise count their share. @@ -585,11 +590,14 @@ def report(capture, ceiling, steps, out, peaks=None, sms=None): notes = [text for ms, text in findings if ms == 0] top = sorted((f for f in findings if f[0] > 0), key=lambda x: -x[0])[:5] summary = ["## Findings\n"] - if top: + if top or notes: summary += [f"- **{ms:.2f} ms per step**: {text}" for ms, text in top] summary += [f"- {text}" for text in notes] - summary.append("\nEach is the time the item costs against its reference, an upper bound on what fixing it " - "saves; the section named in parentheses has the details.\n") + if top: + summary.append("\nEach is the time the item costs against its reference, an upper bound on what fixing it " + "saves; the section named in parentheses has the details.\n") + else: + summary.append("") else: summary.append("Nothing above 0.5 ms per step.\n") lines[findings_at:findings_at] = summary diff --git a/ledger/ascend_import.py b/ledger/ascend_import.py index 2ecc62b..3a3aa56 100644 --- a/ledger/ascend_import.py +++ b/ledger/ascend_import.py @@ -320,6 +320,8 @@ def import_capture( batch=1, draft_tokens=0, prefill=0, + temperature=None, + top_p=None, ): """Convert an Ascend msprof export into a standard Ledger capture directory.""" op_csv = _find_csv(source, "op_summary") @@ -390,6 +392,10 @@ def import_capture( "prefill": prefill, "sms": sms, } + if temperature is not None: + run_meta["temperature"] = temperature + if top_p is not None: + run_meta["top_p"] = top_p with open(os.path.join(out_dir, "run.json"), "w") as f: json.dump(run_meta, f, indent=2) f.write("\n") @@ -434,6 +440,8 @@ def main(): ap.add_argument("--batch", type=int, default=1, help="batch size in run.json") ap.add_argument("--draft-tokens", type=int, default=0, help="speculative draft tokens per request") ap.add_argument("--prefill", type=int, default=0, help="prefill token count (0 for decode)") + ap.add_argument("--temperature", type=float, default=None, help="configured sampling temperature written to run.json") + ap.add_argument("--top-p", type=float, default=None, help="configured sampling top_p written to run.json") a = ap.parse_args() summary = import_capture( a.source, @@ -450,6 +458,8 @@ def main(): batch=a.batch, draft_tokens=a.draft_tokens, prefill=a.prefill, + temperature=a.temperature, + top_p=a.top_p, ) print( f"{summary['kernels']} kernels ({summary['matched_nodes']} with aclGraph params), " diff --git a/ledger/diff.py b/ledger/diff.py index 4bbfc8b..fc00b06 100644 --- a/ledger/diff.py +++ b/ledger/diff.py @@ -19,6 +19,7 @@ from collections import defaultdict from ledger import analyze as A +from ledger import sampling from ledger.steps import load_steps @@ -35,7 +36,8 @@ def groups(capture, ceiling): what = A.group_name(r["weights"][0]["name"]) if r["weight_bytes"] >= 1 << 20 else "" out[(r["name"], r["grid"], what)].append(r["us"]) _, busy = A.busy_and_gaps(rows) - return out, steps, busy / steps / 1e6, run + samp = sampling.inspect_capture(capture, rows, run, steps) + return out, steps, busy / steps / 1e6, run, samp def weighted_median(pairs): @@ -85,8 +87,8 @@ def check_gate(busy_a, busy_b, group_deltas, pretty, variants, fail_above, fail_ def report(a, b, ceiling, min_ms, tolerance, out, fail_above=None, fail_min_ms=0.5): - ga, sa, busy_a, run_a = groups(a, ceiling) - gb, sb, busy_b, run_b = groups(b, ceiling) + ga, sa, busy_a, run_a, samp_a = groups(a, ceiling) + gb, sb, busy_b, run_b, samp_b = groups(b, ceiling) pretty = A.demangle([k[0] for k in set(ga) | set(gb)]) per = lambda us, s: sum(us) / s / 1e3 # noqa: E731 ms per step # A kernel whose template arguments changed (a state dtype, say) keeps its short name: pair groups @@ -120,6 +122,9 @@ def report(a, b, ceiling, min_ms, tolerance, out, fail_above=None, fail_min_ms=0 same = tokens_equal(a, b) if same is not None: emit(f"Generated tokens: {'identical' if same else 'different'}.\n") + mismatch = sampling.compare_sampling(samp_a, samp_b) + if mismatch: + emit(f"{mismatch}\n") changed = [] group_deltas = [] diff --git a/ledger/profile.py b/ledger/profile.py index eeadf34..418b878 100644 --- a/ledger/profile.py +++ b/ledger/profile.py @@ -164,6 +164,9 @@ def profile_options(args): parser.add_argument("--batch", type=int, default=1) parser.add_argument("--prompt-tokens", type=int, default=0) parser.add_argument("--prefill", type=int, default=0) + parser.add_argument("--temperature", type=float, default=0.0, help="sampling temperature (0 = greedy)") + parser.add_argument("--top-p", type=float, default=1.0, help="nucleus sampling top_p") + parser.add_argument("--seed", type=int, default=0, help="sampling RNG seed") parser.add_argument("--out", type=Path, default=Path("ledger-out"), help="new or empty capture directory (default: %(default)s)") split = args.index("--") if "--" in args else len(args) @@ -173,6 +176,8 @@ def profile_options(args): parser.error("pass vLLM arguments after --") if opts.steps < 1 or opts.batch < 1 or opts.prompt_tokens < 0 or opts.prefill < 0: parser.error("--steps and --batch must be positive, and token counts must be nonnegative") + if opts.temperature < 0 or not (0 < opts.top_p <= 1.0): + parser.error("--temperature must be non-negative and --top-p must be in (0, 1]") return opts, vllm_args @@ -182,7 +187,9 @@ def capture(opts, vllm_args, library, out): env["LD_PRELOAD"] = ":".join(filter(None, (str(library), env.get("LD_PRELOAD")))) runner = ceilings.source_dir("examples") / "vllm_decode.py" command = [sys.executable, "-u", runner, "--steps", str(opts.steps), "--batch", str(opts.batch), - "--prompt-tokens", str(opts.prompt_tokens), "--prefill", str(opts.prefill), "--", *vllm_args] + "--prompt-tokens", str(opts.prompt_tokens), "--prefill", str(opts.prefill), + "--temperature", str(opts.temperature), "--top-p", str(opts.top_p), "--seed", str(opts.seed), + "--", *vllm_args] log = out / "vllm.log" print(f"Capturing vLLM output in {log}", flush=True) try: diff --git a/ledger/sampling.py b/ledger/sampling.py new file mode 100644 index 0000000..beda823 --- /dev/null +++ b/ledger/sampling.py @@ -0,0 +1,366 @@ +"""Sampling-path and temperature accounting for Ledger captures and Sibyl profiles. + +Detects three failure modes that distort benchmarks or silently corrupt model output: + 1. Config vs. kernel mismatch: `run.json` records `temperature > 0`, yet only greedy + kernels (`greedy_verify_bf16`, `argmax`, ...) executed. + 2. Host-fallback sampling: `lm_head` ran on device followed by full-vocabulary `DtoH` + copies (>= 256 KiB) with no device sampling kernel. + 3. Zero-temperature deployment profiles: Sibyl `profile.json` sets + `sampling_default_temperature=0` or `sampling_thinking_temperature=0`, silently forcing + greedy decoding on omitted temperatures and all thinking turns. +""" + +import json +import math +import os +import statistics +from collections import defaultdict + +# Minimum single DtoH copy size considered a vocabulary-logits transfer (e.g. 128K x BF16 = 256 KiB). +# Normal token-ID readbacks are tens of bytes (4-64 B). +LOGITS_DTOH_MIN_BYTES = 256 * 1024 + +_NON_SAMPLING_EXCLUSIONS = ( + "topkgating", + "topk_gating", + "moe_align", + "moe_routing", + "routing", + "indexer", + "flashattention", + "paged_attention", +) + +_GREEDY_PATTERNS = ( + "greedy_verify", + "greedy_sample", + "rejection_greedy", + "_argmax_partial", + "_argmax_finish", + "argmax_kernel", + "argmaxops", + "argmax_v2", +) + +_STOCHASTIC_PATTERNS = ( + "sample_verify", + "gumbel_sample", + "gumbel_combine", + "top_p_sampling", + "toppsampling", + "top_k_sampling", + "topksampling", + "top_k_top_p_sampling", + "topktoppsampling", + "min_p_sampling", + "minpsampling", + "sampling_from_probs", + "samplingfromprobs", + "sample_with_temperature", + "apply_temperature", + "rejection_random_sample", + "multinomial_sample", +) + +_PROFILE_SAMPLING_DEFAULTS = { + "sampling_default_temperature": 1.0, + "sampling_default_top_p": 1.0, + "sampling_thinking_temperature": 1.0, + "sampling_thinking_top_p": 1.0, + "sampling_thinking_top_p_with_tools": 0.95, + "sampling_temperature_max": 2.0, + "sampling_top_p_min": 0.0, +} + + +def classify_kernel(name): + """Classify a kernel name as 'greedy', 'stochastic', or None.""" + lo = (name or "").lower() + if any(ex in lo for ex in _NON_SAMPLING_EXCLUSIONS): + return None + if any(pat in lo for pat in _GREEDY_PATTERNS): + return "greedy" + if any(pat in lo for pat in _STOCHASTIC_PATTERNS): + return "stochastic" + return None + + +def _opt_float(val): + if val is None or isinstance(val, bool): + return None + try: + v = float(val) + except (TypeError, ValueError): + return None + return v if math.isfinite(v) else None + + +def _opt_int(val): + if val is None or isinstance(val, bool): + return None + try: + return int(val) + except (TypeError, ValueError): + return None + + +def configured_sampling(run): + """Extract configured sampling parameters from run.json (top-level or nested under 'sampling').""" + if not isinstance(run, dict): + return {"temperature": None, "top_p": None, "top_k": None} + nested = run.get("sampling") if isinstance(run.get("sampling"), dict) else {} + temp = _opt_float(run.get("temperature") if "temperature" in run else nested.get("temperature")) + top_p = _opt_float(run.get("top_p") if "top_p" in run else nested.get("top_p")) + top_k = _opt_int(run.get("top_k") if "top_k" in run else nested.get("top_k")) + return {"temperature": temp, "top_p": top_p, "top_k": top_k} + + +def _scan_logits_dtoh(capture, steps): + """Count DtoH transfers large enough to carry vocabulary logits (>= 256 KiB).""" + from ledger.analyze import read_jsonl + + total_bytes = 0 + total_ns = 0 + count = 0 + max_bytes = 0 + for rec in read_jsonl(os.path.join(capture, "memcpys-*.jsonl")): + if rec.get("kind") != 2: # CUPTI_ACTIVITY_MEMCPY_KIND_DTOH + continue + nbytes = int(rec.get("bytes") or 0) + if nbytes < LOGITS_DTOH_MIN_BYTES: + continue + count += 1 + total_bytes += nbytes + max_bytes = max(max_bytes, nbytes) + total_ns += max(int(rec.get("end", 0)) - int(rec.get("start", 0)), 0) + if not count: + return None + per = max(steps, 1) + return { + "copies": count, + "copies_per_step": count / per, + "mb_per_step": total_bytes / per / 1e6, + "max_mb": max_bytes / 1e6, + "ms_per_step": total_ns / per / 1e6, + } + + +def _has_lm_head(rows): + for r in rows: + for w in r.get("weights") or (): + if "lm_head" in w.get("name", "").lower(): + return True + for name in r.get("partial") or (): + if "lm_head" in name.lower(): + return True + if "lm_head" in r.get("name", "").lower(): + return True + return False + + +def _short_list(names, pretty, limit=3): + from ledger.analyze import short + + rendered = [f"`{short(pretty.get(n, n), 45)}`" for n in sorted(names)[:limit]] + if len(names) > limit: + rendered.append(f"+{len(names) - limit} more") + return ", ".join(rendered) + + +def inspect_capture(capture, rows, run, steps, pretty=None): + """Inspect kernel launches, DtoH copies, and run.json metadata for sampling behavior.""" + pretty = pretty or {} + cfg = configured_sampling(run) + by_kernel = defaultdict(lambda: {"kind": "", "us": []}) + greedy_names, stochastic_names = set(), set() + + for r in rows: + kind = classify_kernel(r["name"]) + if kind is None: + continue + entry = by_kernel[r["name"]] + entry["kind"] = kind + entry["us"].append(r["us"]) + (greedy_names if kind == "greedy" else stochastic_names).add(r["name"]) + + per = max(steps, 1) + kernels = [ + { + "name": name, + "kind": data["kind"], + "launches_per_step": len(data["us"]) / per, + "median_us": statistics.median(data["us"]), + "ms_per_step": sum(data["us"]) / per / 1e3, + } + for name, data in sorted(by_kernel.items(), key=lambda kv: -sum(kv[1]["us"])) + ] + + lm_head = _has_lm_head(rows) + logits_dtoh = _scan_logits_dtoh(capture, steps) if (capture and lm_head) else None + + if greedy_names and stochastic_names: + mode = "mixed" + elif stochastic_names: + mode = "device-sampled" + elif greedy_names: + mode = "device-greedy" + elif logits_dtoh is not None: + mode = "host-fallback" + else: + mode = "none" + + findings = [] + temp = cfg["temperature"] + is_prefill = bool((run or {}).get("prefill") or (run or {}).get("tokens")) + + if temp is not None and temp > 0 and mode == "device-greedy": + findings.append(( + 0, + f"run.json declares `temperature={temp:g}`, but only greedy sampling kernels ran " + f"({_short_list(greedy_names, pretty)}) — requests may have silently fallen back to `temp=0` (Sampling)", + )) + elif mode == "host-fallback": + cost_ms = logits_dtoh["ms_per_step"] if logits_dtoh["ms_per_step"] >= 0.5 else 0 + findings.append(( + cost_ms, + f"logits-sized DtoH copies ({logits_dtoh['mb_per_step']:.2f} MB/step, " + f"{logits_dtoh['copies_per_step']:.1f}/step) ran after `lm_head` with no device sampling kernel — " + "sampling appears to run on the host CPU (Sampling)", + )) + elif not is_prefill and temp is not None and temp == 0.0: + findings.append(( + 0, + "capture ran with `temperature=0` (greedy); results skip softmax/top-p/top-k and can hide " + "stochastic-sampling or host-fallback overhead (Sampling)", + )) + elif not is_prefill and temp is None and mode == "device-greedy": + findings.append(( + 0, + f"only greedy sampling kernels ran ({_short_list(greedy_names, pretty)}) with no temperature " + "recorded in `run.json`; verify whether `temperature=0` was intended (Sampling)", + )) + + return { + "configured": cfg, + "mode": mode, + "kernels": kernels, + "logits_dtoh": logits_dtoh, + "findings": findings, + } + + +def format_section(info, pretty, emit): + """Emit the `## Sampling` Markdown section when sampling activity or metadata is present.""" + cfg = info["configured"] + if info["mode"] == "none" and cfg["temperature"] is None: + return + from ledger.analyze import short + + emit("## Sampling\n") + parts = [f"Observed path: `{info['mode']}`"] + if cfg["temperature"] is not None: + parts.append(f"configured `temperature={cfg['temperature']:g}`") + if cfg["top_p"] is not None: + parts.append(f"`top_p={cfg['top_p']:g}`") + if cfg["top_k"] is not None: + parts.append(f"`top_k={cfg['top_k']}`") + emit(", ".join(parts) + ".\n") + + if info["kernels"]: + emit("| kernel | kind | launches/step | median us | ms/step |") + emit("|---|---|---|---|---|") + for k in info["kernels"]: + label = short(pretty.get(k["name"], k["name"]), 60) + emit( + f"| `{label}` | {k['kind']} | {k['launches_per_step']:.1f} | " + f"{k['median_us']:.1f} | {k['ms_per_step']:.3f} |" + ) + emit("") + + if info["logits_dtoh"] is not None: + d = info["logits_dtoh"] + emit( + f"Logits-sized DtoH transfers: {d['copies_per_step']:.1f}/step, " + f"{d['mb_per_step']:.2f} MB/step (max {d['max_mb']:.2f} MB), {d['ms_per_step']:.2f} ms/step.\n" + ) + + +def compare_sampling(info_a, info_b): + """Return a concise warning when two diffed captures used mismatched sampling modes or temperatures.""" + ta, tb = info_a["configured"]["temperature"], info_b["configured"]["temperature"] + ma, mb = info_a["mode"], info_b["mode"] + + temp_diff = ta is not None and tb is not None and not math.isclose(ta, tb, rel_tol=1e-6, abs_tol=1e-6) + mode_diff = ma != mb and ma != "none" and mb != "none" + if not temp_diff and not mode_diff: + return None + + def desc(mode, temp): + return f"`{mode}` (`temperature={temp:g}`)" if temp is not None else f"`{mode}`" + + return ( + f"Sampling mismatch: A is {desc(ma, ta)}, B is {desc(mb, tb)} — comparing greedy against " + "stochastic or host-fallback sampling can skew step timings and token equality." + ) + + +def parse_sampling_policy(text): + """Parse a Sibyl deployment profile's `sampling_policy` key=value text and collect issues.""" + policy = dict(_PROFILE_SAMPLING_DEFAULTS) + found = False + issues = [] + + for raw_line in (text or "").splitlines(): + line = raw_line.strip() + if "=" not in line: + continue + key, raw_val = (part.strip() for part in line.split("=", 1)) + if key not in policy: + continue + try: + value = float(raw_val) + except ValueError: + issues.append(f"{key}={raw_val!r} is not a valid number") + continue + policy[key] = value + found = True + + if not found: + issues.append("sampling_policy sets no explicit sampling keys") + return {"source": "builtin", "policy": policy, "issues": issues} + + tmax = policy["sampling_temperature_max"] + pmin = policy["sampling_top_p_min"] + bounds = ( + ("sampling_temperature_max", tmax, 0.0, 2.0), + ("sampling_top_p_min", pmin, 0.0, 1.0), + ("sampling_default_temperature", policy["sampling_default_temperature"], 0.0, tmax), + ("sampling_thinking_temperature", policy["sampling_thinking_temperature"], 0.0, tmax), + ("sampling_default_top_p", policy["sampling_default_top_p"], pmin, 1.0), + ("sampling_thinking_top_p", policy["sampling_thinking_top_p"], pmin, 1.0), + ("sampling_thinking_top_p_with_tools", policy["sampling_thinking_top_p_with_tools"], pmin, 1.0), + ) + for name, value, lo, hi in bounds: + if not math.isfinite(value) or value < lo or value > hi: + issues.append(f"{name}={value:g} is outside [{lo:g}, {hi:g}]") + + if policy["sampling_default_temperature"] == 0.0: + issues.append("sampling_default_temperature=0 forces greedy decoding for all requests omitting temperature") + if policy["sampling_thinking_temperature"] == 0.0: + issues.append("sampling_thinking_temperature=0 forces greedy decoding for all thinking turns") + for pkey in ("sampling_default_top_p", "sampling_thinking_top_p", "sampling_thinking_top_p_with_tools"): + if policy[pkey] == 0.0: + issues.append(f"{pkey}=0 must be positive") + + return {"source": "profile", "policy": policy, "issues": issues} + + +def audit_sampling_profile(profile_path): + """Audit a Sibyl deployment profile JSON file for zero-temperature or invalid sampling policy.""" + with open(profile_path, encoding="utf-8") as f: + data = json.load(f) + if not isinstance(data, dict) or "sampling_policy" not in data: + return None + parsed = parse_sampling_policy(data.get("sampling_policy") or "") + parsed["profile_path"] = profile_path + return parsed diff --git a/ledger/sibyl_audit.py b/ledger/sibyl_audit.py index 0e5fa1e..4464af2 100644 --- a/ledger/sibyl_audit.py +++ b/ledger/sibyl_audit.py @@ -28,6 +28,7 @@ from ledger import analyze as A from ledger import ascend_import as AI +from ledger import sampling _COLLECTIVE_OPS = {"REDUCE", "GATHER", "SCATTER", "ALLTOALL", "ALLREDUCE", "ALLGATHER", "REDUCE_SCATTER"} _EVENT_OPS = {"RECORD", "WAIT", "RESET", "EVENT_RECORD", "EVENT_WAIT", "EVENT_RESET"} @@ -585,6 +586,48 @@ def export_ledger_capture( f.write("\n") +def _find_profile_json(pack_dir, explicit=None): + """Locate an explicit or co-located Sibyl recorded deployment profile JSON.""" + if explicit: + return explicit + for candidate in ( + os.path.join(pack_dir, "profile.json"), + os.path.join(os.path.dirname(os.path.abspath(pack_dir)), "profile.json"), + ): + if os.path.isfile(candidate): + try: + with open(candidate, encoding="utf-8") as f: + data = json.load(f) + if isinstance(data, dict) and "sampling_policy" in data: + return candidate + except (OSError, ValueError): + continue + return None + + +def _audit_sampling(pack_dir, step_plan, profile_path=None): + """Inspect step sampling kernels and optional Sibyl deployment profile for temp=0 traps.""" + greedy_kernels = sorted({k["name"] for k in step_plan["kernels"] if sampling.classify_kernel(k["name"]) == "greedy"}) + stochastic_kernels = sorted({k["name"] for k in step_plan["kernels"] if sampling.classify_kernel(k["name"]) == "stochastic"}) + resolved = _find_profile_json(pack_dir, explicit=profile_path) + profile_audit = sampling.audit_sampling_profile(resolved) if resolved else None + issues = list(profile_audit["issues"]) if profile_audit else [] + if profile_audit and not issues and greedy_kernels and not stochastic_kernels: + pol = profile_audit["policy"] + if pol["sampling_default_temperature"] > 0 or pol["sampling_thinking_temperature"] > 0: + issues.append( + f"step plan only contains greedy sampling kernel(s) ({', '.join(greedy_kernels)}) while " + "profile expects positive temperature" + ) + return { + "profile_path": resolved, + "profile_policy": profile_audit["policy"] if profile_audit else None, + "greedy_kernels": greedy_kernels, + "stochastic_kernels": stochastic_kernels, + "issues": issues, + } + + def audit_pack( pack_dir, msprof_source=None, @@ -593,6 +636,7 @@ def audit_pack( sms=24, default_dtype="", tokens=0, + profile_path=None, ): """Run full liveness and redundancy accounting on a Sibyl recorded rank directory.""" mem_path = os.path.join(pack_dir, "omni_memory.plan") @@ -744,6 +788,7 @@ def mark_addr(va): copy_dirs = Counter(_COPY_DIR_NAME.get(c["direction"], str(c["direction"])) for c in step_plan["copies"]) event_audit = _check_events(step_plan) + sampling_audit = _audit_sampling(pack_dir, step_plan, profile_path=profile_path) return { "pack_dir": pack_dir, @@ -814,6 +859,7 @@ def mark_addr(va): "comm_ms": round(sum(o["end"] - o["start"] for o in comm_ops) / 1e6, 3), "time_breakdown": _summarize_time_ledger(compute_ops, comm_ops), }, + "sampling": sampling_audit, } @@ -880,10 +926,34 @@ def format_markdown(summary): for kind, cnt in sorted(s["glue_ops"].items(), key=lambda kv: (-s["glue_ms"].get(kv[0], 0.0), -kv[1])): lines.append(f"| `{kind}` | {cnt} | {s['glue_ms'].get(kind, 0.0):.3f} |") + sa = summary.get("sampling") or {} + if sa.get("profile_path") or sa.get("greedy_kernels") or sa.get("stochastic_kernels") or sa.get("issues"): + lines += ["", "## Sampling Audit", ""] + if sa.get("profile_path"): + pol = sa.get("profile_policy") or {} + lines.append( + f"- Profile: `{sa['profile_path']}` " + f"(default_temp={pol.get('sampling_default_temperature')}, " + f"thinking_temp={pol.get('sampling_thinking_temperature')})" + ) + if sa.get("greedy_kernels"): + lines.append(f"- Greedy kernels in step plan: {', '.join(f'`{k}`' for k in sa['greedy_kernels'])}") + if sa.get("stochastic_kernels"): + lines.append(f"- Stochastic kernels in step plan: {', '.join(f'`{k}`' for k in sa['stochastic_kernels'])}") + if sa.get("issues"): + for issue in sa["issues"]: + lines.append(f"- **Issue**: {issue}") + else: + lines.append("- No sampling policy issues found.") + lines.append("") return "\n".join(lines) +def has_sampling_issues(summary): + return bool((summary.get("sampling") or {}).get("issues")) + + def has_redundancy(summary): m, u = summary["memory"], summary["step"]["unused_declarations"] return any( @@ -911,7 +981,9 @@ def main(): ap.add_argument("--sms", type=int, default=24, help="AI Core count for exported run.json (default: 24)") ap.add_argument("--default-dtype", default="", help="Fallback dtype for weight regions (e.g. bfloat16, int8, float32)") ap.add_argument("--tokens", type=int, default=0, help="Active tokens per step (written as prefill in run.json for compute roofline)") + ap.add_argument("--profile", default=None, help="Optional Sibyl deployment profile.json to audit sampling_policy") ap.add_argument("--fail-on-unused", action="store_true", help="Exit 1 if any dead memory regions or unused declarations are found") + ap.add_argument("--fail-on-sampling", action="store_true", help="Exit 1 if any sampling policy issues (e.g. temp=0 defaults) are found") args = ap.parse_args() summary = audit_pack( @@ -922,6 +994,7 @@ def main(): sms=args.sms, default_dtype=args.default_dtype, tokens=args.tokens, + profile_path=args.profile, ) report = format_markdown(summary) if args.out: @@ -935,7 +1008,7 @@ def main(): with open(args.json, "w", encoding="utf-8") as f: json.dump(summary, f, indent=2) f.write("\n") - if args.fail_on_unused and has_redundancy(summary): + if (args.fail_on_unused and has_redundancy(summary)) or (args.fail_on_sampling and has_sampling_issues(summary)): raise SystemExit(1) diff --git a/tests/test_sampling.py b/tests/test_sampling.py new file mode 100644 index 0000000..87f8773 --- /dev/null +++ b/tests/test_sampling.py @@ -0,0 +1,232 @@ +"""Tests for ledger.sampling: temp=0 / greedy mismatch, host-fallback DtoH, diff mismatch, and Sibyl profile audit.""" + +import json +import struct +import sys + +import pytest + +from ledger import analyze, ascend_import, cli, diff, sampling, sibyl_audit +from report import section + + +def _write_synthetic_capture(cap, kernels, run_meta, regions=None, memcpys=None): + cap.mkdir(parents=True, exist_ok=True) + regions = regions or [] + (cap / "regions-0.json").write_text(json.dumps(regions)) + nodes = [] + with (cap / "kernels-0.jsonl").open("w") as kf: + for idx, k in enumerate(kernels, start=1): + node_id = 0 + if "ptrs" in k: + node_id = idx + raw = struct.pack(f"<{len(k['ptrs'])}Q", *k["ptrs"]) + nodes.append({"id": node_id, "params": [[0, len(raw), raw.hex()]]}) + rec = { + "start": k["start"], + "end": k["end"], + "name": k["name"], + "grid": k.get("grid", [48, 1, 1]), + "stream": k.get("stream", 1), + "node": node_id, + "corr": idx, + } + kf.write(json.dumps(rec) + "\n") + with (cap / "nodes-0.jsonl").open("w") as nf: + for n in nodes: + nf.write(json.dumps(n) + "\n") + if memcpys: + with (cap / "memcpys-0.jsonl").open("w") as mf: + for m in memcpys: + mf.write(json.dumps(m) + "\n") + (cap / "run.json").write_text(json.dumps(run_meta)) + + +def test_classify_kernel_excludes_moe_topk_and_splits_greedy_vs_stochastic(): + assert sampling.classify_kernel("greedy_verify_bf16") == "greedy" + assert sampling.classify_kernel("_argmax_partial") == "greedy" + assert sampling.classify_kernel("_argmax_finish") == "greedy" + assert sampling.classify_kernel("sample_verify_bf16") == "stochastic" + assert sampling.classify_kernel("_gumbel_sample_kernel") == "stochastic" + assert sampling.classify_kernel("TopKTopPSamplingFromProbs") == "stochastic" + # MoE routing top-k must never be misclassified as sampling. + assert sampling.classify_kernel("_ZN4vllm3moe10topkGatingILi8ELi128EEEvv") is None + assert sampling.classify_kernel("MatMulV2_dit_qkv") is None + + +def test_analyze_detects_temp_gt_zero_running_only_greedy_kernel(tmp_path): + """When run.json declares temperature=1.0 but only greedy_verify_bf16 ran, flag silent temp=0 fallback.""" + lm_addr = 0x1000_0000 + regions = [{"kind": "weight", "name": "lm_head.weight", "addr": lm_addr, "size": 16 * 1024 * 1024, "shape": [129280, 64], "dtype": "bfloat16"}] + kernels = [ + {"start": 1_000_000, "end": 1_500_000, "name": "MatMulV2_lm_head", "ptrs": [lm_addr]}, + {"start": 1_510_000, "end": 1_530_000, "name": "greedy_verify_bf16"}, + ] + cap = tmp_path / "ascend-greedy-mismatch" + _write_synthetic_capture(cap, kernels, {"steps": 1, "batch": 1, "temperature": 1.0, "sms": 24}, regions=regions) + + out = tmp_path / "report.md" + analyze.report(str(cap), ceiling=1600.0, steps=1, out=str(out), sms=24) + text = out.read_text() + + findings = section(text, "Findings") + assert "temperature=1" in findings + assert "greedy_verify_bf16" in findings + assert "temp=0" in findings + samp = section(text, "Sampling") + assert "Observed path: `device-greedy`" in samp + assert "configured `temperature=1`" in samp + + +def test_analyze_detects_host_fallback_logits_dtoh(tmp_path): + """lm_head + logits-sized DtoH with no device sampling kernel is flagged as host-fallback.""" + lm_addr = 0x1000_0000 + regions = [{"kind": "weight", "name": "lm_head.weight", "addr": lm_addr, "size": 16 * 1024 * 1024, "shape": [129280, 64], "dtype": "bfloat16"}] + kernels = [{"start": 1_000_000, "end": 1_500_000, "name": "MatMulV2_lm_head", "ptrs": [lm_addr]}] + # 2.07 MB DtoH (8 rows x 129280 vocab x 2B) taking 1.2 ms. + memcpys = [{"start": 1_510_000, "end": 2_710_000, "bytes": 2_068_480, "kind": 2, "src_kind": 3, "dst_kind": 2, "stream": 1, "node": 0, "corr": 1, "rcorr": 0}] + cap = tmp_path / "host-fallback" + _write_synthetic_capture(cap, kernels, {"steps": 1, "batch": 1, "temperature": 1.0, "sms": 24}, regions=regions, memcpys=memcpys) + + out = tmp_path / "report.md" + analyze.report(str(cap), ceiling=1600.0, steps=1, out=str(out), sms=24) + text = out.read_text() + + findings = section(text, "Findings") + assert "logits-sized DtoH copies" in findings + assert "host CPU" in findings + samp = section(text, "Sampling") + assert "Observed path: `host-fallback`" in samp + + +def test_analyze_clean_device_sampled_emits_no_sampling_warning(tmp_path): + """temperature=1.0 with sample_verify_bf16 reports device-sampled with zero sampling warnings.""" + lm_addr = 0x1000_0000 + regions = [{"kind": "weight", "name": "lm_head.weight", "addr": lm_addr, "size": 16 * 1024 * 1024, "shape": [129280, 64], "dtype": "bfloat16"}] + kernels = [ + {"start": 1_000_000, "end": 1_500_000, "name": "MatMulV2_lm_head", "ptrs": [lm_addr]}, + {"start": 1_510_000, "end": 1_540_000, "name": "sample_verify_bf16"}, + ] + cap = tmp_path / "device-sampled" + _write_synthetic_capture(cap, kernels, {"steps": 1, "batch": 1, "temperature": 1.0, "top_p": 0.95, "sms": 24}, regions=regions) + + out = tmp_path / "report.md" + analyze.report(str(cap), ceiling=1600.0, steps=1, out=str(out), sms=24) + text = out.read_text() + + assert "(Sampling)" not in section(text, "Findings") + samp = section(text, "Sampling") + assert "Observed path: `device-sampled`" in samp + assert "`top_p=0.95`" in samp + + +def test_diff_flags_greedy_vs_stochastic_sampling_mismatch(tmp_path): + """ledger diff warns when comparing a temp=0 greedy capture against a temp=1.0 sampled capture.""" + lm_addr = 0x1000_0000 + regions = [{"kind": "weight", "name": "lm_head.weight", "addr": lm_addr, "size": 16 * 1024 * 1024, "shape": [129280, 64], "dtype": "bfloat16"}] + cap_a = tmp_path / "greedy" + cap_b = tmp_path / "sampled" + _write_synthetic_capture( + cap_a, + [ + {"start": 1_000_000, "end": 1_500_000, "name": "MatMulV2_lm_head", "ptrs": [lm_addr]}, + {"start": 1_510_000, "end": 1_520_000, "name": "greedy_verify_bf16"}, + ], + {"steps": 1, "batch": 1, "temperature": 0.0, "sms": 24}, + regions=regions, + ) + _write_synthetic_capture( + cap_b, + [ + {"start": 1_000_000, "end": 1_500_000, "name": "MatMulV2_lm_head", "ptrs": [lm_addr]}, + {"start": 1_510_000, "end": 1_540_000, "name": "sample_verify_bf16"}, + ], + {"steps": 1, "batch": 1, "temperature": 1.0, "sms": 24}, + regions=regions, + ) + + out = tmp_path / "diff.md" + diff.report(str(cap_a), str(cap_b), ceiling=1600.0, min_ms=0.05, tolerance=0.03, out=str(out)) + text = out.read_text() + assert "Sampling mismatch:" in text + assert "`device-greedy` (`temperature=0`)" in text + assert "`device-sampled` (`temperature=1`)" in text + + +def test_sibyl_audit_catches_zero_temperature_profile_and_kernel_mismatch(tmp_path, monkeypatch): + """sibyl-audit detects sampling_default_temperature=0 / sampling_thinking_temperature=0 and profile-vs-kernel mismatch.""" + pack = tmp_path / "rank_0" + deps = pack / "deps" + deps.mkdir(parents=True) + + w_va = 0x1000_0000 + (deps / "fn_verify.bin").write_bytes(b"greedy_verify_bf16\x00") + args0 = struct.pack("