

# docs/weight-quant-w8a16.md
# Load-time 8-bit weight-only linears for a dense checkpoint (`ARBI_WEIGHT_QUANT`)

`ARBI_WEIGHT_QUANT=w8a16[:int8|:fp8]` stores a dense bf16/fp16 checkpoint's eligible linears one byte per
weight with a per-output-row fp32 scale, quantized on the card as each linear binds, so the bf16 matrix is
never resident. Activations stay in the model dtype. The same machinery serves Inkling 2's attention and
unembed (`docs/inkling2-mini-support.md` section 11, which also holds the fidelity bar and its table; this
page does not restate them).

## The seam

- **One flag**, `weight_quant` in `runtime_flags_fields_quant.py` (`off` default; a bare `w8a16` is int8).
  Its claim is `Inapplicable` on the canonical (EXL3) config with the boot counter `weight_quant`, which
  fires when a linear was stored 8-bit and refuses `flag_off` otherwise. A CLI spelling is not added:
  `cli/parser.py` and `cli/config_builder.py` are at or over the file-size ceiling and may not grow.
- **The swap seam is the quant-backend one.** `weight_quant/loader.py::apply_quant_if_present` builds a
  `W8A16Backend` when the checkpoint is dense and the flag asks, and runs the same swap, bind, tied-module
  rebind, `skip_weight_load` deferral and weight-map filter every other backend uses. The backend is not
  registered for detection: no checkpoint "is" W8A16, and a detector that answered from a flag would make
  every `detect_backend` consumer read a dense checkpoint as quantized.
- **Compute is shared with Inkling.** `w8a16/linear.py::w8a16_linear` is the one path (decode GEMV up to 64
  rows on a card, the fused prefill GEMM `w8a16/prefill.py` above; the bounded dense path stays for a host
  tensor or an fp32 activation); `W8A16Linear` and the TP mirrors in `w8a16/parallel.py`
  both call it. `W8A16{Replicated,Column,Row}ParallelLinear` and `W8A16VocabParallelLMHead` mirror the
  dense classes through the same `ColumnParallelMixin` / `RowParallelMixin` scaffold the FP8 and AWQ
  mirrors use, so gather, all-reduce, LoRA, `local_logits` and `org_vocab_size` behave as theirs do.
- **Policy, not an ad hoc list** (`w8a16/policy.py`, rules in its docstring). An architecture (model class) is
  recognized or refused. Every 2-D `.weight` of the checkpoint is classified into a module role by the
  architecture's own patterns; a matrix no pattern names is refused, never taken by default. Only
  `ELIGIBLE_ROLES` (`attn_proj`, `gdn_proj`, `mlp_proj`, `lm_head`: large dense matmuls in the decode path)
  can be taken, only when the architecture's `admitted` table cites the measurement for that role (a document
  and a heading that must exist, `tests/test_weight_quant_w8a16_generic.py`), and only above `MIN_ELEMENTS`
  (below it the saving is nil). Never taken: routers and gates, norms, embeddings (`--embed-quant`), the GDN
  recurrent-state writer `in_proj_qkv` and decay/beta `in_proj_a/b`, MoE experts, vision and audio towers,
  MTP and drafter heads (until measured), small matrices. A checkpoint with its own `quantization_config`
  (an `ignore` list included) or any detected backend is refused. `Qwen3_5Model` is the only architecture
  declared; the MoE class and every other model are refused by name.

## Refusals (each by name, none a silent dense boot)

| case | where |
|---|---|
| checkpoint already quantized (any detected backend) | `loader._with_load_time_backend` |
| an eligible tensor stored as anything but bf16/fp16/fp32 | `W8A16Backend.list_paths` |
| architecture without a policy (incl. `Qwen3_5MoeModel`) | `policy.policy_for` |
| a 2-D weight with no recognized module role; an eligible role with no cited evidence | `policy.classify` |
| checkpoint declares its own `quantization_config` | `policy.refuse_declared_quantization` |
| flag set but no linear eligible | `loader._confirm_load_time_quant` |
| a merged column-parallel projection in a policy | `W8A16Backend.quant_class_for` |
| malformed value | `policy.requested_format` |

TP: a shard dequantizes to exactly its slice of the unsharded matrix, because the scale reads a whole row
before any cut. A column-parallel rank keeps its rows' scales; a row-parallel rank keeps every row's scale and
its columns of the payload (`tests/test_weight_quant_w8a16_generic.py`). A fused-QKV or gate-up module has no
mirror; the Qwen3.5 family builds none the policy admits.

## The plan

`models/shape_only.py` reads `stored_bytes_per_element` off each deferred-bind module, so
`capacity_planner.header_weight_bytes` prices the stored bytes (payload plus the row's share of its scale; a
row-parallel rank's full-row scale is priced exactly because the per-element figure uses its local
`in_features`) and the shape cache is keyed by the flag. The decode/verify transient is
`W8A16LinearBase.transient_bytes(rows, dtype)` (zero up to 64 rows, at most `DENSE_TRANSIENT_BYTES` above);
the serving-step budget that prices it is the decode/verify-bucket pricing landing separately, and takes the
maximum over these modules.

## Validation on a card

Fidelity: `tools/weight_quant_validate/engine_arm_job.sh` is one arm per queued command job
(`--engine-recipe tools/weight_quant_validate/recipes/<arm>.json`). The dense arm decodes greedily and records
top log-probabilities of the `arm_forced` prompt set; every other arm, and the dense boot again (the noise
floor), is teacher-forced on that record (`--stage arm_dense.json`). `tools.weight_quant_validate.verdict`
applies the section 11 bar relative to the floor: mean KL within 10x the floor, top-1 within one point. The
console's own build-arm sessions score no fidelity across builds, so this is the one measurement outside the
console path; throughput is not: it is the console's paired A/B (`ab_decode.json` under `gpu submit --arm`,
concurrent arms on cards of one class, tokens counted not chunks, the base measured twice for the A/A).
What card-free tests cannot say and the jobs settle: the logits' movement on real weights, TP>1 on real
ranks, captured-graph replay of the multi-row verify shapes (`capture_safe_multirow` is the base default, not a
measurement), the MTP head over an 8-bit `lm_head`, and the tok/s itself.

## Open items

- GPT-OSS 20B is out of scope.
- `in_proj_qkv` and the MoE shared experts stay dense until measured; a merged column-parallel mirror
  is needed for any model that builds gate-up or QKV fused.
- A CLI option needs `cli/parser.py` split first.

## Measured: Qwen3.5 dense, 8-bit weight-only

Model: Qwen3.5-4B, a stand-in for the 27B (no dense 27B arm exists anywhere). It ties its embeddings, so
`lm_head` is not quantized and the MTP head over an 8-bit head is NOT exercised here. Covered linears: attention,
GDN output and gate, dense MLP. Card: one RTX 4090 (sm_89), the same card class for every arm below. The
checkpoint is the one `tools/weight_quant_validate/recipes/` names; sampling is the served default (T=1.0,
thinking on) for the A/B, and the fidelity jobs teacher-force the dense boot's greedy tokens.

**Fidelity** (`tools.weight_quant_validate.verdict`, 8 prompts, 1013 scored positions, `arm_dense.json` from
`wq-fid-dense-n-376474`; floor = the dense boot teacher-forced on itself, `wq-fid-rerun-34bc8c`):

| arm | mean KL | worst-position KL | top-1 vs dense | against the bar |
|---|---|---|---|---|
| dense vs dense (floor) | 6.43e-5 | 7.72e-3 | 100.00% | bar: KL <= 6.43e-4 (10x floor), top-1 >= 99.0% |
| W8A16 int8 | 8.10e-4 | 2.80e-2 | 99.61% | KL OUTSIDE (12.6x floor), top-1 inside |
| W8A16 fp8 (e4m3) | 2.67e-3 | 1.01e-1 | 99.11% | KL OUTSIDE (41x floor), top-1 inside |

Verdict: neither arm meets the section 11 bar; int8 exceeds the KL bar by 26% and passes on top-1,
fp8 misses it clearly. For scale, Inkling's own int8 attention read KL 3.1e-3 and 99.03% top-1, so int8 here is
about four times closer to dense than that; whether that is acceptable is the owner's call, not this table's.
The floor is not zero (the engine reorders reductions run to run), which is why the bar is relative to it. An
earlier int8 head (`c6fd00b8b`) read 7.81e-4 / 99.70%, the same result within the run-to-run spread.
The measurement is one 8-prompt set at 4B scale; it says nothing about the 27B.

**Decode throughput** (console paired A/B, `wq-ab-*-34bc8c`, one RTX 4090 per arm slot on `gpu-dev-104`, the dense
boot measured twice for the A/A, 3 reps, 128-token prompts, `--mtp-n-draft 3`, sampled at T=1.0). Ratios are
paired per rep (arm against the dense slot beside it); negative TPOT is faster. TPOT is seconds per token counted
from tokens, not chunks. The A/A row (`dense.2` against `dense`) is the noise reading.

| concurrency | int8 TPOT | fp8 TPOT | int8 TTFT | fp8 TTFT | A/A TPOT |
|---|---|---|---|---|---|
| 1 | -18.1% [-18.2, -18.0] | -14.2% [-16.5, -11.9] | +104% | +99% | +0.22% / +0.34% |
| 4 | -22.4% [-22.6, -22.2] | -25.8% [-38.5, -13.1] | +96% | +96% | +0.13% / -3.7% (unresolved) |

The same A/B on one RTX A5500 (sm_86, `wq-ab-int8-81b-34bc8c`, int8 only; fp8 is refused there): TPOT -23.3% at
c=1 (interval [-50.9, +4.2], not resolved at 3 reps; the dense TPOT there is 5.9 ms) and -16.3% at c=4 ([-18.1, -14.5]),
TTFT +42% and +28%, prefill 897 vs 630 tok/s at c=1.

Prefill is the cost: 128-token prefill runs at about half the dense rate (int8 1646 vs 3359 tok/s at c=1) because
rows above 64 widen a bounded block of weight at a time instead of running an int8 GEMM. Prefill through the int8
GEMM is the deferred follow-up. The fp8 interval at c=4 is wide (3 reps).

**Memory** (boot ledger, same card, `max-context 8192`, `--max-batch 4`):

| | dense | int8 | fp8 |
|---|---|---|---|
| `model.weights` | 6.660 GiB | 3.812 GiB | 3.812 GiB |
| KV capacity | 421,248 tokens | 508,288 tokens | 508,288 tokens |

**Boots.** fp8 needs compute capability 8.9 (Triton compiles no e4m3 operand on Ampere); `ARBI_WEIGHT_QUANT=w8a16:fp8`
on an sm_86 card is refused by name at the flag. An fp8 slot booted on the sm_86 node before that refusal existed and
died in the activation profile with `type fp8e4nv not supported in this architecture`.

**27B smoke** (`wq-smoke-27b-int8-tp2-34bc8c`, Qwen3.8-27B int8, TP2, mixed A5500 + A5000 pair on the sm_86 node):
boots, `loader: w8a16 codec: 353 linears`, KV capacity 257,920 tokens, five prompts answer coherently, and the
served boot logs no `JIT-COMPILING` line (`jit-compiling lines: 0`; the first of two boots in the job, the census
boot, compiled 14 triton and 18 dynamo entries and the second compiled none). The pair is mixed, so the tok/s the
job printed is discarded; there is no quality claim for the 27B.

**Not measured:** TP2 on a 4090 pair (no 4090 node pair holds the checkpoint without a mirror copy), the MTP head
over an 8-bit head, any 27B quality, prefill through an int8 GEMM, long-context fidelity.

Status: the table above is the measurement the `admitted` entries cite. The option stays off by default, and
int8 does not clear the bar it was held to.

**Recommendation among the decode arms** (below). (a), this PR's per-row scale, buys 43% fewer weight bytes and
18-22% faster decode at 4B for a KL 12.6x the floor. The next measurement is (b), the GGUF Q8_0 arm over the existing
int8 GEMM glue, because per-32 scales are the likeliest fix for the KL gap and need no new kernel; its decode rows
1-8 read exact activations and the rest read rounded ones, which the arm job must report. (c), per-32 scales in the
Triton kernel, is built only if (b)'s decode rate or its two numerics rule it out. Prefill through the int8 GEMM is
the follow-up the owner wants and is not built here.

## Decode arms (design note, not implemented)

Owner question: on a bf16 dense linear set, which weight-only 8-bit decode arm, each judged against the dense
boot. Bytes are per weight read by a decode step (dense bf16 is 2.0).

| arm | weight scale | activation | bytes/weight read | rows it serves |
|---|---|---|---|---|
| (a) W8A16 per row (this PR) | one fp32 per output row | bf16 as is, fp32 accumulate | 1 + 4/K, about 1.0008 | decode GEMV to 64 rows, bounded dense above |
| (b) GGUF Q8_0 | one fp16 per 32 of k (34 B per block) | GEMV route: staged fp32, none rounded; int8 GEMM above 8 rows: rounded to int8 | 1.0625 on the GEMV (plus resident planes below) | GEMV rows 1-8 only on cells the boot race gives it; int8 GEMM for the rest |
| (c) W8A16 per 32 in the Triton kernel | fp16 per 32 (1.0625) or fp32 (1.125) | bf16 as is | 1.0625 / 1.125 | same as (a) |

Facts read from the code, not measured:

- (b)'s decode arm is `gguf/gemv_route.py`: a SIMT weight-decode GEMV that "quantizes no activation" (fp32
  staging), rows 1-8 (`AG_LAUNCH_MROWS`), tag 8 (`Q8_0`) is in `GEMV_BAKED_TAGS`, both axes a multiple of
  `GEMV_TILE_ALIGN` (128), and which rows a cell takes is a boot race on the serving card. Above that, and in
  prefill, Q8_0 is served by the int8 GEMM, which rounds the activation: `gguf_serving_shape` returns entry 193
  (per-token activation scale) without and 252 (per-(row, k-group) scale) with `grouped_activation` for
  Q8_0's float-scale family, checked by execution; which one a bind takes is `gguf/linear.py`'s re-ask and
  is read off the bind log. So (b) has two numerics on one model: a decode row count of 1-8 reads exact
  activations, a verify slate of `batch x (K+1)` above 8 rows does not.
- (b)'s resident bytes exceed its read bytes: Q8_0 binds `d` again for the GEMV beside the float-scale plane
  the GEMM reads (`gemv_route` module docstring; `tools/gguf/resident_plane_census.py` prices a pack). KV
  headroom is therefore a measured column in the job, not a derived one.
- A bf16 -> Q8_0 quantizer exists: `attn_sidecar_build.q8_0` (ggml's rule, fp16 `d`, codes rounded against the
  stored `d`) with `repack_decomposition`, used offline by `scripts/convert_drafter_q8_0.py` and at load by
  `gguf/ct_planes.py` for compressed-tensors INT8. What does not exist is the bf16-origin load path:
  `ct_planes` starts from an int8 checkpoint. The cache would follow it: planes written once per source
  checkpoint under the boot cache (`boot_cache_subdir`, `<format>-<digest of the source shards, the linear
  list and the rounding version>`, a `.complete` marker, a flock build lock, 1 GiB shards, `.last_used`),
  bound through the GGUF backend. The bf16 -> planes pass costs one read of the checkpoint on first boot, so
  it is a cache or an offline convert, never per boot.
