Skip to content

Real-head replay: head-input capture, transport and self-evidence bounds - #16

Merged
SamMausberg merged 19 commits into
mainfrom
geometry/replay
Sep 30, 2026
Merged

SamMausberg merged 19 commits into
mainfrom
geometry/replay

Conversation

@SamMausberg

@SamMausberg SamMausberg commented Sep 30, 2026 •

Copy link
Copy Markdown
Owner

Real-head replay for H2 (transport) and H3 (self-evidence) on Qwen3.5-4B, with the capture patch, the bound library, the analyses and the first committed evidence. The PR stays open while the MTP-4B and DFlash-4B captures, which wait in the GPU queue, add the transport numbers.

What is here

  • Capture patch (engine/sglang/patches/0001-head-capture-replay-dumps.patch, capture only, inert unless SGLANG_HEAD_CAPTURE_DIR is set). LogitsProcessor stashes the exact tensor it hands to the LM head. The NEXTN/MTP, DFlash and plain-decode paths write one record per step with aligned draft and target head inputs (BF16 bits), the tokens, the engine's argmax and the accept lengths. return_hidden_states was not enough: it exposes neither the MTP draft's head input nor the DFlash target's head input, and it carries no per-step decisions. The patch applies cleanly to the pin (git apply --check) and is authored with the configured identity.
  • Prompt set: 320 public prompts (chat, code, maths, multilingual) from pinned dataset revisions, split by prompt into analysis and held-out halves before any fitting. The manifest has hashes only, no texts.
  • experiments/head_geometry/:
    • bounds.py: tilings; the paper's scalar, coordinate, grouped and low-rank transport radii; the static screen; int8, int4 and FP8 heads with row, blockwise and Hoelder envelopes; outlier-exact, rotated, centred and two-plane cascade variants. The accumulation terms are taken from the Accumulator models of src/precision_reference.py.
    • Analysis scripts for transport, self-evidence, rho, statistics, the P1 tail test and a work model, plus an alignment check.
    • tests/test_head_geometry_bounds.py checks that every bound encloses exact values on random BF16 heads. It skips without torch.

Findings so far (committed evidence)

  • Alignment (alignment_plain4b.json): the captured plain-decode head inputs reproduce the engine's greedy token at 99.51% of 105,269 positions. Every mismatch lies within one BF16 spacing of the FP64 winner, and BF16-rounding the exact logits reproduces the engine at 99.998%.
  • H3, R-real (selfevidence_plain4b.*, 6,005 held-out positions, 0 envelope violations):
    • int8 per-row with the row Cauchy-Schwarz envelope certifies with 1.55 candidate rows on average (p99 8), at 0.50 of the BF16 head's bytes.
    • int8 g128 with the blockwise envelope needs 1.34 (p99 5).
    • FP8 e4m3 needs 4.9 (p99 60). int4 alone has a median candidate set in the thousands.
    • Gumbel races at T = 1 and 0.7 match greedy.
    • Capture-run decode batches of 7-10 held-out rows need 9.5-12.5 distinct candidate rows.
  • R-stock (same file): the stock-kernel decision passes the stock_gap condition except at 1.9-3.0% of positions, depending on the accumulation model for the stock GEMM. Those rows need the stock kernel. The ~2% floor is set by the BF16 spacing: those positions have an exact top-2 margin below one spacing.
  • Why int8 suffices (stats_plain4b.json): the rigorous int8 envelope is about 1 logit, 75 times the realized error, but the median top-1/top-2 margin is 7.3 logits.
  • P1, negative (tail_killtest.json): an INT8 surrogate of the final FFN, even with an oracle error radius, lowers the single-candidate certification rate (71.8% versus 79.3% for the INT8 head alone). It can save at most 0.071 of the 1.41 GB tail, so certify the head alone.
  • H2: pending the held-out MTP-4B and DFlash-4B captures (not yet committed).

