diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index 1bff90fe..1fe63426 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -141,6 +141,33 @@ struct Kind { int64_t kv_dim() const { return nkv * hd; } }; +/* ---- the GPTQ calibration tap (rad_arch.h's calib_*): the Gram of one bf16 linear's input, + * summed over a corpus in a PERSIST [K, K] f32 buffer. Declared only with RADIANCE_CALIB_DIR set, + * for the dense layers RADIANCE_G4_CALIB_LAYERS names ("lo:hi", default every layer): the 31B's + * four taps a layer are ~364 MiB a rank at --tp 4, so its 60 layers do not fit beside the bf16 + * weights and a calibration runs in slices of layers, the corpus pushed through once per slice. */ +struct G4Tap { + rad_buf h = 0; + rad_op op = 0; + int64_t K = 0; + + int declare(RadBuilder* b, Names& nm, int64_t max_tok, const char* name, rad_buf a, int64_t k) { + K = k; + h = decl_b(b, nm.f("%s.gram", name), RAD_F32, { k, k }, RAD_BUF_PERSIST); + if (!h) return RAD_E_INVAL; + op = rw(b, RAD_OP(b, "gram_accum", + RAD_PARAMS(RAD_RANGE("M", 1, max_tok), RAD_INT("n", k), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, h }, { h }); + return op ? RAD_OK : RAD_E_INVAL; + } + /* gram_accum takes a, a_scale?, h: no scale for a bf16 input. */ + void step(RadCtx* c, rad_buf a, int64_t T, bool live) const { + if (op && live) RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K)); + } +}; + struct Layer { int full = 0; /* attention */ @@ -187,6 +214,10 @@ struct Layer { rad_weight w_next = 0; /* the drafter's tap, on a layer the drafter reads (see declare) */ rad_op op_tap = 0; + /* Calibration: the attention's input (q, k and v share it), its output (this rank's columns, + * o_proj's input), the dense arm's input and its gated product (this rank's columns, down's + * input). */ + G4Tap tap_in{}, tap_o{}, tap_gu{}, tap_dn{}; }; struct Model { @@ -227,6 +258,12 @@ struct Model { int tap_layer[MAX_TAPS] = {}; rad_buf b_dfsrc = 0; + /* The calibration tap: on while `tap_live`, over layers [calib_lo, calib_hi). Written by step, + * which owns the corpus count. */ + bool calib = false, tap_live = false; + int64_t calib_lo = 0, calib_hi = 0; + long long calib_rows = 0; + Dflash1 df{}; rad_kvgroup kv_draft = 0; bool have_df = false; @@ -1223,6 +1260,42 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * ~120 us per layer on 4x R9700), so it hides behind the experts' bandwidth. No collective * rides it, so the reductions stay on lane 0. Its buffers leave the arena's sharing. */ m.arms = m.moe; + /* ---- the calibration tap. It reads each dense linear's bf16 input where trunk issues the + * linear, so a calibration runs every step whole and on one lane. The files are named after + * the weights the 31B's w4a8 container quantises (gemma4_bf16: blk.N.attn_qkv, attn_o, + * ffn_gate_up, ffn_down), which a GPTQ recipe reads with calib=DIR: the Hessians of the bf16 + * model, whose activations a quantised container's own tap would see through its quantisers. + * The routed arm is not tapped. */ + if (calib_dir()) { + m.overlap = false; + m.arms = false; + m.calib_lo = 0; + m.calib_hi = (int64_t)m.layers.size(); + if (const char* s = std::getenv("RADIANCE_G4_CALIB_LAYERS")) { + long long lo = 0, hi = 0; + int used = 0; + if (std::sscanf(s, "%lld:%lld%n", &lo, &hi, &used) != 2 || s[used] != '\0' || lo < 0 || + hi > (long long)m.layers.size() || lo >= hi) { + fprintf(stderr, "radiance: gemma4: RADIANCE_G4_CALIB_LAYERS '%s' is not lo:hi within " + "0:%zu\n", s, m.layers.size()); + return RAD_E_INVAL; + } + m.calib_lo = lo; + m.calib_hi = hi; + } + for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) { + Layer& y = m.layers[(size_t)l]; + const Kind& k = y.full ? m.kf : m.ks; + const int i = (int)l; + RAD_ARCH_TRY(y.tap_in.declare(b, nm, T, nm.f("blk.%d.attn_in", i), m.b_h, E)); + RAD_ARCH_TRY(y.tap_o.declare(b, nm, T, nm.f("blk.%d.attn_o", i), + y.full ? m.b_attf : m.b_atts, k.q())); + RAD_ARCH_TRY(y.tap_gu.declare(b, nm, T, nm.f("blk.%d.ffn_gate_up", i), m.b_h, E)); + RAD_ARCH_TRY(y.tap_dn.declare(b, nm, T, nm.f("blk.%d.ffn_down", i), m.b_act, m.n_ff)); + } + m.calib = true; + m.tap_live = true; + } if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_o)); if (m.overlap || m.arms) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ff2)); if (m.arms) @@ -1464,8 +1537,10 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) { RAD_ISSUE(c, y.op_q, brows(m.b_h, T), RAD_W(y.w_q), brows(m.b_qf, T)); RAD_ISSUE(c, y.op_k, brows(m.b_h, T), RAD_W(y.w_k), brows(m.b_kf, T)); } + y.tap_in.step(c, m.b_h, T, m.tap_live); attend(c, m, y, li, batch); RAD_ISSUE(c, y.op_o, brows(y.full ? m.b_attf : m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T)); + y.tap_o.step(c, y.full ? m.b_attf : m.b_atts, T, m.tap_live); if (y.op_ar_o) RAD_ISSUE_N(c, y.op_ar_o, T * E, brows(m.b_o, T), RAD_NONE); if (y.op_join_r) { RAD_ISSUE(c, y.op_join_r, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T), @@ -1485,9 +1560,11 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) { if (m.arms) lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK; RAD_ISSUE(c, y.op_gu, brows(m.b_h, T), RAD_W(y.w_gu), brows(m.b_gu, T)); + y.tap_gu.step(c, m.b_h, T, m.tap_live); RAD_ISSUE(c, y.op_act, bcol(m.b_gu, 0, m.n_ff, T), bcol(m.b_gu, m.n_ff, m.n_ff, T), brows(m.b_act, T)); RAD_ISSUE(c, y.op_dn, brows(m.b_act, T), RAD_W(y.w_dn), brows(m.b_ff2, T)); + y.tap_dn.step(c, m.b_act, T, m.tap_live); if (m.arms) lanes_ok = rad_lane(c, 0) == RAD_OK && lanes_ok; if (m.moe) { routed(c, m, y, T, 0, T, T); @@ -1668,6 +1745,36 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6 "the first"); } +/* The tap's rows, and its files once the corpus reached RADIANCE_CALIB_TOKENS. The input of q|k|v + * and of gate|up is whole on every rank, so rank 0 writes it, under the name of the linear that + * reads it. The column-split linears (o, down) see this rank's columns only: each rank writes its + * block as `.part`, which libquant's calib_sum places on the diagonal in rank order (the + * cross-rank products are never formed on one card). */ +static void calib_count(RadCtx* c, Model& m, int64_t T) { + m.calib_rows += T; + if (m.calib_rows < calib_target()) return; + const int rk = rad_rank(c); + bool ok = true; + for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) { + const Layer& y = m.layers[(size_t)l]; + char stem[96]; + if (rk == 0) { + std::snprintf(stem, sizeof stem, "blk.%d.attn_qkv", (int)l); + ok = calib_write(c, y.tap_in.h, y.tap_in.K, m.calib_rows, stem, 0) && ok; + std::snprintf(stem, sizeof stem, "blk.%d.ffn_gate_up", (int)l); + ok = calib_write(c, y.tap_gu.h, y.tap_gu.K, m.calib_rows, stem, 0) && ok; + } + std::snprintf(stem, sizeof stem, "blk.%d.attn_o.part", (int)l); + ok = calib_write(c, y.tap_o.h, y.tap_o.K, m.calib_rows, stem, 0) && ok; + std::snprintf(stem, sizeof stem, "blk.%d.ffn_down.part", (int)l); + ok = calib_write(c, y.tap_dn.h, y.tap_dn.K, m.calib_rows, stem, 0) && ok; + } + m.tap_live = false; + std::fprintf(stderr, "radiance: gemma4: rank %d wrote the Hessians of layers %lld:%lld after " + "%lld tokens to %s%s\n", rk, (long long)m.calib_lo, (long long)m.calib_hi, + m.calib_rows, calib_dir(), ok ? "" : ", with errors"); +} + static void step(RadCtx* c, const RadBatch* batch) { const Model& m = g_model[rad_rank(c)]; if (batch->draft_pass != 0) { @@ -1695,6 +1802,7 @@ static void step(RadCtx* c, const RadBatch* batch) { const int64_t cut = split_at(m, T); if (cut > 0) trunk_overlap(c, m, batch, cut); else trunk(c, m, batch); + if (m.calib && m.tap_live) calib_count(c, g_model[rad_rank(c)], T); if (m.op_onorm) RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T)); if (batch->n_out > 0) { diff --git a/data/recipes/gemma4-31b-dense-bf16-w4a8g-df2.recipe b/data/recipes/gemma4-31b-dense-bf16-w4a8g-df2.recipe new file mode 100644 index 00000000..eee625b7 --- /dev/null +++ b/data/recipes/gemma4-31b-dense-bf16-w4a8g-df2.recipe @@ -0,0 +1,44 @@ +# gemma4-31b-dense-bf16-w4a8g-df2.recipe -- Gemma 4 31B dense (text) from Google's bf16 checkpoint +# at w4a8 with the trunk's int4 codes chosen by GPTQ, and RedHatAI's DFlash2 speculator: the +# gemma4-31b-dense-bf16-w4a8-df2.recipe container (same grid, same kernels, same size) with the +# rounding fitted to the bf16 model's own activations instead of to the nearest point. +# +# CALIB=DIR rad-convert --draft-model \ +# --recipe data/recipes/gemma4-31b-dense-bf16-w4a8g-df2.recipe \ +# --set quantization_config.quant_method=compressed-tensors -o gemma4-31b-dense-w4a8g-df2-qkv.rad +# +# DIR holds the trunk's Hessians, recorded from the bf16 checkpoint by arch/gemma4's calibration +# tap (RADIANCE_CALIB_DIR; its files carry this container's weight names): every layer's q|k|v and +# gate|up input whole, and attn_o's and ffn_down's as one block a rank (`.part`), which libquant +# places on the diagonal. The corpus is the GPTQ one in docs/GEMMA4-31B-GPTQ.md: Gemma 4's tool +# calls among chat, code, math and reasoning, rendered with the model's own template. +# +# Why: round to nearest moves the 31B's distribution where a reply is most constrained. After an +# argument string in a tool call, `sku:<|"|>MS-110`, the bf16 model closes the string (`<|"|>`, ~1.0) +# and the round-to-nearest trunk prefers `**,` (58% against 41%), so a streamed call stalls. +# +# Everything else is the -df2 recipe's: the drafter, its head and the trunk's int8 lm_head. + +blk.*.attn_qkv.weight gptq codes=i4 group=128 scale=f16 rule=search calib=$CALIB +blk.*.attn_o.weight gptq codes=i4 group=128 scale=f16 rule=search calib=$CALIB +blk.*.ffn_down.weight gptq codes=i4 group=128 scale=f16 rule=search calib=$CALIB +blk.*.ffn_gate_up.weight gptq codes=i4 group=128 scale=f16 rule=search calib=$CALIB + +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym + +# The drafter's seven linears: block fp8, read at fp8a8 against an E4M3 activation, as the block +# declares them (rad_fp8.h's DenseFP8). The convolution projections, the selector and the norms +# stay bf16, as the block reads them. +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The draft head: the trunk's tied table under the block's own name, int8 with an f16 scale per +# (row, 128 of K), which the block reads at w8a8 (rad_block_dflash2.h, head_i8). Not the 2-bit +# grid the Qwen3.8 recipes use: the selector then ranks the candidates an 8-bit head proposes. +# Drafts are verified, so this changes what is proposed, never what is accepted. +dflash.draft_head.weight rtn codes=i8 group=128 scale=f16 clamp=sym diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index ea93ce74..b61bd86a 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -1026,6 +1026,17 @@ the whole 128-row scale blocks that cover its share of the columns and an `all_g them, with `gemm_nt_q`'s `split_n` keeping every output the unsplit fc's to the bit. The recipe is `gemma4-31b-dense-bf16-w4a8-df2.recipe`. +**The 31B by GPTQ.** `arch/gemma4_bf16`'s linears read int8 activations, which the Gram tap +(`gram_accum`) does not take, so the 31B's Hessians come from this plugin serving the bf16 +checkpoint. With `RADIANCE_CALIB_DIR` set it taps each layer's dense linears, the routed arm aside: +rank 0 writes q|k|v's and gate|up's inputs whole, and each rank writes its columns of o's and +down's inputs as `.part`, all under the names `gemma4_bf16`'s container gives those weights +(`blk.N.attn_qkv`, `ffn_gate_up`, `attn_o`, `ffn_down`), so +`data/recipes/gemma4-31b-dense-bf16-w4a8g-df2.recipe` reads them as written. The prefill overlap +and the fused arms are off while it runs. `RADIANCE_G4_CALIB_LAYERS=lo:hi` takes a slice of layers: +the 31B's four taps a layer are ~364 MiB a rank at four ranks, and its 60 layers do not fit beside +the weights in one pass. docs/GEMMA4-31B-GPTQ.md has the corpus, the run and what it changes. + **The 31B's junctions at four ranks.** At two ranks every junction carries the all-reduce in front of it (`ar_rmsnorm_quant_i8`). At four it does too, in steps of up to 16 rows (decode, and a DFlash or DFlash2 verify), on libr4d's `ar_rmsnorm_quant_i8_4rank`, in a form chosen by height. Every form diff --git a/docs/GEMMA4-31B-GPTQ.md b/docs/GEMMA4-31B-GPTQ.md new file mode 100644 index 00000000..bf77ba6d --- /dev/null +++ b/docs/GEMMA4-31B-GPTQ.md @@ -0,0 +1,154 @@ +# The Gemma 4 31B at w4a8 by GPTQ + +The 31B's w4a8 container (`data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe`) rounds the trunk's +four linears to the nearest int4 on a group-128 grid. That moves the model's distribution most +where a reply is most constrained. After a string argument in a tool call, `sku:<|"|>MS-110`, the +bf16 model closes the string (`<|"|>`, probability ~1.0); the rounded trunk prefers `**,` (58% +against 41%), so a streamed call stalls inside the string and the client never sees its end. + +`gemma4-31b-dense-bf16-w4a8g-df2.recipe` makes the same container (the same grid, kernels and size) +with the int4 codes chosen by GPTQ against the bf16 model's own activations. + +## The route + +1. **The Hessians, from the bf16 checkpoint.** arch/gemma4 serves the 31B's bf16 checkpoint as it + ships, and with `RADIANCE_CALIB_DIR` set it sums the Gram of every dense linear's bf16 input over + the corpus it is fed. The files carry the names the w4a8 container gives the weights + (gemma4_bf16's `blk.N.attn_qkv`, `attn_o`, `ffn_gate_up`, `ffn_down`), so the recipe reads them + as they are. o_proj's and down's inputs are split across ranks at `--tp 4`, and each rank writes + its block (`.part`), which libquant places on the diagonal. +2. **The convert.** `CALIB=DIR rad-convert` with the recipe: libquant's `gptq` on the trunk's four + linears, everything else as the -df2 recipe makes it. libquant factors each Hessian through + OpenBLAS's LAPACK where the build finds OpenBLAS (the container image does once libopenblas-dev + is in its build stage, a separate change); without it, libquant's own single-threaded loops take + hours for each 21504-wide down projection. + +The w4a8 container's own plugin cannot record them: its linears read int8 activations, which +`gram_accum` does not take, and a quantised container's activations would come through its +quantisers. + +## The corpus + +Whole conversations, rendered with the model's own chat template (Hugging Face's +`apply_chat_template`, thinking off) as token ids, so the Hessians see the reply format the server +writes: 2.78M tokens in 4,724 conversations, each at most 8192 tokens, of which a tenth is held out +and the other 2.47M tokens (4,252 conversations) is the calibration corpus. + +| share | tokens | conversations | from | +|---|---|---|---| +| tool calls | 834K | 2,627 | glaive-function-calling-v2 (Apache-2.0): its functions as tools, its calls as `tool_calls` (the template writes them as `<\|tool_call>call:NAME{k:<\|"\|>v<\|"\|>}`), its function responses as tool turns | +| chat | 695K | 730 | UltraChat 200k (MIT) prompts with the served 31B's greedy replies (the round-to-nearest w4a8 container's) | +| code | 417K | 589 | self-oss-instruct-sc2 (ODC-BY) prompts, the 31B's replies | +| math | 417K | 493 | OpenMathInstruct-2 (CC-BY-4.0) prompts, the 31B's replies | +| reasoning | 417K | 285 | rStar-Coder (CC-BY-4.0) prompts, the 31B's replies | + +The held-out tenth (305K tokens) is never fitted to; 44.5K tokens of it are the KL mode's corpus +below. BetterBench's corpora, on which the stall was found and is measured, are in neither. + +## Running it + +```sh +# 1. The Hessians: three slices of 20 layers (60 layers' Grams, ~364 MiB a rank each at --tp 4, +# do not fit beside the bf16 weights), the corpus through prefill once per slice. +for sl in 0:20 20:40 40:60; do + RADIANCE_CALIB_DIR=/calib RADIANCE_CALIB_TOKENS=2300000 RADIANCE_G4_CALIB_LAYERS=$sl \ + radiance --model gemma-4-31B-it --tp 4 --no-prefix-cache --num-speculative-tokens 0 \ + --max-num-batched-tokens 8192 --max-num-seqs 8 --max-model-len 10240 --kv-cache-dtype bf16 + # ...feed the corpus at max_tokens 1 until every rank prints + # radiance: gemma4: rank N wrote the Hessians of layers lo:hi after ... tokens to /calib +done + +# 2. The container. +CALIB=/calib rad-convert gemma-4-31B-it --draft-model gemma-4-31B-it-speculator.dflash2 \ + --recipe data/recipes/gemma4-31b-dense-bf16-w4a8g-df2.recipe \ + --set quantization_config.quant_method=compressed-tensors -o gemma4-31b-dense-w4a8g-df2-qkv.rad +``` + +On four R9700s each slice took about 25 minutes, the corpus through prefill at ~1,500 tokens a +second with the taps live, and the three wrote 45 GB of Grams. The convert took 75 minutes on a +48-thread EPYC. + +## Measuring it + +- **KL against the bf16 model.** The engine's KL mode: the bf16 checkpoint (arch/gemma4) records its + full distribution at every position of the held-out 44.5K tokens, and each container is scored + against it with the same flags (`--tp 4`, bf16 KV). That reference is Hugging Face's: on 41 of + its documents (21,407 positions), Transformers' bf16 31B is a mean 0.0195 nats from it (median + 0.00001), and at each container's 25 worst positions the two agree. +- **Where it counts: the model's turns.** At system and user positions, text the model never + writes, the bf16 model's own guesses are untrained and often odd (` same` at 1.000 after + `<|tool>declaration`, `---` at 0.997 inside a user's problem statement). Any quantisation moves + them, so they carry most of the mean: of RTN's and Q8's 50 worst positions, 46 are system or + user positions, each a confident bf16 guess that both implementations make. The tables give every + position and the model's own turns apart. + +## Results + +The containers are the same size (24.9 GB) on the same kernels, so speed does not move; what +moves is how close each is to the bf16 model. + +**The stall.** The next token after `sku:<|"|>MS-110` in BetterBench's order request, and +BetterBench's two order requests (a single call, and a round trip) each streamed 20 times, sampled +as BetterBench sends them, `--tp 2`, thinking off: + +| | `<|"|>` (the string closes) | `**,` | single calls that stalled | round trips that stalled | +|---|---|---|---|---| +| bf16 (Hugging Face) | ~1.0 | | | | +| RTN (`-df2-qkv`) | 41% | 58% | 10 of 20 | 1 of 20 | +| **GPTQ** | **99.8%** | 0.2% | **0 of 20** | **0 of 20** | + +**KL against the bf16 model**, the 44.5K held-out positions (Q8 is the w8a8 container, 38.2 GB): + +**every position** (44456 positions) + +| | mean KL | median | p99 | over 1 nat | top-1 | +|---|---|---|---|---|---| +| RTN | 0.988 | 0.0039 | 14.81 | 16.7% | 81.9% | +| GPTQ | 0.659 | 0.0020 | 11.15 | 12.8% | 84.5% | +| Q8 | 0.620 | 0.0014 | 12.08 | 11.7% | 85.6% | + +**the model's turns** (31975 positions) + +| | mean KL | median | p99 | over 1 nat | top-1 | +|---|---|---|---|---|---| +| RTN | 0.341 | 0.0003 | 7.49 | 6.7% | 90.5% | +| GPTQ | 0.251 | 0.0001 | 5.46 | 5.7% | 91.3% | +| Q8 | 0.226 | 0.0001 | 5.28 | 4.8% | 92.3% | + +**the model's turns by source** (mean KL / top-1) + +| | chat | math | oss | rstar | tool | +|---|---|---|---|---|---| +| RTN | 0.810 / 81.8% | 0.093 / 94.5% | 0.166 / 92.9% | 0.087 / 94.4% | 0.521 / 88.9% | +| GPTQ | 0.572 / 82.7% | 0.062 / 95.4% | 0.134 / 93.4% | 0.067 / 95.2% | 0.396 / 89.7% | +| Q8 | 0.536 / 84.7% | 0.046 / 95.9% | 0.130 / 94.3% | 0.043 / 95.8% | 0.356 / 90.8% | + +GPTQ closes 78% of the distance from RTN to Q8 on the model's turns and 89% over every position, on +every source; on tool-call replies the mean falls from 0.521 to 0.396. + +**The drafter** (DFlash2, block 8), specbench at 8 users, thinking off, tokens a step: + +| | HumanEval | math | qa | question | rag | summarization | translation | all | +|---|---|---|---|---|---|---|---|---| +| RTN | 5.97 | 6.16 | 2.91 | 3.44 | 4.40 | 3.21 | 4.02 | 3.96 | +| **GPTQ** | 5.98 | 6.19 | 3.25 | 3.56 | 4.37 | 3.21 | 4.08 | **4.11** | + +(The set's `writing` subset is byte for byte its `question` subset and is left out.) Decode speed +on BetterBench's 7 multi-turn conversations is the same: first turns 159.6 tok/s against 159.8, +3.85 tokens a step against 3.88. + +**BetterBench's `tool_call` and `multi_turn` categories at 1-16 users**, sampled at 0.7, `--tp 2`, +thinking off, the two containers served at once and the card pairs swapped for a second run (both +runs given): + +| | main's container | this one | +|---|---|---| +| multi-turn: the right tool | 15/18, 15/18 | **18/18, 18/18** | +| multi-turn: a turn after the tool's result | 16/21, 17/21 | **18/18, 18/18** | +| tool calls: a valid call | 16/17, 15/17 | **17/17, 17/17** | +| tool calls: the right tool | 16/17, 15/17 | **17/17, 17/17** | +| weighted decode, tok/s | 176.7, 175.0 | 183.8, 172.1 | +| aggregate at 1 / 2 / 4 / 8 / 16 users, tok/s | 116 / 174 / 252 / 253 / 308, 113 / 175 / 240 / 261 / 314 | 111 / 169 / 240 / 260 / 309, 115 / 168 / 235 / 244 / 299 | + +Throughput is level within the runs' noise (about 3%; the sessions differ too, since the calls that +now succeed lead to other turns). diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 1b86aa92..93282f40 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -3488,6 +3488,7 @@ The four slots are what the amdgpu kernel driver leaves to user queues. It keeps | `RADIANCE_CALIB_DIR` | where an engine run writes calibration data for a recipe's `gptq calib=DIR` | | `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) | | `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) | +| `RADIANCE_G4_CALIB_LAYERS` | `lo:hi`: the same for `arch/gemma4`'s tap, which takes the Gemma 4 31B's Grams from its bf16 checkpoint (docs/GEMMA4-31B-GPTQ.md) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_AQL_STAMP`, `RADIANCE_AQL_STAMP_OUT` | `N`: every dispatch of one recorded pass in N on card 0 gets a completion signal of its own, which carries its start and end; the barrier bits and chains stay as unstamped, unlike `--profile-ops`, which plays no recorded pass. One CSV line a dispatch (pass, record, queue, kernel, whether it waited for the one before, whether it was chained, start and end in ns) is appended to `RADIANCE_AQL_STAMP_OUT` (default `/tmp/radiance-stamps-.csv`) once the card is done with it; `scripts/stampgaps.py` reads it per kind of pass (idle share, gaps before ordered starts, kernels by time). AQL backend only | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (ยง4.5) | diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 91c97a2e..f28a146d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -272,8 +272,8 @@ endif() # the host backend; convert_test runs rad-convert on the same checkpoints. Both start the built # binaries as children, so they depend on them and on every plugin the checkpoints select # (llama_fp8 for convert_test's --set of an fp8 quantization_config). -set(RAD_E2E_DEPS radiance rad-convert libref libquant qwen35_bf16 lfm2_bf16 gemma4 llama_dense_fp8 - llama_fp8 qwenimage21) +set(RAD_E2E_DEPS radiance rad-convert libref libquant qwen35_bf16 lfm2_bf16 gemma4 gemma4_bf16 + llama_dense_fp8 llama_fp8 qwenimage21) if(TARGET libavx) list(APPEND RAD_E2E_DEPS libavx) endif() @@ -281,7 +281,7 @@ foreach(t engine_e2e_test convert_test) if(TARGET ${t}) target_compile_definitions(${t} PRIVATE RAD_E2E_SERVER="$" RAD_E2E_CONVERT="$" - RAD_E2E_HOME="${RAD_PLUGIN_OUT}") + RAD_E2E_HOME="${RAD_PLUGIN_OUT}" RAD_E2E_RECIPES="${CMAKE_SOURCE_DIR}/data/recipes") add_dependencies(${t} ${RAD_E2E_DEPS}) endif() endforeach() diff --git a/tests/engine_e2e_test.cpp b/tests/engine_e2e_test.cpp index 7435ccfb..4098da71 100644 --- a/tests/engine_e2e_test.cpp +++ b/tests/engine_e2e_test.cpp @@ -1170,6 +1170,89 @@ TEST(gemma4_chunking_and_batching_change_no_logit) { { "--max-num-batched-tokens", "512", "--max-num-seqs", "4" }); } +/* GPTQ for the Gemma 4 31B's w4a8 container, end to end on the tiny Gemma 4 (shaped like the 31B): + * arch/gemma4's calibration tap records the trunk's Hessians from the bf16 checkpoint at --tp 2, + * where o_proj's and down's inputs are split and each rank writes its block; rad-convert makes the + * container with the two shipped recipes, round to nearest and GPTQ; and on documents the Hessians + * never saw, the GPTQ one is more than three times closer to the bf16 model (5.8 times here). A + * Hessian under another name or of another width is refused, and the weight rounds to nearest, + * said on stderr. With the ranks' blocks swapped, the codes fit the wrong inputs and GPTQ is only + * 2.2 times closer. */ +TEST(gemma4_s_calibration_tap_gives_gptq_a_container_closer_to_bf16_than_rounding) { + REQUIRE(world().ok); + World& w = world(); + const tiny::Gemma4 s; + tiny::TempDir d("e2e_g4calib"); + const std::string grams = d / "grams"; + REQUIRE(::mkdir(grams.c_str(), 0755) == 0); + const Ran tap = radiance(w.gemma4, { "--tp", "2", "--kld-record", d / "tap", "--kld-corpus", + w.corpus, "--max-num-batched-tokens", "512", + "--max-num-seqs", "1" }, + { "RADIANCE_HOST_DEVICES=2", "RADIANCE_CALIB_DIR=" + grams, + "RADIANCE_CALIB_TOKENS=1000" }); + if (tap.status != 0) fprintf(stderr, " the tap exited %d:\n%s\n", tap.status, tail(tap.log).c_str()); + REQUIRE_EQ(tap.status, 0); + /* Rank 0 writes q|k|v's and gate|up's inputs whole; each rank its half of o_proj's (the heads) + * and of down's (the FFN). A global layer's heads are wider. */ + auto expect = [&](int rank, const std::string& what, int64_t k) { + const std::string f = grams + "/gram.r" + std::to_string(rank) + "." + what + ".bin"; + std::error_code ec; + const auto n = std::filesystem::file_size(f, ec); + if (ec || (int64_t)n != 32 + k * k * 4) + fprintf(stderr, " %s: %s, expected %lld bytes\n", f.c_str(), + ec ? "missing" : std::to_string(n).c_str(), (long long)(32 + k * k * 4)); + CHECK(!ec && (int64_t)n == 32 + k * k * 4); + }; + for (int64_t l = 0; l < s.layers; ++l) { + const std::string b = "blk." + std::to_string(l) + "."; + const int64_t hd = (l + 1) % s.interval == 0 ? s.global_head_dim : s.head_dim; + expect(0, b + "attn_qkv", s.hidden); + expect(0, b + "ffn_gate_up", s.hidden); + for (int rank : { 0, 1 }) { + expect(rank, b + "attn_o.part", s.heads * hd / 2); + expect(rank, b + "ffn_down.part", s.ffn / 2); + } + } + + auto convert = [&](const char* recipe, const std::string& out, std::string* log) { + const int st = tiny::run({ RAD_E2E_CONVERT, w.gemma4, "-o", out, "--recipe", + std::string(RAD_E2E_RECIPES "/") + recipe, "--set", + "quantization_config.quant_method=compressed-tensors", + "--kernels", "libref" }, + engine_env({ "CALIB=" + grams }), log); + if (st != 0) fprintf(stderr, " rad-convert exited %d:\n%s\n", st, tail(*log).c_str()); + return st; + }; + std::string rlog, glog; + REQUIRE_EQ(convert("gemma4-31b-dense-bf16-w4a8-df2.recipe", d / "rtn.rad", &rlog), 0); + REQUIRE_EQ(convert("gemma4-31b-dense-bf16-w4a8g-df2.recipe", d / "gptq.rad", &glog), 0); + /* Every trunk linear of every layer fitted to its Hessian, none rounded to nearest. */ + size_t fitted = 0; + for (size_t at = glog.find("GPTQ quantises"); at != std::string::npos; + at = glog.find("GPTQ quantises", at + 1)) + ++fitted; + CHECK_EQ(fitted, (size_t)(4 * s.layers)); + CHECK(glog.find("rounding it to nearest") == std::string::npos); + + std::string ref_log; + const std::string ref = w.reference(w.gemma4, w.corpus_short, &ref_log); + REQUIRE(!ref.empty()); + auto kl = [&](const std::string& rad) { + tiny::TempDir o("e2e_g4calib_kld"); + const Ran r = radiance(rad, { "--kld-ref", ref, "--kld-out", o / "kld.json", + "--max-num-batched-tokens", "512", "--max-num-seqs", "1" }); + if (r.status != 0) fprintf(stderr, " child exited %d:\n%s\n", r.status, tail(r.log).c_str()); + const json rep = json::parse(tiny::read_text(o / "kld.json"), nullptr, false); + return rep.is_object() && rep.contains("all") ? rep["all"]["kld"]["mean"].get() + : -1.0; + }; + const double rtn = kl(d / "rtn.rad"), gptq = kl(d / "gptq.rad"); + fprintf(stderr, " mean KL against the bf16 model: round to nearest %.4g, GPTQ %.4g\n", rtn, + gptq); + REQUIRE(rtn > 0.0 && gptq > 0.0); + CHECK(gptq * 3.0 < rtn); +} + /* A container rad-convert made block fp8 (llama_dense_fp8): the fp8 activation quantisers and * GEMMs are per row too, so the invariants hold through them. */ TEST(llama_fp8_container_chunking_and_batching_change_no_logit) {