- `A_PREP_MAX_IN_FEATURES` is 24576 (192 blocks of 128). `refuse_wider_than_the_prep` refuses any GGUF
  linear wider than that at bind, on this rank's `in_features`, even where only the GEMV would serve it. The
  Qwen3.5 family's widest eligible contraction (the dense MLP `down_proj`) is inside it at the sizes read
  from the fixture config; the 27B's own dims are to be confirmed from its `config.json`. A model whose
  linear is wider keeps that linear dense, as `convert_drafter_q8_0` does with `quantization_config.ignore`.
- For prefill, the owner's constraint stands (no plain per-token int8 GEMM). Q8_0 on the int8 GEMM with the
  grouped activation entry (252) is the candidate; the GGUF glue's activation prep has no rotation, so one
  heavy channel spoils a group instead of a row. Whether that is acceptable for a bf16-origin dense model is a
  model-specific question that `docs/gguf-int8-activation-plane-bar.md` poses for GGUF packs and that only the
  arm below answers.
- (c) changes `w8a16/kernel.py` where it is simplest: the contraction loop keeps one accumulator and applies
  the row scale once, which relies on an int8 or e4m3 weight being exact in bf16. Per-32 scales need one
  `tl.dot` per 32-wide group of each `BLOCK_K` chunk and a scale multiply on the fp32 accumulator per group
  (exactness kept), or a widened-and-scaled weight tile (one more bf16 rounding of every weight). Either
  adds a scale-tile load per chunk, a `GROUP` specialisation beside `MULTI_TILE`, a new payload and scale
  layout in the quantizer, the TP cut on whole groups, and the dense path's `dequantize_rows` taking a
  group axis. It is a new kernel, not a parameter.

What decides it. One job, three decode arms and the dense boot (twice, for the floor), over the `arm_forced`
prompt set, on the section 11 bar:

1. Per arm: mean KL and top-1 against the dense boot, relative to the dense-versus-dense floor
   (`tools.weight_quant_validate.verdict`); the worst-position KL and which prompt owns it.
2. Paired tok/s at concurrency 1 and 4 (and the verify width if a drafter is on), `decode_bench`.
3. Card memory used and KV pages (resident, not read, bytes).
4. For (b): the bind log's entry per linear, the boot race's row set per cell, and the KL of decode rows above 8.

Reading it: if (a) is inside the bar and not slower than (b), (a) ships and nothing else is built. If (a) is
outside and (b) inside, the difference is groups, exact activations at 1-8 rows, or both; (c) separates them
(groups with bf16 activations at every row count) and is built only then. If (b) is faster at batch 1 by more
than its extra 6% of bytes can explain, the GEMV's better streaming is the lever and belongs in the W8A16
kernel instead.


## Group scales and the fused prefill GEMM

**Formats.** `w8a16:int8g32|int8g64|int8g128` store the int8 payload with one fp32 scale per G input columns
(`weight_scale` is `[out, in/G]`; the flag token names the group, so a flat dump of one format is never read as
another). Extra bytes over per-row int8 are 4/G per weight: 12.5%, 6.25%, 3.1% (fp32 scales). Both kernels scale
each group's partial sum in fp32 (`BLOCK_K` is the group), so activations stay unrounded. Row-parallel TP keeps
each rank's groups and refuses a cut through one.

**Prefill.** Above 64 rows `w8a16/prefill.py` streams the 8-bit weight tile, widens it in registers and feeds the
tensor cores (fp32 accumulation, scale as the decode kernel applies it). It allocates only its output, so the plan
prices no transient for a bf16 or fp16 activation (`dense_transient_bytes`). It agrees with the decode kernel to
fp32 rounding, not bit for bit (a different `BLOCK_K`). Its launch config is shape-keyed
(`prefill_launch_config`); `tools/weight_quant_validate/prefill_microbench.py --sweep` is the measurement that
names the winner per shape on a card.

**Card-free error signal** (`tools/weight_quant_validate/stage0_cpu_signal.py`, Qwen3.5-4B layers 0/3/19, 19
matrices, Gaussian activations with 1/256 channels at 20x; the proxy has no captured activations): relative
output error, mean over matrices: per-row 9.93e-3; per-row with a 0.80..1.00 clip-ratio search 9.82e-3 (-1.1%);
g128 6.70e-3 (-32.5%); g64 6.09e-3 (-38.6%); g32 5.45e-3 (-45.1%). A clip search buys nothing at 255 uniform
levels, so it is not shipped; group scales are where the error goes. The KL on a card (teacher-forced vs the dense
record) is the fidelity number; this table is only the cheap first signal.

**Prefill microbench** (`w8a16-pf-micro-1`, one RTX 4090, `prefill_microbench.py --sweep`, Qwen3.5-4B shapes, median
of 9, each 8-bit row at its swept-best config; `dense` is `F.linear` on the bf16 weight). Ratio = 8-bit time over
dense time, smaller is faster:

