Repository navigation
Certified int8 LM head: exact stock-head decisions, seeded sampling, kernels and evidence - #45
Conversation
src/certified_head/ builds an int8 copy of Qwen3.5-4B's tied head from the pinned checkpoint, with exact FP64 error metadata computed from the stored values (quantize.py), and certifies greedy decisions against a named dense reference (head.py): - a W8A16 Triton GEMM whose epilogue attaches an outward-rounded envelope to every approximate logit (PTX directed rounding) and keeps per-tile top-4 summaries instead of materializing M x V logits; - candidate compaction, FP64 re-scoring of candidate rows from the BF16 head, and a decision kernel that applies the reference's BF16 rounding and first-index tie rule; - a dense fallback that is the reference call itself, run as a conditional CUDA-graph node, so undecided rows cost time and never change the answer. bounds.py states the error model (tensor-core FP32 accumulation within gamma(2K, 2^-23) * sum|w h|, an assumption tested against cuBLAS) and computes every constant with exact rationals. Contracts: 'bf16' (SGLang's default head), 'fp32' (--enable-fp32-lm-head) and 'real' (exact real argmax, analysis only, with an exact rule for bitwise-identical rows). tests/test_certified_bounds.py checks the bound arithmetic on CPU; tests/test_certified_head.py covers envelope validity, the cuBLAS error model, equality with the reference for random, real and adversarial near-tie inputs, forced fallback, nonfinite inputs and CUDA-graph capture and replay.
bench/micro_head.py times the complete certified path (all stages plus the conditional fallback node), its stages, the int8 GEMM alone, SGLang's GPTQ- Marlin W8A16 kernel and SGLang's BF16 head plus argmax, each captured in a CUDA graph, with warm and cold L2 and per-trial variance. It also measures the fraction of real decode batches that take the dense fallback. bench/tune_gemv.py sweeps tile shapes of the W8A16 envelope GEMM per batch size; micro_head.py can use its output. experiments/certified_head/replay_decisions.py replays the geometry workstream's captured decode head inputs step by step, at the engine's batch shapes, and records candidate counts, undecided rows by reason, and agreement with the engine's own argmax and with the dense references.
Sampling: gumbel_sample now reproduces SGLang's seeded sampler (no top-k, top-p or min-p) token for token: logits.div_(T) in FP32, FP32 softmax and log, then multinomial_with_seed with its MurmurHash3 field keyed by seed, position and token id, FP64 Gumbel and first-index argmax. The softmax shift is common to a row; the rest (expf 2 ulp, logf 1 ulp, the subtraction and division, a subnormal-probability clause and the FP64 add) is bounded per row with an upper bound of the row's largest stock logit collected by the approximate pass. Undecided rows run SGLang's own sampler on the batch. Fallback: fallback_mode='columns' completes a row undecided only by a near tie among a complete candidate list with one stock matmul over its gathered candidate rows. It is enabled only through enable_column_fallback(batch sizes), which checks the gathered-GEMM shape bitwise first; 'batch' remains the default. A tile summary that overflows now appends its whole tile to the candidate list instead of forcing the fallback. Arithmetic: the approximate pass has three variants chosen per batch size: W8A16 (as before), W8A8 with per-row activation codes and exact int32 accumulation (envelope gains s_i ||q_i|| ||e_h||, loses the accumulation term), and BF16 (a certified dense head without the logits write). Any of them can load tiles through TMA descriptors. The stock accumulation model is selectable: 'conservative' or 'hopper-wgmma' (published hardware model). Soundness fixes: the rescoring radius adds 2^-100 for the stock kernel's FP32 underflow; norm bounds are stored at the same row stride the GEMM reads (a refactor-time mismatch caught by the tests before any commit). Tests: norm-bound layout regressions, W8A8/BF16 envelopes, lower-index rows within one BF16 spacing of the winner, column fallback with its self-test, CUDA-graph capture in both modes, seeded sampling against SGLang's sampler (including P8's witnesses over all 32,513 BF16 values in [-1, 1]), and the noise field against SGLang's own computation. 65 pass on the GH200.
experiments/certified_head/stock_invariance.py records, per batch size, the cuBLAS kernel the stock head runs, whether PyTorch's reduced-precision reduction flag changes it, row- and column-subset bitwise invariance (including the column fallback's gathered-GEMM shape), the observed accumulation error against both error models, and the library versions. experiments/certified_head/fallback_vs_model.py computes, on CPU in FP64, how the undecided fraction depends on the assumed stock accumulation bound. bench/head_primitives.py measures primitive costs for other workstreams' predictions (stock chain, int8 pass, tile-restricted BF16 GEMM, gathered-row rescoring, a draft-side tile-summary epilogue); bench/profile_gemv.py drives Nsight Compute; bench/summarize_head.py turns micro_head.json into the head-path CSV. micro_head.py now times each arm on a batch of rows its own certificate decides (row status does not depend on batch composition), measures fallback rates per configuration from consecutive real batches, adds the W8A8, BF16, column-fallback and seeded-sampling arms, releases each graph's memory pool, and writes results after every batch size; tune_gemv.py sweeps TMA variants and writes after every batch size. Default tiles are the sweep's winners.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1fdd347e6c
ℹ️ 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".
| top = torch.topk(x, TOP, dim=1).indices.sort(dim=1).values | ||
| xt = torch.gather(x, 1, top).numpy() | ||
| at = torch.gather(h.abs() @ w_abs.T, 1, top).numpy() |
There was a problem hiding this comment.
Include all potentially competitive rows
Selecting candidates solely with topk(x, 64) is not valid for nonzero gamma: a row outside the exact-real top 64 can have a larger a_i and therefore an upper endpoint x_i + gamma * a_i that overlaps the winner. Such a row is never passed to decided, so the generated fallback_vs_model.json can undercount undecided rows and does not support the documented claim that this exactly reproduces the GPU certificate. Candidate selection must consider the upper bounds over the full vocabulary, or first prove that every omitted row's upper bound loses.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. Fixed in d21b3c6 and 0c0bb7a. After the top-64 decision, fallback_vs_model.py bounds every omitted token from the full-vocabulary x and a it already computes. It checks each bound against the winning BF16 bucket with the kernel's threshold, and the JSON records the decided rows where an omitted token could compete (decided_rows_where_a_token_outside_the_top_could_compete, per gamma). Only there could a full-vocabulary decision differ. The docstring now says what the script decides, instead of claiming it reproduces the GPU decision exactly. The committed 20,000-row JSON predates the check, and a 60,000-row rerun with it is queued. The reviewer's independent check of 3,013 rows found no such token.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Verdict: REQUEST CHANGES Reviewed head acc415c (158 behind main; a trial merge into main is clean). This covers the code and contract, as the PR asks. The certificate is sound in the kernel code, not only in the reference: I checked the outward rounding, the threshold, the underflow terms, the tie rule and the fallback routing (details under "Checked" below). Four items block merge:
BlockingB1. The invariance self-test does not gate column mode (
B2. The contract omits that the approximate pass relies on the same accumulation model (
B3.
B4. The evidence the PR relies on is not committed (README "Pending in this PR").
Checked and correct
Suggestions (not blocking)
|
Review of PR #45 (B1, B3 and suggestions): - Column mode can no longer be selected in the constructor; only enable_column_fallback(batch_sizes) switches it on, and only for the batch sizes whose self-test passed (others keep the whole-batch fallback). The self-test now checks exactly the fallback's GEMM shape, M * min(capacity, COLS_CAP) gathered rows. The graph test enables columns through the self-test. - fallback_vs_model.py also checks every token outside each row's top 64 against the winning BF16 bucket and records the rows where one could compete, and states its population. - stock_multinomial_with_seed raises when SGLang is unavailable unless a test opts into the eager replica. - ABS_FLOOR's docstring states the flush-to-zero case it covers.
Review of PR #45 (B2, B3 wording and suggestions): - The evidence README's contract now states that the W8A16 and BF16 approximate passes rely on the conservative tensor-core model for their own accumulation, and that W8A8 accumulates exactly. - The observed accumulation error is attributed to the FP32-output kernel; for the BF16-output kernel the model is assumed. - The fallback-rate table states its population and how it compares with the GPU replay and the geometry workstream's held-out rows. - src/certified_head/INTEGRATION.md carries the SGLang integration notes in the repository. - run_all.sh records foreign CPU load around each timed step with the bench workstream's host-load helper.
micro_head.py timed batches and computed fallback rates over the first 16,384 real rows, which fall back more often than the 60,000 rows of the decision replay. The evidence script now uses the same 60,000 rows, the JSON records the pool size, and the summary states that its batches are consecutive rows in capture order rather than the engine's own batches.
|
Thanks. Status of each item at 0c0bb7a:
One correction to my own description: it said the partial table used pre-TMA tiles, and that TMA would bring the path from 228 to 197 us at M = 1. The table already used TMA tiles, and 197 us is the approximate pass alone in the sweep. The description now says so. |
The full-vocabulary check in fallback_vs_model.py counted every row where a token outside the top 64 reached the winning bucket, including rows that already fall back. Only decided rows can change, so the count is now over those, and the docstring says what the script decides instead of claiming it reproduces the GPU kernel exactly.
|
Verdict: REQUEST CHANGES This interim re-review covers head 0c0bb7a. B1 and B2 are fixed. B3 is fixed in code, but its evidence has not been regenerated. B4 is still pending.
Still needed before merge (B4, plus B3's rerun):
The interim description's formula and per-M inputs, including the 3-9 us column-mode overhead and the dense share in column mode, address the table points, once they are backed by the committed JSON. I will re-review when the final hold's commit lands. |
experiments/certified_head/p8_witness_cpu.py replicates SGLang's seeded noise in pure Python and evaluates the witness under SGLang's chain, an FP64 log of the same FP32 probabilities, and exact arithmetic. The noise equals the audit's values exactly; both FP32 and FP64 logs give token 1 at both temperatures, and only exact arithmetic gives token 0 at the lower one (boundary T* = 1.02533410). The witness separates SGLang's FP32-softmax chain from exact arithmetic, not the two log precisions; the README says so.
The W8A8 pass uses s_h = RN_fp32(max|h| / 127), which is not a power of
two. It needs none: the kernel forms e_h = h - s_h q_h in FP64 from the FP32
s_h that the epilogue also multiplies by, q s_h has at most 31 significant
bits, and the subtraction is exact (|x| >= 2^-16 s_h, or q = 0), so the
rounded-up group norms bound N2(e_h); the FP32 roundings of s_i s_h acc are
in scale_rel_error('w8a8').
The new test builds rows with non-dyadic scales, elements as close to
half-codes as BF16 allows over about a hundred codes, clamped codes where the
scale rounds down, subnormal elements next to a large maximum, and constant
rows. It checks the stored bounds against the exact rational error, and the
envelope and decisions against the exact logits.
BlockedTensorCoreModel.gamma summed the per-node errors linearly (n * p + gamma_n(2^-23) = 1.192097e-4 at K = 2560), which is below the compounded (1 + p)^n (1 + 2^-23)^n - 1 = 1.192164e-4 for n = 160 nodes. It is now (1 + gamma_n(p)) (1 + gamma_n(2^-23)) - 1 = 1.192216e-4, an upper bound of the compounded error (the appendix editor's report). The change is 1.0e-4 relative; the measured stock error is 58 times below either value. The bound test now requires the compounded product, and fallback_vs_model.py takes both model radii from the kernel's own models, rounded up to FP32, instead of printed constants.
Brings in engine/sglang/README.md, which the stacked SGLang integration (PR #52) documents its patches in.
The final evidence run found the W8A16 pass deciding almost no real rows in chunks of 256 rows, which the GPU tests did not cover: no test checked W8A16 envelope enclosure above M = 64. The new test runs every arithmetic at its default tiles for M = 1 to 256 on real decode rows, requires the envelope to enclose the exact logits, every decided row to equal the stock token, and the undecided share to stay near the replay's rate. large_m_check.py records the same per tile configuration (TMA and pointer loads at the same shapes) with the failing status bits.
At M = 1 the certified sampling arm failed under capture: its warm-up ran on a decided batch, so SGLang's torch.compile'd multinomial_with_seed was first compiled inside the fallback's conditional node. The harness now runs the stock sampler eagerly for each batch size first.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ee2998372a
ℹ️ 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".
| maybe_subnormal = y_lo <= ymax - 74.8 | ||
| lo = add_rd64(add_rd64(y_lo, -eps), g) | ||
| hi = add_ru64(add_ru64(y_hi, eps + tl.where(maybe_subnormal, 1.0, 0.0)), g) |
There was a problem hiding this comment.
Treat zero softmax probabilities as unbounded below
When a logit is sufficiently far below the row maximum, FP32 softmax can round its probability to zero, so the stock torch.log(probs) score is -inf; however, the maybe_subnormal branch only adds slack to hi and leaves lo finite. For a legal seed that gives the surviving high-probability token very negative Gumbel noise, this phantom finite lower bound can raise the row threshold, exclude the actual winner, and let gumbel_sample certify a different token instead of falling back. Set the lower score bound to -inf whenever probability rounding to zero is possible.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct; fixed in ec46d55, in host code. A probability rounds to zero only when expf(y - m) is subnormal, so only for y < m - 87.33, and the stock score is then -inf while lo stays finite. With the clamped noise of a hash-0 top token (-709.8), such a token can hold the best lower bound.
Setting lo = -inf inside stock_score_bounds would also hit the approximate pass, which calls it without the row maximum (ymax = +inf). Every lower bound there would become -inf, so every sampled batch would fall back. Only the winner's lower bound enters the decision, though: other tokens are excluded through their upper bounds, which stay valid, and the row threshold is compared with the winner's refined lower bound. A zero-probability token has lo <= y + g < m - 87.33 + 22.18 <= ymax - 65.1, since Gumbel noise is at most 32 ln 2.
gumbel_sample therefore sends a row to the stock chain (new status zero_probability) when its best refined lower bound is at most ymax - 64. This uses device ops only, so it is graph-safe. An ordinary winner sits within a few units of ymax, so this almost never triggers. The docstring now states the exception, and the derivation is in ZERO_PROBABILITY_GAP. A CPU test stubs the kernel stages with the buffers such a call leaves and fails without the guard. No kernel code changed.
There was a problem hiding this comment.
Follow-up in 2c36737 (reviewer): the same argument needs the winner's lower bound to hold for subnormal, nonzero probabilities too, and their absolute rounding error breaks the bound's model there. A subnormal or zero probability needs y < m - 74.84, and such a token's stock score is then below m - 52.66 in the bounds' units, whatever the rounding. The guard's gap is now 52, and it is renamed to small_probability / SMALL_PROBABILITY_GAP. Above the gap, the winner's probability is normal and its bound valid, and no small-probability token can reach its score.
|
Verdict: REQUEST CHANGES (ee29983, 1 blocking: Codex P1 r4158392867; both earlier items are fixed)
Blocking: Codex r4158392867 (
|
Stock's FP32 softmax rounds a probability to zero when the token's scaled logit is more than about 87.3 below the row's maximum, so its stock score is log 0 = -inf, but stock_score_bounds keeps a finite lower bound (Codex P1). If the top token's hash is 0, its Gumbel noise is the clamped -709.8, and such a zero-probability token can hold the best lower bound and be certified, although stock never returns it. Only the winner's lower bound matters for the decision: every other token is excluded through its upper bound, which stays valid, and the row threshold is checked against the winner's refined lower bound. A zero-probability token has lo <= y + g < m - 87.33 + 22.18 <= ymax - 65.1, while an ordinary winner sits within a few units of ymax. gumbel_sample now sends a row to the stock chain (status zero_probability) when its best refined lower bound is at most ymax - 64, with device ops only (graph-safe, no host sync). No kernel code changes: setting lo = -inf inside stock_score_bounds would also hit the approximate pass, which calls it without the row maximum (ymax = +inf), and send every sampled batch to the fallback. The docstring now states the exception. A CPU test stubs the kernel stages with the buffers such a call leaves and fails without the guard; the temperature test's stub now leaves a decided row. check_outputs.py expects 157 tests (36 CPU).
|
@codex review |
|
Verdict: REQUEST CHANGES (37cf29d, 1 blocking: the guard should also cover subnormal winners; the zero-probability fix itself is sound) ec46d55's approach is right, and better than the one I suggested.
Blocking: the same argument needs the winner's
Verified: ec46d55's guard code and the docstring exception. My CPU tests and pre-commit for c9f0440..37cf29d run in the CPU window (queued), and I will add the fix head to that run. An end-to-end GPU regression (a seed inverted so the top token hashes to 0) would be welcome but is not required. |
stock_score_bounds models a normal FP32 probability. A subnormal one also has absolute rounding error (expf and the division round to multiples of 2^-149), so near the underflow even a nonzero probability's lower bound can exceed the stock score, and the upper bound's extra unit need not cover expf's error there (reviewer, on ec46d55's zero-probability guard). A subnormal or zero probability needs y < m - 87.34 + ln S <= m - 74.84, and then the token's stock score is below m - 74.84 + 22.18 = m - 52.66 in the bounds' units, whatever the rounding. So when the winner's lower bound exceeds ymax - 52, its probability is normal and its bound valid, and no small-probability token can reach its score. The guard's gap is now 52 instead of 64, and the status bit, constant and method are renamed to small_probability. Docstrings state the model's limit; the CPU test's boundaries move (it fails with the 64 gap). No kernel code changes.
|
@codex review |
|
Verdict: APPROVE (provisional, on 9597557: Codex is running on this head, and my CPU tests and pre-commit for c9f0440..9597557 are queued in the CPU window. I will confirm or withdraw once both finish.) 2c36737 and 9597557 resolve my item from 37cf29d.
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 95975572f6
ℹ️ 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".
| for f in ${OUTPUTS[$name]:-}; do | ||
| [ -e "$REUSE/$f" ] && cp -p "$REUSE/$f" "$OUT/$f" | ||
| done |
There was a problem hiding this comment.
Refuse reuse when declared outputs are missing
When a selective run reuses a step whose steps.tsv entry is ok but one of its declared artifacts is absent, this conditional silently skips the copy and the function still records the step as successful. check_outputs.py does not validate every declared output—notably stock_invariance.json, the summarized head-path files, host-load records, and compile logs—so a clean output directory can finish with === done despite incomplete evidence, while an existing output directory can retain an unrelated stale artifact. Verify the required files before recording the reused step as ok and remove any pre-existing destinations before copying.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0f51832. A reused step now needs every output it declares; otherwise it is recorded missing and the run ends === FAILED. Every step removes its declared outputs before it runs, is reused or is skipped, so a stale file from an earlier run in the same directory cannot survive. run_all.sh writes the declared outputs to outputs.tsv, and check_outputs.py requires each of them and an ok status for every recorded step. A CPU test (tests/test_run_all_reuse.py) runs the script with every step reused from a fake earlier run that lacks stock_invariance.json (with nvidia-smi stubbed), and checks three things: the step is recorded missing, the stale copy is removed, and check_outputs names the file. It fails without the fix. No committed evidence is affected: x8s2 ran its steps directly, and x7c, the run that reused steps, holds every declared output of all its steps (checked).
|
Verdict: REQUEST CHANGES (9597557; withdraws my provisional approval; 1 blocking: Codex r4158539791) Codex finished on 9597557 with one comment, and it is valid.
Fix (shell only, no rerun):
Everything else on 9597557 stands as in my previous comment: the small-probability guard and its derivation, and no kernel change. My CPU tests and pre-commit for this range are queued, and I will retarget them to the fix head. |
reuse() copied only the declared outputs that existed in the earlier run and recorded the step as ok regardless, and check_outputs.py did not look at every output a step declares (Codex P2). A reused step now needs every declared output, or it is recorded "missing" and the run ends FAILED. Every step removes its declared outputs before it runs, is reused or is skipped, so no stale file from an earlier run in the same directory survives. run_all.sh writes the declared outputs to outputs.tsv, and check_outputs.py requires each of them and an ok status for every recorded step. A CPU test runs run_all.sh with every step reused from a fake earlier run that lacks stock_invariance.json (nvidia-smi stubbed): the step is recorded missing, the stale copy in the output directory is removed, and check_outputs names the missing file. It fails without the fix.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0f518324c3
ℹ️ 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".
| step tests 900 python -m pytest tests/test_certified_head.py tests/test_certified_bounds.py \ | ||
| tests/test_certified_head_inputs.py tests/test_enclosure_margin.py -q -s -p no:cacheprovider |
There was a problem hiding this comment.
Include the reuse regression in the evidence test step
The newly added tests/test_run_all_reuse.py is still omitted from the explicit pytest invocation, so run_all.sh can report a successful evidence run even if its missing-output reuse safeguard regresses. This is fresh evidence beyond the earlier complete-suite comment because that regression file was added after the four-file test command was introduced; include it here and raise MIN_TESTS so the output check enforces its execution.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Out of scope for this PR; it is done in a follow-up. No committed evidence depends on it. tests/test_run_all_reuse.py is a CPU test of the evidence script itself and runs with the repository's CPU suite (python -m pytest tests/, as the README gives it); pre-commit lints it. The evidence run's test step covers the certified head's own tests. Adding this file to that step and raising MIN_TESTS to match is a one-line change on the follow-up branch, which also carries the stress test's memory cap.
|
Verdict: APPROVE (0f51832) Re-review of 2c36737, 9597557 and 0f51832, with every check on this head complete.
Since x8s2, every change to the package (2ab57df, 09bf64e, 3b137c0, ec46d55, 2c36737) adds refusals or host-side guards, with no kernel code change. So x8s2's GPU evidence at 9f7f369 stands for every default path, as the README's commit table says. |
#52 was built on 9e3a39a, before the TMA-fault fix, the per-variant self-test gate, the runtime probes, the weight digest and the sampling guards. This merges main, which carries #45's final package, and resolves: - head.py: #52's device-gated stages keep #45's self-test gate outside the gated node (as the engine checks' tree 01502cc did); both gumbel_sample guards (temperature, small_probability) run inside the gated stages, so a batch the gate skips sets no fallback flag; enable_column_fallback keeps #52's extend parameter and #45's bf16-only refusal; sibling() carries the parent's weight_check, so a refused head cannot yield an accepted sibling. Every #45 tile exclusion and default is kept (#52 sets no tile). - engine.py, engine_validate.sh: 01502cc's changes (an unsafe head is refused at install; the stats record the self-test summary and probe stats; a check arm fails on refused or probe-tripped rows). - tests: both sides' appended tests kept. - evidence/certified_head/README.md: #45's files table plus #52's rows; the engine section says engine_v1.json ran on the pre-fix package and that the rerun, engine_v2.json, is the evidence for the merged package. - engine/sglang/README.md: the kernel section placed before repair. - evidence/README.md and experiments/README.md: certified_head rows.
evidence/certified_head (tma_repro.json and its README section) merged with #45, so the README points to it instead of describing the runs.
Appendices: cite the certified-head kernel's evidence (#45)
#45's evidence (evidence/certified_head) resolves most of the pending kernel entries. - Table 1 statuses: - The stock-error row is still assumed, now consistent with the FP32-output kernel's observed error, 58 times inside the Hopper model, and with the implemented 2^-100 floor. - Row invariance is measured at 20 batch sizes and re-checked at start-up. - The low-precision kernel is still not proved, but is checked per compiled variant at start-up and by runtime probes. The measured violation is named: int8 TMA tiles with a 64-byte box gave wrong raw products under Triton 3.7.1 and are refused. - Re-scoring is implemented and tested. - The seeded chain's rounding is bounded by CUDA's documented expf and logf accuracy and matched on 60,000 replayed rows. - Abstract and contributions: the TMA violation in contribution 2; the head-path runtime, timed alone, in place of "pending" (about 0.7 of the stock head's time up to 16 rows, slower from 128). - Section 4.3: seeded agreement on 60,000 replayed rows; acceptance in the engine stays pending (kernel-seeded-engine). - Section 4.4, reconciled with the held-out rates: the GPU kernel leaves 0.28% and 1.46% of the first 60,000 capture rows to the stock kernel (held-out: 0.35% and 1.40%), and with the fallback every token equals the engine's. On batches of 128 consecutive rows its measured fallback shares (27% and 77%) fall below what independent rows at its own rates give (30% and 85%). - Section 4.5: the pipeline as implemented (self-test, runtime probes, refused tiles), then the microbenchmark. 239.6 against 370.5 us at M = 1. With the column fallback's expected cost the path takes 0.67-0.70 of the stock time up to 16 rows, 0.81 at 32 and 0.93 at 64 (conservative model). Every mode loses from 128, where the int8 pass alone is slower than the stock chain. Head-only times; the served effect is pending. - Discussion: the measured error, and the open question narrowed by the microbenchmark. - Figure 3 gains panel (c), time per call over the stock head from head_path_time.csv. In (b), the kernel's measured per-M batch fallback rates replace the single capture-step markers. Cuts to stay within ten pages: - The candidate table and the fallback-share table move unchanged into Appendix A.3 (agreed with the appendix editor). Figure 3 and Section 4.4's text keep their headline numbers. - Section 4.5 loses the gather-size sentence. - Figures 3 and 4 are slightly shorter.
Paper: fold the certified int8 head (#45) into the main text
…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).
What this adds
src/certified_head/is a certified low-precision LM head for Qwen3.5-4B's tied head (248,320 x 2,560 BF16). For a batch of post-final-norm hidden states, it returns row by row the token that SGLang's own head returns for that batch:torch.matmul(H, W.T)(cuBLAS BF16 GEMM, FP32 accumulation, BF16 output), FP32 widening, thentorch.argmaxwith first-index ties.It works in four steps:
gumbel_sampledoes the same for SGLang's seeded sampler. The SGLang integration notes are insrc/certified_head/INTEGRATION.md; the engine patch itself will be a separate PR.Status. All evidence is committed at the final configurations:
evidence/certified_head/README.mdhas every result with its file, command and commit. The last shared-lock hold, x8s2, ran at the final code (9f7f369) and its results are committed in 85f48a5: compile 148 of 148 variants, 145 tests passed (121 GPU, 24 CPU), the stress test of all 10 default tile configurations under the margin rule (1.00–1.05 million row-checks each, 0 misses), the full TMA neighbourhood (misses only in the three non-default configurations x7b pointed to), and the SASS statistics at all three default tiles.Exactness contract
reference='bf16'is R-stock. A row is certified only if its winner is the same for every FP32 accumulation of the exact products within a named model, after the stock kernel's BF16 round-to-nearest-even and first-index argmax. Interval endpoints are rounded to BF16, a monotone map, so BF16 ties that hold in every admissible accumulation are certified and broken by index, as stock does.The two stock-kernel models are reported separately:
conservative: 2K roundings at 2^-23 of sum|w h|, in any order. This covers split-K with FP32 partials and truncating adders.hopper-wgmma: the Khattak-Mikaitis model of Hopper BF16wgmmaplus an FP32 split-K allowance. It rests on that published hardware model.The approximate pass needs a model too. The W8A16 and BF16 passes also accumulate on tensor cores (Triton
tl.dot); their own envelope uses the conservative model for that accumulation, whichever model is chosen for the stock kernel, and candidate exclusion and the threshold check rely on it. W8A8 accumulates exactly in int32. Withreference='fp32'these are the only model assumptions.Undecided rows are completed in one of two ways:
batch(the default) reruns the stockmatmulon the whole batch at the same shape. It needs no assumption.columnsfinishes a near-tie row, whose candidate list is complete, with one stockmatmulover its gathered candidate rows. It is exact under the stock kernel's measured row and column-subset invariance. The constructor does not accept it: onlyenable_column_fallback(batch_sizes)turns it on, and only for the batch sizes whose start-up self-test passed bitwise at the fallback's exact GEMM shape (M x min(capacity, 64)gathered rows). Other batch sizes keepbatch.Both fallbacks are conditional CUDA-graph nodes, so there is no host synchronization.
Seeded sampling (
gumbel_sample, temperature only) follows SGLang's chain:div_(T), then FP32 softmax and FP32 log;multinomial_with_seedwith MurmurHash3 noise keyed by seed, position and token id, an FP64 Gumbel draw, and first-index argmax.The softmax shift is common to a row. The remaining rounding is bounded with CUDA's documented
expfandlogfaccuracy, plus a subnormal clause.For fixed-noise sampled verification, the guarantees are:
Seeded top-k (FP64 log over sorted columns), top-p and min-p stay on the stock path.
reference='fp32'targets--enable-fp32-lm-head.reference='real'is analysis only.Kernels
quantize.py: symmetric per-row int8 with FP32 scales. The quantization error is computed exactly in FP64 from the stored values, checked with TwoSum, and cached with group norms under~/vp-data/kernel/.bounds.py: the error models and the envelope coefficients, all computed with exact rationals and rounded outward.kernels.py: one Triton approximate pass with three arithmetics, selected per M (W8A16; W8A8 with exact int32 accumulation; BF16 as a certified dense head), optionally with TMA loads.Evidence (final run x7c, B4)
Every figure below is in
evidence/certified_head/README.mdwith its file and command. The final run, x7c (46bcc84), reran what had changed and reused the rest;steps.tsvgives each step's commit and, for a reused one, why it stands:Six commits after 46bcc84 change package code, and x8s2 ran the correctness checks on all of them:
run_all.shworks withRUN_ALL_ONLYand no reuse directory (Codex);After x8s2, 2ab57df adds two host-side refusals:
build_quantized_headrefuses a suppliedhead_sha256that is not the digest of the weight it quantizes (Codex P1), andcheck_gemv_configrefuses int8 TMA tiles withblock_m >= 128(reviewer). 09bf64e sends sampled rows whose temperature is not finite and positive to SGLang's chain (Codex P2). 3b137c0 refuses the column fallback for any reference butbf16(Codex P1) and makesrun_all.shrun all four test files, withcheck_outputs.pyrequiring at least 157 passed and none failed or skipped (Codex P2). ec46d55 and 2c36737 send a sampled row to SGLang's chain when its winner's lower bound is within 52 ofymax, where a winner or a competitor might have a subnormal or zero stock probability (Codex P1, reviewer). None changes a kernel's code or a default path, so all were checked by CPU tests only:tests/test_certified_head_inputs.py, 15 passed; 7 fail without 2ab57df, 1 without 09bf64e, 2 without 3b137c0 and the guard's test fails without ec46d55 and with its narrower gap.d8b03ff merges main into the branch (no conflicts), so the host-identity guard from #111 runs on the evidence commit. None of the six changes the W8A16 pass's tiles or kernels, so x7c's timings stand for the W8A16 path. eb6ef57 changes nothing at the default
group_size = K, which every recorded evidence result used.Replay of 60,000 real decode rows (at the engine's batch shapes, at most 16 rows):
Seeded sampling at T = 0.7 and 1.0 equals SGLang's sampler on every row. The stock BF16 argmax differs from the exact argmax on 296 rows (0.49%).
Head-path runtime at M = 1, 8, 32. This is a microbenchmark of the head alone, not of decoding:
Where it stops paying. The certified head beats stock only at small batches:
The README has the table for M = 1–256, with both error models and both fallback modes.
Seeded sampling against SGLang's seeded sampler.
Fixes for the sampled path are proposed for a follow-up PR.
Stress test of the default tiles (x8s2, 9f7f369, the margin rule for every bound including the row's lower bound): every default (pass, tile) configuration, at every batch size from 1 to 256 that dispatches to it, on real and peaked rows: 10 configurations, the W8A8 and BF16 defaults from 2d1794a included, 1.00–1.05 million row-checks each, 0 misses on lower bounds, upper bounds, tile summaries and the probe flag. That bounds the per-row miss rate below about 3e-6 at 95%, if calls are independent trials, which a race need not be. x7c's run of the earlier defaults under the lenient row-lower rule (46bcc84) also had 0 misses.
TMA faults. Two TMA tile families of the W8A16 pass miss exact logits on this machine:
tma_m128_neighbourhood.json): only these three missed. All three have block_m 128, and 128x128x128 with 8 warps and 4 stages had a run with no miss, which the self-test would pass, so int8 TMA tiles with block_m >= 128 are now refused (2ab57df). No default has block_m above 64.Defaults, by the rule fixed before the results:
Conditional-node memory. A deleted CUDA graph with a conditional node keeps what the node's body allocated: 160 MiB allocated and 630 MiB reserved per capture-and-delete of five M = 64 bodies, with or without a shared pool.
INTEGRATION.mdrecords the engine implication as a known limitation, to be measured in the engine follow-up.Superseded: the earlier partial runtime table (second hold, x2). Its M = 32 and 64 rows used TMA tiles with block_k 64 (128x32x64, 128x64x64), the family of the first TMA fault. Treat them as suspect. Every runtime figure above comes from x7c.
Validation
tests/test_certified_head_inputs.py(7 fail without 2ab57df, 1 without 09bf64e, 2 without 3b137c0, the guard's test without ec46d55 or with its 64 gap); all 36 CPU tests pass at 2c36737.tests/test_certified_head.py(x7's 119 plus the weight digest and contiguity tests) and 24 CPU tests intests/test_enclosure_margin.py,tests/test_certified_bounds.pyandtests/test_certified_head_inputs.py(new). The weight digest check costs 0.96 s per head at start-up.experiments/certified_head/compile_check.pycompiles every kernel variant for sm_90 on the CPU before each hold.check_outputs.pyvalidates the outputs as well as the exit codes:pre-commitpasses on all changed files.Limitations
Notes
sudofor counter access.x8s2_gpu_memory.csv; the README states it). Just before that window the GPU ran out: three allocations of 350-450 MiB failed at 15:19:34-40 with 81-379 MiB free and were retried after the allocator released cached blocks (x8s2_stress.log); other jobs allocating then could have failed. The cause is not established (likely PyTorch's caching allocator across 224 batch shapes). The results stand. The memory cap is in a follow-up PR; until then the stress script runs under the exclusive lock.Review comments
fallback_mode,enable_column_fallbackenables only the batch sizes that passed, the self-test checksM x min(capacity, 64)gathered rows, and the graph test enables columns through it.fallback_vs_model.pychecks every token outside the top 64 against the winning bucket and counts the decided rows where one could compete (d21b3c6, 0c0bb7a). The README and this description state each figure's rows (6d30754). The 60,000-row CPU rerun is committed (fallback_vs_model.json).src/certified_head/INTEGRATION.md; the 2.07e-6 is attributed to the FP32-output kernel;stock_multinomial_with_seedraises without SGLang unless a test opts into the replica;ABS_FLOOR's docstring states the flush-to-zero case (d21b3c6, 6d30754).fallback_vs_model.py(top-64 only): correct. Fixed as in B3.(1 + gamma_160(p))(1 + gamma_160(2^-23)) - 1= 1.192216e-4, and the bound test requires the compounded product. The Hopper-model rates measured so far used the old value, about 1e-4 relative smaller. The final hold and the 60,000-row CPU rerun use the corrected one.s_h = RN_fp32(max|h|/127)is not a power of two, and the envelope does not need one.e_h = h - s_h q_hin FP64 from the stored FP32s_hthat the epilogue also uses.q s_hhas at most 31 significant bits, and the subtraction is exact.e_hare rounded up.s_i s_h accare inscale_rel_error('w8a8').src/precision_reference.py:250, raising on underflowing subnormal products): fixed in the separate PR Round underflowing leaves in the precision reference instead of raising #43. The GPU counterpart is in this PR: the rescoring radius adds 2^-100 for the stock kernel's FP32 underflow.RN_bf16(max lo), and an adversarial test places a lower-index row within one BF16 spacing below the winner. The 20,000-row replay would probably not have caught a naivemax lofilter, because the envelope of about 1 logit keeps such rows as candidates. The unit and adversarial tests are the real checks.batchas the default.experiments/certified_head/p8_witness_cpu.py):steps.tsv. The x2 rows at M = 32 and 64 are marked suspect above (B4-6). x7 reran the GPU tests at d2712cb rather than reusing x6's. x7c reused that run, since the package was unchanged, sosteps.tsvshows tests reused from d2712cb. x8s reruns them at the final code (647427e).tma_m128_check: the margin rule (a bound must clear the FP64 logit by 1e-9 (1 + |x|)) is the package's convention and stays. Checking it showed the row's lower bound used the margin as a tolerance in the self-test, the stress test andtma_candidates; a9f1793 makes it strict, and a CPU test pins the rule. Every check recorded before passed under the lenient rule; the README says why the strict one cannot change them on those inputs unless epilogue 3's arithmetic differs from the other epilogues'.head.py,from_quantizedwithout checking that the quantization data belongs to the supplied weight): fixed in d3a2b13.from_quantizedcompares the data'shead_sha256with the SHA-256 of the supplied weight, read from the device in row chunks; the time is recorded inhead.weight_check.refused).head.py, non-contiguousweight,q,scale): fixed in d3a2b13. The constructor rejects strided tensors, and a GPU test checks all three.tune_gemv.pyrefactor in the reuse reason, and says the BF16 rule was applied as declared above 64 rows.kernels.py, the row norm withgroup_size < K): fixed in eb6ef57. The row norm now uses the factor for all K squares. A CPU test shows the old factor failing on adversarial rows with 200 groups. No recorded evidence usedgroup_size < K, and the README states this.build_quantized_headdid not recordhead_sha256, sofrom_quantizedrefused freshly built heads. It now records it.run_all.sh's reuse read/steps.tsvwhenRUN_ALL_REUSEwas empty. It now reuses nothing in that case, and a CPU dry run gets past every skip.kernels.py, the refine and probe kernels read 256 coordinates per step without a K tail mask, whilebuild_quantized_headaccepts any K divisible by 128): fixed in 9f7f369 by refusing such shapes. The constructor rejects a hidden size that is not a multiple of 256, and each pass launch rejects ablock_kthat does not divide it. The kernels are unchanged, and a CPU test checks K = 128, 384 and 2688.fallback_vs_model.py's docstring rounded the Hopper constant to 1.19e-4, below the derived 1.19216e-4; fixed in 8aa8319. Every kernel-facing constant already rounds up.quantize.py:170, a suppliedhead_sha256kept without checking it againstw): fixed in 2ab57df. The digest is always computed fromw, and a supplied one that differs is refused; a CPU test fails before and passes after.block_m >= 128refused incheck_gemv_config(2ab57df), with a CPU test on the three configurations that missed;INTEGRATION.mdnow names all three and says one had a run the self-test would pass; the test comment on the refused 128x128x64 tile is corrected;tma_m128_check.pyoverrides the refusal for its own diagnosis runs; the README's commit table says 2ab57df was checked by CPU tests only;x8s2_stress.log.x8s2_compile.log(148 of 148) is committed and cited, and the README cites the SASS statistics for the greedy 64-row tile's spills (none).head.py, non-positive temperatures accepted; a negative T reverses the score bounds): fixed in 09bf64e. Rows whose temperature is not finite and positive get statustemperature(device ops, graph-safe, no host sync) and take SGLang's chain. Seeds and positions need no guard (SGLang hashes them as uint64 and uint32, as the kernel does). A CPU test fails without the fix; no kernel changed.head.py, the column fallback computes BF16-output logits forreference='fp32'): fixed in 3b137c0 by refusing the combination inenable_column_fallback. No committed evidence or engine path used it (column heads are allbf16; the replay's FP32 contract uses the whole-batch fallback), so no GPU rerun. A CPU test fails without the fix.run_all.shran onlytest_certified_head.py): fixed in 3b137c0. The tests step runs all four certified-head test files, andcheck_outputs.pychecks the pytest summary (at least 156 passed, none failed, errored or skipped).kernels.py, a token whose FP32 softmax probability rounds to zero keeps a finite lower bound): fixed in ec46d55, host code only. Only the winner's lower bound enters the decision, and a zero-probability token's lower bound is belowymax - 65.1, sogumbel_samplesends a row whose winner's refined lower bound is at mostymax - 64to the stock chain (statuszero_probability, device ops, graph-safe).lo = -infinsidestock_score_boundswas not used: the approximate pass calls it withymax = +inf, so every sampled batch would fall back. A CPU test fails without the fix; the kernels' code is unchanged (docstring only).y < m - 74.84, and such a token's stock score is then belowm - 52.66in the bounds' units whatever the rounding; with the gap at 52 (was 64), a winner above it has a normal probability and a valid bound, and no small-probability token can reach its score. Renamed tosmall_probability/SMALL_PROBABILITY_GAP; docstrings and README state the model's limit. CPU-checked; no kernel code changes.run_all.shrecorded a reused step ok with a declared output missing, andcheck_outputs.pydid not check every output): fixed in 0f51832. A reused step needs every declared output or is recordedmissing(the run ends FAILED); every step clears its declared outputs before it runs, is reused or is skipped;run_all.shwritesoutputs.tsv, andcheck_outputs.pyrequires every listed file and an ok status for every recorded step. A CPU test (tests/test_run_all_reuse.py) runs the script with every step reused from a fake run that lacks one output, and fails without the fix. No committed evidence is affected: x8s2 ran its steps directly, and x7c holds every declared output of its steps.