Skip to content

Certified LM head in SGLang: greedy decode, verify, drafting and fixed-noise sampled verify - #52

Merged
SamMausberg merged 25 commits into
mainfrom
kernel/sglang-integration
Oct 1, 2026
Merged

SamMausberg merged 25 commits into
mainfrom
kernel/sglang-integration

Conversation

@SamMausberg

@SamMausberg SamMausberg commented Oct 1, 2026 •

Copy link
Copy Markdown
Owner

What this adds

A small SGLang patch series (engine/sglang/patches/kernel/0001-0010, against the pin bd66ce34) that routes the LM head through the certified head of PR #45 on four paths. The engine imports the certified_head package; it is not copied into SGLang. #45 is merged; this PR now targets main and carries a merge of main (8d80119), described below.

Patch Path Flag (all off by default)
0001 greedy plain decode SGLANG_CERTIFIED_HEAD_DECODE
0002 greedy target verify, EAGLE/MTP and DFlash SGLANG_CERTIFIED_HEAD_VERIFY
0003 MTP draft top-1 (draft steps and draft extend), DFlash greedy draft projection SGLANG_CERTIFIED_HEAD_DRAFT
0004 fixed-noise sampled verify, EAGLE/MTP (a separate arm) SGLANG_CERTIFIED_HEAD_SAMPLED_VERIFY
0005 the stats file records the row counts of certified steps SGLANG_CERTIFIED_HEAD_STATS
0006 keeps the stock head if hopper-wgmma is combined with --enable-deterministic-inference SGLANG_CERTIFIED_HEAD_MODEL
0007 the MTP draft and DFlash draft paths also write their counters after each graph replay, so the last replay is recorded SGLANG_CERTIFIED_HEAD_STATS
0008 in check mode, the counters are written again after the sampled-verify comparison, so its last mismatches are recorded SGLANG_CERTIFIED_HEAD_STATS, _CHECK
0009 fixed-noise sampled verify refuses any batch with a greedy row SGLANG_CERTIFIED_HEAD_SAMPLED_VERIFY
0010 sampled verify checks the row limit before staging its inputs, so a larger batch takes the stock path SGLANG_CERTIFIED_HEAD_SAMPLED_VERIFY

Other flags:

  • SGLANG_CERTIFIED_HEAD_FALLBACK is batch (default) or columns. columns applies only to batch sizes whose bitwise self-test passes, run once per size at graph warm-up.
  • SGLANG_CERTIFIED_HEAD_MODEL selects the stock error model: conservative (default) or hopper-wgmma.
  • SGLANG_CERTIFIED_HEAD_MAX_ROWS caps the batch the head serves.
  • SGLANG_CERTIFIED_HEAD_CHECK turns on validation mode.
  • SGLANG_CERTIFIED_HEAD_STATS writes the counters.
  • SGLANG_CERTIFIED_HEAD_SRC points at the package.

Merged with #45's final package (8d80119)

This branch was built on 9e3a39a, before #45's TMA-fault fix, per-variant self-test gate, runtime probes, weight digest and sampling guards. 8d80119 merges main and resolves:

Results on the merged package (x9e2, engine_v2.json, 960ab39).

  • Tests first: the merged package's GPU and CPU tests passed, 167 of 167.
  • Arms: the eleven engine_v1 arms ran with the GDN state cache raised (MAMBA_SLOTS=80, up to 16 plain and 8 speculative requests).
  • Check arms (decode, column fallback, MTP and DFlash verify, MTP draft, DFlash draft projection, fixed-noise sampled verify): 0 rows differing from SGLang's own head, none refused, none probe-tripped. Certified at up to 16 decode, 32 MTP and 128 DFlash verify, and 120 draft-projection rows.
  • Fallback rows: 1.38% (decode), 1.74% (MTP verify), 3.99% (DFlash verify), 3.05% and 2.41% (MTP draft steps and extend), 3.96% (DFlash draft projection, against 89.6% on the pre-fix package), 1.84% (sampled verify).
  • One request at a time: certified and stock outputs are identical on 64 of 64 prompts for plain decode and for MTP.
  • Per-path rule: the committed check passes every check arm.
  • Process faults during the hold, both mine:
    • Patch 0009 reached the engine worktree mid-hold. The README gives each arm's engine commit; 0009 only changes the sampled-verify predicate, and the sampled arm ran it.
    • A mid-hold edit of engine_validate.sh made the script fail after its last arm, so the one-request-at-a-time comparison ran afterwards on the saved outputs.
  • First attempt: x9e stopped at its tests on the guard bug below and ran no arm.

How it stays exact and graph-safe

  • One graph, two heads. Each captured graph contains the certified head under a 0-d device flag and SGLang's own head (LogitsProcessor._get_logits) under its negation. Before each replay the host sets the flag, and the certified ids are copied out after the replay. No conditional node is nested: the certified stages are one node, and each fallback is its own top-level node.
  • Which batches are certified.
    • 0001-0002: the batch is all greedy.
    • 0004: every request is seeded and sampled with temperature only.
    • In both cases the batch must also need no logits: no logprobs, penalties, logit bias, grammar, custom logit processor, sampling mask, observer or beam rows.
    • Its padded graph must have been captured with the head.
    • Any other batch runs the stock head in the same graph.
  • Undecided rows run the stock GEMM on the engine's own head tensor at the same shape. Each call checks that the tensor is the one the head was built from, so a fallback returns exactly the stock token.
  • Drafting. MTP top-1 drafting is greedy for every batch unless rejection sampling is on. Inside the draft graph, the stock top-1 and the certified top-1 are two conditional nodes with the same side effects.
  • Refused configurations. These log a warning and keep the stock head:
    • TP or PP above 1, and DP attention;
    • quantized, LoRA, FP32, scaled or softcapped heads;
    • padded vocabularies;
    • SGLANG_SANITIZE_NAN_LOGITS and SGLANG_ENABLE_ASYNC_ASSERT.

Contract per path

  • 0001-0003. R-stock: every certified row is the token SGLang's own head returns for that row in that batch shape (greedy argmax, or the MTP/DFlash drafter's top-1). This holds under the error models of PR Certified int8 LM head: exact stock-head decisions, seeded sampling, kernels and evidence #45.
  • 0004.
    • Each verify row's token is SGLang's seeded sampler applied to that row's verify logits: div_(T), FP32 softmax and log, then multinomial_with_seed at the request's seed and the row's position.
    • A draft is accepted iff it equals that token, and the token is emitted at the first mismatch or as the bonus.
    • The output is equal in law to target sampling and does not depend on the drafter.
    • It requires --enable-deterministic-inference, which is what seeds every request. Its reference is therefore stock SGLang in that mode, a different engine configuration from the default.
    • That mode replaces aten::mm with SGLang's batch-invariant matmul_persistent: DeepGEMM's BF16 GEMM at the pin's defaults on this GH200, with a Triton kernel only as its fallback. So the stock head (and the certified fallback, which calls the same torch.matmul) is that kernel, not cuBLAS. A profiler check of the kernel name is in the second session. The conservative error model covers it. The Hopper model is validated for the cuBLAS head only, and 0006 refuses it there.
    • It replaces the stock rejection-sampling verify. It is not token-identical to plain decoding or to default-mode stock outputs, and it is not compared with them.

Validation

Check mode (SGLANG_CERTIFIED_HEAD_CHECK=1): every certified step also runs SGLang's own head at the same batch shape and counts, on the device, the rows whose token differs; the emitted tokens are the certified ones. For fixed-noise sampled verify the comparison is with SGLang's seeded sampler applied to the same verify logits (its contract above), under --enable-deterministic-inference. Results and commands: evidence/certified_head/README.md ("The head inside SGLang") and engine_v1.json.

The table below ran on the pre-fix package (repo 8f4f3d7): its W8A16 tiles above 16 rows were the faulty TMA ones, and it had no self-test gate or runtime probes. The arms above 16 rows (DFlash verify at 32, the DFlash draft projection at up to 120, whose 89.6% fallback was that fault, and the sampled verify at 32) ran those tiles, so their 0 differing rows are empirical. The rerun on the merged package (x9e, pending) is the evidence for this PR.

