Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<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
Expand Down
20 changes: 17 additions & 3 deletions examples/vllm_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,23 @@ 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])
parser = EngineArgs.add_cli_args(FlexibleArgumentParser())
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)
Expand All @@ -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()
Expand All @@ -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:
Expand Down
14 changes: 11 additions & 3 deletions ledger/analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)):
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions ledger/ascend_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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,
Expand All @@ -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), "
Expand Down
11 changes: 8 additions & 3 deletions ledger/diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from collections import defaultdict

from ledger import analyze as A
from ledger import sampling
from ledger.steps import load_steps


Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 = []
Expand Down
9 changes: 8 additions & 1 deletion ledger/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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


Expand All @@ -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:
Expand Down
Loading
Loading