Checks

  • pre-commit passes on every changed file, including mypy on the whole tree after merging main. Earlier commits on this branch used SKIP=mypy because of 9 errors then pre-existing on main, none in the new files.
  • pytest tests/test_head_geometry_bounds.py passes (6 tests) in the SGLang venv.
  • .pre-commit-config.yaml now also excludes engine/sglang/patches/*.patch from the auto-fixing hooks. The whitespace hooks were rewriting the format-patch file, which must stay byte-exact to apply.

Not yet done

  • MTP-4B and DFlash-4B captures: the NEXTN run needs --max-mamba-cache-size 24, since otherwise the 0.25 memory fraction leaves one running request.
  • The H2 transport, rho and drift-scaling runs on them, and the self-evidence sets for MTP verify, MTP draft and DFlash.
  • The work-model outputs, committed with their inputs and labelled as a model on measured pass times.
  • The 27B DFlash2 pair, only if time allows.

A capture-only SGLang patch records the exact LM-head inputs (draft and
target, BF16 bits) with the draft tokens, target argmax and accept lengths of
each verify step, for NEXTN/MTP, DFlash and plain decode. Adds the seeded
public prompt set (320 prompts, split by prompt before any fitting), the
capture driver and client, record loaders and an alignment check that
recomputes both argmaxes from the captured inputs.

The whitespace hooks now skip engine/sglang/patches/*.patch so that
format-patch files stay applicable.
bounds.py implements tilings (contiguous, random, k-means), the paper's
scalar, coordinate, grouped and low-rank transport radii and the static
screen, integer and FP8 quantized heads with row, blockwise and Hoelder
envelopes, outlier-exact, rotated and two-plane (cascade) variants, and the
accumulation terms from the theory notes. The analysis scripts evaluate
candidate sets, skip fractions, partition widths, P_? and real-batch unions
on held-out captures. Tests check that every bound encloses exact values on
random BF16 heads.
analyze_rho.py computes rho = ||h_t - h_d||/||h_t|| on aligned pairs, the
per-row threshold ||e_i||/r_c(i) from 64-row mean-centred tiles (the PR #7
definition), head-metric drift ratios, realized per-tile errors of both
mechanisms and the resulting certification rates. The transport analysis gains
oracle (realized) tile radii as a ceiling and a drift-scaling replay
h_d(s) = h_t - s Delta that shows how much drift reduction transport needs.
Adds the DFlash-4B arm and CPU execution for the analyses.
analyze_rho.py now writes a per-pair CSV (position, outcome, domain, context,
rho) and a quantile table with the weight-only per-row thresholds, and
export_candidate_ccdf.py turns a self-evidence run's per-position candidate
counts into CCDF columns for the paper's figures.
Plain decode: the captured head inputs reproduce the engine's greedy token at
99.51% of 105,269 positions, every mismatch within one BF16 spacing.
Self-evidence on 6,005 held-out positions: int8 heads certify with 1.3-1.6
candidate rows on average at about half the BF16 bytes; FP8 and int4 do not.
P1 kill test: an INT8 final-FFN surrogate adds little beyond certifying the
head alone.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 30, 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-09-30T19:41:36.224650Z 277d392 PR opened
ℹ️ 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.

stats_plain4b.json records norms, margins, top-m mass, hidden-dimension
energy and head statistics, and for each quantizer the rigorous row envelope
against the realized error (about 75x wider) and why mean-row centring
enlarges the errors of the rows that compete for the argmax.

@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: 277d392af6

ℹ️ 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".

max_new="${MAX_NEW_TOKENS:-384}"
export SGLANG_WORKTREE="${SGLANG_WORKTREE:-$HOME/sglang-wt/geometry}"
# shellcheck source=/dev/null
source "$HOME/verified-progress/scripts/sglang_env.sh"

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 Source the environment from the detected repository

In the checked /workspace/verified-progress environment, HOME is /root and /root/verified-progress/scripts/sglang_env.sh does not exist, so every documented capture invocation exits here under set -e before launching SGLang. The script already computes repo from its own location on line 16; source $repo/scripts/sglang_env.sh instead so the required environment setup works regardless of checkout location.

AGENTS.md reference: AGENTS.md:L7-L10

Useful? React with 👍 / 👎.

For dense BF16, int8 self-evidence, transport and the static screen, count
weight, metadata and evidence bytes, kernels and fallbacks on the captured
batches, and price them with the profile workstream's measured head chain.
Outputs are labelled model predictions.
work_model.py accepts the kernel workstream's measured int8 envelope-pass
sweep and models both a batch-level dense fallback and per-row resolution of
undecided rows.
@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: REQUEST CHANGES

Reviewed at 0d2acd6 (the branch is current with main), whole diff. The plain-decode evidence is careful: the prompts are split before fitting, violations and missing winners are counted, and the rigorous-versus-realized widths are both reported. What needs fixing is how the evidence names its reference and its setup.

What I ran and checked

  • The capture patch applies cleanly to the pin (git apply --check in ~/sglang at bd66ce343e). I read it in full:

    • it is inert unless SGLANG_HEAD_CAPTURE_DIR is set;
    • the stash is taken with a forward-mode and row-count check;
    • plain, NEXTN (topk 1) and DFlash records store BF16 bit patterns;
    • the engine argmax is recorded from the same FP32 logits buffer the sampler uses.
  • Tests. pytest tests/test_head_geometry_bounds.py: 6 passed in the SGLang venv; it skips cleanly without torch in the repository venv.

  • Hooks. pre-commit on the changed files passes, including mypy. The SKIP=mypy note in the PR body is stale.

  • Reproduction. analyze_stats.py --arm plain4b --device cpu reruns in 43 s on CPU. Its output is identical to the committed stats_plain4b.json.

  • Numbers against the committed files. The README's H3 table matches selfevidence_plain4b.csv: int8 per-row, row Cauchy-Schwarz, tensor-core gamma, greedy gives mean 1.554, p99 8, max 30, 75.4 % single-candidate and 99.3 % <= 8. checks reports 0 violations and 0 missing winners over 6,005 positions and 160 prompts. The alignment figures match alignment_plain4b.json (99.507 %, 519 mismatches all within one BF16 spacing, 99.998 % after BF16 rounding, 1.0 % tied top-2).

  • Bound code. I read bounds.py for soundness:

    • tile radii and the scalar, coordinate, grouped and low-rank epsilons;
    • RTN and FP8 quantization, with exact FP64 error metadata and FP16 scales rounded up;
    • row, blockwise and Hoelder envelopes;
    • the outlier, rotated and two-plane heads;
    • the candidate filter.

    I found no unsound bound.

Blocking

1. Committed files cite the theory notes and use the retired contract name "C1".

  • Where:
    • evidence/head_geometry/README.md l. 13 ("contract C1 in the theory notes") and l. 38;
    • bounds.py l. 10 (~/vp-coord/notes/theory.md) and l. 543;
    • analyze_selfevidence.py l. 12-13 and l. 395, which writes "contract": "C1: ..." into selfevidence_plain4b.json;
    • analyze_rho.py l. 3;
    • experiments/head_geometry/README.md l. 18.
  • The rule. No committed file may cite ~/vp-coord or an unmerged branch as evidence.
  • Fix.
    • Call the reference R-real, as defined in the now-merged sources/manuscript_review.md and src/precision_reference.py from PR Certified low-precision head: exact reference, envelope, contracts and Lean lemmas #7.
    • Cite src/precision_reference.py and evidence/precision/README.md for the envelope recipe and the gamma values.
    • Change the string in analyze_selfevidence.py, so the JSON gets the new name when the evidence is next regenerated. Until then, the README maps C1 to R-real.

2. The H3 numbers are R-real only; the adopted contract is R-stock, and its fallback rate is not reported.

  • What is fine. The README says correctly that "exact" means the real-arithmetic value and not the stock kernel's output, and that the two differ on about 0.5 % of positions.
  • What is missing. The team's exactness contract is R-stock: return the stock head's token at this batch shape, and certify only when the gap condition holds; otherwise run the stock head. Under R-stock, every position whose final top-2 margin is below about one BF16 spacing (0.125 for logits in [16, 32)) plus 2G needs the stock-head fallback, whatever the candidate count. Here G is the stock GEMM's accumulation bound: with ||h||_2 ~ 160 and ||w||_2 ~ 0.65, the Khattak-Mikaitis gamma gives G ~ 0.01 logits.
  • What your data show. The margin quantiles in selfevidence_plain4b.json put q01 at 0.072 logits. The engine's top-2 BF16 logits were tied at 1.0 % of positions. So the fallback rate is at least about 1-3 %, and it is part of what H3 costs.
  • Fix. Report the R-stock fallback rate from the same 6,005 positions: the share where the exact top-2 margin is at most ulp_bf16 + 2G, using stock_gap in src/precision_reference.py. If you do not report it, state explicitly that the candidate counts are R-real and that the R-stock fallback is not measured.

3. The capture configuration is not stated with the evidence.

  • The setup. The plain-decode hidden states come from a server with:

    • --disable-cuda-graph --disable-overlap-schedule;
    • --mem-fraction-static 0.25;
    • --max-running-requests 16;
    • 384 new tokens.

    These are in run_capture.sh and engine/sglang/README.md, but not in the evidence README's "Common setup".

  • Why it matters. "Real decode batches of 7-10 rows need 9.5-12.5 distinct candidate rows" describes the capture server's eager batches, not the serving configuration.

  • Fix. Add the flags to "Common setup", and label the batch-union numbers as batches from the capture run.

4. An unverified mechanism claim.

  • Where. README l. 36: "the remaining two positions differ by cuBLAS accumulation at a rounding boundary".
  • Why. Nothing committed shows that mechanism.
  • Fix. Verify it, for example by recomputing those two rows with torch.matmul at the capture batch shape, or say "consistent with" and name what was not checked.

Suggestions (non-blocking)

  1. Idealized interval centres. The candidate sets centre each interval on the exact FP64 z_hat and add gamma * A. An online kernel centres on its own computed value, which can sit gamma * A away, so a conservative replay would widen by one more gamma * A (about 0.06 logits here). Apply that, or state that the counts use an idealized centre. The same applies to the FP32-rescoring overlap figure.
  2. Pre-commit exclusion is global. The .pre-commit-config.yaml exclusion of engine/sglang/patches/*.patch also hides the patch from the private-file, private-key and large-file hooks. Scope it to the whitespace and end-of-file hooks.
  3. Dataset licences. State the licence of each prompt source (MT-Bench, No Robots, HumanEval, MBPP, GSM8K, MATH-500, m-ArenaHard, MGSM) in build_prompts.py or the README.
  4. MTP capture configuration. run_capture.sh uses NEXTN with 4 steps and 5 draft tokens, while the profile and bench MTP arms use 3 and 4. Align them, or say why rho is measured at a different depth.
  5. For the MTP evidence to come: the first draft row comes from draft-extend hidden_states. Report the draft-side alignment per draft step, so a pre-norm or post-norm mismatch at step 1 would show up rather than be averaged away.
  6. Gumbel noise. The Gumbel races use torch RNG noise rather than SGLang's murmur3 field. That is fine for statistics; say so.
  7. PR body. It cites ~/vp-coord/notes/geometry.md for the H2 numbers. Drop that reference, since those numbers will come from committed evidence.

The accumulation gammas now come from the Accumulator models of
src/precision_reference.py (fused tensor-core adder, blocked FP32 tree). The
self-evidence analysis names its reference R-real and also reports the R-stock
fallback share: positions whose R-real winner fails the stock_gap condition
against some row. Alignment is reported per draft position, and the transport
CSV breaks down only the headline tilings and bounds.
- The capture patch is regenerated from an SGLang commit authored with the
  configured git identity (same content).
- READMEs name the R-real and R-stock references from the merged
  src/precision_reference.py instead of coordination notes, state the capture
  server flags, label batch unions as capture-run batches, describe the two
  unexplained plain-decode positions as consistent with (not proven to be)
  cuBLAS rounding, and justify the 4-step MTP capture against the 3-step arms.
- The DFlash-4B arm uses block size 16 with FlashInfer linear-attention
  backends, the configuration validated by the drafter workstream.
@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: REQUEST CHANGES

Re-reviewed at a577cfd. Items 1, 3 and 4 are resolved; item 2 is still open.

Resolved.

  • Item 1. No committed source file cites the notes or "C1" any more. The READMEs name R-real and R-stock from the merged src/precision_reference.py. selfevidence_plain4b.json still carries "contract": "C1: ..." until the evidence is regenerated; the script string is fixed, and the README defines "exact" as R-real, which is enough for now.
  • Item 3. The capture flags are stated, and the batch unions are labelled as capture-run batches.
  • Item 4. The two positions are now "consistent with" cuBLAS rounding, "not verified at the capture shape".

Also checked:

  • The regenerated patch carries the configured identity and still applies cleanly to the pin.
  • Hooks pass, including mypy, and 6 tests pass.
  • The 4-step MTP justification is sound: positions 1-3 are the same computation, and results are reported per position.

Still blocking: item 2, the R-stock fallback. The README now says R-real and R-stock differ on about 0.5 % of positions, but the H3 section still reports only R-real candidate counts. It does not say what R-stock costs. Under the adopted contract, every position whose exact top-2 margin is at most ulp_bf16 + 2G must run the stock head, whatever its candidate count. Your margin q01 is 0.072 logits, so that share is at least about 1 %. Either:

  • report that share from the 6,005 positions (stock_gap in src/precision_reference.py, with G from the tensor-core model for the stock GEMM); or
  • add one sentence to the H3 section saying the counts are R-real only and the R-stock fallback rate is not yet measured.

Non-blocking.

  • work_model.py has no committed output yet. When its predicted head times land, label them as a model that combines replay counts with the kernel workstream's measured pass times, and commit the pass-time inputs they use.
  • The PR body still cites ~/vp-coord/notes/geometry.md for H2 and says commits used SKIP=mypy, although mypy passes. Update it.

Rerun of the self-evidence analysis with the reference accumulation models:
R-real candidate counts are unchanged up to the last digit, and the new
R-stock measurement shows the gap condition fails at 1.9-3.0% of positions
(15-22% of capture-run batches), a floor set by the BF16 spacing.
@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: REQUEST CHANGES

Re-reviewed at 99b2d3f. Item 2 is resolved:

  • The new README section reports the R-stock fallback share from the reference's stock_gap on the same 6,005 positions: 3.03 %, 2.18 % and 1.95 % of positions, and 21.6 % to 14.8 % of capture-run batches, by gamma. The JSON records the same values (rstock_fallback_share, rstock_steps_with_fallback).
  • It explains the roughly 2 % floor as the BF16-spacing term.
  • The JSON now names its reference as R-real, and the H3 table is labelled as R-real counts.
  • Hooks pass, including mypy. The PR body is updated.

One new sentence blocks. "Resolving those rows one at a time keeps the cost small; running the dense head for the whole batch would not" (README, end of the R-stock section) has two problems:

  • It conflicts with the contract. R-stock is the stock kernel's decision at the served batch shape. Resolving an undecided row by itself runs the stock GEMM at a different M, so its token is the stock decision at another shape. Section 3.6 of the paper and the state workstream's observations show that this can differ. Per-row resolution therefore meets R-stock only if the stock kernel is batch-invariant for that row, which is not established.
  • The cost claim is not measured. work_model.py has no committed output.

Replace the sentence with a statement of what the table shows: the fallback runs the stock head at the served shape, for 15-22 % of capture-run batches. Say that a cheaper per-row resolution would need either a batch-invariant stock reference or a different contract, and that its cost is not yet measured.

@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: REQUEST CHANGES

Re-reviewed at 28a62c1. The rewritten paragraph is now correct about the contract: the R-stock fallback reruns the stock head at the served shape (15-22 % of capture-run batches), per-row resolution is valid only if the stock GEMM is bitwise batch-invariant, and neither fallback's cost is claimed.

One clause remains. "the kernel workstream has measured that for M = 1-256 on this stack but has not yet committed it as evidence" states a result, and a range, that rests on uncommitted work. That is the same standing rule applied to PR #6, where team measurements without committed evidence were removed. Replace the clause with "whether it is on this stack is pending the kernel workstream's evidence", or cite the committed file once it lands. Everything else in the PR is approved on my side.

analyze_rstock.py compares the stock_gap sufficient condition with a
bucket-exact rule that rounds each row's admissible accumulator interval to
BF16 and applies the first-index tie rule. On the same 6,005 positions the
bucket rule needs the stock kernel at 0-1.4% of positions depending on the
accumulation model, against 1.95-3.03% for the gap rule, and no certified
token differs from the engine's. The README no longer states the kernel
workstream's uncommitted invariance result.
@SamMausberg

Copy link
Copy Markdown
Owner Author

Verdict: APPROVE

Re-reviewed at ad9c43a. The last clause is fixed: whether row-wise batch invariance holds on this stack is now "pending the kernel workstream's evidence".

New scope: the bucket-exact R-stock rule (analyze_rstock.py, rstock_plain4b.json).

  • The rule is sound. Under the model, the stock accumulator is an FP32 value in [z - G, z + G], so it lies in the outward FP32 rounding of that interval. BF16 round-to-nearest-even is monotone, so its BF16 logit lies between the rounded endpoints. Certifying c requires lo_c > hi_b for every b < c, and allows lo_c = hi_b only for b > c, which is exactly torch.argmax's first-index rule. Choosing c as the first index attaining max lo can only make the rule conservative.
  • The gap rule is implemented as stock_gap (BF16 spacing 2^(floor(log2 x) - 7)), against every row.
  • The numbers match. The JSON matches the README table for all four gammas and both rules: gap 3.03 / 2.18 / 1.97 / 1.95 % of positions; bucket 1.40 / 0.35 / 0.017 / 0 %. There are 0 certified tokens that differ from the engine's.
  • Wording. The README describes that last result correctly, as consistent with the models and not a proof.
  • Hooks pass, including mypy, and the branch merges into main without conflicts.

Suggestion (non-blocking, before these numbers reach the paper): label which gamma a certifying kernel may rely on.

  • The stock head is a cuBLAS BF16 tensor-core GEMM. Under the Khattak-Mikaitis model its gamma is about 1.0e-4 (the 1.19e-4 row), and 6.11e-4 is the conservative default.
  • 1e-5 and 1.67e-6 (the IEEE FP32 CUDA-core tree) are not justified for that kernel.
  • A reader could otherwise quote "0 % fallback" as achievable. The earlier table labelled its rows; the new one should too.

@SamMausberg
SamMausberg merged commit d7ef173 into main Sep 30, 2026
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