Setup: shared GPU lock, --mem-fraction-static 0.25, 64 prompts (every fifth of
the geometry workstream's public prompt set), up to 256 new tokens, greedy except
the sampled arm (seeded, T = 0.7), the conservative stock error model and the
whole-batch fallback except where noted. MTP is NEXTN with 3 steps and top-1 (4
verify rows per request); DFlash uses block size 16. Equality is claimed only at
the batch sizes each arm reached: at this memory fraction SGLang's GDN state cache
capped several arms at 2-4 running requests.

Arm Path Largest batch (requests; rows) Certified steps Rows Rows differing from stock Rows falling back Steps with a fallback
plain decode decode 3; 3 5,085 14,966 0 184 (1.23%) 180 (3.5%)
plain decode, column fallback decode 16; 16 1,039 14,944 0 209 (1.40%) 189 (18.2%)
MTP greedy verify 4; 16 1,278 19,868 0 345 (1.74%) 288 (22.5%)
DFlash greedy verify 2; 32 1,809 56,080 0 2,118 (3.78%) 1,154 (63.8%)
MTP draft steps 4; 4 2,550 9,936 0 290 (2.92%) 278 (10.9%)
MTP draft extend 4; 4 1,275 4,968 0 118 (2.38%) 112 (8.8%)
DFlash draft projection 8; 120 602 53,820 0 48,212 (89.6%) 541 (89.9%)
MTP, seeded T = 0.7 fixed-noise sampled verify 8; 32 700 21,016 0 386 (1.84%) 279 (39.9%)

The largest batch is the server's running-request cap where the state cache set
one (plain 3, MTP 4, DFlash 2) and otherwise the largest batch in the server's
decode log; the second session records the exact rows of every certified step. The
fallback columns are rates, not runtime: a fallback reruns the stock head for the
batch (or, in column mode, for the near-tie rows), and its cost is measured in the
head microbenchmark, not here. The DFlash draft projection falls back on 90% of its
rows (the threshold check fails on the flat logits of deep block positions); it is
left off in the proposed bench arm, and its runtime was not measured. #45's final
head microbenchmark has column mode ahead of the stock head through M = 64 on
decode rows (420.5 against 451.6 us under the conservative model); DFlash verify
rows fall back about 2.7 times as often, so its margin at M = 64 is not measured.

One request at a time (batch 1, so a certified server and a stock server see the
same shapes), the two servers' outputs are identical on 64 of 64 prompts for plain
decode (14,995 tokens) and for MTP with certified greedy verify (14,990 tokens,
verify batches of 4 rows). The same run passed tests/test_certified_engine.py (7)
and the W8A8 adversarial-activation and P8 witness tests (3) on the GH200.

The state-cache cap depended on the free GPU memory at server start, not only on the memory fraction: plain_check and plain_check_columns had the same arguments but saw 32 and 68 GB free and caps of 3 and 16. A second session is queued (MAMBA_SLOTS=80, so 16 plain or 8 speculative requests): plain decode, MTP verify and draft together, DFlash verify, sampled verify, the Hopper model, and the bench workstream's tuned flags (buffered GDN verify --enable-linear-replayssm-spec, replay SSM, no radix cache, Triton attention). Patch 0005 records the rows of every certified step for it. Its results will be added here.

Bench arms

Proposed for bench/arms.toml. Run with --sglang-worktree pointing at a worktree with this series applied, and set SGLANG_CERTIFIED_HEAD_SRC to the repo's src:

Arm Base Environment
plain_certified plain SGLANG_CERTIFIED_HEAD_DECODE=1, FALLBACK=columns, MAX_ROWS=64
mtp_certified mtp SGLANG_CERTIFIED_HEAD_VERIFY=1, DRAFT=1, FALLBACK=columns, MAX_ROWS=64
dflash_certified dflash SGLANG_CERTIFIED_HEAD_VERIFY=1, FALLBACK=columns, MAX_ROWS=64 (no DRAFT: the draft projection falls back on 90% of rows; its runtime was not measured)

Each arm returns the same tokens as its base arm at the same batch shapes; only time changes. MAX_ROWS=64 follows #45's final microbenchmark (column mode ahead through M = 64 on decode rows; every mode loses from M = 128); treat it as a knob for DFlash, whose fallback rate is higher. The Hopper error model (SGLANG_CERTIFIED_HEAD_MODEL=hopper-wgmma) is a separate variant, because it rests on a published hardware model.

Also in this PR

  • CertifiedHead.argmax and gumbel_sample take an optional device gate.
  • CertifiedHead.sibling shares the int8 codes across per-path buffers.
  • quantize.quantized_for caches the int8 copy of any head by SHA-256.
  • certified_head.engine holds the flags, the per-path heads and the device counters. tests/test_certified_engine.py checks the gated graph shape in both fallback modes.
  • experiments/certified_head/p8_witness_search.py checks P8 on real rows, and the witnesses it finds become GPU regressions.

Engine README

engine/sglang/README.md has a kernel section: the worktree commands, one row per patch with its variable and default (unchanged unless set), and the configurations that keep the stock head. The merge with main places it before the repair section.

Review comments on the merged head

  • Codex on 8d80119, Flags built directly by the glue bypassed from_env()'s checks (a misspelled FALLBACK ran batch mode, a misspelled MODEL the conservative model under the wrong name): fixed in 00f305f. Flags validates in __post_init__; a CPU test fails without it.
  • Codex on 8d80119, the draft paths' last replay never reached the stats file (their only dump was set_gate before the next replay): fixed in 00f305f with patch 0007 (engine/kernel af363a3bee), which writes the counters after each draft graph replay; engine_validate.sh pins SGLANG_CERTIFIED_HEAD_STATS_EVERY=1. x9e had not started and runs on 00f305f.
  • engine.py refuses to import unless STATUS_BITS is in bit order, which its counter kernel assumes (reviewer).
  • x9e's GPU tests (1 failed of 166) found a bug from Certified int8 LM head: exact stock-head decisions, seeded sampling, kernels and evidence #45's sampling guards, also on main: they ran after a refused batch too, where count = 0 and a stale ymax could add small_probability to rows marked refused. Fixed in 4c9fc8f: the guards run only after a decision. Outputs never changed (refused rows take the stock chain), and no committed evidence or paper number counts the bit (every certified-head evidence file predates the guards). A CPU test with stale buffers fails without the fix.
  • Codex on 00f305f, in check mode the sampled-verify comparison added its mismatches after the counters were written: fixed in 4c9fc8f with patch 0008 (engine/kernel a28946e0d4).
  • 4c9fc8f also merges main 3528dfc (Triton int8 TMA fault: needs Triton >= 3.8.0 and ptxas >= 13.3 to go away (evidence/triton_tma) #142), and the evidence README now cites evidence/triton_tma/ and RAW hazard with pipelined wgmma and LHS in register triton-lang/triton#9433 for the first TMA fault.
  • Codex on 4c9fc8f, multi-path check arms summed calls, so one idle hook could pass: fixed in f80f7d8. check_arm_stats.py requires calls on every path the arm declares (expected_paths in engine_validate.sh); CPU tests; applied to x9e2's arms with --check-only, all pass.
  • Codex on 4c9fc8f, a batch mixing greedy and sampled requests: already refused at the pin (a greedy request is normalised to top_k = 1, sampling_params.py:217-220, which sets need_top_k_sampling, sampling_batch_info.py:256, OR-ed on merge at :559). Patch 0009 makes it explicit (not is_any_greedy); a CPU test against the patched glue fails without it.
  • Codex on 960ab39, sampled verify staged its inputs into 256-row buffers before the row-limit check, so 260 rows (65 MTP requests) failed in the copy: fixed in 3646242 with patch 0010 (engine/kernel a3a4c8e99a; 0001-0010 on bd66ce34 give its tree). A CPU test with 260 rows fails against 9b5e82258d.
  • Codex on 960ab39, concurrent builders shared the cache entry's .tmp file: fixed in 3646242 (quantize.publish: process-unique temporary file, atomic rename; also used by load_or_build). A CPU test that completes a second build between the first's save and rename fails with the fixed name.
  • Neither change alters what x9e2 ran: its sampled batches had at most 32 rows, and its servers loaded the existing pinned cache entry (README).

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-01T21:16:18.178136Z 3646242 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: REQUEST CHANGES

Reviewed head cb3885d against its base kernel/certified-head at 90cc31a, of which it is a descendant. The engine glue looks right.

  • The gate. With gate=False the fallback flags are zeroed before the gated stages, so no fallback node fires, and the caller's stock head runs under not gate.
  • The DFlash draft path. Its stock closure is SGLang's own matmul and argmax over weight[:num_org] at the same n. Check mode runs it unconditionally and compares on the device.
  • Check-mode equality. engine_v1.json shows 0 differing rows on every path, and 64/64 identical outputs in both end-to-end comparisons.

What blocks is that this evidence is not yet documented in the repository at the scope it supports, and the engine README section is missing.

Blocking

B1. engine_v1.json has no README entry, and the claims need the batch sizes actually observed (evidence/certified_head/README.md).

  • What is missing. The README adds only the P8 section. The engine equality results, their contract per path and their command exist only in the PR body. Add a section with:
    • the per-arm table;
    • the producing commands (engine_validate.sh, engine_summary.py) with the repo and engine commits;
    • the items below.
  • Name the largest batch observed per arm. Equality is checked per step against stock at the same shape, but at --mem-fraction-static 0.25 the GDN state cache capped most arms.
    • The column "graph sizes captured" is not the observed batch. plain_c1 lists graphs 1-16 but ran 1.0 rows per call.
    • Mean rows per call: plain_check 2.94 (at most 3 requests), plain_check_columns 14.4 (16), mtp_check verify 15.6 rows (4 requests x 4 tokens), dflash_check 31 rows (2 x 16), mtp_sampled_check 30 rows (about 8 requests), mtp_draft_check 3.9 (4) and dflash_draft_check 89 rows (about 6 x 15).
    • The counters record calls and rows but not the largest call. Add the maximum rows per call, or a size histogram, to the device counters, and state "equality at batch sizes up to N" per arm until the larger-cache session lands.
  • State the contract per path in the README. For 0001-0003 it is R-stock at the same shape. For 0004 it is SGLang's seeded sampler on the same verify logits, under --enable-deterministic-inference, not plain seeded decoding and not default-mode stock. INTEGRATION.md already says this well; the evidence README needs it beside the sampled-verify row.
  • Label the fallback shares as rates.

B2. The engine README's kernel section is missing (engine/sglang/README.md).

  • What other workstreams do. Every other patch series (geometry, moonshot, drafter, state) is documented in engine/sglang/README.md on main, with the apply commands and a per-patch table of what it changes and its default behaviour. kernel/0001-0004 has none.
  • Why it is not here. This stack's base predates that file, which lives on main.
  • Fix. Add the section when the PR is retargeted to main, or merge main into the stack now. It should cover the four patches, their flags, "off unless set", and the refused configurations.

Checked

  • The Hopper radius. No file in this PR carries the old 1.192097e-4. The code takes the radius from the base's HOPPER_WGMMA_BF16, which now gives 1.192216e-4. Every engine arm ran model: conservative, so the radius change does not touch these results.
  • Counts. Every count in the body's table matches engine_v1.json: calls, rows, fallback rows and calls, and 0 mismatches. Both comparisons show 64/64 identical outputs, over 14,995 and 14,990 tokens.
  • Gating and fallback. head.py's gate and _gated zero the fallback flags before the conditional stages. Column routing runs inside the gated node, and enable_column_fallback(extend=True) adds only sizes that passed. Column mode remains reachable only through the self-test (Certified int8 LM head: exact stock-head decisions, seeded sampling, kernels and evidence #45's B1).
  • DFlash draft fallback. Patch 0003 keeps SGLang's own matmul and argmax over weight[:num_org] as the stock closure. It is skipped when org_vocab_start is set, and the TP > 1 branch stays stock.
  • Tests and hooks. tests/test_certified_bounds.py passes (14 tests) on the stacked branch, and pre-commit passes on the changed files. I did not run the GPU tests (test_certified_engine.py): the lock queue is long.
  • Attribution. There are no AI co-author lines.
  • Codex. It was still running (👀) when I posted. I will check its comments on re-review.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cb3885d98b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +152 to +154
stop_server
grep -E "Certified LM head|Traceback|Error" "$dir/server.log" | head -20 >"$dir/server_notes.txt" || true
return "$rc"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fail check-mode arms on recorded token mismatches

When a *_check arm records nonzero mismatch_rows, the client request can still complete successfully, and this function stops the server and returns only the client exit code without examining certified_stats.json. Consequently, the primary same-batch equality check described by this script reports success even when the certified head emits incorrect tokens; parse the counters and fail any check arm with mismatches.

Useful? React with 👍 / 👎.

Comment on lines +124 to +126
print(json.dumps(report, indent=1))
if args.out:
args.out.write_text(json.dumps(report, indent=1) + '\n')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Return a failure status when comparison finds divergence

When certified and stock output files contain different token sequences, compare() records the differences but always exits successfully. The caller in engine_validate.sh explicitly relies on compare ... || status=1, so an end-to-end regression cannot make validation fail; return a nonzero status when diverged is nonempty.

Useful? React with 👍 / 👎.

For the SGLang integration:

- CertifiedHead.argmax and gumbel_sample take an optional 0-d device bool
  gate. The certified stages run in one conditional node and each fallback
  in its own top-level node, with flags cleared before the gated stages, so
  an engine can choose per CUDA-graph replay between this head and its own
  stock head without nesting conditional nodes.
- CertifiedHead.sibling gives each graph family its own buffers over the
  same int8 codes and metadata.
- quantize.quantized_for caches the quantized copy of any head tensor under
  its SHA-256, reusing the pinned checkpoint's cache when it matches.
- certified_head.engine reads the SGLANG_CERTIFIED_HEAD_* flags, builds one
  head per enabled path from the engine's own head weight, and keeps device
  counters per path (calls, rows, fallbacks, status bits, and in check mode
  rows whose token differs from the stock token).
- tests/test_certified_engine.py checks the gated graph shape the engine
  captures, in both fallback modes; it has not run on the GPU yet.
engine/sglang/patches/kernel/0001 wires the certified head into SGLang's
greedy plain decode behind SGLANG_CERTIFIED_HEAD_DECODE (off by default):
each decode CUDA graph captures the certified head under a device flag and
the stock head under its negation, and the host sets the flag per replay
for batches that are all greedy and need no logits. The patch applies to
bd66ce34 with git am and reproduces the engine branch's tree.

- engine.PathHead.warm compiles every kernel variant a captured call uses
  and runs the column self-test per batch size on first sight;
  enable_column_fallback(extend=True) adds sizes one at a time.
- Counters cover the rows that are not CUDA-graph padding.
- experiments/certified_head/engine_validate.sh launches servers under the
  shared lock for each arm (check mode in batch and column modes, the
  Hopper model, and one-request-at-a-time certified and stock runs) and
  engine_equality.py drives them and compares outputs.
engine/sglang/patches/kernel/0002 routes greedy target verify for
EAGLE/MTP and DFlash through the certified head behind
SGLANG_CERTIFIED_HEAD_VERIFY. The certified ids travel on the replay's
LogitsProcessorOutput and replace the greedy argmax in eagle_sample and in
DFlash's accept step. The series applies to bd66ce34 and reproduces the
engine branch's tree.

engine_validate.sh gains MTP (NEXTN, 3 steps, top-1) and DFlash (block 16)
arms in check mode and one request at a time, with the stock comparisons.
engine/sglang/patches/kernel/0003 routes MTP draft top-1 (draft steps in
the draft CUDA graph and the draft-extend token) and DFlash's greedy draft
projection through the certified head behind SGLANG_CERTIFIED_HEAD_DRAFT.
engine.PATH_FLAG maps the three draft paths to that flag. The series
applies to bd66ce34 and reproduces the engine branch's tree.
engine/sglang/patches/kernel/0003-0004: MTP draft top-1 and DFlash's greedy
draft projection (SGLANG_CERTIFIED_HEAD_DRAFT), and fixed-noise sampled
verify for EAGLE/MTP (SGLANG_CERTIFIED_HEAD_SAMPLED_VERIFY). The four patches
apply to bd66ce34 and reproduce the engine branch's tree.

- engine.PathHead.warm_sampling compiles the sampler and SGLang's
  multinomial_with_seed for each shape; add_mismatches counts differences
  found outside the graph.
- reference.stock_seeded_sample_from_logits runs SGLang's seeded chain on
  given logits, for the sampled-verify check.
- engine_validate.sh gains the sampled-verify arm (seeded T = 0.7 under
  --enable-deterministic-inference).
- INTEGRATION.md describes the patch series, its flags and when a batch is
  certified.
P8 follow-up (3): for every real row and temperature, compare SGLang's
temperature-only seeded token (FP32 softmax and log, SGLang's own noise)
with the FP64 log of the same probabilities and with exact FP64
log-softmax, count the rows where they differ, and keep the first few
witnesses with their inputs for GPU regressions.
tests/test_certified_head.py replays every witness that
p8_witness_search.py wrote (evidence/certified_head/p8_witnesses.json, or
VP_P8_WITNESSES) and requires the certified sampler to return SGLang's
seeded token; it skips until the file exists.
Patch 0004 needs --enable-deterministic-inference; its reference is stock
SGLang in that mode, so it is not compared with default-mode outputs.
engine_validate.sh falls back to the main checkout's
scripts/gpu_startup_lock.sh, which this stacked branch does not have yet.
On 60,000 real decode rows SGLang's temperature-only seeded token never
differs from an FP64-log variant and differs from exact arithmetic on
0.31% (T = 0.7) and 0.35% (T = 1.0) of rows. The first eight such rows are
kept for the GPU regression.
At a 0.25 memory fraction SGLang caps running requests by its state cache
(3 for plain decode in the first run), so the batch shapes a check covers
depended on the free memory at start-up. MAMBA_SLOTS sets the cache
explicitly; mtp_all_check certifies MTP verify and draft together.
evidence/certified_head/engine_v1.json summarizes engine_validate.sh at
8f4f3d7 (engine 71c521db) with engine_summary.py. In check mode every
certified row equals the stock head's row at the same batch shape: plain
decode, MTP and DFlash greedy verify, MTP draft steps and draft extend, the
DFlash draft projection and MTP fixed-noise sampled verify (against
SGLang's seeded sampler on the same verify logits), 0 differing rows in
each. One request at a time, certified and stock servers give identical
outputs on 64 of 64 prompts for plain decode and for MTP. The engine-glue
tests (7) and the new W8A8 and witness tests (3) pass.

At the 0.25 memory fraction SGLang's state cache capped some arms at 2-4
running requests; a second session sizes it explicitly.
engine/sglang/patches/kernel/0005 keeps, per path, a histogram of the real
row counts of certified steps, so a validation run states the batch sizes
at which equality was observed. engine_validate.sh gains arms with the
bench workstream's tuned flags: buffered GDN verify for MTP
(--enable-linear-replayssm-spec), replay SSM for plain decode, no radix
cache, stream interval 4, and Triton attention. The five patches apply to
bd66ce34 and reproduce the engine branch's tree.
SamMausberg added a commit that referenced this pull request Oct 1, 2026
Brings in engine/sglang/README.md, which the stacked SGLang integration
(PR #52) documents its patches in.
One row per patch with its variable and default, the worktree commands, the
configurations that keep the stock head, and the validation script.
Per arm: the largest batch reached, certified steps, rows, rows differing
from the stock head (0 everywhere), and fallback rates stated as rates;
the sampled-verify row is labelled with its own contract; the column-mode
crossover is marked pending; the commands and commits.
@SamMausberg
SamMausberg force-pushed the kernel/sglang-integration branch from cb3885d to f9ca667 Compare October 1, 2026 00:24
@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: REQUEST CHANGES

Re-reviewed head f9ca667 against its base kernel/certified-head at 9e3a39a. f9ca667 descends from 9e3a39a, and the diff is 20 files, all from this series. Both earlier blocking items are fixed. Four new items remain, two of them from Codex.

Earlier items

  • B1 (fixed). The README section "The head inside SGLang" has the per-path contract, the fallback columns labelled as rates rather than runtime, the DFlash draft row scoped, and the M <= 64 column-mode crossover marked pending. I recomputed every row of its table from engine_v1.json: steps, rows, differing rows, fallback rows and fallback steps all match. The "largest batch" column also matches the raw server logs (max_running_requests at start-up, and the largest #running-req in the decode log): plain 3, columns 16, MTP 4, DFlash verify 2, DFlash draft 8 and sampled 8. In every check arm the observed maximum equals the cap. Mean rows per step agree with the caps: 2.94, 14.4, 15.6, 31.0, 89.4 and 30.0. The c1 comparisons are 64/64 with 14,995 tokens (plain) and 64/64 with 14,990 tokens (MTP), as stated.
  • B2 (fixed). engine/sglang/README.md has the kernel section. I applied the committed patches 0001-0004 at bd66ce343e with git am, and the tree equals engine commit 71c521db exactly. With 0005 added, it equals e93bd233.
  • Other checks. The Hopper radius is not cited anywhere in this diff, and the engine arms used the conservative model. Pre-commit passes on the changed files. The CPU test run skips both certified-head modules, as expected without a GPU.

Blocking

  1. The validation script passes when the certified head emits a wrong token (Codex P1, experiments/certified_head/engine_validate.sh:166).
    • run_arm returns the client's exit code. It never reads mismatch_rows from certified_stats.json.
    • Consequence: a check arm in which the certified head differs from stock exits 0, so engine_validate.sh reports success on exactly the failure it exists to catch. The committed evidence is unaffected, because the README reads the counters through engine_summary.py. But anyone rerunning the validation, including the queued second session, gets a false pass.
    • Fix: after stop_server, parse the stats file and return nonzero for a *_check arm with any mismatch_rows > 0. Also return nonzero when the stats file is missing.
  2. compare exits 0 on divergence (Codex P2, experiments/certified_head/engine_equality.py:126).
    • engine_validate.sh calls compare ... || status=1, but compare() always returns normally, so a c1 mismatch cannot fail the run.
    • Fix: exit nonzero when diverged is non-empty. While there, report prompts present in only one file. common is a set intersection, so a prompt missing from one file is silently dropped and the run can still read as "64 of 64".
  3. The evidence cites commits that the rebase removed from the branch (evidence/certified_head/README.md, Files table).
    • engine_v1.json cites "repo 8f4f3d7", and its run_info records the same. p8_witnesses.json cites "commit ab507a9".
    • Neither commit is an ancestor of f9ca667 or of any remote branch, because the rebase onto 9e3a39a rewrote them as c58a859 and 24e213a. Once this merges, nobody who clones the repo can check out the commit that produced the evidence.
    • I checked that the rewrites hold the same code:
      • 8f4f3d7 and c58a859 have identical src/certified_head, experiments/certified_head, the two test files and patches/kernel.
      • ab507a9 and 24e213a have an identical p8_witness_search.py. They differ in bounds.py, fallback_vs_model.py and p8_witness_cpu.py, which came in from the base.
    • Fix: cite c58a859 and 24e213a, and add one sentence saying the runs were made at their pre-rebase twins 8f4f3d7 and ab507a9 with the same files (list the paths). Alternatively, push the old commits under a tag. Do the same for any other evidence regenerated before the rebase.
  4. The sampled arm's stock reference is not the cuBLAS head (evidence/certified_head/README.md, first paragraph of "The head inside SGLang", and INTEGRATION.md's 0004 paragraph).
    • At the pin, --enable-deterministic-inference calls enable_batch_invariant_mode() (model_runner.py:771-775). That replaces aten::mm, addmm and bmm with batch-invariant Triton kernels (batch_invariant_ops.py, enable_batch_invariant_mode).
    • SGLang's head is a torch.matmul (logits_processor.py:1002-1004), so in the mtp_sampled_check arm it is the Triton persistent matmul, not the cuBLAS kernel that stock_invariance.json characterises. The fallback's torch.matmul and the column self-test run the same Triton kernel.
    • The 0-of-21,016 result is therefore equality with that kernel. It is sound under the conservative model, which the README says covers "any reduction order, split-K with FP32 partials, truncating adders", provided the kernel accumulates in FP32 and rounds its output to BF16 to nearest-even.
    • Fix: say this in both places, and state which error model the sampled arm used. For hopper-wgmma with SAMPLED_VERIFY, either refuse the combination or say that model has not been checked against the batch-invariant kernel. The venue paper (Venue paper: MLSys-format main text on the certified head and transport's failure, with appendices #53) needs the same statement, and the paper should be able to cite yours.

Suggestions (not blocking)

  • The cap wording. "At this memory fraction SGLang's GDN state cache capped several arms at 2-4 running requests" is incomplete. plain_check and plain_check_columns ran with identical arguments, yet got caps of 3 and 16. Their start-up logs show 32.4 GB and 67.8 GB available, so the cap depended on the free memory left by the other shared-lock jobs. Say so, so that a reader does not expect the same cap on a rerun. MAMBA_SLOTS in the second session removes the dependence.
  • The FP64 reference under deterministic mode. reference.py:54 (the FP64 reference) goes through aten::mm. If it is ever called in a process with batch-invariant mode on, check that the override handles float64 or bypasses it.

Codex. The two comments on f9ca667 are items 1 and 2. No earlier Codex comments are open.

Review of PR #52 (re-review items 1-4):

- engine_validate.sh: a check arm now fails if any certified row differed
  from the stock row or if the server wrote no counters.
- engine_equality.py compare exits 1 when outputs diverge or a prompt is
  missing from either run, and lists such prompts.
- The evidence README cites the rebased twins of the run commits, and the
  original commits are tagged (kernel-engine-v1, kernel-p8-witness-search).
- Under --enable-deterministic-inference SGLang replaces aten::mm with its
  batch-invariant Triton matmul, so the sampled arm's stock head, and the
  certified fallback, run that kernel rather than cuBLAS. The README and
  INTEGRATION.md say so; the arm used the conservative model; patch 0006
  refuses hopper-wgmma under deterministic inference.
@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: REQUEST CHANGES

Re-reviewed head af0fa0c (one commit on f9ca667). Items 1-3 are fixed. Item 4 is fixed in substance (patch 0006 and the model statement), but the README and INTEGRATION.md name a kernel that does not run at the pin's defaults on this GPU.

Earlier items

  1. Fixed. engine_validate.sh fails a check arm when its counters are missing or unreadable, when no certified call happened, or when any path has mismatch_rows > 0. A missing key raises and also fails. Every check arm name contains _check.
  2. Fixed. compare exits 1 on divergence or when a prompt is in only one file. On the v1 outputs, plain_c1 vs plain_c1_stock gives rc 0 and plain_c1 vs mtp_c1 gives rc 1. Moving requests into run is fine.
  3. Fixed. The annotated tags kernel-engine-v1 and kernel-p8-witness-search on origin resolve to 8f4f3d7 and ab507a9, and the README names the rebased twins and what is identical.
  4. Partly fixed, see N1.
    • Patch 0006 refuses hopper-wgmma under deterministic inference in _unsupported. That is the right gate whichever kernel runs.
    • git am of 0001-0006 at bd66ce343e gives exactly the tree of engine a630d715.
    • The sampled arm's model, conservative, is stated.

Pre-commit passes on the changed scripts.

Blocking

N1. At the pin's defaults on the GH200, the deterministic-mode head GEMM is DeepGEMM, not Triton (evidence/certified_head/README.md, the paragraph added after "not plain seeded decoding"; src/certified_head/INTEGRATION.md, the 0004 paragraph; engine/sglang/README.md, row 0006).

  • The dispatch chain. mm_batch_invariant calls matmul_persistent (batch_invariant_ops.py:601-602). That function takes DeepGEMM's bf16_gemm_nn, with use_deterministic_algorithms(True), when all of these hold (lines 301-331):

    • SGLANG_BATCH_INVARIANT_OPS_ENABLE_MM_DEEPGEMM is set (default "1");
    • ENABLE_JIT_DEEPGEMM is true, which needs SM >= 90, SGLANG_ENABLE_JIT_DEEPGEMM (default True, environ.py:1168) and an importable deep_gemm;
    • both operands are BF16, a and b.T are contiguous, N >= 16, and the dimensions are TMA-aligned.
  • Why it applies here. All of those hold for the head:

    • the GH200 is SM 90;
    • deep_gemm 0.2.0 imports in ~/sglang/.venv;
    • the head is torch.matmul(h, W.T), and W is contiguous;
    • nothing under --enable-deterministic-inference turns DeepGEMM off.

    The Triton persistent kernel is the fallback.

  • What DeepGEMM does. Its SM90 BF16 kernel (deep_gemm/include/deep_gemm/impls/sm90_bf16_gemm.cuh) keeps one FP32 wgmma accumulator over all of K (lines 231-272). It writes BF16 with __float22bfloat162_rn (lines 345-346), so there is no split-K and the output is round-to-nearest.

  • Consequence. The conservative model and patch 0006 stand. But the description "Triton matmul, FP32 accumulation over 64- or 32-wide K tiles" describes the fallback, not the kernel the sampled arm and its certified fallback ran. The venue paper copies the same wording.

  • Fix.

    1. Confirm the kernel with a kernel-name trace of the head GEMM under deterministic mode. A one-shot under gpu_lock.sh -s is enough: enable_batch_invariant_mode(), torch.matmul on [M, 2560] x [2560, 248320] BF16 inside torch.profiler. Alternatively, grep an nsys trace of the sampled arm.
    2. State the kernel in the three places above, with its accumulation and rounding.
    3. Optionally, record SGLANG_BATCH_INVARIANT_OPS_ENABLE_MM_DEEPGEMM in run_info.txt.

    Patch 0006's comment and its commit message say "Triton" too. Its code needs no change, so updating the message can wait for the next time the series is regenerated.

Codex

There are no Codex comments on af0fa0c yet.

Under --enable-deterministic-inference SGLang's matmul_persistent runs
DeepGEMM's BF16 GEMM at the pin's defaults on this GH200 (one FP32 wgmma
accumulator over K, RN BF16 store); its Triton kernel is only the fallback.
The README, INTEGRATION.md, the engine README and patch 0006 now say so, and
deterministic_head_kernel.py records the kernel names with a profiler.
@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: APPROVE

Re-reviewed head 8dc5e47 (one commit on af0fa0c), base kernel/certified-head. N1, the last blocking item, is fixed, and every item from the three rounds is closed. GitHub shows the PR as mergeable and clean.

N1 (fixed)

  • One description of the kernel, in four places. The evidence README, the 0004 paragraph in INTEGRATION.md, row 0006 of engine/sglang/README.md, and the comment and commit message of patch 0006 now agree. Under --enable-deterministic-inference, the head GEMM is matmul_persistent. At the pin's defaults on this GH200 that is DeepGEMM's BF16 GEMM, with one FP32 wgmma accumulator over K and a round-to-nearest BF16 store; the Triton kernel is only the fallback. This matches batch_invariant_ops.py:301-331 and sm90_bf16_gemm.cuh:231-272,345-346 at the pin.
  • The trace is marked pending. The profiler check is labelled as pending in the second session. experiments/certified_head/deterministic_head_kernel.py is a sound test: it records CUDA kernel names at M = 1-128 with and without enable_batch_invariant_mode(), after a warm-up for DeepGEMM's JIT, and whether the two outputs are bitwise equal. Its result should be committed and cited when it runs.
  • The patch series reproduces the engine. git am of 0001-0006 at bd66ce343e gives exactly the tree of engine/kernel 7500af8c.
  • Hygiene. Pre-commit passes on the changed files. The series has no AI co-author lines. Both Codex comments (P1 and P2, on cb3885d) were fixed in af0fa0c.

Status of every item

Round Item Status
First B1: per-arm batch maxima, contract, rates, README section Fixed
First B2: engine README kernel section Fixed
Second 1: check arms fail on mismatches Fixed
Second 2: compare exit status Fixed
Second 3: orphaned commits Fixed (tags plus rebased twins)
Second 4: the deterministic-mode reference and patch 0006 Fixed
Third N1: the kernel name Fixed

Not blocking. Equality is claimed only at the batch sizes reached (caps 2-16, depending on free memory at start-up). The larger-batch session with MAMBA_SLOTS and patch 0005's per-step row counts should replace the cap-based column when it lands.

@SamMausberg

Copy link
Copy Markdown
Owner Author

@codex review

@SamMausberg

Copy link
Copy Markdown
Owner Author

Update on 00f305f: both blocking items are fixed. My verdict stays pending until engine_v2.json is committed and the checks below finish.

  • r4159625127. Flags.__post_init__ now rejects an unknown fallback or model on every construction, including the glue's direct one in patch 0001, and from_env no longer duplicates the checks. A CPU test covers it.
  • r4159625134. Patch 0007 dumps after every draft graph replay: in after_replay for the draft model runner (DFlash's in-graph projection) and through a new after_draft_replay() right after the MTP draft graph's execute. engine_validate.sh pins SGLANG_CERTIFIED_HEAD_STATS_EVERY=1, so every path's last replay is written. git am of 0001-0007 at bd66ce343e gives tree 9f62a638, which is the tree of engine af363a3bee.
  • Optional item. The import now checks that STATUS_BITS is 1 << i in order.
  • Still needed: engine_v2.json from x9e (running on 00f305f with engine af363a3bee), Codex on 00f305f, and my CPU tests and pre-commit of this head (CPU window).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 00f305fda7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

+ stock = stock_seeded_sample_from_logits(
+ next_token_logits[:n], st.seeds[:n], st.positions[:n], st.temps[:n]
+ )
+ _heads.get("sampled_verify").add_mismatches(ids, stock)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Flush sampled mismatches after recording them

In the mtp_sampled_check flow, after_replay calls attach_ids, which dumps the statistics before eagle_sample reaches check_fixed_noise and increments mismatch_rows here. A later replay's pre-replay dump usually captures that increment, but a mismatch on the final sampled replay never reaches certified_stats.json; consequently the check at the end of engine_validate.sh can still report success. Dump again after this comparison or flush all counters during shutdown.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4c9fc8f with patch 0008 (engine/kernel a28946e0d4). check_fixed_noise writes the counters again after adding its mismatches, so a mismatch on the last sampled replay reaches certified_stats.json. The engine rerun (x9e2) runs on this commit; the earlier attempt (x9e) stopped at its GPU tests and ran no engine arm, so no reported count missed this.

@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: REQUEST CHANGES (00f305f; 1 blocking: Codex r4159755914, valid)

The same class of hole as r4159625134, on the sampled path. In check mode after_replay calls attach_ids, which dumps, and only afterwards does eagle_sample reach check_fixed_noise, whose add_mismatches increments mismatch_rows. A mismatch on the last sampled replay therefore never reaches certified_stats.json, and mtp_sampled_check can pass. A flush at exit (an atexit hook, or one in the scheduler's shutdown) would close this for every path, as would a _maybe_dump() at the end of check_fixed_noise. Then say whether x9e's mtp_sampled_check arm needs a rerun.

Everything else from my update on 00f305f stands.

…atches

- gumbel_sample ran its two guards after a refused batch too. With no
  candidates, the small-probability guard compared -inf with a stale ymax and
  could add its bit to rows already marked refused (x9e's GPU tests caught it:
  status 576 instead of 64 in test_quantization_data_must_belong_to_the_weight).
  The guards check a decision, so they now run only after one; a refused
  batch keeps the single status refused. A CPU test with stale buffers fails
  without the fix. Outputs never changed (refused rows take the stock chain),
  and no committed evidence or paper number counts the extra bit: every
  certified-head evidence file was produced at or before 9f7f369, before the
  guards (09bf64e, ec46d55, 2c36737), and no other workstream's committed
  evidence ran the certified head.
- Codex on 00f305f: in check mode, the fixed-noise comparison with SGLang's
  seeded sampler adds its mismatches after attach_ids has written the
  counters, so a mismatch on the last sampled replay was never recorded.
  Patch 0008 (engine/kernel a28946e0d4) writes them again after the
  comparison.
- Main now carries #142: the evidence README cites evidence/triton_tma for the
  first TMA fault (clean only with Triton >= 3.8.0 and ptxas >= 13.3 together,
  matching triton-lang/triton#9433 by version pattern; the 64-byte refusal
  stays on Triton 3.7.1).
@SamMausberg

Copy link
Copy Markdown
Owner Author

@codex review

@SamMausberg

Copy link
Copy Markdown
Owner Author

Update on 4c9fc8f. The code items are all closed, and my verdict now waits only on engine_v2.json (x9e2) and Codex on this head.

  • The guard bug, which is also on main. In gumbel_sample's stages(), a non-certifiable batch now refuses and returns before _sampling is set. The temperature and small-probability guards therefore run only after a decision, and a refused batch keeps exactly refused. Its rows already take the stock chain. test_a_refused_sampled_batch_keeps_the_refused_status fills _ymax with 0 and checks the status.
  • r4159755914. Patch 0008 calls _maybe_dump() after add_mismatches in check_fixed_noise. git am of 0001-0008 at bd66ce343e gives tree 44236606, which is the tree of engine a28946e0d4.
  • Evidence README. The TMA cause now cites ../triton_tma/README.md and RAW hazard with pipelined wgmma and LHS in register triton-lang/triton#9433, as a version-pattern attribution only, and the 64-byte refusal stays for the 3.7.1 environment.
  • Checks. The CPU tests pass (32 passed, 2 skipped without CUDA), and pre-commit from main is clean.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4c9fc8fd1e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

+ si = forward_batch.sampling_info
+ return (
+ si is not None
+ and not si.is_all_greedy

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject mixed greedy batches from sampled verification

When continuous batching combines a greedy request with a temperature-sampled request, is_all_greedy is false and the remaining predicates can still pass under deterministic inference with default top-k/top-p/min-p settings. _stage_sampling then stages every request and the sampled graph applies Gumbel sampling to the greedy rows as well, so those requests no longer receive greedy verification. Require that every row is genuinely sampled, rather than merely requiring that the batch is not entirely greedy.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the pin a mixed batch was already refused, and f80f7d8 now makes that explicit. The normalisation chain (files unchanged by the kernel series):

  1. python/sglang/srt/sampling/sampling_params.py:217-220: a greedy request (0 <= temperature < _SAMPLING_EPS) becomes temperature = 1.0, top_k = 1.
  2. python/sglang/srt/sampling/sampling_batch_info.py:256: need_top_k_sampling = any(top_k != TOP_K_ALL) is therefore true for any batch with a greedy row; on merge it is OR-ed in (:559).
  3. _fixed_noise_eligible requires not need_top_k_sampling, so such a batch took the stock verify.

The contract should not rest on that normalisation, so patch 0009 (engine/kernel 9b5e82258d, in f80f7d8) requires not is_any_greedy instead of not is_all_greedy. A CPU test (tests/test_certified_engine_glue.py) imports the patched glue in a subprocess and checks that a batch with a greedy row is ineligible even with need_top_k_sampling unset. It fails against a28946e0d4. The engine rerun's sampled arm ran 0009 (evidence/certified_head/README.md, x9e2).

except (OSError, ValueError, KeyError) as exc:
sys.exit(f'no certified counters: {exc}')
bad = {p: v['mismatch_rows'] for p, v in paths.items() if v['mismatch_rows']}
calls = sum(v['calls'] for v in paths.values())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require calls from every path exercised by each check arm

For multi-path arms such as mtp_draft_check and mtp_all_check, summing calls allows validation to succeed if only one enabled path runs—for example, draft_extend can remain at zero while draft has calls. This defeats the script's per-path validation purpose and can hide a disconnected engine hook; validate an arm-specific set of expected paths and require nonzero calls for each.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f80f7d8. The check moved to experiments/certified_head/check_arm_stats.py. engine_validate.sh declares the paths each check arm must exercise (expected_paths), and the arm fails if any of them made no certified call. A flag can enable a path the arm's algorithm never runs (DRAFT enables both the MTP and the DFlash draft paths), so such a path is reported, not failed. CPU tests cover the rule. Applied with engine_validate.sh --check-only to x9e2's arms (engine_v2_arm_checks.log, 960ab39), every check arm passes.

@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: REQUEST CHANGES (4c9fc8f; 1 blocking: Codex r4160186732. Codex r4160186716 needs a reply with its scope, not a code change.)

  1. r4160186732 (engine_validate.sh:178) is valid. The check sums calls over every installed path, so a multi-path arm (mtp_draft_check, mtp_all_check) passes when one hook never fires, for example draft_extend at 0 while draft has calls. stats()['paths'] lists exactly the enabled paths, so require calls > 0 for each, for example idle = [p for p, v in paths.items() if not v['calls']], and fail on any. Then check x9e2's certified_stats.json per arm against the same rule, or rerun the affected arms, and say which.
  2. r4160186716 (mixed greedy and sampled batches) does not apply at the pin, as I read it, but answer it on the thread. At bd66ce343e, SamplingParams turns a greedy request into temperature = 1.0, top_k = 1 (sampling_params.py:217-220), and need_top_k_sampling = any(top_k != TOP_K_ALL) (sampling_batch_info.py:256). Any batch with a greedy row therefore has need_top_k_sampling set, and _fixed_noise_eligible returns False for it. Say so in the reply. A one-line comment at the predicate, or a CPU test of a mixed batch, would keep the reasoning from depending on that SGLang detail silently.

Everything else on 4c9fc8f stands as in my update.

Two Codex findings on 4c9fc8f:

- engine_validate.sh summed certified calls over all paths, so an arm with
  several paths (mtp_draft_check, mtp_all_check) passed with one hook idle.
  The check moves to check_arm_stats.py and fails when any path the arm must
  exercise made no call; engine_validate.sh declares each check arm's paths
  (expected_paths). A flag can enable a path the arm's algorithm never runs
  (DRAFT enables the MTP and DFlash draft paths), so such a path is reported,
  not failed. --check-only reruns the verdicts on finished arms without a
  server. CPU tests cover the rule.
- A batch mixing greedy and sampled requests: at the pin it was already
  ineligible for fixed-noise sampled verify, because SGLang normalises a
  greedy request to top_k = 1 (sampling_params.py), which sets
  need_top_k_sampling (sampling_batch_info.py, also on merge). Patch 0009
  (engine/kernel 9b5e82258d) makes the contract explicit:
  _fixed_noise_eligible requires not is_any_greedy. A CPU test imports the
  patched glue in a subprocess and fails against a28946e0d4.
x9e2 ran the merged package's GPU and CPU tests (167 passed), then the eleven
engine_v1 arms with the GDN state cache raised (MAMBA_SLOTS=80), so the arms
reach 16 plain and 8 speculative requests. Every check arm: 0 rows differing
from SGLang's own head, none refused, none probe-tripped; the committed
per-path check (f80f7d8) passes all of them. One request at a time, the
certified and stock servers' outputs are identical on 64 of 64 prompts for
plain decode and for MTP.

The README gives each arm's engine commit (patch 0009 reached the engine
worktree mid-hold; it changes only the sampled-verify predicate, and the
sampled arm ran it), and says that a mid-hold edit of engine_validate.sh made
the script fail after its last arm, so the one-request-at-a-time comparison
was run afterwards on the saved outputs.
@SamMausberg

Copy link
Copy Markdown
Owner Author

@codex review

@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: APPROVE (provisional, on 960ab39: Codex has not reviewed this head yet. I will confirm or withdraw once it does.)

Code (f80f7d8)

  • Per-path rule (r4160186732). check_arm_stats.py fails an arm on differing, refused or probe-tripped rows on any path, and on any declared expected path with no calls. engine_validate.sh declares the expected paths per arm (expected_paths). An unknown *_check arm gets none and fails, which is fail-closed. A path that a flag enables but the arm's algorithm never runs (DRAFT enables both draft families) is reported, not failed. That is the right reading of the rule.
  • Mixed batches (r4160186716). Patch 0009 (engine 9b5e82258d) requires not si.is_any_greedy. That field exists at the pin (sampling_batch_info.py:60, built at 254, OR-merged at 557), and tests/test_certified_engine_glue.py covers it. git am of 0001-0009 at bd66ce343e gives tree f1cef35d, which is the tree of 9b5e82258d.

Evidence (960ab39) and the conditions for not rerunning x9e2

  • (a) holds. git diff a28946e0d4 9b5e82258d is one hunk in certified_head.py: _fixed_noise_eligible's docstring and predicate, which only mtp_sampled_check exercises.
  • (b) holds.
    • x9e2_commit.txt and each arm's run_info record a28946e0d4 for the first five arms and 9b5e82258d for the other six.
    • For mtp_draft_check, the server installed the head at 20:41:55, and 9b5e82258d was committed at 20:42:05. The README says the file was modified at 20:41:58, so that arm ran a28946e0d4, and it does not exercise the changed predicate anyway.
    • mtp_sampled_check ran with 0008 and 0009.
  • (c) holds. engine_validate.sh --check-only at this head exits 0 on x9e2's seven check arms. Every expected path has calls, and no row differed, was refused or tripped a probe.
  • (d) does not hold as stated, and the README discloses it. The mid-run edit of engine_validate.sh did have a consequence: after the loop of arms, bash failed to parse the rest of the script (line 197), so the c = 1 comparisons did not run and the hold ended FAILED.
    • The arms themselves are unaffected. The loop and run_arm were parsed before the edit, and every arm printed its verdict.
    • The comparisons only read saved outputs. Rerunning engine_equality.py compare myself on x9e2/engine gives 64/64 identical for plain (14,995 tokens) and for MTP (14,990 tokens).
    • On the evidence I see no reason to rerun the GPU arms. Whether the disclosed deviation is acceptable is main's call under its own condition.

The table matches engine_v2.json

  • Calls, rows, fallback rows and fallback calls on every path are correct, including the DFlash draft projection at 2,120 of 53,580 rows (3.96%) and DFlash verify at 2,292 of 57,424 (3.99%).
  • No path has refused, probe, temperature or small-probability rows.
  • The largest certified batches (16, 32, 128, 8, 8, 120, 32) agree with each server's peak #running-req: 16 for plain, 8 for speculation.
  • engine_v2_gpu_tests.log shows 167 passed.

Checks

  • CPU tests pass (37, with 2 GPU-only tests skipped).
  • Pre-commit from main is clean.
  • The new commits have no hostname or AI attribution.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 960ab3964d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +281 to +282
+ if eligible:
+ _stage_sampling(_state[path], forward_batch, rows)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Check row capacity before staging sampled verification

When sampled verification receives more than 256 verification rows—for example, 65 MTP requests with four rows each—eligibility can be true and this stages inputs before set_gate() rejects the unsupported size. The staging buffers are fixed at _MAX_ROWS, so st.seeds[:rows] has length 256 while the repeated source has length 260, causing copy_ to raise instead of letting the larger batch use the stock path as intended. Check the row limit before calling _stage_sampling.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3646242 with patch 0010 (engine/kernel a3a4c8e99a). before_replay now checks the row limit (_fits, the same check set_gate uses) before staging the sampled-verify inputs, so a batch above it takes the stock path instead of failing in the copy. Patches 0001-0010 applied to bd66ce34 reproduce a3a4c8e99a's tree. A CPU test runs the patched glue in a subprocess with 65 requests x 4 rows = 260 rows. It expects the stock path and nothing staged, and it fails against 9b5e82258d with the 256-versus-260 copy error. The engine rerun (x9e2) is unaffected: its sampled batches had at most 32 rows, so the same batches were staged and certified (README).

Comment thread src/certified_head/quantize.py Outdated
Comment on lines +206 to +208
tmp = path.with_suffix('.tmp')
torch.save(qh.__dict__, tmp)
tmp.replace(path)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use a process-unique temporary cache file

When two engine processes start concurrently with the same uncached head, both write the same digest-specific .tmp path. Their torch.save operations can corrupt each other, and after the first process renames the file, the second process can fail at tmp.replace(path) because that pathname no longer exists, aborting server startup. Use a uniquely named temporary file and coordinate publication of the shared cache entry.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3646242. quantized_for and load_or_build now write through quantize.publish: a process-unique temporary file, an atomic os.replace onto the cache entry, and removal of the temporary file on failure. Concurrent builders of the same entry write the same data, so the last rename leaves a complete file and none fails. A CPU test completes a second build between the first build's save and rename. With the fixed .tmp name it fails with the race's FileNotFoundError; with the fix both builds succeed and one entry remains.

@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: REQUEST CHANGES (960ab39; withdraws my provisional approval. Codex's two new comments are valid. Neither affects engine_v2.json, whose arms ran at most 8 requests on one server.)

  1. r4160478421 (P1, patch 0004): sampled verify staged before the row limit. _stage_sampling copies rows seeds, positions and temperatures into buffers of _MAX_ROWS (256) before set_gate() rejects an oversize batch. With more than 256 verify rows (for example 65 MTP requests at 4 rows each), copy_ raises and takes the server down, instead of letting the batch use the stock path. Check rows <= st.max_rows(limit) (the same rule set_gate uses) before staging, and add a CPU test with an oversize batch. This needs a new patch (0010) and a tree check, like 0009.
  2. r4160478427 (P2, quantize.py:208): a shared temporary cache file. Two processes building the same uncached head write the same digest-named .tmp and race on replace. Use a process-unique temporary name (for example tempfile.NamedTemporaryFile(dir=path.parent, delete=False), or a .{pid}.tmp suffix), then os.replace, and accept an existing final file as success.

… atomically

Two Codex findings on 960ab39:

- Patch 0004 staged the sampled-verify inputs into the head's 256-row buffers
  before set_gate checked the row limit, so a larger eligible batch (65 MTP
  requests give 260 verify rows) failed in the copy and killed the server
  instead of taking the stock path. Patch 0010 (engine/kernel a3a4c8e99a)
  checks the limit first, with the same check set_gate uses. Patches
  0001-0010 applied to bd66ce34 give a3a4c8e99a's tree (9cd14d90). A CPU test
  runs the patched glue in a subprocess with 260 rows; it fails against
  9b5e82258d.
- quantized_for and load_or_build wrote the int8 cache entry through a
  fixed <entry>.tmp, so two engines building the same head at once could
  corrupt each other's file or fail at the rename. Both now use
  quantize.publish: a process-unique temporary file, an atomic os.replace
  onto the entry, and cleanup of the temporary file on failure. A CPU test
  completes a second build between the first's save and rename; it fails
  with the fixed name.

Neither change alters what x9e2 ran (README): its sampled batches had at most
32 rows, and its servers loaded the existing pinned cache entry.
@SamMausberg

Copy link
Copy Markdown
Owner Author

@codex review

@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: APPROVE (provisional, on 3646242: Codex has not reviewed this head yet. I will confirm or withdraw once it does.)

3646242 resolves both comments on 960ab39.

  1. r4160478421: the row limit before staging. Patch 0010 factors the row-limit test into _fits(path, rows), which set_gate uses. before_replay now evaluates _fits before _fixed_noise_eligible and before _stage_sampling runs. A covered size satisfies PathHead.supports (at most MAX_HEAD_BATCH = 256), so anything that passes _fits fits the staging buffers, and an oversize batch takes the stock path. git am of 0001-0010 at bd66ce343e gives tree 9cd14d90, which is the tree of a3a4c8e99a. The diff against 9b5e82258d is one file, +17 -4. The new subprocess test (65 x 4 = 260 rows) checks that nothing is staged and the gate stays shut.
  2. r4160478427: atomic cache writes. quantize.publish writes to <entry>.<pid>.<uuid>.tmp, calls os.replace onto the entry and unlinks the temporary file in finally. Both quantized_for and load_or_build use it. The concurrent-build test interleaves a second build between the first's save and rename.
  3. No effect on x9e2. The sampled arm's certified graphs were 4-32 rows, within the limit either way. ~/vp-data/kernel holds only the pinned entry Qwen--Qwen3.5-4B-851bf6e806ef-int8-sym-row-v2.pt, written 2026-09-30 18:58, and no sha256-* entry, so no x9e2 server wrote the cache. The README says both.

Checks. The CPU tests pass (39, with 2 GPU-only tests skipped), pre-commit from main is clean, and the commit has no AI attribution.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 36462420e6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: APPROVE (confirmed on 3646242)

This confirms my provisional approval. Codex found no issues on this head.

@SamMausberg
SamMausberg merged commit 14c6dd1 into main Oct 1, 2026
SamMausberg added a commit that referenced this pull request Oct 1, 2026
SamMausberg added a commit that referenced this pull request Oct 1, 2026
…ull; at most five sessions

Codex on 84717d2: the certified-head package's fingerprint is now part of the identity the
equality hold's preflight records before any run, and build and every later check require
it unchanged. The reused stock references must match bench's declared configuration
(flags with and without Triton attention, c1 pass, concurrency 1, 256 new tokens, top-5
logprobs, 320 prompts, cold cache, S0's model and prompt set with the same prompt token
counts), as must every stack equality run; the prompt file is pinned by hash from preflight
to build. analyze.py accepts sessions stack-s1 to stack-s5 only (three and at most two
replacements). expected.py's H note and the engine README reflect the merged #45/#52
and #133. Tests for each (98 pass).
SamMausberg added a commit that referenced this pull request Oct 1, 2026
…nce (#52)

Cold read of 1a22d86, appendix items (triage in the editorial move log):
- Register IDs: the notes print N-E21 and N-D24 (\regprefix in the shared
  register macros and in the notes' \evref/\devref), so an ID never means two
  things; check_paper_references.py gains check 8, which fails if the paper
  prints a prefix, the notes print none, or both match.
- Each pending marker in the appendices now follows words saying what is not yet
  done; the capacity item, which supports no paper claim, is stated in words and
  stays in the notes' pending list.
- Table captions go above the table throughout both documents.
- Number walls become tables: A.8's speculative positions (adding DFlash's
  5.7%/8.6% verification share from selfevidence_dflash4b.json), D.4's divergence
  rates, E.3's equality rates against stock references; the prose keeps every
  qualification.
- Project-history phrases go or are translated: "kill test", H/P labels, the
  divergence study's "first/pinned matrix" (now unpinned and pinned runs, defined
  once), "second panel", the commit wording in A.9 (the commit stays in the
  register entry).
- Appendix E's opening says it holds the serving protocol and the stock baseline,
  and that no served result for the certified head exists yet.
- Glossary: the last "row" used for a position is gone; twelve terms the main text
  uses now print with the main-text terms; the notes' glossary defines the old
  project terms its moved text keeps.
- E.2 says why the stock chain is 369.0 us in the profile and 370.5 us in the
  certified head's microbenchmark.

#52: register entry kernel-engine (the certified head in SGLang in check mode;
0 of 196,734 certified positions differed from the stock token; engine_v2.json,
not the superseded engine_v1.json). The contracts table's greedy and seeded cells
cite it, and the seeded pending item narrows to acceptance against the stock
rejection-sampling verifier; the notes' status row is updated.

Build: paper 53 pages, References on p10, notes 43 pages, 0 warnings in both;
checker clean.
SamMausberg added a commit that referenced this pull request Oct 1, 2026
Section 4.3 replaces the now-false 'untested on verification positions' with
the 64-prompt check inside SGLang (engine_v2.json): no certified position
differed from the stock head on any path; under the conservative model with
the whole-batch fallback, 1.38% of plain-decode positions fell back (24% of
head calls), 1.74% of MTP-4B verify positions (38%), and 3.99% of DFlash-4B
verify positions, in 90% of verify head calls. That the per-position fallback
would carry DFlash verification is stated as an inference. Section 3.3 adds
the in-engine seeded check (21,016 positions at T=0.7); acceptance against
stock rejection sampling stays pending. The abstract, the intro's draft-head
sentence and Section 7 follow. Every engine number keeps its scope: 64
prompts, conservative model, fallback mode, concurrency, untimed.
SamMausberg added a commit that referenced this pull request Oct 2, 2026
Sync TASKS.md with #45, #52, #91 and #120-#168; measured, derived and open per hypothesis
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant