bfp-quant: the bfp4 GPTQ pipeline, packer/unpacker and publish procedure (#62) #80

Merged
Grok merged 19 commits from bfp-quant into master 2026-09-25 23:05:33 +02:00
Owner

The bfp4 GPTQ pipeline: quantizer, packer/unpacker, the FP8-teacher accuracy gate, the
on-card gate and the publish procedure.

  • tools/bfp-quant/: bit-exact emulation of the tt-metal host bfp4_b/bfp8_b packer
    (with a C++ harness to prove it), RTN and GPTQ/LDLQ onto the bfp grid, the snapped-checkpoint
    writer, the bfp4-packed-v1 format (G2 at 20.56 GB instead of 68 GB, unpacking bit-exact),
    the calibration-Hessian collector and the arm verifier.
  • nix/bfp-quant.nix + nix run .#bfp-quant; the tt-metal rev is read out of flake.lock
    as text so evaluating the app never fetches tt-metal.
  • bench/bfpq/ harness and the P0/P1 records, including the four-arm battery
    (P / G1 / G2 / R2 plus the FP8 teacher) under bench/runs/bfpq-p1-arms/.
  • .claude/skills/bfp-quant/SKILL.md with the publish procedure.

Gates already recorded (LEDGER R-2026-09-25-gptq-g2, already on master): GPTQ all-bf4
(G2) is non-inferior to production against the FP8 teacher; RTN all-bf4 (R2) is the one arm
trending worse. The packed checkpoint passes the on-card gate — 980/980 device tensors
sha256-identical, 44/44 probes token-identical.

Master merged in first, no conflicts. Verified after the merge: docs/ still 11 files, no
root CLAUDE.md, AGENTS.md is the lean rewrite, QWEN36_PREFILLED_SLOTS_FIX still in
qwen36_vllm.py, and nothing PR #68 deleted came back — the 96 files added versus master are
all new tooling and records. Locally green: nixfmt --check, check-cited-records.py,
nix flake check, and the 41 ttx unit tests.

Refs #62, #72.

🤖 Generated with Claude Code

The bfp4 GPTQ pipeline: quantizer, packer/unpacker, the FP8-teacher accuracy gate, the on-card gate and the publish procedure. - `tools/bfp-quant/`: bit-exact emulation of the tt-metal host `bfp4_b`/`bfp8_b` packer (with a C++ harness to prove it), RTN and GPTQ/LDLQ onto the bfp grid, the snapped-checkpoint writer, the `bfp4-packed-v1` format (G2 at 20.56 GB instead of 68 GB, unpacking bit-exact), the calibration-Hessian collector and the arm verifier. - `nix/bfp-quant.nix` + `nix run .#bfp-quant`; the tt-metal rev is read out of `flake.lock` as text so evaluating the app never fetches tt-metal. - `bench/bfpq/` harness and the P0/P1 records, including the four-arm battery (P / G1 / G2 / R2 plus the FP8 teacher) under `bench/runs/bfpq-p1-arms/`. - `.claude/skills/bfp-quant/SKILL.md` with the publish procedure. **Gates already recorded** (LEDGER `R-2026-09-25-gptq-g2`, already on master): GPTQ all-bf4 (G2) is non-inferior to production against the FP8 teacher; RTN all-bf4 (R2) is the one arm trending worse. The packed checkpoint passes the on-card gate — 980/980 device tensors sha256-identical, 44/44 probes token-identical. Master merged in first, no conflicts. Verified after the merge: `docs/` still 11 files, no root `CLAUDE.md`, `AGENTS.md` is the lean rewrite, `QWEN36_PREFILLED_SLOTS_FIX` still in `qwen36_vllm.py`, and nothing PR #68 deleted came back — the 96 files added versus master are all new tooling and records. Locally green: `nixfmt --check`, `check-cited-records.py`, `nix flake check`, and the 41 ttx unit tests. Refs #62, #72. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Grok added 19 commits 2026-09-25 23:04:19 +02:00
#62 needs weights that sit exactly on the native bfp4_b grid so the host
packer becomes the identity. That is only safe if we reproduce the packer
bit-for-bit, including the parts that differ from a textbook block format:
the shared exponent is the max raw exponent chosen BEFORE rounding, a block
max that rounds past the binade SATURATES (1.9 -> 1.75) instead of bumping
the exponent, bits shifted below the mantissa are dropped with no sticky bit,
subnormal inputs are zero, and -0 loses its sign.

The reference is the verbatim upstream blockfloat_common.cpp / bfloat4.cpp /
bfloat8.cpp at the flake-pinned rev, compiled standalone against a shim that
replaces only logging/tracy/MetalContext/Tile. ttnn.from_torch(device=None)
was avoided on purpose: its host path constructs MetalContext -> tt::Cluster,
which opens /dev/tenstorrent on a card host (and `nix build .#ttnn` currently
fails eval on a narHash mismatch of the local tt-metal input anyway).

MEASURED (bench/runs/bfp-packer-emulation-20260924T093051Z.jsonl): 68 cases
x {bfp8_b, bfp4_b}, packed words and unpacked values bitwise identical to
the real code, incl. binade-edge, ties, exp_diff>31, subnormal inputs, bottom
of the exponent range, and real weights from Qwen3.5-9B-FP8 and a
Qwen3.8-27B-FP8 GDN layer (374M values). snap() is a fixed point of the real
packer on every case. Negative controls (exponent-bump, truncation,
half-away rounding) are all detected; an independent float reimplementation
agrees exactly.

The key layout fact for the quantizer: ttnn stores linears as W^T [in, out],
so one shared exponent covers 16 consecutive OUTPUT channels at one input
index -- every bfp block lives inside a single GPTQ column.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Because a bfp block is 16 output channels at one input index, GPTQ's
column-at-a-time error feedback composes with the block structure without
any coupling: a column's shared exponents are fixed when that column is
rounded, using the packer's own arithmetic, and the rounded block keeps its
max exponent, so the packer later re-derives the same exponent. Optional
per-block exponent search {e, e+1} stays exact because values on a coarser
grid are also on the grid the packer will pick. Neither claim is trusted:
every output goes through check_on_grid (fail closed).

MEASURED, synthetic only (bench/runs/bfp-quant-synthetic-20260924T094254Z.jsonl):
GPTQ beats RTN on the H-weighted proxy for every synthetic layer. The 16-23x
gain comes from a steep synthetic spectrum with outlier channels and is NOT a
prediction for Qwen; real Hessians are the P0 blocker. GPTQ with H = I
reduces exactly to RTN (unit test).

`quantize` writes bf16 safetensors for the selected tensors (untouched shards
symlinked), a manifest with per-tensor sha256 and a suggested distinct
tensor_cache suffix (a stale cache silently serves old weights).
MEASURED (bench/runs/bfp-packer-emulation-20260924T093819Z.jsonl): a snapped
9B gate/up checkpoint is a fixed point of the REAL packer (--expect-snapped);
the unsnapped down_proj fails the same gate, as it must.

`nix run .#bfp-quant -- {test,verify-packer,synthetic,proxy,quantize}`; the
tt-metal rev is read from flake.lock as text so the app never fetches the
tt-metal input.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Can't compute calibration Hessians without a large-RAM or CUDA box, so this
maps where plain RTN error sits, using the H = I proxy (relative MSE against
the FP8 weights dequantised the way production does). This cannot rank LDLQ,
because GPTQ with H = I is RTN.

MEASURED (bench/runs/bfp-proxy-hfree-20260924T092920Z.jsonl), layers 0-3,
30, 31, 62, 63 plus embed and lm_head:
- RTN bfp4 relMSE is 1.31-1.47e-2 in every group; RTN bfp8 is 5.5-6.4e-5
  (about 235x lower).
- 8-10% of bfp4 blocks saturate at the block max.
- The {e, e+1} per-block exponent search gains <= 0.1%, so it is not worth
  having.
- Every processed tensor passed check_on_grid.

The spread across groups is small because bfp4 is essentially a
constant-relative-precision format. Which groups can drop to bf4 therefore
has to come from activation-weighted (Hessian) error and the P1 KL gate, not
from weight statistics. Not measured: bf4-from-bf16 vs bf4-from-FP8 needs
the bf16 checkpoint, which no cluster host holds.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The H = I proxy cannot rank LDLQ, so P0 needs real calibration Hessians.
27B bf16 does not fit 4x10 GB, so collect_hessians.py runs the GPTQ-style
sequential pass: one HF Qwen3_5DecoderLayer at a time (the reference
transformers implementation, GDN included -- nothing re-implemented),
weights streamed from safetensors, activations data-parallel across GPUs,
H = sum x x^T per linear input all-reduced in fp32 (TF32 off).
Modules sharing an input share one file, symlinked per module into the
layout `quantize --hessians` reads.

Every 4th layer stores two disjoint calibration halves (H_a/H_b), so GPTQ
can be fitted on one half and scored on the other. In-sample GPTQ gain is
optimistic by construction, and the go/no-go uses the held-out gain.

Verified before touching the GPUs:
- test_collect_equiv.py (tiny random qwen3_5, 3 GDN + 1 attention layer):
  final hidden states match Qwen3_5TextModel to 1.7e-6. Every Hessian
  matches full-model hooks to 3e-7 relative, both single-rank and
  2-rank/held-out.
- CPU run of all 64 real ThinkingCap bf16 layers on 255 tokens gives
  next-token CE 3.748 nats. Production vLLM (Qwen3.8-27B W4A16) scores the
  same tokens at 3.677, so the layer-wise forward is right.

Calibration set (make_calib_set.py, manifest alongside the tokens):
256 x 2048 tokens, rendered with ThinkingCap's own chat template.
- 108 open-r1/codeforces-cots traces and 96 OpenR1-Math traces, both from
  Mixture-of-Thoughts with <think>.
- 52 windows of packed NousResearch hermes function-calling
  conversations.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The first real calibration run saved all 64 layers but then died in the final
CE check (full-vocab logits for every token do not fit a 10 GB card) and lost
the lm_head Hessian, because its group file had the same name as the
per-module symlink pointing at it. CE is now chunked and the group file is
named lm_head.H.safetensors.

The study no longer needs the production GPUs: extract_layer.py pulls one
layer's tensors (bf16 + FP8 with scales) into a mini-checkpoint and
remote_study.sh copies that plus the layer's Hessians to a CPU host, runs
study_hessian.py, and deletes it -- so vllm-pod stays up.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This is the first result that uses real calibration Hessians. We had synthetic
(16-23x) and Hessian-free numbers, and both were upper bounds. It covers 25 of
64 layers (184 modules): 16 full-attention layers held out, where GPTQ is fit
on one calibration half and scored on the other, and 9 GDN layers, in-sample
only, because every held-out layer is a full-attention layer.

Held-out GPTQ gains, i.e. the proxy-error ratio of RTN bf4 to GPTQ bf4:
attn_qkv 5.68x, attn_o 3.88x, mlp_down 3.71x, mlp_gate_up 2.63x.
In-sample GPTQ gains on GDN: gdn_ab 12.5x, gdn_qkvz 5.9x, gdn_out 2.40x.
Held-out shrinks the in-sample gain by 0.89 at the median and 0.48 in the
worst case. If that worst case applies to GDN, gdn_out falls to 1.14x. That
number is an estimate, not a measurement. The first #62 GO condition is met.
The EXL3-4bpw comparison has not been measured, so the verdict is
GO-PENDING-EXL3.

What moves the plan: GPTQ bf4 is still ~36x the error of RTN bf8 on
attention, and ~2.5x the ThinkingCap FP8 checkpoint's own error. The
bf8 -> bf4 move for attention/GDN has to be judged on the device accuracy
gate, not on this proxy.

Also: the skill runbook, and a merge that states which gains were in-sample.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Owner correction: the reference is the native FP8 checkpoint, not bf16. P0 had
measured bf4 error against bf16 weights. What the owner cares about is the
distance from FP8 as served, and a quantizer should start from FP8.
quantize_ckpt.py therefore runs GPTQ from W8, where W8 is the FP8 checkpoint
dequantized the way production does it, and scores it against W8.

On held-out layer 3 k/v it also scored the bf16 source against W8: GPTQ from
FP8 gives 1.32e-3 / 2.37e-3, GPTQ from bf16 gives 1.88e-3 / 2.86e-3. So FP8 is
the better source, as expected.

Two production-layout facts shaped the code:
- in_proj_a/b are fused per device as [a_d|b_d] with 24 rows each. One bfp
  block therefore straddles the two tensors, so they are quantized jointly in
  that order. verify_arm.py round-trips every per-device matrix through the
  real tt-metal packer.
- The lazy FP8 loader passes bf16 keys through untouched. assemble_ckpt.py
  can therefore swap the snapped tensors into the FP8 base without changing
  model code. attn/GDN bf4 is gated by QWEN36_ATTN_GDN_BF4 in copies of the
  image's loaders, and the gate changes weights only.

Modules that share a Hessian are stacked into one GPTQ run. Rows are
independent, so the result matches per-module GPTQ to float noise
(1.2082098e-3 vs 1.2082106e-3), with one column loop instead of three.

The first GPU GPTQ attempt on cfx-llm0 hit an OOM in RTN: the int64
temporaries of a 17408x5120 matrix are ~0.7 GB each. RTN is now chunked, and
the Cholesky is lean with an fp32 fallback. The checkpoint is built on CPU
after all, so production does not go down again.

tt-arm.sh follows the tt-card-slot protocol. It fails closed on the served
root and on the banners, and runs probes, retrieval, GSM8K and the standard
sweep per arm. teacher_fp8.py scores each arm's own continuation with vLLM
FP8 on the GPUs, and kl_reduce.py turns that into top-1 agreement and KL
lower bounds.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The whole GPTQ-from-FP8 checkpoint (64 layers, 448 units, 0 errors) was built in one
cfx-llm0 window. The OOM-then-fp32 fallback could not work: the traceback of the fp64
attempt keeps its temporaries alive. verify_arm now proves itself non-blind with a
one-ulp fault injection that must mismatch. The first P arm boot died because the GDN
loader's local 'import os' makes the global unbound in the whole function.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Assembly previously dropped every weight_scale_inv from the arm index, which
flips is_fp8_checkpoint off and routes the arm through the eager loader -- a
different code path from prod, so the A/B would not be clean. Scale entries are
now kept. Cache seeding hardlinks only tensorbins whose values do not change,
because cold builds reuse any tensorbin present.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The P0 proxy record measured error against bf16, but the owner treats the native FP8
checkpoint as lossless, so this adds a record measured against dequantized W8. On held-out
data, GPTQ beats RTN at bf4 by 1.8x on mlp_down up to 5.1x on attn_qkv. That is smaller
than the in-sample 2.1-6.8x, which overstates the gain. Quantizing from bf16 lands farther
from FP8 in 21/21 held-out units, so FP8 stays the source.

On the cards, all four arms are within GSM8K noise (56-58/60) and every arm sits at the
kv-accuracy ceiling. The bf4 attn/GDN arms decode 3.2-4.6 ms/token faster and cut makespan
by 2.8-6.2%. Because task accuracy cannot resolve the arms, the FP8 KL gate is what has to
decide.

Three teacher windows failed on environment differences between the job container and
prod: flashinfer needs ninja, which the image lacks and prod hides behind its JIT cache;
the vision-encoder profile consumed the KV budget; and the prompt_logprobs fp32 tensors
are not counted by vLLM's memory profile. teacher_fp8 now dedups identical continuations,
is resumable and deadline-bounded, and has been dry-run against a fake engine including a
crash and resume.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The on-card task battery could not rank the arms (GSM8K 56-58/60, retrieval at ceiling), so
the go/no-go rested on KL/top-1 against native FP8. On 9 paired deep probes (24k-32k), G2
has the lowest KL to FP8 (0.085 vs prod 0.111) and the highest top-1 (+2.8 +- 1.4 pp), while
R2 -- same bytes and speed as G2, RTN instead of GPTQ -- is worse than prod (KL +0.065 +- 0.045).
That is the answer to the question P1 was built for: moving attn/GDN to bf4 costs accuracy under
RTN, and GPTQ from FP8 buys it back. FP8 itself scores 59/60 GSM8K and 1.0 retrieval.

Coverage is deliberately stated as partial: the teacher scored 32 of 115 unique continuations
(the deepest) before its deadline, in one 47.8-min window.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The first upload attempt shipped G2 as it was assembled for the cards: the 31 GB FP8 shards
with the 496 replaced tensors still inside, plus 46 GB of grid-snapped bf16 -- a 4-bit quant
larger than its FP8 source. The snapped values are already bfp4_b codes in disguise, so the
checkpoint now stores them as such: 4-bit codes two per byte plus one exponent byte per
16-block, in the tt-metal packer's own block order, with the dead FP8 weight + scale_inv
copies dropped (896 keys). Every other tensor is copied byte for byte. MEASURED: 20.56 GB vs
31.24 GB of FP8 safetensors (-34%); unpack == snapped bf16 for 496/496 tensors, 703 copied
tensors sha256-equal to the base, fault-injection control caught.

One trap found by the packer's own fail-closed check: GDN in_proj_a/in_proj_b are NOT on the
grid as standalone tensors. Production fuses them per device ([a_d|b_d], 24 rows each) and GPTQ
snapped them in that order, so a 16-block straddles a and b. They are stored as one joint entry
per layer with its TP=2 split recorded, which is the only encoding that is exact.

The TT loader hook is a copy of the image's tt/weight_mapping.py (sha256 7e24c7dd...) that maps
codes back into the same lazy key space and prints QWEN36_BFP4_PACKED engaged; tt-arm.sh mounts
it with ARM_PACKED=1 and fails closed without the banner. packed-gate.sh is the on-card gate:
cold build from a fresh cache must write tensorbins sha256-identical to G2's, and the deep
probes must be token-identical.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The model card corrects the earlier draft, which said the FP8 shards had the replaced tensors
removed -- in that upload they had not; in this one no FP8 tensor is left at all. HF rejects a
relative license_link, so the card links the licence file by https URL.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The cold build from the packed checkpoint wrote layers 0-55 and every fully written tensorbin was
sha256-identical to G2's cache, then another agent's cache filled /var/lib/models-sata and
tt-metal died with serialization.cpp 'written == bytes'. The gate now refuses to start with less
than 25 GB free and reads the banner from every log, not only on a clean exit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Cold boot of the bfp4-packed-v1 checkpoint on the P150a pair with a fresh tensor cache, through
the loader hook (QWEN36_BFP4_PACKED engaged; attn/GDN bf4 x64): every tensorbin it writes equals
the one built from the bf16-grid G2 checkpoint, byte for byte, and the deep-context greedy probes
match G2's exactly. So the 20.56 GB packed checkpoint is the same model on the device as the
68 GB one, and every G2 accuracy and speed number carries over. The HF model card now says so
(repo still private, re-verified via API).

The gate ran before the host reboot, under the legacy lock. tt-arm.sh now also runs under the
ttx mesh slot (mesh-slot-run.sh + a vendored tools/ttx/lib/slot.sh from the ttx branch;
TTX_SLOT_HELD skips the legacy lock), per the tt-card-slot skill.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
#	flake.nix
The public Qwen3.8-27B release (#72) needs fresh Hessians for that
checkpoint, and cfx-llm0 had 12 GB free of 468. Owner approved deleting the
four ThinkingCap artifacts: the 118 GB Hessian set, the 46 GB snapped GPTQ
checkpoint, the 52 GB bf16 HF cache (FP8 is the quantization source, so the
bf16 copy was dead weight) and the local packed-G2 copies, which are on the
private HF repo -- API-verified intact first: 22 files, 20,582,480,526 bytes,
still private. 12 GB -> 248 GB free.

The Hessian set is the only one that costs a GPU window to regenerate
(~22 min), so its manifest is kept here as the record of what it contained.
scripts/check-cited-records.py still passes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
merge master into bfp-quant
All checks were successful
tt-stack-ci / Report upstream drift (pull_request) Successful in 8s
tt-stack-ci / Build simulators and check the host module (pull_request) Successful in 57s
4e38f8b53c
Grok merged commit 06ca0eb676 into master 2026-09-25 23:05:33 +02:00
Author
Owner

agent-gateway closeout (merged): cleared agent:* labels.
Hermes kanban card (if any) is left for Hermes to archive/complete.

agent-gateway closeout (merged): cleared `agent:*` labels. Hermes kanban card (if any) is left for Hermes to archive/complete.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitpartner/tt-stack!80
No description provided.