| M (rows) | bounded dense path (the #6977 prefill) | fused per-row int8 | fused int8g64 | fused int8g32 |
|---|---|---|---|---|
| 512 | 2.24 - 4.45 | 1.03 - 1.50 | 1.09 - 1.75 | 1.17 - 1.76 |
| 1024 | 1.67 - 2.68 | 0.97 - 1.22 | 1.04 - 1.27 | 1.11 - 1.38 |
| 4096 | 1.23 - 1.60 | 1.01 - 1.08 | 1.06 - 1.12 | 1.17 - 1.20 |
| 16384 | 1.06 - 1.28 | 0.96 - 1.03 | 1.04 - 1.14 | 1.14 - 1.23 |

(ranges over the shapes measured at that M: seven at 512 and 1024, six above, the head only to 2048; the full rows are in the job's `prefill_microbench.json`.) The fused kernel removes
the regression: the bounded path was 1.06x to 4.45x dense and the per-row fused one is within 8% of cuBLAS at
M >= 4096 (MLP down at 16384 and the head at 1024 ran 3-4% faster) and 3-50% slower at M = 512.
It does not beat dense: both feed the same bf16 tensor-core MMA at fp32 accumulation, which is compute bound at
these row counts, so a weight-only 8-bit prefill saves bytes, not FLOPs. A prefill win needs the int8 tensor cores
(the W8A8 route in the GGUF Q8_0 glue), which is not part of this change. Group scales cost about 3-15% more than
the per-row kernel (an fp32 multiply-add of the partial sum per group).

## Measured end to end: fused prefill, group scales, and the Q8_0 int8-GEMM route (Qwen3.5-4B, RTX 4090)

One card per session (`gpu submit --job-file tools/weight_quant_validate/ab_prefill.json --arm`): dense bf16 (base), the
candidate, then the base again; every ratio is the candidate against the base boot beside it, paired per rep, 3 reps,
sampled at T=1.0 with thinking on, prefill targets in tokens (128, 1024, 4096, 16384) at concurrency 1 and 4,
`--max-context 20480`. The first four candidates ran with `--mtp-n-draft 3`; the Q8_0 route's checkpoint carries no
MTP head, so its session (own dense base) ran without drafting. Negative TPOT and TTFT are faster. The A/A rows (base
against base) read within +-1% on TPOT and TTFT at 1k and above; the 128-token rows are noisy (A/A TTFT +-25%).
TTFT, c=1 / c=4, %:

| candidate | 128 | 1k | 4k | 16k |
|---|---|---|---|---|
| #6977 per-row int8, bounded dense prefill | +105 / +111 | +91 / +87 | +32 / n.a. | +28 / n.a. |
| fused per-row int8 | +34 / +53 (noisy) | +10.5 / +8.8 | +4.5 / +3.1 (n.s.) | +0.0 / +0.8 (n.s.) |
| fused int8g64 | +39 / +14 (n.s.) | +15 / +12 | +3.6 / +3.0 | +3.6 / +3.2 |
| fused int8g128 (BLOCK_K = 128 tile, since changed to 64) | +13 / +6 (n.s.) | +8.1 / +6.6 | +12 / n.a. | +11 / n.a. |
| Q8_0 planes, int8 GEMM (CT g128 checkpoint, no drafting) | +36 / +40 | -23 / -24 | -36 / -33 | -35 / -36 |

TPOT, c=1 / c=4, %:

| candidate | 128 | 1k | 4k | 16k |
|---|---|---|---|---|
| #6977 per-row int8 | -18 / -22 | -30 / -20 | -14 / -22 | -24 / -26 |
| fused per-row int8 | -28 / -22 | -30 / -25 | -13 / -19 | -23 / -17 |
| fused int8g64 | +5.6 / -15 | -12 / -11 | -0.2 / -13 | -9.8 / -13 |
| fused int8g128 | -7.4 / -25 | -22 / -22 | -13 / -28 | -17 / +6 (n.s.) |
| Q8_0 planes (no drafting) | -32 / -32 | -33 / -32 | -33 / -32 | -31 / -30 |

Reading: the fused kernel removes the 2x TTFT regression (bounded +91-111% at 128-1k becomes +9-11% at 1k and parity
at 16k for per-row), keeps the decode win, and does not beat dense on prefill: weight-only 8-bit feeds the same bf16
MMA. The only prefill win is the int8-tensor-core route: Q8_0 planes through the int8 GEMM prefill 1.5-1.6x faster
than dense at 1k-16k tokens (prefill tok/s +30% at 1k, +53-60% from 4k) with decode 30-33% faster, and lose only on
128-token prompts (TTFT +36%).

**Fidelity** (teacher-forced KL against the dense record, floor 6.43e-5, bar 6.43e-4 and top-1 >= 99.0%; the
record is one prefill pass over the forced tokens, so it includes any activation rounding of the prefill path):

| arm | mean KL | x floor | top-1 | bar |
|---|---|---|---|---|
| int8 per-row (#6977) | 8.10e-4 | 12.6 | 99.61% | outside |
| int8g128 | 4.82e-4 | 7.5 | 99.51% | inside |
| int8g64 | 4.67e-4 | 7.3 | 99.61% | inside |
| int8g32 | 4.57e-4 | 7.1 | 99.70% | inside |
| Q8_0 planes, int8 GEMM (g128 CT checkpoint) | 8.77e-4 | 13.6 | 99.51% | outside |
| fp8 per-row | 2.67e-3 | 41 | 99.11% | outside |

Group scales cut the weight-only KL 40% (g128) and clear the bar; g64 and g32 buy almost nothing more (4.67e-4,
4.57e-4) for 2x and 4x the scale bytes. The Q8_0 route has the same weight error as g128 and adds the activation
rounding of the int8 GEMM, which takes it back out of the bar (4.82e-4 to 8.77e-4); it is off by default, and a
checkpoint served that way is the owner's call. Memory: KV capacity 370,560 tokens dense, 453,504 per-row int8,
448,384 g64, 456,064 g128 (MTP sessions, `--max-context 20480`); Q8_0 planes 573,312 against 470,912 dense without
drafting (+22%), with 8.5 bits per weight in the planes against 8.0 for per-row (+3.1% fp32 scales at g128, +6.25%
at g64).

**Not measured**: the bf16-origin Q8_0 load path (the Q8_0 numbers are from a pre-quantized compressed-tensors g128
checkpoint through the existing `ct_planes` seam, not from rounding the dense checkpoint at load); the g128 tile
change on a card end to end (microbench only); per-matrix sensitivity on a card (the CPU error is flat across
matrices, 0.86-1.14% relative output error per-row); sm_86; TP; any model but the 4B.


# docs/voicechat-latency.md
# VoiceChat latency and interrupted replies

For realtime voice service, install the `audio` extra as well as the server
extra. The slim serving image intentionally omits audio dependencies. An
`ARBI_ENABLE_AUDIO=1` environment variable enables the routes but does not
install their optional speech detectors. Verify that Silero actually loads;
the energy fallback can mistake background noise for speech and interrupt replies.

The CLI exposes two existing duplex timing controls:

```sh
arbi-serve --model /models/voicechat \
  --duplex-eou-silence-s 1.28 \
  --duplex-agent-pad-tail-close-s 1.28
```

Both default to 3.2 seconds. The first bounds how much confirmed silence the
server waits for before forcing a reply when the model does not open one itself.
The second bounds the agent's text-PAD tail, subject to its outstanding audio.
These controls retain the model's 80 ms audio cadence. Shortening them can
interrupt pauses within an utterance, so measure with representative speech;
zero disables the corresponding gate.

Read the turn logs before blaming GPU power or buffer capacity. A reply closed
on “the user barging in” was interrupted by speech detection. A connection ending
with `client_disconnected` is distinct from a GPU error or exhausted KV context.
Measure speech-end to first audio, gaps between audio deltas within a response,
and successful replies after several minutes. A WebSocket handshake alone does
not verify conversational responsiveness. Also check for post-ready compilation:
a live request should not pay for an unwarmed audio kernel specialization.

For sentence-aware endpointing, explicitly selecting `smart_turn` must route
turn boundaries through that detector even when the model bundles RNNT. Speech
onset still interrupts the reply. The WebSocket consumer must receive the
interruption and the matching committed turn state together; reading the engine's
live flag before its tick is published can report a normal completion too early.
Interrupted replies cancel queued browser audio and leave the conversation open.

Text-completion rewrites are disabled by default. Missing punctuation is not
permission for the server to replace a model end token with another word.

For validation, measure audible speech rather than the first PCM packet (which
can contain silence). Include pauses inside unfinished sentences, speaking over
an active reply, subsequent silence, and intelligibility of later replies in a
sustained conversation. Run the console's actual prompt/tool configuration as
well as an isolated short-prompt test; passing one does not establish the other.

A Smart Turn endpoint already includes the acoustic pause and the completion
check. Direct duplex admission therefore spends one tick accepting that endpoint,
without starting the acoustic silence window again. Tool-enabled sessions
retain a 640 ms selection window for both model-sampled and forced spoken
starts, capped by the configured EOU timer. This protects the independent
FUNCTION channel from an early spoken response. If the checkpoint's own
ASR has recognized a question ending, that evidence can resolve an incomplete
Smart Turn classification, but only at an acoustic candidate pause. It does not
open a response during active microphone speech or treat a period inside a
longer request as a completed question.

The FUNCTION channel can still be writing a tool call when the spoken TEXT
channel ends a response. Preserve the function grammar across that boundary,
and keep response timers from forcing an empty turn over an unfinished call.
Stage a client result together with its gate release on the engine thread.
Finish any started acknowledgement text first, retain its TTS audio tail, and
discard results or timeouts belonging to an interrupted function cycle.

A text-token rendering budget is an estimate of speech duration. When it
expires while the codec is still producing voiced audio, allow a bounded drain
until the output goes quiet. This preserves an ending without leaving an
unbounded PAD continuation. Barge-in cancels immediately and bypasses the drain.


# docs/voicechat-animation-validation.md
# Validate one native voice and animation engine

This recipe adds optional native facial animation to a decoder that already
produces device audio. It preserves the decoder's class, original model weights,
realtime input and tool channels. The example is Nemotron VoiceChat 11B; the
motion sink consumes the shared tensor/sample-rate/sample-origin contract.

Provision accepted model assets first. Preparation loads metadata only:

```sh
PYTHONPATH=. python scripts/prepare_voicechat_animation_deployment.py \
  --checkpoint /models/voicechat-6bpw \
  --metadata /models/voicechat-matching-tokenizer-and-voices \
  --face /models/audio2face-3d-v3.0 \
  --emotion /models/audio2emotion-v3.0 \
  --streaming-profile realtime \
  --output /runtime/voicechat-animation
```

For interactive calls, explicitly select the realtime animation profile. The
balanced profile remains the preparation default. Realtime retains the full
recurrent face transition but shortens the emotion window. It needs 750 ms
of generated audio for its first complete 30-frame packet.
Starting with a short preroll packet creates a warmup-to-steady-state gap,
so realtime playback uses a complete initial block. This is model lookahead,
not a promise of 750 ms end-to-end call latency.

Realtime sessions default to audio only. Request motion explicitly in the
initial update: `{"type":"session.update","session":{"duplex":true,"output_animation":true}}`.
Omitting `output_animation` or setting it to `false` streams the original speech
without opening an animation sink, running facial inference, or scheduling CPU
fitting. Audio source clocks remain available independently of motion.
Set `output_animation:false` on a live session to cancel pending motion without
restarting or silencing audio. Re-enabling motion takes effect on the next
utterance so its required audio history starts at sample zero. Requests for
animation on a model without that capability receive an explicit error; audio
only sessions remain supported.

For lip-sync-only validation, set `audio_output_animation.emotion` to `false`
in the generated `model/config.json` before starting the server. The device
animation sink then skips emotion inference and uses zero emotion controls;
voice prosody and the facial motion network remain active. This switch does
not remove the emotion model from the composite model deployment.

Before serving, provision Smart Turn v3.2 once using the same image, cache mount
and user as the serving process. Run
`python -m arbi_serve.realtime.smart_turn` with network access enabled, then
serve offline from that cache. Preparation itself never downloads assets.
Explicitly request `turn_detection.backend: "smart_turn"` and
`silence_duration_ms: 160` in the realtime session; a missing classifier
then fails explicitly instead of silently measuring the slower fallback.
The shared classifier uses at most four CPU threads, capped by the container's
quota and affinity. Warm it before measuring
steady-state response time.

Final geometry fitting runs in one spawned CPU-only worker, warmed during
model preparation before the server becomes ready. Neural generation stays
in the original GPU engine. Only final CPU geometry and explicit per-utterance
fitting state cross this boundary. Fitted controls publish in slices of at
most six frames; queue credits and the fitting timeout still cover the whole
native block. The full recurrent face transition and sample clocks are unchanged.

The optional metadata directory fills missing tokenizer and voice files in a
sparse quantized pack. Its non-quantization model config must match exactly;
the selected checkpoint's weights and quantization declaration take priority.
The output is a separate config facade containing read-only-source symlinks,
one media-host declaration, and a private authenticated serving/operator tokens file.
Source files are never rewritten. Mount source and deployment paths at the
same absolute names used during preparation.

`compose.voicechat-animation-validation.yaml` declares all mounts explicitly,
uses the serving image's CUDA 13.1 toolchain, and admits one decoder request
with a bounded context. Use an image containing CUDA 13.1; Compose uses its
compiler and libraries without requiring a host CUDA installation. It names
no guessed GPU utilization or fixed memory reserve. The normal ledger measures
decoder and concurrent animation workspace; retained audio/geometry capacity is
derived from declared shapes. Preparation does not establish that a card fits.
Choose an exact tested image and a dedicated persistent cache in a private
Compose environment file. The canonical recipe uses the image's UID/GID 10001;
provision private files and writable caches for that owner. A local development
override can explicitly select the host owner's UID/GID instead. Per-step
widths default to the engine's `auto`; a validation environment can explicitly
set `ARBI_MAX_BATCHED_TOKENS` and `ARBI_CHUNK_PREFILL` for a bounded experiment.
Start foreground Compose
only while holding the shared GPU lease:

```sh
bash scripts/ci/gpu_lock.sh 0 -- docker compose \
  --env-file /runtime/voicechat-animation/validation.env \
  -p voicechat-animation-validation \
  -f compose.voicechat-animation-validation.yaml up --no-build
```

Verify a real cold boot and a warm boot using the same image, source, config,
assets, flags and cache directory:

1. Start with a new dedicated cache, record model/config identities and the
   measured root, media, retained-buffer and workspace ledger. Wait for ready.
2. Connect to authenticated `/v1/realtime` in genuine duplex mode and stream
   actual caller speech at its declared rate. Verify intelligible spoken output,
   finite 52-control packets, monotonic utterance sample clocks and final flush.
   `response.audio.delta` includes original `source_start_sample`,
   `source_num_samples` and `source_sample_rate`; motion uses its 16 kHz clock.
3. Exercise a function call and its spoken acknowledgement/result, a spoken
   interruption, and disconnect/reconnect. Confirm cancellation discards old
   animation, input remains responsive and the next utterance starts cleanly.
   Geometry fitting runs in a worker thread, outside the WebSocket microphone
   loop. Backpressure reports `response.animation.error` and preserves audio.
4. Stop only this validation deployment. Keep its cache and restart unchanged.
   Verify ordinary checkpoint-cache reuse, independently loaded animation
   assets and the same complete realtime checks. Flat checkpoint headers must
   contain no `hosted_media_tasks.*` tensors. Registered media parameters must
   still appear in device ownership and migration accounting.
5. Preserve recordings, event/sample-clock receipts and allocation logs before
   publishing a result. Stochastic voice output need not be bit-identical
   across boots; protocol success alone does not prove naturalness, latency or
   audio/motion playback synchronization. Review the complete recorded call.

The cold/warm checks must use real model inference. CPU metadata and mocked
transport tests establish construction and ownership contracts only.


## Admin console avatar preview

Provision the approved browser rig assets separately from neural weights.
Start the serving engine with `--avatar-assets-dir /models/browser-avatars`.
This is server configuration, separate from neural checkpoint metadata and
weight-cache identity. Its matching avatar subdirectory (for example `claire/`) contains
`head.glb`, `head-clearance.json` and `blinks.json`.

The Audio tab fetches only those three files through the existing authenticated
console target relay. It uses the stock Three.js renderer and OrbitControls for
slow rotation and dragging. The `Animate speech` control explicitly sets
`session.output_animation`; a rotating idle head alone never requests neural
motion.

Speech keeps the existing PCM scheduler and 120 ms browser lead-in regardless
of preview settings. Motion uses the source-sample clock on a separate delayed
preview timeline; it may trail speech. Missing assets, unavailable WebGL, or a
motion error leave the audio controls usable. This preview does not establish
perfect audiovisual alignment or the subsecond post-tool audible-answer target.


# docs/vocab-shard-interleave-assessment.md
# Interleaving the lm_head vocab shard — assessment

**The proposal.** Today rank `r` of a vocab-sharded lm_head holds one
contiguous global column range. A frequency-ordered prefix `[0, N)` therefore
piles onto the low ranks: at `quarter` on the served 248,320-wide head at TP2,
rank 0 keeps 62,080 columns and rank 1 keeps **zero**. Alternate the
`PREFIX_ALIGN`-wide blocks across ranks instead and every prefix lands
`≈ N / tp_size` on each rank — the cards do equal work at every width.

**The finding.** The balance argument is correct about compute and silent
about the wire, and the wire is where this is decided.

> **Interleaving and `perf/lmhead-gather-to-rank0` are not complementary. They
> are two ways of spending the same bytes, and they cancel.** The gather
> rewrite's entire win comes from rank 1 having *nothing to contribute*.
> Interleaving's premise is that rank 1 must contribute half the row. Adopting
> both gives back most of a 36× cut to buy a fraction of one GEMM.

On box 206's no-P2P link the trade is **net negative by roughly an order of
magnitude**. On an NVLink pair it is plausibly positive. The pivot is one
number nobody has measured, and measuring it costs an hour.

This is reported rather than built, per the standing instruction to stop on a
blocker. It is not a correctness blocker — §4 shows the reorder is cheaper
than feared. It is an arithmetic one.

---

## 1. What is true, and better than the brief assumed

Two corrections first, because both make the proposal look *better* than it
was described, and the case still does not close.

**The reorder is cheap, and it is not a gather.** Under a block interleave the
loader hands rank `r` the global blocks `{r, r+tp, r+2tp, …}` packed in
ascending order, so local block `j` is global block `j·tp + r`. A global
prefix of `B_N` blocks is then the local blocks `j < (B_N − r) / tp` — a
**leading** local range on every rank. Two consequences:

* **VRAM-neutrality survives.** Each rank's piece is still a leading window,
  so it is still an `exl3_gemm` `size_n_out` **bound** over the tensors that
  rank already holds. Nothing is materialized. (This contradicts the natural
  worry that an interleave forces a materialized cut — it does not, provided
  the loader packs blocks in ascending global order.)
* **The composition is a permute, not an index table.** With equal per-rank
  block counts the composed row is
  `stacked.view(tp, rows, Wb, 128).permute(1, 2, 0, 3).reshape(rows, Wb*tp*128)`
  — one transposing copy of the row that is already being copied today
  (`_compose_shard_windows` already writes a fresh `global_width`-wide
  output). Only the ragged last round, when `B_N % tp != 0`, needs care.
  Derived from the same geometry table both ranks already compute, exchanged
  nowhere.

So constraints 1–3 of the brief are satisfiable and constraint 2 is nearly
free **on the drafter's own composition**. The cost is not there.

---

## 2. The arithmetic that decides it

Config as profiled in
[`receipts/dflash-tp-shard-why-2026-09-13.md`](receipts/dflash-tp-shard-why-2026-09-13.md):
TP2, hidden 5120, `rows = B × lm_slots = 8 × 7 = 56`, bf16, lm_head 4.0 bpw,
shard width `W0 = 124160`.

### What crosses the wire, under each combination

The gather rewrite on `perf/lmhead-gather-to-rank0`
(`GroupCoordinator.gather_uneven_to_rank`) collects each rank's **own-width**
contribution onto rank 0 alone: rank 0's own entry "is `x` itself, uncopied",
and "**a zero-width rank contributes an empty tensor and moves no bytes**". So
the bytes on the wire are exactly the peers' kept columns — and at any `N` a
contiguous layout keeps entirely on rank 0, that is **zero**. This is the
sentence the two changes collide on:

| layout | gather | rank-0 GEMM width | bytes on the wire / step |
|---|---|---|---|
| contiguous, today's all-gather | shape-uniform at `max(window)` | `min(N, W0)` | `tp · rows · min(N,W0) · 2` |
| contiguous, gather-to-rank-0 | uneven, to root | `min(N, W0)` | `rows · max(0, N − W0) · 2` |
| **interleaved**, gather-to-rank-0 | uneven, to root | **`≈ N / tp`** | **`rows · N(1 − 1/tp) · 2`** |

At the two rungs that matter, TP2:

| | rank-0 GEMM width | wire bytes/step |
|---|---|---|
| `quarter` (N = 62,080), contiguous + gather-to-rank-0 | 62,080 | **0** — rank 1 holds none of it |
| `quarter`, interleaved | 31,040 | **3.48 MB** |
| `half` (N = 124,160), contiguous + gather-to-rank-0 | 124,160 | **0** |
| `half`, interleaved | 62,080 | **6.95 MB** |

### Pricing both sides

**The wire, measured.** The receipt's draft lm_head all-gather moves 27.82 MB
in 2290–2358 µs → **12.1 GB/s effective** on this pair. Box 206 reads `GNS` on
`nvidia-smi topo -p2p r`: no peer access, every byte stages through host
memory. So 6.95 MB costs **≈ 575 µs/step**, and 3.48 MB **≈ 288 µs/step**.

**The GEMM, bounded.** Rank 0's lm_head shard read at `half` is
`124160 × 5120 × 0.5 B ≈ 318 MB`. At the 58% of card weight-bandwidth the
receipt measures for the unsharded drafter body (§7.1), that is ~540 µs;
halving the width saves at most ~270 µs. But the same section measures what
actually happens when this kernel family's `N` is halved at `M = 64`: **−13.8%,
not −50%** — "at M = B × block = 64 rows the EXL3 trellis GEMM is launch- and
occupancy-bound, and the narrower N gives each weight-tile load less work to
amortise against." On that scaling the realistic saving is **~75 µs**.

**The trade at `half`, on 206: pay ~575 µs to save 75–270 µs.** At `quarter`:
pay ~288 µs to save ~38–136 µs. Net negative either way, by 2× in the most
generous reading and by 8× in the measured one.

### The crossover, stated as a link speed

Interleaving pays iff moving `rows · N(1 − 1/tp) · 2` bytes is cheaper than
the GEMM width it removes. At `half`, TP2:

| GEMM scaling assumed | link speed interleaving needs |
|---|---|
| ideal, bandwidth-bound (−50%) | **> ~26 GB/s** |
| measured, launch-bound (−13.8%) | **> ~91 GB/s** |

Box 206 measures **12.1 GB/s** on this exact collective. An `NV4` NVLink pair
measures **52.7 GB/s** and a PCIe `NODE` pair **25.1 GB/s**
(`receipts/tp2-async-tp-2026-09-07/README.md`).

**So: not on 206. Marginal on a PCIe peer-capable pair. Plausibly a win on
NVLink — and only if the drafter lm_head GEMM turns out to be bandwidth-bound
rather than launch-bound at M = 56.** That last clause is the pivot, it is
unmeasured, and §6 says how to measure it.

### Against today's code, the sign flips — and that is the trap

Without the gather rewrite, today's shape-uniform all-gather ships
`tp · rows · max(window) · 2`. Interleaving halves `max(window)`, so it
**halves the gather too**: at `half`, 27.82 MB → 13.91 MB, about 1.15 ms/step
saved, plus the GEMM.

A benchmark of interleaving taken on `integ/flag-cull` as it stands today
would therefore show a clear win — and that win evaporates the moment
`perf/lmhead-gather-to-rank0` lands, because the two changes are competing for
the same bytes. **Measure interleaving against that branch, never against
main.**

---

## 3. One change or two

One. And it is the gather rewrite.

| | bytes on the wire at `N = 131072` |
|---|---|
| today | 27.82 MB |
| `perf/lmhead-gather-to-rank0` | **0.774 MB** (36× cut, zero numerics change) |
| interleave + that branch | **7.34 MB** (9.5× worse than the branch alone) |

The receipt's item (A) also names a bigger version of the same idea — per-rank
top-C, using the construction `verify_sharded.py` / `mtp_verify_sharded.py`
already runs by default on the verify path — at **35.8 KB, a ~780× cut**.
Interleaving is incompatible with that too, and for the same reason: it
requires the full row to be assembled from both ranks every step.

**Recommendation on sequencing: let `perf/lmhead-gather-to-rank0` land
untouched.** Do not have two branches rewriting `_compose_shard_windows`. If
interleaving is taken up later it is a rewrite *of* that branch's composition,
on a machine with peer access, and it should be designed as one change with
the top-C path rather than bolted beside it.

---

## 4. If it is built anyway — the blast radius, enumerated

The brief's constraint 4 asked for this before anything is written. It is not
confined to the drafter: **the drafter's window is a bound over the verify
head's own tensors, so interleaving the drafter's shard means interleaving
`model.lm_head` — the verifier's layout.** Everything below is a site that
would produce a plausible wrong token rather than an error.

**Highest risk, silent:**

1. **`_compose_shard_windows`'s offset walk** —
   `weight_quant/exl3/linear.py:895-899`, and the identical
   `all_gather(..., dim=-1)` pattern in every vocab head
   (`models/linear.py:327`, `models/layers.py:531`, `weight_quant/base.py:395`,
   AWQ/FP8/NVFP4 mirrors). Produces a permuted row that **every rank agrees
   on**.
2. **`shard_start = tp_rank * per_shard`** —
   `spec_decode/mtp_verify_sharded.py:633` and `:366`. These never read
   `_tp_out_start` at all; they are *already* latently wrong for the current
   uneven EXL3 split, and an interleave makes them wrong on every rank.
3. **The tied embedding.** `TiedLMHead` (`models/layers.py:497`) holds the
   `VocabParallelEmbedding` and runs `invariant_linear(x, embed.weight)`
   **directly on the embedding parameter** — so on a tied checkpoint the head
   has no layout of its own, and changing it changes the embedding's
   contiguous membership mask at `models/layers.py:486-488`. That mask decides
   which rank owns a token; wrong ownership sums garbage through an all-reduce
   that returns a well-formed tensor. Note also that the embedding shards at
   granularity **1** (`ceil_div`), not 128 — a second, different layout
   already coexisting with the EXL3 head's.
4. **`VocabWindow`'s entire contract** — `sampler/vocab_window.py`, whose
   docstring is "a vocab-parallel rank holds a contiguous slice". Every
   penalty (`sampler/processors.py:330-352`), logit bias (`:443-457`), verify
   penalty (`spec_decode/verify_penalties.py`), forced-EOS reopen
   (`sampler/force_stop.py:90`), thinking-budget close
   (`sampler/thinking_budget.py:409`), grammar bitmask slice
   (`sampler/xgrammar_processor.py:864-918`) and ban mask
   (`sampler/omni_guard.py:107`) lands on the wrong columns. The `window=`
   **protocol** at `sampler/processors.py:88-122` encodes contiguity, so this
   is an interface change, not a set of call-site fixes.
5. **The flat-cache fingerprint** — `loader/flat_cache.py:213/221` records
   `(tp_size, ep_size, rank)` and `_FLAT_LOADER_VERSION` but **not the vocab
   shard layout**. A warm dump taken under the contiguous layout would be
   re-mmapped verbatim under the interleaved one: permuted weights, no error.
   `_FLAT_LOADER_VERSION` must be bumped or a layout field added.
6. **The lowest-rank-wins argmax tie-break** — `spec_decode/mtp_head.py:705-710`
   and `:858-862`. It is sound *because* "the ranks' column ranges are
   contiguous and ascending in rank order"; under interleave rank 0 holds
   block 0 *and* block `tp`, so lowest-rank is no longer lowest-id and the
   tie-break silently picks the wrong token.

**Also required:** the global-id maps at `mtp_head.py:794/822/863` and
`verify_sharded.py:139`; the loader's single-contiguous-slice cut at
`exl3/linear.py:1298-1305` (model it on
`EXL3MergedColumnParallelLinear._tp_shard` at `:1502`, the one loader in the
tree that already builds a non-contiguous local weight and deliberately
publishes a meaningless `_tp_out_start`); the padding-tail assumption that
real columns are a prefix and pad a suffix of each shard
(`mtp_head.py:795`, `verify_sharded.py:133`, `models/linear.py:454-459`,
`models/layers.py:420-431`, and the post-gather `out[..., :org_vocab_size]`
trims, which would truncate *real* tokens and keep pad columns).

**What the existing boot checks would still mean.** `shard_geometry_underived`
(`draft_vocab_prefix.py:1481`) compares a derived `(start, width)` against the
head's — a block-list head has no such pair, so the check either fires
correctly (good) or, if "fixed" by changing only `tp_shard_range_aligned`,
starts certifying a lie while the composition is still wrong. The three
`__init__` checks on the window heads (`exl3/linear.py:1122-1141`, `:1093-1112`)
check **totals, not order**, and all three pass under a permuted composition.
`tp_head_without_shard_geometry` degrades to a check that four attributes
exist.

**Tests.** Fourteen files encode the contiguous model, and two of them lock it
as **source text**: `tests/test_mtp_distributed_argmax.py:321-333` asserts the
literal strings `'_tp_out_start", tp_rank * per_shard'` and
`"(local_idx + shard_start)"`. Also
`tests/_draft_vocab_prefix_tp_gloo_harness.py` (the whole harness is the
contiguous model — and it is being edited right now on
`perf/lmhead-gather-to-rank0`), `tests/test_draft_vocab_prefix{,_gpu}.py`,
`tests/test_sharded_verify_windowed_constraints.py`,
`tests/test_mtp_verify_sharded_glue.py`, `tests/test_vocab_parallel_padding.py`,
`tests/_tp_shard_harness.py`, `tests/test_flat_cache_shard_identity.py`.

---

## 5. What the contiguous layout gives up, stated fairly

The owner's point stands on its own terms and should not be lost:

* At every width, the lm_head projection is unbalanced. At `quarter`, rank 1
  does **no drafter lm_head work at all**.
* `half` on this head is exactly rank 0's shard width, so it narrows nothing
  on the critical path — correct, and free of benefit.
* `docs/draft-vocab-prefix.md` has always said this ("even a working routing
  buys a TP=1-speed drafter head, not a parallel one"); it has never been
  actionable.

What the arithmetic adds is that **the idle card is not free capacity — it is
a card whose output would have to cross a 12 GB/s host-staged link to be
useful.** Balance is only worth buying when moving the result is cheaper than
recomputing it, and on this box it is not.

---

## 6. The measurement that would settle it

One number decides the NVLink case: **the drafter lm_head GEMM's per-step cost
at TP2, and how it scales when its `N` is halved at `M = 56`.** The receipt
profiled every other drafter collective and kernel but never isolated this
one — its §7.1 scaling figure is the drafter *body* GEMM, a different weight.

It needs no new code: a console profile window
(`python -m arbi_serve.admin_console.profile_window --concurrency 8`), two boots at `--draft-vocab-prefix` = `half` and `quarter`, and the
same per-rank kernel attribution the receipt's own scripts already do. An
hour on a card, against days of work across the verify head's global layout.

* If the GEMM scales near-linearly with `N`, interleaving is worth revisiting
  **on an NVLink machine**, designed together with per-rank top-C rather than
  beside it.
* If it scales like the body GEMM did (−13.8% for half the width), the
  interleave cannot pay on any link this fleet has, and the question is
  closed.

Until then the contiguous layout stays, and the boot **warns by name** when a
requested width sits at or above rank 0's shard width — naming the per-rank
kept widths, the usable maximum on the topology in front of it, and the rung
that would actually narrow the step
(`draft_vocab_prefix.tp_prefix_advisory`, counter
`draft_vocab_prefix_tp_ceiling`). That warning was written for the case
interleaving would have removed; while the layout is contiguous it is the only
thing standing between an operator and a flag that looks like a speedup.


# docs/video-input.md
# Video input

Qwen3.5-VL checkpoints (and Clef, which is one) read video natively. A deployment that boots with
`ARBI_ENABLE_VISION=1` on a checkpoint that declares a `video_token_id` takes video through
`/v1/chat/completions` and, for decision models, `/v1/systemone`.

## Sending a clip

In chat completions, as a content part of a user message:

```json
{"type": "video", "video": ["data:image/jpeg;base64,...", "..."], "fps": 24}
```

`video` is a list of frames (data URLs, local paths, or bytes), `fps` is the clip's own frame rate
(24 if omitted), and `"sample_frames": false` says the frames given are already the ones to read.
A container (mp4, webm) goes as `{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,..."}}`;
decoding one needs PyAV, which the image does not ship, and a request that sends a container
without it is refused by name.

**Video URLs are never fetched.** `http(s)://`, `file://` and every other scheme is a 400: the
decoder would open them itself, and pulling remote bytes is an egress decision the server layer
owns. A page like a YouTube link is not a media file either way.

## What the model sees

Frames are sampled at 2 per second (4 to 768 of them), resized so the whole clip fits a pixel
volume (`size.longest_edge` in the checkpoint's video config), and paired in time. Each pair is a
**temporal group** the tower reads as one image-shaped block, and the prompt spells its time ahead
of it: `<1.5 seconds><|vision_start|><|video_pad|>…<|vision_end|>`. The layout is the reference
processor's, token for token (`multimodal/video_layout.py`, shared by the chat and decisions
routes).

**Tokens are the cost.** A 30 s clip at 720p is about 60 frames, about 11,700 vision tokens at the
checkpoint's default volume. Downsampling is the lever, and it is safe for coarse questions (what
happens, who is there, is the light on) and not for fine ones (read the label, count the small
objects): fewer or smaller frames cost proportionally fewer tokens. Send fewer frames, or smaller
ones, and the server's volume bound already shrinks a long clip per frame.

## Memory and the host

- **uint8 patches, normalized where they are used.** The processor does only the resize and the
  patch permutation; the patches stay uint8 across the process boundary and in the prefix-cache
  hash (a quarter of the bytes of float32), and the tower normalizes each group on the device with
  the same float32 arithmetic (`multimodal/pixel_norm.py`).
- **One group resident at a time.** The tower encodes group by group and uploads each group's
  patches just before its pass, so the device holds one image-shaped block however long the clip is.
  A group is never larger than the worst-case image the boot profiler prices: the video volume bound
  keeps each frame under `max_pixels / temporal_patch_size`, and the processor refuses, at load, a
  config where that exceeds the image ceiling.
- **No host synchronization.** Grids are host data, per-shape geometry (positions, rotary tables,
  block boundaries) is built on the device, small host tensors go up through pinned memory, and
  M-RoPE positions are worked out on the host and copied once. `tests/test_vision_tower_sync_free_live.py`
  runs all of it with `torch.cuda.set_sync_debug_mode("error")`.
- **Off the event loop.** A request with media is preprocessed on a worker thread, and a clip's
  frames decode in parallel; a text-only request takes the same direct path as before.

## Controlling the cost per request

A `video` part (chat) or `input_video` part (`/v1/decisions`; the same fields exist on
`/v1/systemone`'s `SystemOneVideo`) can lower what the checkpoint's video config would read:

| field | effect |
|---|---|
| `sample_fps` | frames sampled per second of the clip (never above the checkpoint's) |
| `max_frames` | cap on sampled frames |
| `max_pixels` | cap on the pixel volume of the clip (never above the checkpoint's) |
| `start` | the clip's offset in seconds on the conversation's timeline, so a second clip reads as later |

A knob that would raise a limit is clamped, not honoured. Tokens are the cost, so these are the
lever: halving the sample rate roughly halves the vision tokens.

## Streaming over `/v1/realtime`

`input_video_frame.append` (a frame as a data URL, with an optional `timestamp`) buffers frames on
the session; `input_video_buffer.clear` drops them and answers `input_video_buffer.cleared`. A
bad frame is an `invalid_frame` error event and the session carries on. The next `response.create`
(or a user message item) flushes the buffer as clips of 16 frames on one absolute timeline: a lone
frame is sent as an image, and the tail of a split buffer is merged into the last chunk instead of
becoming a one-frame clip. The buffer is bounded (256 frames, 8 MiB a frame, 96 MiB in all), and
past the newest eight video or image parts in history, earlier ones leave their messages (a
message left with none reads "(earlier video omitted)"). The model streams text
back as `response.audio_transcript.delta`, through the same turn streamer as the audio path.
`tests/test_realtime_video_live.py` checks a streamed clip against the same clip sent to chat
completions.

## The tower runs in chunks

Attention projections, the MLP and the patch merger run through one shared `map_in_chunks`
(`models/vision/layers.py`, 4,096 tokens a chunk, set per model in `VisionConfig`), so the tower's
peak is a few chunks and not the whole image. The result is the unchunked pass to float32 rounding
(`tests/test_vision_chunked_tower.py`), the time is unchanged, and the boot profiler prices the
chunked peak: one Clef image at 32,400 patches peaks at 577 MiB, not 1,422.

## Verified against

`tests/test_chat_video_live.py` serves Qwen3.5-0.8B with the vision tower and asks it, greedily,
about an image, a video, a sampled long clip, an image and a video, and two videos, next to
`transformers` on the same weights: the prompt must be the same length token for token and the
answer the same. `tests/test_video_preprocess.py` pins the processor's grids, timestamps, pixels
and expanded ids to the Hugging Face processor's own output.


# docs/tuning-evidence.md
# Serving and boot tuning evidence

The only additional periodic gauge is `arbi_serve.spec_valve_warm_verifies`. It reads the existing counts by valve cell, proposed depth and accepted prefix length. Take differences within the same controller lifetime. The engine publishes this gauge after readiness. The API child keeps its existing heartbeat metrics.

For arm throughput use the existing `spec_decode_valve_widths` in `/v1/admin/server_info`. For exact decode hits and misses by requested batch use `/v1/admin/capture_hist`. A miss may subsequently use padded replay.

For graph planning, the existing `/v1/admin/prefill_coverage` endpoint provides requested token and sequence counts with per-shape hit, too-large, unexpected-miss and padding-waste counts. They count layer dispatches. The `/v1/admin/capture_hist` endpoint includes optional verify and pad diagnostics when their existing producers are enabled. Missing debug data is unknown. Neither histogram times the alternative execution path. The existing request finish log includes shadow estimates where available. Aggregate depth counts cannot pair an individual shadow prediction with its subsequent outcome.

## Collecting the boot records

Run the exporter on a read-only copy of the cache after boot. It uses the producer's committed files and can run on another machine. Use a snapshot to avoid competing with a live race for host I/O.

```sh
python tools/export_boot_races.py /snapshots/arbi-boot > boot-races.jsonl
```

To send these records to a configured receiver, pass `--otlp-logs-url` with its full OTLP/HTTP JSON logs endpoint. Each log body is one JSON record. The envelope includes the source family, relative artifact path, and a stable ID for a given file version. Deduplicate on that ID when repeating an export. Outputs retain the native receipt, including deployment metadata such as model paths. Export time identifies ingestion. A receipt from a shared cache can predate the boot that consumed it; the cache alone cannot identify every consuming boot or request.

| Source | Evidence available |
| --- | --- |
| Completed boot race receipt | The serving engine writes measured speculation ladder rungs, CASPER pair plans, EXL3 MoE arm samples and medians, and completed DFlash route timings once before readiness. The receipt records the boot model and instance. The offline exporter reads it alongside the native receipts. |
| Route races, including legacy EXL3 and current EXL3/GGUF, INT8 split-K, and grouped routes | Geometry, protocol/build identity, per-arm readings, refusals, clocks and decisions as retained by the producer. Per-arm reading fragments may overlap final decisions. |
| Prefill chunk | Timed widths, search order, selected width, widths that did not fit, refusals and failures where recorded. |
| MTP draft depth | Per-depth throughput, samples, accepted lengths, selected depth and measurement protocol when present. |
| TKV decode and verify split tables | Published picks and producer-specific evidence. Verify tables may include timings and regrets. |
| TKV split cost model and INT8 decode probe | Native coefficients, provenance, probe data and thresholds as recorded. |
| Boot timing | Recorded cold/warm total and stage durations. |
| Inductor and standalone Triton | Use `--inductor-dir` for persisted best configs and `--triton-dir` for persisted per-config autotune files. Non-finite timing sentinels are strings. |
| Custom directory layouts | `--mtp-dir` and `--splits-dir` select the actual calibration and tuning directories. |

Some backends publish only the winning configuration. Some races deliberately discard disturbed measurements. The exporter preserves those limits. It never re-races an arm to fill a missing label. Split train and evaluation data by deployment/geometry and hold out entire builds or GPU types when testing transfer.


# docs/tree-speculation-handoff.md
# Tree speculation — what is built, what remains, and where it bites

Companion to `tree-speculation-feasibility.md` (why a tree is worth
serving) and to the geometry/accept code in
`arbi_serve/spec_decode/tree_spec.py`. This file is the resume point: a
seam-by-seam map of what a tree needs that a chain does not, and where
each one landed.

**NOT SERVED. `ARBI_MTP_TREE` is default OFF.** The mechanism is KEPT as the
base for improvement work — see
`docs/receipts/ddtree-feasibility-2026-09-10.md` §10 for the disposition, for
what this file's measurements do and do not settle about the draft depth we
serve, and for the sized measurement nobody has taken.

On a corpus-aware A/B the tree's acceptance win is real and
its net throughput is negative at every condition measured — headline
**−4.43% tok/s**, `main`, B=1, greedy, against chain K=4. See *The
corpus-aware A/B* immediately below, which SUPERSEDES every tok/s figure
elsewhere in this file, including the **+5.26%** this document used to
open with. The machinery is merged, correct and gated behind the flag,
and costs nothing switched off.

The shape every tree number here was taken on is **`2x2x1x1`** — 14
nodes, block_m 15, depth 4, TP=1, GREEDY or SAMPLED. Depth is where the
tokens come from and width is what repairs the depth decay, so AMONG
trees the shape that pays is deep-and-narrow rather than the `2x2x2`
this file used to name: cost tracks the LEAF count, which `2x2x2`
doubles for the same 14 nodes.

At `temperature=0` both `p` and `q` are point masses, so accept is
exact-match and the tokens a tree commits are the tokens the target
model would have produced. At `temperature>0` the accept is
`tree_spec.accept_stochastic` expressed as
`arbi_serve::mtp_verify_stochastic_tree`: ONE uniform per depth,
inverse-CDF over the sibling set's target mass, and a draw from the
sibling residual at the rejection point. The served distribution is the
target's — `tests/test_tree_accept_lossless.py` measures it, with the
per-candidate-coin rule as the negative control, and
`tests/test_tree_verify_stochastic_op.py` pins a width-1 tree to the
shipped `_mtp_sample_residual_kernel` bit-for-bit.

The DRAFTER stays deterministic at every temperature — per-node top-W,
`POINT_MASS_Q`. That is the accept rule's premise: it inverse-CDFs the
target's mass over the candidate set, which is lossless for
deterministic candidates and is not the rule for sampled ones. The
drafter is a free parameter (Leviathan-2023 Thm 1), so declining to
sample there costs acceptance rate and nothing else.

**A tree boot needs a tkv whose ACTIVE attention route takes an
`ancestor_mask`**, and the two routes have separate entries: the bf16
bypass passes it into `BypassBf16Attend.attend` (turbo-attn#883), the
compressed codec into `TKVCore.forward` (turbo-attn#885). Each has its
own signature probe (`bypass_attend_takes_ancestor_mask()` /
`codec_attend_takes_ancestor_mask()`) and the boot refuses without the
one this boot serves through, so a build that predates it serves the
chain rather than serving a tree as one. A paged-KV backend that is
neither is refused by name.

The flag is default-off, so a chain boot's behaviour, buffers and capture
shapes are all exactly where they were.

## The corpus-aware A/B — the tree LOSES at B=1

**This section supersedes every tok/s and tokens-per-step figure dated
before it.** Everything earlier was measured by truncating ONE paragraph
at a random word and greedy-decoding it, which is n=1 for acceptance
however many steps it ran (#1612, `38f96d83`). The numbers here are
paired BY PROMPT, with the interval taken OVER prompts, on the
corpus-aware harness that PR shipped.

| condition | paired tok/step | paired tok/s |
|---|---:|---:|
| **`main`, B=1, short60** | **+8.47%** [+6.70, +10.31] | **−4.43%** [−6.30, −2.54] |
| frozen, B=1, short60 | +8.26% [+6.62, +9.97] | −10.19% [−11.86, −8.49] |
| frozen, B=1, aligned cache | +8.39% [+6.51, +10.37] | −9.47% [−11.32, −7.53] |
| frozen, B=1, mix188 @14k, n=186 | +11.32% [+9.79, +12.91] | −8.09% [−9.46, −6.73] |
| frozen, B=1, vs chain **K=5**, short60 | −0.54% [−2.62, +1.64] | −11.87% [−13.82, −9.86] |

`2x2x1x1` against chain K=4 unless the row says otherwise. `short60` is a
60-prompt short-context basket; `mix188` is the 14k-token mix, 186
prompts after the corpus filter. "frozen" is a frozen copy of the
worktree, so no edit can land between two boots; the `main` row is the
shipped code and is the one to quote.

**Both halves are real, and they point opposite ways.**

* **The acceptance win is NOT in doubt.** +8% to +11% tokens per step,
  and the interval clears zero by a wide margin at every condition,
  including the 14k mix where it is largest. The tree does what it was
  built to do.
* **The step penalty is simply bigger.** +12.4% on `main` at B=1. tok/s
  is the ratio of the two, and the ratio is negative everywhere it has
  been measured.
* **The tree does not beat a deeper CHAIN either.** Against chain K=5 on
  the same basket its acceptance edge is a null (−0.54%, interval
  straddling zero) and it is 11.87% slower. Whatever the tree buys at
  K=4, one more chain depth buys the same for less.

**The instrument was validated before any of it was read.** The
boot-to-boot acceptance null is **+0.000% on all 60 prompts, three
times** — two boots of the same arm commit the same tokens on the same
prompts, so every acceptance delta above is the arm and not the reboot.
The tok/s boot floor is ±0.16–0.47%. Driver counters cross-check to
emitted tokens within 0.6%.

### Acceptance is a function of CONTENT, so a fixed-prompt bench cannot measure it

This is the methodological result, and it is worth more than the tok/s
number above.

Across the 60 prompts, the tree's RELATIVE acceptance gain is
anti-correlated with the chain's baseline acceptance on the same prompt:
**Pearson r = −0.78 (n=60)**. The lowest-acceptance quartile gains
**+15.5%**; the highest gains **+2.5%**. A tree helps most exactly where
the chain is already struggling — which is a property of the TEXT, not
of the kernel, and it means the measurand moves with the prompt by more
than any arm difference this feature has ever produced.

The old harness fed ONE paragraph. Its chain tok/step was **2.31** —
below this basket's ENTIRE range of 2.69 to 4.57. It was an
outlier-hard prompt: the single place in the distribution where a tree
flatters best.

**A one-prompt bench on `main` could have returned anywhere from
−16.9% to +22.3%.** Both the **+5.26%** this document used to lead with
and the **−7.1%** a later single-prompt run produced sit inside that
spread. Neither was wrong about its own prompt; both were wrong to be
quoted as throughput.

The rule that follows is not an anecdote: **anything reporting
tokens-per-step has to draw from a corpus and treat the PROMPT as the
unit of replication.** The re-run instruments named here
(`bench_tree_step_delta.py`, `bench_prompt_corpus.py`) were removed from the
tree with the rest of `arbi_serve/scripts/` in #1799, so the re-run as written
is not executable in this repo; the corpus-unit rule still holds for whatever
instrument replaces them. Without a corpus feed the measurement is n=1, and a
replacement bench must say so.

Step COST at a fixed verify geometry is the exception — it does not
depend on what the prompt says, so the profiled cost decompositions later
in this file stand. It is the TOKEN side, and therefore every tok/s, that
a fixed prompt cannot measure.

### What the single number hides

Per category at 14k (paired tok/s, n=186):

| category | tok/s |
|---|---:|
| pipeline_debug | **+5.3%** |
| inbox_decision | +2.8% |
| … | |
| reasoning | −16.7% |
| code | **−17.0%** |
| math | **−18.7%** |

By register: agentic_rag −4.3%, productivity −4.5%, expository −4.7%,
literary_prose −11.2%.

That is a 22-point spread with the SIGN flipping inside it. Two of the
three worst are code and math — the registers where the draft head is
most confident and the chain therefore already accepts long runs, which
is exactly what r = −0.78 predicts. Any future shape decision has to be
read per category, or it is reading the average of two different effects.

### The chain K ladder, re-taken on the basket

short60, B=1, paired against K=4:

| K | paired tok/s vs K=4 | CI95 |
|---:|---:|---|
| 2 | **−17.40%** | — |
| 3 | −7.05% | — |
| **4** | — | — |
| **5** | **+3.05%** | [+1.36, +4.82] |
| 6 | +1.43% | [−0.70, +3.57] |

**On this basket the chain optimum is K=5, not K=3/K=4.** The
single-prompt ladder under *The chain frontier* below said K=3/K=4 and
put every K above 4 at −6% to −16%. None of that survived the corpus.

**Do NOT read this as "switch the K default to 5."** It is a
K × CONTEXT interaction. At 14k (mix188, n=186) K=5 against K=4 is
**−1.58%** — CI95 [−3.08, −0.03] resampling rows, [−3.47, +0.59]
clustered by instruction. The row-resampled interval barely excludes
zero and the clustered one contains it, so at 14k this is a null and the
sign has flipped from the short basket. The defensible statement is that
**the K default has to be re-taken PER CONTEXT REGIME**, and that the
current default is not evidence-backed in either direction.

**The non-monotonicity claim is WITHDRAWN, and so is what was inferred
from it.** This file used to argue from the single-prompt ladder that
chain tok/step is not monotone in K, and to infer a drafter defect from
that — that acceptance-versus-K is a confounded instrument because the
proposals are not K-independent. On the basket, chain tok/step is
strictly monotone in K:

    K=2     K=3     K=4     K=5     K=6
    2.654   3.253   3.676   4.024   4.217

A non-monotone ladder is what ONE trajectory looks like when the reboot
moves under it. The conclusion drawn from it was itself the
single-trajectory artifact. (The compounded-hazard ladder formerly in
`arbi_serve/scripts/price_depth_gate.py` — removed in #1799 — is a different
object and is unaffected — it compounds one run's per-depth hazards, so it is
monotone by construction and asserts as much.)

### Two things this measurement does NOT say

* **There is no tree data above B=1. None.** The −25% / −26% / −46%
  figures for B=2 / B=4 / B=8 that have circulated are **UNTESTED, not
  refuted** — they were never taken on the corpus harness, and they must
  not be quoted in either direction. Concurrency is also the one axis on
  which the tree's economics could plausibly differ from the B=1 result:
  the verify block is `concurrency × (nodes + 1)` flat tokens against the
  chain's `concurrency × (K + 1)`, and the drafter's `B * parents` rows
  compete for the same exl3 M tile the batch does.
* **A device-side assert / SIGSEGV in the tree verify path reproduces at
  B=2 and B=4** — `index out of bounds: 0 <= tmp5 < 18`, raised from
  `mtp_verify_offload.py:194` — on a build that PREDATES #1610. The chain
  is clean at the same concurrencies on the same build. Whether it is
  live on `main` is being measured now. Treat it as **OPEN**: a B>1 tree
  run that dies is the first thing to check against this, and no B>1
  tree number should be reported until it is resolved either way.

## The 16-row cliff is exl3's, and removing it does not save the tree

**Read this section, and every row-budget claim in this file, as taken at
exllamav3 pin `48d53ff`, whose shape table held only `TILESIZE_M=16`.**
Since pin `b81090d2` the table also carries 32, 48 and 64, so one trellis
decode serves up to 64 rows and the 16 -> 17 riser measured below is gone
on the exl3 pack too: whole-model, census-weighted, it fell from 13.36 ms
to 1.12 ms, at a ±0.95-1.24 ms noise floor (measured 2026-08-27). What
survives is the finding, and it survives strengthened: this section
already showed that removing the cliff does not save the tree, and the
exl3 pack has since removed it and still loses. `block_m <= 16` is
untouched by the deeper table (`exl3_gemm_shape_compat` declines a
multi-row-block shape at `size_m <= 16`), so every number here at 15 or
16 rows still reads true today; the numbers past 17 do not.

The strip is why a tree on exl3 may not be widened past 16 verify rows,
and it is NOT why `2x2x1x1` loses — 15 rows is inside strip 1. Both
halves were tested by re-running the whole question on a quantiser with
no trellis: `Qwen3.8-27B-AWQ-INT4` is the SAME model as the exl3 pack,
compressed-tensors pack-quantized INT4, group 32, served through the
Marlin W4A16 GEMM. TP1 on one RTX 4090, `--lm-head-quant full-int4
--embed-quant fp8` (the AWQ export leaves both heads dense, and at 27B
they do not fit beside the pack on a 24 GiB card).

**The staircase is structural, the riser is not.** Both kernels tile M at
16 rows, so both step at the same places. What differs is what a step
buys. `bench_verify_width_inproc`, same box, same session, whole model:

| verify rows | exl3-4.0bpw | AWQ-INT4 |
|---:|---:|---:|
| 16 → 17 | **+11.36 ms** | **+1.07 ms** |
| 32 → 33 | +11.45 ms | +1.25 ms |
| 48 → 49 | +11.48 ms | +3.52 ms |
| 5 → 64 (total) | +39.20 ms | +5.46 ms |

`exl3_gemm` re-decodes the whole trellis per M tile — 16 rows deep for
every shape at this pin — so row 17 buys a second pass over the weights.
Marlin reads its B tile once per CTA and runs `thread_m_blocks` of MMA
against it (`marlin.cu`, `thread_m_blocks =
min(div_ceil(m, 16), 4)`), so row 17 buys extra MMA and extra output
traffic, not a second weight read. Same tile, one tenth the riser. Both
also step DOWN at 8 → 9, where Marlin leaves its `m_block_size_8` variant.

**Confirmed end-to-end: on AWQ the step cost is linear in verify rows
across 16.** Corpus A/B, B=1, short60, paired by prompt:

| pair | tok/step | tok/s | step ms |
|---|---:|---:|---:|
| tree `2x2x1x1` vs chain K=4 | **+8.07%** [+6.34, +9.91] | **−2.71%** [−4.62, −0.76] | 34.19 vs 31.14 |
| tree `2x2x2x1` (23 rows) vs chain K=4 | +10.65% [+8.61, +12.75] | −4.96% [−6.91, −2.97] | 36.41 vs 31.30 |
| tree `2x2x2x1` vs tree `2x2x1x1` | +2.44% [+1.21, +3.59] | −3.72% [−4.86, −2.58] | 36.41 vs 34.19 |

5 → 15 rows costs 0.305 ms a row and 15 → 23 costs 0.278 — the same
slope, straight through the boundary that costs exl3 a whole strip. So
the in-process ladder's prediction holds on the served step.

**And the tree still loses, wider still worse.** The 16-row cliff was
never the binding cost at `2x2x1x1`, and lifting it does not change the
sign — it buys 1.7 points of tok/s (−2.71% against exl3's −4.43%) and the
step penalty falls from +12.4% to +9.8%, no further. Rows cost ~0.28 ms
each whatever decodes the weights, because most of that is the tree scan's
index gathers, the packed recurrent scan (one row per LEAF), and the eager
drafter — all of which scale with node and leaf count and none of which
is the GEMM. Spending the newly affordable rows makes it worse: 8 more
rows buy +2.44% tokens per step for +2.22 ms, which is −3.72% tok/s.

Acceptance is the model's, not the quantiser's: +8.07% here against
+8.47% on the exl3 pack of the same model, intervals almost coincident.

**Instrument, before the effect.** ABBA over boots, chain / tree / tree /
chain-null. Two chain boots inside that block: tok/step +0.000% on all 60
prompts, tok/s +0.03% [−0.07, +0.15]. Two tree boots: +0.000% and −0.02%.
A chain re-boot 13 minutes later drifted −1.49% — ten times the
within-block floor, which is why an arm is judged against the chain boot
NEXT to it and not against the session's first one. Its arm ran 17 MHz
slower than the first chain's, which is about half of it. Every arm's
counters passed, including `mtp_tree_verify` and
`gdn_tree_replay_commit` moving step for step and `gdn_tree_verify_forward`
at zero under traffic. No clock lock is enforced on these cards: 2625–2880
MHz observed, per-arm means within 17 MHz of each other, 50–57 °C.

**Provenance, and the two places it is not a like-for-like.** Taken at
`816e59a7` plus the bench's head-quant flag — deliberately the same base
as the exl3 rows above, so the two are comparable; #1622 and #1623 landed
after and are not in it. `--lm-head-quant full-int4` changes emitted
logits, so the absolute tokens-per-step is not the served model's; every
arm is held at the same mode, so the paired delta is. And the in-process
ladder prices the GEMM stack in isolation: at 5 rows it mispredicts the
in-graph kernel SELECTION (see the profiled decomposition below), so read
it for the riser at a tile boundary, which is what it is used for here,
and not for the 5-vs-15 comparison the served A/B answers directly.

**What this closes.** The cost argument against the tree does not depend
on the trellis, so a quantiser swap is not the lever, and neither is a
wider tree. Lever 2 (fuse the tree scan's gathers) and the leaf count are
what the row price is made of; until one of them moves, no shape wins on
either quantiser.

## The hybrid's recurrent half — WIRED, and how

`Qwen3.8-27B` (and the 3.6 before it) is 48 GDN layers to 16
full-attention layers — `full_attention_interval: 4`. The ancestors-only
attention mask reaches one layer in four; the other three quarters take
the verify block through a recurrent scan, and a scan over a tree's block
folds every earlier block row into node `j`'s state, siblings included.
That was the blocker. It is now the tree route in
`models/_gdn_fla_verify_tree.py`, and it adds no kernel:

* **conv** — node `i`'s window is the last `Kw` tokens along `i`'s OWN
  ancestor chain, which is one advanced index into the same augmented
  buffer `[base[..., 1:] ‖ x_0..x_{N-1}]` the chain unfolds. Depth does
  not enter: a conv window is finite, so one gather covers the tree.
* **recurrence** — every root-to-leaf path is packed as its own varlen
  row, so each row IS an ancestor chain and the call is the chain's own
  `fused_sigmoid_gating_delta_rule_update`, unchanged. The block is
  `TreeSpec((1, *widths))` — the committed token as node 0 — so block row
  and node id are the same integer and no ±1 shift is carried anywhere.
* **accept** — the forward stages the per-NODE inputs; the accept-time
  masked replay gathers the accepted PATH out of node order into an
  ancestor chain and then runs the shipped replay verbatim, because a
  gathered path IS a prefix. The conv side needs no gather at all: the
  window after the accepted path is `Kw` columns along the accepted
  LEAF's chain, one row of the same static table.

Two asymmetries a chain does not have, both forced by the packed launch
having `L` rows where the slab has one row per request:

* the forward's committed recurrent state is **discarded** — every packed
  row's `final_state_last_only` store names the same slab index, so the
  survivor is launch-ordered. It goes to a spare slab
  (`GdnLayerView.tree_discard_state`) rather than aliasing `initial_state`
  the way a chain's does, or one row's store could land before another
  row's `h0` load and seed that path from a sibling's state. The accepted
  path's state comes from the accept-time replay, which therefore runs on
  EVERY tree step — the chain's full-accept skip is dropped, by name, in
  `_rollback_recurrent_offloaded`.
* the per-token replay inputs are staged by hand. The kernel's
  `save_inputs_kvba` also addresses by `ssm_state_indices`, so on a packed
  launch all `L` rows would race for one slab row's replay slots with
  DIFFERENT tokens. `save_base_state_out` stays in-kernel: every packed
  row writes the same effective `h0`, so those writes agree.

**The verify forward is COMPILED and CAPTURED on this stack.** The
decode/verify capture traces the whole decoder layer, so the tree scan
needs the same treatment the chain's replay-save launch gets — one opaque
call per layer, `arbi_serve::gdn_tree_packed_scan`. Without it the verify
bucket at the tree's width fails to capture and the whole verify pass
runs eager, which is correct output at a step cost no A/B can be read
against.

`assert_tree_supported` (`spec_decode/tree_boot.py`) still refuses, by
name, what is NOT wired: a non-GDN recurrent pool (Mamba2 and the DSv4
compressor both replay a block-order PREFIX, which for a tree names a
different set of tokens), recompute-mode rollback (no replay buffers to
gather the path out of), a paged-KV backend with no mask seam at all
(neither the bypass op's attend call nor the codec op's core forward),
`TKV_MTP_FA4_SPLIT=0` (split-K takes no mask argument), TP>1, and a
keyed watermark.

### Buffer sizing a tree moves, and why it is boot-time

* the masked-replay buffers are `tree_step_k(max_k) + 1` deep, not
  `max_k + 1`: a tree stages one row per BLOCK row because its accepted
  path is gathered out of node order at accept time.
* both page-metadata builders are sized for `max_num_seqs *
  tree_draft_rows_per_seq()`. A tree DRAFTER runs one attention row per
  NODE of the previous depth where a chain runs one per request, and the
  CSR triplet those rows index is allocated once at boot. The factor is
  `1` for a chain and for a width-1 tree, so neither boot moves.

  What that costs, named: the main builder's `indices` is `max_num_seqs *
  max_blk` int32 at the KV pool's page CEILING, and its q-prescale pair
  scales with `max_num_seqs` too, so a `2x2x1x1` boot charges 4× for both.
  Small at the contexts measured here and not small at every context —
  it lands on the same post-capture VRAM gate the drafter-private pool is
  already sized against, so an over-charge is a loud boot failure rather
  than a quiet one.

### Prior art, for expectation-setting only

Lucebox ships DDTree on **Qwen3.5-27B, this exact architecture**, with
tree-aware recurrent kernels, and reports chain DFlash 112.82 tok/s →
DDTree budget-22 **129.52 tok/s**, i.e. **+14.8%** over their own chain
(that division is ours; the two tok/s figures are theirs). They say it is
below the +35-42% they see on pure-attention models. Source, and read it
before relying on it: <https://www.lucebox.com/blog/dflash27b> (April
2026; the DDTree row is a fresh run dated 2026-04-20 on commit
`5bb7f8c`), target `Qwen3.5-27B-Q4_K_M.gguf`, draft
`z-lab/Qwen3.5-27B-DFlash`, RTX 3090, **HumanEval 10-prompt** bench at
`n_gen=256`; `--ddtree` defaults OFF per
<https://github.com/Luce-Org/lucebox>. Read 2026-08-25 via an automated
page fetch, not transcribed by hand. It is a 10-prompt bench on ggml Q4
on a 3090 — evidence the approach works and roughly what it pays on this
architecture, not a number transferable to an exl3 4090. Full provenance
table in `tree-speculation-feasibility.md`.

## Measured on hardware — the correctness gate

Local RTX 4090, `Qwen3.8-27B-exl3-4.0bpw` (bundled MTP head), TP1,
`cuda_graphs=True`, `--max-batch 1`, `--mtp-n-draft 4`, 6 prompts × 96
completion tokens per arm, `temperature=0`, one boot per arm through
`tools/tree_greedy_dump.py`. tkv at **turbo-attn#883**, which is what
puts `ancestor_mask` on `BypassBf16Attend.attend`.

| arm | verify steps | tokens/step | vs non-spec greedy | vs chain K=4 |
|---|---:|---:|---|---|
| non-spec (`mtp_k=0`) | — | 1.00 | — | — |
| chain K=4 | 167 | 3.45 | 3/6 identical | — |
| tree `1x1x1x1` | 167 | 3.45 | 3/6, the SAME three prompts | **6/6 BYTE-IDENTICAL** |
| tree `2x2x1x1` | 151 | 3.81 | **4/6 identical** | 4/6 |

(The chain's step count is read off the width-1 tree, which produced
byte-identical output on all six prompts and therefore accepted the same
tokens at the same steps.)

Counters on the sibling-bearing arm, scraped around the GENERATION and
not the boot: `mtp_tree_verify +151` and `gdn_tree_replay_commit +151` —
the two halves agreeing step for step — and `mtp_tree_draft_spine +1099`,
the off-spine drafter expansions, which is what says siblings were really
drafted rather than a width-1 tree wearing a wider flag.

**Read the divergences correctly.** Strict byte-identity against non-spec
decode is not available on this model at these prompts: the CHAIN fails
it on three of six, which is the bf16 cross-shape tie-fork the shipped
losslessness gate is two-tier for. The tree at `2x2x1x1` matches the
non-spec reference on FOUR of six — more than the chain — and every one
of its divergences from the chain is at a prompt where the chain itself
forks away from the reference. On prompt 1 the tree lands on the
reference's continuation and the chain does not.

So the two gates are:

* **`1x1x1x1` vs the chain, exact.** 6/6 byte-identical across 576
  tokens, with `mtp_tree_verify +167` proving the tree verify path ran.
  This isolates the tree machinery at the chain's own verify shape: the
  node-count step size, the device tree accept op and its `path_rows`,
  the drafter-seed gather by accepted ROW, the KV compaction path, the
  tree drafter recursion, and the capture-shape helper.
* **`2x2x1x1` against the per-path oracle**, which is where siblings are
  isolated, because end-to-end byte-identity cannot separate a tie-fork
  from a fault at a widened block. `tests/test_gdn_tree_verify_gpu.py`
  holds every node's mixer output to a run of that node's OWN ancestor
  chain, alone, from the committed state — 2.2e-3 relative, with the
  chain scan over the same tree block failing the same comparison by two
  orders of magnitude as the negative control. The scattered-accept
  rollback is held to the same standard (byte-exact on the conv window),
  with the chain's prefix rule as ITS negative control.

## The seams, and where each one landed

Every row here was a seam a tree needed and a chain did not. None of them
is open; the column that matters is what pins it, because each fails
silently — the tree serves, acceptance looks healthy, tok/s looks
healthy, and the tokens are wrong.

| seam | where it landed | pinned by |
|---|---|---|
| verify-plan geometry (node count, shared sibling positions, `cu_q`) | `spec_decode/mtp_verify_plan.py` | `tests/test_tree_verify_plan_positions.py` |
| buffer widening to node count | `spec_decode/verify_buffers.py` | `tests/test_tree_verify_buffers.py` |
| capture shape `S = nodes + 1` | `engine/capture_admin/_shapes.py` | `tests/test_tree_capture_shape.py` |
| tree expansion in the drafter | `spec_decode/mtp_driver_tree.py` | `tests/test_tree_drafter_expansion.py` |
| the mask to the bypass `attend` | `backends/tkv_bypass_backend.py::_tree_mask_kwargs` | `tests/test_tree_boot_gate.py` |
| the mask to the codec `TKVCore.forward` | `backends/tkv_attn_op.py::_tree_mask_kwargs` | `tests/test_tree_codec_mask_seam.py` |
| the one shape gate both routes share | `spec_decode/tree_spec.py::verify_block_mask_kwargs` | both of the above |
| KV compaction for a scattered accept | `spec_decode/tree_kv_compact.py` + both page tables | `tests/test_tree_kv_compaction.py` |
| GDN tree scan, conv gather, path replay | `models/_gdn_fla_verify_tree.py` | `tests/test_gdn_tree_verify_gpu.py` |

### KV compaction — the one with two implementations

`finalize_draft_slots` is a pure suffix trim, which is exactly right for
a chain: its accepted tokens are draft slots `0..n-1`, so trimming the
tail leaves the accepted KV in place. A tree's accepted path is
SCATTERED — accepting nodes `1, 4, 11` of 14 and trimming to length 3
keeps slots `0, 1, 2`, three tokens the model never committed — so
`retire_draft_slots` moves each accepted row down to its own depth's
ordinal first, then trims.

Which slot an ordinal names is the part that differs between the two page
tables: `FlatPageTable` addresses one page list, `RadixPageTable` puts
draft slots past the shared prefix in the request's PRIVATE pages. Both
implement `draft_path_moves`; the guards — a path that runs past the
allocated slots, or whose depth-`d` entry precedes ordinal `d` — are the
shared `draft_path_ordinal_pairs`, so neither table can be the lenient
one. RoPE is NOT re-applied: siblings share a position and the accepted
node at depth `d` was written at absolute position `P + d`, which is
where its destination ordinal sits. This is a move of finished KV.

### The drafter runs EAGER — and that is NOT where the tree's cost is

`_draft_captured` replays a graph whose `_step` calls
`head.forward(..., probs=None)` — the greedy argmax carry is BAKED in,
one token per step. A per-node top-`W` expansion cannot replay it, so a
tree pays for its `D` head calls eagerly while the chain pays for `K` as
one graph replay. Measured for the CHAIN's own four head calls with the (since-removed)
`arbi_serve/scripts/bench_drafter_capture_delta.py` (#1578): **+0.418
ms/step**, CI95 `[+0.401, +0.438]`, clearing its own null floor by 5.5x.

The first tree A/B put the eager drafter plus the tree's bookkeeping at
+2.44 ms and called it the budget's largest line. **Most of that was one
pageable host-to-device copy**, not the drafter. The per-depth ancestor
index was built as `torch.tensor(list, device=cuda)` inside the live
path; the CUDA runtime serializes a pageable copy as memcpy plus stream
synchronize, so the first one of each step blocked the host until the
previous step's verify forward had drained. Measured in-process on
`2x2x1x1` at B=1: **23.9 ms** on the depth-1 copy and 1.05 ms on each of
the two after it, against a 35.3 ms step. Caching the index per
`(widths, device)` — the geometry is a process constant, exactly as for
`verify_block_tables` — took the drafter's host time per step from 32.34
ms to 6.45 ms and the step from 35.26 to 33.46. The tree also ran the
eager frontier repair its own depth-0 write already subsumes (the chain
skips it on the sync path for that reason); dropping it removes another
1.09 ms of host and its device work.

What is left of the eager drafter is small, and the profiled table under
"Where the remaining cost is" below measures it by splitting kernels by
LAUNCH SOURCE. Running the drafter eagerly moves 5.9 ms of kernel time
out of a graph and into the launch path, and the whole penalty for that
is **+0.40 ms of device time and +0.65 ms of GPU idle** at the chain's
own geometry. On the SERVING geometry the idle half is only **+0.27 ms**,
because the tree's wider depths give the device more work to hide the
launches behind. **A captured tree-drafter pool is worth a few tenths of
a millisecond, not 2.4.** That reorders the whole lever list.

The VERIFY forward is not part of it. That captures for a tree exactly as
for a chain once the tree scan is behind its opaque op, and
`bench_tree_step_delta.py` refuses to report a delta unless
`cudagraph_verify_replay` moved on both arms and
`gdn_tree_verify_forward` stayed at zero under traffic.

## Measuring a tree against a chain

`arbi_serve/scripts/bench_tree_step_delta.py` (removed from the tree in
#1799; not re-executable here). tok/s is a ratio of two
things that move in OPPOSITE directions when a tree replaces a chain —
more tokens committed per step, and a dearer step — so it measures both,
per arm, from one booted process.

**`--prompt-corpus` is not optional for the token half.** Without it the
feed is one paragraph truncated at a random word, and since acceptance is
a pure function of the continuation the target wants, that is n=1 however
many steps it runs — every "seed" is a cut of the same greedy trajectory.
#1612 made the PROMPT the unit of replication: the corpus loader is
`bench_prompt_corpus.py`, per-prompt rows carry register / category /
regime so a result can be sliced afterwards, and `bench_stats.estimate`
takes the interval over prompts. Every number under a SUPERSEDED heading
below predates that, which is why those headings say so.

**The arm is a BOOT, and that sets the noise floor.** `ARBI_MTP_TREE`
moves the verify plan's step size, every capture-shape decision, the
replay buffers' depth and the drafter route, all resolved at build. So
unlike the drafter's eager-vs-replay delta, the two arms cannot be
interleaved rep by rep inside one process, and the unit of pairing is a
boot. `--arm chain-null` is the chain arm again, byte for byte,
alternated into the same sequence: the spread between two CHAIN boots is
what any tree-vs-chain delta has to clear.

**Counters, resolved before any number.** `cudagraph_verify_replay` must
have moved on every arm — an eager verify pass costs several ms a step
and comparing it against a captured one measures the fallback. A tree arm
additionally needs `mtp_tree_verify` and `gdn_tree_replay_commit` to have
moved (the accept walk and the recurrent reconcile, the two halves), and
`gdn_tree_verify_forward` to be nonzero at BOOT and to have moved by
exactly zero under traffic. That last one is the discriminator that
matters most: it fires from inside the tree scan's opaque op, which the
verify graph RECORDS, so movement under traffic means the verify forward
is re-running eagerly instead of replaying — the one way this harness
could compare a captured chain against an eager tree without noticing.

## SUPERSEDED (single prompt) — the first measured A/B

**Withdrawn: the tokens-per-step and tok/s rows below are n=1.** This
whole A/B ran one paragraph truncated at a random word, so its token side
measures one greedy trajectory and its `+6.97%` is a sample from the
−16.9%..+22.3% spread *The corpus-aware A/B* prices. It is kept here, not
deleted, because it is where the +6.97% a reader may have seen came from
— and because its STEP-COST half is unaffected: cost at a fixed verify
geometry does not depend on what the prompt says. Read the step-cost
column, the counter gates and the profiled decomposition; do not read the
tok/s.

Local box GPU 0, `Qwen3.8-27B-exl3-4.0bpw`, TP1, `cuda_graphs=True`,
`--max-batch 1`, `--max-context 2048`, `--reps 400`, tkv at
turbo-attn#883. Twelve boots, alternated `chain / tree / chain-null` for
four rounds, through `arbi_serve/scripts/bench_tree_step_delta.py`,
against a FROZEN copy of the worktree so no edit can land between two
boots. Every boot's counter evidence passed: `cudagraph_verify_replay`
moved on all twelve, `mtp_tree_verify` and `gdn_tree_replay_commit` moved
on every tree boot, and `gdn_tree_verify_forward` was nonzero at boot and
moved by exactly zero under traffic — the verify graph contains the tree
scan and replays it.

| | tree / chain | worst boot | NULL chain / chain |
|---|---:|---:|---:|
| tokens per step | **+20.26%** | +20.26% | **+0.00%** |
| step cost | **+12.49%** | +13.26% | -0.09% (worst 0.75%) |
| **tok/s** | **+6.97%** | +6.37% | +0.10% (worst 0.74%) |

**Read the null before the effect.** Two chain boots differ by at most
0.74% in tok/s and by exactly zero in tokens per step, so the
effect clears the floor by 9x.

**Tokens per step is not comparable across boxes, and the step cost is
the half that moved.** Every chain-family boot here committed exactly
2.2275 tokens a step and every tree boot exactly 2.6789 — deterministic
within a box, but not the 2.2612 / 2.6282 the first run of this A/B saw
on 206, because the exl3 autotune resolves per box and a different kernel
gives a different token stream. Hold the acceptance ratio at the earlier
run's 1.1623 and this run's step ratio still puts the tree at +3.3%.

The FIRST run of this A/B measured **−1.57%**, and the difference is
entirely the step cost: it was +17.75% and is now +12.49%. Two per-step
costs came out of the drafter, neither of them the tree — a pageable
host-to-device copy that blocked the host behind the previous step's
verify forward, and an eager frontier repair that depth 0's own write
already makes. Neither touches what the drafter PROPOSES, so tokens per
step is unchanged by construction and the acceptance half of the
projection still reads exactly as it did.

### Where the remaining cost is — profiled, and split by launch source

The step is device-bound at both ends: the union of kernel intervals is
93.9% of wall on the chain and 93.9% on `2x2x1x1`, so nothing below is a
host effect. The window is 40 steps starting at step 90, `torch.profiler`
with CUDA activity, kernels attributed by the runtime call that launched
them — `cudaGraphLaunch` for anything inside a captured graph (the verify
graph, and the chain's own drafter graph), `cudaLaunchKernel` for the
eager drafter. Same box, same window, one boot per arm, ms per step.

| arm | block_m | drafter | GDN scan | in graphs | eager | device | wall/step | GPU idle |
|---|---:|---|---|---:|---:|---:|---:|---:|
| chain K=4 | 5 | 4, captured | chain | 27.55 | 1.60 | 29.14 | 31.08 | 1.94 |
| tree `1x1x1x1` | 5 | 4 depths, EAGER | chain | 21.63 | 7.91 | 29.54 | 32.13 | 2.59 |
| tree `2x2x1x1` | 15 | 4 depths, EAGER, 1/2/4/4 rows | packed | 24.74 | 8.12 | 32.86 | 35.07 | 2.21 |

Two clean subtractions fall out of it, and they replace the +2.44 / +2.78
split the first A/B reported:

* **The eager drafter costs +0.40 ms of device and +0.65 ms of idle** —
  the `tree 1x1x1x1` row against the chain, same block, same scan, same
  four drafted tokens. That is the WHOLE eager-vs-captured penalty, and
  on the serving geometry its idle half is only +0.27 ms.
* **The wider block costs +3.11 ms, all of it inside the verify graph** —
  the `2x2x1x1` row against `1x1x1x1`, whose drafter is eager in both, so
  the drafter cancels. The drafter's own widening from 1 row to 1/2/4/4
  is the +0.21 ms difference in the eager column, and is not where the
  cost is.

That widening is spread across three unrelated places, none of them
dominant. Kernels inside the VERIFY graph only, ms per step — the eager
drafter is excluded from both columns by construction, so nothing here
is the drafter:

| component | block 5 | block 15 | delta |
|---|---:|---:|---:|
| exl3 dense projections (408 matmuls in both) | 17.09 | 18.20 | **+1.11** |
| tree-scan index gathers (`indexSelect`) | 0.02 | 0.96 | **+0.95** |
| recurrent scan (`fused_sigmoid_gating_delta_rule_update`) | 1.10 | 1.85 | **+0.76** |
| everything else in the graph | 3.42 | 3.72 | +0.30 |
| **verify graph, total** | **21.63** | **24.74** | **+3.11** |

* **The dense projections, and why "width-flat to 16 rows" was the wrong
  claim to reason from.** The verify forward issues exactly 408 matmuls
  at BOTH widths. At 5 rows, 213 of them dispatch to `exl3_gemv_kernel`
  (6.73 ms) and 195 to the M-tiled `exl3_gemm` (9.87 ms); at 15 rows all
  408 take `exl3_gemm`, across two tile variants (`...,32,256,...` at 261
  calls for 14.22 ms and `...,32,128,...` at 147 for 3.46 ms). Same
  matmuls, same count, 16.60 ms against 17.68. The GEMM IS width-flat
  where it runs — the staircase was not wrong about the GEMM. What it
  could not see, because it forced all 497 modules through `exl3_gemm`,
  is a kernel-SELECTION boundary between 5 and 15 rows. That boundary is
  the whole +1.08 ms, and it points the opposite way from the -1.0 ms the
  staircase predicted.
* **The tree scan's index gathers.** 244 `indexSelect` launches a step
  against 4 in the chain-scan arm: the conv-window gather and the
  `node_slot` un-packing, one pair per GDN layer, ~4 us each.
  Launch-shaped rather than bandwidth-shaped, and the largest single item
  that is pure tree bookkeeping rather than model work.
* **The recurrent scan itself.** Four leaf rows of five tokens where the
  chain has one row of five, for +69% — not +300%: the kernel is
  setup-dominated at this size, which is the one place the original
  projection was conservative in the tree's favour.

**The tree's GEOMETRY was never what cost.** `chain --k 14` has the
tree's block width with the chain's geometry and a CAPTURED drafter, and
on the first run of this A/B it measured 47.05 ms for 2.3174 tokens/step
against the tree's 34.76 ms for 2.6282. Spending a 15-wide verify block
as a tree is far better than spending it as a chain; the question was
only ever whether it beats not widening it, and it now does.

The levers that remain, in the order the measurement now puts them:

1. **A narrower tree.** `(2,1,1,1)` is 8 nodes and 2 leaves — half the
   block widening, and it reaches all three components at once, which no
   other lever does. By the same rank table it is worth roughly +9%
   tokens per step. Priced, not built.
2. **Fuse the tree scan's gathers.** 0.95 ms in 244 tiny launches, none
   of which exists in the chain. This is the only line that is purely the
   tree's own bookkeeping.
3. **Capture a tree-drafter pool.** The pattern exists
   (`_draft_captured_stochastic`, `runtime/capture/drafter.py:730`, with
   its `q_chain` buffer). It was the top item when the eager drafter was
   believed to cost 2.44 ms; measured, it is worth at most ~0.5 ms, and
   the `mbtopk` part of that is inherent to a top-W expansion and
   survives capture. Ordinary work, small payoff.
4. **A cheaper block widening.** 2.78 ms for 10 extra block rows is 0.28
   ms a row, against a 29.5 ms step that reads 14 GiB of weights. That is
   not the memory-bound regime the feasibility note assumed — at this
   context (1536) the verify's KV read is small and the extra rows are
   paying real compute and real launches. A longer context would shift
   the balance toward the tree, and this measurement does not cover one.
   **That 0.28 ms a row does not extrapolate past the M tile.**
   `block_m` 5 and 15 are both inside ONE exl3 GEMM tile — the kernel
   re-decodes the whole trellis per tile and runs the tiles serially
   (`weight_quant/exl3/custom_op.py`) — so the two-point fit prices
   attention, norms, staging and launches, not the GEMM. The first row
   past the tile buys a second decode of all 64 layers' weights, which is
   a cliff rather than a slope. Where that row falls is set by the
   autotuner's `TILESIZE_M` (16, 32, 48 or 64), not by a fixed 16.
5. **A longer context.** The block widening is paying compute and
   launches, not KV bandwidth; at 2048 the verify's KV read is small. A
   longer context shifts the balance further toward the tree, and this
   measurement does not cover one.

## The drafter's WIDTH, measured — and where its cliff is

Every cost projection this feature made charged the tree for DEPTH and
left WIDTH uncharged; #1578 says so in its own docstring, and the +2.44 ms
row above is booked to "the drafter and the tree's own bookkeeping"
without separating the two. `arbi_serve/scripts/bench_drafter_width_cost`
separates them.

The tree drafter runs the head once per depth on `B * parents` rows —
`1, 2, 4, 4` for `2x2x1x1` at B=1, where the chain runs `1, 1, 1, 1`. So
the BATCH and the tree's width are one axis as far as the head is
concerned, and one sweep prices both. The bench drives the production
`_draft_tree_live` with `TreeSpec((W, 1, 1, 1))` from inside the driver's
own `draft`, at counterbalanced ABBA widths, on one engine and one live
request; every rep is gated on the head having OBSERVED `B, B*W, B*W,
B*W` rows and on `mtp_tree_draft_spine` having fired exactly
`3 * B * (W - 1)`.

Depth 0 runs one row whatever `W` is, so its across-arm delta rides
inside every treatment as a same-width control.

### One head.forward, B=1, 200 reps and 44 quads per phase

| rows | ms | delta vs 1 row | CI95 | depth-0 control |
|---:|---:|---:|---|---:|
| 1 | 2.135 | — | — | — |
| 2 | 2.231 | +0.045 | [+0.044, +0.053] | +0.013 |
| 4 | 2.220 | +0.059 | [+0.055, +0.062] | +0.036 |
| 8 | 2.254 | +0.138 | [+0.133, +0.142] | +0.064 |
| 16 | 2.289 | +0.177 | [+0.173, +0.182] | +0.122 |

Null floor 0.011 ms; both nulls (`1 vs 1` and `16 vs 16`) sit inside
0.003 ms at every depth. Three independent boots reproduce the table —
the largest disagreement on any row is 0.016 ms, itself under a third of
the drift each run reports between its own phases.

**Sixteen rows cost under 8% more than one.** The depth-0 control says most of
even that is not the row count: it is per-rep setup that scales with the
tree's node total, and it appears on a call whose width never changed. Of
the +0.177 ms at 16 rows, +0.122 ms also lands on the 1-row call, so the
row-attributable residual is +0.055 ms across 15 rows — under 4 us a row.

### The GEMM stack alone, past the row budget an engine boot can serve

The engine sweep is bounded by the drafter's page-metadata row budget,
which is sized from `--max-batch` and cannot be raised past what the
recurrent state leaves on a 24 GiB card. The same run therefore also
walks the head's nine row-mapping modules — its own block plus the
`5120 x 248320` lm_head it projects through — with no attention and no
bound.

| rows | GEMM ms | vs 1 row | marginal us/row |
|---:|---:|---:|---:|
| 1 | 1.387 | 1.00x | — |
| 4 | 1.411 | 1.02x | 0.5 |
| 8 | 1.429 | 1.03x | 4.3 |
| 12 | 1.452 | 1.05x | 5.9 |
| 15 | 1.462 | 1.05x | 2.5 |
| 16 | 1.467 | 1.06x | 5.5 |
| **17** | **2.686** | **1.94x** | **1219** |
| 20 | 2.698 | 1.94x | 3.1 |
| 32 | 2.748 | 1.98x | 4.1 |
| **33** | **3.971** | **2.86x** | **1223** |
| 48 | 4.042 | 2.91x | 4.7 |
| 64 | 5.330 | 3.84x | 80.5 |

IQR is 0.010-0.024 ms at every row count, so the two 1.22 ms steps are
roughly fifty times the spread of the points either side of them.

The curve is not a slope with a knee, it is a STAIRCASE. Rows 1 through
16 cost the same; row 17 costs a whole extra pass over the weights, and
every 16 rows after that costs another. `exl3_gemm` re-decodes the ENTIRE
trellis per M tile and runs the tiles serially
(`weight_quant/exl3/custom_op.py`) — so the pass over the head's weights
is what costs, one tile amortizes it across `TILESIZE_M` rows, and the
first row past the tile buys a second pass over the same weights to carry
one row's worth of work. At this pin every tile was 16 rows deep, which
is what puts the risers at 17 and 33; the table now reaches 64, so the
riser positions move outward while the mechanism stays exactly this.

### What that means for a tree's shape

**Width inside a tile is free; the first row past one is not.** The
budget was exactly 16 rows per head call at this pin, and the drafter's
row count is `B * parents` — so a tree spends the SAME budget the batch
does, and the block's budget (per request) is not this one. `2x2x1x1` draws `4B` rows
at its widest depth: at B=4 that lands exactly on the last free row, and
at B=5 it is 20 and buys a second strip on two of its four head calls.

**Width is not what the tree pays for.** Priced against this table, the
whole `2x2x1x1` drafter — depths at 1, 2, 4 and 4 rows against the
chain's four 1-row calls — costs about 0.2 ms a step at B=1, against
the +2.44 ms this document books to the drafter and the tree's
bookkeeping. Width is under a tenth of it; the rest is the eager-vs-
replay penalty #1578 measured and the bookkeeping around it.

**The block, not the drafter, is the width budget.** The verify block's
widening measured +2.78 ms for 10 extra rows — 278 us a row across
`block_m` 5..15. That band is ONE exl3 strip for the verify too, so its
278 us a row is attention, norms, node-order staging and launches rather
than the GEMM, and it must not be extrapolated past 16 either. Inside its
own strip the drafter gives rows away at 4 us a row. The two differ by a
factor near 70, so a shape search should treat drafter width as free up
to the strip and spend its whole budget on BLOCK rows.

**Both halves hit the same wall at the same place, for the same reason,
at very different prices.** `exl3_gemm` re-decodes the entire trellis per
M tile and runs the tiles serially
(`weight_quant/exl3/custom_op.py`), so the first row past the tile buys a
second full decode of whatever weights the pass reads. For the drafter
that is the head's own block plus the lm_head, and one strip costs
1.22 ms. For the verify it is all 64 layers, and an order of magnitude
more.

That reframes lever 3, and it reframes it in the direction the shape
work is already going. Narrowing is not what saves the drafter — inside
one strip the drafter is already free, so a narrower tree recovers
almost nothing there. What a narrower tree saves is BLOCK rows, and what
a better-shaped tree saves is nodes at the same block width. The
drafter's own per-node `top_w` costs, on this table, essentially nothing
until the strip fills: a shape may branch as wide as the block budget
lets it without the drafter noticing, and a shape that draws fewer
drafter rows is not thereby cheaper. Width is simply not a term in the
tree's economics until the M tile fills.

## The tree's SHAPE — spine topology, built and MEASURED

**The result first: the spine topology costs nothing and buys nothing.**
It is expressible now (#1583), it serves, it is correct, and at equal
depth, node count and verify rows it is indistinguishable from the
product tree it was supposed to dominate. The section below keeps the
argument that motivated it, because the argument is what the measurement
refutes.

**Its TOKEN comparisons are single-prompt and are withdrawn** — see *The
corpus-aware A/B* above. What survives is the cost half and the
same-geometry control: spine nodes cost no more than product nodes at
equal count, and no spine shape is a reason to prefer a tree to a chain,
because no tree is. `2x2x1x1` is NOT the shape to ship; nothing is.

### The argument that motivated it

`ARBI_MTP_TREE` parsed one width per depth into a COMPLETE tree, and
every complete tree it could name looked dominated at its own row count.
The reason looked structural rather than a matter of tuning: a product
tree replicates each later width across every earlier sibling, and those
replicas are the worst rows in the tree — they are consulted only on a
step that has ALREADY deviated from the drafter's argmax path.

Priced against the K=5 q-rank joint on this model:

* `2x2x2x2` as a PRODUCT is 30 nodes and returns 1.2360x tokens/step;
* the same widths as a SPINE are 14 nodes and return 1.2067x.

The 16 extra nodes buy 0.0293x — 0.0052 tokens per row, about 11x worse
than the spine nodes sitting beside them. On that pricing, widening
off-spine was the single worst row purchase the shape space offered, and
`spine(2,2,2,1,1)/tail2` was modelled at **+14.00%** tok/s against the
chain where `2x2x1x1` had measured +6.97% (both withdrawn — the modelled
figure was never confirmed and the +6.97% is single-prompt).

**None of that survived the GPU.** See *The A/B* below.

### What a spine tree is

`widths[d]` applies to the ARGMAX path only. A node that has already
deviated spawns ONE child while it is within `tail` depths of its branch
point, and none after — so each deviation continues as a truncated
CHAIN rather than as a copy of the remaining tree.

Truncating those tails is what makes a fifth depth affordable. A full
depth-5 spine is 20 nodes / 21 rows and was dead on arrival against the
16-row tile cliff of the pin this was argued at; cutting the tails to two
nodes past the branch brings it to 14 nodes / 15 rows — the identical
verify budget, capture bucket and exl3 tile as the `2x2x1x1` already
measured.

### The grammar

Two spellings, one meaning, and the bare width list is untouched:

| `ARBI_MTP_TREE` | topology | nodes | verify rows |
|---|---|---:|---:|
| `2x2x1x1` | product, as before | 14 | 15 |
| `spine:2x2x2x1x1:tail2` | spine, tails 2 deep | 14 | 15 |
| `spine(2,2,2,1,1)/tail2` | the same value | 14 | 15 |
| `spine:2x2x2x1x1:tail1` | spine, tails 1 deep | 11 | 12 |

`TreeSpec.spelling` emits the canonical form and `describe()` leads with
it, so a boot refusal names a value an operator can paste back. A
`spine:` with no `tail` is a parse REFUSAL and not a default: the tail
changes the node count, so defaulting it would serve a shape nobody
wrote.

### What the topology did and did not move

A spine tree is a different node set, not a different mechanism, so most
of the stack needed nothing:

* **the ancestor mask and the verify block table** are built from
  `ancestors` alone and were already general;
* **the greedy accept walk** (`mtp_verify_greedy_tree`) drives off
  `parent_row` / `depth_of` and `depth` iterations, and a depth with no
  node at it simply matches nothing;
* **the accept-time recurrent replay** gathers a padded path and masks
  past `n_accepted`, which is exactly what a path that ENDS EARLY needs.

Three places did:

* **the level parent map** in the GDN scan was
  `arange(level) // widths[d]`, which assumes one width per level. It
  reads off `spec.parents` now.
* **the path packing.** A product tree's leaves are all at the last
  depth; a spine tree's tails end early, so a short path is padded to
  the full depth by repeating its own LEAF. The padding is free of
  consequence because it sits at the END of a packed row — those repeats
  evolve only states after the leaf, which the packed scan sends to the
  discard slab, and `node_slot` addresses a node's FIRST occurrence,
  which is always the real one. Keeping the packing rectangular in
  exchange keeps `cu_seqlens` uniform, so no kernel is handed a shape it
  has not already been served.

  **Its price, as a number rather than a worry.** The winner packs 24
  tokens where 21 are real, against `2x2x1x1`'s 20; `/tail1` packs 24 for
  18 real. The kernel IS varlen — `fused_sigmoid_gating` reads `bos, eos`
  off `cu_seqlens` per sequence — so a ragged packing is available and
  would recover those 3 and 6 tokens. It is not taken because the scan it
  shrinks is small: path packing measured 61.4 us at `2x2x2` against a
  ~30 ms step, so 12.5% fewer packed tokens is well under 0.1% of a step,
  and the padded form costs no new kernel shape. If a measured result
  ever falls short of its model by enough for this to matter,
  `test_the_paddings_price_is_pinned_as_a_number` is where the budget is
  written down.
* **the drafter expansion.** Rows at a depth want different widths now,
  and a per-row `top_w` would be a data-dependent kernel shape. So one
  `topk` runs at the widest width any row there takes and a static index
  cuts it down — free, on the table above, at under 4 us a row.

### The drafter's row budget, which is where this shows up at batch > 1

A truncated tail also stops EXPANDING, and a node that spawns nothing
must not be handed to the head: it buys no candidate and costs a row of
the same `B * parents` budget the batch competes for. So the spine
shapes are strictly cheaper on that axis than the product shape they
replace — this is the one axis on which the topology still wins, and it
is the one this B=1 A/B cannot see:

| shape | verify rows | drafter rows / seq | last B in one strip |
|---|---:|---:|---:|
| chain K=4 / K=5 | 5 / 6 | 1 | 16 |
| `2x2x1x1` | 15 | 4 | **4** |
| `spine:2x2x2x1x1:tail2` | 15 | 3 | **5** |
| `spine:2x2x2x1x1:tail1` | 12 | 2 | **8** |

`2x2x1x1` sits exactly on the last free row at B=4 and buys a second
full weight decode at B=5. `spine(2,2,2,1,1)/tail2` moves that boundary
to B=5 and `/tail1` to B=8 — so where the shape work at B=1 is about
block rows, the topology is also what decides whether the tree survives
concurrency at all.

These are static geometry, not a measurement: the row counts fall out of
:attr:`TreeSpec.draft_rows` and the 16 is the `TILESIZE_M` `exl3_gemm`
selected at this pin — the table now also holds 32, 48 and 64, so the
`last B in one strip` column is a floor rather than the boundary.
Nothing here was measured at B>1, and the B=1 A/B below says the extra
tokens a spine shape buys are worth about nothing — so this is a reason
to KEEP the grammar, not a reason to ship a spine shape today.

### SUPERSEDED (single prompt) — the topology A/B

**This is the table the `+5.26%` came from, and the `+5.26%` is
withdrawn.** Same defect as the A/B above: one paragraph, so every
`tok/step` and `tok/s` cell is one greedy trajectory. Kept so that a
reader who saw +5.26% finds out it was withdrawn rather than finding it
missing. The corpus-aware replacement is **−4.43%** on `main`, and the
arm-vs-arm cost comparisons here (equal geometry, same box, same window)
are the part that still reads.

206 GPU 1, `Qwen3.8-27B-exl3-4.0bpw`, TP1, `cuda_graphs=True`,
`--max-batch 1`, `--max-context 1536`, `--reps 400`, **greedy**, the
**bf16-bypass** route, tkv at turbo-attn `main`. Four counterbalanced
rounds through `arbi_serve/scripts/bench_tree_step_delta.py` — each round
runs the arms in a different order and every odd/even pair is the exact
reverse of its partner, so a monotone drift across the sequence cancels
within the pair. Every boot's counter gate passed, and every boot
recorded ZERO other compute processes on the card at launch.

| arm | n | tok/step | step ms | tok/s | vs chain K=4 |
|---|--:|---:|---:|---:|---:|
| chain K=4 | 4 | 2.3062 | 29.47 | 78.96 | — |
| chain K=5 | 4 | 2.2837 | 31.08 | 73.91 | −6.40% |
| *NULL: chain K=4 again* | 4 | 2.3062 | 29.47 | 78.99 | **+0.03%** |
| *NULL: chain K=5 again* | 3 | 2.2837 | 31.16 | 73.68 | **−0.31%** |
| **`2x2x1x1`** (D4, 15 rows) | 4 | 2.7408 | 33.21 | **83.12** | **+5.26%** |
| `spine(2,2,2,2)/tail3` (D4, 15 rows) | 3 | 2.7296 | 33.39 | 82.35 | +4.29% |
| `spine(2,2,2,1,1)/tail2` (D5, 15 rows) | 4 | 2.7887 | 35.15 | 79.87 | +1.15% |
| `spine(2,2,2,1,1)/tail1` (D5, 12 rows) | 4 | 2.7549 | 34.84 | 79.63 | +0.84% |

**Read the null first.** Two chain boots differ by +0.03% / −0.31% in
tok/s (worst single pairing 1.51%) and by EXACTLY 0.00% in tok/step.

**The decisive arm is `spine(2,2,2,2)/tail3`.** It is the same depth 4,
the same 14 nodes and the same 15 rows as `2x2x1x1`, so the per-depth
term, the per-row term and the tree's fixed overhead all cancel and what
is left between them is topology alone:

| | tok/step | step ms | tok/s |
|---|---:|---:|---:|
| `spine(2,2,2,2)/tail3` vs `2x2x1x1` | **−0.41%** | **+0.54%** | **−0.93%** |

Inside the null on tok/s. **The cost half of the model was right — spine
nodes cost no more than product nodes at equal count. The token half was
wrong: it predicted 