Compare commits

...
843 Commits
Author SHA1 Message Date
Deadcode ddcb9c69bb radiance 2.0.0
Radiance becomes a multi-model engine: one process serves several models behind one port, loads
each when a request names it, parks it in host memory or restores it from its container, and
shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the
command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP).

Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an
int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block
FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such
weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5,
Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B,
the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0
serves all of them.

Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new
Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill
reworked, and a reworked adaptive draft window.

Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its
configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool
in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server,
each accelerator's memory by model, model states over time.

Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by
AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests
keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410);
eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d
large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi
(#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon
(#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and
multi-model serving as asked for in #367 and #109.

Plugin ABI 39: out-of-tree plugins need to be rebuilt.

Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
2026-11-14 22:32:28 +01:00
StillDeadcode b4c04b6042 Delete .woodpecker.yml 2026-11-12 09:49:23 +01:00
StillDeadcode f0f764d6f5 Delete STRIX_HALOD_RADIANCE.md 2026-11-12 09:48:32 +01:00
KeziandClaude Opus 5.5 60bcc30e5e libr4d: decode tile arms for the int4/int5 x int8 GEMM
gemm_w4a8i8_tiled / gemm_w5a8i8_tiled ran one 256 x 64 tile, built for
2048-row prefill chunks. At decode row counts its time is the weight's
trip through the block and is flat in M (N=5120 K=17408: 272 us at
M=32, 284 at M=256): a 128-row step computes half padding, and N/64
blocks (80 at N=5120) leave most of an R9700 idle.

The kernel is now templated on its tile (TM x TN fragments a wave,
WM x WN waves a block), with the body unchanged, and the rows gain one
tunable axis, `arm`: 0 is the prefill tile (the old constants, so an
untuned install runs the same kernel), 1-8 are 128-, 64- and 32-row
tiles. tools/opshapes.cpp describes the int8-activation operands so
rad-tune can walk the axis, and r4d_selftest checks every arm against
the host reference for int4 and int5, with ragged M and a partitioned
weight; --perfwpa takes R4D_PERF_ARM.

Tuned on an R9700 at the trunk shapes of Qwen3.8-27B ParoQuant int5
(rad-tune, us, arm 0 -> the tuned arm):

  shape             M=32         M=64         M=128
  N=16384 K=5120    258 -> 72    229 -> 97    233 -> 151
  N=5120  K=6144    101 -> 38    101 -> 42    101 -> 62
  N=34816 K=5120    497 -> 217   494 -> 234   504 -> 309
  N=5120  K=17408   273 -> 89    275 -> 103   277 -> 168
  N=12288 K=5120    167 -> 52    167 -> 72    168 -> 112
  N=1024  K=5120     36 -> 21     36 -> 22     37 -> 24

The prefill band (M=2048) keeps arm 0. Which rows reach this kernel is
unchanged: the qwen35 plugin still hands the rotated int4/int5 linears
to it above 64 rows, so the M=32/64 columns only bound what a lower
handover could gain.

The int4 rows share the kernel and gain alike (int4 x int8 at M=128,
arm 0 -> best: N=5120 K=17408 267 -> 150 us, N=34816 K=5120 444 -> 248,
N=16384 K=5120 211 -> 118, N=12288 K=5120 160 -> 91).

End to end, Qwen3.8-27B ParoQuant int5 + DFlash2 on one R9700 (k6_v4
cache, f16 state, depth 3, 32 sequences of ~3k shared + ~2.5k unique
prompt, 3000 tokens out, so 128-row verify steps), against origin/main
on the same boot and tune cache: mean decode step 111.0 -> 93.8 ms,
decode 467 -> 614 tok/s, wall 345 -> 418, no preemptions. Decode at up
to 64 rows (one to eight sequences at depth 7) and prefill (arm 0) run
the same kernels as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019BxxGmKGSAyx2h88G3sEGp
2026-11-11 22:41:02 +01:00
baKon 7da9ccf38b scripts: expert_stats_report.py, what a --expert-stats file says per layer
--expert-stats (merged) writes per-layer expert selection counts. Reading
them one number at a time hides the thing that decides where bits go: a
layer's total is the same at every layer, because top-k routing spends
the same number of selections whatever it picks, so the totals rank
nothing. What differs is the concentration inside a layer and whether
decode and prefill disagree about which experts matter.

Prints per routed layer the top-5/10/20% share, the Gini coefficient, the
experts never selected, and decode against prefill (each one's top-20%
share, the share of decode landing on prefill's top-20%, Jaccard and TVD),
then a skew verdict. The self-check line compares each layer's selections
with its observed tokens x top_k, exact unless the drain lost histograms.

No argument about which layer deserves more bits is made here; the report
is the evidence a person (or a search) spends them against.
2026-11-11 22:36:27 +01:00
behrooz f3e4d11872 libr4d: gqa 7 at head_dim 128
Nanbeige4.3-33B is 56 query heads over 8 KV heads at head_dim 128: seven queries a KV head, the
same ratio at one rank and at two. The gqa-8 unit cannot express it -- its decode body holds 64
rows of q_len * gqa, and 64 is not a multiple of 7 -- so instantiate the shared body at 21
warps: 336 rows, the same 48 query positions a block as gqa 8, and a 63-row decode cap (nine
query positions). Four rows: prefill and decode over bf16 and fp8-e4m3 KV.

The gqa-8 defaults stay as they were. G8_MAX_DECODE_ROWS, G8_P_NWARPS and G8_P_TILE become
#ifndef guards the including unit can win; nothing changes for gqa 8, which is the only other
unit including this file today. The rows state the ratio and both bounds, so a verify wider than
nine query positions takes the prefill kernel.

Without this no checkpoint with that geometry serves at all: declare names no row for it, and the
server stops in startup with nothing selected for attn_paged.

Tested against the model's own releases, which need no change to the engine. llama.cpp 0.9.0-dev
on the same two Radeon AI PRO R9700 measures 1192 tok/s prefill and 23.1 tok/s decode:

  official FP8,  TP=2   34 GiB   4014 tok/s prefill   33.3 tok/s decode
  official INT4, TP=2   20 GiB   3677 tok/s prefill   53.2 tok/s decode
  official INT4, TP=1   20 GiB   2355 tok/s prefill   29.6 tok/s decode

On the FP8 release (compressed-tensors FP8_BLOCK, imported as it ships), 17 * 23 -> 391, 9.11
against 9.8 -> 9.8, 100 - 9 -> 91, every one ending on eos, matching llama.cpp.

The INT4 release does not import as it stands: it carries u4*bf16[1x32]-u4[1x32] while these
linears read u4*f16[1x128]-u4[1x128], so a recipe re-blocks it onto the served grid, which
measures 9.5e-02 relative Frobenius (both grids are four bits, so the bytes are the same and only
the scales move). The answers stay right at that error, and moving about half the bytes a token
it decodes faster on the coarser codes than fp8 does. At 20 GiB it also fits one card.

A Q5_K_M GGUF of this model is no use as a way in: it wants an arch plugin and a conversion of
values that are already quantised, and even then the same questions come out 7 * 3, 9.1 against
9.1 and 10 - 9. The two releases above are the way in; nothing here depends on the GGUF.

Also: the gqa 7 rows against libref on the real 33B weights, 216/216 cases, and rad-kbench -m
with every fusion byte-identical (worst rel-L2 2.08e-3).
2026-11-11 22:32:57 +01:00
neuromanMD c6ef279a12 libr3d: branch-free, bit-identical e4m3_to_f32
The old decode looped over a subnormal's shift, so every fp8 staging loop diverged on gfx11. Normals
re-bias the exponent (+120), a subnormal m is exactly m * 2^-9, S1111111 is the NaN: bit-identical on all
256 codes (the old form is kept as e4m3_to_f32_ref for the check). W7900: the fp8-KV prefill attention
tile 71.6 -> 67.3 ms at 30K keys, output unchanged.
2026-11-11 22:31:33 +01:00
neuromanMD aafec91773 libr3d: mxfp4a8 -- do not scan a VRAM e8 plane from the host
e8_scan_once used hipHostGetDevicePointer to decide whether the host can read the e8 plane. It succeeds
for device memory on a large-BAR discrete GPU, so the host byte-scanned VRAM over PCIe (~12 MB/s measured
on a Radeon Pro W7900: 8 s for a 34816 x 5120 plane), and the 16-entry cache was smaller than a DFlash2
drafter's ~36 MXFP4 planes, so every issued pass rescanned most of them -- 70-120 s first requests and
~1 tok/s decode at long context. Scan only host memory (hipPointerGetAttributes), unbounded seen-set; the
kernel's e8 guard already gives reserved values the scale zero in device planes.
2026-11-11 16:53:54 +01:00
Code000 451b136874 tests: the preemption cases pin --prefill-interleave 0
The served default --prefill-interleave auto:1 (previous commit) follows measured step times, so the
four sequences of preemption_by_recompute_continues_each_stream_exactly sometimes never overlapped
enough to preempt and the test's CHECK(n > 0) failed in about half the runs under a loaded host
(plain main: 6/6 pass). The cases are sized for the fixed schedule they were written against;
small_pool_args() now pins it. Nothing they check is loosened: the streams must still match and
preemption still happen. With the flag: 6/6 alone and 3/3 beside 40 busy threads, and the case
takes 3 s again instead of 5-12 s.
2026-11-05 20:37:24 +01:00
Code000 a58304632a scheduler: --prefill-interleave defaults to auto:1 where nothing pins the schedule
Cause: with --prefill-interleave 0 every step carries a chunk while a prompt prefills, so a
sequence already decoding gets one token group per chunk step. On Qwen3.8-Flash-Next fp8 (TP2,
MTP 3 drafts) with 8 sessions decoding while 64K-token prompts prefill, that is 12.3 tokens/s a
session against ~83 alone; with 4 such prompts at once, 5.4.

Change: not given, engine bring-up now serves --prefill-interleave auto:1: after a prefill chunk
that ran beside decoding sequences, decode-only steps follow for as long as the chunk step took.
--deterministic keeps 0 (a schedule that follows timing is not reproducible), as do KL mode and
generators (nothing decodes beside a prefill there); an explicit --prefill-interleave N|auto[:SHARE]
wins. Startup names the decision with its reason. The Config default stays 0, so a Scheduler built
directly (tests) keeps today's schedule; Config::prefill_interleave_set records the flag.

Evidence (decode tokens/s a decoding session / aggregate prefill tokens/s / TTFT), 8 sessions
decoding beside 64K prompts:
  --prefill-interleave 0       12.3 / 3,664 / 17.3 s
  auto (0.25)                  23   / 3,181 / 20 s
  auto:1                       40.9 / 1,823 / 35.5 s
  auto:2                       50   / 1,166 / 56 s
with 4 concurrent 64K prefills: 0 5.4 / 2,934 / 64 s; auto 14.8 / 2,545 / 74 s; auto:1 33 / 1,395 /
137 s. auto:1 roughly triples a decoding session's rate for twice the prompt's time to first token.
BetterBench quick (short prompts, concurrency 1/2/4/8) shows no reliable difference between 0 and
auto: a short prompt is one chunk, after which nothing is held. config_test: the flag records that
it was given.
2026-11-05 20:20:13 +01:00
Code000 6e134fc15f sched_test: the burst simulation starts with sequences decoding, and takes auto:SHARE
Cause: the device measurements of --prefill-interleave were taken with sessions already decoding
when the long prompts arrive (8 decoders beside 64K prompts); the simulation only had the burst's
own prompts, which decode after their first token, and could not set auto's share.

Change: SIM_DECODERS sequences of 64-token prompts (SIM_DEC_OUT tokens each, default 4096) decode
for 16 steps before the burst arrives and count as decoders while it prefills; the run ends with
the burst's last prompt. SIM_SHARE is auto's share (SIM_IL=-1 SIM_SHARE=1 is auto:1). The summary
adds the decoders, the steps that carried a chunk per checkpoint interval prefilled, and prints
the interleave as given (N or auto:SHARE).

Evidence: RAD_SCHED_SIM=1 SIM_N=1 SIM_LEN=65536 SIM_DECODERS=8 SIM_SEQS=16, SIM_IL 0 / auto /
auto:1 / auto:2: TTFT 17 / 20 / 33 / 51 s, decode while the prompt waits 9.7 / 17.0 / 37.0 / 47.1
tokens/s a sequence, against the device's 17.3 / 20 / 35.5 / 56 s and 12.3 / 23 / 40.9 / 50
(Qwen3.8-Flash-Next fp8, TP2, MTP 3). SIM_N=4: TTFT max 56 / 67 / 109 s at 0 / auto / auto:1,
decode 6.7 / 15.6 / 34.5, against the device's 64 / 74 / 137 s and 5.4 / 14.8 / 33.
2026-11-05 20:20:13 +01:00
Code000 c00b882b96 scheduler: --prefill-interleave auto:SHARE sets the decode-only share of a chunk step's time
auto gave decode-only steps a fixed quarter of a chunk step's time. On the device (8 decoding
sessions beside 64K prefills, MTP on) that left decode at 23 tokens/s a session against 83 alone,
with 0.45 s gaps: two or three decode steps of ~40 ms per 0.45 s chunk. auto:SHARE makes the share a
choice (0 < SHARE <= 4); auto stays 0.25. The cap on decode-only steps rises from 16 to 64 so a
larger share is not cut off. config_test parses it, sched_test checks auto:1.
2026-11-05 20:20:13 +01:00
Code000 5a8c5533d1 sched_test: an opt-in timed simulation of a burst of long prompts
Cause: scheduling policy for many long prompts arriving at once (how chunks share steps,
admission, decode rows beside chunks, interleaving) was judged on the device only, where a
run of 32 x 128K prompts takes 40 minutes and the device is shared.

Change: sim_burst_of_long_prompts drives the real Scheduler through such a burst (prompts,
decode with three drafts a step, the stager floor, --prefix-resume exact) and times each
step with a cost model whose defaults are fitted to Flash-Next at TP2 (a lone prefill and
decode alone). It checks nothing and returns at once unless RAD_SCHED_SIM is set; the
workload, the flags and the model's terms come from SIM_* variables (see the comment).

Evidence (defaults, 128K prompts, 512 tokens out): the schedule keeps ~1984-2048 prefill
tokens in nearly every step at 4, 16 and 32 prompts (two prompts share a step at 1024 each
until the first decodes, then a chunk of 2048 less the decode rows with the next prompt
filling the rest), so the model predicts ~5.1K tokens/s aggregate at every burst size:
TTFT p95 100 / 412 / 814 s at 4 / 16 / 32 prompts against the device's 158 / 966 / 2456 s.
The gap grows with the burst size, so it is the device's cost of the steps a burst runs
(two-sequence and mixed steps), not the number of tokens the scheduler plans per step.
2026-11-05 20:20:13 +01:00
Code000 f87d03d304 scheduler: --prefill-interleave auto sizes the decode-only steps from measured step times
Cause: while prompts prefill, a sequence that is already decoding gets one token group per
step that carries a chunk. On Qwen3.8-Flash-Next at TP2 such a step takes a 2048-token
chunk's time (~0.4 s, more on the device under load), so decoders crawl at a few tokens/s
until the queue of prompts drains. --prefill-interleave N inserts N decode-only steps after
each chunk, but a fixed N costs the prefill whatever N decode steps cost, which grows with
the number of decoders, and is too few where decode steps are cheap.

Change: --prefill-interleave auto (default stays 0). After a chunk that ran beside decoding
sequences with its prompt continuing, as many decode-only steps follow as fit in a quarter
of a chunk step's time at a decode step's (running means of both, fed by step_finished from
the step wall times; at most 16; 1 until a decode step has been timed; 0 where a decode step
costs more than that quarter). The prefill gives up at most a fifth of its rate however
many sequences decode. The hold mechanics (no admission while held, steps issued ahead
count, the stager not armed for a held chunk) are --prefill-interleave N's, unchanged.
Under auto which steps carry a chunk follows the device's timing; a number keeps a
reproducible schedule. A chunk's cut and every row's computation are unchanged.

Evidence: sched_test interleave_auto_* (the count from given costs, the step shapes it
produces, nothing held for a lone prefill or when decode steps are too dear); config_test
parses auto. Host simulation of the scheduler (next commit), 32 x 128K prompts sent at
once, 512 tokens each, MTP 3, step costs fitted to a lone 2048-token prefill and to decode
alone: decode of the sequences decoding while prompts wait 6.5 -> 31 tokens/s each, last
first token 826 -> 875 s (+6 %), TTFT p50 453 -> 480 s; fixed N=2 gives 18 tokens/s at
the same cost. Device numbers: the commit that makes auto:1 the served default.
2026-11-05 20:20:13 +01:00
AnimusNull f713f449c2 glm5next: the width split is for all-MXFP4 experts
The layout rule chose the width split at four ranks and up before it knew the
weights' format. MoeFP8 refuses to slice a plain bf16 expert, so a container
of bf16 experts, or of MXFP4 with protected bf16 ones, that main serves at TP4
was refused unless --weights-disk-tier was set.

Read the container's encodings first, on every rank alike, and take the width
split only when every routed expert is MXFP4. The check declares no name map,
so no pinned graph moves.
2026-11-05 14:25:05 +00:00
AnimusNull e0c386ee85 docs: GLM-5.3-Flash lays its experts out by what the deployment needs 2026-11-05 14:24:14 +00:00
AnimusNull 8ef50a7708 glm5next: experts split by width at four ranks and up, whole for the file tier
Whole experts on their rank let the routed weights live on the drive, which
a two-card host needs, but at four and eight ranks they leave the shapes the
MXFP4 kernels are tuned for: glm_prefill wants 288 experts an op and finds 72.
On 4 x R9700 that cost prefill two thirds and four-stream throughput 37%.

Keep the width split at four ranks and up, as the kernels expect, and take
whole experts at two ranks or when --weights-disk-tier needs them (ABI 37,
RadBuildCtx::expert_file_tier). The file tier's graph at eight ranks keeps
main's pin, and the route-count fix that came with expert parallelism stays.
2026-11-05 14:19:17 +00:00
AnimusNull b954585f9f moe_mxfp4: the small-M form at GLM's TP4 slices too
At TP4 the launcher fell back to the expert-major form for every decode step. The small-M form
now takes gate_up from 9 to 384 routed rows (past one token's 8, where it reads 5 % slower) and
down up to 384 at the K256 x4 tiles. perfmx --perfmx-tp 4, cold, gfx1201, output byte-identical:
gate_up 3 to 18 % faster from 2 to 48 tokens, down 37 % at one token and 4 % at 48.

Served at TP4 with --vision-tower-placement ram, BetterBench against the same tree without it:
decode 52.3 -> 55.7 tok/s, 1/2/3/4 conversations 49.8/73.5/85.6/91.1 -> 52.7/76.5/90.0/96.4,
prefill unchanged. Temp-0 replies identical, needles 8/8 at 4 x 119k.
2026-11-05 14:18:21 +00:00
AnimusNull 220cb3f12c moe_mxfp4: a pin for the small-M form, and --perfmx-tp 4 to time it at the TP4 slices
r4d_moe_mxfp4_pin_small takes the small-M form where the rule does not (any GLM slice up to
384 routed rows, at either tiling) or keeps it off. r4d_selftest --perfmx-tp 4 times GLM's TP4
slices, gate_up 1024 x 4096 and down 4096 x 512, the rule's form beside the pinned ones, and
fails if their outputs differ by a byte. The rule itself is unchanged.
2026-11-05 14:17:44 +00:00
AnimusNull be623ba1dc glm indexer: a step that takes all its blocks does not split
A prefill chunk past the row threshold split the indexer over the ranks
even when every row's history fit the selection, so it scored rows whose
selection was already decided and gathered the result. Such a step now
takes the unsplit take-all path on every rank: zeros into a plane of its
own, [max_tok, topk + 1] (the score plane holds only a run of rows where
a step may split), and a selection over the whole step, with no query
side, scorer or gathers.

Temp-0 replies byte-identical to the scoring path; 114/114 tests.
2026-11-05 14:17:07 +00:00
AnimusNull c9e34d534c glm5next_test: the indexer's tests take both paths, scored and taking all
The fixtures' sixteen- and eight-column tables reach fewer blocks than the
selection, so their steps now take all (DsaCache::takes_all). Where a test is
about the scored path, its batch carries enough history to score; the steps
that take all assert that no query side or scorer runs and that the selection
reads the fill. The pinned graph adds the fill.
2026-11-05 14:16:30 +00:00
AnimusNull 8fa226e620 glm indexer: a step whose every row takes all its blocks skips the query side
With topk or fewer live blocks a row, qsa_select takes every live block in
block order whatever the finite scores, so the query projection, its copy,
the head gates, dsa_query and dsa_score decide nothing. Such a step fills the
score columns with zeros instead; the key side still runs, so the index cache
stays current. The decision reads the host bound splits() reads, so every rank
and every recorded pass agrees. Split steps keep scoring, since their
selection's rebased bounds come off the scorer.
2026-11-05 14:15:00 +00:00
AnimusNull bd38e7eced dma lane: the room check drops a reused fence slot and keeps what it once knew read
dma_read takes the end of the last finished list from ends[k % kDmaEnds]. The lane can have
more than kDmaEnds lists behind the engine (the prefill stager and the mover queue far more
than the prefetch's three), and once a later list has taken list k's slot that value would
overstate what the engine has read, letting the host write over a part of the ring not yet
read. The slot is now used only while fewer than kDmaEnds lists are behind it.

The check also keeps the most it has known read, so a list number it can no longer use does
not send it back to a stale written-back read pointer and wedge a ring that has room.
2026-11-05 14:14:24 +00:00
AnimusNull 8c389c02e7 docs: glm5next serves an fp8 latent cache
GUIDE.md no longer says glm5next refuses --kv-cache-dtype fp8: it narrows the latent-attention
cache alone. ARCHITECTURES.md's KV group table gives kv_latent's E4M3 form and its host-tier size.
2026-11-05 14:13:48 +00:00
AnimusNull d858aa722b glm5next: --kv-cache-dtype fp8 narrows the latent attention cache to E4M3
The plugin refused fp8. It now takes bf16 or fp8 and applies it to kv_latent alone: Geom::kv_dtype
is the configured cache dtype, kv_latent is declared in it, and GlmMla's kv_store and
kv_store_streamed name it, as does every mla_attn over the latent (head form, row form and the
MTP layer's), which then resolves to the fp8kv rows. The store keeps kv_store's default descale of
1, which the attention reads, as vLLM's fp8 cache does. kv_index_tail, kv_dsa_index and the KDA
groups keep their dtypes; the indexer reads only the latent group's tables. Host-tier, streamed
and replicated sizing follow the group dtype already. Under bf16 the attention states no
kv_dtype and the graph is the one declared before.

At 4 x 262144 tokens the latent cache is 12 layers of 512 bytes a token instead of 1024.

glm5next_test: fp8 declares the latent group E4M3 and the other four unchanged, every latent store
and attention names fp8_e4m3, and bf16 (stated or default) leaves the attention without kv_dtype;
the refusal test now refuses f16.
2026-11-05 14:13:11 +00:00
AnimusNull f776ecbf2e r4d_selftest: the mla_attn fp8kv rows against libref
mla_check states kv_dtype fp8_e4m3 for an *_fp8kv row and fills the cache with E4M3 codes over most
exponents, subnormals included; libref reads the same codes. Cases per twin cover its kernel forms:
the wave row, the matrix row's pairings (union, positional, element-wise load) and the rows row's
forms (rule, pinned rows kernel, element-wise load, 32 heads a workgroup).
2026-11-05 14:12:36 +00:00
AnimusNull e494369ed9 libref, libavx mla_attn: an optional kv_dtype, the cache shaped from it
Both schemas take `kv_dtype` beside `dtype`; libref's shape gives the cache operand that dtype when
it is named, the query's otherwise. The kernels already read the cache through ldt, so an E4M3
cache is read as its codes' values. ref_test covers an E4M3 cache under a bf16 query.
2026-11-05 14:10:58 +00:00
AnimusNull 17f0eae420 r4d mla_attn: E4M3 latent cache twins of the three rows
mla_attn takes an optional `kv_dtype`; at fp8_e4m3 the cache is E4M3 as kv_store_fp8 writes it at its
default descale of 1. mla_attn_fp8kv, mla_attn_matrix_fp8kv and mla_attn_rows_fp8kv are the bf16
rows' kernels with the cache element as a template parameter: the key load decodes E4M3 to bf16
(v_cvt_pk_f32_fp8, then the high half), which is exact since every E4M3 value is a bf16, so the
tiles and all arithmetic past the load are the bf16 instance's. The twins carry the bf16 rows'
constraints plus kv_dtype fp8_e4m3 and rank above all three bf16 rows, in their order. At uint16_t
the loads are the plain loads the bf16 kernels made; their launchers still refuse any cache that
is not bf16.

r4d_emu test_mla runs every kernel form (wave, matrix and its element load, rows forms 0-3) on E4M3
codes against its bf16 instance on the decoded cache: bit-identical on all 23 form/case pairs, and
each launcher refuses the other cache dtype.
2026-11-05 14:09:13 +00:00
mici81andClaude Opus 5.5 b632c72f5d sched: an overdue preempted prefill keeps its place ahead of the queue
A preempted request waiting for its whole-recompute gate (kAdmitWait) let the admission walk ask the
next request in the queue. For an overdue one that undoes the overdue path: the room it made in this
step went to a request queued behind it. With preempted prompts published, the victim forced off for
it needs almost nothing to come back, so it was re-admitted at once and forced off again on the next
step. Under KV pressure the same victim was forced off and re-admitted 26 times in 16 s while the
overdue request waited. An overdue preempted request that is still refused now stops the walk, as a
refused fresh request already does.

2x R9700, Qwen3.8-Flash-Next TP2, production flags with the KV cache cut to 6.45 GiB a card
(--gpu-headroom-mib 3072), 16 concurrent 58.6k-token prompts with 4000-token answers:
- without publishing preempted prompts:  wall 390.6 s, mean 338.5 s, 9 preemptions, 1 forced
- publishing them:                       wall 346.4 / 344.1 s, mean 306.6 / 299.8 s, 36 / 32 preemptions, 28 / 26 forced
- publishing them, with this change:     wall 331.0 / 324.4 s, mean 289.4 / 284.0 s, 8 / 9 preemptions, 1 / 1 forced

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 14:59:28 +01:00
mici81andClaude Opus 5.5 12b7b7889b sched: an overdue preempted prefill is failed only when waiting cannot help
On an idle engine the overdue path failed a preempted prefill on any refusal. A restore waiting a step
for a deferred release is a wait, and so is a refusal behind requests this step already admitted (the
budget or a card went to them); both clear by the next step. With preempted prompts published, the
restore path is common: under KV pressure two of ten preempted requests failed with "overdue
preempted prefill could not be admitted with nothing running", the debug log showing "the restore
waits a step for 1 deferred release(s)" right before. The path now fails only when nothing was
admitted this step and the refusal is not such a wait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 14:59:28 +01:00
mici81andClaude Opus 5.5 01c7a3334a sched: a preempted request publishes its prefix; the recompute adopts it
Scheduler::preempt_back dropped everything a request had computed: unlike
close_request it published nothing, so a preempted 96.6k-token prompt was
computed again from its first token. The publish block of close_request is
now Scheduler::publish_prefix, called by both. Its blocks stay in the cache,
so a preemption that published gives eviction its rounds back (the decode
ensure loop and the overdue path) and the cache gives them back, the newest
last, before another request is preempted. preempted_can_prefill counts the
blocks the recompute adopts from the cache (pc_->lookup), so a preempted
request is not held back for room its own cached prompt already covers.

Shared KV with RADIANCE_KV_GUARANTEE=1 (nine Qwen requests preempted for
TranslateGemma's start pool): Qwen 587 -> 458 s, TranslateGemma 139 -> 80 s;
without the guarantee unchanged (340 / 58 vs 339 / 56). Test:
a_preempted_request_publishes_its_prefix; sched 187, engine_e2e and the
related suites pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 14:59:28 +01:00
Asim Siddiqui e3d65f3a7c libr3d: fix the w4a4 activation row pitch (strides are elements, not bytes)
The launcher passed a->stride[0] straight as the byte pitch, but strides are
in elements (abi/rad_types.h): an int4 row of K nibbles is K/2 bytes. The
kernel read row 2*src instead of row src (row 0 correct, every other row from
the wrong source, and past the plane for larger M). The weight side already
converts (r3d_tab_of's s0 = stride*bits/8, the kernel uses w_ld/2); the
activation now does too. The libref reference had the same bug and is fixed on
the w4a4-libref-wip branch, so the two now agree on the correct row.

Missed because r3d_selftest checks finiteness only and ref_test checks status
only on the libref sweep geometries.
2026-11-05 14:59:08 +01:00
Asim Siddiqui 28939a99df libref: fix the w4a4 activation row pitch and the dequant_w4 wq extent
Two layout bugs found in pre-PR review:

1. ref_moe_gemm_w4a4 treated A->stride[0] as a byte pitch. Strides are in
   elements (abi/rad_types.h), and an int4 row of K nibbles is K/2 bytes, so
   the reference read row 2*src instead of row src (and ran past the plane
   for M > ~4). The weight side already converts (w_ld / 2); the activation
   now does too. The kernel has the same bug (separate libr3d fix).

2. ref_dequant_w4_shape declared wq as {N*K/8} I4 elements = N*K/16 bytes,
   but the packed plane is N*K nibbles = N*K/2 bytes (the kernel and the
   reference both read N*K/8 dwords). Declared extent is now {N*K}.

Both were invisible to the harness: ref_test checks status only, and the
64-byte poison margin absorbed the over-read at sweep sizes.
2026-11-05 14:59:08 +01:00
Asim Siddiqui df4e2ea889 ref_test: sweep geometries for w4a8/w4a4 moe_gemm_q and the dequant_w4 zero-point arm
Four moe_gemm_q geometries (dtype w4a8 and w4a4, token- and sorted-order a) so the
w4a8/w4a4 reference GEMMs run against the kernels, and a dequant_w4 geometry at
K=128/group=128 with twos=0 for the zero-point decode arm.
2026-11-05 14:59:08 +01:00
Asim Siddiqui b87010c7dd libref: w4a4 reference implementation and dequant_w4 op
libref side of the w4a4 work; the libr3d kernels ship separately (submitted as PR 403).
- ref_moe_gemm_w4a4_shape; ref_moe_gemm_w4a8_shape now N_odd/K_odd-aware (ref_shapes.cpp)
- dequant_w4 schema with pDequantW4/oDequantW4 (ref_registry.cpp)
- ref_dequant_w4 zero-row guard (ref_quant.cpp)
- w4a4 reference GEMM and op declarations (ref_moe.cpp, ref_ops.h)
- dequant_w4 in kOps plus sweep geometry (tests/ref_test.cpp)
2026-11-05 14:59:08 +01:00
Asim Siddiqui 4bd9c39728 libr3d: accept a null params in sample_logprobs, per the canonical schema
The canonical sample_logprobs schema declares params optional (an absent
optional operand arrives as null data, rad_abi.h), and libr4d's kernel
already honours that (no params = every row). libr3d's launcher refused a
null params and its kernel dereferenced it unconditionally, so since the
canonical schema went optional (3b278dc) the engine refuses the whole
libr3d plugin at load: op 'sample_logprobs' has two different schemas.

Mirror libr4d: the kernel's flag test gains a null guard (no params:
every row runs), the launcher no longer refuses null, and the row's spec
marks the operand optional.
2026-11-05 21:18:00 +11:00
mici81 7f5218ee5f qwen4exp: decode, verify and draft passes are recorded, keyed by their split cap (issue #402)
pass_key() answered 0 for every draft and verify pass, and with a callback present the core neither
records such a pass nor gives its launches the keyed context bound, so with the MTP drafter nearly
every decode pass was issued op by op (1.17.0: 206 passes played and 508,236 issued unkeyed, where
1.15.1 played 492,894). Dropping the export would record them with the cores bucketed bound, which
2026-11-05 09:50:02 +01:00
Asim Siddiqui 036bd8fec0 libr3d: register the fused gdn_conv_recurrent_update row
The kernel and launcher (libhalo's, r3dh_gdn_recurrent_update.hip) have
been in the tree since 1.16.0, but no row referenced them, so the op
always landed on libavx's CPU row. Register them:

- the op's schema (12 params, 18 operands: the convolution's inputs,
  then the recurrence's minus q, k and v, which the fused kernel never
  materialises), identical to libavx's and libref's;
- the constraint set: q_len >= 1, head_k 128, head_v 128, conv width 4;
- the row at R3D_PRIO_ONLY, NOTUNE (one kernel configuration), no
  layout hooks;
- the selftest case (hand-built, as the sibling GDN rows): T=4, Hg=2,
  H=4, K=V=128, window 4, state f32; o_q and o_scale absent;
- the README row, the table count (111 rows over 72 schemas) and the
  decode-path prose.

rad-schemas over the four libs: 244 shared ops, 0 disagree (the new
schema matches the canonical registries). gfx1102 (RX 7600):
r3d_selftest 118 rows / 0 failed, the new row runs with 8 output
planes finite; ref_test 153,146 checks / 294 cases / 0 failures.
2026-11-05 09:49:06 +01:00
Asim Siddiqui 87c604370d libr3d: add 8 kernels — MoE GEMM (w4a8, w4a4, mod4), dequant_w4, row_topk_merge, ngram_ids, gemm_nt_q_bias, gemm_nt_q_short
moe_gemm_q w4a8: the 2-class MoE GEMM with bf16 weight scale and bf16
output. E4M3 activation codes, bf16 weight scale (not f32), single
16x128-block i32 wave-matrix config. The w4a8 dtype row is folded into
the existing moe_gemm_q op as a dtype variant, not a separate op.

moe_gemm_w4a4: the 2-class MoE GEMM with int4 activation codes and
int4 weight codes. i32 wave-matrix core (no E4M3 decode table),
symmetric int4 x int4 multiply-accumulate. Single fixed 16x128-block
config.

moe_gemm_q_mod4: the 4-class MoE GEMM. Experts route to class e%4
(entry e/4 within the class). Same E4M3 wave-matrix core as
moe_gemm_q_e4m3, with 8 individual R3dTab parameters (4 weight + 4
scale tables) to stay within the gfx1102 kernel parameter limit.

dequant_w4: packed int4 weight to row-major bf16. Each 32-bit word
holds 8 int4 codes; the scale is f16 in the low 16 bits, the zero
point is -(1024+zero) as f16 in the high 16 bits. One warp per 32
output elements.

row_topk_merge: top-R of gathered per-rank candidate sets. Each rank
contributes a sorted candidate list; the merge selects the top-R
global candidates by score. int32 ids are bit patterns in an f32
plane (memcpy, not cast).

ngram_ids: hashed n-gram row ids for PLE (Per-Layer Embedding).
Computes the row index for each n-gram in the sequence using a
FNV-1a hash folded into the embedding table size.

gemm_nt_q_bias: narrow fp8 GEMM (M <= 16) with per-column bf16 bias
fused into the epilogue. The bias is added to the f32 accumulator
before the single bf16 narrowing at the store. Extends
r3d_gemm_nt_q_fp8_ex with a bias parameter.

gemm_nt_q_short: narrow fp8 GEMM (M <= 16) for short-prompt decode,
unsplit K. Forces sk=1 (no K-split) in r3d_gemm_nt_q_fp8_ex. The
short-prompt path avoids the K-split overhead when K is small.

The two narrow fp8 rows carry the tGemmM16 tune matrix (sk 0/1/2/4/8/16,
wv 1/2/4/8, nt, the two E4M3 decode impls, 16-row tiles) like the other
gemm_nt_q rows, measured per card by rad-tune.

The six new ops adopt the canonical op schemas. The engine enforces
schema identity across kernel libraries: the first library to declare
an op fixes its schema, and a disagreeing plugin is refused whole at
load. libavx loads first, so the specs match the canonical registries:
- moe_gemm_q_mod4: 15 params / 13 operands (the eight weight tables at
  the RAD_OPD_WTAB role); the launcher reads a_order (token/sorted),
  requires group = 128, checks the activation's row count against the
  output, and refuses unequal class shapes (N_1..K_3 differ from N/K)
  as moe_gemm_q does with N_odd/K_odd.
- ngram_ids: 4 params / 11 operands under the canonical names; state
  required; per, W and the ids pitch derive from the operand shapes.
- row_topk_merge: 4 params (+dtype) / 3 operands.
- gemm_nt_q_short: the family's four optional params (pb1, pb2,
  split_n, w_rb) and two optional operands (a_sum, b_ref).
- gemm_nt_q_bias: a_scale required, not optional.
- dequant_w4: the dtype param, twos required, the scale operand named
  ws; the launcher refuses zero rows with RAD_E_SHAPE like every
  other op.

A kernel audit found five launcher param reads the engine can never
populate (the spec's params plus the row's tune axes are the only
sources): pb1/pb2 in the gemm_nt_q_bias launcher, splits in the decode
attention path, and nt/kb/sk in the tiled rows that tune only impl.
Each always took its default; the reads are deleted, behavior-
identical.

All 8 verified bit-exact on gfx1102 (RX 7600, box card 2).
Selftest: 117 rows clean, 0 failed. rad-schemas over libavx, libr3d,
libr4d and libref: 244 shared ops, 0 disagree.
2026-11-05 09:49:06 +01:00
mici81andClaude Opus 5.5 8ab6f2a8b3 libr4d: qsa_select launches its chained form from a site of its own
The emulator test reads the plain launch's kernel name (tests/r4d_emu/test_qsa.cpp), and one launch
choosing between the two kernels spelled the choice instead; r4d_emu_qsa and r4d_emu_qsa_sweep
failed on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:48:37 +01:00
mici81andClaude Opus 5.5 e2e9416843 qwen4exp: chained launches pay with the MTP drafter
The probe sets chain_pays, as the Gemma 4 DFlash drafter does, so the engine chains the
speculative step's launches on the AQL backend (the chained forms of the previous commit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:48:37 +01:00
mici81andClaude Opus 5.5 b0a58b5dbf libr4d: chained forms for Flash-Next's decode step, hc_read forms G, S and B3
Every kernel of Flash-Next's speculative decode step gets a chained form (r4d_chain.h), so the
step's small launches wait on their predecessor on the card instead of behind a queue barrier:
the router and the fp8 and four-bit expert GEMMs, the gated quantisers, the delta-net recurrence
and conv, the hyper-connection write and its all-reduce gather, the attention layer's indexer,
norm/rope/gate, quantiser and gqa6 decode rows, and the tiled and fused hc_read kernels. A
chained form is taken only at steps of up to 32 token rows (kR4dChainMaxRows); above that the
waiting blocks hold room a wide predecessor needs.

hc_read at one to sixteen decode rows (hc 4, n 2560, E4M3 mixing matrices, inject gains), the
shape Flash-Next calls 97 times a pass:
- form G (1..8 rows): kernel A' as (16-column tile, stream) blocks, so a block reads its W_down
  slice once for every row of the step; the slice and the norm gain load before the chain wait,
  the dots are bf16 WMMA, and the last of a tile's blocks sums the streams in ascending order.
- form S (9..16 rows): as G, but the norm's scale is applied after the dot, so N never sits in
  LDS and one block holds every row.
- kernel B3 (both forms, lr 320): the up product as WMMA over d with W_up's exact quarter
  scales, and the mix in each lane; W_up loads before the chain wait.
From 17 rows the tiled path (now chained) stays faster.

The new forms are not byte-identical to the kernels they replace: the bf16 WMMA dots sum in
another order and S scales after the dot. Against an fp64 host reference, d is as close as the
per-row kernels' at 1..7 rows and closer than the tiled path's at 8..16 (mean error 0.13-0.14 %
of the row's RMS against 0.17 %, max 1.2-1.4 % against 1.3-2.0 %). The selftest's decode-forms
case now holds d to that reference (no further from it than the two-grid form) and x to the
two-grid form within rounding up to 16 rows, and stays byte for byte above.

Flash-Next on 2x R9700, sampled at temperature 1, 25k prompt, 500 tokens, two rounds of
1/2/4/8/16 streams: MTP depth 3 174/291/458/657/851 -> 207/339/493/647/843 tok/s; with depth 5
and the adaptive window 191/331/493/661/897 -> 218/355/494/662/893.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:48:37 +01:00
keptn42 aeaf6a4580 r4d_selftest: sweep the verify-against-decode check to 2048 keys
attn_verify_bits_case ran three contexts. The sweep runs every context from 40 to 300, then the
page edges up to 2048, at 2, 3, 4, 5 and 8 verify rows, for the gqa16 (bf16 and fp8 KV) and gqa8
rows. One line a verify width; a failing context counts. It found the merge difference fixed by
the previous commit. Past 2048 keys a verify of more than 32 rows is cut differently from a decode
by design (r4d_decode_splits), so the sweep stops there.
2026-11-04 22:08:53 +01:00
keptn42 d6109d7e3e libr4d: the split-KV merge reads a causal row's own segments
The decode kernel cuts the tiles of the launch's context into segments, and the merge read all of
them for every row of a verify. A row that ends in an earlier tile than the last row therefore
merged a different number of segments than its single-row decode, and the merge's chains take the
tail differently (the last u mod 4 segments go to chain 0), so the sums associate differently. At
contexts of 16k+1 keys the two-row verify differed from its two decodes in the last bit; with
eight rows 75 of 867 contexts between 40 and 2100 did (gqa 16, bf16 KV), and the same at gqa 8 and
for the fp8 KV. Greedy text with the drafter left the text without it from such a step on.

The merge counts a row's segments from the row's own causal context. Windowed rows, non-causal
rows and tree verifies keep the launch's count, and a plain decode is its own row, so nothing but
the verify rows of causal rows changes.
2026-11-04 22:08:53 +01:00
keptn42 030a3a37b7 advance_test: StepSlot::hrow is the row of the last accepted position
The chain acceptance checks hrow = rtok + accepted; the tree acceptance checks the row of the last
node on the accepted path (rows are nodes, in order; the root when nothing is accepted), over the
same random trees and end-of-generation cuts.
2026-11-04 22:08:53 +01:00
keptn42 1a900398a3 kbench: a fixture for Nemotron-H's rows, and docs/KERNELS.md from it
data/kernels_nemotronh.rkb holds 1009 cases recorded from the 74B skeleton (host only). With
kernels.rkb the report reaches 188 of 1031 rows (134 before), among them the gqa16 attention
rows, and 5226 cases pass.
2026-11-04 22:08:53 +01:00
keptn42 6436410e63 kbench: the report check reads every plugin's table, not only lib*
The per-library header "N row(s) not reached" was matched as lib\w+. A plugin library such as
spechub has a table of its own; its rows were counted into the library above it, and the headline
sum came out six short. The pattern is \w+ now. docs/KERNELS.md lists spechub from this run.
2026-11-04 22:08:53 +01:00
keptn42 7cad854f2b libr4d: the gqa16 decode takes a verify of eight rows, so a draft step matches its single-row decodes
The h128/gqa16 decode row stopped at q_len 4 (64 query-head rows a workgroup), so LiLiCorr's
verify of 7 drafts and the anchor (q_len 8) ran the query-tiled prefill kernel while a plain decode
runs the split-KV one: no verify row was the single-row decode at its position, and greedy text
with the drafter left the text without it within a few hundred characters at one and two ranks.
The gqa16 unit raises G8_MAX_DECODE_ROWS to 128, which compiles an eight-wave arm into the gqa8
body's decode launch; gqa8 and every other unit compile as before. The rows take q_len <= 8.

Selftest: the numeric cases at q_len 8, and attn_verify_bits_case, eight verify rows against eight
single decodes bit for bit at 120, 700 and 2048 keys (gqa 16, and gqa 8 for four ranks).
docs/ARCHITECTURES.md: past 2048 keys the split law partitions a verify and a decode differently,
so a near-tie can still flip greedy text.
2026-11-04 22:08:53 +01:00
keptn42 72160a9cff nemotron-3.5-bolt-74b compose: two cards at w4a8, four at FP8
nemotron-3.5-bolt-74b-w4a8.yaml (--tp 2) and nemotron-3.5-bolt-74b-fp8.yaml (--tp 4): 8 sequences
of 65536 tokens, LiLiCorr at 7 drafts, a bf16 KV cache, as the containers were measured. The
README's model table and docs/DOCKER.md list them.
2026-11-04 22:08:53 +01:00
keptn42 882050e45a data/recipes: nemotron74-fp8.recipe and nemotron74-w4nl64-gptq.recipe
Every block linear and routed expert as block FP8; or the routed experts at w4nl64a8h (GPTQ
against $CALIB, rounded to nearest without it) and the rest block FP8. Both carry the LiLiCorr
drafter's linears when it is merged.
2026-11-04 22:08:53 +01:00
keptn42 0c4292e45b arch/nemotronh: Nemotron-3.5-Bolt-74B-A9B
NVIDIA's Nemotron-H hybrid from its bf16 checkpoint: 40 Mamba-2, 40 latent-MoE and 8 NoPE attention
blocks, the LiLiCorr drafter (7 drafts a step) and the C-RADIO tower with its projector, at one, two
or four ranks. docs/ARCHITECTURES.md describes the model. nemotronh_test: the drafter's KV heads at
two and four ranks, a speculative step at four, and the arena's sizing declares.
2026-11-04 22:08:53 +01:00
keptn42 cc46e3b714 core/mm: the Radio image family and video tubelets
Nemotron-H Omni's processor: NVIDIA's size rule for one tile, torch's antialiased bicubic on float
pixels, patches in merge-block order, and video in tubelets labelled as the reference labels them.
A picture and a video frame share one patch row, so one embedding GEMM serves both. mm_test against
golden rows.
2026-11-04 22:08:53 +01:00
keptn42 eda0e92e8e arch/common: LiLiCorr, DFlash2's backbone with a candidate correlator
Config::lili runs DFlash2's backbone with attention sinks and leaves the head to the plugin;
rad_block_lilicorr.h is the correlator over the draft rows (lili_cand, lili_attn, lili_factor,
lili_walk), conditioned on the context state at the anchor (RadBatch::anchor_rows). At four ranks
drafter_geom replicates the drafter's two KV heads as geom_from does the target's (kv_repl_ok), and
Dflash2 reads k and v at kv_off (DenseFP8::span).
2026-11-04 22:08:53 +01:00
keptn42 6f9c084ac6 arch/common: calibrate in layer ranges (RADIANCE_CALIB_LAYERS)
Nemotron-3.5-Bolt's per-expert Hessians take 169 GiB at once. RADIANCE_CALIB_LAYERS names the
layers a run taps, so several runs over disjoint ranges share one directory, and a layer's host
sums are released once written.
2026-11-04 22:08:53 +01:00
keptn42 c9c3a98894 arch/common: MoeFP8's ungated relu2 experts, a router on the hidden width, and no reduce
For a latent MoE: ungated experts, down(relu(up(x))^2), through GateQuantFP8's relu2; a router that
reads another width than the experts (Config::router_k, Wire::route); and Config::no_reduce, which
leaves the routed sum unreduced for a caller that reduces it with its shared expert.
2026-11-04 22:08:53 +01:00
keptn42 3b7ef1ed48 arch/common: AttnFP8 without positions, and with KV heads replicated above their count
rotary_dim 0 is attention without positions (NoPE): no rope is declared. Above the KV head count
the fused q | k | v takes a span per part, q this rank's heads and k and v the head at kv_off, as
gemma4's q | k | v does.
2026-11-04 22:08:53 +01:00
keptn42 b466c91b26 ops: attn_dense at head_dim 80 and grid_embed_cpe, for the C-RADIO tower
attn_dense at head_dim 80 without GQA (C-RADIO's ViT heads), and grid_embed_cpe, RADIO's cropped
position embedding: the table resampled half-pixel bilinear onto a square and cropped to the
grid, with the class and register rows ahead of each segment. libref, libavx and libr4d; ref_test,
avx_check_hand and selftest cases; docs/OPS.md.
2026-11-04 22:08:53 +01:00
keptn42 2420b2b383 ops: act_mul's relu, relu(x)^2 over one tensor
act_mul's `act` takes "relu": with one tensor in both operands it is relu(x)^2, Nemotron-H's
ungated expert activation and its vision projector's. libref, libavx and libr4d.
2026-11-04 22:08:53 +01:00
keptn42 63416510a0 ops: ssd_update and ple_conv_bias, Mamba-2's scan and convolution
ssd_update is Mamba-2's selective state update, a token at a time, with kda_update's rollback
contract: per_candidate, or the anchor form (one committed state and a scratch of per-token
records). libref, libavx and a libr4d kernel at a 128-wide state (r4d_ssd.hip, r4d_kda.hip's
register layout). ple_conv_bias is ple_conv with a per-channel bias inside the silu, Mamba-2's
conv1d, an op of its own so ple_conv's callers keep their operand list.

ref_test, avx_check_hand and selftest cases; docs/OPS.md.
2026-11-04 22:08:52 +01:00
keptn42 3b278dcec3 ops: attention sinks and LiLiCorr's correlator
For NVIDIA's LiLiCorr drafter:
- attn_paged_sink: attn_paged with a learned logit a query head beside the keys, in libref,
  libavx and libr4d (the windowed kernels at h128, gqa 8 and 16)
- sample_logprobs without params writes every row (a drafter's candidate logprobs)
- lili_cand, lili_attn, lili_factor, lili_walk: the correlator's candidates and features, its
  attention over the candidate lattice, the factor input and the greedy walk

ref_test, avx_check_hand and r4d_emu cases; docs/OPS.md.
2026-11-04 22:08:52 +01:00
keptn42 44490c859a libr4d: paged attention at head_dim 128 and gqa 16
Nemotron-H's attention layers have 32 query heads over 2 KV heads, gqa 16 at one and two ranks.
r4d_attn_paged_h128_gqa16.hip is the gqa8 body at that ratio: prefill blocks of 24 query
positions, decode q_len <= 4. Selftest cases at one rank.
2026-11-04 22:08:06 +01:00
keptn42 dccc6329a9 abi, sched: RadBatch::anchor_rows, ABI 36
A block drafter's query pass gets, for each drafting sequence, the row of its last committed
position in the context pass just run (StepSlot::hrow, written by the advance on the card).
LiLiCorr's correlator reads the context state there. Appended after bidi_used; main ships
ABI 35 and an appended field is read past the end of an older engine's copy, so the version is
36 and the layout table follows. The pass key reads the pointer.
2026-11-04 22:08:06 +01:00
keptn42 a1b7643310 core/format: read nemotron_h checkpoints
Nemotron-3.5-Bolt's config nests its language model under llm_config, which is now read as
text_config is; arrays of objects (Puzzle's block_configs) become flat keys,
block_configs.<i>.<field>; a checkpoint without num_hidden_layers counts layers_block_type; and a
drafter merged from its own checkpoint keeps its own quantisation (Checkpoint::imports_at).
2026-11-04 22:08:06 +01:00
keptn42 e6787b7bdd core/format: a stacked vector may have parts of different widths at TP > 1
Mamba-2's conv1d bias is x | B | C, 8192 | 1024 | 1024 wide. The share of a vector stacked from
parts was cut only when the parts were equally wide; the reader already lays the parts end to end,
so a vector's parts now add their widths. share_test: a stacked vector with parts of different
widths.
2026-11-04 22:08:06 +01:00
keptn42 394b8cd290 kbench: a kernel that lays out a weight table's experts is handed them laid out
A weight table reached every kernel as the tensor its planes decode to. libr4d's 4-bit grouped GEMMs
read each expert through their layout hooks (the w4 codes as R4D_DT_MOEW4, the E4M3 scales of
w4nl64a8h), so moe_gemm_w4a8 refused every case with "dtype this kernel does not serve", which
counts as a failure. Each expert is now laid out from its planes (the container's or
kf_draw_table's) and the entries are stacked one laid expert apart, while the oracle still reads
the decoded table. The container pass and the replay both do it, and a table counts as laid out
where the replay decides whether to compare exactly.

kfixture: kf_table_entry, kf_draw_entry_planes (kf_draw_table's per-expert draw, the same bytes)
and kf_lay_table. fixture_test: a table's experts are each laid out by the kernel.
2026-11-04 22:08:06 +01:00
keptn42 e0c3f971dc arch/common: DFlash2's split fc gathers its message as a range
The context pass's all_gather declared numel as a fixed crows * n_embd. crows is max_tok, so every
sizing declare (RadBuildCtx::shape_probe) changed a fixed parameter and was refused: with a
block-fp8 fc at TP > 1 no arena level was planned and nothing was lent to the expert slab. numel
is now a range with the trunk all-reduce's bound, issued at T * n_embd, as the reference reads it
(band_rows).

arch_test: the fc split's gather is the trunk's bound, as a range.
2026-11-04 22:08:06 +01:00
Deadcode 19d4e8fe0e radiance 1.17.0
IQR-V4 for Qwen3.8-27B:
- 15 recipes, data/recipes/q38-27b-iq2r-v4 .. q38-27b-iq8r-v4 (2.5 to 8 bits a weight), docs/IQR.md
  "IQR-V4". On the quantisation board's private split every entry has 2-19% less KL than its V3 twin
  of the same size (10-19% from 2.5 to 5.4 bits); IQ4R-L-V4 is 24% below the official FP8 checkpoint
  at 55% of its size, and IQ2R-L-V4 (2.8 bpw) is below the MXFP4 checkpoint. Containers with the
  DFlash2 drafter and the vision tower: huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4, served by
  deploy/compose/qwen3.8-27b-iqr-v4.yaml (IQR_V4 names the size)
- GPTQ runs in act order inside the column trellis (tcq_order=1); the head-fed projections
  (attn_output, ssm_out) take a bf16 scale a (row, 128) block from five bits up; widths from
  measured prices
- A vocabulary-weighted lm_head: four width classes of the computed trellis (output.k<B>), the
  tokens carrying the probability on the widest, decoded in one launch by logits_gemm_vocab with
  16-bit head activations; 0.62 ms at one token on a TP2 rank against the int8 head's 1.02 ms.
  tools/vhead.py and data/vhead/ build the class split from the bf16 checkpoint; libquant reads the
  head's input Hessian for every class
- At IQ6R-L and up, the int8 lm_head is GPTQ'd against its input Hessian (same bytes, median KL
  -8..-12%)
- embed_lookup_iqr takes u7/u8 tables under a zero point and the 4096-state trellis at 6 and 7 bits
- The whitepaper: radiance.stilldeadco.de/whitepapers/iqr-v4.pdf

Faster IQR kernels:
- The one-token GEMV gives each 16-row weight tile a block whose waves split K (5120 x 6144 at one
  token 42.3 -> 30.0 us), with a biased-int fold, a v_perm activation broadcast and one code stream
  a column
- A 16-token WMMA tile without block barriers serves 2 to 16 tokens (6- and 7-bit codes from one
  token): a 4-bit weight takes 0.52-0.66 of FP8's time from one token to sixteen, 1.15-1.74x V3's
  kernels from four tokens up
- The activation quantisers after the IQR gate_up (gemm_iqr_gated), the delta net's decode conv
  fold (gdn_conv_recurrent_update_had) and the attention gate (gate_had_quant_i8g) are folded into
  their producers, byte for byte the same codes: 128 fewer launches a decode step
- End to end on one R9700 (TP1, no speculation): IQ4R-S-V4 decodes one stream in 24.7 ms against
  the MXFP4 checkpoint's 25.8 at five times lower KL; IQ3R-S-V4 is faster than MXFP4 at 1 to 8
  streams. Prefill stays 8-9% behind MXFP4's 4-bit tile

Quantisation tooling:
- rescale=1 refits each row's scale to its codes after GPTQ; gptqsim measures a tensor's W16A16
  form (tcq_code=mad16); an int8 trunk's calibration Grams can be recorded from the codes its GEMMs
  read (--calib-dir, TP1)
- Fixed: the GPU trellis packs tcq_code=mad16's values two int16 a register

New models (merged):
- Spark 2.5 (spark25: bf16 and rotated-int8 IQ8R checkpoints, tensor parallelism with exact
  collectives, reasoning and tagged tool calls) with its DSpark drafter (exact attention and Markov
  walk ops), docs/SPARK25-IQ8R.md (@gostar)
- Ling-3.0-flash (bailing_hybrid: KDA, dense latent attention with mla_attn_paged, group-limited
  sigmoid routing, the clipped SwiGLU and its MTP layer as a serial drafter), its w4a8 recipes and
  compose files for four and two cards (@keptn42)
- Gemma 4 12B (gemma4_unified, served by the gemma4 plugins): its picture and audio embedders, a
  picture's placeholders read both ways on the sliding layers as the model was trained (the
  scheduler ends no prefill chunk inside such a run; RadBatch::n_bidi), windowed attention at
  head_dim 512, the assistant head as MTP drafter at one, two and four ranks, suppress_tokens from
  generation_config, bf16 and i8g compose files (@keptn42)

Merged:
- The prefill KV split sized by the live KV length rather than the model's max_ctx, recorded passes
  keyed by their split geometry, and --gpu-memory-mib, the inverse of --gpu-headroom-mib (@gostar)
- Possessive quantifiers in tokenizer patterns where the greedy reading provably matches the same
  (Ling-3.0's), and the Grafana dashboard's first screen of totals (@keptn42)
- The dashboard's history line (decode, prefill and TTFT over finished requests, kept in the
  browser, JSON export), session extremes that age and reset on a restart, card-count changes, an
  Advanced tab for the poll intervals, each request's prefill time from admission in /stats
  (prefill_s), and the page's JavaScript run by tests/js (@Memoria)
- From PR #390: the file tier reads a routed layer with its own router's counts and waits for its
  deposits; the stop-string hold-back keeps back only a tail that can still become a stop string
  (before, every delta waited up to the longest stop's length); the sampler's planes are sized by
  the step's token bound, the n-gram ban runs beside a drafter, and a top-1 row issues no candidate
  cut (@Code000)
- The n-gram reader refills its reads as they land, and a decode gather waits on the other rank's
  read of a row instead of reading it again (#369, @pokesjw)
- libr3d's GEMM structs value-initialised so the tape audit sees no padding (@RikshaDriver)

Added:
- --ngram-placement disk=DIR: the n-gram table read from its own file, DIR/ngram-<id>.bin, filled
  from the container at the first start, on a faster or separate drive (#130)

Fixed:
- input_reference's H.264 round trip runs on libopenh264, which the image carries, at a quantiser
  held at the crf (a side under 16 padded and cut back); a build with no H.264 encoder answers 501
  (#163)
- kvtier: at most 1024 session rows under one shared first block; with one shared prompt the list
  grew a row a request and prefill fell from 9k to 2.5k tok/s after 500K requests (#375)
- Speculative steps on an architecture with no pass-key callback keep their recorded passes under
  the live-KV prefill split

Plugin ABI 35:
- RadArgs::kv_used_max_h and wgp_count, RadBatch::kv_used_max_h and positions_h, the optional
  rad_arch_pass_key export and RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT; RadEncoderDecl::bidirectional
  and RadBatch's n_bidi runs. The layout fingerprint table is regenerated; out-of-tree plugins
  rebuild against 35

Thanks to @gostar, @keptn42, @Memoria, @Code000, @pokesjw and @RikshaDriver.
2026-11-04 18:56:58 +01:00
keptn42 3af8065cc6 deploy: Gemma 4 12B composes and README rows
gemma4-12b-bf16.yaml (two cards) and gemma4-12b-i8g.yaml (one card), both
with bf16 KV, MTP depth 3 and 1120 patches for pictures.
2026-11-04 07:21:07 +01:00
keptn42 a72686b7e7 sampler: read suppress_tokens
generation_config.json's suppress_tokens (Gemma 4: the end-of-image and
end-of-audio markers, ids 258883 and 258882) are never sampled. The ids
reach the sampler as SamplingParams::suppress_tokens and leave the row
the way a grammar's mask does. A container carries them already, as the
space-separated generation.suppress_tokens.
2026-11-04 07:21:07 +01:00
keptn42 c1c05e9029 gemma4_bf16: a picture longer than the window reads it with the window behind only
A run of more rows than `sliding_window` (1120 soft tokens against 1024)
is attended again with attn_paged_ahead, where the window bounds the keys
behind a row, as transformers' mask does. A shorter run keeps the
two-sided window, which is the same mask for it. Where no kernel serves
the ahead form, the two-sided one stays.
2026-11-04 07:21:07 +01:00
keptn42 a0ea6ad1ba libr4d: a non-causal window that bounds the keys behind a row only
attn_paged_ahead and attn_paged_qrow_ahead are attn_paged at causal 0
where `window` limits the keys behind a row and every later key of the
sequence is visible. The windowed kernels take it as a launch flag (h256,
1 to 8 queries per kv head). Gemma 4's sliding layers read a picture's
rows with transformers' mask, the window AND (causal OR the same
picture), which this is for a picture longer than the window. Emulator
cases for the scalar, split and WMMA kernels.
2026-11-04 07:21:07 +01:00
keptn42 eb3aa7eae7 r4d_emu: Gemma 4 picture runs read again non-causally up to the run end 2026-11-04 07:20:43 +01:00
keptn42 c6391e6ef9 gemma4_bf16: a picture's rows read both ways on the sliding layers
use_bidirectional_attention "vision" (the 12B and the 31B): each
sliding layer attends a run's rows again over the cache up to the
run's end without the causal bound, over their causal result. The
global layers stay causal, as transformers' Gemma 4 masks, KerasHub
and vLLM have it. RADIANCE_MEDIA_BIDI=0 keeps every layer causal.
2026-11-04 07:20:43 +01:00
keptn42 da7b911c64 abi, sched: placeholder runs read both ways
An encoder states that the language model reads a picture's or video
frame's placeholders both ways (RadEncoderDecl::bidirectional). The
scheduler then ends no prefill chunk inside such a run, and a trunk
pass names its runs and the keys their rows see (RadBatch::n_bidi).
Fields appended; such a pass is not recorded.
2026-11-04 07:20:43 +01:00
keptn42 81be3cb63d gemma4_bf16: the 12B's image and audio embedders
rad_block_gemma4_unified.h: LayerNorm, the dense with its bias,
LayerNorm, the column's and the row's position rows, LayerNorm (eps
1e-5), the weightless RMS norm and the projection; for audio the norm
and the projection. The position table is read as its two taps of
dimension 1, which a recipe stores (gemma4-12b-bf16, -i8g).
2026-11-04 07:20:29 +01:00
keptn42 a00e5e7094 mm: Gemma 4 12B's pictures and audio
The 12B (gemma4_unified) has no tower: its embedder takes a whole
48 x 48 pooling window as one patch, so a patch is a row (merge 1),
its values u / 255. Its audio is frames of 640 samples as they are,
one frame a token, the last zero-padded. Goldens from transformers.
2026-11-04 07:20:29 +01:00
keptn42 9782a9afb5 rad-convert: name the checkpoint tensors no declared weight reads
They are not written. A tower or head the plugin does not recognise was
left out without a word. A tensor beside one that is read (its scale)
counts as read.
2026-11-04 07:20:29 +01:00
keptn42 326443ca89 libr4d: windowed attention at head_dim 512 with 16 queries per kv head
Gemma 4 12B's full layers at one rank: 16 query heads over one kv head,
in the trunk and in its assistant head. A row pair, its constraints and
emulator cases (scalar, split decode, verify, WMMA prefill, fp8).
2026-11-04 07:20:29 +01:00
keptn42 b88d370722 gemma4_bf16: the 12B's assistant head, also at two and four ranks
The 12B's head is Gemma4UnifiedAssistantForCausalLM, the same head under
another name. It was not declared, so rad-convert left its weights out
without a word. The check that the head fits the trunk compared the
head's kv heads with a rank's times the world; the 12B's one global kv
head is replicated at two and four ranks, one on every rank, so the head
was refused. It compares with the model's count now.
2026-11-04 07:20:13 +01:00
keptn42 d4d6d6cb3e format: Gemma 4 12B (gemma4_unified) goes to the gemma4 plugins
Its text model is Gemma 4's with other sizes. The arch id was
`gemma4unified`, which no plugin claims. model_type stays in the
free-form keys.
2026-11-04 07:20:13 +01:00
Constantin 8088c9a783 test: check DSpark device usage before skipping 2026-11-03 14:35:30 -05:00
Constantin c1c8e40445 test: run DSpark differential against libr4d on device 2026-11-03 14:22:46 -05:00
Constantin cebf759a36 fix: keep one Spark prefill pass key per plugin 2026-11-03 14:10:11 -05:00
Constantin 51b08808de spark: key BF16 and IQ8R prefill tape geometry 2026-11-03 13:56:46 -05:00
Constantin c96cfc9e7b test: verify DSpark device KV rollback 2026-11-03 13:56:46 -05:00
Constantin e14463b8eb docs: describe Spark DSpark serving, not GGUF import
The graph still reads draft.* from a container that already has them. How that
container is built from XHToken's GGUF is not this change.
2026-11-03 13:56:46 -05:00
Constantin f98ccd3f56 Add a DSpark QoS harness that only reports supported evidence
Two-server probe plus tests. Missing or reset counters fail closed;
partial-acceptance, stop-sequence, and timing claims are not made.
2026-11-03 13:56:46 -05:00
Constantin 5b98ba37e8 Stop aliasing DSpark restrict kernel buffers
rmsnorm, sigmoid, and scale_rows declare __restrict__ input and output.
Give those stages separate graph buffers and check the declared graph
does not pass the same allocation to both.
2026-11-03 13:56:46 -05:00
Constantin 9ca20a1fba Use F32 draft logits for the DSpark Markov walk
Score the walk on F32 head logits, reject non-I32 anchors in libref, and
assert the real proposal path. Near-tie policy vs the reference is still
open.
2026-11-03 13:56:46 -05:00
Constantin 445bf8e0d9 Honor DSpark Markov scratch row pitches and exercise device oracles
Index Markov scratch by the padded row stride, not a packed width, and
cover the walk plus shared-anchor attention on device.
2026-11-03 13:56:46 -05:00
Constantin 340ff8781a Implement exact DSpark attention and Markov ops
Shared-anchor window attention and full-vocabulary greedy Markov as named
ops, with libref oracles. Register the anchor-window kernel constraints.
2026-11-03 13:56:45 -05:00
Constantin b43088a334 Draft with a Spark DSpark drafter
Spark's standalone DSpark is five sliding-window layers over a seven-token
block, taps on the trunk residual, sigmoid headwise gates, exact GELU, and
a rank-256 Markov head over the tied table. Own block vs MiniCPM5 DSpark.

The graph follows the pinned reference: shared-anchor window and
full-vocabulary greedy Markov walk. Tensor names are the ones the container
holds; the walk scores at the width it reads. TP>1 drafting is refused.
2026-11-03 13:56:45 -05:00
Constantin f692c3f446 spark: key BF16 and IQ8R prefill tape geometry 2026-11-03 13:53:46 -05:00
Constantin 416c231a18 Report Spark probe cleanup failures without masking outcomes 2026-11-03 13:53:27 -05:00
Constantin 95af71af3a Retain Spark score backups if rollback fails 2026-11-03 13:53:27 -05:00
Constantin 50b60078ab Protect Spark probe artifacts through promotion failures 2026-11-03 13:53:27 -05:00
Constantin acd256ba25 Stage Spark score outputs and protect inputs from overwrite 2026-11-03 13:53:27 -05:00
Constantin a4403a1a90 Harden Spark measurement identity and fresh output checks 2026-11-03 13:53:27 -05:00
Constantin 4a60c64ec5 Guard Spark reference provenance against recording input changes 2026-11-03 13:53:26 -05:00
Constantin 6295ba1d92 Bind Spark quality probes to measured artifacts
Hash architecture and quantizer inventories as well as kernels. Bind reusable references to model bytes, corpus, runtime, settings and data. Bind tail replay to scored reports and launch the verified candidate privately. Reject incomplete forced-length QoS responses. Add CPU-only positive and negative attribution tests; no GPU certification is implied.
2026-11-03 13:53:26 -05:00
Constantin 40442cc81b Record exact sparse keep12 KL provenance 2026-11-03 13:53:26 -05:00
Constantin 08c3e752f7 Document Spark IQ8R quality allocation and replay 2026-11-03 13:53:26 -05:00
Constantin cb97b1c886 Add Spark rotated-int8 inference and calibration
Serve the Spark X2.6 trunk on IQ8R's rotated int8 grid. Six projection types a layer carry
fwht128-rotated int8 weights with a bf16 scale per 128 columns; activations are quantised into
the same 128-column groups and feed the `i8a8h` rows, exact GELU runs before the down
projection's own Hadamard quantiser, and the embedding, the two norms a layer, the head's norm
and the 16-row attention gate stay as they are. The descriptor is `w8a8_fwht128`, and the
container says `quantization_config.quant_method=w8a8`, `fmt=fwht128`.

`data/recipes/spark-x26-4b-iq8r.recipe` fits those weights by GPTQ against the model's own
calibration Hessians, which the BF16 plugin writes as RADGRAM2 files under `RADIANCE_CALIB_DIR`;
each layer's f32 [K,K] accumulators are 533 MB, so `RADIANCE_SPARK_CALIB_LAYERS=lo:hi` calibrates
a slice at a time into one directory. The output head is RTN. Column-sharded inputs and their
offsets must land on whole scale groups, so a rank with an unaligned span is refused rather than
served with misaligned scales: TP 1, 2, 4 and 8 align for these shapes, TP 3 does not for the
FFN-down shard. Calibration asks for TP=1, because the off-diagonal cross-rank terms only exist
on one card.

`tests/spark25_iq8r.py` compares a deterministic quantised fixture against the Transformers
reference, top-10 probabilities included, across cached decoding; `--tp 2` checks two fake host
ranks and `--wide-tp --tp N` the group-aligned attention and FFN shards for N from 1 to 8. Run it
under a GPU-denying device cgroup, as with the BF16 fixture.

Against this checkpoint's own BF16 container, 32 held-out chat, math, code and tool-call samples
and 31,391 positions, greedy with prefix caching off: 98.60% of positions keep their top token,
mean KL 0.00408, median 6.5e-5, p99 0.0496, p99.9 0.348, worst 11.88. The tail is the honest
part -- 13 positions above one nat -- and leaving the first twelve layers in BF16 takes the worst
to 0.247 with nothing above one nat, for about 12% of prefill and 17% of decode. One R9700, zero
cached prompt tokens: 11.8k, 11.8k and 11.3k tok/s of prefill at 1.1k, 4.4k and 9.9k-token
prompts, 93.7 tok/s of decode from a short prompt and 88.9 with a 4.4k-token context. 8.29 GiB of
BF16 weights become 4.52 GiB.

That comparison is distribution agreement against BF16, not a task benchmark, and the corpus the
Grams came from is public text held disjoint from the holdout by hash; no MMLU or GSM8K-class
number is claimed here. The numbers need the prefill softmax scaling per row rather than per
wave: while a row's rounding depended on its wave-mates, the quantised container was worse off
against BF16 than its own error explains.
2026-11-03 13:53:26 -05:00
Constantin 5d6de60318 spark: key BF16 prefill tape geometry 2026-11-03 19:08:58 +01:00
Constantin f697660b8b Document Spark TP collective requirements 2026-11-03 19:08:58 +01:00
Constantin 213403b458 Fail Spark TP declaration without exact collectives 2026-11-03 19:08:58 +01:00
Constantin a5b2f84450 Round Spark TP projections before the FP32 residual add
Reduce attention-output and FFN-down shards in exact BF16, then widen the merged result for the FP32 residual. Keep the disjoint embedding reduction unchanged. Declare the reductions before the casts as well as issuing them in that order so buffer liveness follows the fixed graph. Clarify that TP can still differ from one card through sharded dot-product rounding.
2026-11-03 19:08:58 +01:00
Constantin 8cb2c0a841 Add regression for Spark TP projection rounding
Capture the BF16 midpoint case and require each projection reduction to round before widening into the FP32 residual. This regression precedes the production fix and is expected to fail on the current graph.
2026-11-03 19:08:58 +01:00
Constantin 4204fa4da7 Let the shipped-arch registry expect spark25
The loader test fixes the (architecture id, quantisation descriptor) pairs a shipped plugin may
claim; the Spark plugin was not in it, so the set comparison failed once every architecture plugin
was built.
2026-11-03 19:08:58 +01:00
Constantin 1c96558970 Shard Spark across ranks and reduce the f32 residual
Attention takes whole GQA groups, so a world that does not divide the KV head count still gets a
clean cut; above it the KV heads are replicated and a group splits between the ranks sharing its
KV head. Gate/up, down and the tied vocabulary take matching spans, and every query head, FFN
channel and vocabulary row belongs to exactly one rank at every world from 1 to 8.

The projection outputs are partial sums, so each block widens to f32 and issues an exact f32
all_reduce before the residual add, which keeps the single-card accumulation order.

tests/spark25_reference.py --tp N holds the sharded graph against the HF reference on N fake host
devices; the tiny fixture has 8 heads over 4 KV heads and 3584 vocabulary rows so worlds 1-8 all
get a nonempty shard.
2026-11-03 19:08:58 +01:00
Constantin 48407fb52d Cover Spark configuration refusals and CPU isolation caveat 2026-11-03 19:08:58 +01:00
Constantin 125854df79 Document Spark support and add reference differential 2026-11-03 19:08:58 +01:00
Constantin 1483a1ae17 Support Spark reasoning and tagged tool calls 2026-11-03 19:08:58 +01:00
Constantin e56d948889 Add BF16 Spark 2.5 checkpoint and decoder 2026-11-03 19:08:58 +01:00
keptn42 a0f9eb29c0 deploy/compose: Ling-3.0-flash-Sante w4a8 on two cards 2026-11-03 19:07:34 +01:00
keptn42 ab736ca3e3 libr4d: mla_attn_paged splits by heads alone, so a verify row matches its single-row decode
The history split was sized by rows * heads and clamped by the step's longest table: at eight heads
one and two rows split 16 ways and three rows 11, so the k + 1 rows of a speculative verify summed
their partials in another order than the single-row decodes at the same positions, and Ling-3.0's
greedy text left the run without speculation from MTP depth 2 on. The count now comes from the
head count only; a scratch hook sizes the partials for up to 32 rows a launch, and a larger batch
takes as many splits as its scratch holds. r4d_emu's mla test holds verify launches of 2 to 32
rows to their single-row decodes bit for bit.
2026-11-03 19:07:34 +01:00
keptn42 303060f210 deploy/compose, README: Ling-3.0-flash-Sante w4a8 on four cards 2026-11-03 19:07:34 +01:00
keptn42 36de701090 docs: bailing_hybrid in ARCHITECTURES.md 2026-11-03 19:07:34 +01:00
keptn42 ccb5071228 data/recipes: ling3-w4a8-rtn and ling3-w4a8-gptq -- Ling-3.0's routed experts at four bits
The routed experts as int4 codes with a bf16 scale per 128 of K, everything else as the checkpoint
holds it: rounded to nearest, or chosen by GPTQ against a calibration run of the first container.
One format, so the same kernels serve both.
2026-11-03 19:07:34 +01:00
keptn42 a78352dad1 bailing_hybrid: RADIANCE_LING_DUMP writes the residual stream after each block
Every row of every step after each layer's attention and feed-forward, one bf16 file per site and
rank, for a layer-by-layer comparison against a reference model. It synchronises the stream.
2026-11-03 19:07:34 +01:00
keptn42 0b18331a34 bailing_hybrid: whole experts per rank for a calibration run and for bf16 experts
The GPTQ tap writes each expert's down Hessian over its whole width, and a slice of a bf16 expert
is not one container run. Either way rank r owns experts [r E/W, (r+1) E/W) whole, as qwen4exp
does; served to calibrate and compare, not for decode speed.
2026-11-03 19:07:34 +01:00
keptn42 638663e9ff bailing_hybrid: the MTP layer as a serial drafter
Checkpoint layer 42 behind GlmMtp at 2560, model.layers.42 and final_layernorm.weight: an MLA layer
with the full routed feed-forward, its weights named as a trunk layer's, so a recipe's expert rule
covers them. Declared when the deployment speculates; a draft pass runs as GLM-5.3's.
2026-11-03 19:07:34 +01:00
keptn42 dd43d31e93 arch/common: GlmMtp takes its width, checkpoint prefix, layer and norm name
GlmMtp keeps GLM-5.3's layout as its defaults (4096, model.language_model.layers.45, 45,
shared_head.norm.weight), so that graph is unchanged. Another DeepSeek-style draft head sets them
before declare_inputs.
2026-11-03 19:07:34 +01:00
keptn42 8611feb85e bailing_hybrid: Ling-3.0-flash -- KDA, dense latent attention, group-routed experts
Ling-3.0-flash and its fine-tunes (`model_type: bailing_hybrid`) from the bf16 checkpoint: 42
layers in groups of five KDA layers and one dense MLA layer, two dense feed-forward layers, then
512 experts of 768 under group-limited sigmoid routing with an ungated shared expert. The KDA core
is GLM-5.3's (KdaState); the MLA attends in the latent through mla_project and mla_attn_paged, its
query served as two projections (the heads' rotary rows and their nope rows, each a plain 2-D
plane). One, two or four ranks; at four an expert's six blocks split 2, 2, 1, 1, rotated by the
expert's number mod 4 (moe_gemm_q_mod4). The latent and KDA caches are bf16.
2026-11-03 19:07:34 +01:00
keptn42 1c2f55027c arch/common: group-limited sigmoid routing and a SwiGLU clipped after the SiLU, for Ling-3.0
GlmRouter takes `groups` and `topk_groups` and issues router_sigmoid_group_topk above one group.
MoeFP8 passes them on (a grouped router runs the separate selection, not the single-group fused
one), takes a clamp of its own for the shared arm, and with `swiglu_step` clips both arms after
the SiLU; GateQuantFP8 issues swiglu_step for that, without the fused clamp-and-quantise. Every
default is the existing behaviour, so no other graph changes.
2026-11-03 19:07:34 +01:00
keptn42 523349dd8f libr4d: swiglu_step, router_sigmoid_group_topk, mla_attn_paged, and mla_project at head_dim 128
mla_attn_paged is the wave-per-(row, head) latent attention of mla_attn with the rotary part in
the score, one page table a sequence, the causal bound from cu_seqlens and seqused, and the head
gate in its store; a short batch splits the history and merges f32 partials as mla_attn does.
router_sigmoid_group_topk is router_sigmoid_topk's wave with the groups ranked first, a lane a
group. mla_project takes the head width as a template parameter; at 256 it is the kernel it was.
r4d_selftest holds each new row and the 128-wide mla_project to libref.
2026-11-03 19:07:34 +01:00
keptn42 e4ca20ddf8 libavx: swiglu_step, router_sigmoid_group_topk and mla_attn_paged, held to libref by avx_check 2026-11-03 19:07:34 +01:00
keptn42 7169c9da0a libref: swiglu_step, router_sigmoid_group_topk and mla_attn_paged
Three ops Ling-3.0 needs, with their references, OPS.md entries and ref_test cases.
swiglu_step is the SwiGLU clipped after the SiLU, as vLLM and SGLang serve Ling-3.0.
router_sigmoid_group_topk is noaux_tc routing with groups: a group ranks by the sum of its two best
biased scores and only the best groups' experts are candidates. mla_attn_paged is dense causal
latent attention over a paged cache whose row is the latent then the rotated key part, with an
optional head-wise sigmoid gate; it refuses zero rows and reads a gate row at the gate's own pitch.
2026-11-03 19:07:34 +01:00
keptn42 9c5d4a656c tokenizer: possessive quantifiers where the greedy reading matches the same
A possessive repetition of one class at the top level, whose tail in its concatenation is classes
that share no codepoint with it, gives the same matches read as greedy: a shorter run leaves the
tail facing a codepoint it cannot take. Ling-3.0's pre-tokeniser pattern has two such quantifiers.
Everything else stays refused by name.
2026-11-03 19:07:34 +01:00
Asim Siddiqui 702a0970cc libr3d: value-init the GEMM's by-value structs so the tape audit sees no padding
The recorded-pass audit (Ctx::tapes_agree -> a_tape_diff) byte-compares the serialized
kernel arguments of a pass against its recording, and on the first disagreement it concludes
"the pass depends on something the recording's key does not carry" and stops the engine. On
gfx1102 with the dspark drafter that self-stop fired on the third request:

  E rank 0: draft pass -1 at 23 tokens issued differently from its recording after 0 plays,
    so the pass depends on something the recording's key does not carry:
    record 1: kernel fp8a8_tiled_kernel: its arguments differ at byte 28

Byte 28 is not a pointer offset. With ActQ = 24 bytes (a pointer, a long long, an int, and a
4-byte trailing hole) and WQ = 64 bytes (with a 4-byte trailing hole), the argument block is
a[0,8) aq[8,32) b[32,40) h[40,104) ...; inside aq, gmode ends at 28 and bytes 28..32 are
padding. The audit found the first difference at 28, so every real field before it -- a,
aq.scale, aq.row, aq.gmode -- was identical: only the padding differed.

The launcher built those structs with aggregate-init (ActQ aq{ptr, ll, int};), which
initializes the three members and leaves the trailing padding indeterminate. HIP serializes
the whole struct, padding included, into the kernel-argument block, so the record and the
audit each captured whatever garbage was on the stack. Whether the two garbage patterns match
is a coin flip per run -- a Heisenbug that only surfaced once the stack states diverged.

Value-init the structs (ActQ aq{}; WQ h{}; MxWQ h{};) and assign the fields: value-init
zeroes the entire object including padding, aggregate-init does not. The kernel reads none of
the padding, so behaviour is unchanged -- only the serialized bytes become deterministic, and
the audit can no longer mistake a padding byte for a missing key. Applied to both the
fp8a8_tiled and mxfp4a8_tiled launchers, the only two libr3d kernels that pass a struct by
value.

Verified on the box (RX 7600, gfx1102): r3d_selftest 109 rows clean, 0 failed; the rig with
the dspark drafter armed (speculation at its auto depth) now serves back-to-back requests
past the point that self-stopped it before, with no schema or tape refusal.
2026-11-03 19:06:47 +01:00
Constantin 798fb21e51 prefill: key tape splits from ordered host KV bounds 2026-11-03 19:05:30 +01:00
Constantin aa14eea76c prefill: fail closed when live split geometry is unknown
Head-256 split-prefill launchers now declare that their grid depends on
live KV. Without an architecture geometry key, those passes stay live
instead of replaying a stale tape. Qwen keys only a proven one-sequence
prefill. Plugin ABI 34.
2026-11-03 19:05:30 +01:00
Constantin ded64c0bd3 prefill: key recordings by live split geometry 2026-11-03 19:05:30 +01:00
Constantin 61e275e30f prefill: split KV on live seqused, not the model max_ctx
The 8-tile floor used max_ctx, so a 128-token chunk at --max-model-len
2048 became four splits of ~32 keys. The same prompt in one 977-token
launch stayed unsplit. Only the reduction order changed, and that
moved Spark BF16 first-token top-20 by 0.46 nats.

Occupancy still decides when a long-KV short-Q launch should split.
The floor now reads seqused_k (skipping the copy when occupancy is
already 1). A 128/128 case with declared max_ctx 2048 stays unsplit.
2026-11-03 19:05:30 +01:00
Constantin 9cb04f62a8 config: --gpu-memory-mib, the inverse of --gpu-headroom-mib
N claims that many MiB of every card; headroom is the rest. The two
flags cannot be combined. vLLM's utilisation fraction, written in MiB.
2026-11-03 19:02:52 +01:00
Memoria (Noblistic) aa182fc156 docs+tests: drop the page-wide separator claim, close one surviving mutant
Review B of 54d4613 refuted the second clause of the separator sentence. The
population is 15 dots / 46 pipes, not the 11/15 enumerated before it: the history
line's own anchor dot is written as the escape form, so a glyph grep misses the
sentence's own subject. And triple()/acceptTriple() pipe-separate an extreme from
a window mean from a current value in the strip tiles, which is a plain field
join only by stretch. The clause corrected one overclaim by asserting its
negation; the real state is asymmetric, so only the line-local scoping stays.

history.test.js:
- add tpsF(9.994) == "9.99", which kills the sig3 9.995->9.994 mutant that
  survived 09ac548. Measured: FAIL got "10.0" want "9.99", rc=1.
- the reviewer's other proposed closer, tpsF(99.951) == "100", is NOT added.
  Against the tps 99.95->99.951 mutant it passes, and 2000 samples across
  [99.94, 99.96) give shipped and mutant the same output set ["99.9","100"]:
  cnt and sig3 agree throughout [99.95, 99.951). That mutant is behaviourally
  equivalent and no literal can catch it, so the check would be a guard that
  cannot fail.
- the n=25 floor/ceil check could never fail (mkRows is strictly increasing), so
  it is now a fixture precondition that throws instead of a counted check.

Check count stays 63. Suites after: 27/35/63/34 JS, dashboard_test 241 over 8.
No shipped code touched.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) c776ab9e46 GUIDE: scope the separator rule to the history line, where it actually holds
The delta review recommended one sentence to close the ambiguity behind the three leftover pipes,
and this is that sentence -- but not the sentence it suggested, because the suggested one asserted a
page-wide rule that the code does not have.

The recommendation was to state that the rule is page-wide and that a trailing verdict takes a pipe.
Enumerating every separator site before writing it (11 dot sites, 15 pipe sites) showed the opposite:
the memory panel joins its sibling fields with dots (rest.join at :2692) and reserves the pipe for
the trailing verdict, while the KV sub-line joins its two fields with a pipe (:2531). Two different
idioms on adjacent panels. And most of the 15 pipe sites are ordinary field joins -- version | up,
N cards | M collectives, mean | worst L3 -- so the pipe is not reserved for verdicts at all.

So the rule is scoped rather than extended: the dot/pipe convention is a property of the history
line, and neither glyph means anything page-wide. That is the true statement and it closes the same
question -- the three pipes are not leftovers, they are plain separators in panels that never
adopted the history line's convention.

Two drafts were rejected on the way here, both for overclaiming: one said the KV, memory and kernel
panels "use them the same way" (they do not -- dots vs pipes), one said the pipe "introduces a
trailing verdict" as though that were its role (it is one of several uses). The delta review warned
that rewrites introduce new false claims; it was right about the risk and this is the third time on
this branch I have caught a doc sentence of my own saying more than the code does.

Docs only, no code touched. Within the section's 102-character maximum.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) d564e6e5b1 tests/js: break the tautology the delta review caught, and three surviving mutants
The delta review refuted guard 3 of 4dce97b, and it was right. Replacing the re-typed formatters
with a slice of the shipped ones removed one unfalsifiable shape and installed another: tpsF/cnt3F/
durF are called on BOTH sides of every comparison, so any formatter bug cancels out. Verified with
my own instrument before fixing -- shipped `tps = (v) => "X"` passed all 37 checks. The brief
warned about exactly this and I walked into it anyway.

Three sections added, each mutation-tested with rc captured on its own line:

Formatter literals (14 checks). The only place the formatters are pinned to something other than
themselves. tps -> "X" now fails 5 checks; the dur ms branch -> *100 + " s" fails 2. Band
boundaries are pinned at both edges (9.995 inclusive, 99.95 exclusive) because that is the rule F1
of the docs fix depends on. Values were derived from the shipped source rather than copied from
the review's draft, which caught a real error in it: DASH is U+2013, not a hyphen, so the drafted
`tpsF(NaN) === "-"` would have failed on correct code.

Median at an ODD row count (2 checks). M17 survived the previous fixture change because the median
was only ever asserted at n=24, where floor(12) and ceil(12) are the same row -- a non-uniform
fixture could never have caught it, so the earlier diagnosis named the right cause and the wrong
cure. n=25 makes the two candidates differ, and floor->ceil now fails with "1.80 s" want "1.70 s".

Threshold counts adjacent to the boundaries (8 cases, up from 3). M15 survived because no case sat
at 19, and a >=5 -> >=7 mutation survived because no case sat below 7. Counts now straddle both
thresholds: 4/5/6 pin the 5 boundary, 19/20 pin the 20.

history.test.js 37 -> 63 checks. Full suite: 27/35/63/34 JS, 241/8 and 62646/184 C++.

GAP D (the revoke delay argument) deliberately not pinned: the 1000 ms is a safety margin, not a
contract, and a guard that fails a reasonable 500 ms encodes an arbitrary constant.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 8be040f599 tests/js: five guards that could not fail, now proven to fail
The review ran 27 mutants and 6 survived. Each fix below was then mutation-tested against the
shipped source, with rc captured on its own line -- a piped `| tail` reports the tail's status and
would have hidden every one of these.

download.test.js 31 -> 34 checks:

The assertion at :64 could not fail. `ok(page.indexOf('<span class="cap">Requests</span>') < iBtn)`
compares against indexOf, which returns -1 when the caption is absent, and -1 < anything is always
true. Renaming the caption survived both suites. Now the index is captured and required to exist
before the order is compared.

The stubs recorded counts, not sequence: click() incremented a counter, appendChild pushed to a
separate array. So click-before-appendChild survived -- and Firefox ignores a click on an anchor
that is not yet in the DOM, so that ordering is a silently dead button in a real browser. One
shared seq[] log now makes the order assertable, and the mutant is caught by the new assertion
itself ("the anchor is in the DOM BEFORE it is clicked: ["click","append","remove"]"), not by a
crash. My first attempt at that mutant targeted el.body, which does not exist, and failed with a
TypeError -- proving only that the mutant was malformed, so I rebuilt it against the real line.

history.test.js 29 -> 37 checks:

The formatters were re-typed. The suite passed its own `(v) => v + " ms"` into the shipped
renderer, then asserted "value and unit are one string" against the unit the stub had
manufactured -- testing the fake, not the page. tps/cnt3/dur are now sliced from the shipped
source (DASH..dur is self-contained) and the guard compares against what the real dur() renders.

Presence assertions became value assertions. "last 20" appearing in the string survived
slice(-20) -> slice(-100), because the label was still there while the figure silently became the
last 100 -- a wrong number on a performance dashboard. Each figure is now compared to a mean
computed independently of the shipped group(). The fixture also had to change: the old cycling
values made mean(all) equal mean(last 20) by coincidence, so no window mutation could show up in
the output. Distinct values per row fix that.

Threshold fixtures at 7, 12 and 24 rows. 12 is the discriminating count -- it kills a threshold
lowered to <=12 as well as one raised.

The two .hsep padding regexes are unified. One was loose, one strict, and they disagreed about
whitespace: a reformat from `padding:0 9px` to `padding: 0 9px` passed the loose test and then
CRASHED the suite on `null[1]`. One regex, one match, checked before use.

Verified: slice(-100) caught (2 failures), threshold >=12 caught, ttft median->mean caught
("1.65 s" want "1.70 s"), padding reformat now passes cleanly. Full suite: 27/35/37/34 JS,
241/8 and 62646/184 C++.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 08fa89255c GUIDE: seven doc claims the review found false, plus the comment that caused the worst one
The adversarial review's call was ship the code, fix the docs first. Every correction below was
re-verified against the shipped code before editing, not applied on the verdict's word -- the
review ran against e9f0622 and the tree is now rebased a559977, so all anchors were re-located by
content.

The blocking pair:

F2 was the worst: "Reloading the page resets these figures, a server restart does not" states the
opposite of the code. newEngineRun() deletes extAt/extAtS (dashboard.cpp:1735-1736), poll() calls
it when started_at changes (:3942), and this branch's own extremes.test.js:103 is titled "a
RESTART drops the extremes". Three independent instruments, one doc line saying the reverse. The
error was inherited from a stale comment at :1709-1710, so that comment is corrected too -- it is
the root cause, and it is comment-only: every changed line in dashboard.cpp starts with an
asterisk, verified by filtering the diff.

F1 is a worked example a reader copies: sig3 renders one decimal across [9.995, 99.95), so the
line prints "best 58.0 | recent 54.0", not "best 58 | recent 54".

The rest are one-liners: F3 claimed three categories carry windows when ttft is a median with
none (:2282); F4's rationale for the window rule fails at its own boundary -- at exactly 20 rows
last-20 repeats the overall mean, which is now stated rather than papered over; F5 put the poll
summary under the fields when #advsum sits in the panel header (:1404); F6 said figures hold
while reading another page without the 60 s limit that drops the windows (GAP_S = HIST_S = 60);
F7 showed a middle dot where :2530 ships a pipe. README:19 credited poll_spark.test.js with
poll()'s restart decision -- that file contains zero matches for poll(); the coverage is in
extremes.test.js.

The numbers the brief flagged as suspect (HMAX=200, RECENT_S=15, RECENT_PREFILL_S=5) were correct
and are untouched. The real errors were prose semantics and rendered formatting, which the
flagging did not anticipate.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 742f17f1e3 GUIDE: the history panel and its export were never documented
Section 6.1 described the tiles, the extremes line, draft acceptance, Sessions, Model and
Advanced, and said nothing about the history table under the request list -- the panel this
branch changed twice. A reader could not learn from the docs that the rows are per-browser
localStorage rather than server state, that only the last 200 are kept, that a clear is a
timestamp every tab honours, or that the download icon exists and what it writes.

The summary line needed the same treatment: it now carries a rule a reader cannot infer from
the page, that a dot separates categories and a pipe separates the windows inside one. Stated
because it is a convention the page depends on and nothing else records.

Every number here was checked against the code rather than recalled: HMAX is 200, the file is
radiance-history.json, and the window rule is a flat threshold -- "last 20" appears at 20 rows
and "last 5" at 5, not once a window is wider than its neighbour. The first draft said the
latter; driving the shipped group() at 3, 7, 12, 20 and 25 rows showed 12 rows renders only
"last 5", which is what the paragraph now says.

Docs only, no code touched. Lines kept within the section's 102-character maximum.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 599d904e01 tests/js: README lists all four suites and the render check
The README still named only the two suites that came out of the 2011-01 review; history.test.js
and download.test.js shipped without a line, and render_align.js shipped without its invocation
or its puppeteer prerequisite. A reviewer opening tests/js/ could not tell what to run or what
each one guards.

The render check gets its own section because it is not a unit test and cannot be: it needs
Chrome, and it exists because three visual claims on this branch were made from the CSS and the
SVG viewBox and all three were wrong. That is the argument for measuring the rendered page, and
it belongs next to the tool that does it.

Docs only, no code touched.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 51db1729b1 dashboard: level the download glyph with the caption, measured not reasoned
The operator's intent, drawn rather than described: the bottom of the tray bar should sit on
the same line as the bottom of the letters in REQUESTS. The previous commit claimed the
viewBox-flush geometry achieved that. It did not.

Headless Chrome, screenshotting the real header at 4x and finding the lowest inked pixel row of
each: the caption's letters ended at device row 71 and the tray bar at 63 -- the icon floated
2.00 CSS px high. align-items:baseline puts the SVG's BOX on the text baseline, and the baseline
sits above the box bottom, so filling the box was necessary but nowhere near sufficient. A 2px
translateY on the glyph closes it; re-measured, both bottoms land on device row 63, gap 0.00.

tests/js/render_align.js is that measurement, kept in the repo so the claim can be re-checked
rather than trusted. It is manual and not wired into CMake -- it needs puppeteer and a Chrome
binary, which are not repo dependencies -- and exits nonzero when the two bottoms differ. It
fails on the pre-fix page (2.00px above, rc=1), which is the only reason to believe it.

download.test.js's guard was the thing that gave false confidence here: it asserted the glyph
"sits on the baseline" from the viewBox arithmetic alone, and passed while the icon floated. It
now pins both halves -- the glyph fills its box AND the 2px nudge is present -- and the comment
records that the earlier claim was wrong and why the test could not see it.

A unit test cannot catch either of this session's two visual errors: the collapsed whitespace
(zero width, not the 13px claimed) and this float. Neither is a property of the string the code
builds. Both are properties of the rendered page, and only the rendered page was checked here.

Suites: download 31, history 29, extremes 27, poll_spark 35, dashboard_test 241 over 8 cases,
sched_test 62646 over 184, no failures. Alignment mutations caught: removing the nudge, making
it 1px, re-insetting the bar in its box.

Not deployed. Goes to review with the separator and export commits.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) d537dc09aa dashboard: sit the download glyph on the baseline instead of floating above it
The icon looked awkward next to REQUESTS: it floated a hair above the caps. The header aligns
its items on the text baseline, and an inline SVG's baseline is its box bottom, so the box
bottom was on the baseline -- but the tray bar was drawn at y 13.5 of a 16-unit viewBox,
leaving 1.7 units of empty space below it. The visible bar therefore sat above the baseline
while the letters sat on it.

Redrawn so the bar's stroke bottom lands exactly on the viewBox bottom (centreline 15.2 plus
half the 1.6 stroke = 16.0), which puts the bar on the baseline with no offset to tune. The
shaft and arrowhead moved up by the same amount to keep the proportions.

download.test.js gained a geometry guard that parses the viewBox, stroke width and bar
centreline out of the shipped markup and asserts the stroke bottom is flush with the box
bottom. Re-insetting the bar to the original 13.5 fails it with the measurement (14.3 want 16),
so a future edit that reintroduces the float is caught rather than eyeballed.

Verified: download 29 checks, history 29, extremes 27, poll_spark 35, dashboard_test 241 over
8 cases, sched_test 62646 over 184, no failures.

Not deployed. Goes to review with the separator and export commits.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) c36d04d99c dashboard: move the JSON export to the Requests header as a download icon
The history summary row had grown crowded -- the figures, then a "json" button and a "clear"
button -- and the operator asked for the export to live in the Requests panel header instead,
top-left by the title, as a download icon with a "Download JSON file" tooltip. The Requests
header already carries running/waiting on the right, so the export sits opposite it on the
left rather than lumped in with the history figures.

The button is an inline SVG download glyph (a <button>, so it is keyboard-focusable and
announced), in a new .pleft group so the space-between header keeps it on the left with the
title. The handler now saves a file rather than copying to the clipboard: a Blob of the stored
rows, an anchor with a download name, clicked and removed, the object URL revoked after the
click. The old #hjson clipboard button is gone.

This also fixes a clipping bug the previous commit introduced. Making each category a nowrap
span and the separator a padded element removed every whitespace text node between categories,
so the summary line became one unbreakable run: a long line overflowed the row and clipped the
buttons after it -- the "json" the operator saw cut off at the panel edge. A zero-width space
between groups restores a break opportunity: the line can now wrap between categories, while
each category still stays atomic. The break point sits between groups, never inside one, where
nowrap would make it inert.

tests/js/download.test.js, 27 checks, drives the shipped handler against stubs: the button is
in the Requests header on the left of the aside, exactly one of them (a duplicate id would bind
only the first and leave a dead control), tooltip and aria-label present, an icon not a text
label; the handler builds one anchor, names it radiance-history.json, types the blob
application/json, clicks it, attaches it to the document (Firefox needs that), removes it, and
revokes the object URL only after the click. The payload round-trips through JSON.parse.

history.test.js gained the break-point checks: three zero-width spaces between four categories,
each immediately before its group, none buried inside a nowrap group.

Verified by mutation: dropping the download attribute, never clicking, never revoking, a wrong
blob type, changed tooltip text, and moving the button to the right of the aside each fail the
suite. extremes 27, poll_spark 35, history 29, download 27, dashboard_test 241 over 8 cases,
sched_test 62646 over 184, no failures.

Not deployed. Goes to review with the separator commits.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 1554b451e1 dashboard: a history category wraps whole, and its break is a padded element
The summary line wrapped mid-figure: "ttft median 810" ended one line and "ms" started the
next. A category that cannot fit should move to the next line intact, not break wherever the
browser finds a space.

Each category becomes one span with white-space:nowrap, so it is atomic, and the dot between
categories becomes a padded element carried INSIDE the group it introduces -- as a sibling it
could be left stranded at the end of a line when the group wrapped, which is the same orphan
in a different place.

This also corrects a false premise in the two commits before it. HTML collapses runs of
whitespace, and .hsum sets no white-space, so the "wide" double-spaced separator those commits
introduced never rendered wide: it collapsed to a single space exactly like the tight one. The
spacing change was not subtle, it was zero -- which is why it looked identical. Width has to
come from a padded element, not from spaces in the string. The pipe-within-category and
dot-between-categories distinction is unaffected by this and stands.

tests/js/history.test.js, 24 checks, drives the shipped assembly against a DOM stub and reads
the shipped CSS: every category is a nowrap .hgrp, the break is a padded .hsep, the dot is the
first child of its own group rather than a sibling, a category's own figures carry pipes and no
dot, and the ttft category is a single text node so value and unit cannot split.

Verified by mutation: dropping nowrap, dropping the padding, moving the dot to a sibling,
turning the category break into a pipe, and splitting the value from its unit each fail the
suite -- the last being the exact 810 / ms orphan this fixes. extremes 27, poll_spark 35,
dashboard_test 241 over 8 cases, sched_test 62646 over 184, no failures.

Not deployed. Goes to review with the separator commits.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) d5bb6a6c6e dashboard: category breaks keep the dot; only fields within a category take the pipe
The pipe sweep converted both separator weights at once. That was too far: the wide separator
is the break between categories -- tok/s against prefill against ttft -- and it has been a dot
since the page was written. Reverting the wide tier to the dot keeps that precedent; the pipe
stays only on the tight tier, the fields inside one category (mean, last 20, last 5), which is
where the figures actually ran together.

So the history line now reads:

  40 done  ·  tok/s mean 100 t/s | last 20: 98 t/s | last 5: 105 t/s  ·  prefill mean 1.2k | ...

The dot marks a category change; the pipe marks a different question about the same category.
Two weights, two meanings, one rule applied everywhere rather than dots in one panel and pipes
in another.

Thirteen wide separators reverted across the page (twelve lines; the layer-residency line carries
two), so the rule is global. The two dots that were never separators -- the CSS list bullet and
the browser tab title -- are untouched, as is the range dash in "layers 1-8".

Verified by rendering the shipped page bytes, not by the suite: the suite does not pin the wide
separator, so it is green whether the category break is a dot or a pipe. The render pulls the
join string and the group() body straight out of dashboard.cpp and shows the dot at the category
breaks and the pipe within them. All four suites still pass: extremes 27, poll_spark 35,
dashboard_test 241 over 8 cases, sched_test 62646 over 184.

Not deployed. This change and the pipe sweep go to the same code review before anything ships.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 757ad11b0d dashboard: separate distinct fields with pipes, not middle dots
Every line that packs several distinct figures into one string used the middle dot, at two
weights -- a tight dot between sub-figures and a wide one between groups. At 11px the dot is
too short to read as a boundary, so lines like the history summary ran together: count, three
tok/s figures, three prefill figures and ttft all sat at one visual level. The operator's call
was to use the pipe wherever fields are meant to be distinct.

Fifty-eight separators converted across the page -- the history summary, the version line, the
KV and expert asides, the acceptance and step-time detail lines, the graph and model-view
metadata, the control-vector summary, the poll summary. The two weights are kept: a tight dot
becomes a tight pipe, a wide dot a wide pipe, so the group-versus-window hierarchy the wide
dot carried survives the glyph change.

Two dots stay, because they are not field separators: the CSS list-bullet marker
(.gmeta li::before content) and the browser tab title (file - radiance). The range dash in
"layers 1-8" and the DASH placeholder are likewise untouched. The two " + " the earlier
census turned up are inside pctn building "<0.1" and ">99.9" string literals, not separators.

The sweep missed eight separators at first: the age clause and several detail lines build
their separator as the escape "\u00b7" rather than a literal dot, and a literal replace
never sees those. Caught because the tests that pin the age clause went red on the literal
sites but the escaped ones did not -- a partial conversion that would have shipped a page
with pipes and dots mixed. Both forms are now converted.

Tests: the two regexes pinning the age clause and the one string pinning the poll summary
now expect the pipe. They failed when the code changed and pass now, which is the point --
a separator assertion that could not fail would not have caught the escaped-dot miss.
extremes.test.js 27, poll_spark.test.js 35, dashboard_test 241 over 8 cases, sched_test
62646 over 184, no failures.

GUIDE's two example triple lines, which mirror the page's separators, updated to match.

Verified the sweep by reading all 58 changed lines, not by trusting the count: no pipe landed
inside a regex literal (where it would mean alternation) or a prose tooltip. Both hazard
greps were positive-controlled against known-bad input before their empty result was trusted.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) aaafebcf0a GUIDE: the dashboard has four tabs, and the windows are spans not sample counts
Section 6.1 opened "It has three tabs" and described Dashboard, Sessions and Model. The page has
four -- Advanced was added as a fourth nav view and the doc never heard about it, so a reader
comparing the page against the guide would find an unexplained view and a wrong count. Added the
paragraph: two editable intervals, idle and busy, clamped to 100-5000 ms, equal values give one
fixed rate, stored in the browser rather than on the server, and polling pauses on every view but
Dashboard so the figures hold while another view is open.

Two sentences described the windows as sample counts, which stopped being true when the rings
started pruning on elapsed time:

  "the mean of its last 30 samples there (15 s at one poll every 500 ms; 5 s for prefill)"
  "the tile's recent pools the last 30 polls that drafted"

Both now name the span. The first also assumed a 500 ms poll, which was a constant when it was
written and is now the default value of a field anyone can change -- so the sentence was wrong
twice over, in the mechanism and in the number it derived from it. Note the acceptance ring
prunes the same way (accPool, RECENT_S), which is why the second sentence moved too.

README needs nothing: it defers the dashboard to this section in one line and makes no claim about
tabs of its own.

Docs only, no code touched. Line lengths kept within the 102-character maximum the surrounding
section uses; the diff was read line by line rather than trusted to the anchor counts.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 7bba83c075 dashboard: the history line's group breaks get the page's wide separator
The summary line under the history table joined everything with the tight middle dot: the
count, three tok/s figures, three prefill figures, and ttft, eleven items at one visual level.
The groups ran together.

The page already has a two-tier convention -- a tight dot between sub-figures inside a group,
a wide dot (double-spaced) between major breaks, used that way on the KV lines and the
version line. The history line was the one place using the tight dot at both levels. It now
joins its groups with the wide dot, so a group edge reads heavier than a window edge, using
separation the page already speaks rather than new vocabulary.

Verified: dashboard_test 241 checks over 8 cases, extremes.test.js 27, poll_spark.test.js 35,
no failures; no test pins the separator.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 0ac154c803 dashboard: drop the uptime comparison -- it could only fire on a clock step
8ee893e added `up < lastUp` beside the started_at comparison, to catch a restart landing in
the same whole second as the one the page last read. It cannot catch that. uptime_s is
derived, not independent: unix_now() - started_at_, both whole seconds, so started_at +
uptime_s is exactly the wall clock at every poll. Two processes sharing a started_at are
therefore read at increasing wall times and report INCREASING uptimes, so the comparison
never fires in the case it was written for. It fires on genuine restarts, which started_at
already catches, and on a backward NTP step, which is not a restart at all. Net effect: dead
where it was needed, redundant elsewhere, and a false clear of the session extremes on every
clock correction.

The test that "proved" it worked was fed an impossible fixture: started_at 100 with uptime 40
implies the clock read 140, then started_at 100 with uptime 2 implies 102. Time running
backwards is the only way to reach that pair, which is the same mistake the finding it
answered was about -- reasoning from a state the instrument cannot produce. It now asserts
the reachable behaviour instead: a backward uptime with an unchanged started_at is a clock
step and must NOT clear the extremes, since they still belong to the running process.

The collision the comparison tried to close needs a replacement process stamped in the same
second as the one the page last read. The page can only learn started_at once /stats answers,
startup_s after the old process began -- 69 s on this engine -- so a replacement starting
after its predecessor stopped answering is stamped a later second. The bound is startup_s >=
1 s; a model that came up inside a second could collide, and would cost one stale extreme
carrying a true age. That is documented where the comparison used to be.

The acceptance window's use of the same signal is NOT redundant and is untouched: it has no
started_at comparison, so for a tab that stopped polling while a new process drafted past the
old totals, a falling uptime is the only thing that catches the restart.

Verified: dashboard_test 241 checks over 8 cases, extremes.test.js 27, poll_spark.test.js 35,
sched_test 62646 over 184, no failures. Mutation re-run after the revert: deleting poll()'s
detection line, stamping extAtS on every sample, and deadening acceptTriple's age clause each
fail the suite. Behavior is unchanged from the deployed build, which never had the
comparison, so no restart is needed for this.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 638aa3a683 tests/js: drive poll()'s restart decision, and the two clauses nothing reached
An adversarial pass mutated this leg of the dashboard and found three mutants that survived
every committed check. All three were real gaps in my verification, and the reason was the
same each time: the tests called the helper directly, so the code that DECIDES whether to call
it was never exercised, and two clauses sat behind a guard that no test ever opened.

Drive poll() itself. A scripted /stats sequence and a fixed clock, with resetWindows,
newEngineRun and update replaced by counters, so the assertions are about what poll() decided
rather than what the helper does once called. Three cases: the first poll is a baseline and
clears nothing, a changed started_at clears, and a long quiet span takes the gap path without
being read as a restart -- the distinction the previous commit exists to make.

Re-sample a key after its extreme is set. The stamp records when the extreme was set, so a
worse sample must not refresh it; nothing used to sample the same key twice, so moving the
stamp to every sample -- which makes every age read about zero, wrong output rather than
missing output -- passed unnoticed.

Exercise acceptTriple with a live extreme. Its only previous call came from the restart case,
which clears extAt first, so it returned at its guard before reaching the age clause: the
clause was asserted zero times while triple's was asserted seven.

Use the shipped pctn rather than a re-typed one. The copy diverged from the real formatter for
small and non-finite values; nothing asserted on that output today, so it was a latent trap
rather than a live error. Pass the sampled value as a parameter instead of interpolating it
into the function source, so the null case is a real null and not the string "null".

Verified by mutation, which is the only thing that makes a green suite mean anything here:
disabling poll()'s detection line fails the suite, as does moving the stamp to every sample,
as does deadening acceptTriple's clause, as does removing the uptime comparison added in the
previous commit. extremes.test.js 27 checks, poll_spark.test.js 35, dashboard_test 241 over 8
cases, sched_test 62646 over 184, no failures.

Found by an adversarial review pass on the author's own commits.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 4d8be7099d dashboard: a restart that lands in the same second is still a restart
The poll compares started_at to decide whether the engine is a new process, and clears the
session extremes when it is. started_at is std::time(nullptr) -- whole unix seconds -- so a
restart landing in the same second as the previous start leaves it unchanged and the clear
never runs. The previous run's extremes then render with an age clause attached, and the age
is true: the figure really is that old. What is false is the provenance the age implies, that
it belongs to the process now running. A stale figure with an honest number on it is worse
than no number at all, because it invites the reader to trust it.

Also compare uptime_s, which resets to about zero on any new process. It is the same signal
the acceptance window already trusts for the same purpose, so this adds no new assumption:
it is wall-clock derived, and a backward NTP step reads as a restart and clears the extremes.
That false positive costs a cleared window on one poll, which is what the acceptance window
already accepts.

Found by an adversarial review pass that reproduced it as `highest 75% - 43.0 s ago` from a
dead process.

Verified: dashboard_test 241 checks over 8 cases, no failures. The case that holds this is
the poll() driver in tests/js/extremes.test.js, which fails if the uptime comparison is
removed; it lands in the next commit, so this one is not self-proving on its own.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 08c85ea527 tests: run the dashboard page's JavaScript, in the tree
An independent review of 9cc237f rejected its verification claim: the commit said 18 checks
executed the shipped noteSample, triple, acceptTriple, resetWindows and newEngineRun, and the
tree contained none of them. The harness was real and passing, but it lived in /tmp, so nobody
else could re-run it and the claim was unfalsifiable from the repository. That is a fair
rejection regardless of whether the checks were right -- a verification nobody can repeat is a
claim about the author's machine.

Move both harnesses into tests/js/ and add the extractor they need. The page is one C++ raw
string, so a JS test has to pull the script out of the translation unit it ships in; page.js
does that, and each test slices the functions it exercises by line range and CALLS them. Both
details matter: a retyped copy tests the copy, and a sliced function that is defined but never
invoked passes without testing anything, which has already happened once in this code.

extremes.test.js, 17 checks: the age clause appears only when an extreme stands alone and is at
least a second old, tracks the newest extreme rather than the first, survives a gap with its age,
and is gone after a restart along with the extreme itself.

poll_spark.test.js, 35 checks: the clamp's floor, ceiling and fallbacks, the in-flight trigger,
the old storage key migrating to a flat rate, corrupt storage falling back, the summary label
matching what is set, the sparkline's x axis being time-proportional rather than sample index,
the right-edge fill at startup, a sample gap drawn as a gap in the line, and the prune loop
keeping samples by elapsed time rather than by count. The window expectations derive from the
shipped HIST_S, so changing the constant moves them instead of silently passing.

Verified: both pass, and both fail when the code is wrong -- setting the age gate to zero fails
extremes.test.js, and returning the sparkline to index spacing fails four checks in
poll_spark.test.js. dashboard.cpp is unchanged by this commit and dashboard_test still reports
241 checks over 8 cases.

Not wired into ctest: they need node, which is not a build dependency here and will not be on a
contributor's box or in the ROCm build image. Making a missing optional tool a red build is worse
than an opt-in test, so the README says how to run them and when to bother.

Found by an independent review pass on the author's own commits.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 72ab60ed64 dashboard: a session extreme says how old it is, and a restart clears it
The tile detail lines keep the session's best figure when the window empties, which is
deliberate: a lane that goes quiet for a minute is the same lane, and blanking its best
would throw away the one figure still true. But an extreme with no window beside it is
indistinguishable from a fresh one, so a best from before a gap -- or from before an engine
restart -- reads as the lane's current best. A review flagged the label as honest but
undated; the age is what makes it honest.

Record when each extreme was set and, when it stands alone and is at least a second old,
name the span: "best 500 t/s - 5m 00s ago". Below a second the clause is noise, and a
figure set on this poll is current, so it stays silent.

A restart is a different discontinuity from a quiet minute and now gets its own path. The
previous process's requests are gone and its configuration may differ, so nothing from it
should carry over -- yet the extremes were the one figure that did, while every other
number on the page already refuses to pool across a restart: the acceptance window drops
its rings when the counters go backwards, and the history resets its base when request ids
restart. The poll now compares started_at, which is the process's identity, and clears the
extremes when it changes. A gap still keeps them.

Verified: dashboard_test 241 checks over 8 cases, no failures. 18 checks execute the
shipped noteSample, triple, acceptTriple, resetWindows and newEngineRun sliced out of the
page: the clause appears only when the extreme stands alone, tracks the newest extreme
rather than the first, stays silent under a second, survives a gap with its age, and is
gone after a restart along with the extreme itself. Not tested: the page in a real browser.

Found by an independent review pass on the previous changeset.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) 4e35a00493 sched_test: assert the slot reuse the recycled-slot case depends on
The case that guards the admitted_us reset read two timing inequalities and never checked
that the second request landed in the first request's slot. It rests on that: if the reap
defers, or the free list is pre-populated, the second request gets a fresh struct, the stale
stamp is absent by construction, and the invariant holds with the bug unpatched. A test whose
precondition is a property of the fixture rather than an assertion goes quiet without saying
so, which is worse than not having it.

Read the slot from the published row before the reap and assert it afterwards. This also
settles the one thing the review could not: whether the reap releases immediately or defers.
It releases, because the assertion holds -- proven by running it rather than by reading the
ahead-step planning that decides it.

Verified: the case passes, and removing the reset line still fails it, so the added assertion
did not blunt it. sched_test 62646 checks over 184 cases, no failures.

Found by an independent review pass on the fix itself.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) e53286cdbe dashboard: the history figures mean what their labels say
Five changes to one leg, committed together because they are one claim: a number on the
dashboard should be readable as the thing it is named for. They were deployed as
1.15.1-histfix without being committed, so the running engine carried code no commit
described, and a review of the working tree could not see its own context.

History labels. "avg" becomes "mean", the window figures appear only once enough rows
exist to be the window they name, ttft says median, and every history column carries a
title= spelling out what it averages and over what. A legend that has to be inferred
from a column header gets inferred wrong.

The prefill instrument. The history computed prefill speed as prompt tokens over
time-to-first-token, which charges queue wait to prefill; GUIDE:2808 warns against
exactly that formula. The scheduler now stamps admission and reports prefill_s, so the
column measures admission to first token. The page falls back to ttft when an engine
reports no admission time, so it still works against a stock build.

Windows in seconds. Every displayed window was a sample count, so "60s" meant 60 samples
and its span drifted with the poll rate: 60s at 500 ms, 6s at 100 ms. The rings now prune
by accumulated time and the sparkline's x axis is time-proportional rather than sample
index, so a busy stretch gets the room its seconds deserve and a gap in the samples shows
as a gap in the line. This is the precondition for the interval control below; at a fixed
rate the two agree, so a full ring draws exactly as before.

The interval control. An Advanced view with two editable fields, idle and busy, held in
localStorage: the cadence belongs to whoever is reading, not to what is serving, and the
server has no writable config that would survive an image swap. Both are plain numbers
rather than a mode switch, because the point is that the reader sets the rate; equal
values are one fixed rate and the summary says so.

Wind-down. The tile detail lines now sample on every poll, so "recent" follows the
engine's own idle decay instead of holding the last figure it saw, and a window older than
its own span is cleared rather than drawn as if continuous.

Fixes from an independent review on qwen, which found the first two:

admitted_us was never reset when a slot was recycled. add_locked only allocates when the
slot's pointer is null, so the struct survives release_locked with every field it does not
list intact, and the first-admission guard then kept the previous request's stamp. The
interval spans two requests, the stale stamp is always older, so prefill tok/s reads low
rather than missing. It reaches every row once the slot pool turns over. It feeds only
this one dashboard column: the engine-wide prefill tile uses an independent windowed
counter, and no admission, eviction, preemption or KV path reads the field.

Two tooltips still said prefill includes queue wait after the instrument stopped charging
it. Both now say what the code does and disclose the fallback, since one window can mix
rows measured from admission with rows fallen back to ttft.

Verified: both targets build clean. dashboard_test 241 checks over 8 cases, sched_test
62644 over 184, no failures. The new sched_test case drives submit, finish, reap and a
second submit onto the recycled slot and asserts prefill_s never exceeds ttft_s, since
admission cannot precede arrival; it fails against the bug and passes after the fix, so it
can fail. The embedded page parses under node --check, and 30 checks now execute the
shipped spark(), the clamp and the cadence trigger sliced out of the page rather than
restated: time-proportional spacing, the right-edge fill at startup, a sample gap drawn as
a line gap, the 100 ms floor, and the old storage key migrating to a flat rate. Not
tested: the controls' behavior in a real browser, and how the session extreme should read
when it outlives a cleared window.

Found in review by an independent qwen workstream; the slot-reuse finding was confirmed
by a second adversarial pass and against the source independently.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-11-03 18:09:49 +01:00
Memoria (Noblistic) bf7e473224 dashboard: a card-count change replaces the device rows, it does not stack them
The memory panel rebuilds its per-card rows when the card count changes, but the
rebuild only appended: the previous set stayed in #mem. Every card-count change --
a TP flip, a card swap, a lane re-pin -- therefore grew the panel by the old count,
permanently, until the page was reloaded. On a box that flips TP2 and TP4 by hand
the section becomes unusable within a day: eighteen rows of identical cards after
three flips, and the panel's own header (KV cache, prefix hits) scrolls away.

Remove the old rows before rebuilding, the same shape the request rows already use
above. Per-row removal rather than the sibling guards' container-clear because #mem
is shared with the KV and prefix meters, which are built once and must survive.

Verified: the embedded page parses (node --check on the extracted script), the
translation unit compiles, dashboard_test passes. The behavior itself -- rows gone
after a count change -- needs a live card-count change to prove; not tested here.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI
2026-11-03 18:09:49 +01:00
keptn42 8bbf402d9e grafana: show token totals and the key status on the first screen
Add totals over the selected time range: prompt tokens in, prompt tokens
read from cache (attention cache and linear checkpoint), prompt tokens
computed, generated tokens out and finished requests. They use counters
that /metrics already has.

Move Refused / failed to the first row. The status row is now second.
The ratio panels move below the throughput section. No panel is removed
and no panel id changes.
2026-11-03 10:30:41 +01:00
Deadcode 769b4c64a6 radiance 1.16.0
New models:
- Hunyuan3D-2 (hunyuan3d2): an untextured 3-D mesh from one picture of an object. DINOv2-giant
  over the picture, a FLUX-shaped flow-matching DiT (16 double-stream and 32 single-stream blocks
  of 1024) over 3072 latents with both guidance branches in one step, and the shape VAE's
  geometry decoder. Converted from tencent/Hunyuan3D-2's hunyuan3d-dit-v2-0 folder with
  data/recipes/hunyuan3d-2-bf16.recipe (fp16 cast to bf16, 4.4 GiB, one card). The licence
  (Tencent Hunyuan 3D 2.0 Community License) does not cover the EU, the UK or South Korea
- Served on Hunyuan3D-2's own API server routes, so its Blender add-on and scripts work
  unchanged: POST /generate answers with the mesh, POST /send runs it in the background and
  GET /status/{uid} reports steps_done and then the file. GLB, OBJ, PLY or STL; the field is
  sampled coarse to fine as FlashVDM's hierarchical decoding does, or densely with
  "volume_decoding": "dense"; seed, steps, guidance and octree_resolution as the reference.
  Texturing (Hunyuan3D-Paint) is refused for now (docs/GUIDE.md §5.17)

Merged:
- libr3d rewritten for RDNA3's wave matrix (@RikshaDriver): bf16, f16, int8-activation and vocab
  GEMMs retiled to 16x128 blocks with a double-buffered k-walk; fp8, mxfp4a8, w2a8, w4a16, w5a16
  and w8a8 quantised GEMMs and the gated form; grouped MoE GEMMs (bf16, fp8a8f32, mxfp4a8); the
  norms and quantisers, the QSA state ops and the MoE router, scatter and gather. Brought onto the
  op contract before release (13 schemas, the MoE GEMMs on weight tables with a_order and bf16
  output, moe_gather's gate pitch, moe_scatter above 1024 slots, the mxfp4 m16 dispatch) and its
  gated-delta-net kernels replaced by libhalo's; every op it serves now passes rad-kbench against
  libref on a gfx1151, and r3d_selftest checks its MoE GEMMs by value
- Gemma 4 31B: asymmetric int5 linears (w5a8i8 above 64 rows, w5a16 up to 64, a scale per 128),
  the norm, GELU and two-rank all-reduce junctions at quant_act_i8g's grid (rmsnorm_quant_i8g,
  gelu_mul_quant_i8g, ar_rmsnorm_quant_i8g) so the prefill overlap runs on the i8a8, a4 and w5
  trunks, and compose files for the 31B i8g, heretic-ara-i8g and w5 on two cards (@keptn42)
- The norms' lane sum reads eight at a time: TranslateGemma 27B decode is back from 225 to 239
  tok/s a stream at four streams, bit for bit the same output (@mici81)
- The head-256 prefill softmax rescales each row by its own maximum, not by a vote of the wave, so
  a row's rounding no longer depends on which rows share its launch (@gostar)

Anthropic Messages API:
- /v1/messages takes min_p, presence_penalty, frequency_penalty, repetition_penalty and
  repeat_last_n as top-level fields with the chat path's names, ranges and meaning, so clients that
  speak only the Anthropic format (Claude Code) can set a model card's sampling, such as Qwen's
  presence_penalty 1.5. The penalties count the last repeat_last_n tokens of prompt and reply (64
  by default, --repeat-last-n), as llama.cpp does

Plugin ABI 33:
- Shape generators: rad_declare_shape_generator, RadShapeGenBatch (RadBatch::sgen_b) and
  RadArchProbe::gen_shape, with the SCOND, SSTEP, SLATENT and SQUERY passes. The layout
  fingerprint table is regenerated; out-of-tree plugins rebuild against 33
- New op point_fourier ([x | sin(x 2^j) | cos(x 2^j)], times pi on request) in libref, libavx,
  libr4d and libhalo
- A checkpoint for a model that reads no text gets a one-token vocabulary

More cards from the one image:
- stilldeadcode/radiance now carries libr3d (RDNA3: gfx11-generic, every gfx11 chip) and libhalo
  (Strix Halo: gfx1151, preferred there over libr3d) beside libr4d (gfx1201). docker/build.sh and
  the Dockerfile default to gfx1201;gfx11-generic;gfx1151
- libr3d loads only where the KFD topology lists a gfx11 card and libhalo only where it lists a
  gfx1151; a process without /dev/kfd sees neither. On an RDNA4 card, or with no card at all,
  the image therefore behaves exactly as before, and rad-convert lays weights out as before
- libhalo and libr3d now declare gemm_nt_q's w_rb, and libhalo gram_accum's upper, as libr4d
  does. Before, any build carrying them refused both at load ("9 parameters vs 8"), so a build
  for Strix Halo or RDNA3 had no device kernel library
- libhalo does not yet have every op libr4d added after it was ported (the IQR rows, Pixtral and
  Ministral rope, the tree-attention and DFlash-tree rows, among others); halo_parity lists them
  and is left out of the image's test stage until they are ported

Fixed -- container and checkpoint parsing:
- A .rad expert-1 entry inside or before expert 0 is refused; a vocab section whose count names
  an array at offset 0 is refused rather than read from the file header; offset checks no longer
  wrap; header tables must sit on their element alignment
- An imatrix array of arrays (unbounded recursion) and a safetensors header naming a tensor twice
  are refused; a failed RadWriter undo says the container is damaged; a tune cache measured on
  another machine is refused, as its format contract says

Fixed -- plugins:
- Two plugins declaring one op with different parameter roles are refused; before, the core
  applied the first one's chunk/capacity roles to the other's rows
- Null tables behind nonzero counts, unknown roles, keyless parameters or constraints and more
  operands than an issue carries are refused by name at load; on the host backend device rows are
  dropped even when no fat binary was registered; rad-schemas checks the ABI layout fingerprint as
  the engine does

Fixed -- device:
- Stream slots are recycled under a new generation: before, 1024 stream create/destroy cycles
  (LoRA loads, lanes, uplinks) made every later rad_stream_create fail
- A stream whose drain fails keeps its queue and kernarg ring instead of freeing them under the
  card; the kernarg ring no longer leaks when its access grant fails; a block over 1024 work-items
  is refused
- rad_dev_free takes the allocation off the ledger the pin-cap check reads; the host backend
  charges pages to the card the range was reserved for

Fixed -- engine and server:
- Two NDEBUG-only asserts (runtime-window totals, ring blocks per group) are refusals; a
  plugin-declared lcm past int64 saturates so the quantum check refuses it; every share view rect
  and part span is bounded by its entry
- Video: the timestep regions hold the refine rungs a schedule appends, a zero-frame encode is
  refused, /v1/videos bounds each side before the area product, and a realtime session needs a
  clip length to cut a turn at

Fixed -- kernels and quantisation:
- A trellis run shorter than a state's codes (tcq_rows=1, or N % tcq_rows == 1) read its seam
  out of bounds; the encoder now refuses it as the decoder does, and tcq_rows below one state is
  refused at parse
- qsa_tail_store bounds its slot index by the state plane (libr4d and libhalo); paged attention
  refuses kv_heads <= 0; libavx row_amax skips a NaN as libref does

Fixed -- tools:
- pad_tp.py no longer runs cp through a shell with shard names from the checkpoint's index
  (quote injection, path traversal): names must be bare file names
- ops_doc_check.sh runs under mawk (Ubuntu's awk); rad-kbench --max-cases/--max-bytes are checked
  integers; oot_plugins fails unless the installed replay passed a case and failed none

Thanks to @RikshaDriver, @keptn42, @mici81 and @gostar.
2026-11-02 18:35:02 +01:00
keptn42 cfa6a668f6 deploy/compose, README: Gemma 4 31B w5 on two cards 2026-11-01 21:00:22 +01:00
keptn42 7892524801 gemma4_bf16: fused junctions and the prefill overlap on the i8a8, a4 and w5 grids
The residual junctions take the `_i8g` twins where the linear after them reads quant_act_i8g's
pair, so the prefill overlap runs on these trunks too. An a4 or w5 linear reads an f16 copy of
its input up to 64 rows: in such a step its junction also writes the bf16 norm output into the
linear's input row, where the unfused norm would, and the cast and w4a16_asym / w5a16 run as
before; the feed-forward keeps gelu_mul there. At four ranks the all-reduce is issued apart.

arch_test: the 31B on the three grids at one, two and four ranks -- the junctions, the decode
band's bf16 row, the same GEMMs and casts as the unfused step, the slices against the whole
step, codes and scales of every int8 pair on the same rows -- and the E4B form.
2026-11-01 21:00:22 +01:00
keptn42 b55791b398 libr4d: rmsnorm_quant_i8g, gelu_mul_quant_i8g and ar_rmsnorm_quant_i8g -- the junctions at quant_act_i8g's grid
The norm junction (post-norm, residual add, scalar, norm), the gelu product and the two-rank
all-reduce junction with quant_act_i8g's quantiser in place of quant_act_i8's: row-major int8
codes and an f32 scale per (row, 128 columns), what gemm_nt_q reads at i8a8, w4a8i8_asym and
w5a8i8. The kernels are rmsnorm_quant_i8's and gelu_mul_quant_i8's; only the epilogue over the
staged bf16 row differs (r4d_q8.h, q8_row_i8g: quant_act_i8g's mapping and rule), so each is
byte-identical to its chain ending in quant_act_i8g. out_bf16 may be x's own buffer. No
four-rank form: a four-rank caller finds no row and issues the all-reduce apart.

r4d_selftest: rmsnorm_quant_i8g, gelu_mul_quant_i8g and ar_rmsnorm_quant_i8g (two cards) against
their chains, the junction also with out_bf16 over x.
2026-11-01 21:00:22 +01:00
keptn42 141212dd88 gemma4_bf16: asymmetric int5 linears (w5a8i8 and w5a16 over a scale per 128)
a4 at five bits: u5 codes, a u8 zero point (0..31) and an f16 scale per [1 x 128] (libquant
`codes=u5 zero=u8 group=128 scale=f16`), ParoQuant int5's grid with no rotation. Read by w5a8i8
over quant_act_i8g's per-(row, 128) int8 activation above 64 rows and by w5a16 over the input cast
to f16 up to 64, as a4 reads w4a8i8_asym and w4a16_asym; q|k|v stay one GEMM. The views, row parts
and column cuts are a4's.

arch_test: the 31B form on both asymmetric grids at one and two ranks.
2026-11-01 21:00:22 +01:00
Constantin b264e9bd0c Scale the prefill softmax by row, not by wave
The h256 prefill online-softmax branch must remain wave-uniform, but the
previous branch let one row's growth vote make every row update its reference
maximum. A row's rounding could therefore depend on which other rows shared
the launch.

Keep the branch uniform and make each row update only when its own cross-half
maximum exceeds its own `m_ref + PGROW`. Rows below threshold retain `m_ref`.
This fixes row-coupled rescaling; it does not claim full-model bitwise
invariance across chunk sizes, since other shape-dependent paths remain.

The dedicated regression selector is `--case attn_prefill_rows` (exact match;
`--case rows` is not recognized). The older kernel-name selector runs the
regression only for that named GQA row; rerunning it for GQA4 also passes the
row checks. Three launch pairs run on six BF16 head-256 rows: GQA 2/4/6/8/12
and GQA6 with 4-token pages (18 assertions).
Against v1.15.1, 17/18 assertions failed; with this change 18/18 pass
bit-identically. For Spark GQA4, the baseline 58/128 pair differs in
588/118,784 elements (max abs 0.00195). Although this implementation file is
named `gqa6`, the parameterized body is included by the other head-256 GQA
wrappers too.

Controlled 917-token Spark BF16 rerun (same prompt, binary, model, TP1, BF16
KV, no prefix cache; only libr4d changed): chunk 128 vs 1024 kept top token 198
and all 20 candidates in common before and after. Maximum shared top-20
log-probability delta was 0.23717 on v1.15.1 and 0.28474 with this patch.
This example does not improve; it is included to avoid claiming general chunk
invariance. The earlier raw full-vocabulary pre-fix result (131,070/131,072
logits changed, max abs 0.46925) has no matching post-fix capture; the paired
API top-20 comparison is the comparable result.

On a separate 32-document, 31,391-position BF16 evaluation, chunk-1024 vs
chunk-128 reference achieved 99.49% top-1 agreement (31,231/31,391): 160
positions still choose a different top token between chunk shapes, not against
external ground truth. Mean KL was 0.000879, median 1.29e-5, p99 0.00462,
p99.9 0.10119, max 3.2961. The pre-fix result on this exact set was not
measured. At the separately
investigated scored row 461 (document 20, token position 477), prefix replay's
recorded top token 62594 was replaced by 2561 before the fix; after it, token
62594 was restored with a 0.184-nat top-token log-probability gap. That
0.184 is not a full-set KL, and the 3.296 maximum comes from the separate
31,391-position evaluation.

Fast CTest: 141/141. Full card selftest still has one unrelated
`hc_read_e4m3` prefill-tile failure, reproducible on untouched v1.15.1. No
throughput improvement is claimed or measured.
2026-11-01 20:59:44 +01:00
mici81andClaude Opus 5.5 55da38afbd libr4d: the norms' lane sum issues its reads eight at a time
1.15's kR4dSumLanes partition folds a row's sum of squares over 256 lanes
whatever the block width, so a 1024-thread decode block reads it back with a
quarter of its threads, one read at a time: a Gemma 3 sandwich norm re-reads
the 5376-wide row it has just written twice, 21 dependent loads a lane each.
TranslateGemma 27B lost 5 % of its decode (four streams 225.0 / 227.2 tok/s a
stream against 238.2 / 239.7 on 1.14; ar_rmsnorm_post_quant_fp8 3.1 -> 5.1 ms
a step under --profile-ops).

r4d_lanes_sumsq (r4d_common.h) keeps the partition and the order of the adds
and only batches the reads, eight before their adds; libr4d is built
-ffp-contract=off, so every bit stays the same (greedy Qwen 300/300 x2 and
TranslateGemma 6/6 identical to the merge without it). Used by both
lanes_sumsq copies and rmsnorm_body's two loops. TranslateGemma back to
238.9 / 239.3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 20:57:42 +01:00
keptn42 b34b1ac844 deploy/compose, README: Gemma 4 31B i8g and heretic-ara-i8g 2026-11-01 20:56:46 +01:00
Asim Siddiqui 34c52ebe96 libr3d: the RDNA3 (gfx11) wave-matrix kernel plugin
A self-contained HIP kernel plugin for gfx11 (RDNA3) that exposes the
libref-declared ops as device rows the engine can tune and dispatch:

  * GEMMs (bf16, f16, int8-activation, vocab) retiled to 16x128 on the
    wave-matrix (WMMA) builtins. The retile removes the 8x wave
    redundancy of the naive tile and stages the activation once per
    16x128 block; the 16-row and 64-row forms share the stage. The k-walk
    double-buffers the 128-deep tile (the next tile stages while the
    current one multiplies), on the m64 and tiled forms.
  * Quantised GEMMs: fp8-e4m3 x e4m3 (tiled and ALU), mxfp4 x a8, w2a8,
    w4a16, w5a16, w8a8 (the prefill heights 17..127 on the wave matrix),
    and the gated (swiglu) form. E4M3 decodes exactly to f16 through a
    256-entry LDS table; the WMMA fragments bit-cast the staged halfs
    (a uint16-to-_Float16 assignment is a value conversion, not a
    reinterpret).
  * Half-precision-accumulate arms (acc = 1) on the m64 wave matrix:
    the f16/bf16 16x16x16 builtins with the compile-time opsel half
    select.
  * Grouped MoE GEMMs (bf16, e4m3 with F32 block scales, mxfp4a8, w4a8),
    retiled the same way, over the run-walk / gather structure.
  * Normalisation (layernorm / rmsnorm) and the quantisation ops.
  * GDN linear-attention, the QSA/KV state ops, and the MoE
    router/scatter/gather family (router_topk_scatter, router_sigmoid_topk
    with the correction bias, moe_gather, moe_gather_inv; the top-k
    router runs to n_expert 512).

Every row implements an op libref declares; the selector (tune) picks
the implementation and the NOTUNE rows carry the untuned default.
Selftest-clean (121 rows, schema + finiteness); values verified against
CPU references per op.
2026-11-01 20:56:25 +01:00
Deadcode 203064b487 radiance 1.15.1
Fixed:
- A preempted prefill no longer parks the engine: once its wait is overdue the scheduler
  reclaims prefix-cache blocks over several rounds, returns leaked state slots when nothing is
  running, preempts only decoding requests it is ahead of (never one still building its prompt),
  and fails a recompute an empty pool cannot hold instead of waiting forever. Before, concurrent
  long requests that filled the KV pool could preempt every runner and leave all of them waiting
  with nothing running while /health answered 200 (#360)
- A scored request's candidate list is capped at 4096 ids, and a step whose pinned scored rows
  cannot be allocated cancels those requests instead of stopping the engine
- qwen4exp: the pinned copy of the window bounds is freed when a rank's model is re-declared

Server hardening:
- Keyless loopback-only routes need a loopback socket, a matching Origin and a Host naming the
  loopback or --allow-host; a TLS proxy on loopback no longer makes every client local
- --trusted-proxy CIDR (repeatable): X-Forwarded-For from a vouched network names the caller in
  the logs; authority still reads the socket
- A 401 closes the connection; drains of unread bodies are bounded; multipart form fields and
  buffered Anthropic tool-call arguments are parsed under the same size and depth gates as JSON
- 500s carry a generic message on the wire (the reason stays in the log), client text in log lines
  is sanitised, and a security-relevant header sent twice is refused
- An empty --api-key value stays a startup error (now pinned by a test)
- hfget.sh vets a repo listing's file names before fetching and hashes each LFS download against
  its oid
- cpp-httplib v0.64.0; vendor/SHA256SUMS pins every vendored file (ctest vendor_sums), and
  .woodpecker.yml runs the host suite on every push

Thanks to @baKon (#360) and @fl0l0u.
2026-10-31 09:28:19 +01:00
fl0l0u b6acbd69e4 server: name the caller a vouched proxy carried, without arming the guard
An operator running radiance behind a reverse proxy sees one address in
every log line: the proxy's. --trusted-proxy CIDR (repeatable) vouches
for the networks whose sockets may say who they carried. An
X-Forwarded-For from inside a vouched network is walked from the right:
vouched hops are skipped, the first address no vouched CIDR covers is
the caller, a chain of only vouched hops ends at its leftmost, and
anything else falls back to the socket. From an unvouched socket the
header names no one, because it has not been vouched for.

Attribution is not authority, and the split that keeps them apart is
mechanical. HttpRequest carries `peer`, the attributed caller, sanitized
where it is built because a named address arrives in a header and the
log keeps no client text otherwise -- and `raw_peer`, the socket as the
kernel saw it, which is now the only address peer_is_loopback() reads.
A proxy on loopback therefore hands the keyless loopback-only routes to
none of its clients; it only names them where the proxy used to stand.
transport_test pins both halves: the walk at the unit level, and over a
real socket that a vouched proxy plus X-Forwarded-For leaves the
loopback guard answering 200 and the cross-origin 403 untouched.

httplib's own set_trusted_proxies -- new this side of the vendor bump --
is deliberately unarmed. It rewrites req.remote_addr, the very field the
guards would read as the socket peer, so one over-broad vouched network
would move the guard rather than the log line. Radiance reads the header
itself, and ip_in_cidr refuses across families: a vouched ::ffff:0:0/96
vouches for no IPv4 socket. Config rejects anything but a numeric
network with a prefix at startup, because a typo there would silently
unvouch a proxy; the refusals the transport answers before the router
log the attributed caller too, so the audit trail stays one line per
request whoever the socket belongs to.
2026-10-31 07:50:43 +01:00
fl0l0u 40e1b3073b vendor: cpp-httplib v0.46.1 -> v0.64.0 -- the drain patch retires to one line
Eighteen upstream releases, taken the way the lift was taken: the
split pair llama.cpp now carries (1ab23c33b), against the cpp-httplib
v0.64.0 tag. The vendored pair before this commit was byte-identical
to the old base plus patch 0022 -- re-checked against the pinned lift
commit, not taken on faith.

0022 was written because upstream's keep-alive drain could be paced
one byte per socket timeout forever, and because a refused request's
unread body had no reason to be drained at all. v0.64.0 does both of
those itself: every 4xx/5xx response now carries Connection: close,
a scope_exit in write_response closes the socket when it sees that
option, the drain is skipped for any response committed to close, and
a drain that does run is bounded by a 256 KB cap, the connection's
read timeout as a total, and an immediate close for a part-read body.
The old patch applied nowhere, and mostly needed to be nothing.

What one line is still owed: the library bounds the drain's time only
by the connection's read timeout -- the same knob that bounds a whole
request's reads, uploads included, so lowering it would cap uploads
too. The reworked patch gives the drain a five-second budget of its
own. transport_test's cases for the refusal and the stalled drain are
unchanged: they pin the behavior, whoever in the tree implements it.

Also new in this window and watched with interest: set_trusted_proxies
arrives with real IP matching -- the seam a coming commit wires.
Manifest regenerated; vendor_sums green.
2026-10-31 07:50:43 +01:00
fl0l0u 3decb3ca13 qwen4exp: the pinned window copy survives its model's reset
declare() resets the rank's Model with Model{} on every re-declare --
every rebuild, every sizing probe, every test case -- and the reset
drops pipe_cu_h, the once-made pinned copy of the window bounds, on the
floor: the pointer is overwritten and the pin leaks. arch_test flags it
under the asan tier (qsa_a_widened_step...: 8 bytes, calloc,
pipe_bounds), and the leak grows one pin per re-declare of a rank.

Free the copy where it is dropped. The copy is read only by a widened
step's memcpys, and no step runs across a declare.
2026-10-31 07:50:43 +01:00
fl0l0u 8e65e1a302 ci+vendor: pin the lifted tree by hash, and run the suite on every push
Two standing gaps in how this tree is guarded.

vendor/ records what every lifted file is and what we changed, in prose
-- prose nothing enforces. vendor/SHA256SUMS is the mechanical half:
all 73 files under vendor/, the lifts, the patch series and the record
itself, hashed; tests/vendor_sums.sh recomputes both directions -- a
file whose content drifted from its record, and a file that arrived
without being recorded -- and fails the suite (ctest: vendor_sums, in
the fast tier). An unrecorded change to a lifted dependency now has to
survive being a committed manifest update to ship, instead of slipping
through a rebase the way 33108e4's silent reverts did through this
branch's history.

And no CI ran the suite at all. .woodpecker.yml (Codeberg CI) builds
CPU-only with the media codecs present and runs the host preset --
everything but the gpu and oot tiers. The runner is the current Ubuntu
LTS deliberately: the mp4 writer binds FFmpeg's >= 7 AVIO callbacks and
24.04's 6.1 does not compile it.

Rehearsed on a native Ubuntu 26.04 box -- the same gcc 15.2 the image
carries -- the host preset fails eight cases on this branch, and the
same eight on plain upstream/main: arch, chatparse, engine_e2e, two
gbnf shards, place, quant_ggml and avx_check. Pre-existing under gcc
15, partly machine-dependent (avx_check compares kernels op by op on
the CPU it finds, and the gbnf shards flip under load); this branch
adds none of them. CI's first red is upstream's to see.
2026-10-31 07:50:43 +01:00
fl0l0u 1577854d00 hfget+deploy: fetch a repo on verified claims, and run with a key argv cannot show
The --model repo-id path trusts the hub with the machine's filesystem and
the container runs with the kernel's door off. Both stop here.

hfget.sh trusted a listing's file names to be names: an absolute path or
a .. segment wrote wherever the destination's owner could write, and a
name shadowing .hfget-manifest taught the next run whatever it liked. A
listing is now vetted whole before anything is fetched -- absolute
paths, .. segments, control characters (a tab splices one entry into two
fields), names of hfget's own manifest -- and a child refuses a path
that would escape anyway. Silent skipping was the alternative, and it
leaves a directory that reads as complete and is not.

And the content key was the hub's claim, never checked: an LFS file was
kept for its size and its claimed oid recorded without ever hashing the
download, so a swapped file of equal length -- or a spliced resume at
any length -- passed forever after. The download is hashed on arrival
and kept only when it matches the claimed sha256; a mismatch deletes the
file, and the manifest now certifies verified content.

--model-revision REV fetches at a branch, tag, sha or refs/pr/N instead
of the moving main: without it a restart can serve weights nobody
reviewed, and the guide now says to name one.

--api-key-env NAME reads the key from the environment, where only the
process and root can reach it, not the command line where every process
on the host reads it in ps; an unset or empty variable refuses startup
exactly like an empty --api-key. The compose files carry the key
through environment: now -- the fail-closed :? guard moves with it --
across all 52 model files.

And the containers' seccomp=unconfined has a way out: Docker's default
profile, plus exactly the calls that forced the escape -- io_uring for
the n-gram table, mbind/set_mempolicy/get_mempolicy for ROCm's NUMA
binding -- is shipped as seccomp-radiance.json and selected through
RADIANCE_SECCOMP; the default stays unconfined until each operator
audits their own card stack. Verified: under the profile io_uring_setup
and set_mempolicy behave as under unconfined and a non-listed syscall
earns EPERM.

hf_model_test: the escape-listing refusal, the oid verify (bad rejected
and deleted, good certified), the pinned revision fetched -- against a
fake curl for a hub. config_test: --api-key-env fails closed unset,
reads the key set. ASan+UBSan: config/diag/hf_model/server/transport/
wire/lifecycle, 8/8.
2026-10-31 07:50:43 +01:00
fl0l0u ad3f03dbc6 server: no internals on the wire, no client text in the log, no paths for strangers
Four ways the server told more about itself than the caller earned.

The exception handler logged e.what() sanitized and then put the raw
string on the wire: a 500 whose message echoes request text is a
reflection point, and one that quotes how a handler broke names the
server's internals to whoever prodded it. The wire gets the generic
sentence now; the reason stays in the log. The realtime and speech
sockets caught their session's exception the same way -- raw what() to
the log and onto the client's error event -- and follow. Their WebSocket
wrapper logged e.what() and the request path unsanitized: the path is
fully client text, and a client that can put CRLF and an escape sequence
into a log line can forge the next one.

A security-relevant header sent twice is a request built to be read two
ways: this server reads the first copy, a proxy in front may read the
last or join them, and whichever copy the disagreement lands on, the
attacker picked it. Host, Authorization, X-Api-Key and Origin are
refused whole at 400 before either reader -- the key gate included --
even when every copy carries a valid key. The lookup is
case-insensitive, so an Authorization beside an authorization counts.

And the model card's `root` is a path on this machine, served to anyone
/v1/models admits. Keyless, it now belongs to the local operator, the
rule /diagnostics and the LoRA admin already follow; with a key it
travels with the key.

server_test: the_models_root_path_follows_the_key. transport_test:
a_duplicated_security_header_is_refused. ASan+UBSan: server/transport/
wire/stream/speech/speech_stream/dashboard, 7/7.
2026-10-31 07:50:43 +01:00
fl0l0u 1c967b2f14 sched+engine: keep a scored request's size from reaching the pinned pool
A scored request asks the engine for the logits of chosen candidate ids
at its prompt's last position (Request::token_scores). Three places
where that readout's memory was someone else's decision:

The candidate list was bounded by value, never by count, and the count
is what a scored step pays for: the step stages the union of every
staged request's candidates as hidden and table rows in one pinned host
buffer, before anything is admitted or accounted. One request naming a
million ids -- any caller of the raw request seam -- is a multi-gigabyte
pinned allocation the box either loses or dies on. add_locked caps the
list at 4096, orders above what a decision request names (its prompt's
written answers, a few dozen), and says so in the refusal.

And when the pinned allocation is lost anyway -- the cap bounds one
request's rows, not the batch's union, and the pool can be low for
reasons of its own -- stage_scored_rows returned E_NOMEM into the step
loop's fail path: the whole engine stopped, every connection with it.
It cancels the scored requests instead, on the step loop's existing
deferred-cancel vector the sampler's grammar failures already use: a
request whose scores the box cannot hold is that request's failure. No
alloc-failure seam exists to test the branch directly; its cancel path
is the sampler stage's, applied at the same join.

And declare_scores now refuses a head table shorter than the
vocabulary: the scored readout indexes it by token id, the scheduler
bounds candidate ids by meta.n_vocab, and a table a few thousand rows
short turns the last block of the vocabulary into a read off the end of
a weight -- a device fault, not a refusal. Padding past the vocabulary
reads fine and stays fine.

sched_test: a_scored_request_names_at_most_the_candidate_cap.
build_test: declare_scores_wants_a_table_that_covers_the_vocabulary.
ASan+UBSan: sched/build/server/systemone/config/diag, 6/6.
2026-10-31 07:50:43 +01:00
fl0l0u 5f7244da4d server: bound what an unauthenticated socket can make the transport hold
Three ways a client spent the server's patience or memory without ever
being admitted:

The gate's 401 answers before any handler sees the request, so its body
sits unread on a keep-alive socket, and httplib's anti-smuggling drain
will wait for it: one byte per read timeout paces a whole worker, at the
pacing client's chosen rate. The refusal now closes the connection
instead, says so on the response, and buries the body with the socket --
which is also what makes draining a refusal pointless.

A drain that does have a purpose -- a framed body on a request the
router answered without reading it -- inherits the stream's 30 s read
wait per packet gap and no total bound at all. It keeps both waits now:
five seconds per gap (the stream's own set_read_timeout, the same knob
the WebSocket upgrade uses) and five in total (a deadline the discard
provider checks), then the connection dies and the timeout is restored
for whatever the connection still has coming.

And bodies. The per-request cap bounds one body and no sum, every byte
of a body is buffered before parse, admission or any accounting sees
it, and a few hundred concurrent large POSTs is an OOM that reaches the
engine before any refusal does. read_and_bridge now holds every buffered
byte against a transport-wide budget and answers 429 with Retry-After to
the newcomer the budget has no room for; the reservation releases on
every exit, including the peer vanishing mid-body. The budget defaults
to eight bodies at the per-request cap and moves through
ServerOptions::max_inflight_body_bytes.

Vendor: the two httplib hunks are recorded as patches/0022, and
UPSTREAM's "no file content differs" for the pair is replaced with what
the split actually is and what is now edited in it.

transport_test: a_refusal_closes_the_connection,
a_stalled_drain_dies_on_its_deadline, the_inflight_body_budget. ASan+UBSan:
transport/wire/lifecycle/server/config/diag/dashboard, 7/7.
2026-10-31 07:50:43 +01:00
fl0l0u ec53bce5dc server: stop treating the loopback socket as identity
Three guards read a loopback peer plus a matching Origin as "this is
the machine's operator". Two real topologies forge exactly that:

DNS rebinding hands a hostile page its victim's own browser, so the
peer IS loopback, and the page is same-origin with the server, so the
Origin/Host compare stays silent. Only the Host still says which name
the client asked for, and the attacker's domain cannot be made to read
as the loopback.

The documented TLS-proxy topology puts every remote client behind a
loopback socket, and a non-browser client sends no Origin at all; the
proxy passes the public Host, which the new check refuses.

Server::local_operator now guards the keyless routes: the socket, the
Origin, and a Host naming the loopback, --allow-host, or a concrete
bind address. GET /admin/control-vector takes the guard POST already
had, placed before the 404-that-means-no-vector so a remote page can
probe neither; keyless DELETE /sessions and /reset_prefix_cache --
which destroy other clients' cached conversations -- answer the
machine only. --allow-host (repeatable) admits names an operator
reaches the box by from the box itself.

A local user at the console stays admitted; nothing about a key-set
server changes. GUIDE 6.6 states the new posture.
2026-10-31 07:50:43 +01:00
fl0l0u d54f3b9e6e server: bound the last unbounded parses of untrusted text
Three ways in, each ending in a parse that bounds neither what it
builds nor how deep it nests:

videos.cpp read its multipart form fields with the raw parser, so a
512 MiB field of brackets died at the tree's teardown; the same file's
JSON path was bounded, so the form path now shares its gate, and a
field over budget or over depth reads as a bad parse (a form test pins
both refusals and a well-formed field).

Anthropic's buffered body parsed the model's tool-call arguments
directly; the streaming path already scans them with json_complete,
whose depth cap keeps a cooperating model from stack-killing the
worker, and the buffered body now passes the same gate, reading too
deep as an empty input.

The image decoders checked the container header's dimensions against
the pixel cap but converted whatever the bitstream actually decoded;
a container whose SPS disagrees with its header slipped through. Both
now re-check the decoded frame, as the video path already does. The
re-check is inside RAD_HAVE_FFMPEG and compiles with every FFmpeg
build; the media-less container proves the two server changes.
2026-10-31 07:50:43 +01:00
fl0l0u 546f0c2047 config: pin the empty --api-key refusal with a test
d773992 restored the refusal 33108e4 had silently taken back, so the
behavior is main's again. What no branch carried was a test. The hunk
was written once, merged, and deleted by a stale rebase with nothing
noticing until an audit read the parser; an empty --api-key value --
a unit file whose $RADIANCE_API_KEY was never set -- must stay a
startup error, so a config_test case says so, and the next silent
overwrite trips a test instead of an audit.
2026-10-31 07:50:43 +01:00
baKon 9560780bfa sched: a preempted prefill reclaims cache and leaked state slots before it waits
The whole-recompute gate refused a preempted request forever when the pool held only cache entries, and an empty running set left a leaked state slot unreclaimed. Reclaim the cache over several rounds, release idle state slots when nothing is running, and admit the overdue waiter if it can ever fit. A prefill is never a victim while a decoder is running; tests cover the deadlock, the leaked slot, and the lost KV sequence.
2026-10-30 21:32:03 -05:00
Deadcode 9ed3ef7a7b radiance 1.15.0
New models and formats:
- IQR for Qwen3.8-27B: weights on the int8 grid under GPTQ, a trellis down each GPTQ column
  (IQR-V2), and IQR-V3, a computed trellis code under one scale a row, kept at its codes' width in
  VRAM and decoded in the GEMM; 15 IQR-V3 recipes from ~2 to ~7 bits a weight
  (data/recipes/q38-27b-*-v3.recipe, docs/IQR.md)
- libhalo: a kernel library for Strix Halo (gfx1151), preferred there over libr3d
- Nemotron 3.5 Embed 1B and 8B (nemotron35_embed): text and image embeddings through a Pixtral
  tower, on the card and on the CPU
- Nemotron 3.5 Rerank 8B
- /v1/systemone: Cloudflare's clef and clef-flash, Convai Innovations' Laya and Mica beside
  LiquidAI d1; scored steps read the candidates' logits from the head table with no lm_head pass
- LFM2's 8-bit trunk: block-fp8 or int8 linears with the fused producers, and the d1-3B recipe
- DeepSeek-V4.1's reply format with DSML tool calls and typed argument tags

Weights on the drive:
- The file tier reads only the experts the pass routes rows to; the draft head's weights stay in
  the host pool
- A hot VRAM cache for routed experts read off the drive, reads deposited straight into free host
  pool slots, and copyless evictions; the file tier's counters are now ssd_*
- GLM-5 Next shards its routed experts by expert, not by width, so they can live on the drive
- The stall watch counts drive reads as progress, and the DMA lane's room check reads the lane's
  own completion fence

Quantisation tooling:
- --calib-corpus, --calib-dir and --calib-layers record each linear's input Hessian; beside
  --kld-record the reference's own run records them
- --kld-top N records a sparse KL reference (the N most likely tokens and the tail's mass)
- GPTQ in a third of the time with the same codes, trellis GPTQ on the card, vector codebooks
  with coordinate descent, and rad-convert --reuse repeated, each container supplying what the
  earlier ones lack

Speculation:
- Prompt lookup alone (--spec-ngram K, --spec-ngram-min/-max): each sequence keeps an index of its
  n-grams, and a proposal is verified only when its measured step cost says it pays;
  --draft-window adaptive follows it

Speed:
- IQR decode: the narrow tile splits K for four times the int8 tile's waves and folds each 128-K
  block once; at 8 tokens down and the output projections run in 0.61-0.82x and 0.70-0.92x FP8's
  time (2-6 bits); IQ6R-S-V3 with its DFlash2 drafter steps in 26.3 ms at TP2, against 29.4 ms
  before and FP8's 27.3
- Qwen MXFP4 feed-forward: the gated fold up to 16 rows, not 8
- libr4d: the gated prefill fold, the short-prompt split row, and the rows forms of rmsnorm and
  rope; KLATE again for the head-256 gqa6 paged prefill; gram_accum on the matrix cores

Features:
- /health, /v1/health and /ping answer 503 with "status": "stuck" once the device has advanced
  nothing for a minute or a queue has faulted, so a supervisor can restart a wedged server (#356)
- --image-gen-max-pixels and --image-gen-max-refs size an image generator's buffers (#344)
- The startup report lists only the options not at their default, with a count; -v lists all
  (#250)
- --preempt-wait-ms bounds how long a preempted prefill waits for its whole-recompute room
- --placement layer_offload spills dense layers so one --max-model-len sequence fits
- Startup refuses amdgpu with CWSR off and says how to fix it;
  --proceed-with-incompatible-configuration starts anyway under an UNSUPPORTED banner

Fixes:
- The n-gram read-ahead hands each row to the reader once and reads only as far ahead as the row
  cache holds, and pauses while decode reads: about one drive read a row instead of two (#355)
- A file-tier window reads each of its runs once, not once a run per run
- The decode split law's verify floor is bounded by the batch's workgroups: max_seqs 256 no longer
  declares 64x the scratch (#342)
- A prefetch DMA list's mark stays out of the signal pool until the engine has read it, and a
  prefill stage copies only the blocks its own tables name (#343)
- The split-KV row sum is read with fetch-inactive (#328)
- LFM2 on the host backend: libref and libavx serve the row-form ops it declares (#348)
- The preempted-prefill gate skips a KV group that holds no blocks (#352)
- Every request entry point bounded, gated and sanitised (JSON depth, invalid UTF-8, control bytes
  in the log, the dashboard's CSP, cross-origin browsers on the loopback-only routes); a prompt id
  outside the vocabulary refused at admission; --api-key "" refused at startup
- The telemetry the HTTP thread reads is atomic
- An RMS norm row no longer depends on how many rows its launch carries; prefill attention's
  rescale is decided by live rows only
- A --kld-record prefill chunk that finishes no sequence gets its logits on a tied-head model
- A kernel's lazily made counter block is zeroed outside the lock other ranks take (a TP2 first-step
  hang)

Changes: Plugin ABI 32. Every plugin exports a layout fingerprint of the ABI structs and the loader
refuses a plugin without it or with another (#302), so out-of-tree plugins must be rebuilt.
Appended: RadBuildCtx calib_* and gen_max_*, RadArchProbe gen_max_*, RadBatch score_only and
plugin_words, RadDeviceProps::unified, RadChatFormat arg_json_value_prefix.
2026-10-30 22:01:01 +01:00
overchop 8da043c246 place: the caching layer -- hot VRAM cache, deposits, copyless relabels
Routing-aware reads leave a routed expert's bytes on the drive when the
pass routes nothing to it, but the reads that DO happen still have two
wasteful fates: they land in a per-pass buffer thrown away at the next
layer, and they cross the link even when the same bytes already sit in a
host pool slot that just went cold. This commit gives both bytes
somewhere to stay.

The hot VRAM cache: a routed expert whose read heat ranks past the
admission bar lands in a shadow slab slot and stays there. The slot is
its address from then on, until heat evicts it -- eviction is a copyless
relabel (back to Tier::SSD, publish null); the container is ground
truth. The planner budgets the shadow slots for it (per-class on_disk
count); the mover admits (Kind::Admit), evicts, and retires the
admissions.

Deposits: a free pool slot takes the O_DIRECT read directly -- the
read's destination IS the slot -- and the unit becomes a pool unit the
GEMM reads zero-copy, with heat promoting it at PCIe speed later. Its
demotion is a copyless drop (the slot still holds the bytes). A full
pool evicts its coldest unrouted unit by relabel, copyless, and the
freed slot feeds the next deposit.

The counters follow the traffic: the file stager's family is renamed
file_* -> ssd_* (ssd_layers, ssd_units, ssd_read_bytes, ssd_preads,
ssd_read_ns, ssd_wait_ns) beside the existing ssd_reads/ssd_bytes, and
the new legs are counted (ssd_staging_bytes, ssd_promotions and
ssd_promoted_bytes, ssd_deposits and ssd_deposit_bytes, pool_evictions).
The dashboard's expert plane gains the matching staging, promotions and
deposits rows, and --weights-disk-tier's help text names the tier.

Measured on GLM-5.3-Flash TP2 (2x Radeon R9700), 250-token essay at
temp 0: 5.49 tok/s at ~104 GiB of SSD reads per run, against main's
2.05 tok/s at ~378 GiB.

Assisted-by: GLM-5.3-Flash
2026-10-30 15:02:09 +01:00
overchop 9efdd00c4c place: routing-aware file-tier reads
The file tier read every file-tier unit of a routed layer whether or not
the router sent rows to it. A deep layer keeps whole experts on the drive
(288 per world), but a pass routes rows to a handful of them: the read
volume was ~18x what the router justified, and the engine streamed
~378 GiB from the SSD per run at 2.05 tok/s (GLM-5.3-Flash, TP2).

The layer's router has run by the time the stager triggers -- the
trigger is the layer's first expert op -- so the pass's route counts are
already on the device. Ctx::route_counts_device exposes them; the file
stager hands them to Mover::stage_file_units, and an expert counted
zero, which has no sorted rows and no GEMM run naming it, is left on the
drive: its weights are not read at all. Its table entries are published
at a valid dummy address (the calm region) for the pass and nulled again
with the staged units, because the kernels still issue the layer's table
and a null entry fails the step. Published even when EVERY unit of the
layer is skipped -- a decode step can route nothing to a layer.

The drafter's own weights (the "mtp." namespace) run on every draft pass
of every decode step, more often than anything a profile could rank, so
the planner pins them in the host pool ahead of everything ranked
(MoveUnit::draft_head) instead of letting the expert fill push them to
the file tier every step.

Read extents are also clamped to the container file's size, so a
truncated container fails a read loudly instead of reading past EOF.

Measured on GLM-5.3-Flash TP2 (2x Radeon R9700), 250-token essay at
temp 0: 3.4-3.6 tok/s where main gives 1.42 on the same prompt.

Assisted-by: GLM-5.3-Flash
2026-10-30 15:02:09 +01:00
overchop 9647b84ee0 glm5next: expert parallelism -- experts become file-direct
Main's glm5next width-shards the routed experts unconditionally
(GlmTp::expert_width, ff_lo/ff_hi): an expert's stored form is a shard
across ranks, so --weights-disk-tier refuses it and a 151 GiB expert set
cannot leave VRAM at any pool size. The helper's expert-parallel
declaration (expert_base windows, RAD_SHARD_NONE, no ff spans) already
exists upstream -- qwen4exp uses it -- so this retargets glm5next onto it:
each rank owns 288/world whole experts, the routed arm's buffers
full-width (FE), the shared expert still width-sharded, world 1 unchanged,
and a shape probe's rank >= world clamps to rank 0's window.

Fixes the 24.78 GiB "no eligible tier" startup OOM on 2-card hosts; the
world-8 graph pin is re-recorded from the test's own pin: printout.

Assisted-by: GLM-5.3-Flash
2026-10-30 15:02:09 +01:00
overchop 6f6b5c3f78 aql: the stall watchdog is progress-aware; the DMA lane's ring completion is fenced
Main's stall watchdog samples only the queues' read indices, and the DMA
lane trusts the SDMA queue's written-back read pointer for its room check.
Both stall wrongly: a drive-paced prefill parks every queue for seconds
(one rank spins at the all-reduce while the other reads its layer off the
drive -- spurious dumps), and the SDMA engine's written-back read pointer
can stop moving while the engine runs on -- a full ring then waits forever,
wedging the startup pool fill above ~32 GiB/rank.

pread_exact counts the bytes it returns (rad::dio_progress); every O_DIRECT
read funnels through it, and read_progress adds that to the queues' read
indices: a wait that moves nothing anywhere is a hang however slow the
drives are, so the threshold is a flat 5 s and every stall report is
genuine. The main DMA lane names its lists the way the xp queue already
does -- each list ends by writing its number to a word the engine keeps
advancing (fin/ends) -- and dma_read takes the further of that fence and
the read pointer, so the room check can no longer mistake a stalled
writeback for a stalled engine. dump_dma_lanes reports the finished-list
count.

Verified on the wedge reproducer: GLM startup with a 36000 MiB pool fill,
decode with promotions, and a 13300-word drive-paced prefill -- zero
spurious dumps, the ring live throughout.

Assisted-by: GLM-5.3-Flash
2026-10-30 15:02:09 +01:00
Gaspa79 74e7fddd79 nemotron 3.5 rerank 8b implementation 2026-10-30 09:47:42 -03:00
DeadcodeandClaude Opus 5.5 d773992abc [FIX] restore the prompt vocabulary check, the empty --api-key refusal and scored steps' issue-ahead rule
33108e48 (the preempted-prefill gate's wait bound) was cut from an older main and, landing, took
back three changes that had merged before it:

- a28221eb: a prompt id outside the vocabulary is refused at admission (Scheduler::add_locked),
  never staged into a pass where the embedding gather faults the device and stops the engine; and
  its test, a_prompt_names_real_vocabulary_rows.
- b9c685a9: --api-key "" is a startup error, not a server that looks guarded and answers every
  keyless request; and the guide's lines on it and on the loopback-only routes.
- ed1e5caf: a scored row the step in flight finishes gets no step issued ahead; and its two tests,
  the non-scored one with a token left after the step in flight so that a step ahead exists (#349).

The wait bound itself, the lookup index and the rest of 33108e48 are unchanged. sched_test 176,
config_test 62 and server_test 177 cases pass.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qthwau4zwWgAaD8vZrycp1
2026-10-30 12:18:29 +01:00
mici81andClaude Opus 5.5 8df9240d65 sched: the preempted-prefill gate skips a KV group that holds no blocks
Every program carries a sentinel KV group at index 0. KVGeom reads its decl.kind 0 as RAD_KV_FULL
with block size 1, while the manager's plan for it pages nothing and owns no block. The gate
(e668d49) walked every group KVGeom calls paged, so for the sentinel it wanted the whole prompt,
one block a token, out of a pool of none: a preempted request was never readmitted. The bound on
the wait (33108e4) cannot help, since preempting running requests frees nothing in that group.
engine_e2e_test's qwen35_preemption_by_recompute_changes_no_logit hung on it (the KL recording of a
small pool: one preempted document, nothing left running); with the group skipped it passes in
0.9 s. It may also be the live request in #346 that waited 710 s with gen=0.

The gate now skips a group with no blocks (total_blocks 0), as KVManager::ensure skips a group its
plan does not page.

sched_test: a_preempted_prefill_ignores_a_kv_group_that_holds_no_blocks (a group the scheduler sees
as full and the manager as empty; the preempted request stayed Preempted after the pool emptied
before the fix). 173 cases pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 12:11:13 +01:00
mici81andClaude Opus 5.5 167595a9b4 libr4d: the split-KV row sum read with fetch-inactive (#328)
The prefill KV split (6a7824a) stores each segment's row sum under `if (h == 0)`, so only half the
wave consumes `l_i += swap16(l_i)`. A compiler may sink the exchange into that half, where
v_permlanex16 with fi = 0 reads the lane's own value for the inactive partner, and the stored sum is
then twice one half's instead of the pair's: the merge normalises by the wrong total. The decode
kernel's f32-partial path has the same shape (lrow read under `if (h == 0)` only).

swap16_fi sets fetch-inactive, so the partner's half is read whatever exec says. With every lane
active it is the same exchange. Found by sabi-noema and posted by mordae in #328; this is their
helper and prefill change, plus the decode path.

The compilers I have do not sink it: in this tree's build (ROCm 10.1) and in the published 1.14.0
libr4d.so, every split instance of the h256/gqa6 prefill kernel exchanges before the `h == 0` mask.
So the fix changes the code (op_sel:[1,0] on those exchanges, a register shuffle around them) but
not the results here, and no test here can fail without it. r4d_selftest: the h256/gqa6 prefill and
decode rows, every cache layout, 453 checks, 0 failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:39:08 +01:00
baKon 9cf8d3dad8 arch/common: DeepSeek-V4.1's reply format, DSML tool calls with typed argument tags
The checkpoint's own encoder writes an assistant turn as reasoning followed by a sectioned DSML call block, with each argument tag naming string or JSON. The template analysis cannot state those typed tags, so the format is declared as data and chatparse_test reads it back. Split from #266; no model plugin or kernels.
2026-10-30 10:23:09 +01:00
Gaspa79 94c90b17ad nemotron 3.5 implementation 2026-10-30 10:22:53 +01:00
baKon 33108e488b sched: a bound on the preempted-prefill gate's wait 2026-10-30 10:21:57 +01:00
mici81andClaude Opus 5.5 0792d86375 libr4d: the paged prefill attention h256 gqa6 asks for KLATE again
75b4c92 brought the kernel side of KLATE (tile t+1 K fetched once tile t has its scores) and set
P_OPT to (3954187 | O_KLATE) in this launcher; a later merge restored the old P_OPT line, so the
kernel code is there but Qwen3.8 prefill no longer takes it. This puts the bit back. Load order
only: the bytes are the same.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-30 10:21:34 +01:00
mici81andClaude Opus 5.5 f8e69c4825 libr4d decode split law: bound the three-wave verify floor by workgroups (#342)
49ca5ff made a three-wave verify past 16k keep at least 64 segments a sequence. The declared scratch
is the worst over every sequence count up to max_seqs, so at 256 sequences it became 64x the law's:
h256/gqa12 at max_ctx 200000 went from 7.62 to 487.5 MiB a card, and the KV pool lost that (#342:
5-8 % prefill on an expert-tiered MoE).

The floor is now min(64, 1024 / units), units = KV heads x sequences. Up to eight sequences of two
KV heads it stays 64; at 16 it is 32, at 256 two, and the declared region stays at what eight
sequences need.

Measured on 2x R9700, Qwen3.8-27B MXFP4 TP2, k6_v4, speculation 7 without the short block (every
step an 8-row verify), forced segment counts, ms a decode step:
  45k x8  64: 41.24, 32: 41.20, 16: 42.29
  45k x12 64: 57.42, 32: 57.38, 16: 59.39
  45k x16 64: 74.83, 32: 74.68, 16: 74.79
  90k x8  64: 51.79, 32: 52.02, 16: 54.42
Up to 64 segments past eight sequences changes nothing; the new floor gives x12 42 and x16 32.

r4d_selftest's split-law case pins the region at 16 sequences (100k and 32k: 32 segments) and at
256 (2); it read 64 for all three before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:16:16 +01:00
Brandon Bertelsen ec243c2a7d Merge main into laya-arch-plugin 2026-10-29 13:45:18 -04:00
Code000andPi 8df39472b6 lfm2: the 8-bit trunk -- block-fp8 linears, the fused producers, and the d1-3B recipe
Every linear of the trunk is a LinearFP8, so the container's encoding decides the
GEMM: bf16 stays `gemm_nt` exactly as before, a recipe's block E4M3 is gemm_nt_q at
fp8a8 over an activation quantised once per producer, and int8 is gemm_nt_q at
i8a8. The format is read off layer 0's first linear; a trunk mixing formats is
refused by name. The convolution, the norms and attention stay bf16.

On a block-fp8 trunk the fused producers run: rmsnorm_quant_fp8 with a fold for
each mixer's norm (the previous block's residual add included) and MlpFP8 for the
feed-forward, whose gate|up GEMM applies SiLU(gate) * up and quantises in its
epilogue. The convolution's C * conv(B * x) and the codes its out projection reads
become one gate_quant_fp8 at act none. `gemm_nt_q_gated_wide` puts whole prompts
through the fold instead of falling back to the pair past 64 rows; k and v ask
for `gemm_nt_q_short`; the head norms and rope ask for `rmsnorm_rows` and
`rope_rows`. Each of those is the model's own declaration, so no other
architecture's path moves.

The lm_head is read at its stored codes (bf16, or E4M3/int8 where a recipe made
it so, logits_gemm_fp8/_i8). A tied head also declares the final-normed rows and
the embedding table to the core (rad_declare_scores), so a scored step needs no
head read at all.

data/recipes/d1-3b-fp8.recipe: all 30 layers' linears to E4M3 with a bf16 scale a
128x128 block; the tied head to int8 per row per 128 columns.

Co-Authored-By: Pi <pi@localhost>
2026-10-29 16:23:28 +01:00
Code000andPi b8cd1c950a libr4d: the gated prefill fold, the short-prompt split row, and the rows forms of rmsnorm and rope
Four rows of our own, each declared only by a model that asks for it, so every
other caller keeps the row and the bits it had:

  gemm_nt_q_gated_wide   gemm_nt_q_gated at every M: the narrow tile to 64 rows
                         and, past them, the gated prefill tile (128 gate and
                         128 up rows against 64 activation rows a block), whose
                         accumulators are the unfused prefill GEMM's. The
                         narrow row keeps its M <= 64 ceiling and kernel.
  gemm_nt_q_short        the narrow fp8 row with the short-prompt split rule:
                         N <= 512, K <= 5120 and 41..64 rows run unsplit, where
                         the split's per-slice floors dominate. Its scratch hook
                         makes the same choice, so the arena matches the launch.
  rmsnorm_rows           the same norm; at n <= 256 and 1024 or more rows a wave
                         a row, its sums in rmsnorm_kernel's wave order.
  rope_rows              the same rotation; at 64 or more rows and 4 or more
                         heads one angle a (token, pair), every head turned with
                         it, byte-identical to rope.

gate_quant_fp8 gains act none: the plain product (`mul` then the quantiser) in
one pass, rounded once as mul_bf16 rounds it. Its `mode` stays 1 by default, so
the sigmoid producer every other model issues is unchanged.

r4d_selftest: the act-none chain against mul + quant_act_fp8 at M 1, 8 and 65 with
strided sources and without out_bf16; gemm_nt_q_gated_wide against the tiled
GEMM + gated_quant_fp8 at 65 and 129 rows; and the RDNA4 device phase accepts
gfx1200 beside gfx1201, where the card this was measured on lives.

docs/OPS.md carries the four rows ops_doc checks.

Co-Authored-By: Pi <pi@localhost>
2026-10-29 16:23:28 +01:00
Code000andPi ed1e5caf9d core, abi: scored steps -- rad_declare_scores, RadBatch::score_only, and /v1/systemone's model
A scored request (Request::token_scores, what /v1/systemone asks: the raw logits
at a few candidate ids) does not need the half-gigabyte lm_head read the sampler
would consume. A plugin whose head is the bf16 embedding table declares the
final-normed hidden rows and that table (rad_declare_scores); on a step whose
sampled rows are all scored rows and whose program declared both, the core sets
RadBatch::score_only, the plugin issues everything but the head, and the core
reads the hidden rows and the candidates' table rows back and takes the dot
products in f64 on the host. RadBatch gains one trailing int32 (score_only, 360),
which the pass key mixes; an older plugin never sees it set.

The scheduler issues no step ahead of one that brings a scored row to
max_tokens: that forward pass reads nothing and a max_tokens=1 question would
pay a decode step after its prefill. Scored rows only -- every other decode keeps
the step of overlap it had.

/v1/systemone reports which model answered.

Co-Authored-By: Pi <pi@localhost>
2026-10-29 16:23:28 +01:00
fl0l0u 9093bf618e place+runtime: make the telemetry the HTTP thread reads atomic
/stats and LiveView read the mover's and heat engine's counters, the live tier of every
unit, and OpInfo::issued while the rank and step threads write them between passes. Plain
fields under a concurrent reader are a data race: no torn number matters on a dashboard,
but the compiler may tear, and the sanitizer is right to stop the process for it.

MoverCounters and HeatCounters mirror each struct's fields as relaxed atomics, written
exactly as the plain counters were and read whole through snapshot(); tier_ gains a
per-unit atomic byte mirror (TierMirror, copyable because HeatEngine is), and the step
path and the graph dump meet on OpInfo::issued through std::atomic_ref, which keeps the
struct layout and its copies intact. Engine-internal decisions keep reading the plain
counters -- they never race -- and only the HTTP-thread readers go through the mirrors.
2026-10-29 16:22:35 +01:00
fl0l0u b9c685a9c3 server: bound, gate and sanitize every request entry point
Prepared for exposing the dashboard and the API beyond the local machine. Each piece
answers a finding from the review; none changes what a legitimate client sees.

Parsing. Six entry points still called json::parse with no bound on the tree: the two
WebSocket sessions, the image form's loras field, the two re-parses of template kwargs,
the control-vector POST and the lora-admin body. A legal frame or body of brackets alone
built a tree whose teardown recurses once per level -- one worker stack, one process.
They all go through parse_json_bounded now, the body cap's own value and depth limits.
The same reasoning already refused deep bodies on the generation routes; frames and form
fields were the ones that never passed a gate.

Errors. ApiError::dump threw on invalid UTF-8, and URL-decoded params reach messages
without passing a JSON parser: a 404 becomes a 500, or worse a closed connection. The
dumps replace bad bytes instead of dying.

Logs. Session labels and echoed request text reach the log; an embedded newline forged a
line and an escape sequence drove the terminal reading it. log_sanitize filters control
bytes at the entry points -- labels, refusal logs, the exception handler -- while the
three loggers that print multi-line reports deliberately keep their newlines.

The browser. The dashboard page ships a CSP (its script talks only to its own origin)
and X-Frame-Options DENY; every response carries X-Content-Type-Options: nosniff. And
the loopback-only guards -- control-vector default, runtime LoRA, diagnostics -- now
treat a cross-origin browser as the remote client it is: a hostile page reaches them
through the victim's own browser, which is exactly loopback. Origin not matching Host
refuses; same-origin and non-browser traffic are untouched.

The gate. The API key's path exemptions are method-scoped (reads, plus the POST /ping of
the health-check convention), so an exemption can never ride a method no route answers.
An empty --api-key value is now a startup error rather than a server that looks guarded.

SSE. In the vendored httplib 0.46 an exception escaping a content provider aborts the
process; the provider ends the response instead. Upstream's 0.54 serve_guarded fixes the
cause -- the vendor lift is owed either way, and the catch is harmless belt until it.
2026-10-29 16:22:35 +01:00
fl0l0u a28221eb6a sched: refuse a prompt id that names no vocabulary row
The scored-prompt path (Request::token_scores) has always vetted its ids against the
vocabulary; the prompt itself never was. Raw id arrays arrive at admission verbatim from
the request body -- /v1/completions, /v1/embeddings and the generator take them -- and an
id past the embedding table is gathered by the step, fails it, and a failed step is a
device fault (spec 17): one request, {"prompt":[2147483647]}, ended every session on the
server. The check belongs at admission, where a refusal is a 400, not mid-pass, where it
is an exit.

The sched fixture's model declares 512 vocabulary rows and its requests spell prompts
from 1000 up; admission now refuses those, so the fixture's vocabulary moves above the
ids it uses.
2026-10-29 16:22:35 +01:00
mici81andClaude Opus 5.5 ed5f990d92 qwen MXFP4 feed-forward: the gated fold up to 16 rows, not 8
decl_gated_fold_mx declared gemm_nt_q_gated_mx over 1..8 rows only, from
before libr4d had gemm_mxfp4a8_gated_gemv_wide (9..64, byte-identical to
gemv_wide followed by gated_quant_fp8, the pair it replaces). TranslateGemma
already folds to 64 through RADIANCE_G3_FOLD_ROWS; Qwen's 16-row verify steps
(two sequences at speculation 7) still ran gate_up and gated_quant_fp8 apart.

Qwen3.8-27B MXFP4 + DFlash2 at TP2 on 2x R9700, production flags, ms a decode
step, three interleaved rounds (medians), the 1..8 band -> folding to 32:

  16 rows (x2):            1k 20.96 -> 20.78 (-0.9 %), 16k 21.96 -> 21.70 (-1.2 %)
  32 rows (x4):            1k 23.97 -> 24.10 (+0.5 %), 16k 26.06 -> 25.98
  32 rows (x8 short block): 1k 24.99 -> 25.14 (+0.6 %)

and 64 rows lost 2.1 % (16k x16) on the base before this main. So the band is
16: a taller step takes exactly main's path. Where the wide row does not
resolve (K at or under decode_shortk's corner), the declaration drops to 1..8
instead of losing the fold. Greedy output is identical to main (300 tokens,
two prompts).

arch_test: qwen35_fp8_mxfp4_feed_forward_folds_verify_steps_up_to_16_rows
(one and two sequences of 8 rows fold, three to eight take the pair).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 16:21:56 +01:00
baKon 187a015bda sched: tighten preempt gate headroom and test pool 2026-10-29 13:16:07 +01:00
Bakon e668d493d9 sched: gate preempted prefill on whole recompute plus running headroom 2026-10-29 13:16:07 +01:00
Deadcode 4a61d7296b radiance 1.14.0
New models and formats:
- libr3d: a kernel library for RDNA3 (gfx11) cards
- nomic-embed-text-v2-moe (the nomicbert plugin)
- Gemma 4 E2B with its per-layer MLP width, and Google's unmodified E2B/E4B directories in bf16
- DeepSeek-V4.1-Flash converted straight from its release: the Engram tables, the fused imatrix and
  rad-convert --chat-template for a release that ships no template
- GGUF Q8_0, Q4_K and Q6_K tensors import as their planes; rad-convert writes them without a recipe
- Qwen3.8-Flash-Next-FP8 converts and serves through qwen4exp_fp8

Speed:
- hc_read's decode kernels as one grid (34.7 -> 25.2 us at 4 rows) and its tiled up-mix pipelined
- gemm_fp8a8: the narrow form's scales staged through LDS (Flash-Next int8 at 32 rows 83.6 -> 68.3
  us), the gated three-tile form at 8 waves (gate_up at 48 rows 272.9 -> 180.6 us)
- Qwen3.8-27B: the delta net's out-projection read beside its decode recurrent update (x1 19.40 ->
  19.10 ms a step), and the verify's split-KV attention sized by context depth (x3 at 180K 42.4 ->
  40.3 ms a step)
- Hy-Memory (HYV3) decode: fused QK norm, RoPE and KV store, residual adds folded into the norms,
  coalesced one-token expert GEMMs
- spechub: the coupled verify walks the live candidates only (151 -> 31 us a launch)

Speculation:
- DFlash2: lossless coupled acceptance at T > 0 (--draft-coupling on)
- A block drafter's proposals verified as a tree, on by default for the Gemma 4 31B's DFlash2, with
  a block-16 tree that runs its short block under load

Features:
- Decode-hot residency: --draft-expert-placement host, --expert-profile, --expert-pin-top, and
  --expert-stats FILE for the routed experts each layer selects
- --ngram-placement ram=DIR: one n-gram table shared by engines on separate cards
- Prefix cache: --prefix-resume exact (default) resumes a hit on the cold run's own chunk grid, so it
  answers bit-identically; snapshots at a head other prompts share, from 528-token prompts, and for
  tip-only one drafter window below the tip; hits on models whose KV groups have different block
  sizes; the snapshot store keeps a floor of 8 ahead of --host-headroom-mib
- Typed tool-call argument tags; rad-chatparse --request renders and reads back one request as the
  server does
- MiniMax-H3: keyframes ride a latent upscale
- Gemma 3's fused all-reduce junction on the lossy wire

Fixes:
- A speculative step shorter than its band (an MTP step of 4 rows at gqa 8) no longer stops the
  engine with a scratch refusal at issue (#293)
- --p2p off: prefill back to 1.12.0's rate; 1.13.0's push check read a host-memory slot over the link
  twice (#323)
- A chat template that cannot render a conversation is refused at load, not mid-request
- imatrix entries found under llama.cpp's spelling; the W4A8 prefill's tail scale read; the GDN conv
  kernels on an f32 weight; dense integer rows at the group they compute (a Q8_0 weight at group 32)
- --expert-profile refuses a profile recorded on another model
- hc_read's one-grid wait traps past its deadline instead of reading a stale value

Changes: Plugin ABI 31, unchanged. RADIANCE_DRAFT_TREE, DFLASH2_TREE_NODES, DFLASH2_TREE_TEMP and
DFLASH_Q_TEMP are gone (trees run where the probe says they pay; temperatures 1.25 / 0.6).
2026-10-29 12:04:24 +01:00
Boris Manojlovic 481fcd5df0 mem: give the checkpoint store its floor before the host reserve
--host-headroom-mib is a courtesy to the system: the process's unpooled allocations, the
load's staging windows, the page cache. A linear-state snapshot store is not a courtesy.
A store too small for one snapshot does not serve a smaller store -- it serves none, and
every prefix hit re-prefills the whole conversation, while /metrics still counts the
attention blocks as a hit and the request log's "(cache 0)" is the only honest number.

--checkpoint-slots auto already promises a floor of kCheckpointSlotsFloor slots, but the
floor was only checked against what the host had left once the host pool, the streaming
mirror and the reserve had taken theirs. On a host where those fit exactly, the store
resolved to 0.

Charge the floor before the reserve: when the reserve is what stands between the host's
spare memory and the store's floor, it gives back exactly the shortfall -- whole MiB,
rounded up so the store is never a byte short, never below kHostReserveFloor (1 GiB) and
never above the margin the user asked for. A host that can pin the floor gets it; a host
that cannot still reports the shortfall, now naming --host-headroom-mib among the levers.
The boot guard a few lines below the sizing takes the same margin, or a count auto had
just fitted by giving the reserve back would be refused a moment later.

The rule is bytes over the host's own measurements: checkpoint_slots_want for the count,
MemAvailable, the memory cgroups and the driver's pin cap for the room. It needs no case
per model or per KV encoding -- a wider slot (more linear or windowed layers), a wider
streaming mirror (bf16 rather than fp8) and a larger --tp arrive as different numbers,
not as different rules.

Measured on 2x RX 9070 (16 GB), Qwen3.8-Flash-Next at --tp 2, bf16 KV, 2x262144,
--host-pool-mib 23652: 8 snapshots of 112.73 MiB, the reserve giving back 685 MiB and
holding 3.33 GiB (before: 0 snapshots, every turn re-prefilling 125-134k tokens at
ttft ~31 s with "(cache 0)"). The same 6398-token prompt twice: ttft 1.66 s -> 0.65 s,
cached 0 -> 5120, linear_checkpoints_written_total 0 -> 1.

Tests: the rule itself (fits -> untouched, short -> exactly the shortfall, beyond it ->
the 1 GiB floor, a smaller flag -> never exceeded) and checkpoint_slots_want against the
counts auto already reports.
2026-10-29 10:36:10 +01:00
mici81andClaude Opus 5.5 a64c75eb34 qwen35_fp8: read the delta net's out-projection beside its decode recurrent update
At decode heights the recurrent update runs one workgroup per (sequence, head) and leaves the
card's memory mostly idle. Each delta-net layer now reads its out-projection (the whole weight,
7.9 MB a rank in MXFP4) into the on-die cache there, on the second lane behind a join from lane 0,
as prefetch_beside does beside the all-reduces. Up to four decode sequences and 32 rows; no read on
a step that carries a prompt's rows, at one rank, or where the deployment turns weight prefetch
off (RadBuildCtx::weight_prefetch_off: nothing is declared).

Qwen3.8-27B MXFP4 + DFlash2 at tp 2 on 2x R9700, production flags, 1k context, hwgrid ms/step,
median of five interleaved rounds, none -> whole projection:
  x1 19.40 -> 19.10 (-1.5 %), x2 20.93 -> 20.78 (-0.7 %), x4 24.26 -> 24.17 (-0.4 %),
  every round faster at each of the three;
  x8 25.22 -> 25.48 (+1.0 %, four rounds of five slower) -- hence the four-sequence ceiling;
  x16 (64 rows, no read) and 90k x4 unchanged. 4 MB reads as the whole.
Against this main (one round): x1 19.40 -> 19.15, other cells within noise.
Greedy output identical to the build without the read (300/300 tokens on two prompts, |dlogprob| 0).

arch_test: qwen35_fp8_reads_the_delta_net_out_projection_beside_its_decode_update; the qwen35_fp8
step pins move (prg_pins.py).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 10:35:38 +01:00
mici81andClaude Opus 5.5 49ca5ff9c6 libr4d decode split law: size a three-wave verify by the step's depth
The full-attention decode law gives a three-wave workgroup (q_len * gqa > 32,
an 8-row DFlash2 verify at gqa 6) 128 / units segments whatever the depth.
Three to seven sequences of Qwen3.8-27B (two KV heads a rank) then get 21..9
segments, each walking 4-18k tokens at depth, and one or two sequences stay
at 64 / 32 where 256 / 128 are faster.

The law now reads the step's depth from the block table's width (max_blocks *
block_size, capped at max_ctx; the scheduler rounds the width to the batch's
longest sequence): up to 16k tokens 128 / units as before, past 16k at least
64, past 64k 512 / units capped at 256. Declare passes no table, so the
scratch is still sized at the declared bound, the deepest the law can be
asked for; the law grows with depth, so an issue never needs more.

Qwen3.8-27B MXFP4 + DFlash2 at TP2 on 2x R9700, k6_v4, speculation 7, ms a
decode step against this main:

  x1  90k 22.07 -> 22.03   180k 25.35 -> 24.88
  x2  90k 26.83 -> 26.36   180k 33.18 -> 31.99
  x3                       180k 42.41 -> 40.33
  x4  90k 36.20 -> 34.96

Steps whose count does not change (1k x1..x8, the short block at 16k x16) are
within noise. Greedy output is identical (300 tokens, two prompts). The forced
segment sweeps behind the thresholds are in the comment.

r4d_selftest: decode_split_law_case reads the law through the decode scratch
hook's declare path, 21 batches across the depth thresholds.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 09:25:09 +01:00
Brandon Bertelsen 460de4a1fd Merge branch 'laya-arch-plugin' into mica-support 2026-10-29 00:50:14 -04:00
Brandon Bertelsen 711cdd0cd7 mica: Mica on /v1/systemone over the qwen35 plugins; d1's readout shared 2026-10-29 00:50:14 -04:00
Brandon Bertelsen 035ecde18c tokenizer: Metaspace prepends only to text not already starting with its replacement 2026-10-29 00:44:13 -04:00
Brandon Bertelsen b6cf2b3574 laya: rad-convert rounds Laya's f16 to bf16 itself; the tiny test is f16 2026-10-29 00:28:47 -04:00
Brandon Bertelsen cc58402b71 laya: a recipe rounding the release's f16 linears to bf16 2026-10-29 00:02:06 -04:00
Brandon Bertelsen 213aff9753 laya: convert a checkpoint with no config.json of its own; GUIDE section 2026-10-28 23:58:28 -04:00
Brandon Bertelsen 9c605a103d laya: Laya decision models on /v1/systemone (arch/laya) 2026-10-28 23:44:38 -04:00
Brandon Bertelsen d24cf32a13 Merge main into clef-flash-arch-plugin 2026-10-28 22:53:52 -04:00
Brandon Bertelsen e1323afeb9 Revert the fp8 prefill GEMM's half-band tail 2026-10-28 21:38:12 -04:00
Brandon Bertelsen f9fdc7b57f fp8 prefill GEMM: the last band's upper waves leave when their rows lie past M 2026-10-28 09:51:08 -04:00
Adam Zhang 4374bea1c4 hc_read: the one-grid form's wait traps past its deadline instead of reading a stale d
hc_role_wait, where hc_read_fused_kernel's B blocks wait for every A block, gave up after half a
second and went on, so a counter fault would have read a stale `d` and its scales and written
wrong values with no error. The all-reduce handshakes trap on the same condition (r4d_ar_seq.h,
r4d_ar_oneshot_2rank_exact.hip: a handshake that cannot complete is a lockstep violation); this
does the same. It cannot fire with the counters in order (each launch's last B block clears
them), so nothing that runs today changes.

libr4d/isa/res.sh: no hc kernel spills, hc_read_fused_kernel 126-147 VGPRs.
r4d_selftest --case hc_read_e4m3 and hc_read_bf16 on 890715f: 67 ok, 0 FAIL, the 24 byte-for-byte
comparisons against the previous decode kernels among them. --perfhc 4: 25.4 us a call (the
previous decode kernels 34.6), as before the change.
2026-10-28 08:16:28 -05:00
Asim Siddiqui 890715fd96 libr3d: the wave-matrix record -- the six 16x16x16 variants, the MAC-core measurement, the i8-x4 gap
RDNA3's ISA lists exactly six wave-matrix instructions (f16, bf16, int8 and
int4 in; f32, f16, bf16 and i32 accumulating) and the toolchain emits them on
every gfx11 target; they run over multiple cycles driving the DOT pipeline
internally, and the MAC-core measurement on the 16-CU gfx1102 part confirms
it: f32-acc f16 19.11, f32-acc bf16 19.24, f16-acc f16 19.44, i32-acc i8
19.29 against the paired dot2 path's 18.86 TFLOP/s -- the same pipe within
three percent, matching the full-kernel 1.99-vs-1.97 already in r3d_common.h.
The i32-acc i4 tile is the exception at 25.68 TFLOP/s, 35% above, but it takes
i4 in both operands and the grids served here pair i8 activations against i4
and i2 weights: there is no mixed-precision integer WMMA on RDNA3, so that
pipe is unreachable from the w4a8 and w2a8 rows.

Commentary only -- the rationale passages in the README, CMakeLists.txt,
r3d_rows.cpp, r3d_plugin.h and r3d_selftest.cpp now state the measured
record; no kernel, lane map or numeric path changes, and the rebuilt library
is byte-identical (selftest 78 rows, 0 failed, 0 skipped).
2026-10-28 13:51:45 +01:00
Asim Siddiqui 6cb9826975 libr3d: the gfx11 (RDNA3) kernel library
A complete row set for the gfx11 family (1100/1101/1102/1103/1150/1151 plus gfx11-generic),
mirroring libr4d's structure: the quantised GEMM rows (m16, tiled, gated, the bf16 logits
gemm), the paged and ragged attention for decode and prefill, the KV store, the sampler
spine and the spec rows, with the recorded-fixture, board, selftest and comparison-driver
gates for each.

The gates are the record. Every row is measured against libref on the shape matrix: the
recorded fixture at 1153 cases with worst rel_l2 1.362e-03, the board's five modes with
bit-identical decision lines, the selftest at 74 rows, and the 233-case served-shape pairing
at 0 divergent against the tree libref. End-to-end on a 2B fp8 checkpoint served on the
card, coherent through prefix-cache adoption.

Two platform laws each shape the design. A kernel that calls device printf takes the
implicit hidden_hostcall_buffer argument and is undispatchable by the AQL backend, so the
trace records are plain stores behind a budget. And a plugin-owned __device__ global is not
a channel into the engine's dispatch path: in a dlopened plugin the runtime's symbol stub
is not the address the kernel's module writes, so the served trace channel is a hipMalloc'd
record slot passed as a kernel argument, with the device-global ring kept for the board.

kv_store bounds its slots at the pool's own plane (n_blocks x block_size), the span the
cache operand declares, not at the step's own span: a request that adopts a cached prefix
writes its new tokens at the allocator's global block indices, which sit past any bound
built from the step's token count, and a slot lost there is KV that attention then reads
stale. A corrupt slot map is dropped at the same bound.
2026-10-28 13:51:45 +01:00
baKon 1ffa770901 docs: deepseek41-hf-direct, the release converts without a GGUF intermediate 2026-10-28 13:50:16 +01:00
baKon b64b0de7de convert: --chat-template, bake a template a release ships none of
DeepSeek's release carries no chat_template.jinja and its tokenizer_config.json
names none, so an HF-direct container answers /v1/chat/completions with 501
unless the serve passes --override-chat-template. The converter now takes the
template itself and bakes it into the vocab section, overriding whatever the
checkpoint carried or lacked. Trailing newlines are stripped as for a sibling
chat_template.jinja, and an unreadable or empty file is refused rather than
skipped. Both paths are covered: text_test reads the file, convert_test
converts the tiny checkpoint and reads the template back out of the container.

(cherry picked from commit 6381f61794cd61d1f86925fd23ea61e1b1544dfe)
2026-10-28 13:50:16 +01:00
baKon 73bee2dcc2 data: the DeepSeek-V4.1 release's Engram tables and fused imatrix, from the release alone
engram_tables.py builds the Engram hash tables from the release's own tokenizer.json
and config.json, so rad-convert needs no llama.cpp converter run; imatrix_merge.py
fuses the gate/up imatrix entries llama.cpp's converter writes split, matching the
plugin's fused ffn_gate_up weights. The recipe is the UD-IQ1_S mix for the official
release (251.07 GiB plan).
2026-10-28 13:50:16 +01:00
Adam Zhang 11076c06fc hc_read: the previous decode kernels behind r4d_hc_read_pin_decode, compared byte for byte
The one-grid form and the pipelined tiled up-mix replaced hc_read_a_kernel, hc_up_mix_kernel and
hc_up_mix_tiled_kernel in place. Their previous forms are kept verbatim as *_prev, with
hc_up_mix_prev_launch launching the up-mix as before, and r4d_hc_read_pin_decode(1) selects them:
kernel A, then the up-mix in a second launch, and the tiled up-mix's K passes in sequence. 0, the
default, is the launcher's rule.

r4d_selftest's hc_decode_forms runs both on the same inputs on a real stream at 1 to 7 rows (each
one-grid instantiation), 8, 16, 32, 33 and 64 (the tiled up-mix at both row tiles), with E4M3 and
int8 codes, and compares x, the injected gains, the codes, their scales and the rotated twin byte
for byte. The two forms must dispatch different kernels (r4d_record_dispatches), so an ignored pin
fails: with the hook made a no-op, all 24 checks fail. For that the tiled up-mix now launches
through r4d_emit, so the dispatch log sees it. --perfhc times both under the launcher's prefill rule.

--perfhc M, cold (256 MiB through the caches), one R9700 at 240 W, three runs, medians, previous
-> rule: 1 row 32.3 -> 22.5 us (-30.3 %), 4 rows 34.8 -> 25.4 (-27.0 %), 8 rows 46.2 -> 43.3
(-6.3 %), 32 rows 51.1 -> 48.4 (-5.3 %). r4d_selftest --case hc_read_e4m3: 62 ok, 0 FAIL (24 of
them the new comparisons); hc_read_bf16: 5 ok.

libr4d/isa/res.sh: no hc kernel spills or uses scratch (195 kernels). hc_read_fused_kernel takes
126 to 147 VGPRs (9 or 10 waves). The pipelined tiled up-mix at its 32-row E4M3 tile takes 111
VGPRs where the previous one took 75 (12 waves a SIMD against 16), and is the faster of the two at
8 to 32 rows as measured above.
2026-10-28 13:48:43 +01:00
Adam Zhang 222cbe7981 hc_read: the tiled up-mix pipelined, its loads in flight across LDS-only barriers (51.4 -> 48.4 us at 32 rows)
At 8 to 32 rows (two to eight streams at MTP 3) the up product with the mix ran its five K passes
as loads, barrier, WMMA, one after another. Its K loop now issues a pass's loads before staging
the previous pass from registers, with the mix's operands loaded alongside the first pass. The
barriers there order LDS only (hc_lds_barrier): __syncthreads() fences at workgroup scope, which
on gfx12 in WGP mode waits for every outstanding global load, so no prefetch survived it. The
quantise tail reads each thread's channels once, where it walked them a dependent load at a time.

Same fragments through the same WMMAs in the same K order, and the same tail arithmetic: the
output is bit-identical (compared byte for byte against the previous kernels in this series' last
commit).

r4d_selftest --perfhc M, cold, one R9700 at 240 W, three alternating rounds against 6c33ee4,
medians: 8 / 16 / 32 rows 46.6 / 47.8 / 51.4 -> 43.9 / 44.3 / 48.4 us (-5.8 / -7.3 / -5.8 %).
r4d_selftest --case hc_read_e4m3 and hc_read_bf16: 43 ok, 0 FAIL.
2026-10-28 13:48:43 +01:00
Adam Zhang c896a870ed hc_read: kernels A and B as one grid at decode, their dots off LDS round trips (34.7 -> 25.2 us at 4 rows)
At one to seven rows hc_read is a chain of dependent latencies, not a stream of bytes: kernel A
is mostly its norm prologue and the L2 round trips around its dots, with memory idle meanwhile,
and kernel B cannot ask for W_up until A has ended. At Qwen3.8-Flash-Next's shape (hc 4, n 2560):

- A and B run as one grid (hc_read_fused_kernel), roles by ticket: a block's first act is an
  atomic increment, tickets below `na` run A's body, the rest B's. A B block loads its W_up rows,
  then waits until every A block is done. Every block holding a smaller ticket has started, so
  the blocks it waits on are resident: no co-residency is assumed and none can deadlock. The last
  B block past the wait clears the counters for the next launch on the stream (kHcSyncCtr more
  words in the per-stream counter block), and a wait past half a second gives up rather than hang
  the card. Without the counters the two kernels run as before.
- A's norm prologue loads all of a thread's h and norm gain at once, one round trip for ten.
- B's dot reads d from LDS as bf16, sixteen values in two 16-byte reads, two rows of W_up a thread.
- At four rows a wave computes its two W_down columns in one pass over N (hc8_dot_down2).
- Dynamic LDS starts 16-byte aligned: the fused kernel's static LDS is not a multiple of 16, and
  misaligned N reads ran A three times slower.
- The quantise tail reads its group once instead of three times.

Every sum is the same fmaf sequence in the same order, so the output is bit-identical; this
series' last commit keeps the previous decode kernels behind a pin and r4d_selftest compares the
two byte for byte. Eight or more rows keep the tiled path.

r4d_selftest --perfhc M, cold (256 MiB through the caches), one R9700 at 240 W, three alternating
rounds against 6c33ee4, medians: 1 / 2 / 4 rows 32.7 / 33.2 / 34.7 -> 22.8 / 23.6 / 25.2 us
(-30 / -29 / -27 %); 8 and 32 rows unchanged. r4d_selftest --case hc_read_e4m3 and hc_read_bf16:
43 ok, 0 FAIL.
2026-10-28 13:48:43 +01:00
Adam Zhang fe2b8cd7fe r4d_selftest: --perfhc times the prefill-tile forms a row count is served by
Pinned at 8 rows up to the wide row tile, the wide kernels refuse the shape (RAD_E_SHAPE: they
serve only the wide tile), and --perfhc stopped at that FAIL before timing anything, so hc_read
could not be timed at a verify step's 8 to 32 rows (two to eight streams at MTP 3). A pinned form
that refuses with RAD_E_SHAPE is now a skip; the forms that serve run, compare byte for byte and
time as before. The decode tiles' kernels, the first form, must still serve, and any other error
fails as before.

--perfhc 8 / 32 / 64, cold, one R9700: the decode tiles' kernels 46.5 / 51.2 / 81.0 us a call,
where each stopped at the FAIL before.
2026-10-28 13:48:43 +01:00
Adam Zhang 14e91c4d9f gemm_fp8a8: the narrow form's scales staged through LDS and its split finisher coalesced (Flash-Next int8 at 32 rows 83.6 -> 68.3 us)
Two costs in gemm_fp8a8_body, which every fp8 and int8 linear at 64 rows or fewer runs
(gemm_fp8a8_nt_m16, gemm_i8a8_nt_m16, the bias and gated rows, and r4dchain_gemm_fp8a8):

- The fold loaded its weight and activation scales itself, after the next K tile's prefetch had
  been issued. Loads return in order, so each fold waited for that whole prefetch, twice a tile at
  FK 256, and the "one tile ahead" overlapped nothing. The scales are now staged through LDS a
  tile ahead, beside the B tile: each thread loads one weight-scale dword and one activation scale
  with its B prefetch and stores them with the B tile, so a fold reads LDS. Two registers a
  thread; holding a tile's scales a lane (8 + 2*NT registers) spilled at the decode pins.
- The split-K finisher walked the partial planes token index fastest, `rows` floats apart, one
  element a thread: a cache line a load and a round trip each, most of a 45 us call at N 512,
  M 64. Consecutive threads now take consecutive weight rows, four rows a 16-byte load and four
  loads in flight a plane; a shape off that alignment walks the rows fastest an element at a time.

The int8 single-tile wave pin goes from 12 to 10: the staged form needs a few more registers than
12 waves' 120 leave, gfx12 allocates them 24 at a time so 11 waves leave 120 too, and no decode
shape puts more than 8 of these waves on a SIMD. The gated three-tile form, at 8 waves since the
previous commit, spills 10 at 33-47 rows and 9 at 48 with the staging (0 and 7 without; at 9 waves
it would spill 70).

The same values are summed in the same order (each finished element from 0.0f in ascending split
index, rounded by the same rule) through the same WMMAs in the same K order: bit-identical. A dead
wave's fp8 block scale reads 0 instead of the plane row past the end; its rows are never stored.
A full r4d_selftest in 6c33ee4 and here, every launch of a gemm_fp8a8* or gemm_i8a8* row hashed
after it: 975 of 975 identical (829 gemm_fp8a8_nt_m16, 42 gated, 18 gemm_i8a8_nt_m16, 5 bias).
Greedy replies on Qwen3.8-Flash-Next (int8) and Qwen3.8-27B FP8 byte-identical to 6c33ee4's.

r4d_selftest --perfw8 / --perf at every narrow-GEMM shape of the two models at tp 2, cold
(256 MiB), one R9700 at 240 W, alternating rounds against 6c33ee4, medians, summed over each
model's ops at 1 / 8 / 32 / 48 / 64 rows: Flash-Next int8 61.7 / 64.2 / 83.6 / 111.9 / 130.9 ->
56.8 / 57.0 / 68.3 / 87.5 / 95.7 us, 27B FP8 411.0 / 411.9 / 427.2 / 446.3 / 485.4 -> 404.6 /
405.4 / 415.0 / 428.5 / 438.7 us. Most at narrow N, where the finisher dominated: fp8 512 x 5120
at 64 rows 53.2 -> 15.4 us, int8 256 x 2560 at 48 rows 21.0 -> 8.5 us. The gated row at 27B's
gate_up against the previous commit: 1.3-3.4 % faster at 8-32 and 48-64 rows, 1.8-2.3 % slower
at 33-47 (176.8 -> 180.2 us at 40), where the staging's spills cost more than its overlap gains;
against 6c33ee4, 3.5 % faster there. Decode step at tp 2, old / new / old: Flash-Next 15.76 /
15.69 / 15.76 ms, 27B FP8 28.02 / 27.69 / 28.04 ms.
2026-10-28 13:48:23 +01:00
Adam Zhang 3efb37254b gemm_fp8a8: the gated three-tile form pinned at 8 waves (gate_up at 48 rows 272.9 -> 180.6 us)
The gated row at 33 to 48 rows (NT 3, MW 16) was pinned at 9 waves, 168 registers, where its
epilogue spilled: 57 registers at the full tile (48 rows) and 10 below it (12 and 59 in its
chained twin). At Qwen3.8-27B FP8's gate_up at tp 2 (N 17408, K 5120) 48 rows took 272.9 us
against 180.6 at 56. The gated form is always MW 16, so a block puts four waves on each SIMD, and
8 and 9 waves both hold two blocks a WGP: at 8 the form gets 192 registers for no occupancy, and
spills 7 at 48 rows and none below. f8_waves takes the gated flag (false by default), so no other
form's pin moves.

A pin changes register allocation only. r4d_selftest --case dequant_w4_bf16 (fp8_numeric, which
checks the gated row byte for byte against the GEMM + gated_quant_fp8 pair at every M it runs),
every launch of an fp8 narrow GEMM row hashed after it in 6c33ee4 and here: 879 of 879 identical,
42 of them gated; 1,526 ok, 0 FAIL.

r4d_selftest --perf 17408 5120 M, cold, one R9700 at 240 W, five alternating rounds against
6c33ee4, medians: 48 rows 272.9 -> 180.6 us (-33.8 %), 33 to 47 rows 186.2-187.6 -> 175.9-177.1
(-5.5 %), 8 to 32 and 56 to 64 rows within 0.3 %.
2026-10-28 13:48:23 +01:00
Adam Zhang 14b8f21a1a r4d_selftest: --perf times the gated row at a gate_up shape
--perf N K M timed gemm_fp8a8_nt_m16 and the tiled row but not gemm_fp8a8_gated_nt_m16, the
engine's gate_up at every fp8 SwiGLU model, so that row had no timing. At N % 256 == 0,
K % 256 == 0 and M <= 64 it is now timed with the others, N being the gate and up rows together
as the engine fuses them; a shape the split rule would split is reported as not served. At
Qwen3.8-27B FP8's gate_up at tp 2 (N 17408, K 5120) on 6c33ee4, one R9700 at 240 W, cold:
157.1 us at 8 rows, 164.3 at 32, 186.7 at 40, 271.8 at 48, 180.3 at 56.
2026-10-28 13:48:23 +01:00
baKon 662b7720b5 core/sched: a prefix hit resumes on the cold run's chunk grid, so it recomputes the cold run's own chunks
A hit recomputes the tokens past where it resumes. Kernels may round a row differently at another
chunk length (spec §17: the fp8 GEMM's split-K count is chosen from M), so a hit that recomputes
its tail in other chunks than a cold prefill of the same prompt can flip a near-tie in greedy text.
On the DeepSeek-V4.1 daily (TP4) a 24k-token prompt that hit a 16k one's tail snapshot resumed at
15856, ran a 528-token chunk to the next boundary and answered differently from its cold run.

--prefix-resume exact, the default:

- ChunkGeometry carries the grid an idle server's cold prefill chunks on: --max-num-batched-tokens
  rounded down to the quantum, or the checkpoint interval where chunks split at it and it is the
  smaller, times the span from the second interval on.
- plan_chunk writes checkpoints only on that grid. A prompt's tail snapshot is taken where its last
  chunk starts (sliding-window snapshots keep their one-block margin) instead of at its last
  quantum boundary. The chunk already ends there, so a long cold prompt no longer runs a short
  extra step at its end.
- A checkpoint interval past the chunk must be a multiple of it; otherwise it is rounded up, and
  startup says so.
- admit_one steps a hit with no snapshot to resume from (full attention) back to the grid. A
  request's own checkpoint (Request::checkpoint_at, /v1/systemone's shared head) is honored where
  it falls.

--prefix-resume nearest keeps the previous rule.

The cost is re-prefill: an exact repeat runs the cold run's last chunk again, and an agent's next
turn resumes where the previous prompt's last chunk started, about half a chunk more than nearest
(2048 tokens at a 4096-token budget). The property holds on an idle server; a prefill that shares
its steps with decode rows or other requests (--busy-prefill-chunk, --prefill-interleave) is cut
differently, as batching already changes greedy text.

Tests: sched_test covers the grid for six geometries (GDN hybrid, interval past the budget, span,
periodic and tip-only window snapshots, full attention), the interval rounding, the tail snapshot
at the last chunk start, admission stepping back to the grid, and a property over prompt lengths:
every checkpoint is a chunk start of the cold run of its prompt and of any longer prompt it
prefixes, and a hit from it cuts the cold run's chunks. config_test covers the flag.
2026-10-28 12:50:54 +01:00
baKon f43929ccb8 core/mem, core/sched: a prefix hit on a model whose KV groups have different block sizes, and a hybrid's window in the checkpoint slot
DeepSeek-V4.1 declares its compressed attention at one KV row per r tokens: kv_index_r2 and
kv_compressed_r2 at 2-token blocks, kv_index_r1 and kv_compressed_r1 at 1-token blocks, beside a
16-token sliding window (kv_window), a linear compressor state (kv_comp_tail_r2) and a conv window
(kv_engram_tokens). On that model no request ever reused a token, for two reasons:

- PrefixCache::configure took the first full group's block size as its granularity and left every
  paged group with another block size out ("block 1 != cache granularity 2: not cached").
- KVManager put a trunk's window in the checkpoint slot only on a model without linear state, and
  the scheduler refuses a hit that leaves a trunk group uncovered. With linear state beside the
  window, every hit was zeroed (HitCut::Window).

Either alone leaves the hit at zero. On an agent's growing conversation that is the whole context
prefilled again every turn.

The cache now holds every paged group but a windowed one. An entry covers the lcm of their block
sizes and holds lcm / B blocks of a group with B-token blocks (PrefixCache::entry_groups,
blocks_per_entry). A lookup hands each group its own blocks for adopt(); insert, eviction, trim,
rebind, restore_room, release_session and unshared_tokens count per block; trim() and trim_for()
count entries. The chunk quantum is already a multiple of every paged group's block, so
checkpoints and hits stay on the entry grid. With equal block sizes an entry is one block a group,
as before.

A trunk's window rides in the checkpoint slot whether or not linear state is beside it; the slot is
the state, then the window pages, the layout KVManager::checkpoint_copy already walked. The
scheduler lets a hit stand on a windowed trunk group when it resumes at a window snapshot
(win_hit no longer needs a model without linear state); any other trunk group the cache does not
hold refuses the hit, as before. The reserve's trim asks for entries, from the group furthest
short. The idle tiers move an entry as its blocks: TierExec and the slot layout take
entry_groups(), where a group appears once for each block it holds in an entry, and the VRAM
estimate counts the same.

No plugin on main has a window beside linear state or paged groups of different block sizes, so
every model here keeps its cache and slot as they were. DeepSeek-V4.1 (#266) has both; its slot
grows by the window's pages (10 blocks of kv_window, 6.25 MiB a rank at TP4).

Tests: mem_test -- an entry at the lcm over block sizes 2/1, 2/4 and 16/2 (lookup blocks, adopt,
refcounts, eviction and trim in entries, restore_room, unshared_tokens), a publish short of one
group's blocks refused and unwound, checkpoints on the entry grid (and the binding's key), an
interval off the grid refused, a hybrid with a window and mixed blocks, an entry over mixed block
sizes through the host tier byte for byte (one to three ranks, replicated beside zero), and a
checkpoint carrying linear state and the window together; the window-snapshot rule's test now
expects the window beside linear state. sched_test -- a hit on a hybrid whose slot carries the
window resumes at the snapshot, a trunk group neither cached nor in the slot refuses the hit, a
hit over mixed block sizes adopts each group's own blocks, and the reserve trim asks for entries.
2026-10-28 12:50:54 +01:00
NunzeandClaude Opus 5.5 64c3dc9893 libr4d: the gdn conv kernels read an f32 weight -- a GGUF ships ssm_conv1d in f32
llama.cpp keeps a Gated DeltaNet's ssm_conv1d unquantised, in f32, and a container converted from
a GGUF holds it so. The three kernels that read the convolution weight, gdn_conv_prep,
gdn_conv_update and the convolution gdn_conv_recurrent_update folds in, read bf16, so their shims
refuse an f32 weight. The weight's element type is now a template parameter of all three.
r4d_gdn_conv_tap.h, which already holds the arithmetic the fold shares with the standalone path,
gives the vector a channel's taps are loaded as (ushort4 or float4) and the widening of one tap,
exact for either type. The shims take a bf16 or an f32 weight and pick the instance by its dtype;
any other dtype is still refused.

The raw entry points keep their signatures. r4d.h gets an f32 twin of each standalone one,
r4d_gdn_conv_prep_w4_h128_bf16_f32wgt and r4d_gdn_conv_update_w4_h128_bf16_f32wgt, rather than a
flag, so no caller of the bf16 ones changes. The fold has no raw entry point; its CV parameter now
also says the weight's type (1 bf16, 2 f32), which leaves every existing instance's template
arguments and name as they were. That is twelve new conv instances and sixteen new fold ones.

The bf16 instances compile to the same code. Built before and after with the build's flags, all
116 kernels of the two units have the same instructions, resource counts and metadata; only the
conv kernels' names change with the added template argument. The bf16 reads keep their shape:
widening gdn_conv_update's ushort4 to a float4 before use reorders its loads. The f32 conv
instances use no scratch, conv_prep 56 to 57 VGPRs (53 at bf16) and conv_update 108 (96 at bf16,
12 waves per SIMD instead of 16); each f32 fold instance has exactly its bf16 twin's counts.

r4d_selftest gets three cases for the card. gdn_conv_prep and gdn_conv_update over an f32 weight
holding bf16's values must write the bytes they write over the bf16 weight: q, k and v, g and beta
at prefill, and the conv state. The sequences are uneven; at prefill two are seeded from their
cache, one of them over two chunks, and a one-token one is not. Outputs are poisoned, the cache
must move and an f16 weight must be refused. The fold over the f32 weight must match the pair
over the bf16 one, byte for byte as the fold already does at bf16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:49:37 +01:00
NunzeandClaude Opus 5.5 d73abc28d5 libr4d: the dense integer rows take the group they compute -- a Q8_0 weight at group 32 was read as 128
The dense integer kernels compile their group in and read no `group` argument, and neither the
rows nor the layout hooks checked it: w8_enc_layout accepted an `i8*f16[1x32]` weight (a Q8_0
block) at group 32 and the kernel computed it at 128. The twelve dense gemm_nt_q rows now carry
C_EQ("group", ...), and the four hooks (w4, w5, w8, w2a8) answer RAD_E_DTYPE at any other group,
the one code select() counts as a refusal. relayout_parity_test pins the hooks, plugin_test the
rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:49:18 +01:00
NunzeandClaude Opus 5.5 385318f81a core/format, tools: GGUF Q8_0, Q4_K and Q6_K tensors import as their planes -- rad-convert writes them without a recipe
A GGUF tensor of block type Q8_0, Q4_K or Q6_K could only be dequantised, so rad-convert reached it
through a recipe rule and re-quantised what was already quantised. ckpt_resolve now states the
planes libquant's ggml quantiser writes for the same blocks and marks the weight imported, and
ckpt_plane_rows splits each row's blocks into them bit for bit. The split is
core/format/ggml_planes.h, the reader's copy of lq_ggml's unpack functions, since the core cannot
call libquant; a type there is one table row, its planes and its split. Pieces of one block type
joined along rows import, an expert's slices of a stacked tensor included; mixed types and column
joins keep a GGUF reason.

The weight is not trivial, so the loader refuses it with the hint to serve the container
rad-convert writes, and ckpt_rows_f32 still dequantises it for a recipe. A rule that declines such
a weight is an error in rad-convert, since keeping its planes would hide that the rule did not
apply (spec.md §4.4).

Tests: quant_ggml_test holds every type of the reader's table to the quantiser's encoding,
checkpoint_test decodes the planes of Q8_0, Q4_K (one-block rows and a row join) and Q6_K against
the block definition and holds an expert's gate|up, two slices of stacked Q4_K tensors, to the same
blocks stored on their own, and convert_test runs a declining rule over a Q8_0 tensor, with the
GGUF writer moved to tests/gguf_writer.h for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:48:13 +01:00
baKon 6f034d989f config: list the decode-hot options and spell --draft-expert-placement as a word 2026-10-28 12:40:47 +01:00
baKon 6b544e0d39 core/place: --draft-expert-placement host and --expert-profile/--expert-pin-top (decode-hot residency) 2026-10-28 12:40:47 +01:00
Alex 9f707a0f67 driver+server: keyframes ride a latent upscale -- pinned at the small size, then re-encoded at the full size
A keyframe is pinned on the grid the steps run on, which is why 7935897 refused it with
latent_upscale. The pin can follow the switch instead: the server prepares each keyframe at the
small size too, the same way as at the canvas (stretch or centre crop), and the driver encodes
that picture into the keyframe's slot before the prompt pass, runs the small steps on the pack it
already lays out at the small size, and after the VUPSCALE pass encodes the canvas picture into
the same slot before the first full-size evaluation. The plugin reads its slots as before, so
neither the plugin nor the ABI changes; rad_builder.h documents the order. References keep their
own grids and are encoded once, as before.

Host: video_gen_test checks the pass order (E C S S U E S A D), each encode's size and slot and the
step rows at both sizes, and that a keyframe without its small picture is refused; videos_test
checks that each keyframe is prepared at both sizes with its stretch/crop and that the tower still
sees the canvas frame only. GUIDE, the ComfyUI node's README and tooltip no longer say keyframes
refuse latent_upscale.
2026-10-28 12:37:10 +01:00
mici81andClaude Opus 5.5 812cdeceb0 gemma3 + libr4d: the fused all-reduce junction on the lossy wire, for rows of whole 64-element groups
Under --tp-wire wht6 a TranslateGemma step of 2-3 sequences (16-24 rows) sent its junction as
three launches (the standalone lossy all_reduce, rmsnorm, rmsnorm_quant_fp8): the fused
ar_rmsnorm_post_quant_fp8 sent the exact wire only, and the compressed fused form needed a row of
whole 512-element chunks, which Gemma 3 27B's 5376 is not (10.5).

- r4d_fused_quant_fp8.hip: a row of whole 64-element groups that is not whole chunks ends in a
  partial chunk whose missing groups go out as zeros and are not stored back. Every real group is
  the same 64 elements as in the flat message, so its bytes and the sum are the standalone wire's.
  The (row, chunk) mapping is a template parameter (PAD, wire 6 only), so a row of whole chunks
  (Qwen3.8's 5120) runs exactly the code it ran before; as a runtime branch it cost a Qwen3.8 x4
  step 1.3-1.6 %. POST (the sandwich post-norm) on either wire.
- r4d_ar_entry.hip: K % 64 instead of K % 512 for wire 6, a size check of the padded message
  against the slot and the local pack, and the local pack's scale region a sixteenth of the slot
  instead of a thirty-second (padding adds up to 7 groups a row: a 2048-row prefill chunk would
  have overrun the old size).
- gemma3: the junction declares its lossy twin (op_ar6) and takes it up to kAr6MaxRows (24); a
  taller step keeps the standalone all-reduce, which spread over more blocks wins there (the
  fused kernel gives a block one row).

TranslateGemma-27B MXFP4 + DFlash2, 2x R9700, --tp-wire wht6 --draft-short-from 8, greedy,
aggregate tok/s, two rounds, junction limit never / 24 / any:
  2 streams (16 rows) 350.7 346.2 / 370.4 367.0 / 357.7 356.0
  3 streams (24 rows) 455.8 451.2 / 462.8 460.6 / 437.3 436.8
  4 streams (32 rows) 553.7 553.6 / 553.9 560.2 / 521.0 523.0
  8 streams (32 rows) 717.4 718.0 / 716.7 720.8 / 662.4 661.9
So 2 streams +6 %, 3 +2 %, 4 and 8 unchanged.

Bit identity: with --tp-wire-min-kb 1 (one stream's steps go out lossy) the fused path gives the
unfused one's greedy top-5 logprobs, 300 of 300 tokens, max |d| 0, on two pieces (x1 there 197.6
-> 212.6 tok/s). Qwen3.8-27B MXFP4: 300 of 300 identical on two prompts, speed unchanged.

Tests: arch_test (the lossy-wire junction test now also expects a 24-row step to fuse through the
twin, other op instances than the 8-row step's, and the 64-row prefill to stay unfused).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 12:20:10 +01:00
nickreese 9497bf9061 gbnf: share bounded-repetition chains across identical operands
Reuse one optional-link chain per repeated operand, preserving exact bounds and existing compile limits. Includes a synthetic multi-bound schema regression.

AI-assisted contribution; original implementation by claude-nanbeige.
2026-10-28 11:38:40 +01:00
griffin-warrior caa468389c kbench: state the coverage the pass measured in the report header
The header asserted "Every kernel of every loaded library ran" on a pass
whose own body counted 132 of 510 rows reached, so a coverage gap read as
full coverage. Print the sentence only when no declared row was left
unreached; otherwise name the count and point at Rows nothing ran. The
counts come from the same LibRow data the section below prints, so header
and body cannot disagree.

Reproduces on v1.13.0 (checked-in docs/KERNELS.md); the generator literal
is unchanged on current main.
2026-10-28 11:38:00 +01:00
griffin-warrior bbf90ebaa2 kbench: skip the report check where python3 is absent, like ops_doc
The counting is one python3 pass; exit 77 (ctest's SKIP_RETURN_CODE)
where python3 is not present, the same posture ops_doc takes for plugins
that will not dump.
2026-10-28 11:37:51 +01:00
griffin-warrior 1f4f4420e9 kbench: a report whose counts disagree with each other fails a test
The checked-in libr4d section of Rows nothing ran said 239 not reached
over a table of 243: 486c9331 added the four kv_store_streamed rows to
the table without the count (the previous regeneration, 1e968f6e, was
consistent at 239/239). The generator prints header and table from one
vector, so a file like this cannot be one run's output: it is a hand-
merged regeneration, and its headline (132 of 510) and section totals
read four rows short of the tables.

Count the rows each section emits (tests/kernel_report_check.sh), fail
the fast tier when a header and its table disagree or the headline no
longer adds up, and correct the report to the numbers its own tables
show: libr4d 243 not reached, 291 declared (the four rows are in
r4d_rows.cpp and the library reports them), headline 132 of 514.
Regenerating the report from one run on a rig with cards supersedes the
corrected numbers; the test keeps the file honest.
2026-10-28 11:37:51 +01:00
griffin-warrior 7a039cbb5c selftest: skip 2+ rank collective cases when the cards have no peer path
On a box whose cards expose no peer path (IOMMU off; the engine carries
the fact as device.p2p and selects host-mailbox rows around it), the
2-rank collective cases failed with RAD_E_DEVICE: ar_ipc_enable_peer
throws enable_peer: invalid device ordinal, init maps it, and a box
configuration the engine serves shows up as five failures. A card count
is not the fact the kernel contract gates on; hipDeviceCanAccessPeer
answers it without launching a kernel. Gate every collective case on it,
with a skip naming device.p2p, like the card-count gates. On such a box
the five failing cases now skip (targeted --case runs); the rest of
r4d_selftest is unchanged.
2026-10-28 11:37:41 +01:00
griffin-warrior 1720ed3f4a diag: name the build's media capability; docs(GUIDE): the ffmpeg row
An AUTO probe that misses leaves one STATUS line in the configure log,
and the engine boots green and 500s every media request; the startup
report -- the part of a log to paste into an issue -- said nothing about
the capability that decides it. mm::decoder_version() names it (the
libavformat version, or "absent (built without libav*)"), reported on
the startup report and /diagnostics (hardware.host.media), and GUIDE
1.1 lists the five -dev packages, the RAD_WITH_FFMPEG tri-state and the
symptom.
2026-10-28 11:37:31 +01:00
griffin-warrior 0bb00a836d docs(GUIDE): building against a ROCm SDK outside /opt/rocm
A userspace SDK (venv-style) finds hipcc via -DRAD_HIPCC, then device
compilation dies on clang's 'Could not find standard C++ header cmath':
ROCm's clang needs --gcc-install-dir for the distro libstdc++, and
--rocm-device-lib-path for the tree's amdgcn/bitcode. ROCM_PATH covers
discovery, not these. The working flag set, for the SDK and the core
system install, in 1.2 after the direct-CMake recipe.
2026-10-28 11:37:17 +01:00
griffin-warrior 586f77ae0a docs(TP4): gloss the shorthand the table uses
pp, cN, M, I, T, ti8, FK, W4, iq4r, hc_write, pp64K, QSA and L0..L3 are
used as if defined; the kill levels are defined below the table that
references them. One glossary block after the intro; every other word of
the document is unchanged.
2026-10-28 11:36:34 +01:00
griffin-warrior 27f1b27387 docs(QSA): libref implements all five QSA ops, not only qsa_block_key
The sentence in the Checking section predates the libref rows (ref_qsa.cpp
landed in the same release), and it reads as a reason to skip QSA's reference
comparison in a review. The library rows and the report's completeness matrix
show five registered ref rows. The remaining limitation is the subsystem one:
no oracle compares a dense run against a sparse one above the bound, and that
sentence stays.
2026-10-28 11:36:25 +01:00
StillDeadcode d4371cdd3a Merge pull request 'checkpoint: nomic config key aliases, RAD_MAP_TRANSPOSE honouring src_index' (#287) from steki/radiance:nomic-config-aliases into main
Reviewed-on: https://codeberg.org/StillDeadcode/radiance/pulls/287
2026-10-28 11:36:03 +01:00
Brandon Bertelsen 6a192ff0d7 clef: skip the lm_head on rows the head answers 2026-10-28 03:54:15 -04:00
Brandon Bertelsen 65a9e78acf rad-convert: clef needs --arch clef, refused otherwise 2026-10-28 03:00:56 -04:00
Brandon Bertelsen 0b756e64f8 docs: drop docs/adr; the guide's clef section carries the design 2026-10-28 02:52:53 -04:00
Brandon Bertelsen 72d192dbf6 clef: the head's rows bounded at 32768 prompt tokens, not the context
(cherry picked from commit fdc445a7cf1f6de620df6148d0482c8c795b2b27)
2026-10-28 02:37:49 -04:00
Brandon Bertelsen b1da6a28bd clef: the head in plugins of its own (arch/clef_bf16, arch/clef_fp8); the qwen35 plugins untouched 2026-10-28 02:37:49 -04:00
Brandon Bertelsen a96bfe821f clef: the joint schema head on the card, served on /v1/systemone 2026-10-28 00:33:55 -04:00
Brandon Bertelsen 555fbf62f5 ops: seg_softmax_pool, each segment's rows summed under the softmax of their scores 2026-10-28 00:33:55 -04:00
Brandon Bertelsen 5a2732f063 abi: a request's words for the plugin (RadBatch::plugin_words), ABI 32 2026-10-28 00:33:55 -04:00
Brandon Bertelsen d60da58732 docs: ADR 0001, clef's head on the GPU 2026-10-27 21:33:54 -04:00
Brandon Bertelsen 82c114e84e server: clef's prompt and spans, /v1/decisions, decision in capabilities 2026-10-27 19:48:55 -04:00
Boris Manojlovic 6c33ee4e12 builder: narrow an f32 source to a bf16 declaration at load
The builder accepted one conversion direction beyond the exact widening it already did: a single-plane RAD_F32 source declared RAD_BF16 is rounded to nearest even at load (WeightInfo::narrow, beside widen). It is staged like a widened weight, never read in place from the container, and the planner and oracle treat it as 'not the container's stored bytes'. build_test covers the declaration, the stored dtype and size, and that it is not file-direct.
2026-10-27 20:59:42 +01:00
Boris Manojlovic fd40bb430c nomicbert: architecture plugin for nomic-embed-text-v2-moe
Post-norm encoder with fused Wqkv and biases, NeoX rotary, non-causal attention, a dense MLP on even layers and a top-2 of 8 expert MLP on odd layers, mean pooling into the pooled f32 buffer for /v1/embeddings. The checkpoint is f32; data/recipes/nomic-embed-v2-moe-bf16.recipe casts the linears, the token embedding and the token-type table to bf16 (the device kernels read bf16), norms and biases stay f32. The checkpoint's shared experts.bias is not applied: against a llama.cpp run of the same checkpoint at Q8_0 the variant without it matches best (cosine 0.9994; the others 0.9990 to 0.9993), and llama.cpp's own nomic-bert-moe does not carry it. Verified on a gfx1201 card and on libavx/libref against a pure-float32 torch reference: mean cosine 0.99995, min 0.99983 over 20 texts. Unit tests declare and lint a cut-down model. Not verified: inputs above 512 tokens against a reference on the device, other quantisations.
2026-10-27 20:58:47 +01:00
Boris Manojlovic 4853db97db checkpoint: nomic config key aliases, RAD_MAP_TRANSPOSE honouring src_index
meta_from_config_json reads the nomic spellings (n_layer, n_embd, n_head, n_inner, n_positions, moe_top_k, layer_norm_epsilon, rotary_emb_base) as fallbacks in the same chain as the usual keys; existing checkpoints parse as before. RAD_MAP_TRANSPOSE can first take one expert's sub-tensor of a stacked table: src_index[0] picks the dim-0 sub-tensor of a rank-3 stack, or, with src_rows[0] > 0, the row block of a rank-2 stack flattened over its rows. map_transpose_slice() declares it; map_slice() takes the same optional sub_rows. Tests in checkpoint_test cover the aliases, the [8,4,3] case, the flattened case and an out-of-range index.
2026-10-27 20:58:47 +01:00
Boris Manojlovic 157450a82b gemma4_bf16: per-layer MLP width for use_double_wide_mlp (Gemma 4 E2B), and the bf16 descriptor for unmodified Google E2B/E4B directories 2026-10-27 20:57:20 +01:00
Boris Manojlovic 13d3a8b7af checkpoint: nomic config key aliases, RAD_MAP_TRANSPOSE honouring src_index
meta_from_config_json reads the nomic spellings (n_layer, n_embd, n_head, n_inner, n_positions, moe_top_k, layer_norm_epsilon, rotary_emb_base) as fallbacks in the same chain as the usual keys; existing checkpoints parse as before. RAD_MAP_TRANSPOSE can first take one expert's sub-tensor of a stacked table: src_index[0] picks the dim-0 sub-tensor of a rank-3 stack, or, with src_rows[0] > 0, the row block of a rank-2 stack flattened over its rows. map_transpose_slice() declares it; map_slice() takes the same optional sub_rows. Tests in checkpoint_test cover the aliases, the [8,4,3] case, the flattened case and an out-of-range index.
2026-10-27 20:17:47 +01:00
mici81andClaude Opus 5.5 b74a6b2ece spechub: mtp_couple_verify walks the live candidates only (151 -> 31 us a launch)
The sampler's candidate plane is kSampleCandidates (1024) wide and at top_k 20 about 20 entries are live,
but the coupled verify ran its eligibility scan (global memory, one entry at a time) and its sums and
walks on one thread over all 1024: 92-151 us a launch at any row count, on the critical path of every
coupled step. The workgroup now checks validity and takes the maximum in parallel (order-free, exact),
compacts the live indices in ascending order into LDS, and the serial sums and walks run over that list
in the host reference's order, so the token is the same bit for bit.

vtime (n_cand 1024, 20 live, every row bound): 151.7 / 92.8 / 100.5 -> 31.3 / 32.2 / 35.9 us at 4 / 16 /
64 rows; device == host on every row.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 18:37:28 +01:00
mici81andClaude Opus 5.5 ce79b12126 dflash2 coupled walk: Q at temperature 0.6 by default
Q's temperature (RADIANCE_DFLASH_Q_TEMP) only moves acceptance, never the
output law. Held-out tokens per verify step at request temperature 1, x4,
32 rows of the eval set, Qwen3.8-27B MXFP4 with a DFlash2 drafter fine-tuned on our traffic, our serving flags:
ordinary rule 3.52; coupled with Q at 1.0 3.71, 0.7 3.88, 0.5 3.85,
0.35 3.77. The walk's scores are flatter than the target's law, so a
sharper Q puts its mass where the target's is; 0.6 is the default now.

At 0.6, 3 interleaved rounds against the ordinary rule (64 held-out rows
at x4, and three requests at x1 and x4, 1500 tokens, T 1):
- tokens per step 3.53 -> 3.82 (+8.2 %), every round apart
  (3.50/3.49/3.61 vs 3.82/3.79/3.86); time-weighted decode +5.4 %;
- decode per stream: 0.7k prompt x1 174.1 -> 181.7 (+4.4 %), x4 144.6 -> 153.8
  (+6.4 %); 22k prompt x1 186.6 -> 191.0 (+2.3 %), x4 135.1 -> 146.2 (+8.2 %);
  41k prompt x1 186.9 -> 196.8 (+5.3 %), x4 125.8 -> 135.0 (+7.3 %);
  aggregate at x4 +5.3..+5.5 %.
Coupled at 0.6 against the ordinary rule, 5000-6000 samples of tokens 1-4
of two chat prompts: chi-square p 0.62..0.99.

The walk's kernel issues each candidate's successor slice and unary score
before the predecessor's codebook row (both are independent of it). This is
the build measured above; it moved the pass time within noise (91.3 -> 90.8
us at M 16, steps 7), and tokens, ids, x and status still match the host
oracle on all 40 random lattices (q by FP64 exp ulps, <= 4.3e-16).

ctest (the environment-only tests excluded) 105/105.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 18:37:28 +01:00
mici81andClaude Opus 5.5 cb0abe9ac7 dflash2: lossless coupled acceptance at T > 0 (--draft-coupling on)
DFlash2's drafts were the greedy walk over its candidate lattice, accepted
only when they equal the target's own sampled draw: P(y == x) instead of
rejection sampling's sum min(P, Q). --draft-coupling already did the latter
for a linear MTP head; this extends it to the block drafter.

- dflash_couple_propose (spechub plugin, device row + host oracle): after
  dflash_select, the same lattice walked again, sampled. Position l scores
  each candidate as dflash_select does (unary + low-rank edge from the
  previous token), Q_l = FP64 softmax of score / q_temp over the best eight
  in-vocabulary candidates, x_l ~ Q_l at (seed, base, KEY_DRAFT + l + 1),
  x_l is the next predecessor. Position l writes round l+1's state row, so
  the engine binds it and the sampler's mtp_couple_verify (maximal coupling,
  residual (P - Q)+) verifies it exactly as an MTP round. Q depends on the
  committed text and on x_0..x_{l-1}, never on the verify, and is stored
  exactly. Greedy requests keep dflash_select's tokens (status 0); a draw
  for another card or a Q that cannot be built takes the walk's argmax and
  the ordinary verify (status -1). The shared arithmetic is in
  abi/rad_spechub.h (rad_dflash_couple_step / _walk).
- The block driver stages one draw per drafting row before the query pass,
  reads the states back with the slots and binds them after the commit
  (Engine::bind_couple, shared with the serial driver).
- qwen35_fp8 declares the planes and the op under --draft-coupling;
  RADIANCE_DFLASH_Q_TEMP sets Q's temperature (default 1, exact at any).
- Default (flag off): no op, no plane, no change.

Gates:
- spechub_dflash_couple_test (CPU): emitted token vs P by chi-square over 3
  seeds each, Fisher-combined p 0.135..0.919, for Q = P, Q on fewer tokens
  than P, Q mostly outside P, top_k 20 + top_p 0.95, top_p 0.6, top_k 3 at
  T 0.7, peaked Q; acceptance = sum min(P, Q) within 5 sigma; the walk's
  stored Q equals the softmax of its scores (1e-5) and x follows it (p
  0.993); the whole draft/verify/bonus loop over 3 tokens matches the
  target's autoregressive law (combined p 0.62 at q_temp 1, 0.67 at 0.5,
  0.024 with every 2nd step on the ordinary verify).
- Device row vs host oracle, 40 random lattices at the production geometry
  (V 248320, K 16, R 256, steps 7/3, M 1..16): tokens, x, ids, status
  identical; q differs only by FP64 exp ulps (<= 4.3e-16 relative).
  91 us a launch at M 16, steps 7.
- Engine, Qwen3.8-27B MXFP4 TP2, our serving flags, 4-6 tokens of two chat
  prompts at T 1 / top_p 0.95 / top_k 20, 5000-11000 samples per arm:
  coupled vs ordinary speculation chi-square p 0.23..0.81 (tokens 1-4 and
  pair 1-2); both differ from no speculation on one prompt by the same
  amount (the verify-vs-decode logits, not the rule).
- Flag off, old build (up12 5dbb5dc) vs this: greedy top-5 logprob traces
  identical over 300 tokens (spec 7 and 0, two requests each), 6/6
  fixed-seed sampled texts identical.
- ctest (the environment-only tests excluded) 105/105.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 18:37:28 +01:00
baKon 72a58d0c0c core: --expert-stats FILE, the routed experts every layer selects, from the heat engine's histograms
Which experts a served model actually uses, per layer, is what deciding how to spend an expert's
bits needs, and the core already has it: every routed layer's counts come back to a host bank once
a pass, and the heat engine drains the landed banks once a step, one step behind. --expert-stats
FILE credits the same rows to a host tally and writes it as JSON every 30 s and at shutdown,
through a temporary and a rename (place/xstats.h). No device work, no copy, no synchronisation;
where the heat engine is off (every expert in VRAM, a static plan) the drain runs for the tally
alone, and at shutdown the streams are drained and the banks still in the ring are credited.

Counts are filed by step kind: prefill (no decode rows), decode, mixed (one histogram cannot split
it) and draft, which is every routed layer past the trunk (an MTP or DSpark head; its bank holds
the step's last draft pass). Each rank files its passes' kinds when it issues them.

A histogram row is the rank's own experts from zero, so under expert parallelism (deepseek41) it
is the rank's slice. The map from a rank's index to the model's expert id comes from the container:
index e is the unit declared with group expert e, and the directory entry of that unit's weight
names the expert. An expert several ranks hold (a width slice each) is counted on the lowest; a
rank that counts nothing does not drain for the tally. Without directory ids the map falls back to
the indices (one rank, or every rank holding the model's count) or to rank order.

The file carries the model, the routed layers, each layer's expert count and top_k, tokens and
steps issued by kind, histograms, passes, observed tokens and selections per kind and layer, the
per-rank drain counters (lost, unmapped, unclassified), and counts[kind][layer][expert].
/server_info names the file. Router weights are not summed: they stay on the card.

Tests: xstats_test (the map, the tally's kinds and merge, the file); config_test lists the flag
and checks it is off until it names a file.
2026-10-27 18:34:32 +01:00
Constantin fb8cb95b7e docs: verify non-target kernel dispatch 2026-10-27 18:28:46 +01:00
Constantin c2565369e9 docs: record BF16 W4 review follow-up 2026-10-27 18:28:46 +01:00
Constantin d947d7139e fix: preserve BF16 W4 CPU narrowing semantics 2026-10-27 18:28:46 +01:00
Constantin da8c95d4d9 docs: clarify shared R9700 power caps 2026-10-27 18:28:46 +01:00
Constantin fbffd33e22 docs: record third-card benchmark confirmation 2026-10-27 18:28:46 +01:00
Constantin 05ccf42964 docs: record cross-card HYV3 throughput check 2026-10-27 18:28:46 +01:00
Constantin 31ac68549b docs: record launcher compatibility smokes 2026-10-27 18:28:46 +01:00
Constantin 2c9d415166 docs: record full HYV3 validation and A/B results 2026-10-27 18:28:46 +01:00
Constantin 85b5388089 docs: record release-based GPU and inference smoke 2026-10-27 18:28:46 +01:00
Constantin c301f3315e docs: record release-tag PR build validation 2026-10-27 18:28:46 +01:00
Constantin edbdc44b8e docs: verify engine build on latest upstream 2026-10-27 18:28:46 +01:00
Constantin 87cb41b5fa docs: distinguish validation from final rebased base 2026-10-27 18:28:46 +01:00
Constantin 9d6ae971e8 docs: record local Qwen validation artifact hash 2026-10-27 18:28:46 +01:00
Constantin ad26c95675 docs: record rebased HYV3 validation results 2026-10-27 18:28:46 +01:00
Constantin 3a1706f1fa Document HYV3 optimization scope, measurements and validation
## Summary

Optimize HYV3 decode and the shared W4/W5 and signed-I4 expert paths:

- Compact the asymmetric W4/W5 one-row epilogue without changing its WMMA or split-K arithmetic.
- Pack per-128-scale I4 experts into `t16k64` fragments and load one routed row directly into registers; keep prefill compatible with the same packed weights. Subgroup-scaled codebooks retain their layout.
- Narrow BF16 activations to F16 inside the W4 decode GEMM, replacing the separate activation cast with the same rounding.
- Reuse fused Q/K normalization/RoPE/KV-store, residual norms, routing and the TP1 shared/routed gather in HYV3. TP2 retains separate arm reductions.
- Add cold-weight timing modes, canonical/byte/guard checks, independent nibble-address tests and an affected-path/measurement report.

## Validation

On merged `main` (`2d2f638`):

- `gfx1201` kernel library, selftest executable and all three HYV3 plugins: compiled.
- Release and ASan/UBSan/leak architecture suites: passed.
- Layout parity: 1,145 checks over 20 cases, including GPTQ, rotated experts and subgroup codebooks: passed.
- Reference arithmetic: 136,622 checks over 254 cases passed with two failing upstream inventory/sweep cases excluded; the same failures were reproduced using unchanged upstream test source.

A full engine/unit run is blocked by upstream's missing KV-stream headers. No GPU workload or serving-service changes were made during this validation pass.

## Measurements and readiness

Earlier TP1 HYV3 measurements reached 115.678 decode tokens/s versus 90.290 initially; the isolated expert-packing step measured 95.392 to 103.364. These used a highly repetitive 10,030-prompt/2,000-output `alpha` workload on an R9700. They are **historical, not measurements of this rebased PR**, and establish neither general throughput nor gains on other models.

Keep this PR in draft until current-base GPU numerical/guard checks and matched throughput/text/tool-quality measurements pass for HYV3 and the other affected W4/W5/I4 paths. The historical tool subset did not clear its earlier guard and needs an isolated rerun.

See [the optimization report](docs/benchmarks/hyv3-w4-decode.md) for affected models/encodings, historical results, validation details and remaining gates.
2026-10-27 18:28:46 +01:00
Constantin 9916dcace3 Fold HYV3 TP1 shared combination into the routed gather
Prepare a unity-gate plane once per step and use the existing gather at TP1 while preserving routed BF16 rounding before the shared add. Retain independent arm reductions and combination at TP2, with multi-pass graph and routing-rounding checks.
2026-10-27 18:28:46 +01:00
Constantin 36c39efdca Fold HYV3 residual adds into the following norms
Reuse the existing BF16-rounded add/norm fusion while retaining final output materialization and the original collective positions. Cover TP1, TP2 and multi-pass prefill without introducing calibration hooks.
2026-10-27 18:28:46 +01:00
Constantin d59cdce040 Use fused QK normalization RoPE and KV store in HYV3 decode
Wire the existing fused prologue into the private HYV3 attention helper for small BF16-KV batches. Retain the separate operations for other shapes and KV layouts, with graph coverage of both paths.
2026-10-27 18:28:46 +01:00
Constantin bb48b14005 Reuse BF16 add for HYV3 shared/routed combination
Replace the equivalent FP32 cast/add/cast chain with the existing BF16 add and enable the existing fused router for HYV3. Preserve separate tensor-parallel arm reductions and BF16 rounding boundaries; add the reference arithmetic check.
2026-10-27 18:28:46 +01:00
Constantin 492d33c470 Narrow BF16 activations inside asymmetric W4 decode GEMMs
Replace the separate BF16-to-F16 activation cast with the same nearest-even narrowing on load. Keep existing split-K and WMMA arithmetic. Test finite and raw-bit activations, canonical arithmetic, byte parity and output guards; provide BF16-input cold-weight timing sweeps.
2026-10-27 18:28:46 +01:00
Constantin aeedae4027 Pack per-128 I4 experts for coalesced one-token GEMMs
Change only the per-128-scale load-time expert layout to 16-column/64-K fragment tiles. Add the register-loaded one-row kernel, keep staged prefill compatible, and leave subgroup-scaled codebooks row-major.

Update the stored-layout hashes atomically with the layout and add independent canonical-nibble address checks.
2026-10-27 18:28:46 +01:00
Constantin 692ce7ed8b Measure routed-expert GEMMs with cold live-weight banks
Add the TP1 HYV3 expert geometry to the timing harness while keeping the Flash-Next mode. Rotate actively addressed codes and scales and check all output bytes across dispatch forms.
2026-10-27 18:28:46 +01:00
Constantin 9f90451599 Prune padded-row work from single-row asymmetric W4/W5 GEMMs
Keep WMMA, group and split arithmetic unchanged, but stage and reduce only the live row. Add byte parity, guard and canonical-arithmetic cases over legal launch geometries.
2026-10-27 18:28:46 +01:00
Constantin 2ef0536051 Expose a cold-weight asymmetric W4 GEMM timing sweep 2026-10-27 18:28:46 +01:00
Constantin 99edcc97e0 Cover head-128 BF16 fused QK normalization in existing kernels
Extend registry bounds for the existing qkv_norm_rope_kv_store implementation and exercise the head-128 GQA-8/16 shapes numerically. No HYV3 architecture hook is included in this kernel-only branch.
2026-10-27 18:28:46 +01:00
orca f69c9d8324 test(isa): the two parsers, on fixtures
isa_tools (fast tier) runs libr4d/isa/selftest.sh: no build tree, no card, no
ROCm. rows.awk at the nine 24-VGPR boundaries and at the wave64 quantum;
waterfall.awk on a forward branch after a movrel (not a loop), a real back-edge
(a loop), a movrel with no branch, and a kernel with no movrel after a kernel
that has one.

Against the code this replaces, five of the nine occupancy checks fail (97,
121, 145, 241, 256) and the forward-branch case counts a loop where there is
none. The rest pin behaviour that is right today: the movrel-with-no-branch row
and the empty kernel stay as they are, and the seen-flag reset in flush() has no
observable case in this tree -- waterfall.awk resets it per kernel so a later
edit cannot reintroduce one.
2026-10-27 18:24:13 +01:00
orca f406c4dafc fix(isa): fail closed, and count a back-edge, not any exec branch
Both instruments could report a clean tree after inspecting nothing.
res.sh and waterfall.sh skipped an object whose code object would not extract
(`|| continue`), skipped a disassembly that failed, and then printed a header
and a short table and exited 0. waterfall.sh additionally counted every
s_cbranch_exec* after a movrel -- a forward branch is not the loop that re-runs
the movrel -- and carried that flag across kernels, because flush() reset n and
loops but not seen.

Now: no .hip.o under BUILD, a code object that will not extract, a
llvm-readelf/llvm-objdump that fails, or not one kernel inspected all exit 1. A
HIP translation unit with no kernels carries no .hip_fatbin and is skipped, not
failed -- one exists in this tree (r4d_ar_entry), which is why "every object must
extract" was not an option. The parse is waterfall.awk, and a branch counts only
when its target label was already defined above it, i.e. is a back-edge.

Measured over every kernel this tree builds (761 movrels): 199 loops become 101,
19 rows change, and 12 of them are r4d_ar_twoshot_Nrank_exact reporting 7 where
it has no back-edge at all:

    r4d_ar_twoshot_Nrank_exact  7 -> 0   (x12)
    r4d_hc_bf16                 6 -> 1
    xprefetch                   4 -> 3
    r4d_ple_gate_bf16           3 -> 0
    r4d_ngram_ids               2 -> 1
    spechub                     9 -> 8, 2 -> 0
    r4d_encoder_bf16            1 -> 0
2026-10-27 18:23:49 +01:00
mici81andClaude Opus 5.5 74e701ea17 prefix cache: a snapshot at a head other prompts share
A model with snapshots (recurrent state, or a sliding window the cache does not index) resumes a
hit only at a snapshot, and those are taken on the checkpoint interval and at each prompt's tail.
A head every request starts with -- the same system prompt or instructions in front of a different
text, as a translation service sends its pieces -- is usually shorter than an interval, and each
tail is its own, so the head was computed again by every request.

The cache now counts the blocks published right after each block (Entry::n_children) and reports
where a lookup leaves a head that at least two cached prompts already left differently
(CacheHit::branch_at; one is not enough, the next prompt could be the same conversation going on).
When nothing resumes within kSharedHeadMin (256) tokens of that point, admission sets the request's
own checkpoint there (Request::checkpoint_at, which n > 1 already uses), and the requests after it
skip the head.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 18:17:21 +01:00
baKon 731a23a65a tools: rad-chatparse --request, one chat request rendered and read back as the server does
--request REQ.json --rad MODEL.rad renders an OpenAI request through parse_chat_request with the
server's own adapters (the container's vocabulary, --override-chat-template, --chat-template-kwargs,
the architecture plugin's declared reply format from --home or the template's analysis with
--no-plugin), and reads each --reply file as the model's tokens: stopped at end of generation,
detokenised with the request's preserved tokens, parsed whole (the non-streaming body) and through
the SSE emitter (reassembled as a client does), with the tool-call grammar run over the tokens as
the sampler masks them. --render-raw renders a template with any JSON context through the vendored
jinja engine, for message shapes a request cannot carry. One JSON object on stdout.

rad-chatparse is now a plugin host: rad_core whole-archive with exports, the legacy parser's sources
compiled in.
2026-10-27 18:17:06 +01:00
baKon fe27edb4da core/text: typed argument tags, a format whose argument tag says JSON or string
RadChatFormat/ChatFormat gain arg_json_value_prefix, a second value prefix written in place of
arg_value_prefix before a JSON value (DeepSeek-V4.1's DSML: string="false" before JSON,
string="true" before text). The tag the reply writes decides how its value is read, for declared
and undeclared names alike, and JSON that does not parse is kept as its text; the grammar writes
the tag each argument's schema calls for and either for an undeclared name. The field sits at the
end of the struct, so an older plugin's shorter struct reads as unset and nothing changes for it.
chat_format_check refuses a typed format without both prefixes, with prefixes not told apart, or
with string-typed other values.

Tests: reading, streaming at every truncation, grammar arms per schema, refusals, ABI tail.
2026-10-27 18:16:26 +01:00
baKon 70639f7ea2 core/text: a template that cannot render a conversation is refused at load, not thrown
ChatTemplate::load ran the thinking probe, the first full render, outside any handler; a template
that compiles but fails in the reply-format analysis (here llama.cpp's own DeepSeek-V4.1 template,
which calls dict()) threw out of load and ended the process. It is now RAD_E_FORMAT with the
template's words, as a failing render already is per request.
2026-10-27 18:15:58 +01:00
baKon fa8c746497 core/format: an imatrix entry is found under llama.cpp's spelling, .weight and all
llama.cpp names each imatrix entry by its tensor (blk.0.attn_q.weight.in_sum2); importance_for
stripped .weight from the weight's name and looked up only the bare stem, so --imatrix matched
no weight from a llama.cpp file: the codebook types that need it (iq1_s, iq2_xxs, iq2_xs) were
refused and every other type was quantised without its importances. Both spellings are found now,
per-expert rows included, and the row is read under the entry's own name.

Tests: format_test a_converter_weight_name_finds_llama_cpps_spelling (a dense and a stacked expert
entry spelled .weight.in_sum2, a missing expert, a wrong width) fails without the change and
passes with it; a_converter_weight_name_finds_its_imatrix_row (the bare spelling) is unchanged.
2026-10-27 18:15:44 +01:00
orca b56139a96a fix(isa): wave32 VGPRs allocate in 24s, not 8s
res.sh rounded the VGPR count up to a multiple of 8 before dividing the SIMD's
1536 registers, so 128 VGPRs reported 12 waves where the hardware allows 10, and
256 reported 6 where it allows 5. gfx1201 wave32 allocates in multiples of 24;
wave64 keeps the 8 the script used for both, which nothing measured says is
wrong.

gfx1201 Wave32, 1536 VGPRs/SIMD, measured over every kernel this tree builds
(3369 rows, ROCm 7.15 / clang 23, -O3) -- 755 rows change:

    6 -> 5   214 rows   (256 VGPRs)
    11 -> 10 119 rows
    14 -> 12 118 rows
    10 -> 9  112 rows
    13 -> 12  96 rows
    12 -> 10  96 rows

The parse moved into rows.awk so selftest.sh can check it at the boundaries
(96/97, 120/121, 144/145, 240/241) without a build tree. Five of those nine
boundary checks fail on the arithmetic this replaces.
2026-10-27 17:57:10 +01:00
orca 68468fc957 test(gemm): cover incomplete W4A8 prefill M tiles
The row was only ever run at M = 256, which is a whole number of tile heights,
so no test entered the guarded epilogue. Every tile height the prefill arms
dispatch (64, 96, 128, 256 -- tile_bmbn) now gets the rows just past its tile
and one row past that, which is the shape that reads Ascale[M].

Smoke coverage: the harness checks the return code and the stream sync, not the
numbers, so this catches a fault or a rejected launch, not a wrong tail.
2026-10-27 17:55:52 +01:00
orca 9d37941a44 fix(gemm): guard the W4A8 prefill tail scale read
The epilogue computed $v = acc * Ascale[m]$ before the store guard, so on the
last row tile of an M that is not a multiple of the tile height it named
Ascale[M] -- a row the caller does not own. The read is under the guard now.

inside is STFAST && (m0 + BM <= M), so it implies m < M for every row of the
tile, and n < N holds unconditionally because the launch rejects N % BN != 0.

No behaviour change is claimed: on gfx1201 at -O3 the compiler already
predicates the whole scale-and-store block (s_and_saveexec + s_cbranch_execz
around both the global_load_b32 of the scale and the store), so the published
binary does not issue the invalid load. This keeps the source honest for
compilers and ISA levels that do not.
2026-10-27 17:55:10 +01:00
Deadcode 6645337f69 radiance 1.13.0
New models:
- Tencent Hy-Memory (HYV3) from its BF16, FP8 and GGUF checkpoints, with its native tool calls
- M2XFP4: metadata-augmented MXFP4 weights for Qwen3.8-27B and its DFlash2 drafter (top-1 89.1% ->
  92.4% against plain MXFP4), its quantiser and recipe, and ParoQuant's M2XFP4 checkpoints
- Gemma 4 E2B/E4B audio input; NVIDIA-Nemotron-3.5-Bolt-E4B in int8 and 4-bit, on two cards by
  default; Ornith-1.5-122B compose files

Speed:
- Weight reads beside the decode all-reduces (qwen35_fp8, gemma3; --weight-prefetch, on by default):
  the 27B MXFP4 with DFlash2 61.2 -> 67.9 tok/s at c1, TranslateGemma 27B +13%
- Head-256 split-KV decode attention at 256 workgroups and without bank conflicts (27B: +3-5% a
  step at 25-41K context), and the prefill KV split for small launches (a short turn over a long
  context decodes the other sequences 27% faster in that step)
- MXFP4 decode gate_up, activation and fp8 quantiser in one launch (27B, Gemma 3 up to 64 rows:
  TranslateGemma +2-5% at 2-8 streams)
- ParoQuant int4/int5 tiled GEMMs 6-9% faster
- Speculation: a step's tokens are sent before the drafter's passes end, no step waits behind one
  that ends its requests, and the MTP head's first draft no longer collapses after short chats in
  the prefix cache

Features:
- --kv-resident N: KV streaming for a context bigger than VRAM (qwen4exp_fp8, GLM-5.3)
- MiniMax-H3: reference media and keyframe conditioning with the VAE encoders
- Krea 2 rebalance presets balanced, detail and subtle
- The dashboard's request history; a stall watch that reports a frozen step's thread and stack
- rad-tune at the served configuration, collectives measured as the exchange; Gemma 4 E2B/E4B's
  per-layer embeddings read ahead off the step path
- A GPTQ calibration tap and recipe for Gemma 4 31B's w4a8 container

Fixes:
- The two-rank all-reduce checks that a peer's push has landed before reducing it
- z-lab's DFlash drafter on Gemma 4 31B keeps drafting after a prefix-cache hit
- MiniMax-H3's modulation rows

Changes: Plugin ABI 31: out-of-tree plugins must be rebuilt. RADIANCE_PREFETCH_BESIDE is
--weight-prefetch now; RADIANCE_NO_HUGE_PAGES, RADIANCE_IDS_EARLY, RADIANCE_ATTN_BAND_SPLIT,
R4D_PREFILL_SPLITS, RAD_PLE_TIMING and RAD_PLE_CACHE_ROWS are gone.
2026-10-27 16:47:35 +01:00
hugypufyandClaude Opus 5.5 341cedfc2d data/recipes: q38-27b-paro-m2xfp4-df2.recipe -- a ParoQuant M2XFP4 Qwen3.8-27B with the DFlash2 drafter
q38-27b-paro-mxfp4-df2.recipe for a paroquant_m2xfp4 checkpoint: the trunk is imported as it
ships, rotations included, and the drafter's linears go to M2XFP4 as in q38-27b-m2xfp4-df2.recipe.
TOOLS.md names the import beside rad-convert's other imports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:22:39 +01:00
hugypufyandClaude Opus 5.5 2c645333a1 core/format, arch/common, libr4d: the ParoQuant M2XFP4 import -- Import::ParoM2 reads a paroquant_m2xfp4 checkpoint's planes and rotations, served as rotated MXFP4 is
A paroquant_m2xfp4 checkpoint (format m2xfp4, groups of 32, subgroups of 8, rotation groups of
128) is imported as ParoQuant's MXFP4 is: the codes, exponents and weight_meta bytes become the
m2xfp4 scheme's three planes byte for byte, joined row by row, with the learned rotations beside
them as the givens tables. LinearFP8 declares the rotated form like the rotated MXFP4 one, through
givens_dense_quant into its own E4M3 pair, and libr4d's layout hook and both m2xfp4 rows accept
it, the rows running a fused projection's parts (pb1/pb2) one launch a part as the mxfp4a8 rows
do. libref accepts the rotated planes and runs the parts as its mxfp4a8 arm does; libavx serves
no M2XFP4. checkpoint_test covers the import, quant_m2xfp_test libref's parts and r4d_selftest
libr4d's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:22:39 +01:00
mici81andClaude Opus 5.5 b6ad757bfa gemma3: the gated gate_up fold up to 64 rows (RADIANCE_G3_FOLD_ROWS), and prefetch knobs
The gate_up GEMM + gelu_mul + quant_act_fp8 fold ran only up to 8 rows; at 2-8 concurrent translations with
speculation a step is 16-64 rows and the three kernels ran apart. gemm_mxfp4a8_gated_gemv_wide (9 <= M <= 64,
K >= 2688) is gemv_wide at two column tiles a block, the gate tile j and its up tile n/16 + j: each K-wave loads both
tiles' weights and reads the activation once; the wave partials are summed in gemv_wide's order and the narrow fold's
epilogue quantises, so codes and scales are byte-identical to the unfused path. No spill (96-196 VGPRs, RT 1-4).

RADIANCE_G3_FOLD_ROWS (0 = today's 8) sets the fold band; RADIANCE_G3_PF_ROWS / _PF_MIB / _PF_EARLY expose the
prefetch beside the all-reduces (measured: no gain, defaults unchanged). Unset knobs keep the pinned graph and steps.

Measured on 2x Radeon AI PRO R9700, TranslateGemma 27B (MXFP4 GPTQ, DFlash2 drafter, speculation 7), greedy held-out
translations, aggregate tok/s, 2 interleaved rounds:
| fold ceiling | x2 | x4 | x8 |
| 8 (today) | 289.9 | 521.2 | 686.3 |
| 16 | 298.6 (+3.0 %) | 521.0 (-0.0 %) | 686.9 (+0.1 %) |
| 32 | 296.9 (+2.4 %) | 541.6 (+3.9 %) | 682.7 (-0.5 %) |
| 64 | 297.8 (+2.7 %) | 549.0 (+5.3 %) | 700.0 (+2.0 %) |

Tests: r4d_selftest gated wide fold byte-for-byte against gemv_wide + gelu_mul + quant_act_fp8 (or gated_quant_fp8)
for TranslateGemma's 21504x5376 at M 9-64 and other shapes (156 ok, 0 FAIL on gfx1201); arch_test gemma3 16/16
(defaults keep the pinned graph and steps, knobs move only what they name).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-26 10:08:01 +01:00
mici81andClaude Opus 5.5 96bc0465b3 attn prefill h256: the small-launch KV split for every GQA geometry
The KV split of the head-256 / GQA-6 prefill kernel (few workgroups -> split the KV walk into segments,
f32 partials, the split-KV merge with a cu span) now serves every head-256 prefill row: GQA 12
(4-token pages: fp8, bf16, fp8_v4, k6_v4), GQA 6 with 4-token pages (the same four), GQA 8, GQA 4 and
GQA 2 (fp8, bf16). The fewer KV heads a rank holds, the more it matters: at TP 2 Qwen4-Exp (GQA 12) and
Qwen3.5-35B-A3B (GQA 8) keep one KV head per rank, so a 53-row tail runs 2 workgroups on 32 WGPs.

The host side (the law, the scratch sweep, the scratch-capped count, R4D_PREFILL_SPLITS, the merge
launch) moves into r4d_attn_prefill_split.h; each unit passes its own geometry (query rows per workgroup
= 24 * 16 / gqa, tile 48). The GQA-6 unit is refactored onto it with the same law (Qwen3.8-27B in the
engine: greedy top-5 logprobs bit-identical before and after at 300 positions after 25k and 41k prompts).

Left unsplit: GQA-2 launches with a sliding window (the partition has no window floor; a 1024 window
walks at most ~26 tiles), the lossy e4m3 legs, and the head-128 / head-64 legs sharing the bodies.

Split count, one sequence, N query rows -> S: GQA 12 with 1 KV head: 1-32 -> 32, 53 -> 16, 160 -> 6,
1024 -> 1; GQA 8 with 1 KV head: 53 -> 16, 345 -> 4; GQA 2 with 4 KV heads: up to 160 -> 8. Scratch at
declare at most 25.4 MB per row. Split vs unsplit: at most 0.000488 (fp8 KV) and 0.0039 (bf16, fp8_v4,
k6_v4; about 1 bf16 ulp).

Tests: the split tests generalised over geometry for all 18 split rows (query lengths 1-640 over 8k-20k
keys, empty segments, ragged batches, pipelined pieces, poisoned scratch, oracle rows at each tile edge,
declare-time scratch): 1782 ok; the mixed-step case over 9 geometry x cache pairs: 54 ok. Every kernel
that existed before is byte-identical (311 of 311).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-26 09:25:35 +01:00
hugypufyandClaude Opus 5.5 22df1c7264 arch/common, data/recipes: an M2XFP4 DFlash2 drafter -- DenseFP8 declares and issues an m2xfp4 weight, and q38-27b-m2xfp4-df2.recipe converts one
DenseFP8, the drafter's linear, reads a plain m2xfp4 encoding as LinearFP8 does: the weight view
takes the codes and meta planes together, the E8M0 plane is b_scale and b_ref, and gemm() issues
gemm_nt_q at dtype m2xfp4 over the same E4M3 pair. declare_slice stays block fp8 and clears the
flag. The DFlash2 block keeps an M2XFP4 gate_up off the fp8a8 gated fold, as it does an MXFP4 one.
The recipe is q38-27b-mxfp4-df2.recipe with its 4-bit trunk and drafter rules at m2xfp4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:24:01 +01:00
hugypufyandClaude Opus 5.5 1c6acaf84b arch/common: M2XFP4 linears in the qwen35_fp8 trunk -- LinearFP8 reads an m2xfp4 weight as the MXFP4 views with the meta plane riding the weight operand
LinearFP8 recognises a plain m2xfp4 encoding (codes, E8M0 exponent and one meta byte per group of
32, no transform) and declares gemm_nt_q at dtype m2xfp4 over the producer's E4M3 pair: the weight
view selects codes and meta together, the exponent plane is b_scale and b_ref as for MXFP4, and the
row-part, shape and column-shard rules are the MXFP4 ones. Like the other non-block-fp8 forms it
refuses a stored view. step() issues it in a block of its own with the MXFP4 GEMM's operands, and
MlpFP8 keeps it off the fp8a8 gated fold, so an M2XFP4 gate_up takes the GEMM and gated quantiser pair.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:24:01 +01:00
hugypufyandClaude Opus 5.5 dab34da373 libr4d: gemm_m2xfp4a8_decode and gemm_m2xfp4a8_tiled -- the MXFP4 x fp8 GEMMs with the m2xfp4 meta plane folded into the e4m3 staging table
Two gemm_nt_q rows at dtype m2xfp4: a split-K decode kernel that stages the weight through LDS,
and a tiled prefill kernel after the mxfp4a8 one. The relayout appends the [K/32][N] meta plane to
the fragment-order codes and r4d_m2xfp4.h's e4m3 staging table takes the subgroup multiplier as a
second index, so the WMMAs and the epilogue are the mxfp4 kernels'. The decode row keeps its own
per-output arrival counters, as mxd_out_ctr does. r4d_emu_m2xfp4 runs both kernels on the host,
and r4d_selftest and kbench (a 4e-2 tolerance for the k = 3 rounding) cover the rows. The raw
entry points are declared in r4d_m2xfp4.h, beside the table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:24:01 +01:00
hugypufyandClaude Opus 5.5 21c01f9930 libref, libavx, core/format: gemm_nt_q at m2xfp4 -- a libref arm of its own over the codes and meta concatenated as the weight
libref serves gemm_nt_q at dtype m2xfp4 against the E4M3 activation and its per-128 scales, from
ref_m2xfp4.cpp: libref keeps one row an op, so the gemm_nt_q row takes its launch, shape and
layout hooks from there, each answering m2xfp4 and passing every other dtype to the hook it had.
The layout joins the codes and meta planes into one U8 operand (codes rows, then meta rows) and
the GEMM decodes it element by element. libavx refuses the encoding, so the host backend falls
through to libref. The core's selection reader hands out the same codes+meta form for an m2xfp4
encoding, so the oracle and fixtures can build the operand. quant_m2xfp_test runs the row over the
quantiser's planes; OPS.md gains the operand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:24:01 +01:00
hugypufyandClaude Opus 5.5 a323b76bca libquant: the m2xfp4 quantiser -- M2XFP's metadata-augmented MXFP4, weights only, with its own decode
M2XFP (arXiv 2601.19213) keeps OCP MXFP4's codes and E8M0 exponent and adds one metadata byte a
group of 32: four 2-bit extra mantissas, each refining the shared scale of a subgroup of 8 to
(1 + k/4) . 2^E. The quantiser searches each subgroup's k and the exponent's bias by least squared
error (the paper's Sg-EM), stores codes, scale and meta as three planes of scheme "m2xfp4" and
supplies the decode hook the core needs for a scheme it cannot follow. spec.md gains the
encoding and quantiser rows; quant_m2xfp_test covers the planes, determinism and quality.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:24:01 +01:00
AshlynandClaude Opus 5.5 d8b9ce3a32 gemma4: a GPTQ calibration tap and recipe for the 31B's w4a8 container, whose tool calls then close their strings
Rounded to nearest, the 31B's w4a8 trunk leaves streamed tool calls inside their string arguments:
after `sku:<|"|>MS-110` it prefers `**,` (58%) to the string's close (41%; bf16 ~1.0), and
BetterBench's order request stalled in 10 of 20 tries. This adds what it takes to make the same
container (same grid, kernels and size) with the trunk's int4 codes chosen by GPTQ against the bf16
model's own activations.

- arch/gemma4: with RADIANCE_CALIB_DIR set, the plugin serving the 31B's bf16 checkpoint sums the
  Gram of every dense linear's bf16 input over the corpus a server is fed (gram_accum into a
  PERSIST [K, K] f32 buffer a tap) and writes the files at RADIANCE_CALIB_TOKENS, as arch/gemma3's
  tap does: q|k|v's and gate|up's input whole from rank 0, o_proj's and down's this rank's columns
  as `<stem>.part`, which libquant places on the diagonal. The files carry the names the w4a8
  container gives the weights (gemma4_bf16's attn_qkv, attn_o, ffn_gate_up, ffn_down), so a GPTQ
  recipe converting that container reads them with calib=DIR. RADIANCE_G4_CALIB_LAYERS=lo:hi records
  a slice of layers (the 31B's taps are ~364 MiB a layer a rank at --tp 4, and 60 layers of them do
  not fit beside the bf16 weights). Under the tap a step runs whole and on one lane; without
  RADIANCE_CALIB_DIR nothing changes.
- data/recipes/gemma4-31b-dense-bf16-w4a8g-df2.recipe: the -df2 recipe with `gptq codes=i4
  group=128 scale=f16 rule=search calib=$CALIB` on the trunk's four linears.
- docs/GEMMA4-31B-GPTQ.md: the route, the corpus, how to run it, and the measurements.

Measured (1.11.0, the same tap and recipe): by GPTQ the close is 99.8% and no try stalls; KL against
bf16 on the model's own turns falls from 0.341 to 0.251 (the w8a8 container 0.226), at the same
speed. The convert takes 75 minutes with OpenBLAS in the image (#220; an estimated days without). A
container made this way is on Hugging Face as Ashlyn4202025/gemma4-31b-w4a8-gptq-dflash2, and with
the block-16 drafter as Ashlyn4202025/gemma4-31b-w4a8-gptq-dflash2-b16.

Tests: engine_e2e takes the tiny Gemma 4 (shaped like the 31B) through the whole route at --tp 2:
the tap's files, by name and width on each rank; rad-convert with the two shipped recipes, every
trunk linear fitted and none rounded to nearest; and the GPTQ container's KL against the bf16 model
on held-out documents more than three times below the round-to-nearest one's (0.0018 against
0.0105). With rank 0's and rank 1's .part blocks swapped the margin is 2.2 times, which fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:22:45 +01:00
AshlynandClaude Opus 5.5 66c86b9f89 speculation: a group the window snapshot restores is no hole in a drafter's KV after a prefix hit
On Gemma 4 (sliding layers the prefix cache does not index, no linear state) a hit resumes the
trunk's window from a window snapshot. The check for a hole in a block drafter's own KV after a
hit counted every paged group the prefix cache does not index, the trunk's windowed one included,
so it found a hole the snapshot fills. z-lab's DFlash drafter keeps a full-attention cache, which
the prefix cache indexes; with that false hole its floor sat at the hit, and with no window to
slide it was declined for the rest of every turn after a hit (on the 31B: 1.00 tokens a step on
those turns, 4.25 with this). The scheduler now counts a group the snapshot restores
(IKVManager::window_snapshot, the KV manager's KVGroupPlan::win_snap) as no hole, and the startup
line says how many: `draft floor: 3 paged group(s), 2 prefix-cached, 1 in the window snapshot -> a
hit leaves no hole`. A drafter's own windowed group is not in the snapshot, so DFlash2 and every
model with linear state are unchanged.

Tests: sched_test (a full-attention drafter drafts at once after a hit the window snapshot resumes,
and with the trunk's window counted as a hole never drafts again that turn; the fixture gains a
full-attention trunk).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:21:44 +01:00
mici81andClaude Opus 5.5 5c1c71b147 attn gated fp8: issue a mixed step's dense attention once per band
A step that mixes decoding sequences with a prefill chunk issued the dense attention once, at band
max_q_len, so the decode rows ran through the prefill kernel: one workgroup per KV head walking the
decoder's whole context. With a decoder at 188k beside a 2048-row chunk that tail set the step time.

In a MIXED step the attention is now issued twice:
- the decode half at the decode band (served by the split-KV decode row); at most max_seqs - 1
  sequences of at most the decode band's rows, which its declared scratch covers;
- the prefill half always at the op's top band, which selects the query-tiled prefill row built for
  launches over part of a step (absolute cu from entry D, as the GDN block issues its prefill half and
  as ArPieces issues its pieces); the kernels read exact lengths from cu. At its own query length a
  chunk of 10 rows or fewer would select the decode row, which sizes its partials from the whole
  step's rows and has no cu span.
A chunk no longer than the verify blocks beside it keeps the single launch (the step is decode-
shaped). Pure decode and pure prefill steps issue exactly as before (graph pins unchanged; only the
pinned steps that contain a mixed step move).

RADIANCE_ATTN_BAND_SPLIT=0 restores the single issue.

Measured on 2x Radeon AI PRO R9700, Qwen3.8-27B MXFP4, TP 2: one sequence decoding after a 188k
prompt while a fresh 25k prompt arrives (2 rounds each):
- mixed step 510 / 508 ms -> 211 / 211 ms
- the new prompt's prefill 11.3 / 11.3 s -> 5.0 / 5.0 s (the same as beside a 0.7k decoder)
- the decoder's rate over the window 85 / 82 -> 109 / 103 tok/s
30 minutes of mixed serving load (12 decoding streams with speculation, fresh 25k / 41k prompts,
cached re-sends that prefill a few-row suffix, TranslateGemma beside): 0 errors, 0 restarts.

Tests: arch_test qwen35_fp8_issues_a_mixed_steps_attention_once_per_band (both halves' operands, the
prefill half at the top band for a short chunk, the single launch when the chunk is not longer than
the verify blocks, one issue per layer for pure steps); r4d_selftest attn_mixed_step (production
per-rank geometry, scratch bound exactly as the engine binds it per band, 15 decode sequences of 8-10
rows beside chunks of 1 to 640 rows).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-26 09:20:22 +01:00
mici81andClaude Opus 5.5 6a7824a837 attn prefill h256 gqa6: split the KV walk when the launch has too few workgroups
The prefill attention kernel gives each workgroup 64 query rows of one KV head and walks the whole
causal context serially. A launch with few query rows therefore has few workgroups: the tail chunk
of a prompt (53 rows) or a follow-up turn of a few hundred tokens runs 2-10 workgroups on 32 WGPs,
each walking up to 188k keys (17.7 ms per layer at 188k).

When kv_heads * qtiles * seqs is below the WGP count, the launch now splits the KV range into S
segments (blockIdx.x = qtile * S + segment), writes unnormalised f32 partials (O, m, l) in the
decode partial layout and merges them with the existing split-KV combine. S is the smaller of one or
two rounds of workgroups, capped by the context's tiles and the declared scratch. A segment past a
workgroup's causal end still writes an empty partial; the merge reads every segment it counts.
The merges take a SPAN parameter so a launch over part of a step (pipelined pieces) only rewrites its
own rows; the decode instances are unchanged (identical ISA).

R4D_PREFILL_SPLITS: unset/0 = the law, 1 = off, N = force N (debug/tuning).

Measured on 2x Radeon AI PRO R9700, Qwen3.8-27B MXFP4, TP 2, k6_v4 KV:
- r4d_selftest --perfpaged, off -> on: 53 rows over 40k 3.71 -> 0.47 ms, 80 rows 3.64 -> 0.68 ms,
  345 rows 3.80 -> 1.79 ms, 1024 rows 4.29 -> 4.29 ms (no split).
- Engine, 188k prompt, time to first token: 62.78 -> 62.54 s (the tail chunk).
- KLD vs the bf16 reference: chunk 64 0.040384 -> 0.040337, chunk 2048 0.040237 -> 0.040220;
  top-1 agreement 93.985 -> 93.998 %. Split vs unsplit outputs differ by at most 1 bf16 ulp.
- With R4D_PREFILL_SPLITS=1 the engine is bit-identical to before (top-5 logprobs, 100 positions).

Tests: attn_split_case / attn_split_scratch_case for k6_v4, fp8_v4, fp8 and bf16 KV (q 1-345 over
8k-20k keys, empty segments, ragged batches, pipelined pieces), scratch poisoned; 410/410 ok.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-26 09:20:22 +01:00
AshlynandClaude Opus 5.5 64c652f01e speculation: an MTP head's first draft reads its cache only up to where it sits
The history pass has a row for every position a verify could commit; rows past the last
committed one repeat it, and the run's last row is draft round 1's input. The card gave that pass
the run's whole length as its context. Attention places row j of a q_len-row run at
seqused - q_len + j and reads keys up to there, so after a verify that accepted acc < n_spec
drafts, round 1 also read the n_spec - acc positions after its own: slots the head's layer had
not written for this sequence (last step's speculative rounds, or whatever the block held before
it was handed out). Its proposal then followed those bytes. Positions 2 and on were right: each
round is one row whose context ends at its own position.

This fits #221 (Qwen3.8-Flash-Next, position-1 acceptance 0.01-0.16 after a
few short conversations sit in the prefix cache, healthy with --no-prefix-cache, after a restart
and on long conversations): with the default lending cache the pool hands out blocks it lent the
expert slab once cached blocks pass the live mark, and their unwritten slots hold expert bytes;
above 2051 tokens the head's QSA path bounds each query by its own position. On the reporter's
model (TP2, their flags, 32 distinct short chats on a fresh engine) 1.12.0 falls to p1 0.352 from
request 9; with this change p1 is 0.953, as with --no-prefix-cache (0.955), replies identical.

The context now ends at the last committed position. Earlier rows of the pass count lower than
their positions, but nothing reads their output (the head goes on with draft_out_ids only), and
every row's K and V still store at its own position's slot.

Tests: advance_test (no row of a history pass or a round counts past its own position, and the
run's last row sits exactly at it, for every acceptance and lead; fails before: the last row at
204 for a head at 201; and right after a 1-2 token prompt, where the rows nothing reads count
before the sequence's start, every row still stores at its own position and the last sits at
the committed one); ref_test (rows of a paged-attention run that sit before the context's start
return zeros, not NaN, and the rows after them stay exact).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:19:32 +01:00
AshlynandClaude Opus 5.5 bf6c019571 engine: stream a step's tokens before the drafter's passes behind it end
Since 1.11.0 a block drafter's context and query passes (DFlash, DFlash2), like a serial drafter's
rounds (MTP), are queued behind the step before its readback, and the host waited for all of them
before it read the sampled ids. The ids' copy was already issued ahead of the passes, but the
commit that streams the tokens came only after the passes had run: every token, the first one
included, reached the client a drafter's passes late.

The copy now has an event of its own (tok_end_). collect_step waits on it, the commit streams the
tokens while the card runs the passes, and the step loop waits for the step's end (step_end_)
right after the commit, before finish_*_drafter reads the slots and before anything else is
issued. The commit issues no device work, so whatever it releases is in use only by the passes
that wait covers, and the next work that could reuse it is issued after the wait. KL mode and
embedding programs keep the old wait; RADIANCE_IDS_EARLY=0 restores it, for an A/B.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:18:57 +01:00
AshlynandClaude Opus 5.5 f55570e351 sched: no step issued ahead behind a step that ends every request it carries
A pipelined engine issues each step's successor before the step is read back: block drafters
(DFlash, DFlash2) since 1.11.0, serial MTP and decoding without a drafter since 1.0.0. The step that
emits a request's last token therefore had one more step queued behind it, for a request its commit
then finishes. That step verifies nothing, yet the card runs its whole forward pass and the
drafter's context pass behind it, and a request that arrives once the last token is out -- a
single-stream client's next turn, sent as the reply ends -- waits for all of it before its prefill
starts. On Qwen3.8-27B ParoQuant int5 with DFlash2 on one R9700 that is about one decode step (34-53
ms) of TTFT on every back-to-back request (#225: 105 -> 139 ms); for 127 requests 1.12.0 ran 806
decode steps, all issued ahead, against 1.8.1's 680.

Scheduler::step_next_locked, beside the other rules for issuing ahead and before the next step's KV
is reserved, now issues nothing when the step just issued ends every request it carries: when it can
bring each to its max_tokens (certainly with the token it emits, possibly with the drafts it
verifies: output + 1 + drafts >= max_tokens), or, most likely, when those drafts hold an
end-of-generation id (ignore_eos requests excepted). The engine hands the scheduler the
end-of-generation ids at start (set_eog), the sorted list the card's acceptance reads. A guess that
misses (a drafted end the verify rejects, too few drafts accepted to reach max_tokens) costs one
step built after the commit instead of before it. Ends it does not predict still leave one step
behind: an end the verify chose itself, a stop string, the context limit. Without a drafter only
max_tokens ends are caught, exactly. At -v the commit names each request that ended with a step
issued ahead behind it (finish reason, its last step's tokens and accepted drafts, output against
max_tokens, whether its drafts held an end).

Tests: sched_test pins both halves (a drafted end issues and reserves nothing; a request whose next
token is its last, or whose token and accepted drafts could reach max_tokens, issues nothing; an
ignore_eos request's drafted end, drafts without an end, and a request that every draft accepted
would leave a token short still issue ahead; of two requests one going on, both issue ahead); the
test of a request finishing under a step issued ahead now ends it on an end of text the scheduler
cannot see coming. engine_e2e_test: two 32-token replies without a drafter are 62 decode steps, all
issued ahead, not 64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:18:33 +01:00
keptn42 55cf057a30 deploy: NVIDIA-Nemotron-3.5-Bolt-E4B on two cards by default
Since #239 the E4B form runs at two ranks. The three compose files now
use --tp 2 and name the audio encoder; the one-card profiles move to
nemotron-3.5-bolt-e4b-{bf16,i8g,a4}-tp1.yaml.
2026-10-26 09:17:48 +01:00
keptn42 ae7f16b22b README: the NVIDIA-Nemotron-3.5-Bolt-E4B containers with the audio encoder 2026-10-26 09:17:48 +01:00
keptn42 15065f0463 gemma4_bf16: the audio encoder of Gemma 4 E2B/E4B
Declared after the vision tower when the container carries it. Audio rows
take the media scatter before the embedding all-reduce, and the per-layer
inputs of their positions use the pad row, as image rows do. The probe states
30 s of frames.
2026-10-26 09:17:48 +01:00
keptn42 c5d61eafbb mm: Gemma 4 audio settings from processor_config.json's feature_extractor
Gemma 4 E2B/E4B keep their feature extractor settings there, not in a
preprocessor_config.json. AudioConfig reads preprocessor.* first, as before,
then processor.feature_extractor.*.
2026-10-26 09:17:48 +01:00
keptn42 258d97339a arch: Gemma 4 audio encoder as a shared block (rad_block_gemma4_audio.h)
The USM conformer moves out of embgemma2 unchanged, with the checkpoint
prefix and the plugin name as parameters, so a Gemma 4 conditional-generation
checkpoint (model.audio_tower) can declare it too. The feature size comes
from preprocessor_config.json or, failing that, from processor_config.json's
feature_extractor. embgemma2 declares the same graph (arch_test pins).
2026-10-26 09:17:48 +01:00
keptn42 2370687c70 gemma4_bf16: KV heads replicated over ranks, and the per-layer branch at four ranks
With fewer KV heads than ranks, each rank keeps one head and reads the
rows of k and v of that head (as one span, or the k and v parts of a fused
q|k|v, with the scale plane alongside); q stays an even share. Both classes,
as geom_from already counts it for the sliding class. The attention
junction keeps every row where the per-layer branch follows. Gemma 4 E4B
(two KV heads) then runs at four ranks.
2026-10-26 09:17:33 +01:00
Malic ZilyasandClaude Sonnet 5.5 2e1a5022a9 gemm_w4a8i8_tiled / gemm_w5a8i8_tiled: the weight loaded a slab ahead
As #197 did for gemm_mxfp4a8_tiled (a85f87e): the weight words a thread stages (the nibbles, the
fifth bits, the zero word) are loaded into registers a slab ahead, right after the staging
barrier, so their DRAM round trip runs under the slab's WMMAs instead of in front of the next
unpack. The slab's weight scales are loaded after the WMMAs, just before the fold: held from the
top of the slab next to the words they need 248/251 VGPRs (int4/int5), 5 waves a SIMD instead of
6, and the kernel ran 4-8 % slower than before; loaded late it is 224/227 VGPRs (was 235/237),
no spills. Same fold, same WMMA order: bit for bit.

r4d_selftest --perfwpa (new: warmed min/median and an FNV hash of the output), one R9700 at
230 W, M = 1024, old and new interleaved, 12 rounds, median: int5 gate_up 34816x5120 2769 ->
2572 us, down 5120x17408 1394 -> 1310, delta-net qkv|z 1297 -> 1219, ssm_out 461 -> 430,
q|gate 937 -> 889 (int4 -6..-9 %). Hashes equal the old kernel's on ten shapes at 1024 and 2048
rows. End to end, Qwen3.8-27B PARO int5 at tp 1 with 1024-token chunks (BetterBench, old / new /
old): 23.5k-token prompt 2096 / 2151 / 2085 tok/s, 47k 1934 / 1979 / 1927.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:16:54 +01:00
C_Tamas aa989db567 dashboard: a history section under the requests card
A request is listed in the Requests card only while it exists. The engine
drops it from /stats within roughly 20 ms of its last token on a one-token
reply, and within half a second on a long one, so the per-request figures an
operator actually compares runs on -- average tok/s, time to first token,
context at finish -- are gone before a reader who looked away gets back to
them.

The card now keeps the last 200 completed requests, per browser, in
localStorage, under the live table: prompt, completion and context tokens,
ttft, prefill throughput derived from the uncached prompt and the time to
first token, decode throughput, and age, plus the averages of those rates and
the median time to first token.

Capture is by sighting. A request is recorded the moment a poll catches its
state as done, or, since the engine usually drops it before that happens,
from its last sighting once it leaves the payload. What began and ended
between two polls was never seen, so it is counted in a grey row rather than
invented. The poll runs at 100 ms while something is in flight and 500 ms
when idle; the idle rate is what the page had before, and the faster rate is
what makes capture work at all.

Ids are the history's own, not the engine's. The engine renumbers 1..N and
restarts at 1, so each row carries a unique storage key (engine id plus a
running offset persisted across restarts) and a separate history id shown in
the # column: it starts at 0, and clear writes that counter back to 0, so a
cleared table begins again at #0. Rows are shared by every dashboard tab: a
save unions with what is stored, deduplicates by key, and a clear is a
timestamp every tab honours. clear and json sit in the section header.

The card is 459 px -- one and a half times the stock 306 -- to give the
history rows; the live table stays fixed at the top and only the history
scrolls, under a column header that stays pinned. On a phone the history list
chains its scroll to the document, as the request table already did.
2026-10-26 09:16:16 +01:00
NunzeandClaude Opus 5.5 ca713b4732 scripts: stampgaps.py -- RADIANCE_AQL_STAMP's CSV per kind of pass: wall, busy union, idle share, gaps before ordered starts
The stamps are one line a dispatch; what they are taken for is a pass's idle time and the gaps a
barrier leaves, which need the union over the queues and the kinds of pass told apart. Standard
library only, beside cardclock.py and statsdump.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:15:18 +01:00
Nunze 09f80b8b1e core/device: RADIANCE_AQL_STAMP -- each dispatch's start and end in a played pass, without ordering it
Every dispatch of one recorded pass in N on card 0 gets a completion signal of its own, into which
the packet processor writes its start and end. The barrier bit and the chain are decided as
without the signal, so the queues run the pass as unstamped; --profile-ops, the instrument so
far, plays no recorded pass and puts two barriers around every op. A pass is the plays of a tape
from its record 0, since a pass is played in stretches between host ops. A dispatch a record or a
ride rides on is stamped from that signal, held out of the pool until its times are read.

Nothing waits: a later play reads the signals that reached 0 and appends one CSV line a dispatch
(pass, record, queue, kernel, ordered, chained, start and end in ns, play, tape length) to
RADIANCE_AQL_STAMP_OUT. Unset, nothing changes.
2026-10-26 09:15:18 +01:00
gearwave00001andClaude c463a0ab1b ops: the tiled encode ops take their row count from the operands, not from M
The engine never hands a kernel the issued value of a ranged parameter: the oracle
binds it to the matched band's bound, and ref_common.h's band_rows spells the rule
out -- the parameter stays a ceiling where one is stated -- which is why every
existing kernel derives its counts from its operands. vtile_plan/crop/join were the
first to read M as the row count of the call, so the first real tiled encode refused
on device: a 512 keyframe's 3 x 3 plan, issued under the band bound 33, tripped the
wrapper's rows-of-y < M clause, which answered RAD_E_STRIDE -- and the strerror
insisted, wrongly, that a non-contiguous operand was the problem. Crop and join
carried the same latent bug: crop would have launched 33 blocks over a ~590k-row
cut, and both would have refused every canvas under their bands' real bounds.

All three tiers now count from the operands and treat the passed M as the ceiling it
is -- y longer than the ceiling is refused, equality never demanded. The reference
and host tiers take the count from geom through band_rows; the device wrappers take
it from y's rows and pass that count in the kernel's M slot, which the kernels' own
operand-row guards make safe. OPS.md says the rule once at the head of the tiled
encoder section: an M written in a shape is an operand's row count, the ranged M
argument a ceiling only.

The host gates missed the bug precisely because they drove an exact M. ref_test's
three vtile cases now pass the band's bound -- 33, 33 * 256 * 256, 320 * 320 -- and
demand the same exact output, plus short-operand cases that must refuse E_SHAPE
under the over-declared ceiling; r4d_selftest drives the same bounds on device.
Verified: ref_test 264 cases, device vtile plan 4 / crop 8 / join 5 / gather 2 /
stitch 8 all exact, full ctest 123/123; and the FL2VA render that used to die in
tiled encode now runs its 25 steps with both keyframes visible in the decoded clip.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-25 11:23:15 -05:00
gearwave00001andClaude fe311c5c80 ops: the column map the modulated pads read through was missing from the SCHEMA tables
8a6a118 gave the rms_mod family an optional trailing colmap -- sequences that share
one modulation cell read the shift/scale (and gate) table through that cell's COLUMN,
so the prompt's vision-pad runs share the video cell's row across non-contiguous
boundaries. It taught the device kernel and libref's implementation to follow the map,
but the operand itself reached only the driver's issue: none of the three operand
tables listed it. The schema is what the loader and the engine check against, and all
three declaring libs must agree, so the battery's first serve died at step 1 --
`rms_mod_quant_i8 ... issued with 10 operands; the op's schema declares 9`.

All three tables now list `colmap` as the trailing optional operand of rms_mod and
both quant producers (past every other arch's last operand), and libref's shape
describers answer an explicit skip for it -- the sweep passes no map. libavx's
rms_mod_run was missing the feature outright: it now reads the tables through the
map's column and drops the `s` and `g` row-count checks when a map is bound -- the
table is sized by columns, not by sequences -- while the map's own bound stays the
issuer's. OPS.md's rows and prose regenerated against the dumped schemas.

Verified: ref_test full suite (the rms_mod sweeps run mapless through the new skip),
rad-avx-check on the plain and quant rows, the device rms_mod and rms_mod_quant_fp8
cases, ops_doc, and full ctest 123/123; on device a serve that died at step 1 now
boots and renders the keyframe tasks end to end.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-25 11:22:48 -05:00
gearwave00001andClaude 69087ce773 minimaxh3+ops: a picture too big for one volume encodes tile-by-tile, as the reference does
vae.py's tiled_encode cuts a picture bigger than tile_size (256 px, 16
latents) into overlapping tiles, encodes each tile alone, and blends every
tile's RAW moments with its raw top and left neighbours -- top first, then
left, never an already-blended neighbour -- into the whole latent canvas.
GroupNorm normalises inside the volume it sees, so the tile seams are
observable: our port ran the whole canvas through the trunk at once, and a
photo or keyframe over 256 px a side drifted from the reference's look.

Three ops, libref/avx/r4d alike. vtile_plan lays each tile's geometry rows
the way vae.py splits -- round-robin slack, and one short tile on an axis
no longer than a tile. vtile_crop cuts the picture's pixels tile-major.
vtile_join blends the tile-major moments into the plain pass's b_eq2 with
vae.py's weights, every product and sum rounding through x's dtype. The
split carries one structural gift: with the slack fully distributed,
start[last] = len - tile, so every band is exactly a tile, and a short
band exists only in the single-band branch -- whose axis has no neighbour
to blend against. The join can therefore fetch the left neighbour always
at the full tile width while own and top fetch at the owner's own column
width, and vae.py's min() clamp inside blend is provably dead code.

step_venc_tiled runs the plain trunk once a tile: pixels from b_vtile,
moments out to one slice of b_eqt, the tile's six level geometries read
back off b_tplan (PERSIST) through raw pointers, exactly as every clip's
geometries come off enc_geom_d. The arena packs by declared lifetime, so
op_ve_q moved ahead of the trunk and the tiled ops sit last: b_vtile must
span op_ve_pix's first read to op_vt_crop at the tail and b_eqt must span
op_ve_q to op_vt_join, bracketing every trunk op the tiled pass re-runs.
b_vtile and b_eqt size tile-major at the declared tile cap; a picture
splitting past the cap step-fails by name. Clips never tile -- their
volume forces each side back to kEncMaxSide. OPS.md documents all three.

Verified: ref_test 264 cases (plan pins the round-robin overlaps {6,5,5}
and a short lone row with column neighbours; crop walks a short band at
ratio 4; join checks a 6x9 canvas with uneven round-robin splits point by
point, and a 32x32 eighths-exact f32 blend that must land bit-identical);
rad-avx-check scalar/avx/avx2 on all three ops; device r4d_selftest plan
4 / crop 8 (f32+bf16) / join 5 cases ok. Full ctest 123/123. ABI
unchanged at 28.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-25 09:52:15 -05:00
gearwave00001andClaude 47b7aae7a3 ops+minimaxh3+driver: the condition-noise augmentation the reference adds to visual cond rows
The reference's _cond_video_rows runs every visual conditioning latent through
x = aug x + (1 - aug) z at VISUAL_COND_TIMESTEP 0.999, its generator restarted
per item, while audio conditioning is untouched (its aug is 1.0, a no-op). We
staged the clean latent instead, so every image-, keyframe- and reference-
conditioned render started from un-augmented conditioning.

New op cond_aug: x = f32(f32(a x) + f32(oma z)), a the aug parameter and oma
the f32 of the double 1 - aug -- the reference subtracts in double and rounds
once -- with z the (seed, stream) normal stream at element k n + c on stream
2, the reference's noise never sharing the generator that fills x. Seed words
0-1 of the video's seed, per-item restart by per-row offset. Issued once at
the end of step_venc over the conditioning rows: staging once at encode-build
time is equivalent to the reference's per-call restart because each item's
rows are exactly its own, and the driver's build_encode now re-stages the
seed, where a stale lane's words used to ride through.

Reference RNG is MT19937 and ours Philox, so the noise is distributionally
faithful, not bit-exact. ABI unchanged at 28. Device: r4d_selftest 0 failures,
cond_aug rows 1.13e-9/4.42e-8 rel_l2 against libref.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-25 08:45:29 -05:00
gearwave00001andClaude 8c547fe240 selftest: drop the strided conv1d_f32 cases the 1.12.0 merge resurrected
The merge took libref's older conv1d_f32 case list over the PIN commit's:
five stride-2/4/8 success cases came back on top of the entry that refuses
them. The contract is the PIN's — the strided form lives on the bf16 rows
(the DAC encoder it serves runs there) and the f32 vocoder is stride 1, so
r4d_rad_conv1d_f32 refuses a stride or an explicit pad as a dtype choice,
and the refusal cases (even k, stride without pad, two sequences, f32)
stand. The perf path never noticed: it sends strided upsampling to
conv_t1d_f32, which owns that form at f32.

Device-verified: all eight surviving conv1d_f32 cases ok filtered
(rel_l2 <= 1.6e-6 against the bound of 2e-5).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-25 08:26:02 -05:00
C_Tamas bcdc89eded Merge branch 'main' into fix-stage-drain 2026-10-25 14:19:31 +01:00
C_Tamas 5a463bf992 kv streaming: drain the stage pipe before the map clear
A stage copy is handed to the DMA queue and normally waited for by the next
kvstage_wait or consumed by kvstage_next. A staged pass can end with a list
still in flight. The transition back to the ring then clears the residency
maps, and the first ring pass refills layer 0 from the host mirror; a list that
lands after that refill leaves res calling another layer's bytes resident --
the same silent wrong output the clear exists to prevent, now sticky for layer
0 until the next prefill.

Wait the list out before the memsets. Normally nothing is in flight. Also
correct the comment on the slots < blocks guard: it is the invariant that a
stage exists (bringup gives a stream whose ring covers its context no mirror,
no resolve and no stage), not an identity claim -- a stage row is per layer and
always starts at offset 0.

Measured after the change, exact compose flags, ring 32768, spec 0 and 3:
four rounds of seed -> arithmetic -> passcode -> colors -> json each, 15:55 on
every round and the 3k passphrase on every turn.
2026-10-25 20:17:11 +07:00
gearwave00001andClaude 8a6a1180ce minimaxh3+r4d+driver: the prompt's vision pads are modulated as video, not as text
The reference modulates by a per-token TAG: token_tags_from_embeds_info tags
every image embed span (with one flanking token on each side) 0 -- video --
inside the prompt, while audio pads keep tag 1 (parallel PR #236, point 3).
Our port modulated the whole prompt span as text, so every reference photo's
pad tokens read the text ada projection where the reference reads the video
one. The tags arrive in the prompt itself and nothing else carries them, so
the denoiser could not know, and the look drifted with the reference count.

The driver now writes each image item's token span into a tail of ref_tab --
one count, then {start, length} per run, audio items excluded (the reference
tags images only). The tail rides inert through the pack and ref_parts, and
is present exactly when the reference table is, so an i2va request keeps its
old bytes. ref2va_mod_groups grows a runs argument: it cuts the prompt at the
runs' edges and gives the pad pieces the VIDEO cell -- the video projection
on the video-schedule block; the prompt's own timestep row never changes,
only the projection.

Cells stay few however many photos interleave, but groups no longer equal
cells: two prompt pieces separated by a pad share one cell non-adjacently.
So the merged-group output gains a per-group column map, and the modulated-
norm kernels -- libr4d and libref alike -- accept an optional trailing
colmap (slot 9 quant, 7 bf16, past every other arch's last operand) that
redirects sequence -> table column, relaxing the row-count checks it binds.
rad_arch_video_mod_segs exports boundaries then map, the plugin stages both
only for a reference request -- the plain path still stages boundaries alone,
byte-identical -- and the half-split keeps its single video row by taking
the target's column instead of the last one. max_ref_segs now bounds the
DISTINCT CELLS, its old meaning was the group count. ABI 28; no struct's
shape moved, the layout table is re-stamped.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-25 07:29:27 -05:00
keptn42 d650eca840 gemma4_bf16: image rows before the embedding all-reduce
RadBatch::mm_embd holds the image rows at rank 0 and zeros at every other
rank. The rows went in after the all-reduce of the token lookup, so at more
than one rank every rank past 0 wrote zeros over its image rows, and the
ranks ran on different residual streams from layer 0 on.
2026-10-25 13:09:29 +01:00
C_Tamas 1f3154d366 kv streaming: drop the residency maps when the view returns to the ring
A staged pass copies whole layers into the pool at block-id identity: block b
of layer l goes to base + b * block_bytes. The ring addresses its slots at
base + l * slots * block_bytes + s * block_bytes, so the stage row of a later
layer is the ring row of an earlier one. The copy never touches `res` or
`slot_block`, so every block the map still calls resident names bytes that some
later layer has since overwritten.

Block ids are recycled between requests, so this is not theoretical. The second
request's prefill writes its mirror and -- gated on `res`, which is still valid
from the first request -- its ring slots; the rest of the layers' stage rows
then overwrite those slots. The first decode trusts `res`, skips the resolve,
and reads another layer's, or another request's, KV. Fluent, no fault.

Measured with --kv-resident 32768 on 2x16 GB gfx1201, exact compose flags:
  ring off:  an arithmetic probe answers 15:55 on every round;
  ring on (before): 15:55, then 16:40 for rounds 2-4, on spec 0 and spec 3;
  ring on (after):  15:55 on every round.
The same sequence previously answered a 3k system passphrase as Q97/Q&A and an
unrelated weather question with the previous request's filler text.

Clear `res`, `slot_block` and `slot_state` when the binding leaves the stage
view for the ring, for streams whose ring is smaller than their id space. The
first ring pass then resolves every live block out of the mirror -- the cold-map
path the first request already takes -- and the ring is self-consistent for the
decode steps that follow. One memset per prefill, not per step. A stream whose
ring covers its id space is left alone: there the staged bytes and the ring's
bytes are the same bytes at the same offsets.

Tests: kv_window_test 8/8, p4b_kv_ring_test 3/4 (one skipped: no in-tree test
kernels in this build), sched_test 142 cases green. arch_test has 15
pre-existing graph-pin failures on this tree, identical with and without this
change. The 47-case streaming battery is clean on both ring arms (spec 0 and 3).
2026-10-25 19:06:06 +07:00
gearwave00001andClaude c5483e3241 videos: the tower reads a keyframe's own canvas frame, never a re-decode
The reference feeds the vision tower the same resized tensor it hands the
video VAE: an anchor's identity and its pinned latent are the SAME pixels.
Our port showed the tower the source file at the `match` area instead, so
a keyframe whose native aspect differed from the canvas reached the two
channels differently (parallel PR #236, point 5).

A keyframe now decodes once, onto the exact output canvas, in a pre-loop
that owns every FIRST/LAST_FRAME part: the pixels fill enc_pixels for the
VAE pin as before, and the frame itself rides to the prompt block, where
the anchor loop hands it to the tower through the new IMultimodal
prepare_frame -- implemented by the bridge as Processor::image_from, which
smart-resizes and patchifies the caller's pixels exactly as a prepared
file's would be. A reference picture is unchanged (tower `match`, encoder
grid); the two never share a request. The encode loop's keyframe branch is
gone: its pixels were built above, one decode for both consumers.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-25 06:58:58 -05:00
gearwave00001andClaude baa10db1aa videos+minimaxh3: the keyframe ordinal counts pictures present; chunks back to the trained floor
Two findings from #236's author, both confirmed against the reference:

The <Picture k> ordinal for endpoint keyframes was fixed by ROLE (first = 1,
last = 2), so an l2va request presented its sole frame as <Picture 2>. The
reference numbers its presentation by PRESENCE (a last-frame-only request is
its picture ONE) -- as this server's own ref2va photo numbering already does.
The parse keeps the role's provisional ordinal; the count check settles it
once every part has arrived (parts may come in either order). fl2va is
unchanged: with both ends, roles and positions agree.

kMinChunks carried a stale 'EXPERIMENT: short-chunk test' enum (4) from a
cheap-clip verification battery, letting every request go under the model's
trained 5.17 s floor (7 chunks). Restored; the file's own '5 to 15 seconds:
7 to 20 chunks' comment describes the real bound.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-25 06:51:06 -05:00
keptn42 92093976fe gemma4_bf16: per-layer embeddings at two ranks
The per-layer table is vocab-sharded like the token table. Its lookup is now
reduced the same way, before the pad rows of image positions go in. The rest
of the branch is replicated, so the junction that closes it folds in no
all-reduce. The prefill overlap stays off with the branch. Four ranks stay
refused.
2026-10-25 12:38:34 +01:00
Constantin 2d2f638fa8 Document HYV3 support and add conversion recipes
Add BF16-source W4/W8/block-FP8/MXFP4, native FP8-source and GGUF-to-W4 recipes. Document supported sources, precision/KV limits and unvalidated paths without calibration environment switches or performance claims.
2026-10-25 12:09:29 +01:00
Constantin e3eab050bd Add HYV3 BF16 FP8 and GGUF architecture adapters
Declare the HYV3 graph with a private attention helper and existing kernels/layouts. Support per-head Q/K normalization, sigmoid-correction routing, the dense-first schedule and TP1/TP2 independent arm reductions with FP32 combine. Add graph, format and plugin tests without calibration or decode optimizations.
2026-10-25 12:09:29 +01:00
Constantin 7e04bcac2b Parse HYV3 native sectioned tool calls and tagged arguments
Use the existing RadChatFormat fields for the outer tool-call section, name separator and tagged values. Cover grammar, template replay, streaming at every truncation, section boundaries and OpenAI response lifting; leave the supports_reasoning adapter unchanged.
2026-10-25 12:09:29 +01:00
Constantin 7621e4ac2b Import HYV3 KV scales and decode Q4_K/Q6_K checkpoint tensors
Carry the native FP8 release scalar K/V descales into metadata, reject invalid scales, and support conversion-time decoding of HYV3 GGUF source tensors. Add source metadata and block-decoding regressions.
2026-10-25 12:09:29 +01:00
Constantin a6702f8db5 Fix test fixture lifetimes for sanitizer validation
Avoid empty-payload fwrite, retain the JSON embedding value during iteration, and release fake pinned allocations between Flash-Next redeclarations. Test-only fixes used by the HYV3 sanitizer run.
2026-10-25 12:09:29 +01:00
AlexandClaude Opus 5.5 91fc4192aa minimaxh3: pass mapped to DenseFP8::declare for the modulation's row slices
DenseFP8 takes `mapped` as declare()'s argument since bdb37d5; the member the plugin set was no
longer read, so each modulation slice's COPY map was declared twice and the plugin refused to
declare, in rad-convert and in the engine alike. The plugin now passes it, and the member goes,
so a caller that still sets it fails to compile instead of failing at declare.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 12:05:40 +01:00
C_Tamas 0e7e6ee09a kv streaming: a speculative verify pass must not take the dense path on a ring
With --kv-resident N and --num-speculative-tokens > 0, any prompt under
qsa_exact_to (~2051 tokens) emits digit spam at 65-140 tok/s instead of text;
the same prompt with speculation off is correct, and the same prompt at 61k
tokens with speculation on is correct.

The attention chooses sparse-or-dense with

    T == batch->n_seq || qsa_exact_to <= 0 || reach > qsa_exact_to

where 'T == n_seq' is the decode-step test. A verify window carries
n_seq x (1 + n_spec) rows, so that disjunct is false; on a short context
reach > qsa_exact_to is false too, so the pass takes the DENSE branch, which
reads a block id out of the block table as a pool address. On the stage view
that is the addressing (identity); on the ring the pool is a window of slots,
so the launch reads another layer's blocks. The branch's only guard,
kv_stage_layer(), is a no-op on the ring and its result was discarded, so
nothing failed and the text stayed fluent.

The dense path is now refused whenever the group is ring-addressed: a stream
whose ring is smaller than its id space, on a pass that is not staged. A
stream whose ring covers the context keeps the dense path, where ids and slots
coincide. The dense branch also fails the step by name if it is ever reached
with a ring bound and no selection to resolve, so this cannot stay silent.

Measured on 2x16 GB gfx1201, ring 32768, spec 3: a 63-token prompt is coherent
at 63-78 tok/s (was digit spam) and a 4.9k-token prompt is unchanged at 67
tok/s. Suites: arch_test 181 cases, mem_test 184, sched_test 142,
kv_window_test 8, p4b_kv_ring_test 4, all green.
2026-10-25 17:53:45 +07:00
C_Tamas ac8b3a5017 kv streaming: a speculative verify pass must not take the dense path on a ring
TENTATIVE FIX for a silent wrong-output bug: with --kv-resident N and
--num-speculative-tokens > 0, any prompt under qsa_exact_to (~2051 tokens)
streams digit spam at 65-140 tok/s instead of text, while the same prompt with
speculation off is correct. Measured, and traced:

  * the attention chooses "sparse (resolve) or dense (read the block table)"
    with `T == batch->n_seq || qsa_exact_to <= 0 || reach > qsa_exact_to`
    (arch/common/rad_block_attn_gated_fp8.h). `T == n_seq` is the decode-step
    test, and a verify step is n_seq x (1 + n_spec) rows, so it is false.
  * short context, so `reach <= qsa_exact_to` is also false: the pass takes the
    DENSE branch, which reads a block id straight out of the block table as a
    pool address. That is right for a staged pass (identity view) and
    meaningless on the ring, where the pool is a window of slots.
  * the dense branch's only guard, kv_stage_layer(), is a no-op on the ring: it
    returns 0 when the binding has no stage, and the call discards it.
  * so the verify pass reads ring stripes holding another layer's blocks. Fluent
    garbage, never a fault -- and the drafter's own rounds take the sparse path,
    so acceptance still looks plausible.

The dense path is now refused whenever the group is ring-addressed -- a stream
whose ring is smaller than its id space and whose pass is not staged. A stream
whose ring covers the context keeps the dense path, which is correct there
(ids and slots coincide); the arch test that pins "below qsa_exact_to is dense"
still passes for that shape, which is how the predicate was narrowed.

Verified on 2x16 GB gfx1201, qwen3.8-next-flash-fp8-iq4r-moe, --kv-resident
32768 --num-speculative-tokens 3 --max-num-seqs 2:
  63-token prompt   coherent, 63-78 tok/s (was digit spam)
  4 923-token prompt coherent, 67 tok/s (unchanged)
  arch_test 181 cases, mem_test 184, sched_test 142, kv_window_test 8,
  p4b_kv_ring_test 4 -- all green.

Known gaps, deliberately left for the follow-up: no byte-exact spec-on vs
spec-off gate has been run (only read-back quality), GLM-5.3's MLA path is
untested, and the draft window crossing a page boundary is untested.
2026-10-25 17:40:49 +07:00
C_Tamas 36b131f039 Merge branch 'pr4-tests' into pr5-docs-harness 2026-10-25 17:19:53 +07:00
C_Tamas 0e953eb78b Merge branch 'pr3-models' into pr4-tests 2026-10-25 17:19:53 +07:00
C_Tamas b95265eb51 tests: the qwen pins on the new base, plus this branch's bf16-KV case
main moved the arch fingerprints (PLE, split-KV decode attention, the tune
rows); the values here are main's for every case both sides pin, and the
branch's own bf16-KV case is kept with its hash left for the run to state.
2026-10-25 17:19:50 +07:00
C_Tamas 06172e98de Merge branch 'pr1-device' into pr2-engine 2026-10-25 17:19:16 +07:00
C_Tamas 59870fc32e Merge remote-tracking branch 'origin/main' into pr1-device 2026-10-25 17:19:12 +07:00
gearwave00001andClaude f3c6443d95 docs: the LoRA-slot squeeze is a same-machine affair -- split deployments fit both slots
The node is a pure HTTP client, so ComfyUI's VRAM only contends with
radiance's when both run on the server's box. Headless-radiance setups
(the normal layout: client UI on its own GPU, node pointed at a LAN
server) have idle cards on the server and boot --max-loras 2 fine.
Scope the recommendation to shared machines in node tooltip, README,
and GUIDE; PR body updated out-of-tree.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-25 05:15:51 -05:00
gearwave00001 07904a3628 docs: the second LoRA slot does not fit a busy 32 GB card -- document the budget and default to --max-loras 1
Measured on the flagship serve (MiniMax-H3 dasiwa-fp8, TP2, rank 16): an
adapter slot is 265 MiB a card and EXACTLY one slot of elastic slack
survives the video arena after KV takes the rest. --max-loras 2 boots only
when nothing else holds VRAM (an idle ComfyUI on the box itself holds
~1.7 GiB); otherwise startup stops at 'vram_kv resolved to 0 MiB'. Lowering
--max-num-batched-tokens is not an escape for a video generator -- the auto
value is a floor (the largest denoise step must fit the arena) and the
declare refuses below it (verified live).

Written where a stuck user or their agent will grep it: the node's lora 2
tooltip (names the failure string), a README 'LoRA slots and VRAM' section,
GUIDE's --max-loras bullet, and the PR's Known limits. Recommendation:
serve with --max-loras 1; go to 2 on idle cards.
2026-10-25 05:14:04 -05:00
gearwave00001 258d685768 comfyui node: 60 s per status-poll request (was 30) -- a busy box gets slack
The wait's overall budget is the node's own timeout input (default
1800 s); the 30 s was the give-up-per-single-GET limit. A saturated
server should have to miss two straight minutes of tiny status replies
before the client errors out.
2026-10-25 04:56:01 -05:00
AlexandClaude Opus 5.5 aa5dfaec19 krea2: rebalance presets balanced, detail and subtle at the taps' measured RMS
`rebalance` takes a preset's name beside true/false: "balanced", "detail" and "subtle" are
comfyui-krea2-conditioning's presets with renormalize on at multiplier 1, "legacy" is true
(ConditioningKrea2Rebalance's defaults, about 9x the taps' RMS). The node renormalises by
s = sqrt(sum m_t / sum w_t^2 m_t) per prompt, m_t tap t's mean square; the plugin holds s as a
constant per preset, m_t averaged over twenty prompts through krea/Krea-2-Turbo's text encoder
(scripts/krea2_rebalance_calib.py: balanced 0.44109, detail 0.35702, subtle 0.84759; per prompt
s stayed within 1.7 % of it). The gains are fixed per tap, so the presets reuse #187's
chan_affine into te.h2 with their own `mul`, one declared op per preset and tap.

The preset rides in RAD_GEN_COND_REBALANCE_PRESET, bits 8 to 15 of cond_opts beside
RAD_GEN_COND_REBALANCE, which a plugin declares when it has presets; the driver accepts both
bits, and the server refuses a preset's name on a model whose rebalance declares none. A row the
plugin does not know scales nothing. Enum values only, so no ABI bump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 10:55:27 +01:00
gearwave00001 88540cd263 comfyui node: the heartbeat prints per completed step, not per poll
The 3 s poll must stay -- a plain HTTP client learns nothing unsolicited
(the API pushes no step events) and the progress bar/completion detect
need it -- but the CONSOLE LINE now rides the step counter: printed when
(steps_done or status/progress) moves, or every 30 s as a keep-alive so
encoding and stalls never go silent. A 26-step job logs 27 lines instead
of ~135 near-duplicates, mirroring the server's per-step RAD_INFO rhythm.
The pace tracker keeps sampling every poll regardless of printing.
2026-10-25 04:53:37 -05:00
gearwave00001 feaf008927 comfyui node: pace measured over a >=2-step window -- per-poll step timing is a poll-interval artifact at 3 s polls
At 3 s polls a 12.7 s step shows up as ONE increment between two adjacent
polls, so the per-increment delta read as the POLL interval -- a constant
"3.0 s/step" on every slow job (reported live: server log said 12.72).
The anchor now waits until two or more steps are visible and divides the
elapsed window by the steps in it; the EMA still tracks the draft->refine
re-price within a couple of windows, and the encode warm-up never rides
into the first rate (anchor starts on the first step DONE, not job start).

Also _fmt_secs: minutes and seconds each rounded INDEPENDENTLY, so 175 s
printed "3m 55s" and 119.5 s printed "1m 60s" -- now round to whole
seconds once, split with integer ops.
2026-10-25 04:44:33 -05:00
gearwave00001 19f6cd711e comfyui node: the console heartbeat shows measured s/step, eta = remaining steps x live pace
The old eta extrapolated whole-job progress, which folds the encode
warm-up into the average and drifts badly once a latent-upscaled job
switches grid mid-run (draft steps are cheaper than refine steps). The
node now mirrors the server's per-step log client-side: a _PaceTracker
measures seconds-per-step between polls from the steps_done counter and
smooths it (EMA ~40% new) so the number follows the phase change; the
eta multiplies the remaining steps by that pace and marks the decode
tail as extra. Old servers (no steps_done) keep the progress-based eta.
Help + README updated.
2026-10-25 04:36:07 -05:00
mici81andClaude Opus 5.5 6efffe2a59 libr4d: the split-KV decode attention (head 256, gqa 6) stages V4 without bank conflicts or serial rounds
The V4 tile's store (storeV4) wrote dim octets 8 rows = 96 dwords apart, so the octets a wave stores at once
shared banks (4-way on 32 banks), and on k6_v4 each tile's V fetch ran as three exec-masked rounds, each issued
after the previous one returned, the scale pair packed right after its loads. Now:

- the V tile is skewed: octet o's rows start 16 (o & 3) + 8 ((o >> 2) & 1) + 128 (o >> 2) halfwords later, so a
  store's octets land on distinct banks; the PV read adds the same offset, a compile-time constant a fragment
  (V4 at tile 16, contiguous layout, two or more waves; one wave keeps the plain tile, which its LDS budget
  needs);
- k6_v4: __builtin_assume(tid < NTHR) and a wave-uniform test for the partial round, so a tile's V loads issue
  as one batch, and the scale pair packed at the store, as the prefill kernel does since its own fix. fp8_v4
  keeps the tested rounds (batched there, its 4-row steps ran 6 % slower) and its pack.

Bit for bit: the same values in the same LDS cells, read in the same order.

r4d_selftest --perfdecattn on 2x R9700 (265 W), Qwen3.8-27B TP2 rank, k6_v4, sequences x rows x context,
3 interleaved rounds, medians: 1x8x100k 277.0 -> 260.1 us (-6.1 %), 1x8x200k 404.8 -> 377.7 (-6.7 %),
4x8x100k 799.4 -> 753.0 (-5.8 %), 4x8x200k 1733.3 -> 1655.3 (-4.5 %), 8x4x100k 1257.8 -> 1179.8 (-6.2 %),
16x4x41k 996.3 -> 973.4 (-2.3 %). fp8_v4 with the skew alone: -3.6 % (16x4x41k) .. -0.1 %.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 10:34:04 +01:00
Dustin Ewan 32bb5592d0 engine: a stall watch across the step loop -- a frozen step reports the blocked thread, its syscall and its stack instead of hanging silently 2026-10-25 10:31:06 +01:00
Dustin Ewan cc0a862afa ple: two gather regimes -- decode gathers on demand (lookup or direct read, no queue, no claims); prefill chunks use the producer queue 2026-10-25 10:31:06 +01:00
Dustin Ewan baf503e021 ple: the gather self-produces unclaimed rows on decode -- the queue prefetches prefill futures only; a decode step never waits behind it 2026-10-25 10:31:06 +01:00
Dustin Ewan 2918a2eef2 sched: re-record the pinned step-batch fingerprints -- the read-ahead queue stages 9T tokens, not 2 2026-10-25 10:31:06 +01:00
Dustin Ewan 2078b28fcb tune: --max-seqs, --kv-cache-dtype, --tp-wire, --tp-wire-min-kb -- declare at the served configuration, or the tune rows key to bands no served step selects 2026-10-25 10:31:06 +01:00
Dustin Ewan d2d9b9687e ple: the gather defers all disk I/O to the producer -- the step thread classifies, waits per row on the producer's word, and never touches the ring 2026-10-25 10:31:06 +01:00
Dustin Ewan 1fb35740df ple: an 8-chunk read-ahead queue with a sliced producer and a tunable row cache -- the table's rows prefetch off the step path 2026-10-25 10:31:06 +01:00
Dustin Ewan e9555d2bc1 tune: measure collectives as the exchange -- per-rank operands and instances, device.p2p measured before declare, tune requests carrying their instance 2026-10-25 10:30:52 +01:00
dustin d0c44cf5a3 tools: a w2a8 recipe in the fallback shape table -- rad-tune can now size the draft head it serves
rad-tune skips a (kernel, shape) pair it cannot size: a schema names operands, not extents, and
a tool has to allocate the bytes the kernel will read. For gemm_nt_q the reference describes the
fp8 and the symmetric integer grids and declines every grid with a zero point, because
ref_planes.h joins scale and zero into one operand a RadOpdDesc cannot state. w2a8 is such a
grid, and it is the one the DFlash2 draft head serves, so both of its bands were skipped at
every tune and the served card ran the axis defaults for them.

The extents are not a guess. r4d_rad_layout_w2a8 owns them: codes to fragment order, N*K/4 bytes
(r4d.w2a8.frag.g128), and one dword per row and 128 of K joining that group's f16 scale and
integer zero, tile-major, N*K/128 of them (r4d.w2a8.sz.g128). The activation triple is
quant_act_i8's own output -- int8 codes, one f32 scale a row, and the group-major code sums with
rows padded to 16 -- and the grid is asymmetric, so the kernel refuses the case without the
sums. b_ref stays absent; the reference exponent is mxfp4's.

relayout_parity_test is where both sides exist, so the claim goes there: the table's byte total
for b and b_scale against the same hooks' RadLayout.bytes, over libquant's planes, for w2a8 and
for mxfp4a8, whose sizes the table has carried untested since it was written. Writing the
table's K/4 as K/2 fails it with "the table sizes 32768 byte(s), the kernel stores 16384". The
kernel's own guards -- K a whole number of 128-column blocks, N a whole number of 16-row tiles,
the group the stored form has -- are pinned as refusals, and the shape a two-rank draft head
tunes at (M 8, N 124160, K 2560, group 128) is pinned as accepted.
2026-10-25 10:30:52 +01:00
mici81andClaude Opus 5.5 2af1079415 libr4d: the head-256 split-KV decode attention aims at 256 workgroups at one or two waves
At one or two waves a workgroup (q_len * gqa <= 32: a plain decode step, or the DFlash2 short block's
4-row verify) the 128-workgroup target leaves too few KV bytes in flight for the card's DRAM; twice as
many workgroups reach it. At three waves (an 8-row verify) more workgroups only add contention, so
those keep 128.

Qwen3.8-27B MXFP4 at TP2 on 2x R9700, k6_v4 KV:
- r4d_selftest --perfdecattn: 4 sequences x 1 row over 100k 582 -> 464 us, 1 x 1 over 100k
  264 -> 175, 16 x 4 rows over 41k 985 -> 801; 4 x 8 rows over 100k +9 % (kept at 128).
- The server's decode step at speculation 7 (the median gap between steps carrying every sequence,
  three rounds): 8 x 41k 34.01 -> 32.48 ms (-4.5 %), 16 x 25k 44.65 -> 43.19 ms (-3.3 %).

The split count already moves with the batch (8 sequences at 256 split as 4 do at 128), so the merge
sees no new partition; not bit-identical to the 128 target at the same batch.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 10:12:58 +01:00
mici81andClaude Opus 5.5 bc272f897d arch_test: the pins of the families this branch changes, on the new base
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 10:11:47 +01:00
mici81andClaude Opus 5.5 8998349eec qwen35_fp8, gemma3: the weight reads beside the all-reduces are switched off by RADIANCE_PREFETCH_BESIDE=0
1.12.0 dropped RADIANCE_PREFETCH; the reads are now issued, or not, by prefetch_beside's own switch.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 10:11:47 +01:00
mici81andClaude Opus 5.5 de53cd18c1 runtime: an op that names no buffer is not held to the second lane's window
The window keeps lane 1's concurrent buffers live only across it. A weight read into the cache
(prefetch_beside) names no buffer, so it touches nothing the window protects: it may run on lane 1
outside the window (a DFlash2 drafter's reads come after the trunk's window), and it leaves no window
work for lane 0 to join. runtime_test covers it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 10:11:47 +01:00
mici81andClaude Opus 5.5 c9f79c32d8 gemma3: weight reads beside the decode all-reduces, trunk and DFlash2 drafter
As qwen35_fp8 has them (prefetch_beside, rad_arch.h): behind the o GEMM, beside the attention
block's all-reduce, gate|up's leading 24 MB are read into the on-die cache; behind the down GEMM,
beside the feed-forward's, the next layer's q; the drafter's all-reduces take the same
(Dflash2::Config::prefetch). Decode steps of up to 32 rows, none on a step with a prompt's rows,
only at more than one rank; RADIANCE_PREFETCH=0 declares none.

TranslateGemma-27B MXFP4 + DFlash2, TP2 on two R9700s, no speculation, two rounds, x1 / x4 / x8
tok/s against none (56.8 / 182.0 / 325.0): 8 MB 63.3 / 203.1 / 354.9; 12 MB 63.0 / 202.6 / 354.9;
16 MB 63.5 / 203.9 / 356.6; 20 MB 64.1 / 204.0 / 359.4; 24 MB 64.4 / 206.4 / 359.3 (+13.4 / +13.4 /
+10.5 %); 32 MB 63.1 / 201.4 / 351.9. With speculation 7 (three rounds, greedy, medians) x1 / x4 /
x8 / x16 158.1 / 409.0 / 592.0 / 710.8 -> 177.3 / 428.4 / 592.3 / 717.6 (+12.1 / +4.7 / 0.0 /
+1.0 %). Bit for bit: a prefetch reads weights only.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 10:11:47 +01:00
mici81andClaude Opus 5.5 be85c0ba7f qwen35_fp8: weight reads beside the decode all-reduces, trunk and DFlash2 drafter
As gemma4_bf16 does (prefetch_beside): at two or more ranks, on decode steps of up to 32 rows, gate_up's
first 12 MB is read into the on-die cache beside the mixer's all-reduce and the next layer's first
projection's beside the feed-forward's; the DFlash2 drafter's reads take the same 12 MB.

Qwen3.8-27B MXFP4 + DFlash2, tp 2, 2x R9700: no speculation x1 61.2 -> 67.9 tok/s (+11 %), x4 225.0
-> 251.2 (+12 %), x8 403.7 -> 438.6 (+9 %), x16 650.8 -> 668.1 (+3 %), x32 +0.8 %; speculation 7
x1..x16 +0..+2 % for the trunk, the drafter's reads x1 +6 % (median of eight rounds); prefill
unchanged. The size and ceiling sweep is in the comment by kPrefetchBytes. RADIANCE_PREFETCH=0
declares none: arch_test's pipe-off case now sets it and still meets the serial graph pinned before
either existed. qwen35_w8a8 builds the same source; the routed (MoE) trunk takes no reads.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 10:11:47 +01:00
mici81andClaude Opus 5.5 fa7a5e4164 r4d_selftest: every push landing after its flag (the push check's regression case)
A test-only mode of the two-rank exact all-reduce (drain 4, set by
R4D_AR_TEST_LATE_PUSH=1 in the launcher, not in any tuning table): every block
publishes its flag before its push, pushes about 20 us later and stores its check
word as a release, since no flag release follows to write the bytes back. The new
case runs the 32-round sweep of ar_oneshot_2rank_exact and its host twin under it.

Without the push check the readers sum their slots' previous contents (16.5 million
of 18.5 million elements wrong on the device row, 12.9 million on the host twin);
with it every sum is exact.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 10:11:27 +01:00
mici81andClaude Opus 5.5 0044d8d201 libr4d: check that a peer's push has landed before reducing it (2-rank family)
A two-rank all-reduce or gather pushes its bytes into the peer's slot over PCIe P2P,
drains its stores and then publishes a release flag; the peer reads the slot once it
sees the flag. On 2x R9700 the bytes do not always land before the flag. With reads
streaming beside the all-reduce (prefetch), a greedy reply differed from one server
start to the next.

A probe in ar_rmsnorm_quant_fp8 compared, right after the handshake, a plain load of
the slot with a system-scope load and with the same word 100 us later: in about 1
launch in 1000 the reader saw the slot's previous contents, and the new bytes arrived
about 1 us later, sometimes more. Pushed bytes wait in the writer's L2 until a
system-scope release writes them back: with the flag sent before the push (a test
mode) and nothing after it, they stayed invisible for the whole kernel (49 ms). The
flag's release does write them back, but the writeback and the flag store reach the
peer by different paths, so the flag can arrive first. A stronger drain on the writer
(drain=1), PCIe relaxed ordering off on both cards and an HDP flush on the reader did
not change that; acq=1 hides it only by delaying the reads (and costs 12-33 % of
decode).

The writer now sums a per-dword hash (MurmurHash3's finalizer over value and index)
over what it pushes and stores the block's sum, salted with its handshake value, into
the peer's check word for (slot, block): two parity slots of fine-grained words after
the flags. The flag's release that follows writes the pushed bytes back. The reader
reads the check word, sums the same over the bytes it is about to read and, until the
two agree, takes an acquire fence, sleeps briefly and reads again; a push that never
lands traps after 2 s. A stale element and a stale check word both disagree, so the
order in which the two land does not matter. No value changes.

Kernels: ar_rmsnorm_quant_fp8 (exact and 6-bit wire), r4d_ar_oneshot_2rank_exact,
r4d_ar_hc_write, r4d_ar_gather_hc_write, r4d_ar_gather_2rank,
r4d_ar_oneshot_2rank_wht6, r4d_ar_hc_write_wht6, ar_rmsnorm_quant_i8,
r4d_ar_ln_had_quant_i8. Also: the link gate is released after the check, the exact
and gather launchers round their width to whole waves (the check's wave sum reads all
32 lanes), and ln_had's dynamic LDS ceiling leaves room for the check's static words.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 10:11:27 +01:00
gearwave00001 7935897260 driver: reference media ride both phases of a latent-upscaled request; keyframes stay refused by name
Refs carry their own latent grids, so conditioning is grid-independent and
survives the draft->refine canvas switch; only the pack's video-target
segment resizes. shape_job now lays the pack out twice on a wide+refs job
(draft geometry -> seg_s/mod_seg_s/step_rows_s/lat_v_s + pos_small) and
stage_geom/build_step stage the draft tables while small_now holds. The
arch re-derives the pack from the staged geom, so the plugin needs no
change. Keyframes + upscale now refuse with a message that names the
keyframe and latent_upscale and points at sending the frame as a
reference image instead.

Host: 2 new video_gen tests (per-phase seg_cu/geom/lat/pos staging, the
by-name refusal). Device (dual R9700 TP2, dasiwa-fp8): 2x at 704x704
completes in 133s vs 212s un-upscaled, same-seed rerun bit-identical in
video and audio, refs held identity through both phases; t2va+upscale
control clean; fl2va+upscale refused by name.
2026-10-25 04:10:16 -05:00
mici81andClaude Opus 5.5 2721f7c951 MXFP4 gated fold: review fixes and docs
The parts of the series' review rounds that concern the fold, carried over when the series was
split:

- gemm_mxfp4a8_gated_gemv: operand dtypes checked, the activation scale grid read as the gemm_nt_q
  rows read it (mx_ascale_grid), row pitches checked against the widths; the arrival counters are
  zeroed before any launch reads them (the memset is on the null stream, which the engine's
  streams need not wait for).
- The layout hooks refuse an operand the gated row does not have; the GeGLU chain refuses
  out_bf16 (its bf16 plane is a temporary there).
- r4d_selftest: the reference plane through the gemv row's own hook must be the same bytes; the
  small gated cases at K 256.
- libr4d/README.md and docs/TOOLS.md: the row, and --perfmxd's fold timing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 09:59:53 +01:00
mici81andClaude Opus 5.5 cbc299417e gemm_mxfp4a8_gated_gemv: a block per gate/up tile pair, the group quantised by its last block
One block a 128-column group left the grid at n / 128 blocks (68 at Qwen per rank on 32 WGPs) and
the fold lost to the pair it replaces. Now the gemv row grid and K order, the bf16 product and
row amaxes through the op scratch, an arrival counter per group keyed on the output. Byte for
byte the old fold (selftest, twice into one output); r4d_selftest launch_row sizes scratch.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 09:59:53 +01:00
mici81andClaude Opus 5.5 a596f68782 gemm_nt_q_gated_mx at gelu_tanh: the GeGLU MLP's gate_up, gelu_mul and quant_act_fp8 in one launch
TranslateGemma's MLP over MXFP4 runs gate_up, gelu_mul into a bf16 plane and quant_act_fp8 over it
before down. The gated fold now takes act gelu_tanh: gelu_mul's tanh GELU with its constants, the
product rounded to bf16 as gelu_mul stores it, then quant_act_fp8's quantiser (the same arithmetic as
gated_quant_fp8's). Byte-identical to the three-op chain (selftest at M = 1, 4, 8 on TranslateGemma's
per-rank gate_up, the smallest shape and the per-row scale); the replaces-hook gives the chain. The
GeGLU form writes no out_bf16: the chain's bf16 plane is gelu_mul's own output, which the hook cannot
hand to an optional operand, and the shim refuses one.

The gemma3 plugin declares the fold at up to 8 rows when both MLP linears are MXFP4 and no
calibration tap reads the bf16 plane.

TranslateGemma alone, speculation 7, two rounds each: one stream 144.5 / 144.9 -> 151.5 / 150.5 t/s,
four streams (32 rows a step, past the band) unchanged; greedy translations identical.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 09:59:53 +01:00
mici81andClaude Opus 5.5 f16854499c decode launches: gate_up + gated_quant_fp8 folded for MXFP4 (gemm_nt_q_gated_mx)
A decode step on Qwen3.8-27B at TP2 issues 631 kernels a card, and a dependent kernel costs the card
3.5-6.4 us in a replayed graph on gfx1201 however little it does, so launches are about 13 % of a
step.

- gemm_nt_q_gated_mx: gemm_nt_q_gated over an OCP-MXFP4 weight (b_ref after b_scale; a new op, not
  an optional operand on the old one). Row gemm_mxfp4a8_gated_gemv: M <= 8, a block per 128-column
  group of the gated output, a wave per gate or up tile running all of the gemv WMMA form's partials
  in its order, then gated_quant_fp8's epilogue -- byte-identical to gemv + gated_quant_fp8
  (selftest, M = 1..8, Qwen's and TranslateGemma's gate_up). The MLP block declares it for a plain
  MXFP4 gate_up when a loaded library declares the op (libref does not), so a CPU-only engine takes
  the pair. Layout hooks map its b_ref (operand 4) to gemm_nt_q's index, so the weight is stored once.
  The fold: 82.5 us against 81 + 4.6 for the pair at Qwen's gate_up, 98.8 against 104 + 4.7 at
  TranslateGemma's.
- --perfmxd times gated_quant_fp8 and the fold beside the gemv row at a gate_up shape.

Greedy texts of four prompts, speculation 0 and 3, identical to the production build.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 09:59:53 +01:00
C_Tamas 486c933161 device and plugin boundary: kv_resolve, the streamed store rows, ABI 30 2026-10-25 09:58:04 +01:00
mici81andClaude Opus 5.5 32881da9fd docs/GUIDE: two engines on one R9700 pair -- the driver's queue split (amdgpu.num_kcq) and the start order
The four compute queue slots the GUIDE names are what amdgpu leaves to user queues while it keeps four of the
card's eight for its own kernel queues. With num_kcq=0 MES maps all eight (compute_hqd_mask 0xf), two engines'
queues fit, and the weight reads beside the all-reduces can stay on. The order the engines create their
second-lane queues decides where MES places them, so the first engine should serve one request before the
second starts. Measured with Qwen3.8-27B and TranslateGemma 27B on two R9700s.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 09:33:05 +01:00
keptn42 6d6541af42 docker: libopenblas-dev in the build stage, so libquant's GPTQ uses LAPACK 2026-10-25 09:32:42 +01:00
mici81andClaude Opus 5.5 b61394e13c r4d_selftest: --perfpaged Q CTX times the paged prefill attention at every KV layout
The paged prefill attention rows (head_dim 256, gqa 6) at Qwen3.8-27B's per-rank geometry under TP2: one
sequence whose last Q of CTX tokens are the queries, causal, at fp8, fp8 K + 4-bit V, 6-bit K + 4-bit V and
bf16. A long prompt's prefill step is this at Q = the chunk (or a pipelined piece) and CTX = the tokens so
far, and nothing else times it without a server. Two R9700s at 265 W, 1024 queries ending 41040 tokens:
4.37 / 4.26 / 4.46 / 4.76 ms (fp8 / fp8_v4 / k6_v4 / bf16), 107..120 TFLOP/s.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 07:33:36 +00:00
mici81andClaude Opus 5.5 75b4c92e7e libr4d: the paged prefill attention (head 256, gqa 6) without its exposed global waits
The tile loop waited out a global round trip every tile with every wave of the workgroup (the only
one on its WGP) stalled: the wide K fetch sat in a branch whose join made the compiler drain every
load in flight right after it, and the fp8_v4 / k6_v4 V scales were packed right after their
prefetch was issued, so it was waited on at once. Now the K fetch is branch-free (the launch's
thread count is stated to the compiler), the scales are packed at the store, and on the fp8 and
k6_v4 caches tile t+1's K is fetched once tile t's last m-tile has its scores (O_KLATE), so the
staging phase between the barriers only widens and stores. Load order only: the bytes are the same
(greedy texts of a server identical, r4d_selftest 8124 ok / 0 FAIL on both trees).

r4d_selftest --perfpaged on the R9700, three interleaved rounds, medians, k6_v4: 2048 queries over
100k keys 25.91 -> 21.47 ms (-17.2 %), over 160k 41.43 -> 33.97 (-18.0 %), over 25k 5.63 -> 5.45
(-3.3 %), 1024 queries over 50k 5.69 -> 5.48 (-3.7 %). fp8: -7.8 % at 100k and 160k, within noise
at 25k and 50k. bf16 (the stated thread count alone): 0 to -3.5 %. fp8_v4 keeps the old order on
all three counts: with them it gained 19 % at 100k but lost 3 % at 25k and 50k.

The gap is widest where the cache no longer holds the KV (k6_v4 at 100k is 70 MB against 64 MB of
Infinity Cache), so the round trip is a DRAM one. Qwen3.8-27B MXFP4 at tp 2, production flags,
cold prefill, three rounds: 100k 3830..3856 -> 3932..3935 tok/s, 25k 5255..5292 -> 5292.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-25 07:33:17 +00:00
C_Tamas 0ef2cc9dd6 Merge branch 'pr4-tests' into pr5-docs-harness 2026-10-25 09:58:26 +07:00
C_Tamas 2dbeaf93d1 Merge branch 'pr3-models' into pr4-tests 2026-10-25 09:58:26 +07:00
C_Tamas d49a2ccb9c Merge branch 'pr2-engine' into pr3-models 2026-10-25 09:58:26 +07:00
C_Tamas 8af24965cc kvstream: the raise names the floor that bound it
With only the union raise, "raised to N tokens" always meant "one decode
step's selection". Now that the shipped floor can bind instead, both startup
lines said the wrong thing: --kv-resident 1 reported "a decode step can name
1026 blocks" while carving 8192. KVStreamRing::by_union carries which bound
won, and KVStreamSetup::raised_by_union hands it to the report.

Verified on 2x16 GB: --kv-resident 1 now prints "a ring under 32768 tokens
(8192 blocks of 4) misses more than it saves, so the shipped floor is what the
carve takes", the report line says the same, kv_resident_blocks reads 8192 and
the engine serves.
2026-10-25 09:58:22 +07:00
C_Tamas 2b1eca5d23 docs: the 32 768-token ring floor is enforced, not advised
3.9 said "run 32 768" and 5.1 told operators to size at it, while the code only
raised to the validation union (4104 tokens at 2 sequences, no speculation).
Both now state it as the floor the carve takes: kStreamFloorTokens, the union
applied on top when it is larger, both clamped to the group's context, and the
raised number carried into kv_resolve's declared slot table. Also writes down
what that means at the bottom end: a context under 32 768 tokens streams
nothing at all.
2026-10-25 09:29:45 +07:00
C_Tamas 01345a16f4 Merge branch 'pr4-tests' into pr5-docs-harness 2026-10-25 09:29:45 +07:00
C_Tamas ac5de25b38 mem_test: fixture contexts clear the 32 768-token ring floor
The ring is no longer carved below kStreamFloorTokens, so the tests that used
a 1 024-token context to exercise the streamed path (the fail-safe warnings,
the packed-layout gate, the resolve-for-another-group case, the union ceiling
and the prefix tier's on/off rule) were silently covering the context instead
of streaming.

They now use --max-model-len 65536 --max-num-seqs 2 (8 192 blocks of 16), pass
that context to kvstream_configure/cap_probe, and pin the raised depth where
they used to pin the flag's: the union ceiling test takes sel_pitch 2048 so
the union (4 096 blocks = 65 536 tokens) is the binding bound, and the
fail-safe's "both ops declared" case now expects the 32 768-token floor.
2026-10-25 09:29:37 +07:00
C_Tamas 523dbab68a Merge branch 'pr2-engine' into pr3-models 2026-10-25 09:29:37 +07:00
C_Tamas df338d49a5 Merge branch 'pr3-models' into pr4-tests 2026-10-25 09:29:37 +07:00
C_Tamas 613bbaacfd kvstream: the ring is never carved below the shipped floor of 32 768 tokens
The raise enforced only the validation union -- the largest block union one
decode launch selects, max_seqs x (1 + n_spec) x sel_pitch -- which on the
reference model is 1026 blocks = 4104 tokens. That is the depth below which a
step cannot be served at all, not the depth below which streaming pays: the
measured curve puts the cost point at 24 576 and the shipped value at 32 768
(docs/KV-STREAMING.md 3.9). --kv-resident 1 therefore carved a 4 104-token
ring, and one 7 800-token request took 7 213 misses over 8 decoded tokens.

kStreamFloorTokens (32 768) is now a floor the carve enforces:

  * kvstream_ring_shape raises any ring under it, then kvstream_ring raises
    that to the union when the union is larger; both are clamped to the
    group's context, so a context under 32 768 tokens streams nothing (the
    ring covers it and the group keeps the base engine's path);
  * RadBuildCtx::kv_resident_blocks carries the raised number into the
    declare, because kv_resolve sizes its residency table from it -- a carve
    deeper than the declared table is refused by the kernel;
  * the startup warning says which bound applied, and KVStreamRing::floor_blocks
    keeps the two distinct.

The flag is still the operator's: --kv-resident 65536 stays 65536, and a
context that fits is untouched apart from the 32 768 floor.
2026-10-25 09:29:17 +07:00
keptn42 49a02c79df deploy/compose, README: NVIDIA-Nemotron-3.5-Bolt-E4B 4-bit container
The feed-forward at four bits (GPTQ), attention and layers 19-23 at i8a8, on one card; the recipe is
gemma4-e4b-bf16-a4-df.recipe with GPTQ for the int4 linears. Needs main from 248ecf5 (a4, #214).
2026-10-25 01:55:35 +00:00
gearwave00001 c8e635f4b1 docs+recipes: the fried look was a modulation-table bug, not the quant -- shed the misattribution
The fp8 watercolour and oversaturation claims predated the root cause: the velocity
head's norm_out shift/scale table was staged at the narrow pitch argument instead of
the declared row width, landing all zeros at t>0, so both heads ran un-modulated.
Since the staging fix no quant has been seen to band. minimax-h3-w8a8.recipe keeps
the int8 case (uniform grid, no E4M3 448-clamp, closest to the int8-convrot finetune
lineage) without the artifact story; the fried-hunt conclusion in NOTE-REF2VA and the
decoder-dump and keyframe-anchor comments carry the same correction as history.

Also accuracy against the shipped server: GUIDE 5.16 and ARCHITECTURES document
i2va/l2va/fl2va/ref2va (first_frame/last_frame parts, 9/3/3 reference ceilings,
keyframes xor refs) instead of t2va-only; NOTE-REF2VA's stale keyframe-pin pending
claims marked shipped, ticket numbers stripped from its shipped headings, its ABI-24
line qualified; the ComfyUI blurb widens to ~50-60 GiB for the w8a8 containers; and
PORT-REF2VA.md leaves the index -- info/exclude always meant it local-only.
2026-10-24 20:40:23 -05:00
C_Tamas 9d5169e8a2 docs: the exclusivity table says whether streaming runs, not just what the tier does
The result column now states the outcome the operator cares about -- "streaming
off" for the three rows where it does not run, "streaming on" for the two where
it does -- and the closing line spells out that both "on" rows mean streaming
works, prefix-cache hits work, and only the RAM overflow tier is gone.
2026-10-25 07:50:33 +07:00
C_Tamas d7b7aefdd3 docs: make the exclusivity table consistent with what "streams" means
The column named a model; the decision is per group, per run. It now says
"the group that would stream", defines the context limit the row refers to,
and spells out the two sides: no streamed path (dense attention, a windowed
group, a packed fp8_v4/k6_v4 cache), versus a full group with an fp8 (E4M3)
or bf16 cache whose resolve and streamed store both linked.
2026-10-25 07:46:30 +07:00
C_Tamas ec6bfcd1ab docs: the exclusivity section, as a heading and table of its own
3.8 gains "When it is on, and when it is off. --prefix-cache-mib vs
--kv-resident are EXCLUSIVE": the one-line summary, the five-row table, and
the note that "streaming" means the engine's answer rather than the flag's.
2026-10-25 07:33:40 +07:00
C_Tamas e0bf58dd40 docs: the prefix cache's host tier and --kv-resident are exclusive
An entry covers every cached group, and a streamed group's rows are addressed
by the block id its sequence used, in that group's own pinned mirror: a slot
cannot stand in for them and their ids cannot be given up for one. So the
tier is turned off when a group really streams, and its MiB are not reserved.

  * KV-STREAMING.md 3.8: the rule, the on/off table (flag absent or 0, ring at
    or above the context, an architecture with no kv_resolve, and under the
    context with the tier at 0 or above), the three startup lines, what it
    costs, the defects it replaced and the tp2 measurement; the host-RAM gate
    paragraph no longer counts a tier that will not exist.
  * KV-STREAMING.md 4.1: the module boundary names the host tier beside
    TierExec's gather, since streaming does not take the prefix cache over.
  * GUIDE: the operator line under --prefix-cache-mib, and the streaming
    section's budget bullet, which no longer says the tier must be lowered.
2026-10-25 07:03:43 +07:00
C_Tamas adee014122 Merge branch 'pr4-tests' into pr5-docs-harness 2026-10-25 07:03:31 +07:00
gearwave00001 7c3b5ab7d5 merge 1.12.0: gemma4 E2B/E4B and Nemotron Bolt E4B arrive; the ref2va audio, rows and ABI work carried across
conv1d keeps both stride forms: upstream's causal codec downsample with cu_div (Fish Audio) and the port's explicit-pad non-causal one (the H3 audio encoder's), in libref, libavx and libr4d alike; the ABI takes upstream's 27 on top of the port's RadVideoGenBatch growth.
2026-10-24 19:03:26 -05:00
C_Tamas 4134b70088 mem_test: the host tier never takes an entry with a streamed group
Two pins on the rule in core/mem/prefix.cpp:

  * an_entry_with_a_streamed_group_is_never_demoted -- demotable() is false,
    the tiers are never told about the entry (plan_writeback yields nothing),
    drop_clean takes nothing, and trim_sparing evicts it whole: every group's
    block comes back, the streamed one included;
  * the_prefix_cache_host_tier_is_off_only_when_streaming_is_really_on --
    kvstream_prefix_host_off() turns --prefix-cache-mib off only when
    cfg.kv_streams is set, i.e. the ring is under the context and the
    architecture streams; the flag absent, a ring that covers the context and
    a model with no streamed path all keep the tier. Runs through
    kvstream_cap_probe, so the three cases are the ones an operator hits.
2026-10-25 07:03:19 +07:00
C_Tamas ba8f13bea3 Merge branch 'pr3-models' into pr4-tests 2026-10-25 07:03:17 +07:00
C_Tamas dfed12883b Merge branch 'pr2-engine' into pr3-models 2026-10-25 07:03:08 +07:00
C_Tamas 2bf1096131 prefix cache: the host tier cannot hold a streamed entry, so it is off
The prefix cache's host tier and --kv-resident are exclusive, and the engine
used to find that out at the first restore. An entry covers every cached
group; a streamed group's rows are addressed by the block id its sequence
used, in that group's own pinned mirror, so a slot cannot stand in for them
and their ids cannot be given up in exchange for one.

Three defects came from ignoring that:

  * the write-back gathered the resident sibling with the streamed group's
    block id, so the host slot held another group's row (TierExec indexes
    its block vector by gi_, the entry's ids are in groups_ order);
  * demotion released the streamed group's ids too (PrefixCache::
    release_blocks walks every group), handing the mirror rows the entry
    lives in back to the allocator;
  * a restore reserved one group's ids against an entry that has two, so
    rebind returned RAD_E_SHAPE and the record was dropped -- and
    engine.cpp's failure path then released those ids against the wrong
    pools.

Measured on 2x16GB tp2, three 44220-token conversations and a replay of the
first after the third displaced it, streaming on: 20247 entries demoted,
8588 restored, replay 0 cached tokens / 16.5s against streaming off's
44160 cached / 0.4s. The copies were pure waste.

Two rules now:

  * PrefixCache::demotable() is false when any cached group streams: the
    tiers are never told about such an entry (insert), and trim_sparing no
    longer skips it as though its copy were in flight, so it is evicted
    whole with every group's ids.
  * kvstream_prefix_host_off() turns --prefix-cache-mib off at bring-up,
    before anything is sized from it, when cfg.kv_streams is set -- the
    flag asked, the architecture streams and the ring is under the context.
    A flag with no streaming behind it (0, a ring that covers the context,
    a model with no kv_resolve) keeps the tier exactly as configured.

On the cards: --kv-resident 32768 reports "no host cache ... so it is off"
and 0 (off); --kv-resident 131072 keeps 2.00 GiB / 38836 entries. The tests
live in the mem test file's own commit; the docs in the docs commit.
2026-10-25 07:03:03 +07:00
keptn42 c3567d3f03 deploy/compose, README: Ornith-1.5-122B containers
Four containers on Hugging Face (keptn): FP8 and w4a8, each with MTP or DFlash2, on four cards.
A compose file and a row in the models table for each; docs/DOCKER.md lists them and the two
NVIDIA-Nemotron-3.5-Bolt-E4B files.
2026-10-24 23:47:26 +00:00
gearwave00001 82a2187188 docs: point README and DOCKER at the ComfyUI node -- the PR's flagship needs a map entry 2026-10-24 18:23:05 -05:00
gearwave00001 eda7169749 comfyui: drop negative_prompt -- H3 is guidance-distilled, and the server refuses it
MiniMax-H3 declares no guidance in RadVideoGenDecl (guidance-distilled: CFG
is baked into the weights, one forward a step), so /v1/videos answers any
request that names negative_prompt with "this model takes no guidance".
The box was not inert -- typing into it failed the job. The widget is gone;
graphs saved against the old schema have the value swallowed, not forwarded.
2026-10-24 18:09:04 -05:00
gearwave00001 1438aad26c comfyui: Radiance's first ComfyUI node -- /v1/videos over HTTP, zero VRAM
One node drives a radiance server: DaSiWa-style structured prompts, all
five tasks (t2va/i2va/l2va/fl2va/ref2va) with their media sockets, two
LoRA dropdown slots fed from GET /v1/loras mirroring --max-loras 2,
tier+aspect size picking that mirrors the plugin's size law into the node
title, and a live per-step progress line. Placement is a first draft; the
folder is exactly what ComfyUI loads from custom_nodes/.
2026-10-24 16:38:48 -05:00
gearwave00001 6bcb481450 server: a keyframe request may centre-crop its first anchor instead of stretching it
The reference stretches the first frame to the output canvas, which squashes a portrait
photo pinned into a landscape video (ComfyUI behaves identically). Optional per-request
first_frame_mode: "stretch" (default, the reference's own resize) or "center" -- the
already-implemented cover-crop, previously used only for the last anchor: aspect kept,
the canvas centre-cropped. The latent grid stays the exact target canvas either way, so
pinned rows are unaffected; anything else is refused naming the field.
2026-10-24 14:28:54 -05:00
gearwave00001 a14ea5abad server: a video job logs every denoise step and reports the step tally
A waiting client had only job.progress (the steps' share of 0..90) and no
pace, so a long render looked like a hang. The job's thread now emits one
RAD_INFO per STEP -- step N/M, mean s/step and an eta, measured from the
first step's arrival on the steady clock so queue and encode time do not
inflate it -- and the video object carries steps_done/steps_total while it
runs (absent until the first step lands, so a queued object is unchanged).
The rate is a mean across the job; a latent upscale's small steps are
quicker than its refine steps, so the eta is a mean's guess -- the
completion line's breakdown stays exact. videos_test asserts the tally
reaches the finished object (the fake generator lands two steps).
2026-10-24 11:14:33 -05:00
mici81andClaude Opus 5.5 e25951c51e arch_test: the qwen35 family's pins with the a|b lane
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 15:17:21 +00:00
mici81andClaude Opus 5.5 e6fa74087a qwen35_fp8: the GDN a|b projection on the second lane at decode sizes
At decode and verify sizes (up to 64 rows) the delta net's a|b projection (gemm_nt, N = 48) is
nearly all launch cost and reads only the norm's output, as the in-projection does: it runs on the
second lane beside the in-projection and is joined back before the convolution reads `ab`. A
prefill chunk keeps one lane: there the projection is real work and the lanes would split the
bandwidth the in-projection uses. An opt-in (GdnFP8::ab_lane) set by qwen35_fp8 only, whose second
lane carries no collectives: +1.1 % one stream without speculation (three rounds each). The same
for k and v beside q|gate in the gated attention was measured and left out (-0.7 %: q|gate is a
full-bandwidth GEMM and they compete).

It costs memory: naming the two buffers concurrent gives the arena a second scratch region and the
bring-up a third queue (Qwen3.8-27B at TP2: arena 534 -> 604 MiB, queues 67 -> 100 MiB a card, KV
752k -> 746k tokens).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 14:20:38 +00:00
d 74f186ca85 docs: no history in the text -- the switch section describes only what exists 2026-10-24 21:03:56 +07:00
d 3041596a6e docs: --kv-resident is a slider, 32 768 is the shipped default 2026-10-24 21:02:48 +07:00
d 3ab0affbbc Merge branch 'pr2-engine' into pr4-tests 2026-10-24 20:57:59 +07:00
d 782ea73fd8 Merge branch 'pr2-engine' into pr3-models 2026-10-24 20:57:59 +07:00
d 8a765db488 flags: drop the refusals for --kv-streaming and --kv-stream-threshold 2026-10-24 20:57:59 +07:00
d 50db0dbd90 Merge branch 'pr2-engine' into pr5-docs-harness 2026-10-24 20:57:59 +07:00
d 09d83c42bc docs: which models can stream, and with which KV cache 2026-10-24 20:39:56 +07:00
C_Tamas a886d2a6ec harness: the multi-turn recall gate, and its README row
Twenty turns of a transcript that outgrows a 32 768-token ring, streaming off
against --kv-resident, a fact planted at turn 2 asked at turn 20; the off arm
must hit the cache and the on arm must stream, or the run is not a reuse test.
2026-10-24 20:23:24 +07:00
C_Tamas e54e570bf1 Merge branch 'pr4-tests' into pr5-docs-harness 2026-10-24 14:41:50 +02:00
C_Tamas aa1b050f93 Merge branch 'pr3-models' into pr4-tests 2026-10-24 14:41:39 +02:00
C_Tamas cc198e98c4 Merge branch 'pr2-engine' into pr3-models 2026-10-24 14:41:20 +02:00
C_Tamas fc034b526e Merge branch 'pr1-device' into pr2-engine 2026-10-24 14:40:11 +02:00
d be47bf19af Merge remote-tracking branch 'origin/main' into pr1-device 2026-10-24 19:31:54 +07:00
C_Tamas b54a80de59 docs and harness: the design note, the flag rows, the kv-* scripts 2026-10-24 19:19:19 +07:00
C_Tamas 5b415b2ef8 tests: the emulator fixtures, the mem/ref suites and the kv_resolve self-test 2026-10-24 19:19:19 +07:00
C_Tamas c2219fccb0 models: qwen4exp_fp8 and GLM-5.3 stream their KV 2026-10-24 19:19:19 +07:00
C_Tamas a9e627b7ca engine: the KV plan split, the host mirror, and --kv-resident bring-up 2026-10-24 19:19:19 +07:00
C_Tamas cce687bf2c device and plugin boundary: kv_resolve, the streamed store rows, ABI 30 2026-10-24 19:19:19 +07:00
keptn42 248ecf5858 recipes: gemma4-e4b-bf16-a4-df (int4 feed-forward, int8 attention and layers 19-23, DFlash, vision) 2026-10-24 13:43:30 +02:00
keptn42 60f6eab298 gemma3: a4 at decode heights through w4a16_asym
The same split as gemma4_bf16 and LinearFP8's w4: up to 64 rows an f16 copy of the input and
w4a16_asym, above that quant_act_i8g and w4a8i8_asym.
2026-10-24 13:43:30 +02:00
keptn42 7e42d394a5 gemma4_bf16: a4 at decode heights through w4a16_asym
w4a8i8_asym has only a prefill kernel. Up to 64 rows the input is cast to f16 for w4a16_asym's
skinny kernel, as LinearFP8's w4 does.
2026-10-24 13:43:30 +02:00
keptn42 7054e505d9 gemma4_bf16: asymmetric int4 linears (w4a8i8_asym over a scale per 128)
As gemma3's G3Linear: u4 codes, a u8 zero point and an f16 scale per [1 x 128], read against the
same per-(row, 128) int8 activation as i8a8.
2026-10-24 13:43:30 +02:00
keptn42 6a6c50e718 arch: RADIANCE_PREFETCH_BESIDE=0 turns prefetch_beside off
Beside another server on the same card the lane-1 read costs more than it gains: the card has
fewer hardware queue slots than the two servers have queues, and the join puts a queue switch
into every decode step.
2026-10-24 13:40:05 +02:00
keptn42 8f6f12e288 README, compose: NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8) with DFlash and vision, one card 2026-10-24 13:39:41 +02:00
keptn42 e1ddb61087 recipes: gemma4-e4b-bf16-i8g-df (int8 trunk at i8a8, DFlash drafter on block FP8, bf16 vision tower) 2026-10-24 13:39:41 +02:00
keptn42 c4e372e699 gemma4_bf16: i8a8 linears (int8 weight and activation, a scale per 128)
From arch/gemma3's G3Linear: int8 codes with a bf16 scale per [1 x 128], gemm_nt_q at i8a8
over quant_act_i8g (an activation scale per row and 128 columns). Gemma 4 E4B's activations
carry channels 40-200 times the row median; one int8 scale a row costs most of w8a8's KL
(wikitext-2: w8a8 0.076, i8a8 0.010). q|k|v stay one GEMM; the fused junctions stay off.
2026-10-24 13:39:41 +02:00
Deadcode 5a9ce4912b radiance 1.12.0
New models:
- Fish Audio drama-3: speech with speaker tags and inline direction, voices cloned from reference
  clips (the `references` field of /v1/audio/speech and the streaming session), two cards
- Gemma 4 E2B/E4B (KV-shared layers, per-layer embeddings, clipped vision linears), with
  NVIDIA-Nemotron-3.5-Bolt-E4B in bf16 with DFlash and vision on one card, and E4B recipes

Speed:
- MXFP4 GEMMs for one to 64 rows and a tiled prefill GEMM at TN=4 from 1024 rows: the 27B MXFP4
  with DFlash2 decodes about 1% faster at c1, 5% at c4 and 14% at c16
- The fp8 and int8 LM heads read their weight once for 65 to 128 rows
- A prefill step of one sequence runs in two pieces on a second lane at two ranks (qwen35_fp8,
  gemma3): a 45K-token prompt on the 27B fp8 in 15.1 s instead of 16.2 s
- Gemma 3's fused all-reduce junctions also under a lossy wire
- --draft-short-from N: a block drafter runs its shorter block from N decoding sequences on
  (off by default; with 8 on the 27B MXFP4: c8 +12%, c16 +18%, c64 +32%, c1 unchanged)
- --tp-attn-split rows: GLM-5.3-Flash's MLA attention split by rows over the ranks, 18 to 21%
  faster prefill; lossy, `heads` stays the default
- --draft-coupling on: Qwen3.8-Flash-Next's MTP drafter samples its proposals from its reranked
  top-8 and the target's draw is coupled to it; pays at high temperatures (c1 at T 1.0: 155 ->
  178 tok/s), costs at low ones; off by default

Features:
- Edited prompts on windowed models (Gemma 4) reuse their prefix: periodic window snapshots, and
  snapshot-backed prefix KV kept across recomputes (an edited tail on Gemma 4 31B: 96 s -> 2.6 s)
- DELETE /sessions/<label> and DELETE /sessions?id=<id> forget one stored conversation
- --state-cache-dtype f16: the delta-net state cache at half the memory (qwen35 plugins; lossy)

Fixes:
- A browser's CORS preflight allows DELETE

Changes: Plugin ABI 27: out-of-tree plugins must be rebuilt. The environment switches the PRs
added are flags now (--tp-attn-split, --draft-coupling, --state-cache-dtype).
2026-10-24 13:12:28 +02:00
gearwave00001 f7c349075c minimaxh3: one canvas-sized frame must fit every encoder level; keyframes ride any legal output size
A one-frame media -- a reference picture, or an endpoint keyframe -- never
shrinks through the temporal downsamplers (1->1->1->1 against a full clip's
17->17->9->5), so it rides every level alone, and a keyframe must ride the
TARGET canvas: it is resized to the output resolution before the VAE and its
latent rows share the target grid. The deep level buffers only held a full
clip's shrunken temporal volume, which capped a single frame at 5*256^2
(~572-sided) -- 480x736 was refused, 544x736 had died the server with
'venc.l3.in 6256>5120' before cont.36 added the accept-time 400.

declare_venc now sizes each level's rows as max(full clip, kEncOneFrames)
frames at the tile side, kEncOneFrames = ceil(1344*768 / 256^2) = 16, so a
single frame is bounded only by the model's whole canvas (16*256^2 >=
max_area); venc_geom applies the same max() per volume. Multi-frame media are
unchanged (the pixels volume still forces sides <= 256). Levels 2-5 grow
(R 36864->65536, 5120->16384, 1280->4096, 192->1024): about +150 MB arena,
plugin-only -- no kernel, ABI, or container change; the driver's accept-time
check delegates to the plugin export and follows automatically.
2026-10-24 05:03:00 -05:00
keptn42 4bca30369b README, compose: NVIDIA-Nemotron-3.5-Bolt-E4B bf16 with DFlash and vision, one card 2026-10-24 11:13:16 +02:00
keptn42 eeeeea3c88 recipes: Gemma 4 E4B (bf16 with DFlash, w8a8 with DFlash, w4a8 with and without)
Wikitext-2 KL against the HF bf16 reference: bf16 0.0015, w8a8 0.076, w4a8 0.242 (attention and
layers 19-23 int8, feed-forward int4; all int4 is 0.612).
2026-10-24 11:13:16 +02:00
keptn42 f41f998e60 gemma4 DFlash: read dflash_config.causal for the sliding layers
NVIDIA's Nemotron-3.5-Bolt-E4B drafter states causal false with all five layers sliding; z-lab's
configs state nothing and keep the causal default.
2026-10-24 11:13:16 +02:00
keptn42 cf10b28663 gemma4_bf16: per-layer inputs of image positions use pad_token_id
As the reference (Gemma4Model.forward) the token-identity lookup of a multimodal placeholder is the
pad token's row; the context projection reads the scattered image rows.
2026-10-24 11:13:16 +02:00
keptn42 d337f53043 gemma4 vision: clipped linears (vision_config.use_clipped_linears)
Gemma 4 E2B/E4B clamp every projection input and output of the tower to bounds the checkpoint
stores. Nine clamps a layer around the fused q|k|v and gate|up GEMMs (the fused parts share
their bounds in NVIDIA's E4B).
2026-10-24 11:13:16 +02:00
keptn42 9921067b04 gemma4_bf16: name the fused q|k|v row by class, not by k_eq_v
A global class with its own v projection (attention_k_eq_v false, Gemma 4 E2B/E4B) named its row
attn_qkvs like the sliding class, and the second declaration failed at w4a8.
2026-10-24 11:13:16 +02:00
keptn42 a58d23f4eb gemma4_bf16: per-layer embeddings (hidden_size_per_layer_input)
The token-identity table embed_tokens_per_layer (scaled by sqrt(n_ple)), the context projection
of the scaled embedding with its per-(token, layer) norm, combined (ctx + tok) * 2^-0.5; in each
layer after the feed-forward add: gate, gelu_tanh times the layer slice, projection, norm, add,
then the layer scalar. With fused junctions j_ma closes the PLE branch instead of the
feed-forward. One rank only.
2026-10-24 11:13:16 +02:00
keptn42 e9d34c1611 gemma4_bf16: KV-shared layers (num_kv_shared_layers, Gemma 4 E2B/E4B)
From layer n_layer - num_kv_shared_layers on, a layer has no k or v projection and attends over
the cache of the last earlier non-shared layer of its class (transformers store_full_length_kv).
Shared layers are not bound to a KV group, so pages count only the layers that write. A null
num_global_key_value_heads falls back to num_key_value_heads.
2026-10-24 11:13:16 +02:00
Constantin f2c892761a mem: preserve snapshot-backed prefix KV across recomputes
When a stateful model's cached prefix is host-resident and another request recomputes shared tokens without restoring that entry, PrefixCache::insert can replace KV still referenced by an older recurrent checkpoint. Preserve the first cached copy for snapshot-backed prefixes regardless of tier, while retaining rebinding behavior for non-stateful caches.

Add a regression covering a recomputed shared prefix, the original host copy, and its recurrent snapshot.

Tests: `ctest --test-dir build-gfx1201 -L '^fast$' --output-on-failure --parallel 24` (96/96 passed).
2026-10-24 11:11:46 +02:00
mici81andClaude Opus 5.5 7fa2ec0e4a arch_test: qwen35_fp8's two-rank pins for the pipelined prefill alone
The pins came from the whole series (with the gated fold and the a|b lane); this PR alone pipelines
the 4096-row budget's step to another graph, and with the pipeline off the build is upstream's serial
one, whose pin the off case now checks (main's 0x36da8d762194e24e / 0xe4022daff02ec8bd).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 acd06d2a48 docs: the pipelined prefill, the second lane's window and scratch region, the narrow all-reduce at three and eight ranks
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 4ec175549c pipelined prefill: review fixes
The parts of the series' review rounds that concern the pipelined prefill and the second lane,
carried over when the series was split:

- qwen35_fp8: a trunk whose norms write rotated int8 codes (qwen35_w8a8 where libr4d serves the
  `_had_quant_i8g` forms) prefills serially -- the boundary norms on the second lane issue the E4M3
  pair only, and before the fix libr4d refused them for the int8 op, failing every one-sequence
  prefill step of 1024 rows or more; a pipelined step whose bounds have no storage fails the step
  rather than falling back on one rank only.
- The three- and eight-rank overlap all-reduce rows accept every tunable pin their wide rows accept
  (r4d_selftest checks it).
- rad_builder.h: the window joins lane 1 into lane 0 at its end only, so an op declared before it
  must not be issued again while lane 1 has work pending.
- tests: arch_test for the w8a8 trunk; plugin_test's lane-row comment.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 48e41fda1e the narrow overlap all-reduce at three and eight ranks only on request: R4D_AR_LANE_3_8
The three- and eight-rank `overlap` rows (ar_twoshot_3rank_exact_lane, ar_twoshot_3rank_ti8_lane,
ar_twoshot_8rank_exact_lane) took the four-rank lane rows' narrow launch for every collective a plugin
issues beside compute: qwen4exp's --prefill-span, gemma4's prefill trunk overlap and the image and
video plugins' second-lane collectives included. That changed a default above two ranks without a
measurement, and a narrow grid can lose there too: where the all-reduce is the longer of the two (a
large message, slow or shared links, seven peers to feed at eight ranks) the step waits on a slower
collective. They now launch exactly as the wide rows by default (tArTs38Lane holds tAr's defaults: the
same grid, the same bits, the same time); R4D_AR_LANE_3_8=1, read once at load, gives them the
four-rank lane's four blocks of 1024. The bits are the same either way.

r4d_selftest checks the defaults both ways (failed before the change: nblocks 4 where the wide rows'
rule is 0). GUIDE §4.7 (with what to set and what it may gain or cost), §4.5, the environment table,
OPS, TP3 and libr4d/README say it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 0d2b502d51 the second lane's window (rad_lane1_window_begin / _end): concurrent buffers live across it, not the whole program
rad_buf_concurrent held a buffer for the whole program because the planner cannot tell when lane 1
runs. An architecture whose lane-1 work lies in one stretch of its declared ops now declares it, and
its concurrent buffers live across that window and their own uses, so the drafter's and the heads'
buffers share their bytes again. Ctx holds it: an op on lane 1 outside the window fails the step by
name, and the first lane-0 op past it joins lane 1 first when work is pending there. qwen35_fp8 and
gemma3 declare it from the embedding's all-reduce to the final norm. Qwen3.8 + DFlash2 at 64
sequences with speculation: activation arena 633.99 -> 526.32 MiB a card, upstream's exactly (with
the second lane's own scratch region, KV 86208 -> 93856 tokens against upstream's 95520).
arch_test's fake builder applies the window too, so the pinned steps check every plugin touches its
concurrent buffers only inside it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 0c813784a0 core: the second lane's scratch region sized by the ops it may issue
A program naming a buffer to rad_buf_concurrent got two scratch regions of the program's largest kernel
scratch each, though by Ctx::lane1_ rule 3 an op on the second lane touches only rad_buf_concurrent
buffers. Program::scratch_bytes_lane1 is the largest device scratch of such an op (or one naming no
transient buffer); the Arena takes per-region sizes, arena_plan_bytes counts them for the VRAM budget,
and Ctx::issue refuses a larger lane-1 request by name instead of overrunning the region. Qwen3.8 with
its drafter: region 1 0 B instead of 50 MiB (17 MiB without speculation).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 5838c25343 pipelined prefill: the drafter taps on the first lane, so dflash_src stays in the sharing pool
dflash_src ([max_tok, n_taps * n_embd], 100 MiB at a 2048-row chunk) was written on lane 1, so it
had to be a rad_buf_concurrent buffer, held for the whole program. Each piece of a tap layer is now
copied on lane 0 right after lane 0 has waited for that piece's feed-forward boundary, before
anything writes those rows of x again. Same copy, same bytes (pinned steps unchanged); qwen35_fp8
and gemma3. On its own it does not move the activation arena's peak, which other concurrent buffers
set; it is one buffer fewer for the second lane's window (next commit) to bound.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 ad01fcaf19 review notes of the pipelined prefill past two ranks; selftest timings warm the clocks first
Independent review of fa118d8 / 14fb72c: no defect. Notes taken:

- RADIANCE_PREFILL_PIPELINE takes 1 / true as on and 0 / false as off (the old per-arch switches
  took 0 for off; such a value must not leave the pipeline on); the header says that past two
  ranks only the two-shot band is narrow and that eight ranks pipeline on the exact wire only; the
  note says the switch allows the pipeline (gemma3 may still turn it off); "rad_arch.h" as the other
  common headers include it; comment lines rewrapped.
- plugin_test resolves the all-reduce at `overlap` 1 against the real libr4d: the two-shot band
  takes the lane row at three, four and eight ranks, exact and ti8; the one-shot band keeps the wide
  row. arch_test: every spelling of the switch, off at two ranks in all three; no three-rank arch
  case (neither test model's heads split three ways, nor do the real models' KV heads).
- r4d_selftest: gemv_wide's two column tiles at four row tiles and on the per-row scale.
- r4d_selftest: every timed pass is preceded by an untimed one. A fresh process otherwise times its
  first pass while the clocks ramp up from idle (up to 1.5x slow, +-30 % between runs); two builds
  of the same machine code read 13 % apart until both warmed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 284feda3a6 pipelined prefill past two ranks on request: RADIANCE_PREFILL_PIPELINE, narrow all-reduce at three and eight
- One switch for qwen35_fp8's and gemma3's pipelined prefill, RADIANCE_PREFILL_PIPELINE=auto|on|off
  (arch/common/rad_prefill_pipe.h), in place of RADIANCE_QWEN35_PIPE / RADIANCE_GEMMA3_PIPE. auto
  (or unset) pipelines at two ranks, where it is measured; on also at three, four and eight, with a
  declare note that it is not yet measured on such hardware; off never. Another value is noted and
  taken as auto.
- libr4d: the narrow `overlap` all-reduce rows at three and eight ranks, as the four-rank ones are:
  the wide two-shot rows' entry points (exact at three and eight, ti8 at three) at tArTs4Lane's
  launch, so the collective beside the other piece's compute does not take the card (a wide one
  slows the GEMM beside it 1.45-2.1x and ate the whole gain at two). Bit-identical to the wide rows
  by construction; neither launch is tuned on three or eight cards, which this rig does not have.

arch_test: at four and eight ranks a 2048-row step of one sequence is serial unless asked; asked,
it runs in two pieces on every rank with every collective on the second lane at `overlap` 1 and
the embedding's whole (failed before the change: the step stayed serial).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 28f1f2dd8c gemma3: the pipelined prefill's shared pair keeps every linear's own quantiser
The pipeline is decided before the blocks are declared, the fused fp8 junctions only after them.
Where those then did not resolve (no rmsnorm_quant_fp8, a mixed container), every q|k|v and
gate|up still read the shared pair as a shared linear with no quantiser, and the serial fallback
read whatever the last writer left there. The pair is now handed to each such linear as the
target of its own quantiser (G3Linear::q8_into / s8_into): the fused junctions write it when they
resolve, the unfused step's quantisers otherwise.

- a note says why the pipeline is off when declare turns it off;
- a missing bounds buffer fails the step on both ranks (rad_step_fail) instead of one rank
  falling back to the serial step alone.

arch_test: with rmsnorm_quant_fp8 refused at two ranks and 2048 rows the step is serial, every
q and gate|up quantises into the pair it reads (failed before: no quantiser).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 73b1d039a0 gemma3: a prefill step of one sequence in two pieces, block boundaries on the second lane
qwen35_fp8's pipelined prefill on Gemma 3's MXFP4 trunk at two ranks: every block runs a piece
at a time on lane 0 (the attention over its own query bounds and positions, the GeGLU MLP), and the
work between two blocks a piece at a time on lane 1 -- the block's all-reduce at `overlap` 1, its
post-norm and the fp8 junction (the add and the next norm with its quantiser), after the last block
the add, the DFlash2 taps and the final norm. RADIANCE_GEMMA3_PIPE=0 turns it off.

- Every q|k|v and gate|up reads one shared E4M3 input pair under the pipeline (the junctions write
  it), so the second lane's buffers cost one pair, not one a linear (rad_buf_concurrent keeps them
  live for the whole program).
- A window KV group's seqused counts from its rebased first block, so the first piece's cannot be
  its position: it is the group's seqused less the second piece's rows, computed on the card by a
  new libr4d op, sub_i32 (y = x - s[0], int32; documented in OPS.md, a selftest case). The first
  try used the position and faulted on a 12k prompt past the 1024-token window.
- G3Linear and G3JunctionFP8 row-sliced forms; each block's overlap all-reduce.

Bit for bit the serial step: TranslateGemma's KL recordings at chunk 2048 and one sequence a step
(so a document's steps from 1024 rows pipeline) compare equal with the pipeline on and off. Prefill
on two R9700s, chunk 2048: 6k tokens 1.27 -> 1.21 s, 12k 2.48 -> 2.42 s; at chunk 1024 (pieces of
512) no gain, so a deployment wants 2048 (against 1024: -9 % / -7 %). arch_test: a 2048-row TP2
step runs in pieces with its collectives on lane 1 and the shared pair; RADIANCE_GEMMA3_PIPE=0 runs
it serially.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 57d2cb4043 review fixes of the pipelined prefill (independent review)
- pipe_ready: past the batch's and the build's own conditions (the same on every rank), a
  rank-local failure -- no pinned host memory for the bounds table, or its copy failing -- now
  fails the step instead of running it serially. A serial step on one rank beside a pipelined
  one on the other issues different collectives on the shared all-reduce instance: a hang or a
  wrong sum.
- declare frees the previous build's pinned bounds table before resetting the model.
- NormQuantFP8: the slicing comment back above step(); step_plain() gets its own.
- r4d_rows: the TN axis's help text says the new crossover (M >= 1024).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 d39e0511e7 qwen35_fp8: a prefill step of one sequence in two pieces, block boundaries on the second lane
At two ranks a prefill step of at least 1024 rows is cut into two pieces of about half
(pipe_rows: rounded up to 64, both in the whole step's band). Every block runs a piece at a
time on lane 0; the work between two blocks runs a piece at a time on lane 1: the block's
all-reduce at `overlap` 1 (the narrow lane rows), then the next block's plain norm, and after
a feed-forward that keeps its add, the add, the DFlash2 taps and the final norm. The fused
all-reduce + norm is not used there: it holds its blocks while waiting on the link and slowed
the GEMM beside it by a third (measured: no gain at all with it).

- GdnFP8, AttnGatedFP8: takes_pieces(); the dense attention gets a two-piece path (each piece
  its own rows, positions, slots and query bounds, seeing the cache up to its own end), and
  the delta net's piece path takes the caller's normed input (ArPieces::in_ready) and passes
  each piece its own context length (positions + r0), so a prompt's first chunk works.
- MlpFP8: slice() split into body() and tail(), and an overlap all-reduce (issue_ar).
- NormQuantFP8::step_plain().
- M-RoPE batches (the vision tower loaded) take it when no token's components differ: plane 0
  of rope_pos is then every token's position.
- RADIANCE_QWEN35_PIPE=0 turns it off; a wide prefill step that runs serially says why, once.

Bit for bit the serial step: Qwen3.8-27B KL recordings (k6_v4, wht6) compare equal with the
pipeline on and off, and greedy answers to three long requests (680-41k tokens, speculation 3
with the DFlash2 taps) are identical. 41k-token prefill on two R9700s: 9.00 -> 8.41 s with the
TN crossover of the next commit (-6.6 %). arch_test: the two-rank pin moves; new tests pin the
serial build under RADIANCE_QWEN35_PIPE=0 and the pieces, lanes and overlap of a wide step.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:10:08 +02:00
mici81andClaude Opus 5.5 0f4c1afc38 r4d_selftest: timed passes after an untimed one; gemv_wide at two column tiles
A fresh process otherwise times its first pass while the card's clock ramps up from idle: up to
1.5x slow, and two builds of the same machine code read 13% apart until both were warm. Numeric
cases for gemv_wide's two column tiles a block at four row tiles and on the per-row scale.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:09:03 +02:00
mici81andClaude Opus 5.5 fb880cbc2d MXFP4 decode rows: review fixes and docs
The parts of the series' review rounds that concern these rows, carried over when the series was
split:

- gemm_mxfp4a8_decode: the 64-wide slab is chosen by the split the launch runs (a pin or a tuned
  point included), as before the register kernel; the header states the split-row bound the rule
  applies (ks*M = 1024).
- r4d_selftest: the priority order of the MXFP4 rows is checked (gemv / gemv_wide over decode,
  decode_shortk over gemv_wide, decode over tiled); gemv_wide's numeric cases at K 256 and at 56
  rows; the M-invariance check names the decode_shortk corner it does not cover.
- Comments: gemv_wide's two-tile condition (N >= 4096, K >= 3072, an even tile count), the
  decode_shortk corner's bit change at M = 33, decode_shortk in the list of rows whose state is
  keyed on the output.
- libr4d/README.md: the rows by row count, with the measurements behind each band;
  docs/TOOLS.md: r4d_selftest and its --perfmxd mode.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:09:03 +02:00
mici81andClaude Opus 5.5 40d205929a r4d_selftest: --perfmxd for the dense MXFP4 rows; --perfmx is GLM-5.3's expert GEMM
Since 1.9.0 --perfmx times the MXFP4 expert GEMM (M, experts, top_k, skew). The dense rows timing
added in this series had taken the same switch and, parsed first, shadowed it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:09:03 +02:00
mici81andClaude Opus 5.5 f3429d8c13 gemm_mxfp4a8_decode_shortk: the decode kernel at 33..64 rows of a wide, short weight, above gemv_wide
gemv_wide's blocks hold three or four row tiles over the whole K, so on a short K the cross-wave
reduction of a block outweighs its WMMAs, and on a wide N there are many such blocks. Swept over 24
per-rank shapes (Qwen3.8 and TranslateGemma at TP1/2/4/8, 1B/4B/8B-class dense) at 24..64 rows, each
row timed alone: gemv_wide is at least upstream's decode kernel everywhere except N >= 8192 with
K <= 2560 past 32 rows, where it lost by 7..30 % (19456 x 2560 at 64 rows 131.8 us against upstream's
104.5; 16384 x 2048 92.8 / 76.1; 9728 x 2560 74.1 / 67.4). This decode kernel takes that corner:
93.3, 68.6 and 52.5 us. A row of its own (same entry, scratch hook and tunables as the decode row,
priority 59, constraints M 33..64, N 8192..36864, K <= 2560) rather than a rule in the gemv entry,
so the planner's choice stays a table lookup. Narrower N stays with gemv_wide (5120 x 2176 at 40
rows 39.2 against 52.8), as does every shape of the models we serve. r4d_selftest: five numeric
cases over the corner, both activation grids and parts.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:09:03 +02:00
mici81andClaude Opus 5.5 d4eacec5c6 gemm_mxfp4a8_decode: the split and slab rule past 64 rows re-tuned for the register kernel
The rule was tuned with the weight staged through LDS. Past 64 rows (the multi-fragment register
kernel) it now takes the 128-wide slab always and splits K only while every split keeps 16 slabs,
towards a 48-block grid or, at K >= 8192, regardless, up to ks*M = 512 split rows. Swept every
split 1..8 at both slabs on Qwen3.8-27B's and TranslateGemma-27B's per-rank shapes at 96 and 128
rows (warmed); old against new rule, two repetitions, 80 / 96 / 128 rows:

  17408 x 5120   161 / 187 / 215 -> 161 / 175 / 197 us
  5120 x 8704    105 / 116 / 160 -> 110 / 116 / 149
  6144 x 5120     83 /  97 / 105 ->  80 /  87 / 109
  5120 x 3072     71 /  79 /  67 ->  55 /  60 /  69
  21504 x 5376   192 / 207 / 228 -> 187 / 200 / 217
  5376 x 10752   133 / 155 / 197 -> 132 / 154 / 184

Up to 64 rows the rule is unchanged. A different split changes a split row's summation order, so
these rows' bits move within the selftest's bound (gemm_mxfp4a8_decode: 86 ok).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:09:03 +02:00
mici81andClaude Opus 5.5 9daf738909 gemv_wide: two column tiles a block only from N 4096 and K 3072
Measured on smaller models' MXFP4 shapes (r4d_selftest --perfmx, clocks warmed, two repetitions),
two tiles a block lose on narrow or shallow weights -- fewer blocks than the part has units, a
short K a wave: at 32..64 rows 1024 x 2048 +7..30 %, 2048 x 2048 +6..28 %, 2048 x 4096 +4..37 %,
6144 x 1536 at 32 rows +14..30 %. From N 4096 and K 3072 every measured shape gained or held
(4096 x 2048 even; 14336 x 4096 at 64 rows 120 -> 90 us; 4096 x 7168 67 -> 55; the 27B shapes as
before), so the launcher takes two tiles there only. Bits unchanged either way.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:09:03 +02:00
mici81andClaude Opus 5.5 0fb3badc6c review notes of the MXFP4 decode GEMMs: comments, unreachable instantiations
Independent review of 675322e: no defect (the double buffers, the ratio timing against the old
kernel including a split starting mid-block and the 64-wide slab, the clamped tile, the empty
split; every variant without spills inside its waves budget). Notes taken:

- the slab rule's LDS formula was the LDS-staged kernel's; say so, and that the DTM 4 arm may no
  longer pay (not re-tuned);
- mxd_ratio's comment describes when each kernel publishes the ratio;
- gemv_wide no longer instantiates two column tiles at one row tile (unreachable: two tiles need
  more than 24 rows);
- a comment line over 100 columns.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:09:03 +02:00
mici81andClaude Opus 5.5 2382686d3b MXFP4 decode GEMMs past 16 rows: gemv_wide two column tiles a block, the decode row's weight to registers
Bit for bit as before, faster where several streams speculate (25 to 128 rows a step):

- gemm_mxfp4a8_gemv_wide carries two 16-column tiles a block from 25 rows. The activation is read
  per block, so one tile a block read all of it N/16 times -- 356 MB from L2 at 64 rows on a 27B's
  17408-row gate_up, against a 47 MB weight. Each activation fragment now serves both tiles; a
  tile's WMMA chain is unchanged. Four tiles spill past 32 rows.
- gemm_mxfp4a8_decode's multi-fragment kernel (17..128 rows) loads each wave's weight words straight
  to registers, as the gemv kernel does (a fragment-order word is the WMMA fragment's register), and
  double-buffers only the shared activation in LDS: one barrier a slab, the next slab's loads in
  flight across this one's WMMAs. Same fold, k-step and slab order, scale carry and epilogue; its
  whole output compared byte for byte with the LDS-staged kernel's on Qwen3.8-27B's and
  TranslateGemma-27B's per-rank shapes at 17..128 rows, both scale grids, the 64-wide slab, parts
  and forced splits (312 cases, an experiment-only selftest case).

r4d_selftest --perfmx with the clocks warmed (a first timed pass from an idle card catches them
ramping up and read up to 1.5x slow), before -> after:
  17408 x 5120   32 rows 125 -> 85 us, 64 157 -> 122, 96 205 -> 159, 128 245 -> 214
  5120 x 8704    32 rows  75 -> 56,    64  95 -> 75,  128 169 -> 139
  6144 x 5120    64 rows  70 -> 57,   128 121 -> 92
  21504 x 5376   32 rows 154 -> 111,   64 183 -> 150
  5376 x 10752   32 rows 105 -> 68,    64 123 -> 98
At 16 to 24 rows within a few percent either way (unchanged kernels there).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:09:03 +02:00
mici81andClaude Opus 5.5 b66752adcc libr4d: gemm_mxfp4a8_gemv_wide, the gemv row's WMMA form at 9 to 64 rows
The WMMA form takes up to four 16-row tiles a wave: each weight word of a chunk is loaded and folded
once and multiplied with every tile's activation fragment, so the weight streams once from DRAM to
registers whatever the row count, with no LDS staging. A row's sum is its tile's WMMA chain alone, so
its bits are the same at every tile count: the first row is bit-identical from M = 1 to 64 (selftest),
across the gemv row (M <= 8) and the new gemv_wide row (9 <= M <= 64, K % 128 == 0, same entry and
priority). Several streams with speculation land there (4 x (1 + 7) = 32, 16 x (1 + 3) = 64).

--perfmx against the decode row that served 9..64 before (us, Qwen3.8-27B / TranslateGemma per-rank
decode shapes): down 51-80 vs 56-105, ssm_out 27-42 vs 30-55, attn_qg 40-63 vs 44-74, TranslateGemma
down 61-97 vs 66-123, o 22-35 vs 25-51, gate_up at 24-48 rows 110-141 vs 145-170; gate_up at 48-64
rows about even (Qwen) or behind (TranslateGemma at 64, 171 vs 153).

Selftest: gemv_wide at RT 2..4, both activation grids, a partly live tile, parts; the M-invariance check
runs the wide row under the gemv row's selection (mxfp4a8_numeric's any_row).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:09:03 +02:00
mici81andClaude Opus 5.5 75b4d0baa7 libr4d: gemm_mxfp4a8_gemv, the MXFP4 x fp8 GEMM for one to eight rows
One stream's decode (M = 1 + the draft depth) is a pure weight stream; the decode row stages the
weight through LDS and leaves narrow projections at a third to two thirds of DRAM bandwidth. The new
row (priority 58; M <= 8, K % 64, N % 16; the same packed weight bytes as every MXFP4 row) keeps the
weight in registers: WMMA from register fragments when K % 128 == 0, v_dot4 otherwise. The form and
the wave count per block depend on K alone, so a row's output bits do not depend on M (a verify
step's first row equals the plain decode of it). The scale and reference planes must be 4-byte
aligned.

Selftest: every reachable instantiation (both forms, both activation grids, M = 1..8, tile counts
divisible by 4, by 2 only and odd, parts), the output prefilled with NaN, an odd column stride, and
the first row's bits against M for gemv and decode. --perfmx times the MXFP4 rows at one shape.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:09:03 +02:00
John d6957e88a1 sched: skip periodic window snapshots under tip-only
Treat tip-only as a true opt-out from periodic window snapshot creation and interval chunk splits, while retaining the existing tail snapshot and explicit request checkpoints. Leave recurrent-state scheduling unchanged and report the effective chunk bound accurately.

Cover geometric-backoff and keep-all interval behavior, tip-only chunk planning and single-snapshot reservation, aligned and short prompts, explicit checkpoints, and recurrent-state scheduling.
2026-10-24 11:08:38 +02:00
John 192fe10278 sched: checkpoint sliding windows at prefill intervals
Keep intermediate window snapshots as well as the prompt-tail snapshot so a tail edit can resume below its divergence instead of re-prefilling the entire matched prefix. Reuse the existing checkpoint retention policy and preserve the pre-template-divergence tail boundary.

Add scheduler and cache regression tests for interval snapshots, aligned prompt tails, constrained chunk budgets, and edited-prefix lookup. Update the geometry report and guide to describe periodic window snapshots.
2026-10-24 11:08:38 +02:00
gearwave00001 6dad488dbe recipes: how a T2VA-era container upgrades to ref2va
The ref2va heads are the vae/ and audio_vae/ encoders, in every pipeline
directory since the ref2va release -- what a T2VA-era container lacked was the
plugin's declare, not the weights. A reuse with nothing marked changed converts
only the never-declared head weights and copies the rest where they are; the
w8a8 recipe adds that a reuse under it re-quantises the DiT linears on the way,
since a weight copies only at the same encoding.
2026-10-24 00:34:07 -05:00
gearwave00001 1ac980a928 recipes: the DaSiWa curve-form finetune at fp8
minimax-h3-dasiwa-fp8.recipe is minimax-h3-fp8.recipe with the modulation rule
dropped -- the same one-line delta minimax-h3-dasiwa-w8a8.recipe carries for the
int8 line. A curve-form checkpoint reads its ada as K=8 table GEMMs, which no
128x128 block quantiser can serve, so the plugin declares those weights plain
bf16 and the recipe must leave them as the checkpoint holds them.
2026-10-23 19:31:56 -05:00
mici81andClaude Opus 5.5 9322ea0b92 docs: --draft-short-from measured on the card driver against 1.11.0
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-23 12:42:10 +00:00
mici81andClaude Opus 5.5 877e8e44e4 block drafter: the short block on the card's driver
1.11.0 runs a block drafter on the card only (issue_block_drafter). Engine::block_shape chooses the block
and the proposal count a step runs: the drafter's own, or its short block from --draft-short-from
decoding sequences on, off again two below. The card's query pass runs that block, ADV_BTAKE takes that
many proposals from the front of each row at the drafter's pitch, and the step issued ahead verifies
that many (expect_draft and finish_block_drafter read block_steps_). sched_test runs the card driver's
sequence at DFlash2's short block (4 rows, 3 proposals) against the host's reference.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-23 11:26:39 +00:00
mici81andClaude Opus 5.5 7e2d6a205d docs: --draft-short-from (GUIDE 4.6, the flag table) and rad_drafter_short_block (PLUGIN)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-23 11:25:06 +00:00
mici81andClaude Opus 5.5 634e805ce2 block drafter: proposal_pitch documented; arch_test pins with the short block
RadDrafterDecl::proposal_pitch defaults to depth for a block drafter and is refused below it (the
short block fills a row's front). arch_test: the qwen35 family's pins now that DFlash2 declares its
short block.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-23 11:24:45 +00:00
mici81andClaude Opus 5.5 da52bc8593 review fixes of the block drafter's short block (independent review)
- declare_drafter: a block drafter's proposal_pitch, now the row pitch the engine reads row s
  at, defaults to depth (it defaulted to 1, which a pitch-reading engine would take as packed
  rows: wrong drafts from the second sequence and a read past the readback) and is refused
  under depth. The engine's fallback goes.
- run_block_drafter: hysteresis -- the short block goes on at --draft-short-from decoding
  sequences and off only two below, so a load wavering at the threshold does not switch the
  block (a new pass shape, the adaptive estimates) every step. Comment: the proposals are for
  the next step.
- block_begin's comment: after a long block a short one's reservation stops short of the trunk
  step's end; the rejected rows past it land on freed pages with slot -1, which every kv_store
  drops. Named as the load-bearing rule it is.
- The --draft-short-from warning names a serial head as such; the arch_test stub returns the
  real builder's codes.
- build_test: the pitch's default and refusal.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-23 11:24:45 +00:00
mici81andClaude Opus 5.5 90e14c5015 block drafter: a short block chosen per step by load (--draft-short-from N)
A block drafter proposes its block whole, so the block's length is paid for every drafting
sequence whatever each verifies. At one sequence a long block pays: Qwen3.8-27B + DFlash2
(block 8, --draft-window adaptive) decodes one stream 135 -> 155-165 t/s against block 4. At
sixteen it does not: block 8 750-790 t/s, block 4 900, its drafter rows and weaker first
positions costing more than the extra drafts bring. --draft-window adaptive alone cannot help,
since it only shortens what each sequence verifies.

- rad_drafter_short_block(b, block): additive export (RAD_ABI_VERSION unchanged); the plugin
  declares that its query pass also runs at `block` rows a sequence. Builder validates it
  (block drafter, shorter than its own, still proposes).
- --draft-short-from N (default 0 = never): the engine stages the short block once N sequences
  decoded in the step just run (Scheduler::decoded_seqs).
- The engine reads the proposals at the drafter's declared row pitch, not at the step's count:
  dflash_select writes row s at s * pitch, and a short block fills only a row's front (with the
  pitch read as the count, every sequence but the first got the wrong tokens).
- Dflash2: a short block of 4 rows (depth 3) wherever its own is longer: its own convolution and
  selector ops at that block (every other op is per row); the query pass picks by T / n_seq and
  fails the step on a block it has no ops for. qwen35_fp8 and gemma3 declare it.
- Tests: build_test (the declaration's checks), arch_test (the qwen35 family's short query pass
  runs the short ops, a block without ops fails the step; the DFlash2 pin moves), config_test.

Measured (Qwen, speculation 7 adaptive, short block from 4 sequences, against production's
speculation 3 fixed): one stream +15-20 % (kratky) / +9 % (syslog), 4 streams +3 %, 16
streams equal (915 / 906 t/s).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-23 11:24:35 +00:00
mici81andClaude Opus 5.5 4d68a01a08 qwen35_fp8: the GDN state cache at f16 when a deployment asks (RADIANCE_GDN_STATE_F16=1)
libr4d's recurrent update and chunk scan already read the state's width off the cache; the plugin
declared it f32 unconditionally because f16 changes the generated text. A deployment may now trade
that: RADIANCE_GDN_STATE_F16=1 (exactly) declares the cache f16, anything else keeps f32, and the
declare log says so. The default does not change.

Lossy. Qwen3.8-27B (MXFP4, TP2), mean KL against the bf16 reference, f32 -> f16:

- k6_v4 KV: chunk 2048 0.040238 -> 0.040005; chunk 64 (the state stored and rounded every 64
  tokens) 0.039607 -> 0.040468, top-1 94.07 -> 94.00 %;
- fp8 KV: chunk 2048 0.039171 -> 0.039600 (+1.1 %), chunk 64 0.039327 -> 0.039690 (+0.9 %).

It halves the state pool, its host checkpoints and the state's traffic, which grows with the
decoding sequences. Decode on two R9700s, greedy, three rounds (medians, tok/s, f32 -> f16):

- no speculation: 1 stream 67.1 -> 67.5 (+0.6 %), 4 246.8 -> 253.3 (+2.6 %), 16 708.0 -> 779.5
  (+10.1 %); the rounds agree to a tenth;
- speculation 7: 1 stream 222.2 -> 215.1 (-3.2 %), 4 636.9 -> 621.0 (-2.5 %), 16 1223.8 -> 1276.7
  (+4.3 %); f16 also changes which drafts the greedy text accepts, and the text and the step were
  not separated.

So it is for many concurrent sequences where the KL is acceptable. GUIDE §4.4 has the tables.

arch_test: the state group is f32 unset, at "0" and at "yes", f16 at "1".

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-23 11:14:38 +00:00
Deadcode 9eaf10da6e radiance 1.11.0
New models:
- GLM-5.3-Flash reads pictures: its vision tower and processor (--image-tokens sets the budget),
  with decode kernels for a few rows and the DSA indexer split over the ranks
- Sage-A1.5 (fp8 and MXFP4) with its vision tower and a DFlash2 drafter
- Unlimited-OCR (bf16)
- Gemma 4 31B with z-lab's DFlash and RedHatAI's DFlash2 drafters; at four cards its all-reduces
  are fused with the junctions, overlapped with the compute and sent compressed
- Ornith-1.5-35B-A3B w4a8 compose files

Speed:
- Block drafters (DFlash, DFlash2) accept their drafts on the card, and the next step is issued
  ahead
- The four-rank all-reduce is faster for every --tp 4 model
- qwen35_w8a8: the norms and SiLU write the int8 linears' operands directly
- --attn-prefill-fp8 off|qk|pv|both: fp8 QK and PV legs for the h256 prefill attention (about +20%
  prefill on a 221K-token prompt for the 27B MXFP4 at TP2); lossy, off by default

Features:
- Control vectors: --control-vector off|on|disabled (disabled by default), a per-request switch,
  and the published Qwen3.8-Flash-Next refusal-direction vector (its license is in NOTICE)
- Krea 2: the `rebalance` request field, as ComfyUI's ConditioningKrea2Rebalance
- Cards with a small PCI BAR run, with kernel arguments kept in host memory
- Dashboard: live acceptance figures; statsdump rotates its file at a size cap
- KV caches every rank holds whole (GLM-5.3's latent and index caches) take one host-tier slot

Fixes:
- Long conversations taking turns no longer fall back to an early snapshot: a host-tier restore
  makes room as memory pressure does and waits a step for the previous turn's release (two
  conversations of 142K and 147K tokens sent back to back: 31.3 s per turn before, 2.8 s now)
- Kernels before Linux 6.16 (amdgpu below 3.64) no longer hang at startup: virtual memory
  management is turned off there, with a warning
- Gemma 4 dense scales its token embeddings as Hugging Face does (bf16), which changes its output
- The four-rank all-reduce fences prefill-sized messages, for a rare divergence after a fresh start
- GLM-5.3: every refusal names the setting and the reason; its template keeps string content
- Several pictures in one request no longer refuse processors that take one image at a time

Changes: Plugin ABI 26: out-of-tree plugins must be rebuilt. The environment switches the PRs
added are fixed rules or flags now (R4D_ATTN_FP8 is --attn-prefill-fp8).
2026-10-23 11:57:52 +02:00
gearwave00001andClaude a75bdd7fd6 minimaxh3+driver: a one-frame encode cannot exceed the deepest clip buffer, and must be refused for it
The venc_geom cap tested only the pixels volume -- clip * h * w against 17
squares -- but the encoder arena holds five volumes, and the temporal
downsamplers shrink a full clip 17 -> 9 -> 5 while a one-frame clip stays 1:
the deep buffers (5 frames at their side) bind a single frame at
h * w <= 5 * kEncMaxSide^2, a ~572-sided square, not the 17-frame budget.
A 544x736 endpoint keyframe (the workflow-native Flair size) passed the
volume check and then killed the server mid-step: `operand 5 reaches past
buffer 'venc.l3.in': [6256,256] at offset 0, declared [5120,256]`. Check
every volume; the spatial divisor cancels between clip and arena, so the
temporal factors alone decide. 512^2 keyframes, every reference video and
the 256-side pictures all ride exactly as before.

The driver's picture and keyframe branches never asked the encoder at all
(only videos queried rad_arch_encode_geom), so the refusal has to arrive at
accept: probe the geometry for one-frame media and name the size in the
error, instead of a step-time rad_step_fail -- which stops the engine and
takes the server with it.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 21:21:31 -05:00
gearwave00001andClaude 4ca02f18dd minimaxh3: the full-form ada declare must tell rad_fp8 it was pre-mapped
The LoRA-runtime refactor moved DenseFP8::declare's `mapped` from a struct
member to a trailing parameter -- the body now gates its map_linear on the
parameter, and rad_builder refuses a COPY name map declared twice. minimaxh3
kept setting the (now-ignored) member, so every full-form container died at
boot on `name map for 'dit.blk.0.ada0.weight': declared twice`. The ada rows
are mapped by map_rows above for both modulation branches; pass the flag so
declare() reads through that map. Curve-form (adaln_t_table) never reaches
DenseFP8 and kept booting, which is why only the ref2va containers failed.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 21:05:10 -05:00
gearwave00001andClaude 6131e59693 server: drop WebM output; /v1/videos always writes MP4
The reference workflow moved to MP4 as its default and it plays everywhere, so the
webm/webm-av1 containers, the `format` field and the container-aware writer are
maintenance without a user. This reverts them to the pre-webm shape: core/mm/mp4.{h,cpp}
and the Dockerfile/docs are byte-identical to upstream again (the writer's H.264
runtime-discovery and faststart were always upstream's), the ffmpeg build loses
libvpx/libaom/libopus and the webm muxer, and the runtime image loses libvpx9/libaom3/
libopus0. Input-side webm is untouched: media.cpp still demuxes webm/matroska
references, audio endpoints still accept webm uploads, and the decoder set keeps
VP8/VP9/AV1/Opus.

A `format` in a request is now refused as an unknown field.

videos_test drops the WebM case (and the format echo/caps checks), keeps the refusal;
engine_e2e, video_gen and videos suites pass, mm_test unchanged (pre-existing webp gap).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 19:23:33 -05:00
gearwave00001andClaude a1a75da7e9 merge origin/main: the upstream LoRA-runtime refactor beneath the ref2va port
Merges upstream 1.10.0 (152 commits: the LoRA acquire/runtime refactor, the
form-1 LTX-2 scheduler family, guidance terms + negative prompts, decoder
selection, input_reference, new architectures) into the ref2va port branch.
Resolution rule throughout: keep BOTH feature sets; ABI numbering follows
upstream (RAD_ABI_VERSION 26, RAD_FORMAT_VER 2), with the port's video fields
unioned into RadVideoGenBatch/RadVideoGenDecl and abi_layout_table.h
regenerated from the live table.

Notable reconciliations:
  * videos.cpp: the task grammars are disjoint by capability -- keyframe tasks
    (i2va/l2va/flash-attn l2va/fl2va) are recognized only when decl.encodes,
    so upstream models keep refusing them as unknown tasks; input_reference,
    the LoRA tag/field pipeline, and the guidance/negative_prompt rendering
    coexist with refs/ref2va; the prompt put() helper hoisted to block scope
    for the media branch.
  * video_schedule(): upstream's (steps, video_tokens, refine) keeps its
    positional slots; the port's shift_video/shift_audio overrides move to the
    tail so upstream's schedule tests call unchanged.
  * r4d_selftest conv3d cases: the port's sp/st/causal/down/refl geometry and
    upstream's tpad/tpre fold into one reference (ft = causal ? 2 : tpad==2 ?
    2+tpre : 1); rms_mod rows keep the port's i8/fp8 quant modes alongside
    upstream's wadd/norm_once/norm parameters.
  * tests/oot_plugins.sh: the per-plugin cmake --install gains a --prefix
    staging dir -- plugin .so files still land in the absolute
    RAD_PLUGIN_INSTALL_HOME, but libr4d now also installs r4d_selftest to a
    relative bin/, which needs no root.

Host ctest: 112/113 (mm_test's webp gap pre-exists this merge); r4d_selftest,
engine_e2e, oot_plugins, abi_layout, all LoRA tests green.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 18:38:04 -05:00
gearwave00001andClaude dab82de105 docs+tests: mock-user home paths (/home/main), no machine-specific usernames
The parity harnesses already honored COMFYUI_HOME; their defaults, and the docs'
provenance references, now use the mock home. No behavior change: export
COMFYUI_HOME (or pass argv) to point them at a real checkout.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 17:37:14 -05:00
d912c694f3 feat(sampler): port linear MTP coupling and cooperative verify upstream
Port GitHub PRs #12 and #13 onto Codeberg upstream main, retaining upstream kernel-chain handling. Include the source Clang target-attribute fixes required by the host build; omit the KFD header workaround and unrelated fork work.

Co-Authored-By: Claude Code <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 22:58:08 +02:00
gearwave00001andClaude 2477456b36 minimaxh3: the velocity head's modulation table landed where the kernel could not see it
b_nout is declared with row width kMaxSegs*2*D, but the cond pass staged it
through bcol_at with a narrower pitch ARGUMENT (ncell*2*D) and the step pass
indexed row (lane,step) with that same narrow multiplier. The runtime strides a
buffer operand by its DECLARED row width, so every staging row past the first
landed beyond the consumer's window: the shift/scale table the rms_mod head
reads was ALL ZEROS for every denoise step after the first. Step 0 aligned by
coincidence (staging row #0 == the cell starts), which is why step 0 always
reproduced and hid this. The heads -- video and audio alike -- then ran
un-modulated at t>0: rms(h)*w*(1+0)+0, silently dropping a scale field of std
0.295 per step, inflating the velocity (measured 2.90 vs reference-math 2.05 at
step 1) and baking the fried look into every render.

Fix: stage and consume b_nout at its declared width, the pattern b_ada/b_modg
already use (block modulation was never wrong -- only the head table was). No
kernel, arena, or ABI change; the shared host issue path is fixed with it.

Proof chain: the nout shadow re-cast AT THE KERNEL'S OWN POINTER (the old one
sampled the declared pitch and lied -- zero_frac 1.0 at step 1 pre-fix) shows
cells matching emb(t)@W+b to 2e-3, modality-correct; torch replay on the device
stream: step-1 velocity cos 0.970->0.9975, device std 2.901->2.065 vs 2.051
reference math; device renders (512^2 6s seed 1234, flair FL2VA + T2VA control,
workflow prompt) read frame-by-frame: fried look gone on every arm, pins force,
bitrate 6.75MB->1.88MB at identical settings.

Kept (R4D_DIT_SEL-gated): per-step dump tagging dit_s{K}_*, kernel-pointer nout
shadow, tvid/tarr schedule dumps.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 14:16:17 -05:00
mici81andClaude Opus 5.5 e9d03362f0 docs: gemma3's fused all-reduce junctions under a lossy wire (ARCHITECTURES)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-22 18:36:17 +00:00
mici81andClaude Opus 5.5 5a7dac7ce1 gemma3: the fused all-reduce junctions under a lossy wire too, taken by the steps whose message goes out exact
Both junction kernels (ar_rmsnorm_quant_i8, ar_rmsnorm_post_quant_fp8) send the exact wire only, so
they were declared only on the exact wire. Since TranslateGemma moved to --tp-wire wht6 (19. 10.,
prefill +50 %) its decode ran every junction unfused -- all-reduce, post-norm and junction, three
launches for one -- although a decode step of a few rows goes out exact anyway (under
--tp-wire-min-kb). Now they are declared at two ranks whatever the wire and taken per step where
ar_wire_is_exact(T); a wider step keeps the lossy all-reduce, unfused. A fused step is bit for bit
the unfused exact one (the kernels are byte-identical to all_reduce).

arch_test: under a lossy wire an MXFP4 trunks decode step folds its junctions all-reduces, a
prefill chunk above the floor does not.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-22 12:25:08 +00:00
mici81andClaude Opus 5.5 58142a6638 docs: the fp8 and int8 heads past 64 rows
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-22 12:24:16 +00:00
mici81andClaude Opus 5.5 b90723eabe logits_gemm_fp8: 65..128 rows in one pass, the head read once
lm_wmma_kernel held at most four 16-row tiles a wave, so past 64 rows the launcher made passes of 64
and read the fp8 head again for each. With MH = 2 the workgroup's eight waves split into two M halves
of four tiles over 64 weight rows that share one staged tile: Qwen3.8's per-rank head (124160 x 5120)
at 128 rows 3059 -> 1984 us, TranslateGemma's 3242 -> 2036 us; 65..128 rows -33..-39 %, 160..256
-26..-37 %, 64 and fewer unchanged. Same scale blocks, WMMAs and K order per output: the same bytes.
r4d_selftest: the heads' numeric cases at 65..150 rows, --perf times the head up to 256 rows, and
R4D_PERF_ONLY=<row> times one row alone.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-22 12:23:58 +00:00
mici81andClaude Opus 5.5 824e238996 MXFP4 tiled GEMM: review fixes, tests and docs
Carried from the series' review rounds when it was split: numeric cases for the plain kernel at a
whole row of blocks (TN=4 forced and by the rule from 1024 rows, TN=2 at the 64-wide slab), the
plain kernel's comment, and libr4d/README.md's account of the row with the measurements behind
TN=4 from 1024 rows, the slab-ahead weight load and the thin last row.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-22 12:23:51 +00:00
mici81andClaude Opus 5.5 6249462bfa gemm_mxfp4a8_tiled: a thin last row of blocks skips its padding WMMAs, in a kernel of its own
The block is 256 rows at every M, so a block the M edge cuts ran its padding rows' WMMAs on clamped
copies of the last fragment (half the only block's math at 129 rows). M whose last row holds 1..160
rows (under 1024 in all) now runs a two-body kernel whose blocks of that row skip the WMMAs of their
fragments past M: same-session A/B over 12 shapes, M 129..160 -8..-20 %, 320..384 -2..-16 % (Qwen
gate_up at 320 rows 402 -> 339 us, TranslateGemma's 513 -> 441). Every other M runs the plain kernel,
whose body declares its own LDS, so its ISA is the old kernel's instruction for instruction: guarding
inside the one kernel cost full blocks 1..15 %, handing the body the LDS by pointer 2..8 %. Per output
byte the fold, the WMMAs and their order are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-22 12:23:13 +00:00
mici81andClaude Opus 5.5 a85f87ea2f gemm_mxfp4a8_tiled: the weight loaded a slab ahead
Each slab used to load its weight words and exponents, wait for them, unpack them to LDS and only
then compute, so a DRAM round trip stood in front of every slab's unpack. The words a thread stages
are now loaded into registers right after the staging barrier, a slab ahead, and fly across the
slab's WMMAs (+1 VGPR at TN=4, no spills). Same fold, same WMMA order: bit for bit.

r4d_selftest --perfmx, warmed, at 1024 rows (a pipelined prefill's piece): Qwen3.8 gate_up
804 -> 768 us, down 443 -> 417, ssm_in 396 -> 384, ssm_out 249 -> 231, attention q|gate
306 -> 318; TranslateGemma gate_up 1063 -> 1029, down 651 -> 617; at 2048 rows 0..-4 %. Loading the
A fragments a slab ahead too (+38 VGPRs) was slower everywhere. End to end (three alternating
rounds against the production image): Qwen 41k prefill 8.57 -> 8.28 s (-3.4 %); TranslateGemma 6k
and 12k unchanged at 0.1 s; KL 0.040237.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-22 12:23:13 +00:00
mici81andClaude Opus 5.5 168a26a6b8 gemm_mxfp4a8_tiled: TN=4 from M >= 1024
TN=4 wins from 1024 rows on (r4d_selftest --perfmx, a rank's weights: Qwen3.8 gate_up
17408x5120 1105.6 -> 1080.8 us, down 5120x8704 618.5 -> 599.1, TranslateGemma gate_up
21504x5376 1395.0 -> 1273.8, its down 5376x10752 793.6 -> 799.6; 1536 rows better on all four;
512 and 768 mixed). It matters to the pipelined prefill's 1024-row pieces and to TranslateGemma's
1024-row chunks. Same bytes: Qwen's KL recording and TranslateGemma's KL (0.054628) unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-22 12:23:13 +00:00
Nunze 3aded1bbf8 server: DELETE /sessions forgets one stored conversation
A client that deleted a conversation, or compacted it past a prefix, knows the
rest is dead before --prefix-cache-ttl does. DELETE /sessions/<label> (or
?label=, ?id=<engine id>) walks the session's chain from the tip inwards like
expiry: VRAM blocks to the pool, the host copy with them, the session's
snapshots to the store. ?keep_tokens=N keeps the chain's start in whole blocks.
Blocks another stored session shares (the system prompt) and blocks a live
request reads stay and are counted apart; the row is cut at the deepest block
that stayed, so a later release reaches it. A request of the same conversation
in flight is 409. IScheduler::release_session beside reset_prefix_cache,
PrefixCache::release_session over the tiers' session table (find_sessions,
shared_prefix_blocks, cut_session). Counters released{entries,snapshots} on
/sessions and /stats, prefix_cache_released_total{what} on /metrics.
2026-10-22 09:58:08 +00:00
NunzeandClaude Opus 5.5 d90e19dc15 r4d_emu: the MLA row form against the head form, element by element
Three host checks of where GLM's MLA split by rows can part from the split by heads:
- the f32-scale E4M3 GEMM gives a run of rows and a slice of columns the whole product's bytes
  there, so q_b and o at full width over a rank's rows match the head form's slices;
- a TP8 step of 300 rows: each rank's run, placed as the all_gather places it (rank r's 38 rows
  at r * 38, the last 34), lands on its rows;
- row by row on a prefill chunk past the DSA budget, bit for bit against the paired union tile:
  the 16-head tile gives the union's first rows exactly and differs from its second rows in
  about 0.1 % of their outputs by one bf16 step; the rows kernel differs in about 0.1 % of every
  row's outputs, by the same step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:58:07 +00:00
NunzeandClaude Opus 5.5 eb14e4f642 glm5next: the MLA row form, opt-in with RADIANCE_GLM_MLA_ROWS=1 -- a prefill-sized step by rows over the ranks, each rank with all 64 heads
From GlmTp::kSplitRows each rank runs its run of the step's rows (GlmTp::run_of: ceil(T / world)
rows, the last run shorter) through q_b, absorption, attention with all 64 heads
(mla_attn_rows_bf16), expansion and o, and an all_gather of whole runs takes the all-reduce's
place. The latent cache and the DSA selection are whole on every rank, so nothing is exchanged
before the attention; each rank sends its run to seven peers, half the bytes of the two-shot
all-reduce, through the same exchange instance. In a 4096-row chunk at 16k of context a rank's
attention drops from 14.0 to 3.9 ms a layer on the kernel bench. The price is q_b, kv_b and o at
full width on every rank: 120 MiB a layer, 1.29 GiB a card over the 11 trunk layers, and about
0.1 GiB of activations; the MTP layer keeps its heads. The full-width weights are whole views
(RadWeightDecl::source) of blk.N.attn_q_b, attn_kv_b and attn_output, the head form's container
entries, so they take the stored encoding (fp8a8f32, bf16) and need no name map; LinearFP8 gets
`stored` for that, served by its block-fp8 branch only, and LinearFP8::step writes a run of rows
from a given output row.

The head form stays the default, unset or RADIANCE_GLM_MLA_ROWS=0, and declares none of it: that
graph is the one before this change, byte for byte (the pinned hashes). The row form is not
bit-identical to the head form, and GLM-5.3 turns that into a measurable divergence: over a
43k-position KL corpus at TP8 (English prose, German prose, code) the row form scores a mean KL
of 0.033 against the head form (median 0.004, top-1 agreement 93.5 %), with greedy text
unchanged. The projections are not the cause: q_b and o over a rank's rows give the head form's
bytes (r4d_emu), and o summed as eight rank partials in the all-reduce's order
(RADIANCE_GLM_MLA_ROWS=2, a test form, GlmMla::Form::rows_sliced_o) scores 0.032. The
attention's rounding is: the rows kernel parts from the paired union tile in about 0.1 % of
every row's outputs by one bf16 step (the union pairing sums a pair's second row in another
order), and the 16-head tile, which parts in the same share of every second row only, halves the
KL to 0.015. A bit-identical row form would run the union tile eight times a row over its own
group of eight heads, without this kernel's gain, or need a rows kernel with the union's
arithmetic; neither is here, so the form is opt-in.

Measured on eight R9700 at Gen5 links, the same build: a 20k-token prefill 5074 tok/s in the row
form against 4270 in the head form, BetterBench prefill at 22k 4984 against 4151, single stream
181.8 against 180.2 tok/s, eight streams 468 against 454.

glm5next_test declares the block at one to eight ranks and checks the full-width views and their
sources, the fp8a8f32 GEMMs, the gather's bound against the all-reduce's, each rank's operands
at 300 rows (runs of 38, the last 34 at eight ranks) and the head form at 255; the o-slices
form's eight GEMMs and seven adds; the model's counts and the TP8 pin under
RADIANCE_GLM_MLA_ROWS=1 (0x1d378152c40f8834 / 0x82ed1094dbf4b637), with the default pins
unchanged; and the row rule against both formulas it replaced. plugin_test resolves every band
of every op the row form adds at eight ranks against libr4d, with no card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-22 09:58:07 +00:00
NunzeandClaude Opus 5.5 7d7c66da55 arch/common: LinearFP8::step writes a run of rows from a given output row
An optional `y0`: rows [r0, r0 + rows) of the input land at row y0 of the output instead of at
row r0, so a rank's run of a step's rows can go to a buffer sized for the run. Unset, every
branch issues what it did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:58:07 +00:00
NunzeandClaude Opus 5.5 87701cb6b8 libr4d: mla_attn_rows_bf16 -- one key load for all 64 heads of a query row
A third mla_attn row, at 64 heads. A workgroup takes one query row and all its heads, four waves
to each group of sixteen, and loads each 16-token key chunk once for all of them, where the
matrix row loads it once a tile of sixteen. The scores are K Q^T, tokens as the tile's rows and
heads as its columns, so a head's running maximum and denominator stay in its lane; the waves of
a group each take a quarter of the latent's dot products and add the four partials in one order,
and the probabilities reach the value product through a permlanex16 swap instead of LDS. The
next chunk's keys are fetched into registers while the current one is multiplied, two barriers a
chunk. A row's bytes do not depend on the other rows of the batch. Under 32 rows the launcher
runs the matrix row's kernel; r4d_mla_rows_pin_form, a test hook, pins the element-wise key load,
32 heads a workgroup, the rows kernel at any row count, or the matrix row's kernel at every row
count (the form a KL measurement needs to tell this kernel's share of a row split's difference).

Measured on gfx1201 (r4d_selftest --perfmla, one sequence past the DSA budget at 16k of
context, 513 blocks): 512 rows x 64 heads take 3.9 ms, 35 TFLOP/s, against 12.3 ms on the
matrix row, and the 4096 rows x 8 heads they stand for in a TP8 prefill chunk 14.0 ms on the
paired union tile. Against the wave row the output stays within the matrix row's tolerance
(max abs 2.4e-4 at 513 blocks).

r4d_selftest checks it against libref at 1 to 33 rows, 32 and 64 heads, every fill and both key
loads, and times it against the matrix row (--case mla_attn_rows_bf16, --perfmla at 64 heads).
r4d_emu_mla runs it on the host against an f64 softmax, its forms bit for bit against each
other, a run of rows against the same rows of the whole batch, and a mixed TP step (decodes, a
verify window, a prefill past the budget, a fresh chunk) split by heads over the matrix row and
by rows over this one, at runs that do and do not divide the step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:58:07 +00:00
AlexandClaude Opus 5.5 123c439684 krea2: rebalance, the text taps at ConditioningKrea2Rebalance's gains
A request may ask for Krea 2's twelve text taps to be multiplied by fixed gains
before the text fusion, as ComfyUI's ConditioningKrea2Rebalance (nova452) does at
its defaults: multiplier 4 times the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5,
5, 1.1, 4, 1. `rebalance: true` on /v1/images/generations (JSON or form) sets
RAD_GEN_COND_REBALANCE in RadGenBatch::cond_opts, appended in ABI 26; the plugin
then scales each tapped layer's rows into te.h2 with chan_affine (f32, rounded
once) and scatters those instead of te.x, so the residual stream is untouched.
Without the field every pass issues exactly what it did before; other models
ignore it.

The gains cannot be folded into weights: the taps enter the fusion's layer-wise
blocks raw, through a pre-norm residual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:55:38 +02:00
NunzeandClaude Fable 5.1 7aa51e5b4a libr4d: r4d_selftest folds the exact all-reduces' oracle from inputs whose sum depends on the order -- the old pattern passed any order
The eight-rank two-shot claims the same bits whatever the shard weights and piece count: a word is
reduced by one thread of its owner, acc = 0.0f, then src[0..7] added in ascending rank order in
fp32 and rounded once (reduce2 in r4d_ar_twoshot_Nrank_exact.hip), the one-shot's ar_vsum fold;
weights move only which rank owns a word, pieces only which step reduces it, and every form
(lockstep, ring, split) keeps both. The selftest's check of that claim was blind, though:
ar_pattern_value is k / 64 with |k| <= 254, and eight such values sum exactly in fp32 in any
order, so a kernel folding in another order, or twice-rounding a partial sum, passed.

ar_rough_value gives bf16 values (8 significant bits) whose exponents span 2^-12 to 2^12, so
partial sums round and the order shows: of 20000 elements, 547 fp32 sums differ between
ascending order and rank 3 first. The exact wide rows' pattern runs (ar_wide_pattern, the
weighted eight-rank runs over weights, pieces and forms) and --perfar8 now fold their oracle
from it, ascending from 0.0f, and must match it bit for bit; the lossy and fused cases keep
ar_pattern_value, whose bounds assume its range.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-22 11:54:56 +02:00
NunzeandClaude Fable 5.1 c25bca83d5 libr4d: RADIANCE_AR8_FORM -- the eight-rank two-shot's steps in ring order, or with a flag after each half instead of a handshake a step
The eight-rank two-shot reaches 56% of its link time at 16 MiB (1316 to 1340 us against 763), and
measured(K) = f x link time(K) + h x (K + 1) fits f of about 1.45 and h of about 20 us a step:
both the transfers and the step boundaries lose time. Two schedules of the same work go after
them, each a new form beside the existing one, chosen by RADIANCE_AR8_FORM (unset or lockstep:
as before) or per launch by the `form` parameter:

- ring: the first hop goes to the peers in ring order from rank + 1 instead of ascending. In the
  lockstep order every card but rank 0 starts by writing rank 0's shard, then rank 1's, so the
  seven senders can converge on one receiver while the other links idle; in ring order each card
  receives from one peer at a time.
- split: ring, and the one handshake a step, which waits until every peer has finished the
  whole step (next piece's first hop, this piece's reduce, the previous piece's assemble), becomes
  a flag after each half, awaited only before its data is read: before reducing piece j the
  peers' first hop of j, before assembling j their reduce of j. A card whose half is done goes on
  with the next piece's first hop while a slower card still reduces, so each link runs at its own
  pace instead of the slowest card's per step. The flags stay one monotone word per (block,
  source): the first hop of piece 0 at v0, of piece j + 1 at v0 + 2j + 1, the reduce of piece j
  at v0 + 2j + 2; the launch reserves pieces + 1 steps for its 2 pieces + 1 values, so it mixes
  with every other kernel on the instance. A launch still ends only after every peer has
  published its last reduce inside it, so the slot parity argument holds unchanged.
  r4d_ar_publish and r4d_ar_await (r4d_ar_wide.h) are the two halves of r4d_ar_handshake.

Neither changes which rank folds a word or in what order, so all forms give the bits of the
lockstep form, which compiles to the code it was. Ring and split are eight-rank only; the
three- and four-rank launches stay lockstep and refuse another form. Every rank must read the
same form; init compares it with the other eight-rank settings.

--perfar8 numel iters dtype forms (comma-separated) times the forms side by side; the timeline
prints a pair a synchronisation (K + 1 handshakes, or 2K awaits split, up to 8 pieces).
r4d_selftest's weighted eight-rank runs repeat for ring and split at 1, 4 and 8 pieces over even,
uneven, single-owner and zero-weight tables and with the piece count changing launch to launch,
and the box's own weights run auto, duplex and off. On one card (R4D_SELFTEST_ONE_CARD) all three
forms give the fold on every rank at 65536 to 8388608 elements, even and weighted, bf16 and fp32.
Which form is fastest on the board is for the TP8 window to measure.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-22 11:54:56 +02:00
NunzeandClaude Fable 5.1 5b9bc13e5f libr4d: RADIANCE_AR8_SHARD_WEIGHTS=duplex -- shard weights from the both-directions link model, 8 to 1 instead of 4 to 1
The eight-rank two-shot in pieces runs both hops on a link at once, so each direction of rank r's
link carries (1 + 6 x_r) N for a shard fraction x_r: N - x_r N out in the reduce-scatter and
7 x_r N out in the all-gather, the same in. The slowest rank sets the time. The quadratic rule
(round(4 (rate / max)^2)) gives four Gen5 x16 and four Gen5 x8 cards 4 and 1: x8 carries 1.3 N at
28.6 GB/s (763 us for 16 MiB) while x16 carries 2.2 N at 57.1 (647 us), so the x16 links idle
15% of the time.

r4d_ar_weights_duplex equalises the ranks instead: x_r = (T B_r - 1) / 6 where positive, the x
summing to 1, filled from the fastest rank down. On that board it gives x16 2/9 and x8 1/36,
weights 64 and 8, and both kinds of card carry the same time's bytes: 7/6 N / 28.6 GB/s, 685 us
for 16 MiB, 10% under the quadratic rule's 763. On the earlier board with two Gen4 x8 links it
gives 64,9,0,64,0,9,64,64: the Gen4 cards nothing, as the measured best 4,1,0,4,0,1,4,4 did, the
Gen5 x8 ones half of what it gave them.

It is a new value of the variable, not a new default: unset and "auto" keep the quadratic rule,
so nothing runs differently until a measurement on the board says so. Which rank owns a word
changes only the link it crosses, not its fold, so the bits are those of every other table.
--perfar8 reads the variable the same way. r4d_ar_links_test checks both boards, equal links and
that every rank with a shard finishes together.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-22 11:54:56 +02:00
NunzeandClaude Fable 5.1 91200c900b libr4d: the eight-rank two-shot's timeline -- where a 16 MiB all-reduce spends 1.36 ms against 0.76 ms of link time
At 4 x Gen5 x16 + 4 x Gen5 x8 the weighted two-shot moves a 16 MiB message in 1316 to 1340 us
(K4 to K8, --perfar8), against 763 us that the x8 cards' links need for its bytes, and
measured(K) = f x link time(K) + h x (K + 1) fits f of about 1.45 and h of about 20 us a
handshake. Whether that is link efficiency, waiting for the slowest rank, the local reduce or the
step boundaries cannot be told from the period alone.

A launch now takes an optional `timeline` parameter, a device buffer of nblocks x
R4D_AR_TL_WORDS int64 (r4d_ar_shards.h). Every block of the eight-rank two-shot stamps the device
wall clock after its sequence step, at each handshake when all its stores have drained (arrive)
and when every peer's flag has been seen (release), and after its last local work. The stamps sit
in r4d_ar_handshake behind a null check, so a launch without the parameter pays a branch per
handshake; no value changes either way.

r4d_selftest --perfar8 --timeline launches each two-shot point once more with the stamps on and
prints, per rank, the first push, every step's work and wait, and the final assemble. In one piece
that is the reduce-scatter's send, its receipt, the reduce with the all-gather's send, its receipt
and the local assemble, so the two hops are measured apart; in K pieces it shows which rank works
while the others wait.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-22 11:54:56 +02:00
NunzeandClaude Fable 5.1 b34af6c509 libr4d: eight ranks on one card for r4d_selftest -- the eight-rank protocol testable on a box with fewer cards
The eight-rank collectives could only run on eight cards, so a change to their protocol, shard
table or arithmetic went untested until a TP8 window. Their bits do not need eight cards: a peer
on the same card is just another region of its VRAM.

build() now skips hipDeviceEnablePeerAccess for a peer on the rank's own card (the runtime refuses
it, and nothing needs it). On distinct cards nothing changes.

R4D_SELFTEST_ONE_CARD=1 lets --perfar8 run its eight ranks on the first card: each rank takes a
non-blocking stream of its own (one stream would serialise ranks that spin on each other), main()
raises GPU_MAX_HW_QUEUES to 16 before the runtime starts so the streams get queues of their own,
the block counts stay at 4 and 8 so all eight ranks' blocks are resident at once, and the workers
meet at a barrier before fini and the frees, which synchronise the card. With a card a rank the
worker keeps the legacy stream, so the timed launches are as before. On one card the results are
checked against the fold exactly as on eight; the times are not a board's, since the card runs
the eight queues in time slices of several milliseconds, and the run says so.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-22 11:54:56 +02:00
NunzeandClaude Fable 5.1 4f821ce0b9 glm5next: the latent and index caches are declared replicated -- the host tier holds each once a slot
Every rank computes the whole normed latent (kv_store over the replicated kv_a) and pools
into the whole index cache, in the head form and the row form alike, so both cached groups
carry rad_kv_group_replicated. At eight ranks a 4-token block costs 49.59 KiB a slot
(kv_latent 48.00 KiB over its 12 layers, kv_dsa_index 1.59 KiB) rather than 396.75 KiB,
12.4 KiB a token rather than 99.2 KiB: --prefix-cache-mib 32768 holds 2.7M tokens rather
than 338K.

glm5next_test pins the two flags at 1, 2 and 8 ranks; the flag is outside the recording
fake's graph hash, so the pinned graphs and steps stand.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-22 09:08:44 +00:00
NunzeandClaude Fable 5.1 66a1d5aa15 kv tiers: rad_kv_group_replicated -- a group every rank holds whole is kept once a host slot
Under tensor parallelism a host slot held every rank's shard of an entry end to end, so a
group every rank holds whole (an MLA latent cache computed from a replicated projection) was
stored once a rank: on GLM-5.3-Flash at eight ranks 396.75 KiB a 4-token block for 49.59 KiB
of distinct bytes. The plugin now says which paged groups are replicated (additive export,
RAD_ABI_VERSION does not move), and the slot holds those once, in one window at its front
that rank 0 writes and every rank reads back on a restore; the sharded groups follow, one
window a rank, as before. Without the declaration nothing changes.

TierExec::slot_layout is the one place the slot arithmetic lives: bringup takes the windows
from it, and it refuses a group replicated on one rank but zero, unflagged or another width
on another. A follower moves only its own window on a copy out (nothing, when every cached
group is replicated) and both windows on a restore. The startup log names what is held once
and the tokens the tier holds either way.

RADIANCE_DEBUG_TIER_VERIFY now covers the claim: each follower gathers the replicated groups
into a pinned scratch beside the copy and hashes them once landed, and the engine, once every
rank has landed, has the leader compare its window with every follower's sum.

mem_test moves a chain through the real TierExec with a replicated and a sharded group at 1,
2 and 8 ranks, the ranks' copies differing on purpose, and checks every rank gets the leader's
bytes back; beside a zero group; the verify path alike and differing; and the layout's refusal.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-22 09:08:44 +00:00
Juup 17d004d0d0 data/recipes, deploy: Sage-A1.5 MXFP4 with DFlash2
The trunk linears, the routed and shared experts, and the DFlash2 linears
round to OCP-MXFP4 (fp4_e2m1, one e8m0 scale per 32 of K); output.weight
stays block FP8 and the draft head its 2-bit copy. 19.52 GiB against the
block-FP8 sibling's 34.45, served at 25.8 GiB of VRAM a card on tp2.
2026-10-22 11:07:23 +02:00
Juup ef219c2192 arch, data/recipes, deploy: Sage-A1.5's routed trunk with its vision tower, and DFlash2 in place of the MTP head
Sage-A1.5 (InternScience) is Qwen3.5-MoE's routed trunk with the Qwen3.5 vision tower beside it -- a shape qwen35moe_fp8 already declares, but no fixture covered the two together: the MoE fixture had no tower, the VL fixture was dense. arch_test gains q35moe_vl_meta, and checks the tower declares once for the build (not a copy a rank), that it is withheld when no encoder budget is given, and that the routed blocks, the folded shared expert and the MTP layer's own router are still declared beside it.

sage-a1.5-fp8.recipe puts every trunk linear -- attention, the delta net's in- and out-projections, the routed and shared experts of all 40 blocks, and the MTP layer at index 40 -- into block fp8, the head likewise, and keeps the routers, the shared-expert gates, the delta net's parameters, the norms, the embedding and the whole vision tower as the checkpoint ships them. recipe_test reads the shipped file and asserts all of that.

sage-a1.5-fp8-df2.recipe is the same trunk with incoai/Qwen3.6-35B-A3B-DFlash2's tensors in place of the MTP head, which the shared source declares through declare_dflash2. On two R9700s it decodes 392.9 tok/s against 281.6 with the MTP head, at 49.3% acceptance and depth 7; on one card, 231.6 against 168.3.

Compose: sage-a1.5.yaml (two cards, four 32k sessions), sage-a1.5-tp1.yaml (one card, an 8 GiB pinned host pool, one 262,144-token session) and sage-a1.5-df2.yaml. README, DOCKER.md and ARCHITECTURES.md list the containers and the drafter.
2026-10-22 11:07:23 +02:00
NunzeandClaude Opus 5.5 c4a47673f2 docs: GLM-5.3's vision -- the tower, its processor and traps, converting, serving
ARCHITECTURES.md's glm5next section describes the tower, the processor's budget against the
encoder pass, and the readings that are wrong without an error (the downsample's column order, the
rotary's pairing, no rotary in the language model, the draft head's image rows), with what the
tower measured against transformers. GUIDE.md, spec.md §11, PLUGIN.md, the README and the compose
file say GLM-5.3 takes pictures and how a container gains the tower.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:06:34 +02:00
NunzeandClaude Opus 5.5 1f7e1faa73 tests: GLM-5.3's template renders a picture as the reference does; its tower against transformers
The golden renders gain GLM-5.3's picture between text: the engine's media marker becomes
<|begin_of_image|><|image|><|end_of_image|> with no separator, as the template's own emit_image()
writes it (tests/mkchatgolden.py).

tests/glm5_vision_reference.py runs transformers' tower alone on the CPU (only model.visual.*,
about 3 GB) over the pictures of one encoder pass and writes the processor's patches and the
merger's rows, with --taps the tensors on the way (the patch embedding, block 0's q and k after the
rotary, blocks 0, 11 and 23, the post-norm, the downsample), in bf16 or f32. With --compare it
checks what an engine wrote with RADIANCE_DEBUG_MM_DUMP: patches bit for bit, rows to a cosine of
0.99 and a median per-row relative error of 0.08 against the bf16 reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:06:34 +02:00
NunzeandClaude Opus 5.5 2387a23e00 glm5next: pictures -- the tower last, its rows over the trunk's and the draft head's embeddings
With the container's tower and an encoder budget (--mm-max-patches), glm5next declares
rad_block_glm_vision.h's tower after every text and draft op, its weight groups from 46, past the
MTP layer's; an encoder pass issues only the tower. The encoder's rows overwrite the placeholders'
embeddings before the vocab-sharded lookup's reduction (MediaRows), in the trunk and in the draft
head's own lookup (GlmMtp::declare_inputs with `media`), which is what SGLang feeds its draft
model: without them the drafts read the placeholder's embedding and acceptance falls on a prompt
with a picture. The model has no rotary, so nothing else changes in a step. The probe states the
tower's merged block (enc_merge 4).

glm5next_test: the tower only with an encoder budget, at one and eight ranks, its maps, groups,
rotary, unfold and clips; the refusals; an encoder pass issues the tower and nothing else over
two pictures; a prefill with a picture scatters its rows before the all-reduce in the trunk and
in the draft head's history pass, a text step none; a sizing declare with the tower is the real
graph. The operand-count and container cases run on the container with the tower. The pinned
text graph and steps are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-22 11:06:34 +02:00
NunzeandClaude Opus 5.5 b8885461ee arch/common: GLM-5.3's vision tower -- an axial rotary, a 2 x 2 downsample through conv2d_unfold
rad_block_glm_vision.h, transformers' Glm5NextVisionModel: the Conv3d patch embedding as a biased
linear with no position table; 24 pre-norm blocks of RMSNorm, a biased qkv whose q and k are
RMS-normed per head and turned by a 2-D rotary (qk_norm_rope's axial mode, the row on the first
quarter of the frequencies and the column on the second, NeoX pairs across the whole head),
attention within a picture, and a SwiGLU clipped at swiglu_limit (gate above, up both ways, with
gate and up joined into one GEMM); post_layernorm; the 2 x 2 stride-2 downsample; the merger's
bias-free projection, LayerNorm, exact GELU and clipped SwiGLU.

The downsample needs no new op and no weight permutation: the processor stages patches in
merge-block order, so conv2d_unfold (two input rows of two patches a block) writes each merged
block as one row in the checkpoint weight's own (channel, kernel row, kernel column) order, and
the [4096, 1024, 2, 2] weight is read as a [4096, 4096] linear as stored. Every op has rows in
libref, libavx and libr4d.

Weights are replicated and RAD_ACCESS_PER_REQUEST, a group a block, as rad_block_vit.h's are; a
sizing declare sizes the activations at the probe's rows and declares nothing to the core. A
tower with another activation, rotary, no swiglu_limit, no attention bias or rows of another
width than the model's is refused by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:06:34 +02:00
NunzeandClaude Opus 5.5 b0bcb74c5b core/mm: GLM-5.3's processor -- a canvas within a token budget, padded rather than stretched
A fourth processor family beside Qwen-VL, Gemma 4 and LFM2-VL, chosen by vision_config.model_type
glm5_next_vision, as transformers' Glm5NextImageProcessor (torchvision backend) computes it:

- The canvas: both sides rounded up to patch * merge (28), grown by the area ratio under
  min_image_tokens, and fitted by the reference's binary search over the picture's height past
  max_image_tokens, a token being two frames of 28 x 28 pixels.
- The picture keeps its aspect ratio, is never enlarged while it reaches the floor, is resized
  with torchvision's fixed-point bicubic only when its size changes, and sits in the top left of a
  canvas of zero bytes, which the normalisation turns into each channel's -mean / std as it does
  the reference's padding. Patches as Qwen-VL's (merge-block order, (channel, frame, y, x), the
  picture in both frames, CLIP's mean and deviation from processor_config.json).
- <|begin_of_image|>, one <|image|> a token, <|end_of_image|>; the tokens rotate at their
  positions (the language model has no rotary). Pictures only.

The budget is in tokens and comes from processor.image_processor.{min,max}_image_tokens; one
encoder pass bounds it, so it is lowered to max_patches / merge^2, as a Qwen-VL pixel band is
(4096 tokens at --mm-max-patches auto, the checkpoint's 8000 at 32000). --image-tokens sets the
ceiling; the pixel-band and video flags, a request's image_tokens and a video are refused by name.

tests/mkglm5golden.py writes glm5_golden.h from Glm5NextProcessor; mm_test checks canvases over a
grid of sizes and both budgets, and whole pictures (padded only, grown under the floor, shrunk to
a budget) patch for patch and token for token, all bit-exact, and the processor read from a
container's keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:06:34 +02:00
gearwave00001andClaude f7cc1b3a3b minimaxh3 convert: restore the SwiGLU gate-half swap — cont.25's identity maps rendered tile-scrambled garbage
77ef8f0 flipped the three ff.net.0.proj map_rows sites (dit/refiner ffn_gate_up,
vae ffn_up + bias) to identity because the container bytes were "gate-second"
against a gate-first CPU reference. That reference was circular: it read
CONTAINER rows through comfy's gate-first `_swiglu_eager`, so it agrees with
whichever order the container carries. The checkpoint's own library settles it:
ff.net.0.proj is diffusers' SwiGLU (diffusers/models/activations.py,
`hidden, gate = proj(x).chunk(2,-1); hidden * silu(gate)`) — VALUE first, gate
second — transformer AND VAE (autoencoder_kl_minimax_h3 builds its FFNs from
the same FeedForward). `silu_mul`/`gated_quant_fp8` gate with the FIRST half,
so the convert must swap. The swap was load-bearing.

Device evidence (task #64): every render of the identity-map container
(minimax-h3-dasiwa-w8a8-gatefix.rad) — including the pinned FL2VA frame-0 — was
a full-frame grid of ~16px tile-scrambled colour squares, while the original
swapped container on the SAME binary renders coherent video with both pins
forced (cmp45/FINAL_t2va512.mp4, FINAL_fl2va512.mp4; frames read by eye).
Aggregate metrics (luma 81, clipHi 0.1%) were perfectly normal on the
scrambled output — only vision caught it, and the cont.25 "device-verified"
claim was metrics-only.

Reverted maps verified by byte round-trip: rad-convert with the restored
recipe and --reuse minimax-h3-dasiwa-w8a8.rad writes 3273/3273 tensors
byte-identical to it. Kept: the R4D_DIT_SEL-gated decoder shadows + driver
readback, the trailing-optional operand arity fix (43a6768), and the ABI-24
table regen (3f0f4ef) — all still valid. minimax-h3-dasiwa-w8a8-gatefix.rad
stays only as the documented bad artifact; the good container remains
minimax-h3-dasiwa-w8a8.rad. The fried look itself stays OPEN: the restored
renders are coherent but still over-bright vs the reference. Docs cont.26
supersedes cont.25.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 02:07:23 -05:00
gearwave00001andClaude c2e4dea468 docs cont.25: #63 CLOSED — the fried look was a SwiGLU gate-half swap baked into the container
Root cause, byte proof, reconvert recipe, device A/B (clipHi 37.8->0.1%), the final
velocity parity (cos 0.9886 / std ratio 1.071 supersedes cont.24's block table), and
the two pre-existing red tests fixed on the way (timestep_embed arity since e28cf86;
the ABI layout snapshot since 9d67df3).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 00:57:50 -05:00
gearwave00001andClaude 5fb9dc92ad tests: regenerate abi_layout_table.h at ABI 24; complete abi_layout_rows.h
abi_layout_test has been red since 9d67df3 bumped RAD_ABI_VERSION to 24 without
regenerating the snapshot, and the row file never listed Batch.sampler or any of the
trailing debug fields (dbg_ve_*, dbg_dit_*, dbg_vd_* — 61 rows missing from the
snapshot). Verified purely additive: no previously-listed field moved or changed size,
both growths are fields past the old struct ends. kTableAbi 24.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 00:57:42 -05:00
gearwave00001andClaude 80b13b49d8 runtime: an issue may omit trailing optional operands
e28cf86 made timestep_embed's curve `table` an optional WEIGHT operand but left the
arity check demanding exact equality with the schema, so every sinusoidal issuer —
qwenimage21, minimaxh3's full-form path — died at step 0: engine_e2e_test has been red
since that commit. The check now accepts a count at or above the last REQUIRED operand
and nulls the dropped schema slots, which is what rad_abi.h promises ("an absent
optional operand is a null RadTensor.data") and what every shim already branches on
(r4d_opt(), rad_args_have(), libref's finish(); the curve kernel still requires the
table when curve > 0). Only TRAILING optionals: an omitted optional before a required
operand would shift positions, which is the miscount the check exists to catch.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 00:57:42 -05:00
gearwave00001andClaude d480a47bef vae/dit/refiner FFN: store the SwiGLU gate half FIRST — the container's row swap was the fried look
Three map_rows sites reordered ff.net.0.proj rows so the gate landed SECOND, while
silu_mul / gated_quant_fp8 gate with the FIRST half (comfy's _swiglu_eager — the
reference that produced the ground-truth clips — chunks gate-first). Every DiT,
refiner and video-VAE-decoder FFN therefore computed silu(up)*gate instead of
silu(gate)*up: the block-0 device internals dump measured the FFN down-projection at
cos 0.49 against the reference while attn/to_out sat at the bf16 floor, and renders
came out over-bright with 37.8% of pixels clipping high. The maps are now identity
(checkpoint order) at all three sites; quant scales follow because they are computed
from the mapped rows. TE blocks were never affected (separate gate/up concat,
already gate-first).

Reconverted with --reuse (707 tensors / 803 weights): minimax-h3-dasiwa-w8a8-gatefix.rad.
Byte check flips in every class (vae relFro 1.7e-3 vs 1.24 swapped, bias exact, dit
sign-match 0.989 vs 0.484, ref fp8 2.6e-2 vs 1.37). Device A/B 512² 6s seed 1234:
clipHi 37.8% -> 0.1%, luma 136 -> 81 (reference 86), T2VA control clean; step-0
velocity vs the full CPU reference cos 0.9886, std ratio 1.071 (was a 7.6x gap) —
the W8A8 quant floor.

Kept: the R4D_DIT_SEL-gated decoder parity shadows (dbg_vd_* decl fields + driver
readback) that localised the fault.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-22 00:57:09 -05:00
gearwave00001andClaude bf6dc374d4 docs cont.24: #62 verdict — DiT faithful end-to-end; fried look localizes to the VAE decoder
Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-21 21:38:12 -05:00
gearwave00001andClaude f617cbafb5 dit dump: velocity-head isolation shadows (b_hn video rows + b_nout table row)
The per-block window verdict showed the block stack faithful to its quantization
floor (cos 0.98 -> 0.78 smooth decay over blocks 0-19, cascade at 20), leaving
the 7.6x step-0 velocity-std gap pointing at the FinalLayer. Dump its two own
operands so a CPU replay can judge them without the trunk: norm_out's modulated
stream over the first 256 video rows (bf16 -> f32 cast shadow) and lane/step's
shift|scale table row. The driver writes them as dit_hn.f32 / dit_nout.f32
after the existing slab files.

Replay verdict (compare_head.py, dasiwa-w8a8 dump): the table's video cell
equals t8 @ norm_out.linear + bias to the bf16 floor (relFro 1.5e-3, no silu --
the curve form bakes it, a_temb.x aliases b_temb), and the checkpoint head
reproduces the device velocity exactly (row cos 1.000000, affine 1.0000). The
head and its modulation are faithful; the vel-std gap is a harness-side
statistic, not a device op.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-21 21:37:50 -05:00
gearwave00001andClaude c783a7cb72 R4D_DIT_SEL: a per-block window shadow for the CPU-replay bisection
The first replay verdict (dev vs ref step-0 velocity) came back decorrelated
(cos -0.45, affine relFro 0.89) -- the fork is somewhere in the 50-block trunk,
and the modulation interface is EXONERATED against the checkpoint (dev_mod
cross-check: every block's cell = ada_w_block @ the step temb + bias, cos
1.0000, std ratio 1.000; weight order [video,text,audio] for stream cells
[text,audio,video]). To say WHO diverges and WHERE, declare_dit (env-gated) now
also casts the stream's first 64 rows into [L, 64, D] f32 PERSIST after every
block -- the same rows and ordering point the next block's norm reads -- and
the driver reads it back as dit_blk.f32. 69 MB, one cast op, no fingerprint
lost: the CPU harness gained the matching window stats (win64std) + ref_blkwin.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-21 16:57:48 -05:00
gearwave00001andClaude ea7a4e2d26 docs: cont.21-23 -- curve-form checkpoints ship, the fried look survives them on every arm (T2VA worst), R4D_DIT_SEL step-0 dump verified live
Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-21 13:56:40 -05:00
gearwave00001andClaude cfbccb46dc minimaxh3: adaln_t_table curve-form checkpoints + an R4D_DIT_SEL step dump
The DaSiWa overlay ships its modulation curve as a precomputed table (adaln_t_table
[1025,8]): timestep_embed gains a curve mode -- y[m] = the table linearly sampled at the
timestep, no sinusoid, no MLP -- in the HIP, AVX and ref tiers, and the arch drives the four
timestep rows (video, audio, and each re-embedded with its reference pin) through it with the
ada projections as plain bf16 K=8 lines. The dasiwa-w8a8 recipe carries the overlay.
Device-verified at 512: T2VA, I2VA and FL2VA complete clean and the T2VA re-run is
bit-identical; the fried look PERSISTS on the exact finetune the reference clips rendered
from, which kills the checkpoint-style theory and pins the fork to Radiance's forward.

For the value-parity localisation: R4D_DIT_SEL (env, driver and plugin) declares f32 PERSIST
shadows of the stream entering block 0, the timestep table and the step-0 modulation, and the
driver reads those plus the velocity head back on a plain request's step 0 into
R4D_ENC_DUMPDIR, for the CPU reference DiT replay to diff against.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-21 13:37:03 -05:00
gearwave00001andClaude 3a7a79fb47 videos: per-request shift/audio_shift; the fried look is decode/quant, not schedule
Adds `shift` (video) and `audio_shift` (soundtrack) as per-request /v1/videos
fields, (0,100], each defaulting to the model's trained shift; echoed in the
video object and advertised in the model card as video_shift/video_audio_shift.

ABI-invisible: VideoRequest carries the two doubles, video_schedule() re-shifts
that stream's sigma grid, and the shifted sigmas ride RadVideoGenBatch::sched --
the plugin reads only sigmas/timesteps, never a shift scalar, so RAD_ABI_VERSION
stays 24 and no plugin rebuilds.

Diagnosis (cont.20): the review batch's blown-highlight/crushed-black "fried"
look is present in the text-only T2VA control at native res (clip 54-79% vs the
reference's ~4.5%), so it is not the keyframe/tower path (#52) and not a
regression (old ex10 T2VA has clip 51%). It is not the sampler (euler vs
res_multistep: clip 53-61% vs 56-65%) and not the shift: the container already
runs 12/3 (the reference's settings) and shift=4 leaves clip at ~54%. With
sampler, shift and CFG (=1, no guidance) all matched, the gap is downstream of
the schedule -- the video VAE decode scale parity and/or the DiT int8 quant, i.e.
#37/#44/#45. The shift field ships regardless: correct, useful, and requested.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-21 09:11:34 -05:00
NunzeandClaude Opus 5.5 69f4906a5c docs: GLM-5.3's decode at a few rows
The five changes for decode's few rows in the glm5next section, where they apply and their
kernel times.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:26:57 +02:00
NunzeandClaude Opus 5.5 b86b25e406 arch/common: GLM KDA issues both low-rank down-projections before either up-projection -- one ordered point fewer a layer
A KDA layer projects its input seven times: qkv, beta, the two rank-128 down-projections into
the forget and gate paths, their two up-projections, and the output. The block issued forget's
down- and up-projection, then gate's: a recorded pass orders the input's four readers, then
forget_b, then gate_a reading the input again, three ordered points where two would do. Both
down-projections now issue before either up-projection, in declare as in step, because the
buffer plan takes lifetimes from the declaration order and forget_low and gate_low must not
share bytes while both are live. The same GEMMs over the same operands, so the bytes are the
same; the pinned step hashes move with the order (world 1 0x906897570034f5f5 /
0x68ffc03d2b640d51, world 8 0x9f39f6f7a04dc4d3 / 0x3818eedb4ac10d1b), and the block's test holds
the four readers first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 15:26:57 +02:00
NunzeandClaude Opus 5.5 f909576d09 libr4d: logits_gemm_bf16_cols -- the bf16 head without a block per column at n_embd 4096
logits_gemm_bf16 runs a 256-thread block per vocabulary column. At n_embd 4096 a thread makes two
16-byte weight loads before the block-wide sum, and each row widens both operands for its own
product: GLM-5.3's TP8 slice (19360 columns) took 303 us at six rows and 1133 at 24, where a verify
pass of eight streams lands, against 235 at one.

The new row runs a wave per four columns: lane l takes, in turn, threads 32q + l of the old
block for q = 0..7 -- the same 8-wide k chunks summed from 0 and added in k order, the same lane
butterfly per q, the eight wave sums added in q order from 0 -- so each column gets the old row's
bytes. bf16 widens to f32 exactly, so each weight is widened once for every row and each
activation once for every column. It outranks the block row at n_embd 4096 only; the block row
is unchanged and serves every other width.

Measured at the TP8 slice (r4d_selftest --perflogits), us:

  rows                 1      6      8     16     24     48
  logits_gemm_bf16  239.1  303.2  378.2  741.4 1133.2 2354.5
  ..._cols          235.5  247.5  250.4  404.5  635.6 1220.1

Two columns a wave and 16 rows a pass measured slower. r4d_selftest compares both rows byte for
byte from one row to past one 8-row chunk, at a vocabulary off the column step and a pitched
activation with a NaN and a signed zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:26:57 +02:00
NunzeandClaude Opus 5.5 1ff9abe2ba libr4d: gemm_nt_f32 keeps steps of k in flight below 64 rows -- GLM's router read its weights at 150 GB/s
The router (288 x 4096 f32, every MoE layer, the MTP layer in every draft pass) and the index
head gates (32 x 4096) took 26 to 36 us a call at decode's few rows: a lane loaded one weight a
step and fed it straight to its FMA, so a wave had one request in flight. The tile kernel now
loads U steps of k before their FMAs; each lane keeps its ascending fmaf chain and the butterfly,
so every form gives the same bytes, and U = 1 is the tile form as it was.

Below 64 rows the rule takes 2 x 2 tiles with 16 steps, at the router's width from 17 rows 8 x 1
with 8; the wave-per-output kernel for one row goes. Measured (r4d_selftest --cold 256 --perff32,
K 4096), us:

  rows                   1     4     8    16    24    48
  N 288, before       28.1  36.0  36.3  41.9  45.4  47.9
         after        14.4  14.5  15.0  19.1  21.6  35.5
  N 32,  before       27.3  33.3  32.9  36.4  36.2  36.1
         after         9.8   9.8   9.9   9.9  10.0  10.2

r4d_selftest's byte comparison with the host arithmetic passes at every form tried, r4d_emu gains
three shapes with K short of and past whole groups of steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:26:57 +02:00
NunzeandClaude Opus 5.5 4fdc786332 libr4d: moe_gemm_fp8a8_f32scale's small-M form at GLM's MTP gate_up slice -- a draft pass routes one token
Every draft pass runs the MTP layer's experts on one token: eight experts, and the expert-major
form's four column tiles a block below 128 routed rows left sixteen blocks, each a chain of 64
stages of 256 K. fp8_f32scale_small takes one column tile of the y-th touched expert a block
(grid rows min(experts, rows) + 1, as the MXFP4 small-M form), stages of 512 K, unconditional
loads masked at the store, LDS-only barriers, and a 128 of K's eight fragment pairs loaded before
its WMMA chain; the per-element sequence is the expert-major form's, so are the bytes.

The rule takes it at the MTP gate_up slice (288 experts, top 8, 512 x 4096) to 384 routed rows.
Down's K of 256 gains nothing from it (within a few percent, a quarter slower at three tokens) and
keeps the expert-major form. Measured (r4d_selftest --cold 256 --perfmxf8), expert-major against
small-M, us:

  tokens       1      2      4      8     16
            73.6   83.6  118.4  214.0  375.6
            36.7   65.8  114.9  203.9  343.9

Byte for byte against the expert-major form at 1 to 16 tokens during the work, and in r4d_emu,
whose grouped cases hold both forms at GLM's MTP slices to a host restatement of the sequence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:26:57 +02:00
NunzeandClaude Opus 5.5 961a9b3f13 libr4d: moe_gemm_mxfp4a8's small-M form at GLM's TP8 slices -- a one-stream verify pass is a chain of short expert launches
At 1 to 48 tokens a chunk (8 to 384 routed rows) the expert-major forms spent their time around
the loads rather than on them. Taking the loads out left gate_up at 72 of its 115 us at six
tokens; what remained was the skeleton of each block: 289 grid rows for the few touched experts,
activation scales read row by row from LDS behind a divergent branch, weight rows loaded through
generic pointers (flat loads, which every LDS wait also waits for), loads behind branches so each
store waited for the whole prefetch, and __syncthreads' workgroup fence. With 160 blocks resident
at 21.8 KiB of LDS each, the last round of an expert-major launch ran nearly empty, at the latency
of one block's chain.

moe_mxfp4_small_kernel keeps the expert-major per-element sequence, and so its bytes:

- block row y takes the y-th touched expert, counted by ballot over the offsets, so the grid has
  min(experts, rows) + 1 rows;
- weight codes stay packed in LDS and are decoded at the fragment read, halving the weight tile;
  gate_up stages 512 of K, reading 256 bytes of each weight row at once, down its 128-byte rows
  whole over four column tiles;
- loads are unconditional from clamped addresses and masked at the store, weight rows load
  through global pointers, the barriers order LDS only, and a 128 of K reads its activation scales
  and eight fragment pairs before its WMMA chains.

The rule takes it at GLM's TP8 slices for gate_up to 384 routed rows and down to 32; from five
tokens down reads 3 to 5 % slower than the staged form and keeps it. Other shapes are unchanged.
A deeper register prefetch, a barrier-free form with B straight from global memory and A tiles
sized to the chunk's tokens measured no faster.

Measured at the TP8 slices (r4d_selftest --cold 256 --perfmx), expert-major against small-M:

  tokens          1      3      6      8     16     48
  gate_up, us  36.8   79.5  120.5  145.0  230.3  416.7
               31.4   69.5  101.4  122.4  206.8  390.0

  tokens          1      2      3      4
  down, us     21.2   26.0   34.3   39.5
               16.4   22.5   33.2   37.9

Byte for byte against the expert-major forms over 1 to 48 tokens at every form tried (perfmx with
the old form kept beside it during the work), and in r4d_emu against the host restatement: three
GLM TP8 cases, with runs longer than one tile, dropped slots and E8M0 codes 0 and 255.
r4d_selftest checks the new band against libref at 1 to 48 tokens, and --perfmx names the form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:26:57 +02:00
NunzeandClaude Opus 5.5 332b5fa986 docs/GUIDE: a restore gives up other conversations' VRAM; prefix_restore_cuts_total, resumed_below
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:24:20 +02:00
NunzeandClaude Opus 5.5 4be0a34791 kv tiers: a restore makes room the way pressure does, and a chain the pool cannot hold stops at a snapshot
A restore reserved only from the free list. The reserve's trim leaves a quarter of the pool free
after every publish, so a returning conversation larger than that came back as far as the free
list reached, and the lookup stopped at the first block still on the host. On GLM-5.3-Flash at
eight ranks, two conversations of 314K tokens in a 446,832-token pool: the second turn of the
first brought back exactly the 27,930 free blocks, hit 111,772 tokens, and on its hybrid state
resumed at the snapshot at 1,024, since geometric backoff keeps nothing between 1,024 and 131,072.
Its prefill took 84 s instead of under one.

PCBinding::restore_plan now makes room before the engine plans the restore, the same way
PCBinding::evict does for an admission: PrefixCache::trim_for drops entries whose host copy has
landed, the engine lands pending copies (flush_fn), and it drops again. It never erases one,
spares the restoring chain itself and every chain a waiting request holds, and like trim never
touches one a running sequence reads. The free quarter may go; the reserve's trim after the next
publish frees it again. One block table serves every rank, so the room rank 0's cache makes is
room on every rank, as with evict.

When the pool still cannot hold the chain, PrefixCache::restorable_from cuts it at the deepest
valid snapshot the shorter prefix reaches, so no block comes back past the point the hit resumes
from; without recurrent state it cuts where the room ends. TierExec::issue_restore keeps its own
cut as the backstop.

Both cuts are counted: radiance:prefix_restore_cuts_total for restores the pool could not hold
whole (/sessions moved.restore_cuts), and radiance:prefix_hit_cuts_total{reason="resumed_below"}
for admissions that resumed more than one checkpoint interval below their attention hit, which
hit_cut_tokens alone did not tell apart from many small tails (/stats and /sessions hit_cuts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:24:20 +02:00
NunzeandClaude Opus 5.5 7d392b0400 mem_test: a conversation restored from the host tier comes back no further than the free list
A restore reserves only from the free list, so after the reserve's trim has left a quarter of
the pool free, a session larger than that comes back partly, and the lookup stops at the first
block still on the host. On a hybrid model the hit then resumes at the deepest snapshot below
that point, which the retention ladder can put far down the chain. These tests drive the
engine's restore against the real cache, tiers and manager: two conversations of 0.6 of the pool,
the second admitted by pressure and published, then the first restored. Red on this tree: the
first comes back as far as the free list reaches, the hybrid one resumes below its tip, and a
restore the pool cannot hold is cut where the reservation ended, not at a snapshot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:24:20 +02:00
NunzeandClaude Opus 5.5 1ad675e10c glm5next: the DSA indexer scores and selects by query rows over the ranks -- the prefill op that grows with context runs a run of rows a rank, bit for bit
Every rank scored every query row of a step against every complete block of its sequence and
selected its 512 blocks, the same work eight times: 58 ms of a 1029 ms step at a 4096-row chunk
and 20k of context, about 185 ms at 64k, the largest op that grows with the context. From
GlmTp::kSplitRows each rank now scores one run of the step's rows with dsa_score's row_part,
selects for the rows of its run under the bounds the scorer rebased (cu_part), and two
all_gathers lay the page tables and lengths end to end (8 MiB a layer at 4096 rows). The key
side stays replicated. The run's queries are all a rank needs, so the query projection, its
quantiser and the head gates run on the run's rows too, and the gates lose their column split
and gather; the bf16 projection stays on the step's rows where a run would be 64 rows or fewer,
the skinny band whose split count a tuned configuration may set. Each row's selection is the
same kernels' answer to the same operands, so the joined table is bit-identical to the
replicated one and MLA reads it unchanged.

The rule for a run is GlmTp's, stated once: ceil(T / world) rows rounded up to whole 16-byte
words of the gathered row, because an all_gather moves whole words; the indexer gathers one i32
length a row, so its runs are multiples of four (DsaCache::part_rows). A rank whose run lies
wholly past a small step takes the first run and computes dead rows, so every plane it gathers
is written (GlmTp::run_of). The selection planes hold world runs, which can reach past the step,
and the score plane shrinks to one run, 256 MiB to 32 MiB at 64k of context and a 4096-row
chunk. A decode step splits too once rows x live blocks reach 2^18 from 16 rows
(GlmTp::kSplitWork): eight sequences verifying five drafts from about 22k of context, where
scoring 48 rows over 8000 blocks (250 us on one R9700) outweighs the two eight-rank gathers
(about 50 us); a single sequence's six rows never pay. The replicated issue passes cu_part
absent as its tenth operand, because the engine counts operands against the schema and refused
the nine-operand issue at a served engine's first long prompt.

On eight R9700s (TP8, two ranks on Gen4 x8 that day) a 19887-token prompt prefills 3927 tok/s
against 3748 on 1.9.0, 7881 tokens 3990 against 3655, 2k 3849 against 3663; greedy text with the
adaptive draft window is identical. r4d_emu splits decode rows beside a prefill chunk at 2, 4
and 8 ranks and joins the runs as the gather does, byte for byte against the unsplit scorer;
glm5next_test declares the split at 2 and 8 ranks with the lint, holds the row rule to the
formula it replaced at every world, and pins the graph and steps (world 1
0xed3fc26c486ea1b5 / 0x33e5f136f0dbba15, world 8 0x712f01858dbe1047 / 0xf9e357b1333c638f).
dsa_score_fp8's selftest passes 62 of 62 on eight cards, and --perfdsa times the indexer whole
and as one rank's run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 15:24:05 +02:00
NunzeandClaude Fable 5.1 66812280bb r4d_selftest: --perfdsa -- GLM's DSA indexer timed at a context length, whole and as one rank's run
dsa_score scores every complete block of each row's sequence and qsa_select ranks them, so both
grow with the context in decode as in prefill. --perfdsa CTX [M] [iters] times them at M rows in
the packed-cache form glm5next issues, and as one rank's run of a step split over 2, 4 and 8 ranks
by rows (dsa_score's row_part), printing what the split saves before its two all_gathers.

On one R9700, 48 rows (eight sequences verifying five drafts) take 273 + 155 us at 60k of
context and a run of 8 rows 53 + 21 us; six rows save 9 us. qsa_select at 4000 blocks takes 89 us
for any row count up to 32: its split path needs two chunks of 4096, so a list of 3500 to 4096
blocks falls to the single-workgroup kernel past its key cache.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 15:24:05 +02:00
NunzeandClaude Fable 5.1 afe5318259 dsa_score: row_part -- score one run of a step's query rows, and rebase cu for the selection after it
With `row_part` p, `score` holds R rows and row i is query row p * R + i; `q`, `q_scale` and
`gate` stay the whole step's, so a run is the unsplit op's rows bit for bit. A row past the last
sequence scores -inf, so every rank's run can be the same length whatever the step's. The optional
output `cu_part` receives cu - p * R, under which qsa_select runs over the run's own rows (pos
offset by p * R) and finds each row's sequence unchanged; qsa_select itself is untouched.

This is what an indexer split over tensor-parallel ranks by query rows needs from the op: the
scoring is the only per-row work in GLM-5.3's indexer that grows with the context.

libr4d offsets the query operands and compares row0 + r against cu; libref and libavx index the
same way. Without `row_part` nothing changes. Tests: the selftest scores each case's rows in equal
runs and holds every run to the unsplit rows' bytes and cu_part to the rebased bounds; ref_test
checks a run, a run past the step and a short query plane; r4d_emu_dsa (r4d_dsa.hip now runs on
the emulator) splits decode rows beside a prefill chunk at 2, 4 and 8 ranks, selects with the
rebased bounds and joins the runs as the all_gather does, byte for byte against the unsplit
scorer and selection, ties and signed gates included.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 15:24:05 +02:00
AshlynandClaude Opus 5.5 5e8bae8ae6 libr4d, arch, deploy: coded overlap all-reduces, multi-user verify tuning, the split junction, a compose file
The prefill overlap's lane all-reduces coded losslessly at ~12.2 bits a value; the verify step's
GEMM, norm and all-reduces tuned for 17-64 rows; at 4-16 rows each GPU norms its own rows between
a reduce-scatter and an int8 all-gather; deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml.

Squashed from:

- libr4d: the four-rank exact two-shot coded at ~12.2 bits a bf16 value, for the lane row
- libr4d: the prefill overlap's lane all-reduces coded by default
- libr4d: decode-sized two-shots take fewer blocks
- libr4d: gemm_w4a8_nt_m64 at multi-user verify heights (33-64 rows) -- narrower row tiles, wider N
- libr4d: rmsnorm_quant_i8's register form at 512 threads too (33 to 72-120 rows)
- libr4d: ar_rmsnorm_quant_i8_4rank's `sp`, the all-reduce split around the junction
- arch/gemma4_bf16: the 31B's junctions take libr4d's `sp` at 4-16 rows at four ranks
- deploy/compose, README: Gemma 4 31B with RedHatAI's DFlash2 drafter on four cards

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 03:00:48 -05:00
AshlynandClaude Opus 5.5 ab2b3be6c0 core, libr4d, arch: chained launches with block drafters, more prefill overlap, weight reads beside the all-reduces
Chained launches on the AQL backend (a dependent kernel waits on a queue counter in its own
prologue), on by default where the model's plugin measured a gain with its block drafter (the
Gemma 4 31B and 26B); the prefill overlap runs attention per slice with narrower lane-1
reductions; the next GEMM's weight is read into the on-die cache beside each all-reduce at decode
heights.

Squashed from:

- core, libr4d: chained launches -- dependent kernels wait in their prologue, not behind the barrier bit
- core, libr4d: chain a kernel by its name, not by the row that launched it
- libr4d, core: chained forms hold nothing across their body
- libr4d: a chained kernel's prologue polls its counter less often after the first few tries
- core/sched: the advance kernel's chained form
- docs: GUIDE lists RADIANCE_CHAIN; chained launches stay opt-in
- core/device: a chained packet behind a chained one keeps its barrier bit while a plain one may run
- libr4d: qkv_norm_rope and its kv_store fold as chained forms
- libr4d: the split-KV decode attention and its merge as chained forms
- libr4d: the four-rank fused junction's tail form as a chained form
- libr4d: the attention, prologue and junction chained forms hold nothing across their body
- libr4d: the 31B's windowed attention and quant_act_i8 as chained forms; r4d_chain.h stubs for the host emulator
- libr4d: DFlash2's kernels as chained forms
- libr4d: chained forms for the decode tail
- abi, core, arch: chained launches on by default where the plugin measured a gain with its drafter
- arch/gemma4_bf16: the prefill overlap's lane-1 all-reduces take the narrow launch (`overlap` 1)
- arch/gemma4_bf16, libr4d: the prefill overlap runs attention per slice; kv_len_trim
- abi, core, libr4d: RAD_LAYOUT_ANY, and a device-only weight read (prefetch)
- arch: read the next GEMM's weight into the cache beside each collective at decode heights

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 03:00:48 -05:00
AshlynandClaude Opus 5.5 1bb7ad3ef9 The series' PR beneath, composed (a copy; it drops out when it lands)
#159's tree (a full fence on four-rank prefill-sized all-reduces), which the maintainer will merge
by hand in the next release, as the integration branch composed and tested it. Not for review
here: review the last commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 02:59:52 -05:00
AshlynandClaude Opus 5.5 cb5a69ac3f engine: a block drafter on the card's acceptance -- its passes queued behind the step, the next step issued ahead
A block drafter (DFlash) ran its two passes after the commit, staged from the committed sequence:
the verify, a host wait and the commit, the context and query passes, a second host wait for the
proposals, then the next step's build and issue, with the cards idle through each host turn and
the ranks starting every pass at different times. Pipelining was off for block drafters.

It now takes the serial drafters' path (sched/advance.h). After the trunk's ranks join, the
acceptance runs on every rank (ADV_ACCEPT). block_begin runs before the commit (on_card): the
context pass mirrors the trunk step, whose positions the host knows (a row issued ahead continued
from the committed end, as commit() reads it); the query block's rows are device rows staged at
the furthest anchor acceptance could leave, with the KV reservation that far, and ADV_BLOCK puts
the anchor (the token the verify chose) and the masks at the card's committed end. After the
query pass, ADV_BTAKE takes the proposals into each StepSlot behind the anchor, which is the token
row the next verify reads (ADV_TRUNK), so issue_ahead verifies them with no host round trip. The
slots come back with the step's one readback; finish_block_drafter checks the card's acceptance
against the host's, as the serial driver does, publishes the proposals and moves the drafter's
filled range.

RADIANCE_DRAFT_BLOCK_HOST=1 keeps the host's driver, for the A/B, and has a row in GUIDE.md's
environment table. On libref with the tiny 31B-shaped checkpoint (and one doctored so its drafter
is right part of the time) the two drivers give the same replies, the same draft acceptance and
the same sampled text, and greedy matches plain decoding. sched_test runs 24 pipelined steps
against the host's driver: the same trunk steps and the same context and query passes, positions,
lengths and slots (the context pass's token ids aside, which that pass does not read);
advance_test covers the two modes and the chain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:48:51 +02:00
AshlynandClaude Opus 5.5 015cba8837 libr4d, arch: the 31B and DFlash2 with fewer launches a step, same bytes
Attention reads q and the gqa-8 drafter's KV in place (attn_paged_qrow); the 31B's attention
prologue stores k and v itself (qkv_norm_rope_kv_store); DFlash2's norm/rope/cache-store chains
and add-then-norm pairs run as one launch each. Carries the launch-cliff padding until that PR
merges.

Squashed from:

- libr4d: attn_paged_qrow on the split-KV decode kernel -- h256/gqa2, and h128/gqa8 by two groups a kv head
- arch: the 31B's sliding layers and its drafter read through attn_paged_qrow where a card serves it
- libr4d: step past the full-card launch cliff in qkv_norm_rope and the row norms
- libr4d: qkv_norm_rope describes its operands, so rad-kbench and rad-tune can time it
- libr4d, arch/gemma4_bf16: qkv_norm_rope_kv_store -- the 31B's prologue stores k and v itself
- libr4d, arch/common: qkv_norm_rope takes v_norm; DFlash2's query pass folds its q/k chain
- libr4d, arch/common: qkv_norm_rope takes n_head 0; DFlash2's context pass folds its key chain
- libr4d, arch/common: add_rmsnorm; DFlash2 issues each residual add with the norm after it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:48:20 +02:00
AshlynandClaude Opus 5.5 04e5480387 arch, data/recipes, libr4d: the 31B's prefill overlap, q|k|v as one linear, RedHatAI's DFlash2, its fc split
The 31B's prefill steps of 1024 rows or more run as two slices with each slice's all-reduces
beside the other's compute; q, k and v as one linear where the container holds them so; the 31B
serves RedHatAI's DFlash2 speculator; DFlash2's fc projection is split over the ranks, bit for bit.

Squashed from:

- arch/gemma4_bf16: a prefill step in two slices, each slice's reductions on the second lane
- arch/gemma4_bf16: q, k and v as one linear where the container holds them so
- data/recipes: the 31B -df recipes make q, k and v one linear (blk.*.attn_qkv)
- arch/gemma4: the 31B serves RedHatAI's DFlash2 speculator (gemma-4-31B-it-speculator.dflash2)
- libr4d: gemm_nt_q takes split_n, and all_gather lands rows at a wider output pitch
- arch/common: DFlash2's fc split over the ranks as windows of block-aligned rows, bit for bit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:48:20 +02:00
AshlynandClaude Opus 5.5 bdb37d5d16 arch: Gemma 4 31B with z-lab's DFlash drafter
Gemma 4's DFlash drafter moves into arch/common so both Gemma 4 plugins declare it, on the int8
grid too; the 31B declares it beside its w4a8 / w8a8 trunk when the container carries one; the
w4a8 and Q8 -df recipes and compose files; the tests.

Squashed from:

- arch: Gemma 4's DFlash drafter into arch/common, for both Gemma 4 plugins, and on the int8 grid
- arch: z-lab's DFlash drafter beside the 31B's w4a8 / w8a8 trunk, its gqa-8 attention at gqa 4
- data/recipes: gemma4-31b with DFlash, the w4a8 trunk with a block-fp8 drafter, and Q8
- tests: the 31B with its DFlash drafter declares the chains where libr4d's fused ops are not declared
- tests: the 31B's steps with its DFlash drafter lint clean, on both grids, at one, two and four ranks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:48:20 +02:00
AshlynandClaude Opus 5.5 239da14d17 libr4d, arch/gemma4_bf16: the four-rank all-reduce by message size, and the 31B's junction fold to 16 rows
The four-rank exact all-reduce picks its transport and block count by message size, for every
tp-4 model; the four-rank fused junction gains its tail form (the two-shot with the junction after
it), which the 31B takes up to 16 rows. Carries rmsnorm_quant_i8's register form until that PR
merges.

Squashed from:

- libr4d: the four-rank all-reduce's fold a word at a time, 16-row standalone all-reduces on the two-shot, counters in L2
- libr4d: the standalone four-rank all-reduce takes the exact two-shot from 32768 elements
- libr4d: the four-rank exact all-reduce's two-shot takes 2 blocks at a DFlash2 verify, not 4
- libr4d: the all-reduce rows' nblocks axis offers 2 and 4
- libr4d: rmsnorm_quant_i8 at decode heights loads the row's operands before its reductions
- libr4d: the four-rank fused junction's tail form -- the two-shot with the junction after it
- arch/gemma4_bf16: the four-rank fold up to 16 rows, on libr4d's tail form

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:47:23 +02:00
Marc Siebenhaar 51db508f91 libr4d: R4D_ATTN_FP8 also for the fp8_v4 and k6_v4 caches
fp8_v4's K is E4M3 already and goes to LDS as raw bytes, as on the fp8 cache.
k6_v4's K and the int4 V of both layouts are widened to the value times its
group scale (as for the f16 legs) and rounded once to e4m3 at staging. The
launcher reads R4D_ATTN_FP8 for all three fp8-family caches. The eight new
prefill instantiations spill no registers.

Measured with radiance 1.10.0, fp8_v4 KV, otherwise as above (KL against
the fp8-KV reference with R4D_ATTN_FP8=0):
- R4D_ATTN_FP8=0 with fp8_v4 matches the shipped libr4d (mean KL 0.006713
  in both)
- 3: mean KL 0.0073, p99.9 0.89, max 5.2, top-1 98.3 %
- prompt 200K: 2,609-2,611 -> 3,073-3,091 t/s; 5 x 200K joint prefill
  2,403 -> 2,834 t/s; decode unchanged
2026-10-21 09:46:23 +02:00
Marc Siebenhaar cdc0ae26df libr4d: opt-in fp8 QK and PV legs for the h256/gqa6 prefill attention (R4D_ATTN_FP8)
Ports the 8-bit prefill legs of radiance-vllm-mxfp4's r4d_radiance_extras.patch (commit afa21b5
there) to the h256/gqa6 prefill kernel as two separable bits, off by default:

- O_QK8 (32): Q is quantised to e4m3 once at load (after the folded scale), K stays raw bytes in
  LDS, and Q.K^T runs as fp8 WMMA.
- O_PV8 (64): P is packed to e4m3, V stays raw bytes in LDS, and P.V runs as fp8 WMMA. PGROW
  tightens to 8 octaves (e4m3 max 448) and DOT2 is off.

Both need CONTIG and are compiled out for bf16 KV. Byte tiles halve the K/V LDS footprint.
prefill_launch reads R4D_ATTN_FP8 once: 0 = f16 (unchanged), 1 = QK8, 2 = PV8, 3 = both.

Measured with radiance 1.9.0 on 2x R9700 (230 W), Qwen3.8-27B MXFP4, TP 2, fp8 KV,
--tp-wire wht6:
- kernel, ctx 200K, chunk 6592: 161.8 ms -> 113.9 ms with 3 (x1.42); per-row relative error
  against fp32 1.7e-3 -> 3.1e-2
- prompt throughput at 200K: 2,621 -> 3,082-3,127 t/s; at 25K: 4,746 -> 4,861-5,011 t/s
- --kld-ref against the unpatched build: R4D_ATTN_FP8=0 is bit-identical (KL 0 on 10,198
  positions); 3 gives mean KL 0.0076, p99.9 0.94, max 14.3, top-1 98.4 %, PPL x1.0024
- decode and DFlash2 acceptance unchanged (the decode kernel keeps its f16 legs)
2026-10-21 09:46:23 +02:00
NunzeandClaude Fable 5.1 fa4a7a75a4 glm5next: the plugin over its blocks, one a file, and rad_glm_tp.h for the shards and the split threshold -- the same graph, read in order
The plugin carried the draft head's buffers, weights and ops in its declare and its draft pass
in its step, with the three ops that join the head to its layer declared inside the layer
function; each GLM block carried its core in a header of its own (rad_block_mla_latent.h,
rad_block_kda_state.h, rad_block_dsa_cache.h), the split threshold sat in rad_tp_split.h beside
the router's column split, and 64 / world, 8192 / world, 2048 / world were spelled across the
plugin and the blocks. tests/arch_test.cpp held the recording builder, the run-phase fakes, the
step lint, the batch kits and the fingerprints beside every architecture's cases, 9.5k lines in
one translation unit, GLM-5.3's among them.

Now one block a file in arch/common: rad_block_glm_{mhc,kda,mla,indexer,router,mtp}.h, the
cores joined to their blocks, and GlmMtp the draft head in three parts (inputs, join, head),
declared and stepped around the plugin's layer 45. rad_glm_tp.h (GlmTp) holds the widths a
rank's shard divides, the one threshold kSplitRows and the replicated all_reduce declared once;
SplitF32Proj moves over unchanged. The plugin reads as the stream's buffers, then each block's,
the KV groups, the layers, the head and the draft head.

tests/arch_fakes.h holds the fakes and the helpers every architecture test needs, included by
one translation unit a binary (neither binary links rad_core, as before); GLM-5.3's cases are
tests/glm5next_test.cpp, which includes only its plugin, with two cases new: every op the plugin
issues carries the operand count its schema declares (the kernel libraries' schemas under
$RADIANCE_HOME/kernels, counted as core/runtime/issue.cpp counts), and every declared weight
reads an entry the served container holds, at the dtype its stored encoding calls for (the
container's names and encodings as rad-info -v lists them).

Every declared name, declaration order and issue order is as it was: the pinned graph and step
hashes at one and eight ranks are the values arch_test pinned before the move (world 1
0xed3fc26c486ea1b5 / 0x98ba2952bb37b075, world 8 0x8204e073efdeee0c / 0x1279aecfe4e32d9a), and
arch_test's pins of the other architectures are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 09:44:46 +02:00
NunzeandClaude Fable 5.1 d2a165d56d jinja: the caps probe hands the template an empty tools array, not [null] -- GLM-5.3's template iterated it and lost string content
json{nullptr} is the one-element array [null], not an empty one. The string-content probe
passed it as `tools`; GLM-5.3's template iterates `tools` under `{% if tools %}`, so the probe's
render threw on the null element, the throw was taken for "cannot render string content", and
with typed content unsupported as well every request logged `render_message_to_json: Neither
string content nor typed content is supported`. llama.cpp master passes json::array() (PR
#27130); so does this probe now. The GLM-shaped template in chat_test asserts string content.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 09:42:27 +02:00
AshlynandClaude Opus 5.5 61266c812b libr4d: a full fence on four-rank prefill-sized all-reduces, for a rare fresh-start divergence
On a freshly started 31B server at four ranks (4x R9700), the first greedy reply now and then
flipped a near-tie: 1 of 8 fresh starts after scribbling the cards' memory. Per-op output hashes
located the divergence at a prefill all-reduce that read a peer's scratch before that peer's words
had landed: the first reuse of a double-buffered slot, inputs identical on every rank. A full
system fence on every thread before the flag (drain 1), or after it (acq 1), cured it on the cards
(26 of 26 fresh starts). The per-wave store wait, the publisher's single writeback and Relaxed
Ordering off on every link did not. The mechanism below the fence is not known.

r4d_cfg_ar now takes drain 1 for a four-rank message of RADIANCE_AR_FENCE_FROM elements or more
(default 131072: 24 rows of the 31B's 5376, above any verify height and below every prefill chunk).
Decode and verify all-reduces keep the per-wave store wait and pay nothing; 0 turns the fence off.
Two-rank all-reduces never take it: Qwen3.8-27B's prefill at tp 2 paid 4.5% for it, and no
two-rank fresh start ever flipped. GUIDE.md lists the switch. Bytes are unchanged either way; only
when the flag goes out moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 02:31:40 -05:00
Memoria (Noblistic) 459529638e dashboard: statsdump exits cleanly when its handle is dead; sparkline comment told a third wrong story
Judge ringer 4 on the final tree (3 slices, Tasmania, independent questions).
Slice A PASS-WITH-CAVEATS, slice B PASS-WITH-CAVEATS, slice C FAIL. Both
findings were real and both are fixed here.

statsdump (slice B, R1 + R2): the rotation fix deferred the death instead of
removing it. If the best-effort reopen inside rotate() itself fails, out stays
CLOSED, the re-raised OSError is swallowed by the cap check's handler, and the
next poll's write raises ValueError -- which no handler in the file catches
(they all catch OSError). Slice B found the unpatched twin in the write-failure
handler: close succeeds, reopen fails (EMFILE/ENOENT/EACCES/EIO -- not ENOSPC,
which append-open survives), and the cap check's out.tell() dies on the closed
handle two statements later. Both paths now raise a dedicated RecorderDead,
caught at the loop: the recorder exits loudly with its exit summary, because a
handle that cannot be reopened means recording cannot continue. Deferring a
traceback by one iteration was the wrong ambition; exiting with the count is
the honest terminal state.

Canaries reproduce both geometries (reopen fails after rotation shift fails;
reopen fails after write fails): pre-fix dies 'ValueError: I/O operation on
closed file' with no summary in both; post-fix exits rc=0/rc=1 with the summary
printed in both.

dashboard.cpp (slice C, FAIL): my previous commit replaced one wrong sparkline
comment with another. The truth, verified against the call sites: setMetric
samples EVERY poll for every tile (idle polls push 0), so the accept sparkline
spans the same 60 s as the others; the only difference is the dash case -- no
draft head, no value, a gap that stretches the line over more wall-clock. The
original comment claimed 10 s drafting windows; my rewrite claimed drafting-only
sampling, conflating the sparkline (setMetric/hist) with the triple's recent
window (noteSample, win=false). Two lies in one comment block, both caught by
review rather than by me.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) b2e0ef7911 dashboard: the accept sparkline comment described a sampling scheme that never existed
Auditor flagged this twice; it is a lie in shipped source (the comment is
served inside the page), so it goes before merge rather than after.

The comment claimed the sparkline's samples are 10 s drafting windows. No
10 s clock exists anywhere in the page: HIST is 120 at the 500 ms poll
(dashboard.cpp:1249), and the accept series pushes via noteSample only when
the poll drafted (aw.dr > 0). The true distinction from the other tiles is
the drafting-only sampling, not a different window length: 120 drafting
samples are 60 s of continuous drafting, stretched over more wall-clock when
drafting is intermittent.

Comment-only change; no behavior touched.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 3178807ba7 dashboard: detail-line 'now' clauses stop reporting stale values as current
Operator ruling 2026-10-20, applied one line down: the idle-0 law exists
because a stale value wearing a current name is a false measurement. Judge
slice 26 found the same defect surviving in the detail lines under the three
figures already fixed -- the headline obeyed the law and its own detail line
did not, so a busy lane that drafted nothing showed 0 and 'now 87% of
highest' directly beneath it.

- Accept tile: 'now' is shown only when THIS poll drafted. The guard inside
  acceptTriple (last.dr > 0) can never be false -- the ring only stores
  deltas with dr > 0 -- so the freshness test moved to the caller, where the
  poll's own delta is known. highest/recent are session statistics by design
  and stay.
- Step tile: 'now X% of best' is gated on this window HAVING decode steps,
  not on the lane being busy. During a prefill-only stretch the lane is busy
  and lastStepMs holds the last decode poll; the headline reads 0, so the
  clause must not print.
- Speculation 'per step': reads 0 when the window took no decode steps
  instead of holding the last value. EXTENSION of the ruling by one figure,
  named here because it was not one of the three the operator listed -- same
  defect class, flagged by slice 26, and it is derived from the step tile
  that already reads 0, so leaving it frozen made the panel disagree with
  itself.

Fully-idle was already correct on all three; every one of these was the
busy-but-no-measurement window.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) eed70619cc dashboard: 'Average' -> 'Accepted of drafted' -- the label names its denominator
Operator call. The bullet is the engine's lifetime marginal ratio,
accepted/drafted (core/sched/draft.h:172, 'cumulative and exact' -- a pooled
ratio of sums, not an average of anything). 'Average' was wrong twice: it is
not an average, and it hid which denominator it used.

The panel shows two ratios that count the SAME accepted tokens and differ
only in the denominator -- reached for the live figure, drafted for this one.
'Average' distinguished them by time, which is not the axis they differ on,
and invited reading the lifetime figure as a longer window on the live one.
Naming the denominator makes the panel self-documenting, which is the same
reason the live figure became 'conditionally accepted'.

The label is ours, not upstream's: 685ec5b's panel had no such key, so this
asks nothing of upstream vocabulary. No test keys on the string (checked).

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 87becd5812 scripts/statsdump: rotation failure must not leave a closed handle (auditor ringer Q2)
The disk-full fix in c9aa677 guarded the WRITE path but not the ROTATION path:
rotate() closes the handle first, so if the generation shift or the reopen
itself raises (ENOSPC bites when the directory must grow), out stays closed --
and the next poll's write raises ValueError, which the OSError handler does
not catch. The poller dies with a traceback and no exit summary: the exact
terminal state the size cap exists to prevent.

Fix: rotate() reopens best-effort before re-raising (append-open needs no
disk space, so it succeeds even on a full disk), and the exit close is
guarded so a failing flush cannot eat the summary line.

Can-fail verified by injecting ENOSPC into os.replace at the second shift --
the auditor's geometry, rotation failing with the handle already closed:
pre-fix dies 'ValueError: I/O operation on closed file' with 0 summary lines;
post-fix completes the run, rc=0, summary printed.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 8cfcd3c6e5 dashboard: the .hold mobile scroll override was dead code -- specificity fix
Judge slice 31 FAILed a91bf44 and the operator's thumb confirmed it: the
request table still locks under a phone drag. The media-query override
listed bare .hold, but the base '.hold { overscroll-behavior:contain }' is
defined LATER in this file -- equal specificity, later rule wins the
cascade, so the override matched and lost. The .pbody half won (its base
rule is earlier), which is why the page scrolled some of the way but the
request block did not.

Fixed by specificity, not by moving the block: '.body .hold' outranks the
base '.hold' regardless of order, and the media query stays co-located
with the other breakpoint rules per this file's convention. The graph
modal (.ginfo .pbody) deliberately stays contained: it is an overlay the
user scrolls on purpose, and chaining out of it into the page behind is
the wrong feel.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 57184a0724 dashboard: un-trap mobile scrolling; rename 'accepted now' to 'conditionally accepted'
Two operator findings from live phone use:

- Scroll trap: nested scrollers (the request/batch card bodies and .hold)
  carry overscroll-behavior:contain, set deliberately for the desktop wheel
  so a scroll over the request table does not move the page behind it. On a
  phone that containment traps the thumb-drag: the card scrolls, bottoms
  out, and the page refuses to chain -- the operator's 'scroll halfway, then
  use the sides for traction' symptom is exactly that, the margins being the
  only place with no scroller under the finger. Narrow screens now restore
  overscroll-behavior:auto so the scroll chains to the document; desktop
  containment is unchanged.
- Caption: the Speculation panel's live figure reads 'conditionally
  accepted' (displayed uppercase by .cap), naming the ratio's basis on the
  face of the panel. README's reference to the same figure follows. No test
  asserts on either string (checked before editing).

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 52b3069f76 scripts/statsdump: survive disk-full AT the cap (judge slice 23)
Slice 23 refuted my 'survive a failed write' claim in the primary geometry:
a write fails at the cap, the cap check's out.tell() FLUSHES the dirty
buffer and raises OUTSIDE the handler -- the poller dies with a traceback
and no exit summary, exactly the terminal state the cap was supposed to
prevent. Fix: on a failed write, drop the dirty buffer and reopen; the cap
check is wrapped so a size check can never be the thing that kills the
poller.

Can-fail verified with a real EFBIG geometry (RLIMIT_FSIZE 5 KB, cap 104 B,
live engine): the pre-fix code dies 'OSError: File too large'; the fixed
code completes the run, 16 rotations, exit summary printed, rows counted.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 61e3131262 dashboard: live figures read 0 when the lane is idle
Operator ruling 2026-10-20, on the three real-time figures: the decode-step
headline, the acceptance tile, and the Speculation live figure.

The defect was the FREEZE. Each of these held its last value while the lane
did nothing, so a stale number kept wearing a current name -- a reader
checking the dashboard at rest read a measurement of work that was not
happening. Judge slice 10 named the failure mode in review.

The fix follows the page's own convention rather than inventing one: every
other live figure on this page shows 0 when the lane is idle (tps() renders
0 as "0", and the engine publishes 0 rates when nothing runs), so 0 IS the
idle signal here. The dash stays reserved for a quantity that has no value
at all -- no draft head, no engine attached.

- Decode step: the tile reads this window's step time; a window with no
  decode steps reads 0. The engine's own best/recent floor figures below it
  are the engine's windows and stay put.
- Acceptance tile: drafted nothing this poll -> 0. Dash only when there is
  no draft head at all.
- Speculation live figure: same condition, same 0.

Sparklines are unaffected: setMetric() pushes nothing for a null sample, so
history stays honest across idle gaps. The restart path needs no special
case -- a restart poll has no delta, so it reads the idle 0 -- and the
pooled-ring clear inside accWindow stays, so a pre-restart pair never pools
with a post-restart one.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 1cf31320a9 metrics+dashboard: judge-slice cleanups -- HELP text, dead window, window comment
Non-gating findings from the Tasmania judge fan-out (reviews/judge/):

- HELP text on radiance:decode_step_seconds_best/_recent said 'seconds per
  token'. It is a window mean of STEP times, and with speculation a step
  emits several tokens, so the two differ by the accepted-per-step factor --
  the wording invited a comparison that is wrong by exactly that factor.
  Now says PER STEP and names the conversion. No test asserts on HELP text
  (server_test parses it into d.help and never reads it), so this is a
  documentation-only change to the exposition, not to the value.
- noteSample gains a  argument; acceptance passes win=false. Its
  winAt["accept"] ring was written every poll and read by nobody --
  acceptTriple takes highest from extAt and recent/now from accPool -- so it
  was a second copy of the same samples that a reviewer reasonably mistook
  for a second figure.
- RECENT's '15 s at the 500 ms poll' is true only while the quantity keeps
  updating; acceptance samples only when it drafts, so its 30-sample span is
  30 UPDATES, minutes under sparse drafting (slice 01). Comment corrected.

Diff is 16 insertions / 7 deletions across two files, read line by line
(scripted sweep -- no test would have caught a wrong anchor).

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) df42bd5c26 scripts/statsdump: size-cap rotation, monotonic dt_s, survive a failed write
Auditor gating fix 2 (Qwen 27B, AUDIT-qwen-20261020.md §6), confirmed by
judge slice 05. An append-only recorder with no cap is a disk-full timer:
at 1 poll/s the /stats payload runs to hundreds of MB a day, and the
terminal state was an uncaught OSError traceback with no exit summary.
--max-mib (default 256) rotates keeping 5 generations; rows carry their
own timestamps so the chain stays readable in order. A failed write is
now counted and the poller survives to report it. dt_s moves to the
monotonic clock -- a wall-clock step could make it negative and every
consumer dividing counters by it would inherit the step; t stays
wall-clock because it is a timestamp, not a delta.

Can-fail check run against the live engine: --max-mib 0.00002 produced
17 rotations with generations capped at .1-.5 and no rows lost. Does not
touch the engine or the page, so the running image is unaffected; this
lands for the PR and for whenever statsdump is wired in.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 77f91a0240 dashboard: fix the pooled ring's property names -- recent/now were NaN, never rendered
Two judge slices (Tasmania 27B, :8101) independently found what the auditor's
pass at 1505ef2 missed: accWindow pushes {ratio, dr, da} but acceptTriple read
d.r/d.a/last.r/last.a -- accPrev's names, a different object. Every pooled sum
was undefined, so the acceptance detail line was frozen at 'highest X% - recent
-' in the PRODUCTION page since 1505ef2. The headline was unaffected, which is
why it looked alive. Fixed to d.dr/d.da/last.dr/last.da.

Also from the judges: the Speculation 'Average' bullet printed 0% for an
undefined lifetime marginal (no drafts yet), breaking the panel's own rule that
0 reads as failure -- now a dash. The comment above it cited a 'GUIDE' that does
not exist; it now cites the README section, which is re-landed here (dropped in
the rebase onto v1.9.0) with the worked example corrected: 56/75/77 implies
43.4% marginal, not the 44% previously claimed.

New test the_pooled_acceptance_ring_reads_the_names_accWindow_writes holds both
sides of the ring contract to the same names -- it fails on the exact bug above,
which no C++ test could see because the page JS is never executed here.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 7c18d8d1bb dashboard: close the restart gap in the acceptance tile (Turnstone audit)
Auditor Qwen (27B, :8788) returned SHIP-WITH-FIXES; this is gating fix 1.
accPool was push-only, so after an engine restart up to RECENT=30 delta
pairs from the dead process pooled with the new one's and biased 'recent'
-- largest exactly when a restart is likeliest to change acceptance.
Restart detection now also watches uptime_s going backwards, which catches
the case backward counters cannot: a backgrounded tab whose accPrev froze
while the new process drafted past the old one's lifetime total, giving a
positive bogus delta. On either signal every pooled ring is cleared and
the accept headline + Speculation figure dash for that poll instead of
freezing a dead process's ratio. Also drops the dead accDelta/ACC_WIN
left by the pre-pool design and corrects the stale '10 s' comment.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 2dde313121 dashboard: rename the acceptance ring off 'p' -- dashboard_test's contract scanner
Full-suite build of the production branch FAILED 1 of 96: dashboard_test
every_field_the_page_reads_is_one_the_routes_emit reported the page reads
draft_positions[].length/.push/.shift. Cause: that test extracts every
'p.<field>' inside update() and asserts each is a field /stats emits --
p is the page's conventional name for a draft_positions element. My pooled
ring buffer reused p for an array, so its own methods were read as engine
fields. No logic error; a naming collision with the test's contract.
Renamed to 'ring' in update() and acceptTriple(). The gate worked exactly
as designed: rc=8, flip aborted, lane stayed on stock.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) ddb8aa9127 dashboard: acceptance tile recent/now are pooled ratios of sums
Math audit before the production roll (op request): triple()'s recent
averaged per-poll ratios, but polls carry unequal draft counts, so quiet
polls weighed as much as 500-draft polls. Live c8 replica measured the
skew: avg-of-ratios 65.7% vs pooled 54.7% -- 11 points, growing with
burstiness. The tile now keeps a per-concurrency ring of delta pairs and
reports sum(accepted)/sum(reached) for recent and now; highest stays the
full-session extreme. Speculation panel headline unchanged (it is the
newest window ratio, which is a per-poll quantity by definition).

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI
2026-10-21 09:27:48 +02:00
Memoria (Noblistic) 8bc457d7e7 dashboard: triple-tile rework, acceptance live-leads, Speculation bullet
metrics: export radiance:decode_step_seconds_best/_recent (omitted until measured)
scripts: statsdump.py -- /stats to JSONL verbatim recorder

Base: pr/decode-floor tip 14c5c8a (PR #142 content). Rebase onto v1.9.0 owed at
review time: upstream dashboard.cpp moved +87 lines in 1.9.0, expect conflicts.
NOT pushed, NOT merged. Turnstone review pending (Qwen busy).

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI

(cherry picked from commit 4a8b8fabdd834f8eb59320e1945471a8caff47c9)
2026-10-21 09:27:48 +02:00
C_Tamas 7e1f73c2a0 abi: the control vector's field is ABI 26, not the 25 main released
Merging main brought 1.10.0's own 24 -> 25 bump, byte for byte the same two lines this
branch carried (abi/rad_abi.h's RAD_ABI_VERSION and the layout test's snapshot constants),
so the merge made those files identical to main and the PR's diff fell from 49 files to 47.

What is left is a version number that names two different layouts. main's 25 grew
RadGeneratorDecl (aux_max_tokens, sigma_grid, min_tokens, aux_tokens), RadStep's
conditioning tensors and the tokenizer's RAD_PRE_* constants; this branch's grew
RadBuildCtx by the trailing cvec pointer, which is that struct's offset 112 of 120. Both
trees said 25, and core/plugin/loader.cpp compares nothing but that number, so the one
direction that matters -- an engine from this branch loading a plugin home built from
1.10.0 -- was accepted: qwen4exp reads ctx->cvec at declare (qwen4exp_fp8.cpp:951) out of
an eight-byte-shorter struct, past its end, and treats whatever follows as a direction
table. The PR's own note, that an engine from here refuses an older home and names the
stale .so, was no longer true for the release it now merges.

26 it is, with the layout table and the snapshot constants saying so. ABI 25 keeps
meaning what shipped.
2026-10-21 09:26:17 +02:00
C_Tamas 4141988217 data: ship the published qwen4exp vector in the plugin home
Discovery's third path, <home>/vectors/<arch>-control-vector.gguf, was the one an operator could
never rely on: it existed, but nothing filled it, so a deployment had to fetch Cudecnik's package
and rename two files before the switch was worth anything. The published file is small (483 KB),
specific to this architecture and width rather than to any one quant, and unchanged from upstream,
so it belongs with the other things the home ships next to architectures/ and kernels/.

CMake copies the GGUF and its JSON into the built home (and installs them under the data dir), which
means a missing file is a configure error rather than a silently missing feature. Discovery order is
unchanged, so the per-container and per-directory sidecar paths still win when an operator places one.

The directions are a derivative of Qwen3.8-Flash-Next and are not ours to relicense: they stay under
the Qwen Community License 1.0, whose text now sits beside them (data/vectors/LICENSE.qwen-community-1.0.txt),
is recorded in NOTICE, and is installed to share/doc/radiance/third_party/qwen-community.LICENSE. The
Apache-2.0 grant covers the loader and the kernels, not the directions.

The feature is still opt-in -- without --control-vector the file is never read -- and the request
default is still off, because what this particular vector removes is a safety behaviour.
2026-10-21 09:26:17 +02:00
C_Tamas f5cb4b8ff3 server: the panel names the family the vector was validated against
The summary line led with the layer range, which is the least load-bearing term on it: a file
carrying another model's directions is refused at startup, so the range alone never tells the
operator whether this vector belongs to the model on the card. The panel now reads
`qwen4exp · layers 4-44 · project · scale 1`, with the family taken from the same
`meta_.arch_id` the loader compared against the file's `controlvector.model_hint` -- served as
`arch` in the payload, not invented by the page.

The switch's label says what it does rather than what it is called, and the note under it says why
the change is not retroactive: a running request keeps the choice it was admitted with, and a
session with a refusal already in its context may repeat it.
2026-10-21 09:26:17 +02:00
C_Tamas f9d80d6cac control vectors: load only when the deployment asks
The graph is declared once, so whether the projection op exists cannot follow a per-request
switch. It follows a startup flag instead:

  --control-vector off       load the vector found for this model, requests default off
  --control-vector on        the same, requests default on
  --control-vector disabled  load nothing (also the default with no flag)

`disabled` declares no op, so an unprojected request costs the stock model's launches rather
than 41 empty ones; a request that asks for the vector is refused by name and the admin route
answers 404. `off`/`on` keep the per-request switch and the dashboard default.

Measured four ways on one box (stock, disabled, off, on -- one boot each, six 4,096-token answers,
speculation off): decode 85.1 / 86.1 / 83.7 / 82.8 tok/s. `disabled` is the stock graph, so there
is nothing to pay; `off` pays the 41 launches, `on` pays the projection. KLD mode serves no
request to carry the switch, so `--control-vector on` is how the projection itself is scored;
config_test covers the three states and the absent default.
2026-10-21 09:26:17 +02:00
C_Tamas b15cbb546d docs: the switch's effect and the off guarantee, measured on this box
GUIDE 4.10 carries numbers instead of assertions: the first-token table over 18 policy prompts
(stock / off / on inside one boot, KL over the union of both top-20 lists), the engine's own KLD
metric over eight boots a side (off 0.021-0.075 mean KL, median 0.044, against unmodified stock's
own floor of 0.019-0.095, median 0.046; permutation p=0.96), and the finding that the boot-to-boot
spread is bimodal (~0.02 or ~0.08 mean KL, top-1 ~96.5% or ~92.5%) and wider than any neutral-text
effect the switch has. The measurement runs are what took the space; the result is one table and a
paragraph about what can and cannot be claimed from this box.

libavx's README transcript is refreshed to 1.9.0's counts (924 checked per ISA level).
2026-10-21 09:26:17 +02:00
C_Tamas ad7c962375 core: only the package's layer range steers, and the table stays out of the budget
The loader stored a norm for every direction in the file, and the plugin declares
an op wherever a layer's scale is nonzero, so `layer_range` (4..44, the package's
own selection) reached only the range checks and the log line: the engine steered
all 47 directions -- 94 hc_project instances in the declared graph where the
sources and the docs say 41. The scale is zeroed outside the range now, which is
what RadControlVector documents ("a zero scale means this layer is not steered")
and what llama.cpp's patch does (its tensor is absent outside the range).
cvec_test asserts it for the default and for a JSON-stated range; --debug-graph
shows 41 a rank.

The direction table is also taken back out of the VRAM budget
(VramFacts::held_out). It is allocated in declare(), before vram_budget_resolve
reads free VRAM, so without the term the pools are planned around bytes the
program never sees. On this box the split came out identical either way
(claimable 12.92 GiB in both), so the term is a guarantee by construction rather
than a fix for an observed miss -- and it keeps a deployment that merely offers a
vector on the same plan as one that does not.
2026-10-21 09:26:17 +02:00
C_Tamas 071d204252 server: a null control_vector is "not sent", and the alias yields to the field
Reading the field's own name last made a null canonical value win over a
non-null alias (JSON null leaves the parsed bool untouched, so it became an
explicit off) and made a malformed alias fail a body whose canonical field was
valid. The loop now walks the field first, skips absent and null keys as the
rest of the parser does, and stops at the first one it finds: the field wins,
null means "the deployment's default", and the alias is only read when the field
is not.

server_test covers both -- a body with both spellings, and a null field with the
default on -- and cvec_test pins n_dirs, which the startup line now prints.
2026-10-21 09:26:17 +02:00
C_Tamas cd1f2f59cc docs, comments, tests: a consistency pass after the kernel move and the 404
Stale text that outlived the fixes around it: the deleted unit's filename in
libr4d's gated-residual comments, hc_project missing from that unit's header,
"THE SPEED PROJECTION" heading the page's control-vector code, ABI 22 comments
beside a table that says 23, a projection_test header crediting rad-kbench with a
case it does not have, a comment stating the wrong scale arithmetic, a duplicated
<cstring>, and GUIDE's "off in all cases" (the admin switch flips it). libavx's
README transcript is refreshed from a real run (807 checked, at every level).

And the test the alias order needed: a body carrying both `control_vector` and
`experimental_speed_projection`, with the field's own name winning.
2026-10-21 09:26:17 +02:00
C_Tamas d09d733b07 core: bound the loader's layer index to the table it fills, and log the file's own count
The direction table is indexed by layer (row 0 unused) and sized n_layers, so a
file carrying direction.<n_layers> passed the range check and then wrote one
row past `dir`, and a package JSON whose range ended at n_layers read one past
`scales`. Both bounds are exclusive now, and cvec_test covers each: direction.48
of a 48-layer model, and a JSON range 4..48 on the same model.

The startup line printed `n_layers - 1` as the direction count -- the published
file's count, but wrong for a file carrying fewer directions; the loader records
what it read and the line prints that. Also drops an unused <cstring>.
2026-10-21 09:26:17 +02:00
C_Tamas f3979aa538 docs, tests: say what the branch does, and test what the docs say
Review found four places where the branch's prose had outrun its code:

  - docs/GUIDE.md 4.10 promised that an incompatible sidecar "stops startup" two
    sentences after promising it is "reported and skipped" (the code warns and
    serves without it), and claimed deployment-level bit-identity for a request
    without the vector, which the PR explicitly withdraws. Both now say what the
    engine does; the wording is core/cvec.h's, which already had it right.
  - cvec_test claimed discovery order and a range past the model in the PR, but
    neither case existed. Both are there now, reusing the file writer and load()
    the file already had, so discovery -- the branch's policy choice -- has
    coverage at all.
  - the libr4d row descriptions still said "experimental speed projection" after
    the naming commit, and pointed at the unit that no longer exists;
    ref_hc.cpp's comment had a duplicated clause.
  - /stats' `n_layers` reported the direction count (47 of 48 layers); it is the
    model's layer count now, with first/last carrying the range.

The alias is read before the field's own name, so a request that sends both is
read as `control_vector`, and engine.cpp's /server_info comment is back above
engine_info.
2026-10-21 09:26:17 +02:00
C_Tamas 6964d05f75 server: the control-vector switch answers 404 where it has no vector
The route's own comment, server.h and the dashboard's page all say a deployment
without a vector answers 404, and the page uses exactly that to tell "no vector
here" (hide the panel) from "not signed in" (show it, disabled). The handler
answered 501 instead, so such a deployment showed a panel claiming the vector was
present. The route now assembles the same 404 the server uses for a model it does
not serve, and the case that had no coverage -- a deployment without a vector --
checks it. The unreachable 405 arm goes: only GET and POST are registered.
2026-10-21 09:26:17 +02:00
C_Tamas cac79bb3ba libr4d: hc_project takes one direction for every stream, reduced at the wave's width
The device kernel did not implement the operation core/cvec.h states, in two ways
found with a card probe (one row, n 2560, hc 4, through the plugin's own entry
point):

  - it offset the direction by the stream (`v + blockIdx.y * v_ld`, with v_ld
    falling back to n), so each hyper-connection stream was projected along a
    NEIGHBOUR layer's direction -- rows of the table the caller never named, and
    past its end when the range ends at the last row. libref and libavx both use
    one v for all streams, as the package's JSON does;
  - its block reduction used `__shfl_down(acc, off, 64)` under a 64-lane "wave"
    bookkeeping, but gfx12 runs wave32 and nothing sets -mwavefrontsize64, so half
    of each 64-group's partials never reached LDS: one application left h.v at
    0.45 where the operation leaves 0.

Now one workgroup per (row, stream), the direction read once per stream, and the
reduction is the house one (r4d_wave_sum, a partial a wave in LDS, kWaves 32).
The entry refuses a [hc, n] direction table by name instead of reading it as one
direction a stream.

The kernel moves into the gated residual's unit (r4d_hc_bf16.hip), which already
has kWave/kThreads/bf2f/f2bf and the hc_common operand checks: one file fewer and
89 lines fewer than the standalone unit, and no duplicated reduction or conversion
code.

Measured through r4d_rad_hc_project after the change: each stream's h.v ends at
1e-3..6e-3 (bf16 rounding; rel_l2 1.6e-3 against the operation computed in
double), a row with `on` 0 changes 0 of its 10240 bf16 values, and a [hc, n]
table is refused. ctest -L fast: 80 of 82, the two failures environmental
(videos_test needs FFmpeg, ops_doc needs gawk, absent from rad-toolchain).
2026-10-21 09:26:17 +02:00
C_Tamas 40f7390766 naming: comments and log lines say control vector, not speed projection 2026-10-21 09:26:17 +02:00
C_Tamas 3e9e0f4d03 tests: the switch's semantics, the operation's arithmetic, and the loader's refusals
cvec_test writes control-vector GGUFs and checks what loads and what must not: the published shape,
the package JSON setting range and scale, a wrong architecture or width, a gap in the range, a
non-controlvector file. projection_test pins the per-row mask (a mixed step projects one
conversation and not the other) and launches libref's hc_project against an independent computation,
including the untouched disabled row. ref_test gains the operation's behavioural case, its
vocabulary entry and a sweep geometry.
2026-10-21 09:26:17 +02:00
C_Tamas 6f26cdb5f4 server: a control_vector request field, its admin switch and the Model-view panel
The field is per request, with the deployment's runtime default when absent, and a deployment with
no vector refuses 'true' by name rather than serving the stock model. Strata's
`experimental_speed_projection` is accepted as an alias.

The dashboard's Model view carries a "Control vectors" panel with the switch for that default;
GET/POST /admin/control-vector is its endpoint, behind the API key like every other route. The state
is in /stats and /server_info. Nothing here reloads the model: the directions are uploaded once and
each step carries a per-request mask.

The panel stays visible when the page has no API key, with the reason, instead of disappearing --
a control that vanishes because the page has not signed in reads exactly like a build without the
feature.
2026-10-21 09:26:17 +02:00
C_Tamas 66c6d71254 sched, mem: the per-request switch reaches the device, and the cache keeps the modes apart
`projection_on_rows` expands each request's choice across its tokens once per step, into the int32
mask hc_project reads; rows outside every sequence are zeroed first, so the reused arena region can
never carry a previous step's flag.

The prefix cache keys a projected request's blocks on the vector itself, through the same extension
point the runtime LoRA adapter uses: one content key spanning the whole sequence, pushed into
`media_keys` beside the adapter's, so every block overlaps it. Blocks and linear-state checkpoints
(whose keys are the same chained hash) therefore never cross modes; an unprojected request, or a
deployment with no vector, adds no span and hashes exactly as before, and an adapter and a vector
compose.
2026-10-21 09:26:17 +02:00
C_Tamas 809257e393 arch/qwen4exp: the control vector's projection after every block's write
HcProject in arch/common/rad_block_hc.h owns the block: its per-token switch buffer
(`projection_on_rows`, a derived buffer), the per-layer op and the issue point. The plugin declares
it with one call per layer and issues it with one call after the feed-forward write -- the place
llama.cpp's build_cvec(res_hc, il) sits in the qwen4exp graph, in both the serial and the pipelined
step. An unsteered layer, or a deployment with no vector, declares nothing and issues nothing.
2026-10-21 09:26:17 +02:00
C_Tamas 459dd4f42d vocabulary: hc_project -- a control vector's direction, projected out of the wide stream
h[s] -= scale * (h[s] . v) * v        for each of the hyper-connection streams s

llama.cpp's --cvec-mode project semantics: the dot is per stream, because the patch applies it to
the [n_embd, hc, tokens] view where mul_mat(v, cur) reduces over dim 0. v is one layer's unit
direction (f32), scale is the norm its file stored, and 'on' is a per-row int32 switch: a zero row
is skipped without a read or a write, so an unprojected request is byte-identical to a deployment
with no vector loaded.

libref is the oracle and the host fallback, libavx carries it at every ISA level, libr4d (one
workgroup per (row, stream), LDS reduction) serves the card. docs/OPS.md gains the row and the
operation's three facts.
2026-10-21 09:26:17 +02:00
C_Tamas 64adee3ece core: a control vector loaded from a controlvector GGUF, discovered per model family
A control vector is one unit direction per layer, applied to the residual stream while the model
runs (llama.cpp's --cvec-mode project). This is the loader and its ABI, with no configuration
surface: a vector is a property of the model family, so the engine looks for one beside the
container, in its directory or in $RADIANCE_HOME/vectors, and uses it when it fits the container.
The operation's parameters (layer range, scale, mode) come from the package's own JSON.

Validation is against the container, never the file's provenance: architecture hint, direction
width against n_embd, every layer in the range present, F32 rows. A discovered file that does not
fit is reported and skipped; the switch stays off until a request asks for it.

The ABI grows by one trailing, zero-defaulted field (RadBuildCtx::cvec), so an architecture plugin
that ignores it is unchanged, and the cache gains a salt (0 without a vector) that keeps blocks and
linear-state snapshots of one mode from being reused by the other.
2026-10-21 09:26:17 +02:00
Deadcode aa12f79579 device: run cards with a small PCI BAR by keeping kernel arguments in host memory
A card whose PCI BAR spans less than its VRAM was refused at startup, because the kernel argument ring is written by the host and the runtime maps such VRAM PROT_NONE. Instead, place the ring, and a recorded pass's argument blocks, in a pinned host memory pool and grant them to the card, as HIP's own launches do; every dispatch then reads its arguments across the link. A card whose BAR spans its VRAM keeps its arguments in VRAM, unchanged.

RADIANCE_DEBUG_AQL_HOST_KARGS forces the host-memory path on a card that needs no fallback, to measure the cost.
2026-10-21 09:26:02 +02:00
keptn42 1431838a9a deploy/compose, README: Ornith-1.5-35B-A3B w4a8 container
Two compose files (two cards, one card) and a row in the models table.
2026-10-21 09:25:49 +02:00
keptn42 6908377f3d qwen35moe: read the experts' stored format, serve four-bit experts, calibration tap
Probe the expert encoding as qwen4exp does, declare the rotated input pair, set the GPTQ
calibration tap, and read expert sources stacked or per expert.
2026-10-21 09:25:49 +02:00
eddie168168andClaude Opus 5.5 e28e2d89f8 qwen35_w8a8: the int8 linears take their rotated codes from the norm and silu producers
- ActFP8::q8_rot marks fed codes as rotated. NormQuantFP8 declares (ar_)rmsnorm_had_quant_i8g and
  GateQuantFP8 declares gated_had_quant_i8g when an activation is fed and rotated. LinearFP8 takes
  fed codes on an i8a8h weight only if their rotation is the weight's.
- The MLP no longer writes the bf16 silu product when the down projection is fed.
- qwen35_w8a8 feeds the normed input and the FFN activation only where libr4d declares the ops
  (at TP2 the all-reduce form too), so the CPU graphs are unchanged.

A decode step's had_quant_act_i8g launches fall from 288 to 64; the 64 left quantise the attention
and delta-net outputs. The codes are the same bytes. On 2x R9700, against 1.9.0 with the RTN
container:
- KL rows are identical, and greedy answers are byte-identical at TP2 and TP1, with acceptance
  unchanged.
- TP2: 33.98 -> 32.87 ms a decode step, 111.2 -> 114.9 tok/s.
- TP1: 55.81 -> 54.59 ms, 62.7 -> 64.1 tok/s.
- Prefill: +2%.

arch_test pins the unfused chain where the ops are undeclared, and the fed path where they are
(had_quant_act_i8g 8, rmsnorm_had_quant_i8g 16, gated_had_quant_i8g 8). The every-op-declared graph
hashes are re-pinned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:25:39 +02:00
eddie168168andClaude Opus 5.5 d999524054 libr4d: rmsnorm_had_quant_i8g, ar_rmsnorm_had_quant_i8g, gated_had_quant_i8g -- producers that write rotated int8 codes
An i8a8h linear quantises its own input from the bf16 plane with had_quant_act_i8g, so a decode
step of the int8 Qwen3.8-27B issues 288 of them after the norms and the silu product. These three
device ops write those codes from the producer instead:

- rmsnorm_had_quant_i8g and ar_rmsnorm_had_quant_i8g (exact and wire=6): norm_quant_row gains an
  HI8 form, r4d_fwht_wave<128> and then quant_group<I8>, on the lane mapping, rotation and rounding
  had_quant_act_i8g uses.
- gated_had_quant_i8g: the gated kernel's existing ROT && I8 instance, which the shim refused.

Each writes the bytes its producer followed by had_quant_act_i8g writes. They are ops of their own,
not a flag on the fp8 forms, as gated_had_quant_fp8 is: a rotated and a plain quantiser must not be
substitutable. n % 128 == 0; device only, so a graph falls back to the pair where they are not
declared.

r4d_selftest checks each against its pair byte for byte (plain, with the residual add and the
residual it leaves, and the gated product) and that each refuses E4M3 codes. The all-reduce form
is skipped like ar_rmsnorm_quant_fp8, since it needs a peer rank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:25:39 +02:00
AshlynandClaude Opus 5.5 3ef9ce33ae core/sample: issue sample_temp only where some row is scaled
The decode timeline shows sample_temp at ~10 us a step on the 31B at tp 4: a launch over every
row's whole vocabulary shard (up to 256 workgroups a row) whose rows all return at once, since a
greedy request under a split vocabulary has temperature 0 and a plain sampled one 1, and the
kernel leaves both as they are. Sampler::run now issues it only when a chain row has another
temperature; every other row's logits are untouched either way, so the tokens are the same. The
request check's note on greedy chain rows now says when run() issues the stage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:25:28 +02:00
AshlynandClaude Opus 5.5 104c81f005 libr4d, core: two first-launch races that could change a fresh server's first reply
Counter blocks: the per-(stream, output) counter blocks of the fp8a8 split-K finisher (split_ctr),
the gated delta-net conv (ru_conv_ctr), the mxfp4a8 decode GEMM and the hc mix are zeroed with
hipMemset, which queues on HIP's null stream and returns before it lands. The engine launches on
queues of its own that need not wait for that stream, so the first launch on a new block could run
beside its own zeroing: a split-K finisher counting arrivals while the memset reset the count gives
that one launch a wrong output. r4d_moe.hip's router counters and the all-reduce's IPC allocations
already wait; these four now do too (hipDeviceSynchronize, once per block).

Seen as a greedy reply that differed on the first request of a freshly started 31B DFlash2 server
(2 of 13 fresh starts on 4x R9700, 2026-10-17; every later request matched): the drafter's fp8a8
GEMMs take split_ctr blocks on their first launch, and a draft that differs moves the verify blocks,
whose rounding the target's greedy choice can feel at a near-tie. No value changes otherwise.

Weight transfers: resolve_weight puts the mover's `ready` wait on the issuing lane's stream, but
remembered the generation it waited on per weight for the whole context. A weight resolved first on
lane 1 then had its wait on lane 1 only, and the lane-0 GEMM resolving it next skipped its own and
could read the slot before the copy landed. The Gemma 4 26B-A4B's dense arm is such a weight: a
decode step issues it on lane 1, beside the routed arm, and an overlapped prefill on lane 0.
waited_gen_ is now per lane, one record for each of the context's two lanes (set_lane admits 0 and
1 only), indexed by lane_ like the other per-lane state: at worst one more stream wait. Inert where
no transfer is in flight (static weights, the 31B on four cards); it matters wherever weights
stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:25:20 +02:00
AshlynandClaude Opus 5.5 82aec1766c libr4d: the windowed attention's split merge loads a group ahead, and its WMMA prefill does less work a key tile
The merge: the 31B's global layers merge their split-KV partials in merge_body
(r4d_attn_paged_window.hip), one wave a row, four splits at a time into one accumulator chain:
~9.4 us a layer on 4x R9700 in the decode timeline. Each group's loads went out only after the
previous group's FMAs, so a row paid one L2 round trip a group. Group g + 1's loads now go out
before group g's FMAs (two register groups in turn; 175 VGPRs at head_dim 512, no spill). The FMAs
and their order are unchanged, so the bytes are too.

The prefill kernel: attn_wmma_kernel (the 31B's global layers at prefill, ~1.1-1.5 ms a 1024-row
slice on 4x R9700) does three things a tile that change no byte:

- fp8 V widens to its f16 pairs with v_cvt_pkrtz: every e4m3 value is exact in f16, so the pack's
  rounding and f16_bits' clamp (unreachable under 448) leave the same bits, for 2 instructions a
  pair instead of ~10.
- A tile wholly inside [lo, hi) and, causal, at or before the block's first position is visible to
  every valid row, so it takes its scores without the per-key masks.
- With an fp8 cache, a wave whose rows all kept their running max (corr exactly 1) skips the
  rescale of O^T: x * 1 = x.

One-card microbenchmark of the three with the skip on both caches (the kernel against the shipped
one, random operands, a 1024-row slice at the end of the context): head_dim 512 gqa 8 fp8 cache
1481 -> 1295 us at context 4096, 657 -> 531 at 2048, 2220 -> 1785 at 6144; head_dim 256 gqa 2 fp8
675 -> 544, bf16 589 -> 511. Every output byte-identical to the shipped kernel's at all four
instantiations (512/8 and 256/2, fp8 and bf16). The skip measured ~4% at head_dim 512 with an fp8
cache, but with bf16 its split loop ran ~10% slower than the fused one (1634 against 1427 us at
context 4096; v_cvt and the interior path alone: 1318), so bf16 keeps the fused loop.
fp8x16_f16, left with no caller, is removed.

The pack is f16x2_exact: v_cvt_pkrtz on gfx12, f16_bits elsewhere (the host SIMT emulator,
tests/r4d_emu, compiles this unit as C++), the same bits since neither rounds a value exact in f16;
r4d_emu_attn passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:25:04 +02:00
AshlynandClaude Opus 5.5 dffec0b770 libr4d: step past the full-card launch cliff in qkv_norm_rope and the row norms
On gfx1201 a launch whose wavefronts fall in the last 32 before a multiple of 2048 (every wave slot
of the R9700's 64 CUs x 2 SIMDs x 16) runs about five times slower than the same work one workgroup
wider, whatever the kernel does. A launch-count sweep on one card (2026-10-17): 256-thread
workgroups take 27.6 us at 253 to 256 of them and 5.2 us at 252 or 257, for a norm, an LDS-only
kernel and a plain copy alike; 128- and 512-thread workgroups hit it at the same wavefront counts.
An empty kernel does not, and moving the data does not move it.

The 31B lands on it: qkv_norm_rope at a tp-4 verify is 16 rows x 16 heads of 8 wavefronts, exactly
a full card (21 us a call against ~6 expected; kbench's one-card 4-row point, 256 workgroups, 17.4
us against 5.3 at 8 rows), and a drafter's 256-row head norm through rmsnorm likewise (21.9 us).

r4d_cliff_rows(rows, per_row, waves) is the row count to launch: `rows` when clear of the window,
else the first count past it. qkv_norm_rope, rmsnorm and rmsnorm_p launch that many and return at
once in a row at or past the real count, so every result is the same bytes. r4d_selftest's
qkv_norm_rope case gains 8 rows of the head-256 class (32 heads a row: 256 workgroups, padded).

The window's two numbers are the R9700's, named as such in r4d_common.h, and apply on every target
libr4d builds for (RDNA4 only). They are not derived from the device: no other card has been
measured, and HIP's multiProcessorCount counts WGPs, not CUs, on RDNA. On an RDNA4 part with fewer
CUs a launch padded here costs one idle row and gives the same bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:24:52 +02:00
AshlynandClaude Opus 5.5 13a917910f libr4d: rmsnorm_quant_i8 at decode heights loads the row's operands before its reductions
The kernel re-read its row from memory in each of three passes, each behind a barrier, so a
row cost three dependent round trips: 11 us a launch at any height on gfx1201 against a 4.2 us
launch floor. Every pass partitions the row the same way, so at 1024 threads (M <= 32, n <= 8192)
each thread now loads its own columns of the branch row, the residual and both gains in one go
and keeps them in registers; only the fragment-order store crosses threads, through LDS as
before. Same sums in the same order and the same per-element arithmetic, so the same bytes.
8.2 us a launch in a four-card microbenchmark at 1, 4, 8 and 16 rows of 5376.

The row gains a reg axis (1 the new form and the default, 0 the old), and the selftest checks
both forms against the unfused chain at M=8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:24:39 +02:00
AshlynandClaude Opus 5.5 3251975384 arch/gemma4_bf16: the embedding scale as the reference rounds it, 73.5 and not 73.32
Gemma4TextScaledWordEmbedding multiplies the looked-up rows by `embed_scale.to(weight.dtype)`,
which is sqrt(5376) rounded to bf16: 73.5. gemma4_bf16 multiplied the trunk's embedding by the
unrounded 73.32, and the assistant head's entry, which reads the trunk's embedding module, did the
same. The first layer's norm hides a 0.25% scale, but the residual stream every later layer adds to
does not. arch/gemma4 has taken the bf16 value since it was written (53.0 at 2816).

Both now take embed_scale(n_embd), the bf16-rounded value. arch_test's two checks of the scale
expect 73.5, and its three pinned gemma4_bf16 graphs move with the `mult` they record; no other
model's pin moves.

On 4x R9700 at tp 4 the replies move against main's, as a 0.25% scale on the residual stream
would (7 of 7 long prompts, drafter off). A drafter trained on the reference's hidden states
tracks the corrected stream better: z-lab's DFlash drafter (the next change) accepts 2.88 tokens a
step over seven 2-6K-token prompts against 2.71 with the scale unrounded, and 5.21 against 4.91 on
a code prompt (270 against 259 tok/s).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:24:25 +02:00
eddie168168andClaude Opus 5.5 21d6b7836e tests: place_test takes the VRAM readings once they hold still (#124)
a_mover_gives_back_every_event_and_device_byte compares the process's KFD VRAM after two
identical runs. Each stream is a hardware queue, and KFD gives every queue a context save area
(the topology's cwsr_size + ctl_stack_size, 29.3 MiB on a 64-CU RDNA4 card) that can be released
a few milliseconds after the queue is destroyed. A reading straight after the test's streams are
torn down sometimes still held it: on 2x R9700 the check failed about 1 run in 5, by exactly
30765056 bytes, and polling showed the figure back within 10 ms.

settled_vram reads process_vram every 10 ms until 100 ms pass without a change, for at most 2 s,
and both readings use it. The warm-up run and the 2 MiB + 4 KiB allowance stay. Back to back on
the card, place_test -perf_ passed 17 of 20 runs before and 20 of 20 after; the host backend
passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:24:15 +02:00
AshlynandClaude Opus 5.5 5f78a1d0cd libr4d, arch/gemma4_bf16: at four ranks the 31B's junctions carry the all-reduce in front of them
ar_rmsnorm_quant_i8_4rank is the wide family's exact four-rank one-shot with the junction (the
residual add, the sandwich norm and the int8 quantiser) as its epilogue, as ar_hc_write_4rank is
that one-shot with hc_write. The reduce is the standalone exact all-reduce's arithmetic element by
element (fp32 from zero, ranks ascending, one rounding to bf16), so the reduced row matches it to
the bit, and the junction is rmsnorm_quant_i8's over that row. It shares the standalone
all-reduce's transport and instance and ends the engine's link hold itself, as docs/TP4.md asks of
a new collective row.

Every block takes one handshake, a system-scope release by its first thread and a system-scope
acquire by every wave. Both fences are needed: on 4x R9700 behind an EPYC root complex, dropping
either left the readers with stale scratch on nearly every element. `nblocks` 2 and 4 (fewer
handshakes, each block owning several rows) are tune points, off by default.

r4d_selftest's case of the same name holds every rank's reduced row, residual, output, codes and
scales byte for byte to all_reduce followed by rmsnorm_quant_i8 on four cards, at 1, 8, 40 and 97
rows of 5376 and 64 rows of 2816. r4d_selftest is now installed in the image, so a card box can run
the rows' checks without a build tree.

At four ranks a 31B decode step issued 121 standalone all-reduces, 119 of them followed by a
separate norm launch. The plugin now declares ar_rmsnorm_quant_i8_4rank for steps of up to 4 rows
(kAr4FoldRows), where it serves every junction but the last layer's feed-forward one: a decode step
issues 2 standalone reductions. Taller steps, every speculative verify among them, issue the pair
(the all-reduce, then rmsnorm_quant_i8): a one-shot sends three times the message a rank, and at 16
rows the standalone all-reduce's exact two-shot beats the fold's per-row handshakes.

On 4x R9700 (the w4a8 container, tp 4, two rounds): plain decode 90 / 90 / 89-90 tok/s against
86 / 87 / 86 for code / prose / story, and 85 against 82 after a 6442-token prompt, +4.7%; a
DFlash verify at 16 rows measured 300 tok/s on the pair against 276 on the fold, hence the band.
Both paths give the same bytes. Where no library declares the fold, every step issues the pair.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:22:06 +02:00
gearwave00001andClaude cd393a0973 keyframes: feed endpoint keyframes through the vision tower (TE-anchor tokens)
Image-conditioned MiniMax-H3 (I2VA/L2VA/FL2VA = first_frame/last_frame) rendered
over-saturated / posterized while T2VA was clean on the same container. Root cause:
the reference conditions a keyframe TWICE -- a vision-tower anchor (clip.tokenize
images=[kf] -> <Picture N> soft-tokens in the text conditioning) AND a VAE-latent pin --
but Radiance did only the VAE pin for endpoint keyframes. The absent semantic anchor
left the DiT reconstructing the frame from low-level VAE pixels alone -> posterize /
black-outline / oversaturation.

Route endpoint keyframes through the existing vision-tower media path, so they produce
<Picture N> anchor soft-tokens in addition to their VAE pin (the reference's dual
channel). No new kernels, no ABI / arena change: build_cond stages r->media generically
and the arch scatter is the generic op_mm.

  - videos.cpp: keyframe index = <Picture> ordinal (first=1,last=2); stable-sort keys
    by kind before merge; run the prepare+placement loops for FIRST/LAST_FRAME as well
    as IMAGE (area-matched tower form, aspect-kept; the exact-canvas VAE pin is a
    separate, unchanged second encode); budget wording covers keyframes.
  - video_driver.cpp: a towerless container no longer refuses a keyframe request (skip
    FIRST/LAST_FRAME in the "needs a vision tower" scan) -> pin-only path runs; the
    encodes guard still requires the VAE encoder and now labels a keyframe correctly.

Device A/B (uncensored w8a8, TP2, seed 1234, 512^2): prompt tokens i2va 27->291,
fl2va 1560->2088 (the +256 / +2*256 keyframe vision tokens + labels), t2va 27->27.
T2VA output is bit-identical across binaries (text path untouched). Image-conditioned
output diverges (cos 0.77/0.80): the realistic I2VA mid-frame recovers foliage
structure (blobs -> trees), softens outlines and shadow detail toward the clean control;
FL2VA gains semantic adherence (prompted "wings spread" now renders). Endpoint-pin
cosine unchanged (0.971 / 0.988 / 0.980, at/above the 0.985 bar). No budget reject.

Tests: fl2va keyframes now feed the tower and still pin the ends (index 1/2, token
stream with both vision blocks); towerless fl2va pins-only; driver-level keyframe
conditions through the tower and needs no tower. NOTE-REF2VA.md #8 closed.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-21 01:06:26 -05:00
gearwave00001andClaude 8785774fc0 sampler: res_multistep (DPM++2M data-pred) as a per-request field; ABI 24
Radiance's video denoising had only first-order Euler. The DaSiWa reference
workflow samples MiniMax-H3 with res_multistep + simple, so add it as a second
order option, exposed as a `sampler` field on /v1/videos (default euler).

New op `flow_res_multistep` across all three kernel tiers (device==avx==libref),
closed form reusing the driver's per-step scalars:
  x' = r*x + hb1*den + hb2*x0,  den = x + sigma*v,  r = sigma_next/sigma
  order 2: h=ln(sg/sgn), h_last=ln(sg_prev/sg), r_s=h_last/h,
           hb1=(1-r)(1+1/(2 r_s)), hb2=-(1-r)/(2 r_s)
hb1+hb2 == 1-r, so it collapses to Euler when x0==den. Order 1 (Euler) is forced
at the first step, the first full-size step after a latent upscale (stale
history), and the last step (sigma_next==0); order 2 otherwise. The previous
denoised estimate persists in new PERSIST buffers b_vx0/b_ax0. Verified equal to
k-diffusion sample_dpmpp_2m to 5.6e-17 on three sigma grids.

- ABI 23->24: trailing int32_t sampler on RadVideoGenBatch; RAD_SAMPLER_EULER=0
  / RAD_SAMPLER_RES_MULTISTEP=1 in rad_runtime.h.
- driver: R_SCHED region widened 6->16 f32 ([0..5] Euler, [6..10] video coeffs,
  [11..15] audio); step_dit branches on V->sampler.
- server: `sampler` string field ("euler"/empty, "res_multistep", else
  invalid_request_error with the supported list); echoed on the job object;
  capabilities advertise video_samplers.

Tests: rad-avx-check 816 + 451 hand-built, 0 fail (left-assoc grouping matches
ref/device at tol 0); r4d_selftest --case flow_res_multistep_f32 f32|bf16 x
order {1,2} exact, both INOUT pitch gaps untouched.

Device-verified (TP2, fp8 container, 256^2/2s/10-step, seed 1234 identical):
both samplers complete clean 73-frame h264; outputs differ (branch genuinely
consumed, not ignored); bad value rejected; field omitted -> euler. res_multistep
renders warmer/higher-contrast than euler -- a tone lever, not an over-exposure
fix. The euler default path is unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-20 18:28:49 -05:00
zivius b1f4fccc52 docs: drama-3's voice cloning -- the references field (clips, transcripts, speakers), its limits and cost, the encoder against fish-speech's, and how closely cloned takes follow their reference 2026-10-21 01:00:13 +02:00
zivius 871aa7dd97 fishomni: voice cloning -- Fish S2's codec encoder (strided causal convolutions, a windowed transformer, two downsamplings and the residual quantiser) over a request's reference clips, their frames embedded as made frames are, the tower teacher-forced with them as fish-speech's prefill does, and the window of main picks seeded from the prompt; the reference prompt with each transcript tagged as the prompt builder tags it 2026-10-21 01:00:13 +02:00
zivius bdc5c5b063 core: references for an audio generator -- a request's clips of a voice and their transcripts (RadAudioGenDecl::tmpl_ref, ref_item), decoded to mono at the model's rate and padded to whole frames, each frame a prompt row the plugin encodes in the PROMPT pass (RadAudioGenBatch::ref_audio, ref_cu, ref_frame); /v1/audio/speech's and the streaming session's references 2026-10-21 01:00:13 +02:00
zivius 4e750fed01 libref, libavx, libr4d: conv1d's stride and cu_div, and vq_encode -- a causal codec encoder's downsampling (the left pad the reach less the stride, every sequence a whole number of strides, the bounds read in samples at every rate) and one step of its residual quantiser, the code of greatest cosine and the residual it leaves (Fish Audio's codec encoding a reference) 2026-10-21 01:00:13 +02:00
zivius 00f9703892 fishomni: sampling as SGLang-Omni draws -- temperature 1.0 and top-p 0.9 from Fish Audio's model card, the main token uncapped and each head at top-k 30; at fish-speech's server settings the model fell silent after a tag or a speaker's line in 8 of 40 short takes, here in none 2026-10-20 23:07:48 +02:00
zivius d886e4d0ab docs, compose: Fish Audio drama-3 -- the architecture with its traps and measured parity against fish-speech, serving it (speaker tags, direction in the input, the length, sampling), its recipe and compose file, and its licence 2026-10-20 23:07:48 +02:00
zivius a01d1c1cd5 fishomni: Fish Audio drama-3 -- the Qwen3.5-35B-A3B backbone with its block-fp8 experts at f32 scales, a 13-layer codebook tower over the backbone's full-attention cache, the main token over 4097 candidates with repetition-aware sampling, and Fish S2's modified DAC read from codec.pth; one branch on two cards, the input's speaker turns written as fish-speech's server writes them 2026-10-20 23:07:48 +02:00
zivius f201c140ab core: a frame pass names the row before the frame's own -- its KV slot, position and context, for a frame head that attends at the row its hidden state comes from (Fish Audio drama-3's codebook tower) 2026-10-20 23:07:33 +02:00
zivius 346efdeb2e libref, libavx, libr4d: rvq_embed's clamp -- a code past a codebook smaller than the heads that wrote it reads the codebook's last row, as Fish Audio's codec reads its 1024-entry residual codebooks 2026-10-20 23:07:33 +02:00
zivius 832a88faac core: a speech model without instructions, and a refusal's reason from its text_prepare -- an audio generator may declare tmpl_plain alone (a request's instructions refused by name), and the reason a plugin leaves in the output buffer reaches the caller 2026-10-20 23:07:33 +02:00
zivius 61abb990ab core/format: a torch.save checkpoint beside the safetensors, read as data -- stored zip entries mapped, the pickle run by a weights-only machine that refuses any other global or opcode by name; hfget fetches a .pth that is not the weights again (Fish Audio drama-3's codec) 2026-10-20 23:07:33 +02:00
zivius baf6e89ecb core: an audio generator of one branch over a hybrid language model -- the driver stages a delta net's state and convolution groups beside the paged one, with each entry's context and num_accepted, the generator loop zeroes the slots a request is granted, and a model may read its input with special tokens (its speaker tags) 2026-10-20 23:07:16 +02:00
zivius 0c35fc8070 libref, libavx, libr4d: cfg_topk_sample's top_p and ras_pick -- Fish Audio's nucleus over the whole candidate set, cut before the top-k, and its repetition-aware choice between two draws 2026-10-20 23:07:16 +02:00
zivius 8a993b7de9 libavx: spread the 5-bit codes without _pdep_u64 -- BMI2 is not in level 3's flag set, and clang refuses to inline the intrinsic without it 2026-10-20 23:07:16 +02:00
gearwave00001andClaude c8c8f93789 docs: document WebM/VP9/AV1/Opus in the Docker build for the image maintainer
/v1/videos now emits webm (VP9+Opus) and webm-av1 (AV1+Opus) as well as mp4.
docs/DOCKER.md gains a "Video output: MP4 and WebM" section covering what the
ffmpeg stage must enable, the runtime shared libs (libvpx9/libaom3/libopus0) the
rootfs ldd-chroot gate pulls transitively (they are link-time deps of libavcodec,
not dlopen), the BSD/no-GPL license posture, the graceful mp4-still-works path,
the 32k->48k Opus resample, and no-card verification. Fixes the stale
"three encoders" comment in the Dockerfile header.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-20 14:41:39 -05:00
Deadcode 4246a1dd04 radiance 1.10.0
LoRA for image and video generators:
- civitai and Hugging Face adapter files as published: kohya, ComfyUI and diffusers/PEFT key names;
  LoRA, LoCon, LoHa, LoKr and full-weight diffs; DoRA, OFT and Tucker are refused by name
- stacked per request with a strength each, through the `loras` field or <lora:name:strength> tags
  in the prompt; --lora-dir serves every file in a directory, GET /v1/loras lists them, and
  --max-loras / --max-lora-rank size the slots on the card (generators default to rank 64)
- Krea 2, Qwen-Image 2.1, FLUX.3 [klein], MiniMax H3, LTX-2.5, Anima and SDXL

New models:
- Anima (base, aesthetic and turbo): Cosmos-Predict2 DiT with the Qwen3-0.6B text encoder and the
  Qwen-Image VAE, on one card
- Stable Diffusion XL and its single-file finetunes (Illustrious, NoobAI including V-Pred, Pony),
  read as civitai ships them, with the Euler, Euler a and DPM++ 2M samplers

Recipes:
- q38-27b-mxfp4-df2: any bf16 Qwen3.8-27B or finetune at MXFP4 with the DFlash2 drafter
- Krea 2 finetunes from civitai: scripts/krea2_native.py reads Krea's own key names, and
  krea-2-fp8-unscaled keeps a plain-fp8 file's codes exactly

Changes: --max-num-batched-tokens defaults to 2048 (was 8192). Plugin ABI 25: out-of-tree plugins
must be rebuilt.
2026-10-20 21:05:16 +02:00
gearwave00001andClaude ad7e0f8b89 server: /v1/videos writes WebM (VP9 and AV1) as well as MP4
A `format` field chooses the container a generated video is written in:
mp4 (the default, H.264 + AAC, unchanged) or webm (VP9 + Opus) or webm-av1
(AV1 + Opus). Old-hardware users -- this box's CPU is Zen 3, AVX2 only --
get the browser-friendly WebM the DaSiWa workflow ships without a fragile
client-side re-encode, and both webm codecs so either a VP9-friendly or an
AV1-parity file is available.

core/mm/mp4.{h,cpp} become core/mm/video_out.{h,cpp}: Mp4Writer generalises
to VideoWriter with a VideoFormat enum, branching the muxer, the video
encoder (libx264/libopenh264 for H.264, libvpx-vp9, libaom-av1/libsvtav1),
the rate-control options and the audio codec. Opus encodes only at 48 kHz,
so a WebM soundtrack is resampled to 48 kHz with libswresample (the model's
is 32 kHz); the encoder is fed packed FLT at its fixed frame size, AAC keeps
the planar FLTP path at its own rate. faststart and the shift_data reader are
MP4-only; WebM writes forward. Each codec/muxer is runtime-discovered and a
missing one fails open() with a message naming it, so the mp4 default always
works.

videos.cpp parses `format` (mp4|webm|webm-av1, mp4 default, refusing any
other name), threads it to the job and the writer, serves the file under the
matching content-type and a .webm/.mp4 Content-Disposition, echoes `format`
in the object, and advertises video_formats in the capability block.

The Docker FFmpeg build gains libvpx/libaom/libopus and the webm/matroska
muxers (all BSD, so the LGPL posture holds) and their runtime libraries.

Verified host-side: the videos_test webm case writes a real VP9+Opus file
(completed on libvpx-vp9, EBML magic + content-type + disposition checked);
a standalone writer harness produced mp4/webm/webm-av1 at 512x512 with stereo
32 kHz audio -- ffprobe reports h264+aac@32k, vp9+opus@48k and av1+opus@48k
respectively, and all three decode in software on this AVX2-only box.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-20 11:51:52 -05:00
gearwave00001andClaude 0fe7771210 minimaxh3: fuse the int8 modulated-norm producer, dropping the bf16 plane
b025018's W8A8 DiT path unfused the norm: rms_mod wrote a bf16 plane and
each int8 linear re-quantised it. That bf16 plane grew the activation arena
14.41->15.54 GiB, which left vram_kv=0 and the server aborted at startup.

Mirror the E4M3 path instead. rms_mod_kernel gains a third quant mode (i8),
sharing r4d_q8.h's q8_top/q8_pack4 with the int8 quantiser, exposed as the
new rms_mod_quant_i8 op; the block's modulated norm now writes a_hm's int8
code pair directly (a_hm is q8_fed, so qkv/gate_up read the codes with no
per-linear quantiser) and a_hm carries no bf16 plane. ActFP8::cq()/cs()
resolve the pair by trunk format, so the norm producer and both step issues
collapse to one path. LinearFP8's int8 guard now demands the bf16 plane only
when it quantises itself, matching the fp8 branch, which never required it.

Arena is back to fp8 parity (243 buffers, vram_kv 938 MiB); the container
serves at TP2 and renders all five task types device-clean.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-20 10:40:03 -05:00
Juup a36f91947b docs: document OCR encode concurrency and link the container
--mm-max-patches now says that a pass is not one tower invocation (8 tiles
per weight read at most, 4 at the 64 grid with the default pass), and the
Unlimited-OCR section explains the pass-per-geometry queue, the measured
TTFT ladder, the activation cost of batching, the tuning order and the
decode batching limit. Link the converted container
(Aijuus/unlimited-ocr-bf16) from the model table and the guide.
2026-10-20 15:39:42 +00:00
Juup 912c57cb21 unlimitedocr: prefill and decode performance work
- sam_attn: tile queries and hoist the relative-position dots; the tower
  drops from 0.44-2.09 s to 0.10-0.36 s per tile.
- processor: split OCR patch/LUT staging across rows, then make both bicubic
  passes and the LUT append AVX2 (bit-exact, 1.15-1.38x host preprocessing).
- tower: batch the DeepEncoder across every tile segment of an encode pass.
  Patch embed, the 12 SAM blocks, neck, the 24 CLIP blocks and the projector
  run once per batch of up to 8 tiles (4 at the 64 grid); sam_attn and
  attn_dense stay segment-independent through B+1 cu tables, and position
  tables are host-staged PERSIST planes. B == 1 emits the old graph.
  Fix the newline layout: the reference expands image_newline over every map
  row, while the copy read past the one-row vector; with a multi-tile batch
  that made the trailing cells live data and the decoder dropped the text at
  the right margin of every line.
- attn: instantiate attn_paged_qrow at head_dim 128 (bf16 and fp8 caches) and
  read OCR's q slice of the fused q|k|v plane in place, keeping the dense cast
  as the fallback when the library does not serve the qrow row.
- tests: h128 attention emulator cases, a batched-tower arch test, an AVX2
  bit-identity test, and a 15 s arch_test CPU budget for the image.

Measured through the router at 256 tokens: 8-page TTFT 4157 -> 1327 ms, 640
page 608 -> 284 ms, 8 concurrent pages 17.6 -> 4.26 s wall; decode unchanged
at ~344 tok/s. Parse gate 0.9901 text / 1 px on the deployed image.
2026-10-20 15:28:34 +00:00
gearwave00001andClaude cbbab03183 minimaxh3: W8A8 DiT path -- int8 weights and int8 activations
The denoiser's linears were E4M3 with fp8a8 activations. Three mantissa bits
band the smooth per-token activations that carry image detail (a watercolour
look) and the 448 clamp clips highlights (oversaturated colour). int8 is 126
uniform levels per group with no clamp, at the same one byte a weight, so the
container footprint and served memory are unchanged; iu8 WMMA runs at the fp8
rate. A quarter of E4M3's error on the activations that were the fidelity limit.

Serve the fp8 and the new int8 containers from one plugin, told apart by
probing one trunk linear (linear_is_w8) before the activation code planes are
declared. There are no int8 forms of the fused producers (rms_mod_quant_fp8,
gated_quant_fp8), so for the int8 trunk the producers come apart: plain rms_mod
writes a bf16 modulated-norm plane and each int8 linear quantises that plane
into its own codes (LinearFP8::i8's quant_act_i8g), and the gate is a bare
silu_mul. The attention's own quantiser already emits int8 (QuantFP8 q8_fed),
so o_proj reads those codes directly. A trunk read entirely by int8 linears
declares no E4M3 code pair (ActFP8::declare_qs fp8_pair=false), freeing arena
the KV cache needs.

data/recipes/minimax-h3-w8a8.recipe converts the DiT linears to symmetric int8
on a per-row 128-column grid; reuse the fp8 container and list only the
transformer.* tensors as changed.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-20 10:00:44 -05:00
gearwave00001andClaude 5098672aee docs(ref2va): embedding-placement vram is not viable at TP2 — aborts, KV=0
Follow-up to the link-bound finding: tried --embedding-placement vram to
take the 1.45GiB/rank embedding read off the gen4 x8 link. It resolves to
VRAM but starves the KV cache: static weights fill the whole per-card
weight budget -> every MoE expert streams + vram_kv=0 MiB -> startup
aborts (invalid argument). So the shipped embedding-in-ram default is the
trade that keeps VRAM for KV+experts; forcing it to vram trades a small
streaming cost for a catastrophic one. No rows produced (aborted before
VRAM claim). Cards stayed 61MB.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-20 08:40:31 -05:00
gearwave00001andClaude fce342d710 docs(ref2va): #10 power-cap A/B — 215W/−75mV vs uncapped 300W/0mV
Removed the 215W cap + −75mV undervolt, re-ran bench2.sh. Uncapped vs
capped: ~2% at 6s, 5.3% at 12s (207→196), noise elsewhere; busy=100% on
519/528 samples. Conclusion: TP2 diffusion is NOT SM-clock-bound — the
gain is small because the step waits on the gen4 x8 fabric (all-reduce +
embedding/encoder reads over the link), which doesn't shrink with core
clock. Corrects the earlier note that implied the cap was a major
long-row handicap; the sol 12s gap is not the power cap — the link cap
is. Leaving the box at 215W costs ~5% worst-case on diffusion.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-20 08:36:42 -05:00
Juup 8bcf695db9 unlimitedocr: lift q dense before attn_paged for the fused q|k|v plane
The fused q|k|v GEMM writes one plane, so the q operand is a column slice
whose row pitch is q_dim + 2*kv_dim. libr4d's attn_prefill_h128_gqa1_fp8kv
reads q only contiguous and refuses the slice with RAD_E_STRIDE, which aborts
the step and stops the engine on the first prefill. attn_paged_qrow would read
the pitch in place but has no h128 row (only head_dim 256/512), so lift the
slice into a dense [T, q_dim] buffer with a cast after rope, as gemma4 does.
2026-10-20 12:09:32 +00:00
Juup 859efc7208 review: apply the Unlimited-OCR code-review findings
The 2a1ca01..f308216 range's 45 review findings (12 performance, 33 quality)
are applied: ABI 23 for the RadBatch append, the fused q|k|v projection, the
batched patch-embed GEMM and pitched layout copies, the sam_attn w-dot hoist
with an alignment-gated vector row path and NaN poisoning for malformed
segments, the fused quick_gelu act, and the R-SWA/scheduler/drafting gates.

Quality items: stale comments corrected, env reads hoisted, the ngram_window
negative refusal, the parts-form chat template instruction, the whitelist
fallback warning, and the segmented R-SWA refusal of the fixed/runtime window
mix.

The 3.2 MB generated resample header becomes a 9.6 MB little-endian blob
(tests/data/golden/uocr_resample_golden.bin) read by a small loader;
resample_golden.py emits and round-trip-verifies it.

One perf-med item (AVX2 bicubic passes/LUT patch staging in the processor) is
left as the follow-up the review itself recommends; the code says why.

Verified: ninja -C build-review -k 0; host ctest 89/89; GPU r4d_selftest
0 failures, kbench/kbench_moe and the card tests pass.
2026-10-20 07:06:18 +00:00
Juup 1f661bf2e0 deploy: ignore LibreChat's image placeholder in the OCR template
LibreChat sends the picture followed by U+FFFC (an object replacement
character) as the text part, so the turn looked non-empty and the parser
instruction was not supplied; the model then emitted a one-word preamble
before the layout. Treat U+FFFC like whitespace and drop it from the
rendered prompt, and default the instruction for any picture count.
2026-10-20 07:04:11 +00:00
Juup 34f2bf26e2 deploy: share the Unlimited-OCR parser chat template
Render only the last user turn and supply the reference parser instruction
when that turn carries no text, so clients that send a bare image (or
system/history text) no longer get a prose preamble before the layout.
Mount the template directory read-only at /chat-templates.
2026-10-20 07:04:11 +00:00
Juup 0901ef9c50 docs: how to serve and parse with Unlimited-OCR 2026-10-20 07:04:11 +00:00
Juup f98f223fa6 deploy: an Unlimited-OCR bf16 compose service
One card via RADIANCE_GPU, --tp 1 --max-num-seqs 8 --max-model-len 32768,
--kv-cache-dtype fp8, the vision tower on the card (the default placement)
and --gpu-headroom-mib 96. About 7 GiB of VRAM, so the other service in
this directory is stopped first.
2026-10-20 07:04:01 +00:00
Juup 10afeadb7b media: document FFmpeg's VP8L refusal of some libwebp streams
The lossless-webp round-trip test failed on this host because FFmpeg's
native VP8L decoder rejects valid palette-coded libwebp streams (the
system ffmpeg 8.0.1 CLI refuses the same bytes; libwebp/PIL decode them).
The test now validates the RIFF/WEBP/VP8L container and tolerates exactly
that 'Invalid data' refusal with a visible note, while other decode errors
and wrong pixels still fail. media.h records the consumer-side caveat.
2026-10-20 07:04:01 +00:00
Juup 2211fb9e46 tests: Unlimited-OCR wide lines are chunked into whole tiles
A 16000x1024 picture's 16-tile line takes two passes, 10+6: the earlier
chunk ends at its last tile, only the last carries the newline column,
only the real 4x4 separator is flagged, and the placeholders still equal
(10*cols+1)*10 + 273.
2026-10-20 07:04:01 +00:00
Juup 52637ec186 unlimitedocr: tiled/base e2e parity, per-segment tower layout, n-gram whitelist
The pass packer now keeps a view and its one-cell separator in one pass, and
RadBatch carries each segment's grid host-side (enc_seg_h/enc_seg_w) so the
DeepEncoder no longer reads device coordinates to pick a geometry. The tower
lays out a line of n tiles as kMap rows of n*kMap features plus one newline
cell, accepts an earlier chunk of a longer line, and emits the learned
view_seperator for an explicit 4x4 separator rather than any square segment.

The device sam_attn resamples a rel_pos table that is not 2*tile-1 rows on
read (the 127-row global tables serve a 40-grid block as 79), matching
libref/libavx. The n-gram ban gains the reference's optional whitelist
(5th operand, OAI keys, generation_config alias) with range/dtype checks.

Gates: tiled e2e stage cosines 0.9994-1.0, det/text 0.9901 with every
coordinate within 1 px; two-page 0.9917 within 2 px; device selftest
sam_attn (incl. 127->79) and ngram whitelist (1344 columns) 0 mismatches.
2026-10-20 07:04:01 +00:00
Juup fad4ba7f1a unlimitedocr: the DeepEncoder tower, R-SWA ring KV and the n-gram ban
DeepEncoder (arch/common/rad_block_sam.h): the checkpoint's SAM ViT-B/16,
neck and CLIP ViT-L/14 producing its 16x17+1 row layout, with a new
`sam_attn` op for the windowed, zero-padded SAM attention and its
decomposed relative-position bias (libref oracle, libavx kernel, libr4d
kernel and selftest). The plugin declares the tower when the container
records `radiance.encoder`, and splices its rows over the placeholders
after embed_lookup.

BOS: the chat path adds BOS when the rendered template does not already
start with it. This checkpoint's template is a bare concatenation and its
tokenizer states add_bos_token, so without it every position was off by
one and the det boxes came out wrong. A media run's placeholders shift
with it.

R-SWA: RAD_KV_RING, paged like a window group but with a per-sequence
floor armed at admission. adv_groups now computes the same clamped
seqused and modulo ring slots the builder stages; the mismatch read the
block table's -1 padding and faulted the card. Prefill stays causal;
prefix cache, checkpoints and speculation are off for the group.

Sampling: sample_ngram_ban in libref/libavx/libr4d and the host chain,
the request knobs, and the container's generation config (35 over 128).

Processor: the checkpoint's grid/mode selection, its tall-last tie order,
Pillow's bicubic pass order, and goldens generated from its own code.

Tools: --mm-max-patches auto-detection accepts a tower stated as per-width
tables under vision_config.image_size, and rad-convert records
radiance.encoder.

Verified: tower stages match the checkpoint's code (rows cos 0.9998), the
device sam_attn selftest is within tolerance, the R-SWA device repro
returns text, a GPU e2e reproduces the reference's first det block, and
the host suite is 88/89 (known webp decode baseline).
2026-10-20 07:04:01 +00:00
Juup 543cba7416 unlimitedocr: the decoder plugin, the fused router ops and an h128 MHA attention leg
The text side of Unlimited-OCR: a 12-layer, 1280-wide decoder, 10 query heads over 10 KV
heads at head_dim 128, a dense layer 0 and 64 routed experts (top-6, softmax, no
renormalisation) plus one ungated shared arm in layers 1-11. arch/unlimitedocr_bf16/
carries its own plain-Llama bf16 attention, the shared MoE block in its bf16
external-input mode, and the tied LM head; data/recipes/unlimited-ocr-bf16.recipe is the
bf16 passthrough convert. core/format/checkpoint.cpp learns n_routed_experts, so n_expert
is read from the checkpoint's own key.

The router is issued as one op rather than a selection and a sort: libref gains
router_topk_scatter and router_gemm_topk_scatter (the second with the shared expert's
one-column gate at N = 1), libavx composes both from its router/gemm/scatter kernels, and
both get sweep geometries and the gate-absent/gate-present tests.

libr4d had no head_dim 128 leg at ratio 1, so every attn_paged band of this geometry
resolved to no kernel and the server refused to start on device.
r4d_attn_paged_h128_gqa1.hip instantiates the generic body at GQ 1 for both legs; the
rows and the selftest cases come with it.

Device numbers, one R9700 (gfx1201, HIP 7.16), bf16 weights and KV, no reference-kernel
fallback: a 523-token prompt prefills at 35.0-35.8k tok/s (15 ms) and a 4043-token prompt
at 54.2k tok/s (75 ms); decode is 351-354 tok/s (2.82-2.85 ms/token) at short context and
315 tok/s at 4k. r4d_selftest is 0 failures; the host suite is 86/87, the miss being
mm_test's lossless-webp decode, which fails on this box in code this change does not touch.
2026-10-20 07:03:49 +00:00
gearwave00001andClaude 4277d414a2 docs(ref2va): #10 throughput comparison, 512 keyframe parity re-confirm, example inventory
- #10: matched TP2 battery vs ComfyUI single-card (stock + solattn); honest
  two-framing verdict (parity vs stock at every row incl. 12s; sol wins at
  6-12s where its sparsity engages) + 215W power-cap caveat.
- #8: 512-output keyframe encoder-band fix + R4D_ENC_DEBUG gating of the
  debug shadow casts; endpoint parity re-confirmed at 512 (pinned cos~0.985
  vs un-pinned ~0/-0.57).
- example-clip inventory: 5 categories at 512x512 12s seed 1234.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 23:52:27 -05:00
gearwave00001andClaude 5dd0ba8a81 venc: let one-frame media (endpoint keyframes) encode at output resolution
Endpoint keyframes are resized to the target canvas and their latent rows share the TARGET grid
(ref2va_build), so they must VAE-encode at output resolution -- but venc_geom had a flat
h,w > kEncMaxSide(256) reject, so I2VA/L2VA/FL2VA failed at any output above 256 with "the video
encoder refuses a reference at 512x512 over 1 frames". The flat cap is a crude proxy for the real
limit: the encoder holds one clip's pixels sized for a kVaeClipLength(17)-frame clip at 256
(Rmax=17*256^2). Replace it with clip*h*w <= 17*256^2 -- a multi-frame video ref is unchanged
(clip=17 forces each side back to 256), while a one-frame media fits at up to sqrt(Rmax) per side.
No buffer, kernel, or arena change: a 512^2 keyframe (262k rows) is a third of the existing budget.

A first relax then faulted ("cast n=128 at M=262144 outside band") because the encoder's debug
shadow casts (op_ve_cindbg / op_ve_ldbg / trunk / nout -- write b_vcin/b_vl/b_vtrunk/b_vnout, read
only under R4D_ENC_SEL) were issued on EVERY encode at a PF[] plane range a 512 frame overflows.
Gate them on R4D_ENC_DEBUG (the env the readback already uses): a no-op for the production latent,
and it stops paying for debug work on every encode.

Device-verified: FL2VA 512x512 and I2VA 512x512 12s complete clean, server survives, no band fault;
host vae_geom/video_gen/videos/ref2va_pack/encoding tests green.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 23:44:25 -05:00
gearwave00001andClaude 60e920cd4d video: endpoint keyframe completion (I2VA / L2VA / FL2VA)
One keyframe path serves three DaSiWa modes: first_frame pins output frame 0,
last_frame pins the last frame, and the gap is diffused. A keyframe is pure
attention conditioning -- its VAE latent rides as a pinned (update=0) cond row
at its frame's time position, faithful to comfy/ldm/minimax/model.py where
keyframe latents are img_update==False rows. The sampler is untouched; the step
merely widens to carry the extra cond rows.

- server (videos.cpp/iface.h/adapters.h): first_frame/last_frame form parts ->
  VideoRefMedia::FIRST_FRAME/LAST_FRAME; kf_task validation (i2va/fl2va need
  first, l2va/fl2va need last); keyframes are mutually exclusive with refs;
  encoder_image_canvas(cover=LAST) sizes the anchor.
- driver (video_driver.cpp): keyframe pass issues a RAD_ENC_IMAGE Vencode per
  anchor (slot = ++ref_tab[1], ordered), appends ref_tab key triples
  {frame(0|frames-1), video_t=1, audio_t=0}.
- arch (minimaxh3.cpp): ref_parts emits keyframe cond parts FIRST; the step
  scatter admits kR2VCond/kR2VCondAudio rows.
- tests: video_gen_test keyframe-completes-widens-the-step-and-pins-the-ends
  (2x Vencode at slot 1,2; widened step; seg_cu/lat_cu/ref_tab pinned); fake_pack_ref
  lays keyframe rows (nk=0 byte-identical to before); videos_test keyframe API.

Device-verified (TP2, seed 9999): FL2VA completes a valid 73-frame MP4+AAC; pins
are consumed (fl2va != same-seed t2va) and force the endpoints (frame0 vs anchor
0.687 pinned vs 0.460 un-pinned; last 0.719 vs 0.521). Fidelity follow-up (not
function): anchors ride as pins only; the reference also feeds them through the
TE as vision tokens, so a prompt that contradicts the anchor lets text win --
full endpoint parity vs a golden needs TE-anchor tokens (#10/P6 bucket).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 22:19:16 -05:00
gearwave00001andClaude 8ddcbbf01f docs: #8 keyframe-pin disposition — pack layer done, engine wiring left optional
Chaining already works via ref_video; the FL2VA exact-pin is an alternative
mechanism whose fidelity claim has no golden on this box, and its wiring lands
in the shared step_dit — so it is left pending rather than blind-changed.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 18:42:58 -05:00
gearwave00001andClaude 4b0b787d53 docs: P6 Radiance TP2 engine-throughput numbers (FFmpeg blocker resolved)
Record the fixed-shape TP2 wall-clock (plain 256/3s/25st=12s, 512/3s/25st=38s,
full-shape ref2va 256=93s / 512=121s). Encoder value-parity half of P6 is done;
the dual-vs-two-singles claim is documented as blocked on the external Hermes
sol-attn ComfyUI baseline (the 590/315 rows are stock-attention floors that
include queue wait), not on anything in this branch.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 18:41:59 -05:00
gearwave00001andClaude 40e4e3c2d8 venc: value-parity fix — shortcut must read the raw input, not silu(norm1)
In step_venc the ResnetBlock shortcut conv (op_sc) was issued after norm1
(op_n1), but on a shortcut level norm1 normalizes the input `in` IN PLACE
(nb = E.in), so the 1x1 nin_shortcut residual was fed silu(norm1(x))
instead of the raw x the reference uses:

    ResnetBlock3D.forward:  x = self.nin_shortcut(x)   # raw, before any norm
                            return self.conv2(h, pre_norm=norm2, residual=x)

This shrank the residual term on every shortcut level (cout != cin, i.e.
levels 1 and 3), producing the ~0.49x structural deficit that accumulated
down the video/image VAE trunk. Reorder op_sc to read `in` before op_n1
overwrites it -- an op reorder, not a kernel change; it corrects the SHARED
trunk so the image encoder's fidelity is fixed too.

Localised by a frame-0 per-level bisection: R4D_ENC_SEL=all now dumps
frame-0 f32 shadows of every level's post-resnet output v_lv[0..4].a
(dbg_ve_l0..l4, a 9-buffer host slab) alongside the existing tail, and
ref_venc_parity.py --evcl0..--evcl4 compares each against the reference
level output on the device's own staged pixels. The std ratio walks to the
exact entry point -- conv_in 0.999, L0 0.999, L1 0.455 (first shortcut
level) -> every level 1.000 after the fix, tail nout/q48/q2 to the bf16
floor (relFro ~4e-3, affine 1.000). Device-live: a single-image ref2va
encode generates clean with the fix loaded.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 18:32:56 -05:00
gearwave00001andClaude 1dc850d17f venc debug: trunk shadow + GN-extent/temporal discriminators; localize #14 video gap to spatial trunk
Adds a fourth R4D_ENC_SEL=all shadow — the norm_out INPUT (v_lv[5].a, level-5 trunk) as an
f32 PERSIST cast twin (b_vtrunk), via a new trailing RadVideoGenDecl field dbg_ve_trunk (no ABI
bump) + layout rows + a 4-readback "all" slab (trunk|nout|q48|q2). ref_venc_parity.py gains
--evctrunk (whole-volume vs per-frame GroupNorm discriminator) and --expand/--zeropad (single-frame
temporal tests).

Device-anchored golden comparison on a 256x256 image exonerates, one by one: input normalization
(byte-identical affine + IMAGENET consts), norm_out (faithful, relFro 1.6e-3), GroupNorm extent
(device already per-frame; #20 closed), temporal handling (reference frame0 std flat 8.986 at N=1..17
under both replication and zero-padding vs device 4.40), a single multiplicative gain (nout differs
0.57 non-affinely after per-group norm => structural), and weight precision. The gap is a structural
~0.49x spatial-trunk deviation (conv_in/resnet/spatial-downsample), NOT confined/golden-fixable, so it
is documented precisely and left open — no shared-kernel edit. Host tier green.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 17:55:36 -05:00
gearwave00001andClaude 2acc0261ff docs(ref2va): audio parity root-caused to pre_block norm swap; video still open (#14)
Rewrite the superseded "shared final-norm / encoder-norm-kernel scale fault"
narrative: the audio ~0.37x under-gain was a pre_block norm1/norm3 swap (a
wiring bug), now fixed and device-verified. Records that the shared LayerNorm
kernel is demonstrably fine (audio matches using it), which kills the
"one norm damps both families" hypothesis; the video/image (conv3d) encoder has
no pre_block and remains a separate, open divergence (with the GN-extent gap
#20 stacked on it). Keeps the pre-fix measurements as labelled history.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 17:15:40 -05:00
gearwave00001andClaude 39602c1c7b arch: audio pre_block feeds each branch the reference's norm (#14)
The reference AttnProjection (comfy/ldm/minimax/audio_vae.py:267) computes
proj(norm3(x)) + attn(norm1(x)), then + mlp(norm2(·)). The two 2048-wide
LayerNorms are not interchangeable: norm3's affine |w|mean is 0.60, norm1's
0.27, so the projection branch carries most of the block's magnitude (std 6.6
via norm3 vs 0.4 for the attention via norm1).

The device had them wired the other way -- it staged norm1 into the projection
and norm3 into the attention (qkv). Feeding the small-affine norm1 to the
projection shrank it 6.6 -> 1.8, collapsing the pre_block output and every
audio latent downstream to ~0.25-0.27x the reference.

Fix: stage norm1 for the attention (feeding p_op_qkv) and norm3 for the
projection (feeding p_op_proj). Both LN ops are the same ln(...,2048,b_apb->
b_aln3) kernel, so only the consumer wiring changed -- no kernel touched, no
re-convert (norm1.*/norm3.* weights are already loaded correctly).

Also adds a gated read-only R4D_ENC_SEL=amb readback (dbg_ae_amb = b_amb, the
f32 mean_proj input): the bf16 b_ax2 readback lags the arena and dumps garbage,
so b_amb is the reliable pre_block output used to localise the gap. Inert when
R4D_ENC_SEL is unset.

Device-verified (seed=7 tone, minimax-h3-ref2va-fp8, warm TP2): pre_block out
b_amb std 1.65 -> 6.43 (ratio 0.25 -> 0.97); final latent b_enca std 0.23 ->
0.546 vs reference 0.588 (ratio 0.39 -> 0.93), affine slope 0.385 -> 0.923,
R^2 0.975 -> 0.989. Host tier green (abi_layout/arch/ref/videos).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 17:15:30 -05:00
gearwave00001andClaude 0bfde46414 docs(ref2va): localize the ~0.37x under-gain to the final norm/conv; record GN-extent gap (#14/#20)
Architecture refutes the "per-level attenuation compounding" reading: both encoders
TERMINATE in a normalisation that re-writes activation scale (video norm_out=venc_gn
before conv_out/quant_conv; audio pre-block norm1/2/3 LayerNorms before proj/mean_proj).
A GroupNorm/LayerNorm output has std ~= its per-channel gamma regardless of input, so
any gain accumulated in the encoder BODY is erased before the latent is emitted. The
~0.37 can therefore only originate in the FINAL norm's affine application or the final
conv/linear: video norm_out(gamma)->conv_out->quant_conv; audio norm3(gamma)->proj->
mean_proj. The two families' scale differing slightly (0.385 vs 0.369) is simply those
final chains differing per arch.

Re-explains encoder-confinement cleanly: the DiT uses RMSNorm (rmsnorm_op), the encoders
use GroupNorm/LayerNorm kernels (shared with the latent upscaler) -- a defect in those
kernels is invisible to the DiT's RMSNorm path, consistent with the DiT generating
correctly. Narrowed confirming step recorded: dump per-channel std of norm_out output and
conv_out/quant_conv output (and audio norm3/mean_proj) -- post-final-norm std ~0.37 pins
the norm affine/kernel; ~1.0 with collapse only after conv_out/quant_conv pins those
conv weights. Not blind-fixed (shared with live image/plain + upscaler paths).

Also records a SEPARATE real fidelity gap found while localising (task #20): the device
GroupNorm reduces statistics over a level's whole clip volume, but the reference
TemporalIsolatedGroupNorm normalises per frame. Exactly neutral for the single-image
parity measurement (T=1) but it biases real multi-frame video reference encodes -- what
DaSiWa actually feeds -- as a shape change stacked on the 0.37. Recorded, deliberately
not touched (shared kernel; whole-volume pooling may be an intentional temporal choice).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 16:38:00 -05:00
gearwave00001andClaude 04440dd3a9 test(ref2va): decompose the encoder parity gap = near-pure ~0.37x under-gain (#14)
Fit a single global affine dev_sorted ~ a*ref_sorted + b to both encoders' value
distributions (both harnesses now print it):

  audio  (conv1d):     a=0.385  b=+0.009  R^2=0.975  relFro 0.79 -> 0.062 after affine
  video  (conv3d):     a=0.369  b=+0.159  R^2=0.912  relFro 0.65 -> 0.114 after affine

Two entirely different encoder networks both reduce to ~0.37x the reference with
R^2 0.91-0.98 -- near-perfect linearity. This overrules the earlier "not a single
scale" and "suspect the strided conv1d temporal reduction" readings: a conv-reduction
or structural transform bug would not collapse to a clean global scale. The device
encoders compute the right SHAPE of latent, damped to ~0.37x amplitude. The scale is
~0.37 for both but not bit-identical (0.385 vs 0.369) => not one shared post-multiply,
but a fixed per-level attenuation compounding over each arch's own depth.

The DiT generates correctly on the same fp8 path and the same normal kernels, so this
is not a global kernel/quant fault -- the under-gain is confined to the encoder pass.
Prime suspect: the encoders' per-level / per-frame GroupNorm (the per-frame CS in
{8,4} template) applying a near-constant sub-unit gain that compounds level-over-level,
or an encoder-path dequant scale mismatch the convert round-trip does not see. If it is
a fixed encoder-norm gain, a fix is confined to the encoder path and never touches the
DiT's norms -- which is why this is worth localising rather than shipping. Not
blind-fixed (encoder kernels are shared with the live image/plain encode paths).

Confirming step is cheap and read-only: dump one encoder block's GroupNorm input AND
output on-device, check whether output std is a fixed fraction of the reference GN.

docs/NOTE-REF2VA.md point 4 corrected (the superseded "not a single scale" clause) and
the affine table + encoder-specific-under-gain hypothesis recorded.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 16:29:02 -05:00
gearwave00001andClaude 241629fe8c test(ref2va): measure video/image VAE encoder parity = DIVERGED (#14)
The audio half of the #14 strict numeric value-parity was already measured and
found to diverge. This measures the OTHER half — the conv3d_ndhwc video/image
encoder, a separate kernel family — the same device-INPUT-anchored way, and it
diverges too, with the SAME signature.

New harness tests/data/ref2va/ref_venc_parity.py:
- Does NOT import comfy.ldm.minimax.vae (that drags comfy attention -> an aiter
  JIT build that fails on this box), so like vae_geom/gen_golden.py it
  AST-extracts just the encoder classes + the _normalize_pixels /
  _encode_moments methods, execs them on torch alone, and loads the REAL fp16
  minimax_h3_video_vae_fp16.safetensors into encoder+quant_conv (decoder
  excluded; the encode path has no attention). --selftest validates the
  reshape / normalisation / sorted metric with no device involvement.
- Device stores b_evc PATCH-FOLDED (op_ve_fold: 24ch x 2x2 = 96-wide rows) and
  per-channel-normalised. The fold is a pure bijection and the norm is
  per-channel, so the value MULTISET of the device slot region matches the
  reference's normalised latent regardless of fold order; the harness compares
  the two SORTED value vectors. This is immune to re-deriving the fold's
  (t,h,w)+channel packing — the mistake that once cost a bogus audio reading.
- A single reference IMAGE is the cleanest case (encode()'s T==1 branch, one
  clip, exactly one latent frame), so keep-first/last is moot; the harness
  refuses T_pad!=1.

Two inert, R4D_ENC_DEBUG-gated dumps added to core/gen/video_driver.cpp (the
staged pixel buffer + enc_geom, next to the existing audio ones) so the
reference can be fed the device's OWN staged input and only encoder math can
differ. Zero-touch when R4D_ENC_DEBUG is unset.

Result on a 256x256 gradient picture: sorted relative Frobenius 0.65, device
latent std 0.44 vs reference 1.15 (~2.6x under-spread), max-abs 4.26. DIVERGED
like the audio path.

The finding is the SHARED signature: audio collapsed std 0.59->0.23 (~2.6x) and
video 1.15->0.44 (~2.6x) across two entirely different kernel families, AND for
BOTH families the latent-normalisation constants are byte-identical to the
reference (kVaeLatentsMean/Std vs LATENTS_MEAN/STD max rel-diff 0.0). So the
collapse is NOT the norm constants and NOT audio-specific — this refines the
earlier "suspect the strided conv1d temporal reduction" note. Localising it
needs stage-by-stage activation dumps on kernels the live image/plain paths also
run through, so the kernels are deliberately NOT blind-fixed. The device
encoders remain content-live and deterministic (cont.3/5/19): self-consistent,
so conditioning is genuinely live; only reference-matching OUTPUT fidelity is
open (= #10 / P6).

docs/NOTE-REF2VA.md point 4 records the video-half result and the sharpened
ruling-out of the normalisation constants.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 16:26:21 -05:00
gearwave00001 04daf51e42 test(ref2va): correct aenc parity device slice + record measured audio-encoder divergence (#14)
The device stores a slot's stereo latent channel-major with per-channel row
stride MAXA=625 (ch1 at base+625), not contiguous after ch0; the harness sliced
contiguous rows and thus compared reference-ch1 against device zeros. Fix the
slice to vstack the two channel blocks. With the correct slice the audio encoder
measures relative Frobenius 0.79 / corr 0.67 / device std 0.23 vs ref 0.59 — a
real encoder-network divergence, not fp8 precision (unbiased, floor ~1.6e-3),
not preprocessing (device-input-anchored), not the reference export (97 shared
encoder tensors bit-identical to the HF source), not the norm constants
(identical). Recorded honestly in NOTE-REF2VA: measured on audio; video/image
VAE is a separate kernel family, not yet measured; functional conditioning is
unaffected; kernels deliberately not blind-fixed.
2026-10-19 16:10:03 -05:00
gearwave00001 393d5416b0 test(ref2va): device-input-anchored audio-encoder parity harness (#14 value-parity)
Unblocked by the on-box torch env. ref_aenc_parity.py loads the reference HF audio
VAE (fp32) under ComfyUI's --cpu branch (no GPU context — the TP2 server holds both
cards), and compares the device's b_enca normalised latent to the reference encode()
run on the device's OWN staged enc_samples buffer. Device-input-anchored => removes
every decode/normalise/pad confound; a kernel bug shows gross, a correct fp8 port
shows at/below the ~1.6e-3 convert quant floor. --selftest validates the reshape /
slot / metric logic without a device (perfect->0, temporal-misalign->0.24).

Driver side: extend the R4D_ENC_DEBUG scaffolding to raw-dump the staged enc_samples
(host buffer at stage time) and the b_enca / b_evc readback to R4D_ENC_DUMPDIR.
Inert unless R4D_ENC_DEBUG + R4D_ENC_DUMPDIR are both set; host tier green.
Reference model.py re-baked golden.json byte-identical (no reference drift).
2026-10-19 15:56:35 -05:00
gearwave00001 7f4bc9c3a4 docs(ref2va): correct keyframe-golden + torch-status claims
Re-baking golden.json under the on-box torch env (comfyui-rocm10-venv, torch
2.13.0+rocm) came out byte-identical, proving: (1) the reference model.py has not
drifted, and (2) the pack keyframe/cond golden is NOT stale or torch-blocked —
pack_golden_fl2va / _chain already assert kR2VCond layout bit-exact and pass. So
#8's PACK layer is reference-verified; only the engine consumption (driver keyframe
staging, step_dit cond scatter, tail input) is unwired. Corrects point 3's 'pack
keyframe rows remain unimplemented' and point 4/6's 'this host has no torch' (the
encoder value golden is now actionable, not blocked — not yet produced).
2026-10-19 15:48:53 -05:00
gearwave00001 f4c8af1eb3 docs(ref2va): record self-contained dual-GPU throughput benchmark
Wall-clock per job on TP2/dual-gfx1201 (empty queue, completed_at-created_at):
plain 256/512, step/duration/resolution scaling, and the full DaSiWa reference
shape (4 img + video + soundtrack + standalone audio). Conditioning cost is the
widened sequence, not the encoders. Self-contained scaling figures, NOT a
ComfyUI parity claim (parity = open, needs reference stack).
2026-10-19 15:46:29 -05:00
gearwave00001andClaude d73f94c387 docs(ref2va): record full-shape content-control (all ref kinds consume in the DaSiWa max request)
Acceptance test #5 on dual gfx1201/TP2: one request with 4 images + a video +
its soundtrack + a standalone audio is accepted and completes clean; changing
only the standalone audio at a fixed seed changes BOTH output streams, proving
the full-shape denoise consumes the audio reference (not just its count).

PLACEHOLDER AUTHOR — re-author before any push. Do NOT push.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 15:39:30 -05:00
gearwave00001andClaude e93dae4f5e docs(ref2va): correct NOTE-REF2VA — video/audio refs are live; chaining via ref path; parity torch-blocked
The gap note still asserted a defect the device probes disproved. All three
reference kinds (image, video, audio) are device-verified live + content-sensitive
+ deterministic on a warm-server fixed-seed content-control; the earlier
'video/audio give byte-identical output, encoder collapses' claim was a
measurement artifact (raw-MP4-byte comparison + a cold-start pair). Continuity
chaining is drivable today through the ref_video path (a control shows the tail
conditions scene B); the kR2VCond keyframe-pin mechanism stays open (FL2VA
exact-pin, reachable via image refs). Strict numeric encoder value-parity is
environment-blocked on a torch-less host and was never the claim.

PLACEHOLDER AUTHOR — re-author before any push. Do NOT push.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 15:33:03 -05:00
gearwave00001andClaude 658f7b7214 ref2va: wire video and audio reference conditioning end-to-end (all three ref kinds live on device)
Follows the merged-cell pin (c725a2d). That commit proved reference IMAGE
conditioning consumed on device; reference VIDEO and AUDIO were plumbed
through the pack and step but still refused at submit — only their decode
and encoder-enqueue were missing. This lands them.

Server (videos.cpp): `task ref2va` now decodes `ref_video_N` and
`ref_audio_N` (and a video's paired `ref_video_audio_N`) into encoder form
via the mm encoders and enqueues them as Vencode/Aencode passes, instead of
the old image-only decode loop that rejected them. A soundtrack is folded
into its video's row (the `audio` word), matching how the pack lays that
pair. Caps stay <=9 images / <=3 videos / <=3 audios.

Driver (video_driver.{h,cpp}): the encode queue `enc_q` now carries VIDEO,
VAUDIO and AUDIO items in presentation order; `ref_tab` stamps each
reference's latent counts straight from the encoder geometry (rad_arch_encode_geom:
a video's frame count eg[24]=its total latent frames, its soundtrack's eg[12]),
so the pack's ref segments are sized by the encoder, not hand arithmetic.
processor.{h,cpp}/iface.h/adapters.h gained the media decode entry points.

Arch (minimaxh3.cpp): step_dit scatters reference rows into the packed step —
picture/video via op_vin from b_evc, audio via op_ain from b_enca, at each
segment start, targets last. A bounds audit confirms the scatter reads exactly
the slot region the encode pass wrote this job (eg[24]=lat = the pass's
written row count = the pack's segment size; no stale-neighbor read).

DEVICE-VERIFIED on dual gfx1201 / TP2, warm server, fixed seed, comparing
DECODED stream md5 (never raw mp4 bytes — the muxer stamps a field): all three
reference kinds are DETERMINISTIC (a rerun of one reference is bit-identical,
including raw bytes) AND CONTENT-LIVE (a different reference at the same seed
gives different output video AND audio). Image (content tokens), audio
(tone/noise/880 distinct) and video (refv_a vs refv_b: both streams differ)
each steered the generation. An earlier "the video step is nondeterministic"
note was a measurement artifact — it compared raw mp4 bytes and straddled the
one-off cold-start outlier; the warm decoded-stream probe is bit-reproducible.

Debug scaffolding (R4D_ENC_DEBUG, 4 trailing RadVideoGenDecl fields + a pinned
driver slab + an FNV digest in done()) is entangled in these files. It is
env-gated and zero-touch when unset; STRIP IT BEFORE ANY PR.

tests: video_gen_test/videos_test/server_fakes cover the video/audio enqueue
paths; abi_layout_rows adds the new trailing rows; ref_audio_sensitivity.py is
a standalone host golden harness (audio reference separates 4/4), not a ctest
case. Host tier green (only mm_test's pre-existing webp demuxer gap fails, and
the GPU card/kbench tests fail solely on VRAM contention with a live server).

NOTE-REF2VA.md updated: continuity tail (#8) remains unimplemented; strict
numeric parity vs the ComfyUI CPU reference remains open.

PLACEHOLDER AUTHOR — repo has no git identity; re-author before any push.
DO NOT PUSH this branch.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 15:25:32 -05:00
Deadcode 685ec5bd85 radiance 1.9.0
New models:
- LTX-2.5 (base and distilled): video with a stereo soundtrack from text or from text and a first
  frame, on one card, with its duration head, tiled VAE decoding, the diffusion decoder and the x2
  latent upsampler
- Krea 2 Raw and Turbo, and FLUX.3 [klein] and its base: text to image, and for FLUX.3 edits from up
  to ten reference pictures, on one card
- GLM-5.3-Flash from AMD's Quark MXFP4 export, on eight cards (John McDonough, Nunze)
- Gemma 3 / TranslateGemma 27B with an optional DFlash2 drafter (mici81)

Engine:
- --kv-cache-dtype fp8_v4 and k6_v4 for Gemma 3 and Qwen3.8-Flash-Next (mici81)
- the rotated int8 trunk (i8a8h) for Qwen3.8-27B (eddie168168)
- eight-rank all-reduce bands, weighted shards and pieces (Nunze); --host-headroom-mib (sfjes)
- the dashboard shows the single-stream decode floor and its most recent window (Memoria)

Fixes: prefix-cache reservations kept until their save lands (baKon), tool calls in Responses
namespaces (#119), system messages merged when a template refuses several (#137), a prefill
continued with no open step (#127), calibration of a Gram accumulation (#122), JSON Schema patterns
read unanchored (davetha), GLM-style tool calls, the KV floor counting every sequence's state.
Plugin ABI 24.
2026-10-19 21:58:07 +02:00
NunzeandJohn McDonough 778cbf315e docs, compose: GLM-5.3-Flash
The glm5next section of ARCHITECTURES.md (geometry, traps, KV groups, linears, tensor parallelism,
the MoE decode fusions, measurements), the conversion and the four RADIANCE_GLM_* variables in
GUIDE.md, the README's models table. deploy/compose/glm53-flash.yaml serves the container on eight
R9700s with the expert plane resident and the native MTP layer drafting, with the flags of the
measured run.

Co-Authored-By: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com>
2026-10-19 20:13:47 +02:00
John McDonoughandNunze fba4ee0188 glm5next: GLM-5.3-Flash -- mHC streams, KDA and sparse latent MLA, MXFP4 experts, native MTP
An architecture plugin for GLM-5.3-Flash (45 layers, 4096 wide) from its Quark MXFP4 export: four
mHC residual streams; KDA layers and full layers with absorbed MLA behind the DSA indexer; a MoE
block of 288 MXFP4 experts (top 8, sigmoid routing with a correction bias and route_scale 2.5) and
an ungated shared expert; clamped SwiGLU; the block-fp8 attention and MTP weights at their f32
scales; and its native MTP layer as the drafter. Under tensor parallelism experts shard by width,
MLA by whole heads, and the f32 router and index-head projections split their columns from 256 rows.
The MoE block's decode fusions are on by default (RADIANCE_GLM_ROUTER_FUSE,
RADIANCE_GLM_SWIGLU_QUANT, RADIANCE_GLM_GATHER_INVERSE; 0 restores the separate launches, byte for
byte). Its tool-call format is derived from the chat template, as for the other models.

data/recipes/glm53-mxfp4.recipe decodes only the combined MLA projection to bf16; every other
weight keeps its stored encoding.

arch_test declares the model at one, two, four and eight ranks and lints its steps: the mHC
connections, the routing's f32 path, the head-complete MLA shards, the indexer's cache pages and
tail ring, KDA's local heads, the expert geometry at TP4 and TP8, that the sizing declares give
the real graph at every arena level, where the decode fusions replace their launches, and, with
the fusions off, a pinned graph and step hash.

Co-Authored-By: Nunze <lorenz.lamping1@web.de>
2026-10-19 20:13:47 +02:00
John McDonough 544753fc40 arch/common: GLM-5.3's blocks, and f32 scales, MXFP4 experts and sigmoid routing in the shared ones
New blocks: mHC (rad_block_mhc.h), KDA and its state (rad_block_glm_kda.h,
rad_block_kda_state.h), absorbed MLA over a latent cache (rad_block_glm_mla.h,
rad_block_mla_latent.h), the DSA indexer and its paged key cache (rad_block_glm_indexer.h,
rad_block_dsa_cache.h), the correction-bias router (rad_block_glm_router.h), and rad_tp_split.h:
a replicated f32 projection computed column-split over the ranks and all-gathered, so every value
is the replicated one's bits (from RADIANCE_GLM_TP_SPLIT_ROWS rows, 256 by default).

The shared blocks gain what GLM's checkpoint stores, each off unless a model asks for it:

- LinearFP8 reads a block-fp8 weight whose scale plane is f32 (dtype fp8a8f32), and the import
  check accepts that form beside bf16 scales.
- GateQuantFP8 serves a clamped SwiGLU (swiglu_clamped), optionally fused with its quantiser.
- MoeFP8 takes MXFP4 experts (format 8) and block-fp8 experts with f32 scales (format 9), the
  sigmoid router with f32 weights, an ungated shared arm, the router/scatter fusion and the
  sort's inverse handed to the gather (moe_scatter_inv, moe_gather_inv) where they resolve.
- The MLP's gated fold excludes the forms it cannot serve (f32 scales, a clamped product).

share_test checks that KDA's convolution weight shards per head across its three parts at TP4.
2026-10-19 20:13:47 +02:00
NunzeandJohn McDonough 78c58841bf libr4d: GLM-5.3's kernels -- mHC, KDA, the DSA indexer, MLA, f32-scaled FP8, MXFP4 experts
The device rows for GLM-5.3-Flash's ops, at its geometry and at TP4 and TP8 slices:

- mhc_pre / mhc_post / mhc_contract, and mhc_pre_partial / mhc_pre_finish, which run mhc_pre's
  own projection and finishing kernels with its chunk-sum order, so the pair is byte-identical
  to mhc_pre at n 4096, hc 4, chunk 2048.
- kda_update_k128_v128_bf16, one, two or four value rows a wave, both state forms.
- dsa_pool_fp8, dsa_query_fp8 and dsa_score_fp8 (fp8 WMMA, 32 heads of 128).
- mla_attn: a matrix row whose WMMA tile holds a query's heads, or pairs eight heads of two
  neighbouring queries over the union of their page tables, above the wave row; mla_project
  with up to eight rows a thread or wave.
- gemm_nt_f32 and router_sigmoid_topk in tiled and one-wave-a-row forms; gemm_fp8a8_f32scale
  and moe_gemm_fp8a8_f32scale read f32 block scales in place; moe_gemm_mxfp4a8 decodes e2m1 into
  exact E4M3 bytes for fp8 WMMA, with an expert-major decode form and a wide prefill form.
- swiglu_clamped, and the device-only fusions of GLM's MoE block: swiglu_clamped_quant_fp8,
  router_sigmoid_topk_scatter, and moe_scatter_inv / moe_gather_inv, which pass the gather's slot
  table from the sort instead of rebuilding it.

moe_gather takes f32 routing weights in its column-per-thread kernel. The sort and the gather
kernels move from r4d_moe.hip into r4d_moe_sort.h and r4d_moe_gather.h, so the fused router and
gather instantiate the same code.

Every form that replaces another gives its bytes: tests/r4d_emu runs the kernels on the host
(test_f32, test_fp8f32, test_kda, test_mhc, test_mla, test_moefuse, test_moemx), r4d_selftest
compares them on a card against libref and against each other, and plugin_test pins the
mla_attn band. docs/OPS.md states what libr4d serves.

Co-Authored-By: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com>
2026-10-19 20:13:47 +02:00
John McDonoughandNunze da77f86332 libref, libavx: GLM-5.3's ops -- mHC, clamped SwiGLU, f32 routing, KDA, the DSA indexer, MLA
The reference and CPU forms of the ops GLM-5.3-Flash's graph needs, with their schemas and shape
hooks: mhc_pre / mhc_post / mhc_contract and the column-split pair mhc_pre_partial /
mhc_pre_finish; swiglu_clamped; gemm_nt_f32 (bf16 activation, f32 weight and result) for the
router logits and the indexer's head gates; router_sigmoid_topk (correction-bias top-k);
kda_update with per-channel decay and both state forms; dsa_pool, dsa_query and dsa_score; and
mla_attn and mla_project for absorbed latent attention. moe_gather takes f32 expert weights beside
bf16, and fp8a8f32 joins the dtype list. docs/OPS.md states each op.

ref_test checks every op against hand-computed cases, avx_check_hand the CPU forms against
libref, build_test the indexer cache's page size.

Co-Authored-By: Nunze <lorenz.lamping1@web.de>
2026-10-19 20:13:47 +02:00
John McDonough c8311068d0 qsa_select: signed -- a ranking for indexers whose scores can be negative
qsa_select ranks max(score, 0) and treats a score at or below -1e30 as dead: QSA's block scores
are sums of relus, so the clamp changes nothing there. GLM-5.3's DSA indexer weights its heads by
signed gates, and its block scores can be negative; ranked through the clamp, every negative block
ties at zero and the selection is wrong. `signed` 1 ranks finite scores as they are (-0 tying +0)
and treats nonfinite ones as dead; absent or 0 is the ranking as it was. libref, libavx and libr4d
take it together, since the three declare one schema. docs/OPS.md; tests/r4d_emu/test_qsa.cpp
runs both rankings against the reference.
2026-10-19 20:13:47 +02:00
John McDonough 9e0e28315d vram_budget: the prefill staging region is paid by expert residency before the cache
With a lending cache the staging region (two buffers of one layer's off-card experts) always came
out of the cache, which left a large-context MoE model short of its configured coverage. Expert
residency above the host pool's floor now pays first; the cache pays only when the experts are at
their floor, and an expert with no other home is never evicted for it. The startup report names
whichever paid. mem_test (prefill_staging_*).
2026-10-19 20:13:47 +02:00
John McDonough 2c67e93342 engine: the one-sequence KV floor is the live plan's inverse, its state slots included
The floor a KV pool must keep for one --max-model-len request came from a separate plan at
max_seqs 1. A hybrid model's recurrent and conv slots are fixed per configured sequence and stay
allocated while one request is active, so that plan undercounted and the pool it allowed could
not hold max_ctx. The floor is now pool_mib_for_tokens over the real plan's groups. mem_test
(hybrid_context_floor_accounts_for_all_configured_state_slots).
2026-10-19 20:13:47 +02:00
John McDonough 385754f44f core/format: a Quark export whose excluded layers stay block-FP8; DeepSeek's expert counts
GLM-5.3-Flash's Quark export is MXFP4 throughout except the layers it excludes, attention and the
MTP layer, which it keeps as 128x128 E4M3 block-FP8 with F32 scales and names in
layer_quant_config. Every nonempty override map was refused. Each override is now checked: MXFP4
(fp4, per_group 32, e8m0) or block-FP8 (fp8_e4m3, per_block 128 128) passes, anything else --
including a null or empty weight, which flattening used to drop -- is refused by name.

The expert counts read n_routed_experts and n_shared_experts as DeepSeek-style configs spell them
(GLM-5's included). checkpoint_test covers both spellings, the mixed export, and the refusals.
2026-10-19 20:13:47 +02:00
keptn42 11334c8ed5 deploy/compose, README: Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B containers
Two containers on Hugging Face (keptn), each with a compose file and a row in the models table.
2026-10-19 20:12:09 +02:00
Memoria (Noblistic) 14c5c8a68b review: fix the stale note_ready comment, drop a tautological check
The note_ready comment claimed "the page divides by this figure", but the
submitted dashboard does not divide by startup_s (the payback formula that did
was removed). Reworded to describe the actual risk: a zero cost would price
every restart as free in any payback formula that divides by it.

Dropped CHECK(gap_pct >= 0) in the decode-floor drift test: recent >= floor
holds by construction (floor is the min of the window means, recent is one of
them), so the check can never fail. The load-bearing assertion is the adjacent
CHECK(gap_pct < 3).

Authored at: Tasmania Qwen 3.8 27B Dense XHigh (level not visible) via Open WebUI

(cherry picked from commit 98429a9b15d7da1aa0e644cbd7e519d1bf33d797)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) 8a4816dc8f dashboard: cap the decode-step percentage at ~99, not 100
100% would claim a sustained floor the ~500 ms poll window cannot
confirm, and would read as a bug the moment a fast stretch briefly beat
the 32-step floor. Cap at 99 and show it with a tilde: "now ~99% of
best" says "at your best" without overclaiming. Anything slower still
reads a plain percentage of the floor.

Operator-directed 2026-10-18.

Authored at: Tasmania Qwen 3.8 27B Dense XHigh (level not visible) via Open WebUI

(cherry picked from commit 7c35068e60d8a7baf61483e4d2a6452d71e0bc6f)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) 87882e4c9c docs/GUIDE: document the decode-step percentage and its 100% cap
The tile's detail line gained a third figure in 4fe6ff1 (now X% of best)
and a 100% cap in e083a2d; the GUIDE still described only the two engine
figures. Document the percentage: 100% is the fastest, anything slower a
percentage of it, capped at 100 because `now` is a ~500 ms poll mean while
`best` is a 32-step window mean, and keyed by concurrency above c1.

Authored at: Tasmania Qwen 3.8 27B Dense XHigh (level not visible) via Open WebUI

(cherry picked from commit 7263163748b98c1e5b5c9d4fa3e7fe8fed924678)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) 0a222c6723 dashboard: cap the decode-step percentage at 100%
`now` is a ~500 ms poll mean; `best` is a 32-step window mean. A fast
stretch shorter than a window can therefore read faster than the recorded
floor, which the ratio printed as >100% -- "105% of best", which is a
contradiction: if it beat the best, the best should have moved.

The engine only ratchets the floor on a completed 32-step window, so a
sub-window blip is not a new record. Cap the figure at 100: a live window
at or above the floor reads "100% of best" (at your best), and anything
slower reads a percentage of it. The "best X ms" figure is unchanged.

Operator-directed 2026-10-18.

Authored at: Tasmania Qwen 3.8 27B Dense XHigh (level not visible) via Open WebUI

(cherry picked from commit e083a2d606c2194539bd0640916fb0ae0852962e)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) 46c7dc26be dashboard: read the decode step as a percentage of the fastest, not a multiple of it
The suffix was a ratio of time (100 * lastStepMs / ref): the fastest step
read 100% and anything slower read ABOVE 100% -- 18.75 ms against a 15 ms
floor printed "125% of best". Slower meant bigger, which is backwards.

Flipped to a ratio of speed (100 * ref / lastStepMs): the fastest reads
100%, anything slower reads a percentage of it (the same pair now reads
80%), and the figure can never exceed 100% because ref is always the
minimum. The "% of best" label now says what it shows.

Operator-directed 2026-10-18; live-verified on the Tasmania lane
(best 33.73ms / recent 35.76ms -> "94% of best").

Authored at: Tasmania Qwen 3.8 27B Dense XHigh (level not visible) via Open WebUI

(cherry picked from commit 6540ff811addc15288e6fcaa09b37b6c82ee7ebb)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) 52a646431a dashboard: state the decode step as a percentage of the best at its own concurrency
The drift line carried a percent-of-best suffix that left with the drift
verdict on 10-18. Restored as a raw ratio, keyed by concurrency: a c8 step
against the fastest c8 step this process has done, never against the
single-stream floor (that cross-read is what made the old line lie about a
batch arriving). No threshold, no colour.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI

(cherry picked from commit 4fe6ff1c838d67b642cc12782ce6a441368c3d76)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) 5dfa61372a docs: devlog for the decode floor — the failures, and why they ended in simplification
The five-rung chain that produced step_ns_decode_best/recent: the raw min that
latched 1.16 ms, the two guards refuted by measurement before being built, the
phase gate that passed 38,820 checks and failed live, window averaging that kept
a 10%-low floor, and the advisory whose premise — step time ratchets with engine
age — survived a day of watching zero observations. The advisory was deleted,
not tuned: the gap it priced is operating load (3-11% on a healthy lane), and
the payback formula assumed a permanent gain the lane never offered.

Written for the next contributor tempted to add a gate, a smoother, or a verdict
here: each rung's temptation was to add mechanism, and each rung's cheap move
was to measure the premise first.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI

(cherry picked from commit 9260f8e646c95aa8537d5e632a948bc54653c2ba)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) cb6cd3f69a docs: explain the decode floor and recent window, and what their gap is not
The tile now shows two engine figures and no verdict, so the guide says what
they are: window means of 32 single-sequence steps, best the lane's most
favorable moment and recent its current one. The load-bearing sentence is the
one nobody can derive from the numbers: a gap of a few percent up to ~11% is
operating load on a shared card, not degradation, and not a reason to restart.
That claim is measured, not stylistic — the live lane held a flat floor while
its recent window moved 3-11% with what else the machine was doing.

Cross-references rad::DecodeFloor and the devlog for how the interpretation was
tested and withdrawn.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI

(cherry picked from commit 604617bd72b7360d3855acac5e96d82e51ef91b7)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) 845f0a5646 dashboard: state the engine's decode floor and recent window, without a verdict
The decode step's detail line now shows two figures the engine measures itself: the
fastest single-sequence decode window this process has run, and its most recent
one. Nothing is asked of the reader -- no ruler to type, no panel to open -- and
no conclusion is drawn.

Both come from the engine rather than the browser because the browser cannot
produce either well. A tab only sees the steps taken while it is open, and a floor
learned from a lane that was already degraded says "at your best" forever. The
engine sees every step and knows the concurrency of the step it timed.

Single-stream on both sides of the engine's own measurement. The floor is a
single-sequence window, so the engine keys it to one row: a decode step at eight
sequences is a different measurement, and reading it against a single-sequence
floor would report a batch arriving as a slowdown. On an engine too old to emit
the field, the page falls back to the fastest single-stream step this tab has
seen.

This commit previously also priced a restart, and that clause is removed here
after being built, deployed, measured, and refuted on live traffic the same day.
It compared the floor against the recent window, called the gap drift, and
computed a payback from startup_s. The gap is not drift. On a healthy shared lane
the floor held flat at 14.79 ms while the recent window moved between 15.2 and
16.5 ms -- 3% to 11% -- tracking what else the lane was doing: it froze when the
lane went idle and rose on a fresh short request, so it was neither context
length nor engine age. The payback formula assumes a restart's improvement is
permanent, so following it pays the measured 49 s bringup and re-drifts within
minutes; the line was advising a restart every 12 to 19 minutes forever, for a
gain that was never there. What floor-vs-recent actually measures is the distance
between the lane's most favorable moment and its typical one.

An earlier version of this clause also compared the engine's floor against a
median of the browser's per-poll means -- two instruments over different sample
counts, disagreeing by pure order statistics on a flat engine, a measured 7.7%
phantom drift. That is why the two figures shown now are both engine window means
of one stream at one size. They are honest numbers; only the interpretation was
withdrawn.

A verdict can return once someone observes what none of this data shows: step
time rising with engine age and staying up. Every excursion measured was load.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI

(cherry picked from commit 2eaf32201cb1a8c45857dfbb509a12acaa9ee216)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) d4998b1f75 server: report how long bringup took, as a raw figure
A restart's cost is the one number a reader needs in order to decide whether one
is worth suffering, and any guess at it would decide the answer by itself. The
server knows it exactly: the interval from process start to the socket listening,
on this machine, with this model and this cache state.

Emitted on /stats as startup_s, 0 until the server has listened. Raw figure only
-- the page no longer consumes it. It is here because it is the missing half of
any restart decision a human or a tool makes downstream, and because the
decode-step advisory that did consume it was withdrawn the same day it shipped
(see the following commit for what the live data showed).

Trailing zero-defaulted field on both SchedMetrics structs plus the adapter copy;
neither struct is ABI-pinned, so this is the sanctioned append.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI

(cherry picked from commit 76a9e2f7a28b8e034cfd56caa091792c68fe19b6)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) ed2da8c9da sched: record the fastest single-sequence decode step, for the dashboard to read
The dashboard's restart advice needs a reference the degraded engine is read
against. Asking a human to type a ruler is fragile (a stale or mistyped number
silently mis-advises) and cannot see steps taken while the dashboard tab is
closed. The engine sees every step and knows the concurrency of the exact step it
just timed (plan_.n_seq_decode), so it can keep the reference itself.

Records two figures over single-sequence decode steps: the floor (the fastest
window mean this process has measured) and the current (the most recent window
mean). Both are window means of one stream at one size, so the advisory compares
like with like. A min, not a max: drift only raises the CURRENT step, so the
reference a degraded engine is read against is its own demonstrated floor.
Single-sequence on purpose -- a decode step at eight sequences is a different
measurement, so keying the floor to one row keeps a batch arriving from being
misread as drift. A mixed step is excluded by the phase gate even when it carries
one decode row: that row shared the step with a prefill chunk an order of
magnitude dearer.

Why not a raw min over step brackets: step timing is host-side, and with
pipelining on the next forward pass is issued behind the current step's commit.
Behind a step with long host work -- a prefill chunk, or a decode step that saves
a KV checkpoint -- the decode pass is finished before its own bracket opens, so
the bracket holds readback and commit and no GPU work. It is a real step
advancing a real token, so no token-count or predecessor-phase guard catches it.
A raw min latches that degenerate on the first occurrence and never recovers:
measured live 2026-10-18 on a TP2 R9700 lane, 1.16 ms against a 15.55 ms mean on
the first request after bringup.

Why averaging alone is not enough: these degenerate brackets are not rare. At the
observed ~1.4% rate a min over hundreds of windows reliably lands on a
degenerate-heavy window, and the floor sits ~10% below the true floor -- still
phantom drift, because the engine can never reach a floor that was an artifact.
So a candidate is rejected BEFORE it enters a window when it is under half the
running mean of accepted steps: degenerate brackets sit at ~9% of a real step and
real single-sequence steps at ~96%, so the populations are ~10x apart and any
threshold between them separates them -- 0.5 is the midpoint of that gap, not a
value tuned to one distribution. Filtering at the step level is essential; at
this rate a degenerate dilutes inside a 32-step window to ~0.91x, which no
window-level threshold would catch.

The first window is recorded by neither figure. The rejection gate needs a
window's worth of accepted samples before it can judge one, so the first window
is un-gated by construction; recording it lets the floor latch an unreachable
value forever (measured: a 5% degenerate rate put the floor ~2% low through
bootstrap alone). The cost is one window -- about a second of single-stream
decode -- against a 46 s bringup and a 10 s repaint, so it is never observed.

The estimator is a small struct (rad::DecodeFloor) so it is testable on a
synthetic stream: the scheduler fixture runs steps in microseconds and cannot
manufacture a degenerate bracket, which is why the first round of tests missed
this. The tests feed streams laced with degenerate-short samples, assert a raw min
latches them, assert the estimator rejects them and tracks the true floor, and
assert the rejection does not eat real steps.

Emitted on /stats as step_ns_decode_best and step_ns_decode_recent (0 until the
first gated window completes). Trailing zero-defaulted fields on both SchedMetrics
structs plus the adapter copy -- neither struct is ABI-pinned (scheduler<->server
internal), so this is the sanctioned append. Matches the kv_tokens_max
running-extremum precedent.

Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI

(cherry picked from commit bf5a803deaa08ae0c2d94e2c3dda0d518c08d9aa)
2026-10-19 17:35:05 +00:00
Memoria (Noblistic) 51e6020998 dashboard: give the sparklines back their amplitude
Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI

(cherry picked from commit d1dd050d5165536885840fb485f7041706938f8c)
2026-10-19 17:35:05 +00:00
gearwave00001andClaude 72624973ad ref2va: merged-cell modulation lifts the reference-photo ceiling from five to nine
A modulation cell is a pure function of a segment's kind -- (modality ada,
timestep block) -- so all reference photos share one cell. Runs of consecutive
same-cell segments collapse to a group; group boundaries are a subset of the
fine segment boundaries and the merge is sequence-length independent (the key
is kind alone). The modulated norm now reads COARSER group boundaries via a new
trailing RadVideoGenBatch::mod_cu while attention keeps the fine seg_cu, and the
fixed-width table is pitched by GROUP count. Nine photos therefore occupy four
groups (prompt / all-photos / soundtrack / video); buffer sizes and the arena
are unchanged (kMaxSegs stays 8, no kernel change, no re-convert).

No regression for <=5 photos: each photo cell already filled its own column from
the same input rows and weights, so it was bit-identical to the others; merging
issues it once instead of N times and yields the same per-row value. Only the
previously-rejected sixth through ninth photos change, by being allowed.

Driver: rad_arch_video_mod_segs (trailing plugin export) computes the merged
groups host-side; the driver stages them into R_MOD, guards the GROUP count
against max_ref_segs at submit (a clean refusal beats a step-loop fault), and
the plain path stages the fine table into both operands.

Device-verified on dual gfx1201 / TP2 with a CONTROLLED same-seed battery
(task=ref2va, seed fixed on every job, so neither the seed nor the token count
is a confounder): same prompt, same seed, same ref-count, DIFFERENT image
content give DIFFERENT outputs -- the reference is genuinely consumed. Nine
photos complete (the case the pinned build refused at submit), whole-run fault
scan clean.

Adds docs/NOTE-REF2VA.md: what this port reproduces of the DaSiWa workflow and
what it does not -- the residual 8-group ceiling under heavy interleaved mixed
refs, the reference-token / row budget, continuity tail (unimplemented), the
video/audio reference paths (plumbed, not yet device-verified), references x
latent-upscale exclusion, and open conditioned-step parity.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 12:31:55 -05:00
gearwave00001andClaude 490d4c604a PIN ref2va: verified device differential + ref-count gate (revert anchor)
Ref2VA ref-image conditioning verified on-device: ref step runs all steps no
fault; output differs ref-present vs ref-absent (by log). 6-9 images rejected
cleanly at submit (no engine crash). Merged-cell modulation (<=9) tracked next.
NOTE: placeholder author -- re-author before any push. Do NOT push this branch.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-19 12:04:47 -05:00
NunzeandClaude Opus 5.5 e60810116c chat: tagged calls whose name the opener opens -- GLM-5's <tool_call>NAME<arg_key>
GLM-5 writes <tool_call>NAME<arg_key>K</arg_key><arg_value>V</arg_value>...</tool_call>: no
prefix of the name's own and no suffix, the name ends at the first argument or at the call's
close. The tagged family now takes an empty name_suffix when name_prefix opens the call (no
call_open): the derivation from the template makes the per-call opener the prefix and its closer
call_end, the grammar takes eps() for the suffix, and the streaming parser finds the name's end
byte by byte (name_stop, name_plausible) and reads the closing tag as the first item of the
body. arg_name_suffix and arg_value_prefix may both be set and are read back to back, so
chat_format_markers keeps both tags. value_newlines comes from a probe render of the template
rather than a constant (GLM and MiniCPM false, Qwen true). The ABI struct is unchanged; its
comments say what an empty name_suffix means now.

chatparse_test: GLM's template serves tools; the derived format equals the one a plugin would
declare; every rendered reply in the corpus reads back as the message it rendered, split at
every byte; and replies that stray from the grammar. Each fails without this change. The Gemma
refusal names call_end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-19 15:34:15 +02:00
NunzeandClaude Opus 5.5 5ac0bc9690 tests/data/chat: GLM-5.3's template as a fifth reference render
The template as GLM-5.3-Flash ships it, in cases.json beside the other four, with its goldens from
mkchatgolden.py (jinja2 3.1.6); bos is empty, eos <|endoftext|>, and no media, since no
architecture here reads its pictures. It needs the dotted index (vendor/patches/0021).

Two cases leave it out: an assistant turn with tool calls and content null. The template prints
that content bare ({{- content }} in visible_text), so jinja2 writes "None" into the turn, and the
engine, as llama.cpp's runtime does, writes nothing. The golden would hold the engine to a
template bug; the reply-side tests for this format read those turns instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:34:15 +02:00
mici81andClaude Opus 5.5 3e656f0b02 libr4d: review fixes -- the quantised stores apply v_scale; scales clamped so every code decodes finite; two more selftest shapes
kv_store_fp8v4 / k6v4 and the folds now read v_scale as the fp8 store does (attention already
applied v_descale). Scales are clamped to 8188 (V) and 2112 (K) so 7 or 31 times them stays an
f16: a group gone inf or NaN decodes finite, as E4M3's clamp to 448 does. r4d_selftest adds
decode at ctx 1000 (a partial last block) and q_len 7 (three waves) for both layouts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:28:21 +02:00
mici81andClaude Opus 5.5 1823ccd5e9 --kv-cache-dtype fp8_v4 | k6_v4 (RadBuildCtx::kv_quant, RadArchProbe::kv_quant_ok; ABI 23)
The flag sets the trunk's cache to E4M3 plus a RAD_KVQ_* layout; a plugin offers the layouts it
serves in its probe and the server refuses any other, naming the plugin. qwen35_fp8 offers both
at head_dim 256, gqa 6, and declares the group at head_dim 200 / 176 (the row's bytes / 2), so
the core sizes pages as for fp8; a drafter's cache stays fp8. Qwen3.8-27B on two R9700s, KL
against bf16 on 17 long documents: fp8 0.039963 (518,800 tokens of KV), fp8_v4 0.040076
(664,400), k6_v4 0.039965 (755,184); prefill and decode at fp8's speed. ABI 23: two trailing
fields, the layout table regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:28:21 +02:00
mici81andClaude Opus 5.5 c00a650bce libr4d: fp8_v4 and k6_v4 caches -- stores, folded prologues, h256/gqa6 attention
Two narrower layouts of an attention cache, a head's dims in groups of 32 with an f16 scale:
fp8_v4 (E4M3 K, int4 V; 25 * head_dim / 16 bytes a token and head) and k6_v4 (int6 K, int4 V;
22 / 16). kv_store and qk_norm_rope_gate_kv_store write them (the folds byte-identical to the
pairs); attn_prefill / attn_decode at h256 gqa6 widen the codes to f16 in a tile's staging, V a
key pair's 8 dims a thread fetched a tile ahead and widened with packed f16 (one rounding, a
dword store holding both keys), K6's high bits laid out so one mask and shift join them to the
low nibbles. r4d_selftest: the stores against an exactly representable set, the folds, and the
attention rows against the inline oracle extended to the layouts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:28:21 +02:00
NunzeandClaude Opus 5.5 a14fab2317 jinja: a dotted integer is an index, as in jinja2 -- llama.cpp's #28817
jinja2 reads `obj.0` as `obj[0]`; the engine threw "Static member property must be an
identifier". GLM-5's template tests a tool result with `m.content.0.type`, and the capability
probe swallows the throw, so the template came back as tools=0 tool_calls=0 and every request
with `tools` was refused.

The fix is llama.cpp's ae9afff8, which landed after the lifted commit, taken as it is so the next
refresh drops it. vendor/patches/0021, vendor/UPSTREAM; chat_test
(a_dotted_integer_is_an_index_as_in_jinja2) fails without it on both counts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:27:18 +02:00
NunzeandClaude Opus 5.5 da1ffff9a8 docker: the test stage can leave entries out (TEST_EXCLUDE, build.sh -E)
Without perf_event_open in the build sandbox, tokenizer_perf_test bounds the encoder's linearity by
CPU time. Its 500 KB single word reads a ratio of 10 to 12 against the threshold of 9 on a Zen 2
VM with 512 KiB of L2, every run, with the tokenizer unchanged. A ctest -E regex lets such a host
build the image without the threshold moving for everyone. Empty by default. docs/DOCKER.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:37:01 +02:00
NunzeandClaude Opus 5.5 748f63637e docker: the test stage's parallelism and CPU budgets apart from the compile (build.sh -J, -B)
The per-binary CPU budgets are set on a fast machine. A VM on an EPYC 7302 spends 4.6x the quoted
CPU time on tokenizer_test's reference pass, so the image's test stage failed there on a correct
tree, and -j sized for the compile also sized the tests: twelve at once on a 24-thread host put
tests on busy SMT siblings, which costs CPU seconds too.

RAD_TEST_CPU_BUDGET_SCALE multiplies the budget where rad_test.h reads it, at run time, so a
direct ctest takes it as well and the build layer is untouched by it. The stage takes it as
TEST_CPU_BUDGET_SCALE (build.sh -B) and its parallelism as TEST_JOBS (build.sh -J), each empty by
default, which is the stage as before. harness_test checks the factor and keeps it out of its
fixture's environment; docs/DOCKER.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:37:01 +02:00
mici81andClaude Opus 5.5 44aecb0ab8 arch/gemma3: review fixes -- calibration declares no fused junction, so no container writes zero Grams; docs corrected
On an MXFP4 container the fused junctions skip the bf16 activations the tap reads, and q/k/v and
gate_up Grams came out zero without a word (down likewise behind gelu_mul_quant_i8). Under
RADIANCE_CALIB_DIR no junction or fused down-quantiser is declared, so any container
calibrates, unfused; checked on the production MXFP4 container. RADIANCE_G3_CALIB_LAYERS
refuses trailing characters. Docs: which trunk fuses what, the four-stream numbers' two
workloads, which sizes are tested. arch_test's world-2 check counts the post-norm op.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:44:46 +02:00
mici81andClaude Opus 5.5 f2c0468335 docs, recipes, compose: TranslateGemma 27B
The gemma3 section of ARCHITECTURES.md (geometry, traps, KV groups, linears, calibration,
measurements, the DFlash2 drafter), the calibration variable and the conversion of record in
GUIDE.md, the README's models table. Recipes: the int8 calibration container (KL 0.003),
MXFP4 + GPTQ (KL 0.042, 56 tok/s a stream on two R9700s), and with a drafter. The compose file
serves a plain Gemma 3 template: TranslateGemma's own refuses the startup render's plain turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:44:46 +02:00
mici81andClaude Opus 5.5 a91a2837ff arch/gemma3: Gemma 3 dense text (TranslateGemma 27B), per-(row, 128) activation linears, DFlash2
gemma4_bf16's block structure with Gemma 3's differences (modeling_gemma3, transformers 4.57):
GemmaRMSNorm everywhere, one head geometry, scores at query_pre_attn_scalar^-0.5, linear rotary
scaling on the global layers only, the bf16-held embedding scale, no value norm, soft-capping
and YaRN refused. Linears i8a8, mxfp4a8 and w4a8i8_asym over an activation scaled per
(row, 128), beside bf16 and w4a8 / w8a8: one int8 scale a row costs KL 0.097 at w8a8 on
Gemma 3's outlier channels. Fused junctions on a quantised trunk. A calibration tap
(RADIANCE_CALIB_DIR, RADIANCE_G3_CALIB_LAYERS), the column-split linears as rank parts.
A DFlash2 drafter as qwen35_fp8 declares one; rad_block_dflash2.h applies the drafter's
input_embedding_scale through embed_lookup's mult when it is not 1, so other drafters'
graphs are unchanged. Against transformers' float32 forward on a tiny Gemma 3: KL 0.00016 on
the host backend and the cards. arch_test: 7 cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:44:46 +02:00
mici81andClaude Opus 5.5 f92cce07f1 libr4d: Gemma 3's rows -- windowed h128/gqa2 attention, qkv_norm_rope at h128 without a value norm, ar_rmsnorm_post_quant_fp8
- r4d_attn_paged_h128_gqa2w.hip: decode and query-tiled prefill at head_dim 128, gqa 2,
  window >= 1, instantiations of the h256/gqa6 templates with WIN = 1 (as h256_gqa2 for
  Gemma 4); the h128/gqa2 rows keep window 0.
- qkv_norm_rope: head_dim 128, and an optional v_norm (0 leaves v alone).
- ar_rmsnorm_post_quant_fp8: ar_rmsnorm_quant_fp8 with a post-norm of the reduced sum against
  w_post before the residual add (the sandwich junction), exact wire only. Its own op: an
  optional seventh operand on ar_rmsnorm_quant_fp8 broke every plugin issuing its six.
r4d_selftest: the windowed rows against the inline oracle over a history past the window, and
qkv_norm_rope at h128 / v_norm 0 byte-identical to its chain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:44:46 +02:00
eddie168168andClaude Opus 5.5 37deff85ca data/recipes: q38-27b-w8a8-df2, Qwen3.8-27B with an int8 trunk, an int8 head and the DFlash2 drafter
From the bf16 release: the trunk's linears RTN int8 under fwht128 (weight error 6.3e-3), the
lm_head int8 (6.8e-3), the drafter as q38-27b-fp8-df2.recipe makes it; 29.0 GiB. Against the
bf16 model over 45K mostly-Go positions: mean KL 0.00051 and 99.25% top-1, against 0.00404 and
97.75% for Qwen's FP8 release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:42:13 +02:00
eddie168168andClaude Opus 5.5 5d11c7c200 qwen35_w8a8: qwen35_fp8.cpp built for a rotated int8 trunk
A third build of the qwen35 source, as qwen35moe_fp8 is, claiming (qwen35, w8a8_fwht128).
Behind QWEN35_W8A8: check_format's method and fmt, a probe of the first delta-net input
projection that learns the trunk is rotated int8 before the activations are declared (and refuses
one that is not, plain int8 included: the descriptor names the rotation), and the plugin
identity; the four trunk activations then carry int8 code pairs.

It declines imported checkpoints (RAD_ARCH_SERVES_IMPORTS(0)): as the family's second quantised
plugin it would make every imported Qwen3.8 release (Quark, ParoQuant, GPTQ, NVFP4) refuse, so
those stay with qwen35_fp8.

arch_test: every trunk linear an i8a8h GEMM behind its own quantiser at one and two ranks, the
refusals (no int8 trunk, a plain one, another format, no fmt), lint clean with the MTP head and
with DFlash2, and two ArchCases (pinned graphs; libref's vocabulary serves it at one rank).
shipped_plugins_test lists the new key and holds each shipped family to at most one plugin that
takes imports. ARCHITECTURES.md and GUIDE.md list the plugin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:42:13 +02:00
eddie168168andClaude Opus 5.5 2ac0d966b3 arch/common: the MLP's gated fold is an fp8a8 tile; an int8 gate_up takes the pair
decl_gated_fold was declared for any gate_up that was not bf16, MXFP4 or rotated 5-bit, so an
int8 one got an fp8a8 fold over int8 codes. Only a host kernel took the op, and placement then
pinned every layer group's weights to the host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:42:13 +02:00
eddie168168andClaude Opus 5.5 3c01aacef2 arch/common: LinearFP8 serves a rotated int8 weight at i8a8h behind had_quant_act_i8g
linear_is_w8h recognises i8*bf16[1x128]/fwht128; probe() reports it as int8 so the producer
writes the bf16 plane, and declare() quantises it with had_quant_act_i8g. A rotated weight fed
codes its producer wrote (ActFP8::q8_fed) is refused: those codes are unrotated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:42:13 +02:00
eddie168168andClaude Opus 5.5 0b0403603b core: an architecture plugin can decline imported checkpoints
An imported quantisation names its tool, which no plugin claims, so the family's one quantised
plugin serves it and two are refused. rad_arch_serves_imports(), optional and absent = yes, lets a
second quantised plugin that reads only its own containers return 0: the import pick then leaves
it out of the family, neither counted nor picked as the only plugin. Its own descriptor still
selects it. Additive export; RAD_ABI_VERSION does not move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:42:13 +02:00
eddie168168andClaude Opus 5.5 f706caecec docs: i8a8h in OPS.md's dtype list; had_quant_act_i8g folds nothing
Its consumer's scale carries the whole 1/group, as had_quant_act_fp8's does; the per-row had_*
int8 forms fold 1/sqrt(group) and are not interchangeable with it. TOOLS.md: libr4d reads the
int8 block rows rotated too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:42:13 +02:00
eddie168168andClaude Opus 5.5 61afe50b96 libref, libavx: had_quant_act_i8g, the activation of the i8a8h GEMMs
had_quant_act_fp8 at int8 codes (top 127), one body shared by both in each library, so a
rotated int8 trunk runs on the host kernels too. gemm_nt_q needs no change: both libraries pick
the int8 product from the operands' dtypes, and i8a8h's rotation is in the values. libref's
operand description takes i8a8h, and rad-avx-check gains cases for the op and the dtype.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:42:13 +02:00
eddie168168andClaude Opus 5.5 037427e67e tests: a rotated int8 group decodes back through the Hadamard
libquant's rtn at codes=i8 group=128 scale=bf16 transform=fwht128, decoded through the core:
the weight gemm_nt_q reads at i8a8h comes back as its source, with less error than the plain
grid on a source with outliers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:42:13 +02:00
eddie168168andClaude Opus 5.5 83856506e1 libr4d: i8a8h -- the int8 trunk GEMMs read a weight rotated by fwht128, against had_quant_act_i8g
gemm_i8a8_nt_m16 and gemm_i8a8_tiled take dtype i8a8h: the same launch over i8 codes rotated by
the unnormalised 128-wide Hadamard along K, the 1/128 in the bf16 scale (libquant's
transform=fwht128). The layout hook accepts only the transform its dtype names and tags the
rotated codes r4d.i8h.w.frag64, since the bytes cannot tell the two forms apart.

r4d_selftest's i8a8h_rot measures the pair against the exact f32 product: rel_l2 0.009-0.012
rotated, 0.012-0.014 plain, ~1.0 for the rotated weight against the plain quantiser. The
had_quant_act_i8g row now says the factor of 128 is the weight's, not sqrt(128).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:42:13 +02:00
mici81andClaude Opus 5.5 cec70ad1c7 libquant: review fixes -- loops kept as the LAPACK reference (RAD_LQ_LAPACK=0) and tested against it, NaN pivots refused, 4 layer factors kept
The single-threaded loops stay beside LAPACK; RAD_LQ_LAPACK=0 takes them and
gptq_through_lapack_matches_the_loops compares the two (output error equal to rounding). A
factor whose diagonal is not finite and positive is refused, as the loops refused a NaN pivot
that dpotrf lets through. The cache keeps the 4 most recent layer factors: a MoE layer's
experts alternate between two stems. The size in the comment is the f32 factor's, 1.85 GB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:41:22 +02:00
mici81andClaude Opus 5.5 400bbefa13 libquant: a column-split linear's Hessian from per-rank parts
Under tensor parallelism an attention output or down projection sees only its rank's K / world
columns, so no rank can write the K x K Gram. A tap may write each rank's block as
<stem>.part; with no whole file calib_sum places the parts on the diagonal in rank order (the
cross-rank products, never formed, zero) and converts the result like a whole file. Parts that
do not cover K, or not in domain 0, are reported and the weight rounds to nearest. Tested
byte for byte against the whole block-diagonal file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:41:22 +02:00
mici81andClaude Opus 5.5 c94a0e6cc2 libquant: GPTQ's factorisations through LAPACK where OpenBLAS is found; one layer's factor at a time
At K = 21504 (a dense 27B's down projection) the single-threaded Cholesky and inverse took hours
a layer; dpotrf / dpotri take 13.5 s for all three on 24 cores, identical to 1e-14. Without
OpenBLAS nothing changes. The factor cache kept every layer's factor, 3.7 GB each at that
width, which OOM-killed a 62-layer conversion at layer 25; it now keeps one at a time (a layer's
experts arrive together and still share it). RAD_LQ_FACTOR_CACHE_ALL keeps the old behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:41:22 +02:00
mici81andClaude Opus 5.5 d82c11644e libr4d: review fixes -- a tuned ar_ln_had_quant_i8 count under the ceiling; say which gathers it cannot cap
ar_ln_had_quant_i8 clamped a tuned block count to M only; it stays under R4D_AR_MAX_BLOCKS
now, as every other entry's. The MoE hyper-connection gathers keep the minimum their LDS table
needs, which may exceed the ceiling: the comment and GUIDE say so instead of "every
collective". r4d.h states that a refused IPC export leaves the handle zeroed, out_len 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:39:53 +02:00
mici81andClaude Opus 5.5 1d1cb21e02 libr4d: R4D_AR_MAX_BLOCKS, a ceiling on collective blocks for two engines on one set of cards
Every block of a collective spins until its twin on the peer card has pushed. One engine is safe
(both cards dispatch its blocks in the same order); two tensor-parallel engines on the same
cards can deadlock, one engine's spinners filling a card while their twins wait behind the
other engine's kernel. Two TP2 engines on two R9700s hung within a minute of concurrent
prefill and the failed queue eviction froze the host. Capped in both engines so their spinners
together leave part of a card free, the cycle cannot close: 15 minutes of concurrent load
clean at 64 / 16. Only launch counts shrink; each element's sum is the same. Unset, nothing
changes. GUIDE section 8 documents it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:39:53 +02:00
mici81andClaude Opus 5.5 fb7a30cd84 libr4d: a refused IPC export is not fatal
r4d_ar_ipc_alloc exports every collective buffer with hipIpcGetMemHandle. Beside another
process holding the same cards it answers invalid argument while the allocation is fine, and
HIPOK stopped the engine. libr4d's ranks are threads of one process and share the pointer
itself, so the handle is never read: a refused export leaves it empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:39:53 +02:00
NunzeandClaude Opus 5.5 6fb31c0577 docs/GUIDE: eight cards on unequal links -- weighted shards, pieces and their environment
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:38:33 +02:00
NunzeandClaude Opus 5.5 2c0dd8535e sample: at eight ranks a rank keeps the candidates the merge can hold
Over a split vocabulary every rank's candidates are gathered and merged in one workgroup
(sample_merge_topk), and libr4d's row holds world_size * n_cand <= 4096 pairs in LDS. The engine
declared the default 1024 a rank, 8192 pairs at eight ranks, and the first step stopped on a shape
the merge does not serve. Declare now narrows the width to 4096 / world_size, 512 at eight ranks,
and says so in one line; a request whose top_k is wider is refused at admission, as a top_k over
the width already was. Two and four ranks keep 1024.

sample_test: at two, four and eight ranks declare succeeds, top_k at the width is admitted and one
more is refused, naming the width.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-19 10:38:33 +02:00
NunzeandClaude Opus 5.5 279214f520 libr4d: the eight-rank two-shot's shard weights from the PCIe links by default
Weights from a variable describe one board on one day. Unset or "auto", RADIANCE_AR8_SHARD_WEIGHTS
now reads them from the links: each rank takes its card's bus id from the runtime
(hipDeviceGetPCIBusId), walks /sys/bus/pci/devices from the root port down to the card as
core/diag/sysinfo.cpp's read_card does, and keeps the slowest hop's current speed x width x line
code (8b/10b under 8 GT/s, 128b/130b from there) / 8. The R9700 sits behind an on-card switch
whose endpoint reports Gen5 x16 in any slot, so a degraded slot shows only at the root port. The
weight is round(4 x (rate / fastest)^2): x16 4, half the rate 1, a quarter 0. On the board of the
previous commits that is the measured best, 4,1,0,4,0,1,4,4, and after both Gen4 links retrained
at Gen5 x8 it is 4,1,1,4,1,1,4,4, where the 16 MiB two-shot takes 1360 us. "off" keeps the shards
even and eight integers set them, as before.

The ranks publish their links in the rendezvous (ar8_settle) and, after one barrier, derive the
same table from the same eight entries before anything is sized; settings that differ between
ranks fail init on every rank. Equal weights run the unweighted kernel, and a rank whose path says
nothing (no /sys/bus/pci in a container) leaves the shards even, with a warning naming it. Startup
logs one line, "[r4d] eight-rank two-shot shard weights from the slowest PCIe hop of each card: r0
32.0 GT/s x16 63.0 GB/s w4, r1 32.0 GT/s x8 31.5 GB/s w1, ...". The links are read once, at init:
a link that falls back while the server runs changes the weights at the next start.

r4d_ar_links_test builds that board's sysfs under a temporary root (root port, on-card switch,
endpoint) and checks the bottleneck hop, the weights before and after the repair, equal links, the
line code and a path that says nothing; it needs only libr4d's include path. r4d_selftest runs
auto and off at the default floors, for bits only since what auto derives depends on the box, and
--perfar8 derives the weights the same way and names each rank's link. 206 of 206 on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:38:33 +02:00
NunzeandClaude Opus 5.5 adc7f37a70 libr4d: the eight-rank two-shot in pieces, both hops on the link at once, by message size
Each block splits its words (in shard space) into K runs. Step j pushes run j+1's first hop and
reduces and pushes run j's second, then handshakes, so a rank with a short shard sends and
receives at once instead of one direction a hop. A launch takes K+1 handshakes instead of two.
The flag a (block, source) publishes is a monotone counter, so one handshake vouches for every
earlier one, and r4d_ar_seq_take reserves the K steps at once (`steps`, 1 for every other kernel):
one-shots and gathers on the same instance stay in the family's flag space. The regions stay at 0
and the longest shard, so the scratch is as before; every word is touched by the same thread in
the same three steps, so the fold, the bits and the in-place form are unchanged. The launcher
clamps K to the words a block holds, and K 1 is its own instantiation without the loop.

  16 MiB, bf16, warm   K 1      K 2    K 4    K 8
  even                 2841 us  2806   2667   2470
  4,1,0,4,0,1,4,4      2730     2126   1798   1636
  4,2,1,4,1,2,4,4      2495     2121   1940   1922

4,1,0,4,0,1,4,4 in 8 pieces is 42% under the even split. Fitting measured = f x computed + h x
(K+1) at K 4 and 8 gives f = 1.21 and h about 5 us a handshake: what separates 1636 us from the
1.17 ms the Gen4 links need is their efficiency, not the handshakes.

A decode-sized message loses with either:

  numel      even K 1   4,1,0,4,0,1,4,4: K 1 / K 2 / K 4 / K 8
  196608     73 us      85 / 76 / 81 / 113
  524288     214        207 / 166 / 169 / 198
  2097152    699        711 / 581 / 531 / 527
  8388608    2841       2730 / 2126 / 1798 / 1636

so below RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS and RADIANCE_AR8_PIECES_MIN_ELEMS (262144 elements
each) the message runs even and in one piece, on the kernel as it was. Above them, without
RADIANCE_AR8_PIECES, K follows the size (r4d_ar8_auto_pieces): 2 under 1048576 elements, 4 under
4194304, 8 above, where the crossings above lie. RADIANCE_AR8_PIECES (1 to 16) fixes K over the
floor, and a launch's `pieces` parameter (the selftest's) overrides that. Weights and K are a
function of the message size and the instance (ar8_weights_for, ar8_pieces_for), so a replay of
the same size decides the same; the slot is sized for weights only when the largest message is
over the weight floor. Every rank compares both variables and both floors at init.

r4d_selftest, with both floors at 0: the weighted and even sets at K 1, 2 and 4 (1- and 9-word
messages cross the launcher's clamp), and one instance whose K changes from launch to launch (1,
4, 2, 8, 16, 3, 1), which a wrong flag reservation hangs or races. At the default floors: the size
rule over 131072 to 4194304 elements, K 4 on both sides of the piece floor, a 131073-word message
over the weight floor (served only weighted) and a 9-word one under it (refused, and served at a
floor of 64). 192 of 192 on the cards. --perfar8 names the floors and times the two-shot as the
server runs it and at K 1, 2, 4 and 8.

GLM-5.3-Flash at TP8 (an out-of-tree plugin) on these eight cards with 4,1,0,4,0,1,4,4, against
the same build without in the same hour: a 20K-token prefill 3450 tok/s against 2945, 8K 3372
against 2920; eight agent streams 457 tok/s against 458, one 141 against 139. K 8 at every size
instead gave the same prefill (3461) and 436 at eight streams, 113 at one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:38:33 +02:00
NunzeandClaude Opus 5.5 4777be8654 libr4d: the eight-rank two-shot's shards weighted per rank (RADIANCE_AR8_SHARD_WEIGHTS)
In the two-shot rank r reduces shard r: in the first hop it sends N - len_r and receives
(ws-1)*len_r, in the second the reverse. With even shards every rank moves 1.75 N each way at
eight ranks, so on a board whose links differ the slowest link sets the time. On eight R9700 (four
links at Gen5 x16, two at Gen5 x8 and two that trained at Gen4 x8, 14.3 GB/s one way by
TransferBench) the 16 MiB two-shot, a 2048-token chunk at 4096 wide, takes 2.45 to 3.05 ms over a
day, where the Gen4 links alone need 2.05 ms for their 28 MiB.

RADIANCE_AR8_SHARD_WEIGHTS=w0,...,w7 sizes rank r's shard in proportion to w_r (the floor, then
the few remaining words one each to the weighted ranks in ascending order); a rank of weight 0
owns no shard and only pushes, gathers and handshakes. The shard bounds become a table the kernel
takes by value (r4d_ar_shards.h, host-only, shared by the launcher, the shim and the selftest), so
a recorded launch keeps its table. Equal weights give the even split word for word, and unset the
split is the even one as before; three and four ranks stay unweighted. Which rank reduces a word
changes the link it crosses, not its fold, so every table gives the same bits.

Every rank must cut the message at the same words: init reads the variable on each rank and fails
on all of them if the ranks disagree. A weight over half the sum makes the longest shard's two
regions outgrow a message, and only then does init grow the slot. Weighted shards need not divide
the words evenly, so the even rule (words % 8, else RAD_E_SHAPE) applies without weights only.

Measured with --perfar8 (16 MiB, bf16, warm): even 2.78 to 3.05 ms that day, 4,1,0,4,0,1,4,4 (no
shard on the Gen4 ranks) 2.71, 4,2,1,4,1,2,4,4 2.50, 2,1,1,2,1,1,2,2 2.58. Only 10 to 17%: with
the hops separated by a handshake a rank sends in one and receives in the other, and the larger of
N - len and 7 len a hop is least at len = N/8. The weights pay once the hops overlap.

r4d_selftest: ar_wide_weighted runs 0,3,1,0,5,1,2,4, 1,0,0,0,0,0,0,0 and 4,1,0,4,0,1,4,4 over
uneven and empty shards, a single owner (the slot grows) and messages of 1 and 9 words, which the
even split refuses; the refusal check runs without weights whatever the environment. 55 of 55 on
the cards, every one bit for bit with the fold. --perfar8 prints the weights, every size's shard
lengths and each rank's time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:38:33 +02:00
NunzeandClaude Opus 5.5 0eb3d96ce1 libr4d: at eight ranks the exact one-shot ends at 8192 elements, the two-shot at 8 blocks
The exact all-reduce at eight ranks shared the three- and four-rank band: one-shot up to 524288
elements. The one-shot sends (ws-1)*N bytes a rank, seven times the message at eight ranks, where
the two-shot sends 2*(ws-1)/ws*N, and on eight R9700 (PCIe P2P, bf16, warm) the two-shot is the
faster from 16384 elements on. A decode step of eight streams with a draft window of six on
GLM-5.3-Flash (4096 wide, an out-of-tree plugin) reduces 48 x 4096 = 196608 elements: 232 us
one-shot, 68 us two-shot, where all_reduce was 20.7% of the step's device time.

R4D_AR_8RANK_ONESHOT_MAX_ELEMS is 8192, a multiple of 64, the eight-rank two-shot's DIV;
cArTsExact8 starts one element above it. The two-shot's block rule stops at 8 blocks at eight
ranks: every block handshakes with seven peers, and past eight blocks the extra flag rounds cost
more than the reduce bandwidth they add (4 blocks up to 393216 elements, 5 at 524288, 8 instead of
16 from 2097152). Both rows fold in fp32 in ascending rank order, so neither change moves a bit.

  numel      before                    after
  4096       one-shot         22.5 us  one-shot nb 4    12.8 us
  16384      one-shot         39.7     two-shot nb 4    21.5
  131072     one-shot        176.3     two-shot nb 4    52.3
  196608     one-shot nb 16  233.2     two-shot nb 4    68.7
  524288     one-shot        573.7     two-shot nb 5   177.4
  2097152    two-shot nb 16  615.8     two-shot nb 8   610.5
  8388608    two-shot nb 16   2460     two-shot nb 8    2489
  16777216   two-shot nb 16   4999     two-shot nb 8    4824

At 4096 the rule already chose 4 blocks; the 22.5 us was the microbenchmark's, ten launches after
the host-side check, which now warms up with as many launches as it times.

Band edges are the union over every candidate row (core/plugin/bands.cpp), so the edge at 8192
splits the two-, three- and four-rank bands too. Both halves resolve the same row, kernel and
bits, at the cost of one more instance per (width, dtype) whose slot holds 8192 elements. Keeping
the edge to eight ranks would need the band builder to skip rows whose fixed constraints the
geometry rules out (world_size 8 here), a change to every op's bands for one row; plugin_test
states the new edges instead.

r4d_selftest runs the eight-rank rows (ar_oneshot_8rank_exact, ar_twoshot_8rank_exact,
ar_gather_8rank) through the width-parametrised cases of the three- and four-rank ones instead of
skipping them: the pattern's band edge is at 8192 and 8256 there, and a 9-word message must be
refused. --perfar8 numel [iters] [dtype] times both rows, one thread a card, at the block rule
and at 4 to 64 blocks, each checked bit for bit against the fold on every rank. On the cards:
ar_oneshot_8rank_exact 20 ok, ar_twoshot_8rank_exact 16 ok, ar_gather_8rank 5 ok.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-19 10:38:33 +02:00
davetha 8015d9a639 json-schema: control-character escapes match their JSON escape; other class escapes are refused
Inside a class, escapes GBNF does not know ([\b], [\f], [\v], [\0], an escaped space, \p{..}, \c,
a backreference) were copied raw and the grammar then failed to load, an internal error on a
schema the converter had accepted.

A JSON string holds a control character only as an escape, so \t \n \r \f \v \0 (and \b in a
class) now match that escape, in a positive class as alternatives beside it and in a negated
class by leaving the escape out. Outside a class the escape is a group, so a quantifier takes all
of it. An escaped space or non-ASCII character is itself; \x and \u in a class need their hex
digits. Any other class escape is refused at conversion with a message naming it.
vendor/patches/0020, vendor/UPSTREAM; gbnf_test cases.
2026-10-19 10:38:06 +02:00
davetha 12735a62dc json-schema: identity escapes of punctuation are read as the character
Patterns written in JavaScript escape punctuation that needs no escape: "\/" in a path, "\-" in
a class. zod's email pattern carries "[A-Za-z0-9_'+\-]", so any tool validating an email with zod
sent a schema that was refused outside a class ("Unsupported regex escape") or, inside one,
produced a grammar that failed to load.

Outside a class such an escape is now the bare character; regex syntax characters and '"' keep
their backslash. Inside a class it is written \xHH, so an escaped '-' or '^' cannot read as a
range or a negation. Found by running 203 patterns harvested from installed agent packages
through rad-gbnf-check. vendor/patches/0019, vendor/UPSTREAM; gbnf_test cases.
2026-10-19 10:38:06 +02:00
davetha dd56e1158d json-schema: \d \w \s and their negations are written out as classes
\d \w \s \D \W \S were refused in a literal ("Unsupported regex escape") and copied raw into a
class, where GBNF cannot load them. Tool schemas use them freely: oh-my-pi's workpool tool sends
"\S" thirteen times, so with 0017 its requests got past the anchors and were refused here.

Each shorthand is written out as its ECMA-262 class before the scanner reads the pattern. The
negated forms leave out '"', '\' and the control characters and admit any JSON escape instead, so
a match cannot run past the closing quote; \s also admits \t \n \f \r. In a class a positive
shorthand becomes its ranges and [\s\S] and its kin become any text; a negated shorthand mixed into
a class is refused. vendor/patches/0018, vendor/UPSTREAM; gbnf_test cases, and sample_test's
"cannot spell" case moves from \d to \b.
2026-10-19 10:38:06 +02:00
davetha 52f47505c2 json-schema: a pattern without ^ or $ searches, as JSON Schema reads it
_visit_pattern() read only ^...$ and refused every other `pattern` with "Pattern must start
with '^' and end with '$'". JSON Schema patterns are unanchored (ECMA-262 search, validation
6.3.3). Since 1.8 constrains tool-call arguments with a grammar, a bare pattern on array items
failed the whole request: an opencode agent's tool list did, on every request.

A missing anchor is now written out as any string text on that side, (?:[^"\\]|\\.)*, not ".*"
('.' matches '"' here, so on array items ["1","x"] read as one string holding a digit). A
one-sided anchor beside a top-level '|' is still refused. vendor/patches/0017, vendor/UPSTREAM;
tests in gbnf_test (json_schema_grammars_admit_exactly_their_instances) and sample_test (an
empty pattern now matches every string).
2026-10-19 10:38:06 +02:00
eddie168168andClaude Opus 5.5 35b357825e tests: the oot test builds libr4d at the tree's RAD_HIP_VOPD_REPEATABLE
oot_plugins.sh gave libr4d's out-of-tree configure the tree's HIP compiler and targets but not
RAD_HIP_VOPD_REPEATABLE. In a tree configured as the build image configures it (ON, for the
patched LLVM 24), the out-of-tree libr4d was compiled with VOPD pairing off and step 5 found
different device code. The option is now the script's sixth argument (default OFF), forwarded to
the device libraries' configure. In radiance-build, ctest -L oot failed at step 5 and now passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:37:07 +02:00
mici81andClaude Opus 5.5 df030c7483 core/text: added (non-special) tokens go through the decoder chain, as in HuggingFace
Gemma's tokenizer.json spells runs of 2-31 spaces as added, non-special tokens in U+2581
(ids 138-167). piece_at returned every user-defined token literally, so indentation and
double spaces in a Gemma reply came out as U+2581. HuggingFace runs every token it keeps
through the decoder; now a user-defined token does too, and only control and unknown
tokens stay literal. decode, the Detokenizer and TokenView change together. tokenizer_test
covers it with a Gemma-shaped tokenizer.json.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:36:27 +02:00
sfjes f10c8521cd --host-headroom-mib N: the RAM radiance leaves free for the system at startup becomes a flag -- kLockMargin's fixed 4 GiB suited a busy server, and a 30 GiB host paid it in dead RAM to no purpose: startup refuses a host pin unless available memory covers it with that much still free, and --checkpoint-slots auto's bound is priced with it; so when 1.7.0 began counting the checkpoint store against this check, configs that 1.6.0 ran refused to start and the fix cost a quarter of the prefix cache. 2026-10-19 10:35:58 +02:00
baKon d37639ef71 prefix cache: a reserved snapshot is a save target until its commit (#129)
A checkpoint reservation (Scheduler::reserve_ckpt, at planning) is written only after the
step (Engine::checkpoint_save), and nothing between the two checked that the slot was still
the reservation's. A later reservation in the same step that found the store full ran
retention over every session, and the policy, placing its ladder from each session's tip,
could release the very slot just handed out: a second request's reservation lands on a
snapshot a first session already holds (the same prefix, so the same key) below that
session's tip, or a lookup's take_over indexes a fresh reservation under a session whose
ladder does not keep it. The save then faulted in checkpoint_copy ("the store does not hold
that slot ... given back after its id was handed out"), the step loop read the negative as a
device fault, and the engine exited with every in-flight request (#129: every 25-50 min
under multi-session agentic load, the store not full at the fault, 12-15 of 16 in use --
the eviction itself had freed the rest).

A reservation now keeps its slot the way a handed-out snapshot does: retention, the LRU
eviction and expiry skip it from reserve_checkpoint until commit_checkpoint, or until the
next step begins when the save was skipped (its request gone), so a skipped save cannot hold
a slot for good. The engine issues every save before it plans the next step, so the window
covers the copy. A reservation that finds every slot handed out or awaiting a save is
refused as before (ckpt_refused) and the chunk goes without a snapshot.

mem_test: the two cases, the shared-prefix one at the position geometric backoff releases,
and a step boundary (begin_step) in the three cases that reserve several snapshots in a
row without committing, as the engine does one per step.
2026-10-18 22:53:56 -05:00
Deadcode 816e24bd46 radiance 1.8.1
- MiniMax-H3 and FastH3 no longer stop the server on a prompt longer than 16 tokens (FastH3) or
  128 tokens (MiniMax-H3)
- latent upscaling for the MiniMax-H3 containers: with LBH-123-AI's latent upscaler in the
  container, `latent_upscale` runs the first steps at a smaller size and refines the latent at the
  full size; `upscale_refine_steps` sets how many steps refine, and the video object reports both
- rad-convert --in-place extends a container whose weights the plugin has regrouped since
- plugin ABI 22: out-of-tree plugins must be rebuilt
2026-10-18 15:41:44 +02:00
Deadcode 7a7707a955 radiance 1.8.0
- video: MiniMax-H3 and FastVideo's FastH3 8-Step V2, a video with its stereo soundtrack from text
  on OpenAI's /v1/videos, block fp8 on two cards
- music: MiniMax-Music3, songs from lyrics and a description on /v1/audio/speech
- speech: Breeze-TTS-2 on /v1/audio/speech and vLLM-Omni's realtime WebSocket
- runtime LoRA adapters beside the base model, picked per request by `model` (baKon, #105)
- several agent streams keep their cached history: --checkpoint-slots auto, the new default, sizes
  the snapshot store by --max-num-seqs (#108)
- the Swift 1.5 27B W4 releases convert and serve: compressed-tensors AWQ and GPTQ int4, AutoRound,
  ModelOpt NVFP4 (#110)
- the image's host tests pass where perf_event_open is refused, as in BuildKit's sandbox (#106)
- plugin ABI 21: out-of-tree plugins must be rebuilt
2026-10-18 11:38:37 +02:00
baKon 91127395ee lora: an unload of an adapter in use drains it instead of answering 409
POST /v1/unload_lora_adapter for an adapter requests still hold marks it draining and answers
202 {"action": "draining", "lora_name", "in_flight": N}: from then on a request naming it gets the
404 an unknown model gets and /v1/models leaves it out, the N requests finish normally, and the
last hold to go frees the slot, which then cools for three step-loop rounds like any freed slot.
An idle adapter still unloads at once with 200; a second unload while it drains answers 202 with
the count as it is then, and 404 once it is gone; a load of the same name while it drains answers
409 (is being unloaded).

The slots' bookkeeping moves out of Engine into lora::SlotTable (core/lora/slots.h): reserve,
publish, acquire with its hold, unload, names. It has its own lock, so a request's hold and an
unload no longer wait behind a load's device copy; Engine::lora_mu_ now only serialises loads,
which is what keeps a reserved slot from being handed out twice. lora_test drives the table
through both paths, and server_test drives the routes over a real table with a streamed request
held open: 200 idle, 202 draining twice, 404 for a new request and on /v1/models/:id, 409 for a
load while draining, the slot freed when the stream ends, 503 while it cools, 200 after.
2026-10-16 20:52:09 -05:00
baKon 582cda0a53 abi: RadBatch::lora_slot, each row's runtime LoRA adapter; RAD_ABI_VERSION 18
The per-row adapter slot moves from the core's `lora_slot` derivation into the step batch, beside
the other per-row arrays: [n_tok] i32 device, the row's slot in the adapter pools, < 0 or >= S a
base row, null when the engine serves no adapters. The batch builder fills it from
Request::lora_slot where it fills token_ids and positions, in the slab every rank's batch already
points into -- one address per rank for the engine's life, uploaded in stream order ahead of the
step's kernels -- so a recorded pass replays it the way it replays token_ids. Ctx::pass_key reads
the pointer; the adapter ops are issued whatever the slots hold, so nothing a pass launches depends
on their values.

Off: the slab carves nothing for it (a zero-length carve), no buffer is declared, and every other
slab offset and the arena are what they were. The derivation, its program buffer and
Program::lora_slot_buf are gone. abi_layout_table regenerated at 18 (RadBatch grows to 320 bytes,
the fields after seq_ids move by 8); sched_test holds the per-row fill, and that the slot array is
the only thing adapters add to the slab.
2026-10-16 20:52:09 -05:00
baKon 09ff76701c r4d_selftest: LoRA at real shapes, on-card batch invariance, --perflora
lora_case now runs each row pair as the engine issues it at real shapes --
M 1 / 8 / 2048, K 2048 / 5120 / 6144 / 17408, N 2560 / 12288 / 17408, R 16 /
48 / 64 / 192 -- with slots in runs of requests and base rows, the f64 sums
on the host's cores. The tiled rows add the batch-invariance check only the
card can make (a row alone vs inside M = 8 / 37 / 2048 must give the same t
and y bits: the WMMA unit's answer for a row must not depend on its tile
position) and a base-only launch. A static check holds the tiled rows above
the scalar ones.

--perflora M K N R S PATTERN [iters] times every lora_shrink and every
lora_expand row at one shape and slot layout (base, one, half, mix, runs),
comparing each row's t and y with the first row's; R4D_PERFLORA_A and
R4D_PERFLORA_Y pick the activation and output dtypes, --cold applies.
2026-10-16 20:52:09 -05:00
baKon 487a9f4399 tests/r4d_emu: the tiled LoRA rows -- matrix, real shapes, batch invariance, codes
The shared lora_cases matrix now runs the tiled rows beside the scalar ones,
handing a row the scratch its hook asks for. test_lora adds: the real shapes
(K 2048 / 5120 / 6144 / 17408, R 16 / 48 / 64 / 192, N 256 .. 12288, odd M,
S 1..4, bf16 / E4M3 / E5M2 / i8, aligned and unaligned rows), each a shrink
-> expand pair held to the f64 bound and to libref's bytes; a row alone vs
the same row inside M = 7 / 16 / 17 / 37 / 300 of random slots and base
rows, bit for bit, through aligned and unaligned buffers; a base-only M 2048
launch touching nothing; and every fp8 / i8 code widened exactly through a
one-hot pool. The emulator shim gains the fence, atomic and allocation calls
the split's arrival counters use.
2026-10-16 20:52:09 -05:00
baKon ec1e830c43 libr4d: tiled runtime-LoRA rows over row tiles, preferred over the scalar rows
The v1 rows grid by row: shrink is one block a row walking K serially, and
expand one block a (row, 256 columns) that re-reads all of B[s] for every
row, so a prefill chunk reads it M times and a chunk of base rows still
launches M * ceil(N/256) blocks that read a slot and leave.

lora_shrink_wmma (bf16 a) and lora_shrink_wmma_q (fp8 / i8 codes whose scale
group is whole 32-wide steps) run WMMA bf16 over 16-row x 16-j tiles: K in
32-wide steps over 4 waves, the waves summed in fixed order in LDS, and a K
split fixed by K and R alone (sh_plan) whose partials live in the op's
scratch and are summed in split order by the last block to arrive; the
arrival counters are a small block keyed on (device, t). Codes are exact in
bf16 and each step's partial is scaled by its group's f32 scale; f16 / f32
activations and other groups stay on the scalar kernel.

lora_expand_tiled stages B[s]'s [128 columns, 32 j] slab in LDS as f32 for a
32-row tile and keeps v1's per-output sequence (j ascending, no FMA), so its
bytes are libref's.

Both grid by row tiles; a tile of base rows leaves on one ballot before any
barrier or operand load, a mixed tile runs one pass per distinct slot, and a
small grid spreads a tile's passes over blockIdx.z. No choice depends on M
but which block runs a pass. The scalar rows stay, by name and as the
f16 / f32 shrink, below R4D_PRIO_LORA_TILED.
2026-10-16 20:52:09 -05:00
baKon b427e2774c lora: a load waits for a just-freed slot instead of answering retry
A hot swap (unload, then load at once) under traffic found the freed slot still inside its three
step-loop rounds and got a 503 almost every time. The rounds pass in milliseconds whether the engine
is busy or idle, so the load now waits for them (up to 2 s, the lock let go meanwhile).
2026-10-16 20:52:09 -05:00
baKon be4ebdc3af build: a LoRA-declined fused GEMM owns no weight and is not a reference-kernel op
Found on Qwen3.8-27B fp8: the 64 declined gemm_nt_q_gated folds tripped the reference-kernel gate,
and as unresolved readers of gate_up they would have told the planner the weight cannot live on the
card.
2026-10-16 20:52:09 -05:00
baKon 63e6d01394 kld: --kld-lora-sources PREFIX, an adapter for some documents and the base for the rest, in the same steps 2026-10-16 20:52:09 -05:00
baKon e419c1acc3 kld: --kld-lora NAME scores a runtime LoRA adapter against a reference 2026-10-16 20:52:09 -05:00
baKon 6490b900e2 docs/GUIDE: runtime LoRA adapters (4.9.1) and their flags 2026-10-16 20:52:09 -05:00
baKon 383544f073 server: adapters on /v1/models, load/unload_lora_adapter, and a hold that keeps an adapter loaded while a request uses it 2026-10-16 20:52:09 -05:00
baKon ba406ace1b core: runtime LoRA declare, startup adapters, model routing and a per-adapter prefix key
--lora NAME=PATH, --max-loras, --max-lora-rank, --lora-target-modules. Off unless
named: no site, no pool, no op, and every prefix hash is what it was.
2026-10-16 20:52:09 -05:00
baKon 86cbc59063 tests: lora_ops_test names itself 2026-10-16 20:52:09 -05:00
baKon 41d3b1d907 tests/r4d_emu: name lora_ops_test where the shared case matrix is used 2026-10-16 20:52:09 -05:00
baKon 39dfaf6368 core/lora: LoRA sites from the declared program, and a PEFT adapter packed per rank
build_sites() walks one rank's Program after declare and makes a Site of every LoRA-capable
trunk GEMM (gemm_nt, gemm_nt_bias without act, gemm_nt_q without pb1/pb2 and with K equal to the
weight's, gemm_nt_q_bias) whose `b` weight a target leaf names. The geometry is read off what the
plugin recorded on the weight -- shard mode, row parts, shard and per-part spans, name-map
sources -- and is checked against weight_share() on a plain view of the weight, so the LoRA slice
and the loader's slice cannot disagree. Sites of one declared weight share one pool.

weight_targeted() is the one predicate (scope rule in lora.h), usable mid-declare.
find_unsupported_uses() lists every live op that reads a targeted weight and is not a site: a
fused gated fold, a routed expert, a weight stored in a transform basis, a rotated or widened
gemm_nt_q. Unresolved ops the builder recorded are never issued and are skipped.

load_adapter() reads adapter_config.json and adapter_model.safetensors, refuses what is not
plain linear LoRA (DoRA, other peft types, modules_to_save, trained or lora biases, embedding
LoRA, fan_in_fan_out, parameter LoRA, rank above the cap, rank/shape mismatches, an ambiguous
VLM spelling), computes alpha/r or alpha/sqrt(r) with rank_pattern/alpha_pattern searched as
rad-export does, converts BF16/F16/F32 to bf16 RNE and packs one slot per pool. A fused weight
whose sources are fewer than its row parts (the delta net's ssm_inz) is laid out from the
adapter's B rows. A module no site on this rank takes is listed, not refused -- an
attention-zero rank declares no q/k/v/o -- and check_placed() refuses one no rank took.

tests/lora_test.cpp declares with the real Builder and arch/common's LinearFP8 (fused qkv and
gate_up; gated attention with an attention-zero rank and KV replication; the delta net's uneven
2/2/1 head split) at worlds 1-4 and holds every rank's slot product to the dense delta. It
loads no kernel plugin, so it never reaches the device layer.
2026-10-16 20:52:09 -05:00
baKon 0fce4d4e21 tests: the kernel ops' test is lora_ops_test; lora_test is the loader's 2026-10-16 20:52:09 -05:00
baKon 50543d931b core: runtime LoRA issue chain and the program tables it reads
Off by default: no program has a LoRA site until declare builds one, so issue
and the batch derivations do exactly what they did before.
2026-10-16 20:52:09 -05:00
baKon 51293b269c tests: lora_test and r4d_emu_lora over one shared case matrix
lora_cases.h holds the matrix (M 1/3/17/64/130, R 16/32/48, S 4, K and N 64/256/1000, a bf16 or
E4M3 with a 128-column scale, y bf16/f32, f16/f32/E5M2/i8 once; a, a_scale and y as column
slices; slots -1, -5, 0..3 and S) and the checks: base rows untouched by bytes (a sentinel NaN in
t, -0 in y), adapter rows against an f64 sum within (K + 2) 2^-24 sum|terms| (shrink) and half an
ulp of y plus 4 (R + 2) 2^-24 (|y| + |scale| sum|terms|) (expand).

lora_test runs libref and libavx at every ISA level through rad_plugin_open (libavx builds its fp8
decode table there). r4d_emu_lora runs libr4d's source on the SIMT emulator beside ref_host.cpp
and libref, expand bit for bit.
2026-10-16 20:52:09 -05:00
baKon 979b54e091 libr4d: lora_shrink and lora_expand, scalar f32 v1
r4d_lora_bf16.hip: shrink is one block a row (a base row's block leaves at once), one wave a
column of R, each lane's k in order and a fixed xor butterfly, so a row's bytes depend on nothing
but the row. Expand is one thread an output over M strips of 256 columns, j ascending, sum then
scale then one rounding to y's dtype: libref's order, so the emulator holds it to libref bit for
bit. A base row of y is neither read nor written. Strides of a, a_scale, t, y and the pools come
from the tensors; the grid is M (and N) only.

Rows lora_shrink_scalar / lora_expand_scalar with libref's schemas field for field, constrained
with C_IN on the tensor dtype names, so an activation the decode does not read never resolves.
Not concurrent: the core orders them behind their GEMM. r4d_selftest gets a device case (not run
here: this host's GPU is off limits for this work).
2026-10-16 20:52:09 -05:00
baKon 94ae86f6fd libref, libavx: lora_shrink checks group against the stream's grid
The stream states the group through its extent (make_scales' grid_block), and a K no wider than
one group has one group whatever `group` says: a 64-wide row under group 128 read as group 64 and
was refused. Compare the grid -- groups along K -- instead of the number. An a_scale with no
dtype is absent, like one with no data.
2026-10-16 20:52:09 -05:00
baKon 7864acf50a libref, libavx: lora_shrink and lora_expand, the per-row runtime LoRA ops
The two halves of y += scale * (B . (A . x)) at a trunk GEMM, with each row's adapter named by an
i32 `slot`:

    lora_shrink  t[m, j] = sum_k x(m, k) * lora_a[s, j, k]
    lora_expand  y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * lora_b[s, n, j]

A row whose slot is outside [0, S) is a base row and neither op touches it: shrink writes no `t`,
expand neither reads nor writes `y`, so a base row stays bit for bit what the GEMM wrote (y + 0
would already turn a -0 into +0). x(m, k) is gemm_nt_q's activation value, read through the same
make_scales; an fp8/i8 activation without its scale stream is refused. The dtype parameters carry
the tensor dtype names (rad_dtype_name). Sums are per row in a fixed order, so a row's bytes do
not depend on M or on its neighbours.

libref is the oracle (straight f32 loops, OpenMP over whole output elements); libavx covers both
at every ISA level with vectorised dots. ref_test gains hand-computed cases (column slices, -1 and
S as base slots, a -0 that must survive, the fp8 scale fold, the missing-scale and wrong-group
refusals); avx_check gains a case table; docs/OPS.md the two rows; rad-kbench and avx_check a
tolerance row for the shrink's f32 reduction.
2026-10-16 20:52:09 -05:00
Deadcode 48f7b8eb6d NOTICE: the contributors as a list 2026-10-16 19:45:11 +02:00
Deadcode 93326a27f9 NOTICE: --prefill-interleave is baKon's (#82), from Smellyyyy's idea (#73) 2026-10-16 19:42:38 +02:00
Deadcode 1e968f6e1d radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
2026-10-16 18:25:18 +02:00
Deadcode b068190326 radiance 1.6.0
- Qwen-Image 2.1 and 2.1 Turbo: text to image and image edits over OpenAI's images API,
  /v1/images/generations and /v1/images/edits. An edit takes up to ten pictures and an optional
  mask, outside which the picture comes back exactly as it was; `background: transparent`, png,
  jpeg and webp output, `n` pictures from one prompt, streamed previews (`partial_images`), and
  vLLM-Omni's seed, negative_prompt with true_cfg_scale, num_inference_steps, width and height.
  arch/qwenimage21 serves the diffusers pipeline directory, converted with
  data/recipes/qwen-image-2.1-fp8.recipe (block fp8) or qwen-image-2.1-bf16.recipe.
  deploy/compose/qwen-image-2.1.yaml and qwen-image-2.1-turbo.yaml serve the fp8 containers on
  two cards. Two R9700s make a 2048x2048 picture in 61 s at the base model's 40 steps and in
  13 s with Turbo (56 and 12 s with --tp-wire wht6), a 1024x1024 one in 6.0 and 2.6 s. The
  models are under Qwen's research license, which is non-commercial
- an image generator is a program kind of its own (core/gen): an architecture declares its
  conditioning, denoising and decoding passes, and the driver runs the schedule, the pictures of
  a batch and the conditioning cache. An image model's /v1/models entry is its generator's name
  (qwen-image-2.1, qwen-image-2.1-turbo), and its capabilities and startup banner list only the
  images endpoints
- the tiled prefill GEMMs run their tiles in groups of activation bands, 16 for fp8 and 8 for
  bf16, so an operand larger than the 64 MB cache is read once a group instead of once a band. A
  bf16 GEMM with more than 64 MB of weight runs up to twice as fast
- fixed: a second lane opened in the middle of a step started beside work lane 0 had not
  finished. Gemma 4 26B-A4B opens its lane that way, so its first step after startup could read
  rows not yet written
- startup no longer warns about --checkpoint-slots when it was not passed, nor about an expert
  floor on a model with no experts
- the image's FFmpeg writes png, jpeg and webp (libwebp)
- for out-of-tree plugins: RAD_ABI_VERSION is 16. The op vocabulary gains the image generator's
  ops (conv2d_nhwc, ln_mod, ln_mod_quant_fp8, flow_euler, attn_prefix_self and others; docs/OPS.md,
  "Image generation"), and all_reduce takes an optional `overlap`. Plugins built against 1.5.0
  must be rebuilt
2026-10-14 14:03:59 +02:00
Deadcode b93b531f63 radiance 1.5.0
- Gemma 4 31B (PRs #74, #75, #81, #86; sfjes, keptn42): sliding and global attention with their
  own kernels, the assistant head as a drafter that reads the trunk's cache, the vision tower, a
  fused w4a8 decode step, bf16 and compressed-tensors int4 checkpoints, and window snapshots so a
  prefix hit on a sliding-window model resumes instead of prefilling again.
  deploy/compose/gemma4-31b-w4a8.yaml serves keptn42's container on two cards
- ParoQuant (PRs #65, #66, #67; malic): Qwen3.8-27B checkpoints with learned Givens rotations,
  as int4, int5 and MXFP4, imported without re-quantising, the prefill's rotations on the matrix
  cores. deploy/compose/qwen3.8-27b-paro.yaml serves them on one card. A ParoQuant container made
  with the PR builds is refused: convert it again with --reuse <old container>
- Gemma 4 26B-A4B with z-lab's DFlash drafter (PR #88; Perire): arch/gemma4 serves Google's bf16
  checkpoint with the routed experts in block fp8 or bf16 (data/recipes/gemma4-26b-a4b-df*.recipe),
  and libr4d gains its windowed paged attention, the fused sandwich-norm joins, expert_scale and
  the sharded draft head's pair_argmax. A prefill chunk runs as two slices with its all-reduces
  beside the compute, bit-exact with the whole step. The 31B's global layers take the windowed
  attention too: an 11.5K-token prefill on two R9700s in 3.1 s instead of 4.9
- a startup that logs nothing for two minutes says where it waits (#89): the system call (a KFD
  request by name), the library that made it, and its stack, which addr2line resolves against the
  binary
- the prefix cache is kept in VRAM and host memory only (#70): the disk tier wrote every block and
  snapshot a prompt produced, and its copies never outlived the process. --prefix-cache-host-mib
  is renamed --prefix-cache-mib; --prefix-cache-dir and --prefix-cache-disk-mib are removed, and
  startup refuses all three with what replaced them. The compose files no longer mount /data, and
  .env no longer needs RADIANCE_STATE
- --prefix-cache-ttl S (default 3600, 0 never): a conversation no request has used for that long
  leaves the cache, whichever tier holds it; radiance:prefix_cache_expired_total counts them. A
  full host tier now drops its least recently used conversations
- --vision-tower-placement vram|ram (#84): ram keeps an encoder tower in pinned host memory and
  gives its VRAM to the KV cache, read over the link once an image
- timings carry ttft_ms and total_ms (#85): the server's own time from the request body's arrival
  to the first and the last token, queueing and tokenisation included
- a KV-cache recall that found a moved expert with nowhere to go stopped halfway and leaked the
  slots it had already freed: after it every recall failed, the cache stayed short until a
  restart, and requests failed with HTTP 500. A recall now waits for the slots it is owed and
  always finishes
- a tool result or tool-call arguments that are not JSON are no longer refused as nesting past
  1024 levels for their unmatched brackets (#90): only text that parses as JSON is held to the
  bound, since nothing else is parsed into a tree
- the host-pool refusal names the limit that applies to pinned memory (RAM less 1/64 and
  1.5 GiB), not ttm.pages_limit
- --embedding-placement auto, removed in 1.3.0, is refused with what replaced it
- for out-of-tree kernel libraries: gemm_nt_q gains two operands (pb1, pb2, the part bounds), and
  the loader requires identical op schemas, so a library built against 1.4.0 must be rebuilt. For
  architecture plugins, rad_op_declared(b, op) asks whether an op is in the loaded vocabulary
  without declaring it
2026-10-13 19:35:16 +02:00
AshlynandClaude Opus 5.5 c527863248 arch/gemma4: the dense arm on the second lane beside the routed arm, in a step that runs whole
The two feed-forward arms of a Gemma 4 MoE layer read the same normed residual and meet only at
the feed-forward join; issued one after the other, the dense arm's three launches -- gate_up,
act_mul, down, ~36 us under --profile-ops at a 26B-A4B decode step on 4x R9700 -- wait behind the
routed arm's ~120 every layer. At a few rows its GEMMs are latency-bound, nowhere near the
bandwidth the experts' GEMMs take.

In a step that runs whole -- every decode and verify step, and a prefill chunk too short to cut --
the dense arm now rides the second lane: issued behind a join from lane 0 (the attention join is
its producer), beside the routed arm on lane 0, and joined back before the feed-forward reduction
reads both. Its rows of the join buffer and the routed arm's are disjoint. No collective rides it,
so the reductions keep lane 0 here and lane 1 in a cut prefill chunk, and a step's collectives are
on one lane as before. h, gate_up, ffn and ff2 are named to rad_buf_concurrent. Off with the
overlap's switch, RADIANCE_GEMMA4_OVERLAP=0, which now keeps every step on one stream; a startup
note says which.

arch_test: a decode step issues the dense arm's three launches a layer on lane 1 and every
all-reduce on lane 0, two joins a layer, and nothing on the two lanes that touches a common
element unordered; a 4095-token chunk the same; the cut chunks keep lane 1 for their reductions
alone. GUIDE.md's switch and ARCHITECTURES.md say so.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 7a1ae22690 gemma4k, arch/gemma4: norm_add_norm_route -- the attention join writes the routed arm's inputs
The 26B-A4B's router reads rmsnorm(x) * w_r * hidden^-0.5 and its experts rmsnorm(x) * w_e,
quantised to E4M3 for the fp8 gate_up: an `rmsnorm` and an `rmsnorm_quant_fp8` a layer, each
reading back the x norm_add_norm has just written and taking the sum of squares it has just taken.
At decode that is 60 launches a step (8.3 and 7.8 us under --profile-ops on 4x R9700); at a
prefill, eleven passes of each a layer per 20K-token request.

norm_add_norm_route is norm_add_norm, then from the norm factor it already holds the router's row
by rmsnorm's expression, ((x * s) * w_r) * mult, and the experts' codes as rmsnorm_quant_fp8 writes
them: the bf16-rounded norm, a scale of amax * (1 / 448) a 128 columns (1 for an all-zero group),
the value times its reciprocal clamped to +-448, one v_cvt_pk_fp8_f32. Element i is thread i % 256
at slot i / 256, so a group is four waves at one slot -- a wave's max, then the four through LDS.
Its own name rather than optional operands on norm_add_norm: the codes need whole 128-column
groups, which the plain join does not, and the arch falls back cleanly where it does not resolve.
A device row and a host arm (one helper with norm_add_norm's), the schema, OPS.md.

arch/gemma4 asks for it on every layer whose gate_up is block fp8 -- the user's fp8gu container,
every layer -- and then issues neither op_rnorm nor op_enorm; it declares both still, and
norm_add_norm and the chain behind it, for where it does not resolve. The routed arm's two norm
gains are declared ahead of the attention join now, which names them. The overlap takes either
join. A startup note counts the layers that take it.

The same rounding as the chain, but for the order a sum of squares is added in, as every join here:
g4k_emu holds the kernel to a chain summed in its block order bit for bit -- x, y, the router's
row, every code and scale -- at the 26B-A4B's 2816 at four heights, at 128, 3072, 3200 and 6144,
and with an all-zero group; against the host arm, no code more than a step off. The emulator gains
v_cvt_pk_fp8_f32, through the project's saturating encoder. arch_test: with fp8 gate_up experts the
route op resolves on all six layers, a decode step issues it and no rmsnorm_quant_fp8 and one
rmsnorm fewer a layer; refused, norm_add_norm and both launches; a tp-4 prefill through the
overlap issues it a slice and keeps every reduction ordered.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 efff69be1d arch/gemma4: the drafter's residual add, norm and quantiser in one rmsnorm_quant_fp8 launch
Every input of a drafter layer was three launches after its all-reduce: `add` (x += h), `rmsnorm`
(x -> h) and `quant_act_fp8` (h -> hq | hs), ~8 us each under --profile-ops on 4x R9700 and a few
unprofiled, twice a layer -- thirty a draft pass, every decode step.

libr4d's `rmsnorm_quant_fp8` is that chain in one pass where it takes the residual operand (the
fused_add_rms_norm form): the norm of the bf16-rounded sum, the codes of the bf16-rounded norm,
which its row states is the chain's function. The drafter now issues it for both inputs of every
layer, the attention input of layer 0 with no residual -- x as the embedding left it -- and the
last layer's trailing add stays, ahead of the final norm, which no quantiser follows. Nineteen
launches fewer a draft pass. Where nothing serves the op the chain is declared and issued as
before. A draft is verified whatever it is, so this cannot change what is accepted.

arch_test: a draft pass issues ten rmsnorm_quant_fp8 and one add, the residual operand x and the
delta h past layer 0 and x alone at it; refused, the chain's ten adds and fifteen quantisers.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 34ee08ea5e arch/gemma4: a prefill chunk in two slices, the all-reduces on the second lane beside the compute
On gemma-4-26B-A4B at tp 4 on 4x R9700 the all-reduces were 47% of a 20K-token prefill under
--profile-ops (957 of 2020 ms): a layer reduces T x E after attention and both arms' 2T x E after
the feed-forward, at ~16.5 GB/s a rank on the link, against ~8 ms of compute a layer at the average
chunk. Run whole, the two take turns.

A chunk of two routed passes or more (4096 tokens) now runs as two slices, and every trunk
all-reduce rides the runtime's second lane (rad_lane) beside the other slice's compute: slice A's
attention reduction under slice B's output projection, slice B's under slice A's two arms, slice
A's feed-forward reduction under slice B's arms, and slice B's under the next layer's join and
projections of slice A. Attention runs whole -- it reads every row's keys. A model of the measured
times puts it at up to a quarter off an unprofiled prefill; --profile-ops syncs every op and cannot
show it.

The same bits as the whole step: the cut is a whole number of routed passes, so the routed arm
makes the passes the whole step makes, and both slices are at least one pass, above every row band
the sliced kernels have (the GEMM's 16 and 64, the reduction's one-shot edge) -- core's rule four
for the second lane. The slice's partials sit dense-then-routed in its own run of the join buffer,
so each slice's feed-forward reduction is one message.

The order: a reduction is issued on lane 1 behind a join from lane 0, its producer; lane 0 joins
lane 1 back before the consumer and before the next reduction is issued, since a join orders behind
everything its lane has issued. The embedding's reduction stays on lane 0, ahead of everything lane
1 is first joined behind, so the collectives keep one order on every rank. The two buffers reduced
in place are named to rad_buf_concurrent. Taken where the joins are fused, the wire is exact and
there is more than one rank; RADIANCE_GEMMA4_OVERLAP=0 runs every chunk whole, and the startup note
says which. A decode step never takes the lane.

routed() takes a run of rows and the join row its partial lands at; attention between the
projections and the output projection moves into attend(), which both paths issue.

arch_test records the lane of each issue and where each join sits, and a new test holds a 6-layer
26B-A4B with the DFlash taps, at tp 4: no two issues on different lanes that touch a common element
go unordered (taking every operand as read and written; dropping one wait makes it count six), lane
1 carries the trunk's 4 x 6 reductions at the slices' sizes and nothing else, the slices issue the
whole step's rows by op and its routed passes, a 4095-token chunk and a decode step stay on one
lane. GUIDE.md has the switch, ARCHITECTURES.md the paragraph.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 743b7e1a6a arch/gemma4: the DFlash head reads a block-fp8 copy of the table where the container holds one
The drafter's head was `gemm_nt` over the target's bf16 table -- 352 MiB a rank at tp 4, every draft
pass, 566 us of a 26B-A4B decode step under --profile-ops on 4x R9700: the widest read on the draft
path, and the "first thing to change once the model runs" its own comment named.

A container may now hold the table a second time as `dflash.draft_head.weight`, block fp8 -- one
checkpoint tensor, two logical weights, as rad_block_dflash2.h does it -- made by the recipe line

    dflash.draft_head.weight  rtn codes=fp8_e4m3 block=128x128 scale=bf16

which the three gemma4-26b-a4b -df recipes now carry. Where the copy is there, the head is
quant_act_fp8 over the gathered rows and gemm_nt_q over the copy at fp8a8: half the bytes, for 176
MiB a rank more. The copy is row-sharded exactly as the table, so a rank's rows are the same
vocabulary slice and row_topk's vocab_off, the all_gather and pair_argmax are unchanged. Drafts are
verified, so the coarser logits change what is proposed and never what is accepted --
draft_n_accepted says whether they propose worse; there is no rerank against the bf16 table yet.

Where the copy is not there -- every container converted before this, or one whose recipe made it
something other than block fp8 -- the head reads the bf16 table exactly as before. The decision is
the stored encoding's (weight_enc on the copy's name), and the copy's name map entry alone writes
nothing: rad-convert walks the declared weights. The startup note names the head in use. The
block-fp8 test moves to one helper, which the routed experts' encoding check now uses too.

arch_test: with the copy's encoding block fp8, the copy is declared and the head is gemm_nt_q over
it from the quantised rows; without, nothing is declared and the head is gemm_nt over the table;
a draft pass issues the head once either way. ARCHITECTURES.md says so.

Not yet run on the cards; it needs a container converted with the new recipe line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 73c3dc38be gemma4k, arch/gemma4: attn_paged_qrow -- q in the fused row only where gemma4k reads it
8772d5b handed the sliding layers' attn_paged q as a column slice of the fused [q|k|v] row. gemma4k
reads that; libr4d's paged attention reads q only dense and refuses the slice with RAD_E_STRIDE,
which stops the engine at the first step. Under attn_paged the first library in --kernels wins, so
the slice was only safe with gemma4k ahead of libr4d -- and the deploy script's default order
(libr4d,gemma4k,libavx) took the server down at layer 0's attention on both profile runs.

gemma4k now declares the same kernels a second time under attn_paged_qrow: attn_paged's schema
field for field, with q read at its own row pitch. Only gemma4k declares it, so it resolves there or
nowhere. The sliding layers ask for it once; where it resolves they read q in place (no lift), and
where it does not -- a hierarchy without gemma4k, or RADIANCE_GEMMA4_FUSE=0 -- q is lifted into a
dense block by a `cast` again and attn_paged reads that, which every attention library takes. The
lift's buffer is declared only then, since an unnamed buffer is live for the whole program. A miss
is the swa group's first op carrying a block_size, and answers rad_kv_block_size with the
RAD_KV_BLOCK it declares, as attn_paged would. No libref row, as the joins.

The kernel order still matters for speed -- gemma4k first is the order this model was measured with
(ARCHITECTURES.md) -- but no longer for whether the server runs. A startup note says which form
was taken.

arch_test: the slice reaches attn_paged_qrow and never attn_paged; refused, every sliding layer
lifts q for attn_paged; a decode step issues either form; and the three older gemma4 tests
count the sliding layers' attention under its new name. docs: OPS.md's row and paragraph (and a
line of the joins' text reflowed to the width, as one of gemma4.cpp's), ARCHITECTURES.md's kernel
paragraph, which now names expert_scale too, and GUIDE's FUSE row.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 e173365823 gemma4k: the sandwich joins issue every load first
A barrier is a fence, so a load written after a reduction waits for it. norm_add_norm fetched the
residual and both gains phase by phase, join_add_scale the residual, three or four gains and the
layer scalar, so each paid a global round trip per phase on top of its reductions: --profile-ops on
4x R9700 has them at 13.2 and 17.8 us a call at decode, 30 of each a step, where a launch that does
nothing costs ~7.

Now every operand of the row is in flight at once before the first reduction, the two arm norms
share one barrier pair (block_sum2: each value takes block_sum's butterfly and wave order), and a
thread holds 12 elements where the row fits -- n <= 3072, Gemma 4 26B's 2816 among them -- and
kMaxPer's 24 past that, instead of 24 always. The arithmetic is the same expressions in the same
order; a sum's terms past n were +0 and are gone.

g4k_emu: both joins at the edge between the two widths (3072, 3073), with and without the next
norm, bit for bit against the chain as every other case.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 76dd0019ac libr4d: logit_softcap spreads a row over blocks
One 256-thread block a row: at Gemma 4's tp 4 a row is a 65536-wide vocabulary shard and a step has
a decode's few rows, so a handful of blocks walked 256 elements a thread of tanhf each. --profile-ops
on 4x R9700: 82.7 us a decode step and 85.6 us for the prefill's single row, for 256 KiB of f32 a row
-- four times the drafter's row_topk over a row as wide (18.6 us).

Both legs now put a row on up to 64 blocks, eight elements a thread (32 blocks at 65536). Elementwise,
so no bit moves; libr4d's selftest and rad-kbench's libref comparison hold it as before.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 a378b41abb libr4d: the exact two-shot all-reduce takes every prefill-sized message
R4D_AR_TWOSHOT_WIDE_MAX_ELEMS was 20971520 -- a 4096-token chunk of a 5120-wide residual -- and the
band above it went back to the one-shot, which sends (ws-1)*N bytes a rank where the two-shot sends
2*(ws-1)/ws*N. At the default --max-num-batched-tokens 8192, Gemma 4 26B-A4B's attention reduce is
8192 x 2816 = 23M elements and its feed-forward reduce, which carries both branches for their own
post-norms, 46M: both over the bound, so every full prefill chunk went one-shot at twice the bytes.

--profile-ops on 4x R9700, tp 4, a 20489-token prefill (chunks of 8192, 8192, 4105) fits one link
rate across all of it: the attention reduces 16.8 ms the three calls (two one-shot, one two-shot)
and the feed-forward reduces ~37 ms (all one-shot), 1.6 s of the 2.7 s prefill. The same rate with
every call two-shot is ~9 and ~19 ms: about 0.8 s less a 20k prefill.

The bound guards the kernel's int word offsets and nothing else -- the scratch already holds a
full message per slot (r4d_ar_entry.hip build()), twice what the two-shot uses -- so it is now
2^28 elements, 2^26 words at fp32. The fold is the one-shot's, fp32 in ascending rank order, so
the band edge moves no bits. Fewer bands also means one scratch set less: the old 20971520 band
was its own instance, ~335 MiB a rank at tp 4.

plugin_test: a 16384-token chunk is two-shot to its end, and the one-shot still takes a message
past the bound. r4d_selftest's three-rank pattern walks a 46137344-element message, past the old
ceiling.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 0d95046f6f gemma4k, arch/gemma4: expert_scale -- per_expert_scale on the routing weights in one launch
Gemma 4 multiplies each renormalised routing weight by per_expert_scale of the expert it chose.
In the conventional vocabulary that is an `embed_lookup` of the [n_expert, 1] table by the ids
and a `mul` into the weights -- two launches a MoE layer, a few dozen elements each at decode
(--profile-ops: ~0.26 and ~0.22 ms a step across the 30 layers). gemma4k's `expert_scale` is the
pair as one kernel, ew = bf16(ew * w_e[id]), with an id outside the table reading 0 as
embed_lookup's missed row does: one product rounded once, so the pair's value bit for bit.

Like the joins it has no libref row on purpose, so arch/gemma4 falls back to the pair wherever
gemma4k is not loaded, and RADIANCE_GEMMA4_FUSE=0 turns it off with them. 30 launches a step the
fewer.

g4k_emu: device and host rows against the pair over 32 shapes -- top-k 1 and 8, pitched rows,
pads and one-past-the-end ids, rows past M untouched -- every element equal. arch_test: a decode
step scales in one launch, and in two with it refused. docs/OPS.md: the row and its paragraph;
GUIDE: what the switch now covers.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 29f981fd6c arch/gemma4: route a decode step in one launch -- libr4d's fused router, top-k and sort
At decode heights the router GEMM (128 x 2816), its top-k and the expert sort are each one small
workgroup's work behind a full dispatch: --profile-ops put the three at ~0.27, 0.29 and 0.24 ms a
step across the 30 MoE layers. libr4d already fuses them for the Qwen MoE blocks --
`router_topk_scatter` for the pair, `router_gemm_topk_scatter` with the GEMM in front -- and
documents both as byte-identical to the launches they replace, so the routing does not move.

arch/gemma4 now asks for them as rad_block_moe_fp8.h does: the pair up to the sort's
single-workgroup bound (1024 routing slots, 128 rows at top-8), the GEMM form up to the skinny
GEMM's decode band (64 rows), and the separate ops for a pass past either, declared regardless.
The per-expert scale and the experts' input norm sit between them in the issue order and read only
the ids and weights the fused op writes. Two launches a MoE layer the fewer at decode, 60 a step.

arch_test: a decode step routes with the fused op; refused, with the pair; both refused, with the
three separate ops -- and the per-expert scale and the gather run in every case.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 171dcee15b gemma4k, arch/gemma4: the feed-forward join writes the next layer's input norm
join_add_scale takes an optional gain `w_n` and output `y` (both or neither) and, given them,
writes y = rmsnorm(x) * w_n over the residual it has just stored -- the next layer's
input_layernorm, or the final norm after the last layer. Those norms read the x the join writes
and nothing else, so each was a launch of its own and a second read of the row; now it is a fourth
reduction in a block that already holds x in registers. On the 26B-A4B that is 30 launches a
forward pass the fewer (29 input norms and the final norm), at decode a step's worth of ~8 us
launches.

Rounding where the chain rounds: y is taken over the bf16 x the join stores, with libr4d's
expression, so g4k_emu holds it to the chain bit for bit (+next cases, decode to prefill heights,
odd widths and pitches) and to the host arm within a flipped rounding.

arch/gemma4 declares every layer's input-norm gain ahead of the layers so a join can name the
next one's; where a join resolves, the norm it replaces is neither declared nor issued, and where
it does not, the chain is as before. docs/OPS.md: the row and its paragraph. arch_test: fused,
the only x -> h rmsnorm is layer 0's and every join writes h; refused, all thirteen come back.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 3a48ee78de arch/gemma4: the sliding layers' attention reads q in the fused qkv row
The q lift -- a `cast` copying q out of the fused [q|k|v] projection into a dense block -- was
there because libr4d's paged attention reads q only dense. gemma4k's takes q at any row pitch
(its head_view, and g4k_emu's q-pitch-slice cases), and gemma4k serves all of Gemma 4's attention,
so the slice goes straight in: one launch and a [T, q] copy less on each of the 25 sliding layers,
every step. With libr4d ahead of gemma4k its attention refuses the slice by name (RAD_E_STRIDE)
rather than reading it wrong.

arch_test: no copy between projection and attention, and the attention reads `qkv_s`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 9967158d4a docs: gemma4 -- the architecture, its kernels, converting it, its two switches
ARCHITECTURES.md: a `gemma4` section in the file's form -- the 26B-A4B's geometry, the readings
that stay plausible when wrong (proportional rope is not a partial rotary, K is V, the router reads
the residual, per-arm post-norms, the bf16 embedding scale, the FULL sliding group, the drafter's
causality), tensor parallel, fp8 experts, which kernel library serves what, and what is not
declared. Its table gains the arch/gemma4 row, and the gemma4_bf16 row is corrected: that plugin
claims ("gemma4", "compressed-tensors"), not ("gemma4_bf16", "i4").

GUIDE.md: converting gemma-4-26B-A4B-it with its drafter, and RADIANCE_G4K_WMMA /
RADIANCE_GEMMA4_FUSE in the tooling table. IMPLEMENTATION.md: gemma4k/ in the layout.

KERNELS.md is rad-kbench's and is not edited here; it wants regenerating on a card with gemma4k
loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 753e9c598b data/recipes: gemma4-26b-a4b with DFlash -- fp8 gate_up, 768-padded fp8 experts, bf16 experts
The three containers arch/gemma4 has been served from, each with the usage header the in-tree
recipes carry:

- gemma4-26b-a4b-df: the routed experts' gate_up block fp8, their down bf16 (K = 704 is not
  whole 128-blocks), the drafter's linears block fp8. The measured container.
- gemma4-26b-a4b-df-pad768: both expert projections fp8, from a checkpoint whose experts were
  padded 704 -> 768 before conversion (zero rows of gate and up, zero columns of down: exact).
  The padding is described rather than shipped: the tool that did it is Python and stays out of
  the tree.
- gemma4-26b-a4b-df-bf16x: only the drafter quantised -- the bf16 reference for the KL mode.

The rules are the ones the containers were converted with; only the headers are new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 c2bd41fe95 arch/gemma4: Gemma 4 text with z-lab's DFlash drafter -- the 26B-A4B MoE and the dense sizes
Claims ("gemma4", ""): a container converted from Google's bf16 checkpoint, the recipe choosing
what is fp8. gemma4_bf16 keeps ("gemma4", "compressed-tensors"), the CT-INT4 dense release; the
two do not overlap. Serves gemma-4-26B-A4B-it (128 experts of 704, top 8) and the dense sizes
without per-layer embeddings, with a DFlash block-diffusion drafter merged at convert time.

The readings that stay plausible when wrong, each explained at its site:

- Proportional rope is not a partial rotary: the full layers rotate the first 64 frequency pairs
  of the 512-wide head at theta^(-2j/512), pair j = channels (j, j + 256), declared as full-width
  NeoX with the frequencies past pair 63 divided by 1e30 through the YaRN ramp `rope` carries.
- K is V on the full layers: V is the un-normed, un-rotated k projection, so its norm is issued
  before the key norm overwrites `k`.
- The router reads the residual through a gainless rmsnorm times its `scale` times hidden^-0.5,
  and per_expert_scale multiplies after the renormalised top-k.
- Two post-norms a layer's feed-forward, one an arm, each arm's partial reduced before its norm;
  both partials share one [2T, n_embd] buffer so one all-reduce carries them.
- The embedding scale is sqrt(hidden) rounded to bf16 (53.0, not 53.066).
- The sliding layers' KV group is RAD_KV_FULL with the window on the attention op: a WINDOW
  group is not prefix-cached, and on this tree a hit on one re-prefills; FULL keeps the hit.
- fp8 experts are two tables by parity, so a rank holds an even count; down at K = 704 cannot be
  fp8 (whole 128-blocks), hence the 768-padded recipe.
- The sharded draft head's merge is pair_argmax at R = 2 on the wire.
- The drafter's tap copy is declared at the end of the layer it taps, where it is issued. The
  buffer planner takes liveness from declaration order; declared once after the trunk, it let the
  plan share `dflash_src` with `moe_edn`, which every MoE layer writes, whenever the sizes
  allowed. At --max-num-seqs 16 they did, and on the cards DFlash accepted 2% of its drafts
  (97 tok/s against 135 with speculation off and 186 with the taps intact), the text fluent
  throughout.

The sandwich joins are asked for as norm_add_norm / join_add_scale (gemma4k) and declared as the
rmsnorm / add chain where nothing serves them; RADIANCE_GEMMA4_FUSE=0 asks for the chain. The
reply format is the shared one (arch/rad_gemma4_chat.h), so tool calls are parsed in the engine;
the plugin as measured declared reasoning only and left calls to an out-of-tree sidecar, so the
call path is untested on this plugin's containers.

arch_test: the MoE trunk declares both arms and six of each join; both KV groups FULL with the
window on the op; the full layers' rope over the whole head with the ramp at 63.5..64; with the
joins refused, the chain is declared and issued instead; both Gemma 4 plugins export one format;
with a DFlash drafter, `dflash_src` is live from the first tap layer (its range overlaps
`moe_edn`'s, so no plan can share them) and a step writes each tap once.

Measured on 4x R9700 at TP4 (gemma-4-26B-A4B-it + DFlash, gate_up experts block fp8), with
gemma4k and --draft-window adaptive: a story at T 1 177 tok/s, greedy thinking 572 tok/s, code at
T 0 319-334 tok/s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 368d0363eb arch: Gemma 4's reply format into arch/common, for both Gemma 4 plugins
Two plugins are about to serve Gemma 4 -- gemma4_bf16 the CT-INT4 dense release and arch/gemma4
the bf16 / fp8-expert containers -- and the reply format is the model's, not the weights': the
thought channel, and calls written as a name and one object in Gemma's dialect of JSON. One
declaration in the shared header library (installed as <arch/rad_gemma4_chat.h>), so the two
cannot drift apart and the reply-format tests read what both export.

The declaration moves unchanged, from gemma4_bf16::chat_format_decl() to
rad::arch::gemma4_chat_format(); chatparse_gemma4_test follows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 846e52148a tests: g4k_emu -- gemma4k's kernel source on the host, every GPU thread a fiber
gemma4k builds for gfx12 only and its two joins have no libref oracle, so nothing on a machine
without the card, and nothing in rad-kbench, would ever run its kernels. g4k_emu compiles the
.hip sources as host C++ against a HIP shim: every GPU thread a fiber, __syncthreads and every
cross-lane op a barrier (one not reached uniformly is reported as a deadlock), the WMMA operand
layouts gfx12's. Checked against a port of libref's ref_attn_paged (attention, fixed cases and a
random sweep over every compiled geometry), against the host rows (pair_argmax), and against the
unfused chain bit for bit (the joins).

Registered in CTest under the label g4k_emu, on x86-64 with a clang: the kernels use
ext_vector_type and the fiber switch is SysV inline assembly. Under a clang C++ compiler they are
ordinary targets. The docker image compiles host C++ with g++, so there g4k_emu/run.sh builds the
same tests with the HIP compiler, ROCm's own clang++, and runs them as one test -- so wherever
gemma4k is built, this runs, the image's host-test stage included. About 40 s at the default
40-case sweep (50 s through run.sh, which compiles too); `g4k_emu_attn sweep 200` is the long run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 833173cc04 gemma4k: Gemma 4's kernels beyond libr4d -- paged attention, pair_argmax, the sandwich joins
A kernel library beside libr4d, gfx12 only, and AHEAD of it for Gemma 4:
`--kernels gemma4k,libr4d,...`. Its own library rather than rows in libr4d: a smaller change,
its own gfx12 gating, and no churn in libr4d's row table; folding it in can follow.

- attn_paged at head_dim 256 and 512, gqa 1/2/4/8, bf16 or fp8 cache, any window, causal or not.
  One scalar kernel serves decode, verify and prefill, with a split-KV path whose merge is one
  wave a row (live pieces found by ballot, four at a time; a piece that saw no key writes only
  its max and sum); a WMMA prefill kernel takes a query of at least 64 rows and 32 a sequence on
  average -- Q and K bf16, P and V f16 (bf16 P measured 0.25% of the V range in error), the
  denominator summed from the rounded P. RADIANCE_G4K_WMMA=0 keeps every launch on the scalar
  kernel.
- pair_argmax, device and host, described as libref describes it so rad-kbench checks both.
- norm_add_norm and join_add_scale, ops of its own (docs/OPS.md, a new subsection): each one
  kernel for a post-norm / residual add / pre-norm chain, rounding where the chain rounds. libref
  has no row for them on purpose -- a reference row would resolve them where gemma4k is not
  loaded and the architecture would never fall back to the chain -- and no row declares
  `replaces`, since rad-kbench assembles a replaced chain from the fusing library's own rows.

WHY FIRST. libr4d on this tree also has rows at h256/gqa2 and h512/gqa8, Gemma 4's own
geometries, written for the dense 31B (which has no drafter) and not measured on the 26B-A4B or
under a DFlash verify; the hierarchy is absolute, so the first library takes them. These rows are
the ones every Gemma 4 number below was measured with. No other row overlaps libr4d's (the h256
gqa4/gqa8 rows take a window only), so putting this library first takes nothing else from it. The
softcap is libr4d's and libavx's `logit_softcap`.

Measured on 4x R9700, gemma-4-26B-A4B-it + z-lab DFlash, TP4: decode attention 3.234 -> 0.104 ms
a step on the full layers and 1.906 -> 0.722 on the sliding ones (the split-KV merge); a
20,489-token prefill 4.01 -> 2.83 s (the WMMA kernel); rad-kbench against libref 176/176. Not yet
run on the cards: the joins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 d0f6f332ff ops: pair_argmax in libref and libavx -- the sharded draft head's top-1, one id a row
A vocab-sharded draft head proposes each position's argmax: every rank takes its slice's top-R
as (id, value) pairs, an all_gather puts them side by side, and something picks the winner.
row_topk_merge does that with an R-wide answer; a block drafter wants ONE id a row, written
contiguously into the token buffer it verifies, and a rank cannot send R = 1 -- a
row-interleaved all_gather moves whole 16-byte words and a pair is 8 bytes. pair_argmax is the
merge at R = 1 over world_size * R pairs: largest value, ties to the lower id, a negative id a
pad, -1 and -inf for a row with nothing valid, `val` optional.

The Gemma 4 DFlash head is its caller (arch/gemma4, later in this series) and gemma4k its device
kernel. libref is the oracle and the schema's first declarer; libavx carries the host row,
because an op the placement puts on the host cannot run on a reference (avx_check holds libavx
to libref's vocabulary). Both scalar: n is sixteen pairs at TP8.

docs/OPS.md: the row and a paragraph beside row_topk_merge's. ref_test: ties to the lower id in
any slot, a pad carrying the row's largest value dropped, an all-pad row, all-negative values,
`idx` at a pitch of two with the slots between untouched, and `val` absent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 29bfe8f00c sched: --draft-window adaptive applies to block drafters
The adaptive window priced only a serial head's rounds and was refused for a
block drafter, on the grounds that the block is proposed in one pass. But
every verified draft is still a verify row, and on a MoE whose verify reads
the experts each row routes to, rows are not free (16 rows read ~10x the
experts one does). A block drafter now takes the same policy with its rounds
fixed: each sequence verifies the first min(D, its stop) of the block, its
stop from its own measured acceptance and D from the measured step times.
Prompt lookup alone keeps the fixed window and says so.

Speculation stays lossless: what is verified is a prefix of the proposal.

Measured on gemma-4-26B-A4B-it + z-lab DFlash (block 15), 4x R9700, TP4,
together with gemma4k's split-KV merge rewrite (landed in the same build, so
the two are not separated): story at T=1 95 -> 177 tok/s, greedy thinking
~360 -> 572 tok/s; code at T=0 319-334 tok/s (it verifies deep either way).

tests/sched_test.cpp: the block-drafter case now expects the policy on
(4 drafts verified while the estimate is the prior, 1 after 64 rejected
steps, draft_verify_depth[4] and [1] both counted); the prompt-lookup-only
and no-speculation cases are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 fb716830c2 oai: preserved_tokens on /v1/completions; find a text-tailed reasoning opener by its token
/v1/completions accepts llama-server's preserved_tokens: control tokens the
completion's text keeps rather than drops. A client that renders its own
template and parses its own reply (a tool-call sidecar) has no other way to
see a reply format built of control tokens. Bounded like the stop strings.

A thinking budget needs the reasoning block found by token. Gemma 4's opener
<|channel>thought is one control token followed by text; it is now found by
that first token (what a reply opening its own block writes first, and no
text can spell), with the text after it counted as reasoning. An opener with
a second control token in it is still refused, since its first token may open
something other than the reasoning. The refusal message says why.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 2381591823 tokenizer: end a Gemma 4 generation on <turn|> and <|tool_response>
Gemma 4 declares <eos> as its eos but ends a turn on <turn|>, and a
tool-calling turn on <|tool_response> (the opener of the result the caller
supplies, written after the model's last <tool_call|>). Neither was in
kEogNames, so every Gemma 4 reply ran to max_tokens. llama.cpp's loader
lists both for this vocabulary.

A vocabulary that has <|tool_response> as a control token also has </s> as
ordinary text (llama.cpp concludes the same); ending on it would cut a reply
that writes the HTML tag, so </s> is not an end-of-generation token there.

This branch already ends a generation on every id generation_config.json
names (c65fabe), which covers both tokens for a container that carries
`generation.eos_token_id`. The spellings here cover one that does not, and
the </s> rule is new either way: the eos list never names </s> for Gemma 4,
but kEogNames did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 c37f47cc78 libref, libavx: logit_softcap calls std::tanh on a float, not std::tanhf
std::tanhf is in <cmath> only from libstdc++ 14; against 13 (Ubuntu 24.04's) the host build stops
at libref and all four libavx levels. std::tanh's float overload is tanhf, so the arithmetic is
the same to the bit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
Deadcode f6a9467cb5 Merge ParoQuant: PRs #65, #66 and #67 (malic), with fixes
Rotated Qwen3.8-27B checkpoints: ParoQuant MXFP4, int5 bit-plane and z-lab's int4 import (the givens
transform with parts, per-row scales, zero points), the w5a16/w4a16_asym decode GEMMs, the
w4a8i8/w5a8i8 prefill band, the givens_rotate kernel, and the dense per-group rotation
(givens_dense_quant: one 128x128 f16 matrix a part and group on the matrix cores) for the quantising
rotation in prefill. gemm_nt_q gains part bounds (pb1/pb2), an op-schema change an out-of-tree
kernel library has to follow.

Fixes on top: the dense matrices are a container table ("t.dense") that rad-convert composes in f64
from the pairs and angles, and the loader only moves its bits. A container converted before this is
refused at load, naming the re-convert (--reuse copies every unchanged weight). A gemm_nt_q row that
does not read part bounds refuses them instead of ignoring them. libavx implements givens_rotate and
givens_dense_quant.
2026-10-12 20:46:37 +02:00
Deadcode d10b64f9e5 gemma4 compose: prefill in 2048-token chunks
The 8192-token default makes a long prompt's step take about 5 s on Gemma 4 31B, holding every
running decode for that long. At TP2 on two R9700s, a 26K-token prefill: 1475-1477 tok/s at 2048
against 1456-1463 at 8192; decode step time equal at c1 and c4.
2026-10-12 20:46:37 +02:00
Deadcode 7c7f755931 Merge Gemma 4 31B: PRs #74, #75, #81 and #86 (sfjes, keptn42), with fixes
The gemma4_bf16 architecture (sliding and global attention, the proportional RoPE ladder, the
assistant head as a drafter that reads the trunk's cache, the vision tower), its w4a8 decode
junctions, the h512/gqa8 and h256/gqa2 attention kernels, compressed-tensors int4 import, multi-EOS
from generation_config, the call/reasoning reply format, a window group that keeps the keys a
prefill chunk still reads, and window snapshots in checkpoint slots so a prefix hit on a
sliding-window trunk resumes.

Fixes on top: the investigation switches and diagnostic blocks out of the served paths; int4 import
through the checkpoint import framework; attention_k_eq_v from the config; the fused junctions only
where every reader takes their pair; a shared-KV head binds no group of its own; the compose file
without HSA_ENABLE_IPC_MODE_LEGACY (TP2 fails with it on ROCm 10.1); a checkpoint carries a window
only where a hit resumes from it; the README says the linked container is keptn42's calibrated GPTQ
build and what the in-tree recipe gives.
2026-10-12 20:46:37 +02:00
Deadcode dc339b4cd2 radiance 1.4.0
- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and
  the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at
  decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against
  1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20%
- deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM
  (4096-token prefill steps, 4 sequences, a 301K-token cache)
- #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the
  requests decoding beside it and to new arrivals, instead of taking all of it (baKon)
- LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50)
- a startup report: every option with its value and where it came from, the hardware, and what
  on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only
  to the same machine)
- #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at
  once (exit status 70), instead of hanging or writing a core of tens of gigabytes
- #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of
  crashing at the first launch
- the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's
  libLLVM rebuilt so the same source compiles to the same kernels every time; a source build
  takes ROCm 10.1 or 7.2
- #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container,
  and hfget.sh runs under its busybox (baKon)
- --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an
  integrated GPU instead of stopping
2026-10-12 11:46:14 +02:00
keptn42 9a2747eaef checkpoint slots: startup and help name the window snapshots too 2026-10-12 09:05:31 +00:00
keptn42 e35052abfe sched: a prefix hit on a sliding-window model resumes from a snapshot of the window behind it
The prefix cache cannot index a windowed group, so every hit on a windowed
trunk re-prefilled the whole prompt (73620ef). Gemma 4 31B (50 of 60 layers
windowed at 1024) paid that on every chat and agent turn: 17-48 s to the
first token at 25-49k tokens.

A model with a window and no linear state now takes one checkpoint per
prompt, a block short of its end -- the next turn re-renders the last few
tokens -- if the prompt is --checkpoint-interval tokens or longer, and does
not split chunks at the interval. The prefix cache treats the window like
linear state: a hit is reusable at a checkpoint only. admit_one adopts the
full-attention blocks as before, seeds the windowed groups at the window's
floor, and the entry's restore fills them from the slot; anything else
re-prefills as before. A model with both linear state and a window keeps
refusing the hit.

Measured on Gemma 4 31B, TP 2, agent transcripts: a follow-up turn's first
token in 0.8-3.4 s instead of 17-48 s; greedy output byte-identical to a
cold prefill with the same chunk boundaries (32 turns, chains five hits
deep, thinking on and off).
2026-10-12 09:04:43 +00:00
keptn42 93389679e8 kv: a checkpoint slot carries the window behind it
A WINDOW group keeps only the blocks its window can still read, so no block
list from the prefix cache describes it. A checkpoint slot now carries, after
the linear state, window_blocks pages a WINDOW group (every layer, layer-major
rows): the window a query at the checkpoint reads, blocks
[max(0, P/B - (window_blocks - 1)), P/B) -- the floor recycle_window keeps.

window_rows() names those pages from the leader's table, padded per group, so
every rank copies its own shard with one vector (followers keep no sequence
tables); it answers false when the table no longer holds them. seed_window()
gives a sequence with an empty window table fresh blocks at that floor for a
restore to fill. checkpoint_save/restore take the rows; a model with no window
passes none.
2026-10-12 09:04:43 +00:00
keptn42 45109ebb45 Merge branch 'main' into gemma4-mtp 2026-10-12 02:38:12 +02:00
keptn42 ab4ae529f8 chat: a string the model leaves open ends at the call's close
Gemma 4 sometimes skips the <|"|> that closes a string and writes the
object's `}` and <tool_call|> straight after the text (measured on the
31B: the close delimiter at p=0.86, `}` at p=0.08). The object reader
only ended a dialect string at its own close, so the call's close, a
repeated close, an empty thought channel and the next call's opening
were read into the value -- up to the next call's <|"|>, which then
"closed" it.

Inside a string, the call's close now ends the string and the call when
the closers just before it close every open bracket of the object, as
vLLM's and HF's Gemma 4 parsers end a call at the first `}<tool_call|>`.
Those closers are the object's and leave the value, a repeated close
goes with them, and a quote or backtick just before them that leaves the
string with an odd count of its kind was the string's close in the wrong
spelling (seen with thinking on). The call's close inside a string that
does not close the object is text, as before.

A value opened with a plain `"` or `'` in a dialect with strings of its
own is read the way the model writes it there (measured: `'...'` for
nested arguments, `"..."` verbatim, or with only `\"` escaped): verbatim
but for an escaped quote, never with JSON's other escapes -- `\n` stays
the two characters, as in the JS source it came from. It ends at a quote
the object's syntax goes on after (a member, an element, the closers and
the call's close), or at <|"|>. Single-quoted values were read as bare
words before.

The object grammar admits such a value too. Refused, the model took the
next token the grammar allowed, a `-`, and every single-quoted string
came out as a number (-1, -2, ... at temperature 0).

Held bytes stay bounded (a 16-byte run, 32 bytes of lookahead).
2026-10-12 00:16:28 +00:00
keptn42 05033f3911 readme: the Gemma 4 31B container and its compose file
gemma4-31b-w4a8.rad on Hugging Face (keptn/gemma4-31b-w4a8): the bf16 checkpoint's trunk as GPTQ
int4 with int8 activations, the assistant head as MTP drafter, the vision tower. The compose file
carries the flags the model card's numbers were measured with.
2026-10-11 15:18:41 +00:00
keptn42 0895588b76 gemma4: the vision tower -- images and video through Gemma 4's own encoder
The 31B's tower (27 layers of 1152, 72-wide heads, a 2-D rotary over two 18-pair
neox blocks, 3x3 pooling, per-channel standardisation) declared beside the text
model when the container carries it and the deployment serves media; its rows
replace the placeholder embeddings after the lookup. qk_norm_rope's blocks mode
now runs at any head_dim and section size (a lane a pair outside the register
layout).
2026-10-11 02:51:18 +00:00
keptn42 191972eb75 gemma4: the w4a8 decode step through the fused norm/quant ops
Between two w4a8 blocks the stream ran five single-row dispatches
(post-norm, add, layer scalar, norm, quantiser), q, k and v quantised the
same norm output three times, the attention prologue was five more ops
and down's input two. Now every junction is one rmsnorm_quant_i8 (at two
ranks on the exact wire ar_rmsnorm_quant_i8, with the all-reduce in it),
q, k and v read one int8 pair, the prologue is qkv_norm_rope and down's
input gelu_mul_quant_i8. The trunk pass at k=3 goes from 1786 to 840
dispatches.

Byte-identical to the unfused step: greedy output equal at k=0 and k=3.
A kernel set without an op keeps that op's chain; RADIANCE_G4_FUSE=0
keeps every chain, for an A/B against the same build. arch_test checks
the issued op sequence fused, at two ranks, and with the ops refused.
2026-10-11 02:24:21 +00:00
keptn42 bdb50b2a9c gemma4: the trunk's lm_head is declared at its codes' dtype, like the assistant head's
bf16 as the checkpoint ships it; int8 or block fp8 where a recipe quantises
output.weight, served by the logits_gemm row for that encoding.
2026-10-11 02:23:48 +00:00
keptn42 e366777a0f gemma4: a bf16 checkpoint's plain weight names, and an int8 linear on the w4 grid
The plugin mapped only the CT-INT4 release's X.weight_packed. A bf16
checkpoint (Google's gemma-4-31B-it, every finetune of it) stores
X.weight; the name is now chosen from the checkpoint's own
quantization_config. A linear a recipe keeps at int8 on the same
128-column grid is served by gemm_nt_q at w8a8 with the activation
quantiser the w4a8 path already declares.

Recipe gemma4-31b-dense-bf16-w4a8 added: the CT recipe's grid and size
(int4, f16 scale a 128 columns) with the least-squares scale search. The
assistant head was trained against the bf16 trunk: served from this
container it accepts 0.71/0.62/0.63 of its k=3 drafts on prose, against
0.49/0.50/0.44 from the QAT container, at the same step time.
2026-10-11 02:23:48 +00:00
keptn42 d49d664381 libr4d: ar_rmsnorm_quant_i8 -- the two-rank exact all-reduce in front of rmsnorm_quant_i8
At two ranks the residual junction follows the row-parallel GEMM's
all-reduce. ar_rmsnorm_quant_i8 is that all-reduce (exact wire, the
ar_rmsnorm_quant_fp8 handshake) and rmsnorm_quant_i8 in one kernel, x
INOUT because it is the message. A deployment on the lossy wire keeps the
standalone all-reduce. Needs a peer rank, so the selftest skips it like
ar_rmsnorm_quant_fp8; byte identity is checked through a model run.
2026-10-11 02:23:39 +00:00
keptn42 0a4cf9b893 libr4d: gelu_mul_quant_i8 -- gelu(gate)*up and the w4a8 activation quantiser in one pass
The down projection of a GELU-gated feed-forward on a w4a8 grid is fed by
gelu_mul then quant_act_i8, two single-row dispatches at a decode batch.
gelu_mul_quant_i8 is the pair in one pass, byte-identical to it: the
product formed as gelu_mul_kernel forms it (tanh form, bf16 store), then
quant_act_i8's partition. The selftest compares it against the pair at
M 1/4/40.
2026-10-11 02:23:39 +00:00
keptn42 d90d90e43a libr4d: qkv_norm_rope -- q/k/v norms and both rotaries of separate projections in one dispatch
An attention block with separate q, k and v projections and per-head
norms (Gemma 4) runs five single-pass ops between the projections and the
cache store: rmsnorm_p on v (or on the raw k where v is k), rmsnorm over
the q heads, rmsnorm over the k heads, rope on q, rope on k.
qkv_norm_rope does them in one dispatch, one workgroup a (token, head).

Byte-identical to the five: the same norm widths r4d_act_threads picks
and rope's ladders, head included. The row is constrained to head_dim
256..512 in steps of 256; other shapes keep the five. The selftest
compares both of Gemma 4 31B's attention classes at M 1/4/40.
2026-10-11 02:23:39 +00:00
keptn42 dd6a7071a8 libr4d: rmsnorm_quant_i8 -- rmsnorm and the w4a8 activation quantiser in one pass
A w4a8 linear is fed by rmsnorm then quant_act_i8, two single-row
dispatches at a decode batch; in a sandwich-norm model (Gemma 2/3/4) the
residual junction in front adds a post-norm, the add and a layer scalar,
five dispatches at every junction. rmsnorm_quant_i8 is that chain in one
pass over the row, with the junction optional (w_post, scalar and the
residual operand).

Byte-identical to the chain it replaces: the same row partition
(r4d_act_threads) and a bf16 rounding wherever the chain stores. The
selftest compares it against the chain at three forms x M 1/8/40.
2026-10-11 02:23:39 +00:00
keptn42 8bde9f9c16 gemma4: the assistant head as a serial drafter that reads the trunk's cache
Google's Gemma 4 assistant (Gemma4AssistantForCausalLM), merged under
`draft.` by `rad-convert --draft-model`, declared when the container carries
it and the deployment speculates (max_spec > 0):

  x  = pre_projection(concat(E_trunk[tok] * sqrt(n_trunk), h_trunk))
  x  = 4 layers (3 sliding, 1 full): q-only attention over the TRUNK's cache,
       o_proj, plain-gain sandwich norms, GELU ffn, per-layer scalar
  hd = norm(x); logits = the head's own tied table (no soft-cap)
  h' = post_projection(hd), the next round's hidden state

h_trunk is the trunk's final-normed hidden state. Each head layer reads the
last trunk layer of its class (58 sliding, 59 full on the 31B), as vLLM wires
it. The head keeps no cache, so it is declared with rad_drafter_shared_kv:
one row a drafting sequence, every round at the committed position.

TP: q heads row-sharded with the trunk's kv heads; o_proj and down are
column-sharded and all-reduced before their post-norm; projections and norms
replicated; the lm_head vocab-sharded through the ordinary sampler chain.

Declare refuses a head whose kv geometry, window, rotary or vocabulary differs
from the trunk's, and use_ordered_embeddings (centroid masking). The probe
answers draft depth 3 for `--num-speculative-tokens auto`.

arch_test: no head without one or at max_spec 0; shapes, name maps, the
drafter declaration; the issue order of a history pass and a round; the
attention reading trunk layers 10/11 of the 12-layer fixture; TP2 reduces
before each post-norm; a history pass of the wrong shape is refused.
2026-10-10 19:15:05 +00:00
keptn42 997e1ae05f drafter: a serial head that keeps no cache of its own
rad_drafter_shared_kv(b, pos_offset), an additive builder export: the
declared SERIAL head reads the trunk's K and V and writes none (Gemma 4's
assistant head has a query projection and nothing else per layer). A
plugin that does not call it drafts exactly as before; RAD_ABI_VERSION is
untouched (same pattern as rad_kv_group_zero).

For such a head the serial driver changes in two places:

- No history is owed. The history pass carries round 1 only: one row a
  drafting sequence, at the committed position, with the token the trunk
  chose after it and the trunk's hidden state there. A sequence that does
  not draft gets no row; a step with nothing to draft runs no pass.
- Every round runs at that same position, over the same context. seqused
  ends at the committed position: past it, the trunk's cache holds the K
  and V of drafts the verify rejected, or nothing.

`pos_offset` (0 or 1) is where the rows sit for the rotary, relative to the
committed position; it moves nothing else.

Card side: ADV_HIST and ADV_ROUND take the shape from AdvanceArgs::shared_kv
and rot_shift, which the scheduler fills from the Program. Host side:
serial_begin/serial_batch stage one row and a constant ceiling.

Tests: build_test checks the export's refusals; sched_test stages one verify
step both ways (the old path pinned: five history rows, rounds stepping),
checks that a cacheless head runs no pass when nothing drafts, and runs the
card's advance rows directly for both shapes.
2026-10-10 16:29:34 +00:00
keptn42 d59e0bb003 gemma4: declare the reply format -- the thought channel and calls as one object
Gemma 4's template is one llama.cpp reads with a hand-written handler, so the template analysis
found no format in it: the server warned "this model's reply format cannot be described",
returned the thought channel as content and refused every request with tools (HTTP 400).

The plugin now states the format its tokenizer_config.json declares (`response_template`), in
gemma4_chat_format.h, exported through RAD_ARCH_CHAT_FORMAT:

  thinking    <|channel>thought\n ... <channel|>, reasoning_anywhere
  calls       <|tool_call>call:NAME{...}<tool_call|>, repeated, triggers on <|tool_call>
  the object  bare keys, strings between <|"|> and <|"|>, other values as JSON writes them

The template closes an empty channel in the generation prompt when thinking is off and opens one
after a tool response when it is on; RAD_CHAT_THINK_FROM_PROMPT reads both. llama.cpp's handler
records an extra thought channel after the answer and a lone <channel|>; reasoning_anywhere reads
the first as reasoning and drops the second, so neither reaches the content.

chatparse_gemma4_test, against the model's own template (tests/data/chat/gemma4) and llama.cpp's
Gemma 4 parser as the oracle (tests/legacy, which now takes a declared format): every reply the
template renders reads back as the message it rendered, byte for byte as llama.cpp reads it; the
shapes the model writes and the ways it leaves the format; thinking on, off, and after a tool
response; reasoning_format none; a conversation with role:tool results rendered into the open
turn and continued; every truncation, fuzzed replies and a 200 KB string under the streaming
contract; the call grammar against llama.cpp's on rendered calls, tool_choice required and a
response format; and the chat bridge serving it, with the decoder rendering <|"|>.
arch_test holds the export to the header.

End to end on the 31B QAT checkpoint, two R9700 at TP 2: 60 requests over greedy and
temperature 1.0 / top_k 64 / top_p 0.95, streaming and not, thinking on and off. Every request
with tools came back with finish_reason "tool_calls" and JSON arguments -- one call, two parallel
calls, integer and boolean arguments -- every follow-up with role:tool results as an answer with
finish_reason "stop", and no <|channel>, <channel|>, <|tool_call> or <|"|> reached any content or
reasoning_content. With thinking off the model writes <|channel>thought\n<channel|> itself
before its answer to a tool result; it is read as an empty thought.
2026-10-10 08:08:44 -07:00
keptn42 2c9ffc2888 vocab: every id the checkpoint's generation_config names as eos ends a generation
A checkpoint states the tokens a generation ends on in generation_config.json (eos_token_id, one
id or a list), and rad-convert already carries it into the container as
`generation.eos_token_id`. The vocabulary did not read it: it ended on eos, eot and a list of
known spellings. Gemma 4 names three, [1, 106, 50] -- <eos>, <turn|> and <|tool_response> -- and
the container's eos is only the first.

- <turn|> closes every turn. Without it a reply runs past its own end: a three-sentence answer
  stopped at max_tokens 400 after ~390 tokens of "---" lines instead of finish_reason "stop" at
  65 tokens.
- <|tool_response> is what the model writes after its calls, where it waits for the result.
  Greedy on the 31B QAT checkpoint (TP 2): after a finished call the next token is 50 with and
  without this change; without it generation goes on and writes the same call again until the
  token limit, with it the reply ends there (stop_type "eos", one token).

The engine reads `generation.eos_token_id` from the metadata before loading the vocabulary
(VocabBuild::eos_ids, not baked) and Vocab::load ends a generation on every id in range, logged
beside the spellings it adds.

text_test: ids in the list end a generation, an id naming no token is no id.
2026-10-10 08:08:44 -07:00
keptn42 dbd4e164b3 chat: a call written as its name and one object; reasoning that opens again later
The reply format described one call syntax, the tagged one: each argument in its own tags,
typed by the tool's schema. A call written as its name followed by ONE object holding the
arguments could not be described -- Gemma 4's `<|tool_call>call:NAME{key:<|"|>text<|"|>}<tool_call|>`
is one, and its tool requests were refused; JSON behind a name tag (`[TOOL_CALLS]NAME[ARGS]{...}`)
or inside a function tag is the same shape.

RadChatFormat grows at its end (no ABI bump; an older plugin reads the new fields as zero):

- args_form RAD_CHAT_ARGS_OBJECT: the arguments are one object after the name. name_suffix may
  be empty, and the name then ends at the object's `{`; call_end may be empty, and the object's
  own `}` ends the call. The arg_* fields are unused and must be empty.
- object_string_open / object_string_close: a string delimiter of the object's dialect besides
  JSON's `"`, between which the text is verbatim (Gemma 4: <|"|> twice).
- object_bare_keys: the dialect writes keys bare, `key:value`.
- reasoning_anywhere: a reasoning block may open again later in the reply (after the answer,
  between calls) and is read as reasoning there too; a close with no block open is dropped.

The streaming parser reads the object as it arrives and writes it as JSON as it reads: brackets
and separators as they come, a key once its `:` shows it is one, a string's bytes as they arrive
(the dialect's verbatim, JSON's with its escapes checked: an unknown escape is text, a lone
surrogate is U+FFFD), and a bare value as the tagged family writes a typed one -- held while it
could be a number or literal, else a string. Trailing and missing separators, a bracket of the
wrong kind, a key without value and an object cut off by the call's close are repaired locally
and reported as leaving the grammar; a closed call's arguments are JSON whatever was written.
The streaming contract holds: deltas are never revised, holds stay bounded.

The lazy grammar writes the object in its dialect (strings between the delimiters, bare keys,
JSON numbers and literals) and leaves the values to the model, as llama.cpp's own Gemma 4
grammar does: the schema converter speaks JSON, and the dialect is not JSON.

chat_format_check refuses what the parser could not read unambiguously, by name: tagged fields in
an object format, a dialect string opener that begins like a bare word, a call close that holds
object punctuation or cannot be told apart from the string opener, a reasoning marker that
overlaps a call opener in content.

chatparse_test: JSON behind a name tag and behind a function tag (strict, lenient, streamed every
way, grammar admits and refuses), reasoning_anywhere on and off, and the refusals.
2026-10-10 08:08:44 -07:00
keptn42 b9229091a9 gemma4: all-reduce before the post-norm
o_proj and down_proj are column-sharded, so under TP each rank holds a partial sum of the
projection. The post-attention and post-feedforward norms ran on those partials and the
all-reduce summed the normed halves: sum_r rmsnorm(p_r) instead of rmsnorm(sum_r p_r). HF and
vLLM (RowParallelLinear) reduce first. At TP 1 there is no all-reduce and nothing changes.
2026-10-10 08:08:43 -07:00
keptn42 cb5e812ccc attn prefill: a windowed CTA starts its KV walk at its own first row's window
The windowed prefill took the walk's first tile from the chunk's row 0, so every CTA of a long
chunk walked from the chunk's window start to its own causal limit. Tiles below the window of a
CTA's first row are masked for every row it holds, so starting there changes no value.
2026-10-10 08:08:43 -07:00
keptn42 c045ff85e9 rope: the head ladder rotates the whole head, as HF's proportional RoPE
ladder=head kept the rotary_dim-wide pairing: pair i = (i, i + rotary_dim/2). HF's proportional
RoPE (and vLLM's Gemma4RotaryEmbedding) rotates the whole head: inv_freq has head_dim/2 entries,
the first rotary_dim/2 of them 1 / theta^(2i/head_dim) and the rest zero, so pair i is
(i, i + head_dim/2). On Gemma 4's global layers (128 of 512) the old pairing turned channels
64..127 and left 256..319 alone.

rope in libr4d, libref and libavx now rotates the whole head under ladder=head, with the
frequencies past rotary_dim/2 at zero. The rotary ladder is unchanged. op_rope_ladder and the
r4d_selftest mirror check the HF pairing.
2026-10-10 08:08:43 -07:00
keptn42 921b02b60b kv: a window group keeps the keys a prefill chunk still reads
ensure() recycled a RAD_KV_WINDOW group against the end of the step, so a
prefill chunk lost the keys its first rows read (a 2185-token prompt kept
no window KV for positions 0..1151). Recycle below the step's first query
(keep_from = n_computed), size the caps for one extra chunk, and trim the
window when a prefill chunk is committed. The old test pinned the bug.

Found while debugging #75 (Gemma 4).
2026-10-10 08:08:43 -07:00
sfjes 77c266ce8f docs: catalog the gemma4 arch and its eight attention kernels
ARCHITECTURES.md gains the gemma4_bf16 row (two attention classes, CT-INT4
served form); KERNELS.md gains the h256/gqa2 and h512/gqa8 decode+prefill rows
(bf16kv + fp8kv legs) the arch selects.
2026-10-10 00:36:08 -07:00
sfjes 3259b4a8a2 arch: gemma4_bf16 plugin + w4a8 recipe + graph cases
Gemma 4 dense as two attention classes (sliding-window + proportional-RoPE
global, k_eq_v) over one GemmaRMSNorm stream with GELU ffn, two KV groups,
softcapped logits, tied scaled embedding. arch_test builds the full graph.
Env-gated residual-trace instrument in the arch (RADIANCE_TRACE_RESID, default
off). 21.7 GiB w4a16 QAT checkpoint serves coherent sampled output on the box.
2026-10-10 00:36:08 -07:00
sfjes 61cf8b7b1a engine: host-domain binding for weightless host-only ops
bind_ops falls back to the host domain when an op is host-only and carries no
weight tensors: a plugin declaring host-only math gets the same binding path as
device ops, with no model-specific quirk. Adds the R4D_DIAG kernel-selection
trace in plugin selection (default off).
2026-10-10 00:36:08 -07:00
sfjes 73bfc310aa format: CT-INT4 (QAT) checkpoint decode — _packed/_scale resolution, i4 affine planes
ckpt_rows_f32 resolves packed/scale tensor pairs and decodes i32-packed int4
rows to f32 planes. checkpoint_test cases added.
2026-10-10 00:36:08 -07:00
sfjes dd3310849a kernels: paged attention at h512/gqa8 and h256/gqa2, windowed prefill band
head 512 (gqa 8) — a head width the library had not compiled before — for the
global layers, head 256 (gqa 2) for sliding-window decode, plus the >=32-token
windowed prefill fix. Numeric selftests vs an inline port of ref_attn_paged
with negative control; env-gated attn-verify probes (R4D_VERIFY_ATTN, default
off) at the decode entries.
2026-10-10 00:36:08 -07:00
sfjes 8b825a941c rope + embed extensions: proportional-RoPE ladder, runtime embed scale (mult)
ladder param on rope/rope_table across ref/avx/r4d legs; embed_lookup gains its
runtime scale under the canonical registry name (mult). Default-preserving:
existing checkpoints replay unchanged (kbench rope fixture 44/44).
2026-10-10 00:36:08 -07:00
sfjes c37ce73d72 ops: rmsnorm_p, gelu_mul, logit_softcap, scale in lockstep across libref/libavx/libr4d + OPS.md rows
Elementwise ops with numeric selftest cases against the f64 oracle (both legs
of logit_softcap: bf16 and the f32 band the sampling chain carries). libr4d
gains env-gated verification probes alongside them (R4D_VERIFY_OFF
recompute-on-host checks; default off — instruments, not features).
2026-10-10 00:36:07 -07:00
sfjes 73620ef00e sched: a prefix hit on a windowed TRUNK re-prefills — reuse cannot cover a group the cache does not index
prefix.cpp indexes the RAD_KV_FULL groups and skips RAD_KV_WINDOW (its own
words: "a hit's blocks do not describe a cache whose floor moves" — the
blocks below the window are recycled). admit_one clamped a hit for the
linear/checkpoint cases; a model whose own attention includes a group the
cache skips — every windowed+full pair — passed every clamp, reused, and
adopted blocks covering the CACHED groups only. The windowed trunk layers
take used = ctx_len + n_tokens (batch.cpp) and read positions below
ctx_len this sequence never wrote; grab_block's min-heap (kv.cpp) hands
out the most recently freed blocks, i.e. the previous tenant's. The
sequence attends to the PREVIOUS REQUEST'S KV as its own prefix: fluent
text carrying the last request's content. Reproduced on a live server
with sequential prompts (A-B-C-A-B: the re-run of A reads C's prompt),
and it is why a windowed model with the prefix cache on cannot currently
serve more than one conversation at a time.

The fix is a second predicate next to the drafter floor, computed once
in init(): a paged group bound to a TRUNK layer (below meta.n_layers —
a drafter borrows from base_layer and above, per rad_bind_layer_kv) that
cached_groups() does not name. In admit_one, a hit with such a hole
reuses nothing: the prefix re-prefills (windowed prompts are small;
milliseconds). The drafter's own hole stays the refill design's —
HitCap ends the hit one drafter window before the prompt's end so the
tail-recompute covers the drafter's window while the trunk reuses the
rest (the e95d397 tests keep passing, all of them); no tail-recompute
can repair a trunk hole, which is why zero is the honest answer there.

sched_test gains an opt-in WINDOW group in the fixture (bound to a
trunk layer) and a_hit_on_a_model_with_a_windowed_group_reuses_nothing:
a deep, checkpoint-covered hit — legal under every other clamp — on a
cache indexing only the FULL group. Reuse lands at 0, nothing is
adopted, and attn_cached_tokens still reports the 304-token match: the
cache hit and the scheduler refused it. Disable the clamp and the hit
adopts 16 blocks of the seeded (previous tenant's) KV — n_computed 256,
the leak as shipped; that is the regression net.

Box: ctest lane + A-B-C-A-B battery green (evidence in the PR body).
2026-10-09 23:13:26 -07:00
sfjes f1d9afadfa sched: a prefix hit on a windowed TRUNK re-prefills — reuse cannot cover a group the cache does not index
prefix.cpp indexes the RAD_KV_FULL groups and skips RAD_KV_WINDOW (its own
words: "a hit's blocks do not describe a cache whose floor moves" — the
blocks below the window are recycled). admit_one clamped a hit for the
linear/checkpoint cases; a model whose own attention includes a group the
cache skips — every windowed+full pair — passed every clamp, reused, and
adopted blocks covering the CACHED groups only. The windowed trunk layers
take used = ctx_len + n_tokens (batch.cpp) and read positions below
ctx_len this sequence never wrote; grab_block's min-heap (kv.cpp) hands
out the most recently freed blocks, i.e. the previous tenant's. The
sequence attends to the PREVIOUS REQUEST'S KV as its own prefix: fluent
text carrying the last request's content. Reproduced on a live server
with sequential prompts (A-B-C-A-B: the re-run of A reads C's prompt),
and it is why a windowed model with the prefix cache on cannot currently
serve more than one conversation at a time.

The fix is a second predicate next to the drafter floor, computed once
in init(): a paged group bound to a TRUNK layer (below meta.n_layers —
a drafter borrows from base_layer and above, per rad_bind_layer_kv) that
cached_groups() does not name. In admit_one, a hit with such a hole
reuses nothing: the prefix re-prefills (windowed prompts are small;
milliseconds). The drafter's own hole stays the refill design's —
HitCap ends the hit one drafter window before the prompt's end so the
tail-recompute covers the drafter's window while the trunk reuses the
rest (the e95d397 tests keep passing, all of them); no tail-recompute
can repair a trunk hole, which is why zero is the honest answer there.

sched_test gains an opt-in WINDOW group in the fixture (bound to a
trunk layer) and a_hit_on_a_model_with_a_windowed_group_reuses_nothing:
a deep, checkpoint-covered hit — legal under every other clamp — on a
cache indexing only the FULL group. Reuse lands at 0, nothing is
adopted, and attn_cached_tokens still reports the 304-token match: the
cache hit and the scheduler refused it. Disable the clamp and the hit
adopts 16 blocks of the seeded (previous tenant's) KV — n_computed 256,
the leak as shipped; that is the regression net.

Box: ctest lane + A-B-C-A-B battery green (evidence in the PR body).
2026-10-09 18:47:09 -07:00
baKon d5b65cddc6 hfget: run under the image's busybox (df, xargs -I) (#71)
With curl and jq in the image, hfget.sh got further and stopped twice more,
both times on busybox, which is the only shell and coreutils the runtime
image has:

- `df -BG --output=avail` is GNU-only. Busybox printed its usage, $free came
  out empty, and every download "did not fit". Free space now comes from
  POSIX `df -Pk` (KiB), and the fit check compares bytes against KiB * 1024.
- Busybox `xargs -I` strips a line's leading blanks, and GNU's doesn't. A
  non-LFS file (config.json, tokenizer.json...) has an empty oid, so its line
  started with a tab and reached the child one field short. The size landed in
  oid and the path in size, so every small file failed its size check:
  "config.json is 721 bytes, listing says config.json". The list line is now
  <size><tab><oid><tab><path>. Size is never empty, so no line starts with a
  blank. The manifest format is unchanged, so an existing cache stays warm.

Tested in the image (busybox) and in ubuntu:24.04 with curl and jq (GNU):
fresh fetch, warm re-run, a truncated shard resumed and a deleted file
re-fetched (sha256 matches the hub's LFS oid), and the does-not-fit guard on a
1 MiB tmpfs.
2026-10-09 12:21:48 -05:00
baKon 4ab587a8a2 docker: ship curl, jq and a CA bundle, so --model can fetch an HF repo (#71)
`--model <repo id>` runs hfget.sh, which needs curl and jq, and curl needs a
CA bundle to reach huggingface.co over TLS. The runtime image is built FROM
scratch and had none of the three, so inside the container the fetch stopped
at "hfget: jq is required" (and with jq alone it would have stopped at curl,
then at the TLS handshake).

The rootfs stage now installs curl, jq and ca-certificates and copies the two
binaries and /etc/ssl/certs/ca-certificates.crt in. Their libraries go through
the same ldd closure, ELF-from-the-chroot check and licenses.sh as everything
else. They're installed in rootfs rather than build, so this doesn't
recompile the engine. The rootfs grows from 297 to 315 MB.
2026-10-09 12:16:15 -05:00
Malic Zilyas 32fa1a27ec libr4d: 5-/4-bit decode GEMM covers all row tiles in one block
cfg_for() pins MB = 1 across the decode band (M <= 64): right for the bf16
and MXFP4 skinny kernels, where the grid, not the weight, is the cost. The
w5a16 / w4a16_asym kernel is dequantise-bound, and one block per 16-row tile
unpacks every weight fragment once per tile, so two or three concurrent
streams (M = 16..48) paid the unpack two or three times: 104 us/call at one
stream, 190 us at three (profile-ops, PARO int5, 1.3.0).

Cover every row tile in one block (MB = ceil(M / 16), at most 4) unless a
tuned MB is pinned. The split-K bound is unchanged, so every output element
is still one wave's accumulation over the same K slices: output bits are
identical.

PARO int5, prod shape (175k / 3 seqs), BetterBench c3 aggregate t/s at
1 / 2 / 3 streams:  96 / 156 / 155  ->  92 / 169 / 170 (+9% / +10%);
same-source A/B on the dev build: c3 127 -> 166. Single-stream decode is
unchanged (that GEMM streams the weights at the memory roofline, ~620 GB/s).
Quality unchanged: ppl wiki 6.797 / code 1.533, GSM8K 100%, genchat 17/17
cold-verified, dia-mini v2 23/27, v3 15/15.

r4d_selftest gemm_w5a16_nt_m64: pass (incl. M = 40 with 3 parts, M = 64).
2026-10-09 12:30:15 +02:00
baKon 04405089cb sched: a long prefill leaves the rest of the step its room (--busy-prefill-chunk)
A prefill chunk took every token the step had left (plan_chunk(..., budget)). On a step budget of
a few thousand tokens and a prompt of a few hundred thousand, that is every step for a minute or
more, and for all of it a decode row behind the prefill in running_ got nothing (`want > budget`
-> break) and admission never ran (`while (... budget > 0)`). A mostly-cached turn that needed a
few hundred tokens waited for somebody else's whole prompt: on three ranks at
--max-num-batched-tokens 2048, a 94,529-token turn with 94,208 cached took 40.6 s to its first
token, which landed on the instant a 264,725-token cold prefill ahead of it ended (#61).

--busy-prefill-chunk auto (the default) holds a prefill chunk back only when work that would
otherwise get nothing is pending in the step: one row plus the draft window for each decode row
behind it, a share (an eighth of the budget, at least one quantum) for each prefill behind it and
for the next request waiting to start. The chunk never drops under the smallest step the prefill
stager overlaps -- under it every routed layer reads its pooled experts synchronously, the
-65 % prefill measured at a budget one token under the threshold. Where holding it back for a
waiting request or another prefill would leave a remainder under that floor before the checkpoint
boundary, the interval is split into two staged halves instead. Decode rows alone only take their
few tokens: the chunk ends a quantum short of the boundary and the next step finishes the
interval, the same pair of steps a prefill already runs when decode rows are planned ahead of it.
(Halving for decode rows too held a long prompt to half-interval chunks for as long as anything
decoded behind it, the larger cost.) Whatever the reserve was not used for (a refused admission, a
decode row that drafted less than its window) goes back to the chunk before the step is issued.
Admission shares the same way, so a cold prompt admitted with others queued behind it does not
take the whole step either; an embedding input still runs whole or not at all.

A prompt with nothing beside it, and rows already planned ahead of the prefill, are planned
exactly as before, so a lone request's steps -- and every greedy output -- are unchanged. `off`
restores the old loop including its break. `N` holds a chunk that shares the step to N tokens,
rows ahead included (the operator trading prefill speed for every other row's latency); startup
warns when N is under the stager's step.

The engine hands the scheduler the stager's smallest pass after init (PrefillStager::min_rows,
the largest over the ranks). radiance:engine_prefill_chunks_capped_total counts the chunks held
back. sched_test covers admission during a long prefill, a decode row behind one, off reproducing
the old plan, a lone prefill unchanged, an explicit N with rows ahead and behind, the share
handed back when nobody takes it, and the cap's arithmetic at a 2048-token step with the stager
at 1025, with and without a share in the reserve.
2026-10-09 00:28:03 -05:00
Malic Zilyas 9137948b95 ParoQuant dense: review fixes -- the matrices composed exactly, out checked, the stored form pinned
* r4d_rad_relayout_gdense composes in f64 (angles widened, cos/sin and products in double) and rounds to
  f16: the stored matrix is a derivation of the planes, the same bytes whichever libm computed it, as
  abi/rad_abi.h asks of a relayout.
* givens_dense_quant (libr4d and libref) refuses an `out` that does not name q's dtype instead of reading
  the quantiser off q alone.
* relayout_parity_test pins the dense stored form by hash, checks each matrix is orthogonal to f16
  accuracy and that a broken pairing is refused.
* r4d_givens_dense: static_assert that a thread stages one channel scale of the group; the selftest's
  givens_numeric takes one mode (rotate / dense fp8 / dense i8) instead of three flags; cGivensDense
  sits after the Hadamard constraint with its own comment.
2026-10-08 23:35:43 +02:00
Malic Zilyas d6b506fe4f ParoQuant dense: the gdense relayout checks the pairs with the givens pairs hook's gv_pairs_ok (a full pairing of each group, not only the range) 2026-10-08 23:35:43 +02:00
Malic Zilyas ec65b8cbeb ParoQuant: drop the sequential rotate-and-quantise ops (givens_quant_act_fp8 / givens_quant_act_i8g): givens_dense_quant replaces them; the rotate-only f16 kernel keeps its own file 2026-10-08 23:35:43 +02:00
Malic Zilyas c17f5fdc89 ParoQuant: dense per-group rotation (givens_dense_quant): composed 128x128 f16 matrices built at convert time, WMMA kernel with int8/fp8 epilogue; LinearFP8 uses it for the quantising rotation 2026-10-08 23:35:43 +02:00
Malic Zilyas a19cbcae85 ParoQuant int5/int4: review fixes -- docs, the w5 layout pinned and inverted, zero points checked, int4 import tested
* docs/OPS.md: the dtypes w5a16, w4a16_asym, w5a8i8, w4a8i8_asym, givens_quant_act_i8g, and which rows read pb1/pb2.
* r4d_gemm_w5a16_nt_m64: drop the unused two's-complement dequant copied from w4; the errors name this kernel.
* r4d_layout: r4d_rad_unrelayout_w5 (the inverse, wired to both w5 rows; the int4 rows take w4's); a zero point
  that is not a 4-/5-bit code is refused at load (the int8 prefill kernel reads five bits of it, the f16 one all).
* rad_fp8.h: one linear_is_givens predicate (table dtypes checked for both formats, the zero plane's u8 too);
  declare_rotation declares the tables and rot_stages only, decl_rot_op the op in front of each GEMM.
* tests: relayout_parity pins the w5 stored form and its refusal; checkpoint_test imports z-lab's int4 as a fused
  gate|up (two rotated parts); the selftest's asymmetric planes and part bounds come from one helper each.
* checkpoint: the ParoQuant refusal names both readable forms.
2026-10-08 23:35:43 +02:00
Malic Zilyas 3491aca6fe ParoQuant int5/int4: the review fixes of PR 1 carried to the 5-/4-bit path
* givens_rotate and givens_quant_act_i8g take the same checked `pairs` relayout as givens_quant_act_fp8.
* gemm_w4a8i8/w5a8i8_tiled: one re-tile slab for every part, as gemm_mxfp4a8_tiled (they share its
  scratch hook, which is one slab now).
* LinearFP8::decl_gemm_q: the one gemm_nt_q declaration, pb1/pb2 only with parts, for the MXFP4, the
  skinny 5-/4-bit and the int8 prefill GEMMs.
2026-10-08 23:35:43 +02:00
Malic Zilyas 6091039926 libr4d: int8 prefill band for ParoQuant int4/int5 (gemm_w4a8i8/w5a8i8 tiled, givens_quant_act_i8g); LinearFP8 uses it above 64 rows 2026-10-08 23:35:43 +02:00
Malic Zilyas cfe03f8ad8 qwen35_fp8: serve rotated 5-bit and 4-bit linears; keep the fp8 gated fold off them 2026-10-08 23:35:43 +02:00
Malic Zilyas 9e9fce3aca libr4d: w5a16 / w4a16_asym GEMM (5- and 4-bit asymmetric, any M, parts), givens_rotate kernel, layouts, selftest 2026-10-08 23:35:43 +02:00
Malic Zilyas ffa235bf0f libref: givens_rotate (the rotation without the quantiser, f16 out) 2026-10-08 23:35:43 +02:00
Malic Zilyas e45bb596f4 format: import ParoQuant int5-bitplane and z-lab's int4 (u5/u4 codes, f16 scale, u8 zero, givens tables) 2026-10-08 23:35:43 +02:00
Malic Zilyas 9af15f3a6e ParoQuant: check the givens pairs at load; one re-tile slab for every part; one bounds helper; one mxfp4 GEMM declaration
* libr4d: givens_quant_act_fp8 gets layout/relayout/unrelayout hooks for `pairs` -- stored as is,
  refused (RAD_E_FORMAT) when a stage is not a pairing of its own group of 128, which the kernel would
  index out of bounds. relayout_parity_test covers it.
* gemm_mxfp4a8_tiled: the parts run in order on one stream, so they share one re-tiled activation;
  the scratch is one slab again.
* mx_part_bounds: the pb1/pb2 clamping in one place (mx_parts, the decode scratch hook).
* LinearFP8: one gemm_nt_q declaration and one issue path for the plain and the rotated MXFP4 weight;
  pb1/pb2 still only on a weight with parts, so a one-part op keeps its tune-cache geometry.
2026-10-08 23:35:43 +02:00
Malic Zilyas 5681da471c qwen35_fp8: serve rotated MXFP4 linears (LinearFP8 rotates its input first); paro recipe
A rotated weight reads the producer's bf16 plane, rotates and quantises it into its own planes
(parts side by side) and runs the ordinary mxfp4a8 GEMM. Adds data/recipes/q38-27b-paro-mxfp4-df2.recipe
and the GUIDE entry.
2026-10-08 23:35:43 +02:00
Malic Zilyas 36e3b78c76 libr4d: givens_quant_act_fp8 kernel; mxfp4a8 GEMMs take parts as launches over windows
The rotate+scale+quantise kernel does a (part, group) per wave with the stages' tables prefetched.
The three MXFP4 GEMM rows learn row pitches (lda, ldws, ldc) and launch once per weight part; the
layout hook accepts the codes/exponent planes of a givens-encoded weight. r4d_selftest checks the
kernel against an f64 rotation and every GEMM row's parts against the planes' meaning.
2026-10-08 23:35:43 +02:00
Malic Zilyas 1213c05cd8 ops: givens_quant_act_fp8; gemm_nt_q pb1/pb2 for activation copies per weight part
libref implements both (and is the oracle); libavx refuses a call that names a part.
2026-10-08 23:35:43 +02:00
Malic Zilyas 3402acf82d format: import ParoQuant MXFP4 checkpoints (givens transform with parts, per-row fp8 scale)
quant_method paroquant_mxfp4 is Quark's MXFP4 planes in a rotated basis plus z-lab's learned
Givens rotations. rad-convert reads the codes and exponents byte for byte and builds the
encoding's givens tables (t.pairs/t.angle/t.scale) from pairs/theta/channel_scales; a fused
gate|up or qkv|z gets one set of tables a checkpoint tensor (new t.part table). The core decoder
undoes the per-part rotation. fp8 tensors with one f32 scale a row are read exactly.
2026-10-08 23:35:43 +02:00
1733 changed files with 735479 additions and 124135 deletions

No files matched your search

+2
View File
@@ -5,3 +5,5 @@ build*
.claude
**/*.rad
compile_commands.json
dashboard/node_modules
dashboard/dist
+1
View File
@@ -5,3 +5,4 @@ compile_commands.json
*.rad
/sync-jarvis.sh
__pycache__/
.cache/
+161 -219
View File
@@ -1,8 +1,7 @@
cmake_minimum_required(VERSION 3.21)
# VERSION is what /version reports and what a client checks compatibility against. It is NOT the
# ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because
# a plugin contract and a server release do not move together.
project(radiance VERSION 1.3.0 LANGUAGES C CXX)
# VERSION is the server release that /version reports. The plugin ABI version is separate and is
# read from abi/rad_abi.h below.
project(radiance VERSION 2.0.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -13,31 +12,31 @@ if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE RelWithDebInfo)
endif()
# NOT option(): option() is boolean-only, so a default of AUTO collapses to OFF and the detection
# below never runs -- a machine with cards then silently builds the host backend. Tri-state wants a
# cache STRING.
# A cache STRING, not option(): option() is boolean, so AUTO would collapse to OFF and skip
# detection.
set(RAD_WITH_HIP "AUTO" CACHE STRING "ON | OFF | AUTO -- build the HIP backend and device kernels")
set_property(CACHE RAD_WITH_HIP PROPERTY STRINGS ON OFF AUTO)
set(RAD_WITH_FFMPEG "AUTO" CACHE STRING "ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample")
set(RAD_WITH_FFMPEG "AUTO" CACHE STRING
"ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample")
set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO)
option(RAD_BUILD_TESTS "Build the test suite" ON)
option(RAD_ASAN "Build with AddressSanitizer" OFF)
option(RAD_ENABLE_KV_ROLLBACK_TEST_HOOK "Compile the test-only device KV rollback observer" OFF)
option(RAD_ASAN "Build host code with AddressSanitizer and UBSan" OFF)
option(RAD_TSAN "Build host code with ThreadSanitizer" OFF)
# LLVM 24's VOPD pairing is not repeatable unless patched (docker/llvm-vopd-pairing.patch); when
# OFF, pairing is disabled on LLVM 24. See rad_hip_repeatable in cmake/RadAddPlugin.cmake.
option(RAD_HIP_VOPD_REPEATABLE "The HIP compiler's VOPD pairing is repeatable (the image's LLVM 24 is)" OFF)
# ---------------------------------------------------------------- HIP detection
# RAD_GPU_TARGETS is the set of offload architectures device kernels are compiled for. The project
# does not fix it and holds no opinion about which cards are acceptable: a kernel library is a
# plugin, so which hardware the engine can serve is decided by which kernel plugins are installed,
# not here (spec §2.1). Leaving it unset means "ask this machine", through the enumerator the ROCm
# toolchain ships.
# RAD_GPU_TARGETS lists the offload architectures device kernels are compiled for. Which cards the
# engine serves is decided by the installed kernel plugins, not here (spec §18). Unset means
# enumerate this machine's devices with the ROCm toolchain.
#
# A kernel library that covers only some architectures narrows the list for itself with
# rad_plugin_gpu_targets() and skips its own build when the intersection is empty. That is how
# libr4d, which is RDNA4-only, coexists with a target list that may name anything, and it is the
# same mechanism a library for another card uses from out of tree.
# A kernel library covering only some architectures narrows the list with rad_plugin_gpu_targets()
# and skips itself when the intersection is empty (libr4d is RDNA4-only).
#
# With no ROCm at all the host backend is built. That is a supported configuration and not a
# degraded one: everything except device kernels is exercised by it.
# Without ROCm the host backend is built, a supported configuration that exercises everything
# except device kernels.
set(RAD_HIP_FOUND OFF)
if(NOT RAD_WITH_HIP STREQUAL "OFF")
find_program(RAD_HIPCC hipcc HINTS /opt/rocm/bin /opt/rocm/llvm/bin ENV ROCM_PATH)
@@ -50,10 +49,8 @@ if(NOT RAD_WITH_HIP STREQUAL "OFF")
endif()
if(RAD_HIP_FOUND AND NOT DEFINED RAD_GPU_TARGETS)
# amdgpu-arch and offload-arch each print one architecture per visible device. EVERY device is
# listed, integrated graphics included, and that is the right input: a plugin filters the list
# down to what it serves, so an architecture no library covers costs a skipped plugin rather
# than a refused configure.
# amdgpu-arch / offload-arch print one architecture per visible device, integrated graphics
# included. Plugins filter the list to what they serve.
find_program(RAD_ARCH_TOOL NAMES amdgpu-arch offload-arch
HINTS /opt/rocm/bin /opt/rocm/llvm/bin ENV ROCM_PATH)
if(RAD_ARCH_TOOL)
@@ -67,12 +64,11 @@ if(RAD_HIP_FOUND AND NOT DEFINED RAD_GPU_TARGETS)
endif()
endif()
if(NOT RAD_GPU_TARGETS)
# A toolchain with no card attached is an ordinary build machine. Guessing an architecture here
# would emit kernels for hardware nobody named, so the device build is declined and the way to
# ask for it anyway is spelled out.
# No card attached: do not guess an architecture. Decline the device build and say how to
# request one.
set(RAD_HIP_FOUND OFF)
message(WARNING
"radiance: hipcc was found but no AMD GPU could be enumerated, so this build has NO device "
"radiance: hipcc was found but no AMD GPU could be enumerated, so this build has no device "
"kernels. To cross-compile them anyway, name the architectures: -DRAD_GPU_TARGETS=gfx1201 "
"(semicolon-separated for several).")
endif()
@@ -84,88 +80,66 @@ elseif(RAD_WITH_HIP STREQUAL "OFF")
message(STATUS "radiance: HIP backend OFF by request -- host backend only")
elseif(NOT RAD_HIPCC)
message(WARNING
"radiance: HIP backend OFF -- hipcc was not found, so this build has NO device kernels.\n"
" That is correct on a machine without ROCm and WRONG on one with cards. Looked in "
"/opt/rocm/bin, /opt/rocm/llvm/bin and \.")
"radiance: HIP backend OFF -- hipcc was not found, so this build has no device kernels.\n"
" Expected on a machine without ROCm, wrong on one with cards. Looked in /opt/rocm/bin, "
"/opt/rocm/llvm/bin and $ROCM_PATH.")
endif()
# HOST CODE ONLY, AND THAT IS NOT A COMPROMISE -- IT IS THE WHOLE AVAILABLE SURFACE.
# ASan + UBSan for host code only. AMD's amdgcn ASan needs xnack+ for its page-fault-based shadow,
# and RDNA has no xnack, so the generator expressions keep the flags off HIP. Device kernels rely on
# rad-kbench's red zones instead: a poisoned margin around every operand and scratch allocation,
# checked after the launch, which catches out-of-bounds writes.
#
# AMD ships an amdgcn AddressSanitizer (/opt/rocm/amdgcn/bitcode/asanrtl.bc) and it cannot run
# on an RDNA card: its shadow is page-fault based, which needs xnack+, and RDNA does not implement
# xnack -- rocminfo reports `XNACK enabled: NO`. Handing -fsanitize=address to the HIP
# compilation therefore buys a device binary that cannot work, so the generator expression keeps
# it off the HIP language entirely. What device kernels get instead is rad-kbench's red zones: a
# poisoned margin either side of every operand and every scratch allocation, verified after the
# launch. That catches the out-of-bounds WRITE, which is the one that corrupts a neighbour.
#
# What this DOES cover is everything else, which is most of the project: the core, the tools,
# libref in full, and every host-side launch wrapper in libr4d. UBSan comes with it because the
# two share a build and the interesting reports here -- a signed shift, a misaligned load, an
# enum out of range -- are UBSan's, not ASan's.
# TSan, likewise host code only, for the threaded host paths (scheduler, server, stager, tokenizer
# cache). libgomp is not instrumented, so tests run it with one thread (tests/CMakeLists.txt).
if(RAD_ASAN AND RAD_TSAN)
message(FATAL_ERROR "RAD_ASAN and RAD_TSAN cannot be combined; use a build directory for each.")
endif()
if(RAD_ASAN)
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fsanitize=address,undefined>
$<$<COMPILE_LANGUAGE:CXX>:-fno-omit-frame-pointer>
$<$<COMPILE_LANGUAGE:CXX>:-fno-sanitize-recover=all>)
add_link_options(-fsanitize=address,undefined)
endif()
if(RAD_TSAN)
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fsanitize=thread>
$<$<COMPILE_LANGUAGE:CXX>:-fno-omit-frame-pointer>)
add_link_options(-fsanitize=thread)
endif()
add_compile_options(-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers)
# GNUInstallDirs before the ABI, not after it, because the ABI target's INSTALL_INTERFACE include
# path is spelled in CMAKE_INSTALL_INCLUDEDIR and an undefined variable there expands to nothing --
# which is not an error, it is an exported target whose include directory is the install prefix
# itself, so every consumer's `#include "rad_abi.h"` misses by one directory level.
# Before the ABI: its INSTALL_INTERFACE path uses CMAKE_INSTALL_INCLUDEDIR, which would otherwise
# expand to nothing and silently export the wrong include directory.
include(GNUInstallDirs)
# ---------------------------------------------------------------- the ABI
# Header-only. The ONLY thing plugins compile against.
# Header-only, and the only thing plugins compile against.
add_library(rad_abi INTERFACE)
# radiance::abi is the name plugins link, in-tree and out. It is an ALIAS here and an imported
# target in the installed package, and the two are spelled identically on purpose: rad_add_plugin
# has ONE body (cmake/RadAddPlugin.cmake) and it cannot branch on which world it is running in.
# Plugins link radiance::abi: an ALIAS here, an imported target when installed, so rad_add_plugin
# (cmake/RadAddPlugin.cmake) needs one body for both.
add_library(radiance::abi ALIAS rad_abi)
set_target_properties(rad_abi PROPERTIES EXPORT_NAME abi)
# CMAKE_INSTALL_FULL_DATADIR and not a literal "share": it is <prefix>/share under every default,
# and it moves together with the destination the plugins are actually installed to. Those two
# disagreeing is a prefix that looks complete and whose loader finds nothing.
# CMAKE_INSTALL_FULL_DATADIR, not a literal "share", so it follows the plugin install destination.
set(RAD_DEFAULT_HOME "${CMAKE_INSTALL_FULL_DATADIR}/radiance" CACHE STRING "default $RADIANCE_HOME")
target_include_directories(rad_abi INTERFACE
# abi/ AND NOT THE REPO ROOT, which is the whole reason the headers sit in a directory of their
# own rather than being included as `abi/rad_abi.h` from the top. A plugin links this target and
# gets exactly the headers in abi/ on its include path -- not core/, not arch/, not the tree. An
# ABI a plugin can see past is not a boundary.
#
# BUILD_INTERFACE/INSTALL_INTERFACE rather than one bare path, because this target is exported:
# a bare ${CMAKE_CURRENT_SOURCE_DIR}/abi is a hard error out of install(EXPORT) ("path which is
# prefixed in the source directory"), and the export is the whole point -- an interface target
# that cannot leave the tree is the defect, not the fix.
#
# The spelling is the same in both worlds: `#include "rad_abi.h"` in-tree and installed, because
# rad_add_plugin has ONE body and cannot branch on which world it is running in.
# abi/, not the repo root, so a plugin sees only the ABI headers, never core/ or arch/.
# Generator expressions because the target is exported, and install(EXPORT) rejects a source
# path. Plugins write `#include "rad_abi.h"` both in-tree and installed.
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/abi>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/radiance>)
target_compile_definitions(rad_abi INTERFACE RAD_DEFAULT_HOME="${RAD_DEFAULT_HOME}")
if(RAD_HIP_FOUND)
target_compile_definitions(rad_abi INTERFACE RAD_HAVE_HIP=1)
# core/device/hip.cpp is compiled by the ORDINARY C++ compiler -- only plugins go through
# hipcc -- so it needs the HIP headers on the include path explicitly. hipcc supplies them to
# itself, which is why this is invisible until the first non-plugin translation unit includes
# hip_runtime.h.
# Host translation units such as core/device/hip.cpp use the ordinary C++ compiler and need the
# HIP headers explicitly.
#
# SYSTEM, AND NOT AS A MATTER OF TASTE. hipcc has this same directory on its own path as a
# SYSTEM include, where a warning inside it is suppressed. Naming it again as an ordinary -I
# puts the user-include copy first and the headers stop being system headers -- for every
# plugin, because this is an INTERFACE property of rad_abi and every plugin links it. One ROCm
# header alone (amd_device_functions.h: `__fns`, `__fns64`, unused) then warns in every
# translation unit that includes it, which is a large share of the build output and none of it
# ours. A build whose warnings are mostly somebody else's is a build where nobody reads the
# warnings.
# SYSTEM: hipcc already has this directory as a system include. A plain -I would take precedence
# and make ROCm headers warn in every plugin (rad_abi is an INTERFACE dependency of all of them).
#
# BUILD_INTERFACE only: the path is this machine's, and an exported target carrying it fails to
# configure wherever ROCm sits elsewhere. The installed package config finds the headers again on
# the consumer's machine (cmake/radiance-config.cmake.in).
# BUILD_INTERFACE only: the path is this machine's. The installed package config finds the
# headers on the consumer's machine (cmake/radiance-config.cmake.in).
get_filename_component(RAD_ROCM_BIN "${RAD_HIPCC}" DIRECTORY)
get_filename_component(RAD_ROCM_ROOT "${RAD_ROCM_BIN}" DIRECTORY)
if(EXISTS "${RAD_ROCM_ROOT}/include/hip/hip_runtime.h")
@@ -186,16 +160,12 @@ endif()
set(RAD_PLUGIN_OUT ${CMAKE_BINARY_DIR}/radiance_home)
file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/kernels ${RAD_PLUGIN_OUT}/architectures)
# THE RECORDED KERNEL FIXTURE, COPIED INTO THE BUILD'S HOME.
#
# data/kernels.rkb is checked in and is what makes `rad-kbench` runnable with no model present: it
# holds the geometries, the seeds the inputs are drawn from and libref's answers reduced to a norm
# and a sample. Copied rather than pointed at, because $RADIANCE_HOME is what the tool looks in and
# an installed prefix has no source tree beside it. Recording a new one is
# Recorded kernel fixtures, copied into the build's $RADIANCE_HOME (where rad-kbench looks; an
# installed prefix has no source tree). data/kernels.rkb lets rad-kbench run with no model: it holds
# geometries, input seeds and libref's answers reduced to a norm and a sample. Re-record with a 27B
# IQ8R container that carries its DFlash2 drafter:
#
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels.rkb
#
# and that is the only step that needs a 27B container on the machine.
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb
${RAD_PLUGIN_OUT}/kernels.rkb COPYONLY)
@@ -203,13 +173,9 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb)
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance)
endif()
# THE SECOND FIXTURE, AND WHY THERE ARE TWO. A recording is of ONE container -- it holds that
# model's declared geometries -- and no single container in scope declares the whole vocabulary.
# The 27B is dense, has a DFlash2 drafter and gqa 6; the 35B-A3B is routed (moe_gemm_q,
# router_topk, moe_scatter, moe_gather, scale_rows), has an MTP head and gqa 8. Recording only one
# leaves five ops and a whole attention dispatch with no replay coverage at all, so a kernel that
# no locally available model exercises would regress unseen. Recording a new one is
# A recording covers one container's geometries, and no single model declares the whole vocabulary.
# The 27B is dense with a DFlash2 drafter and gqa 6; the 35B-A3B IQ8R container is routed
# (moe_gemm_q, the fused router, moe_gather, scale_rows) with an MTP head and gqa 8. Re-record with
#
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels_moe.rkb
#
@@ -219,87 +185,65 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance)
endif()
# THE DOWNLOADER `radiance --model <owner/name>` RUNS (core/hf_model.cpp). The engine finds it at
# <bin>/../libexec/radiance/, so the build puts a copy at the same place under the build tree and
# a binary run from either tree finds it without a path to configure.
# The published refusal-direction vector for qwen4exp, copied into the built home's vectors/ so a
# Flash-Next container offers the switch with nothing for an operator to install: core/cvec.cpp looks
# for <home>/vectors/<arch>-control-vector.gguf after the sidecar paths. The file is Cudecnik's,
# unchanged (huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection; the gguf is sha256
# ef0724c5b79297e4..., the json d4a3dd842506a6fb..., and that is what the measurements in
# docs/GUIDE.md 4.10 were made with). Refresh with:
#
# huggingface-cli download Cudecnik/Qwen3.8-Flash-Next-refusal-projection \
# Qwen3.8-Flash-Next-refusal-projection.{gguf,json}
#
# The directions are derived from Qwen3.8-Flash-Next's weights and stay under the Qwen Community
# License 1.0 (data/vectors/LICENSE.qwen-community-1.0.txt, NOTICE); radiance's Apache-2.0 grant
# covers the code that reads them, never the file. It ships loaded only when the deployment asks
# (--control-vector), and the request default is off, because what it removes is a safety behaviour.
file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/vectors)
foreach(rrad_vector qwen4exp-control-vector.gguf qwen4exp-control-vector.json)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/${rrad_vector}
${RAD_PLUGIN_OUT}/vectors/${rrad_vector} COPYONLY)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/${rrad_vector}
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance/vectors)
endforeach()
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/vectors/LICENSE.qwen-community-1.0.txt
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME qwen-community.LICENSE)
# The downloader behind a model source naming a repo, `model: <owner/name>` (core/hf_model.cpp).
# The engine looks in <bin>/../libexec/radiance/, so the build tree mirrors that layout.
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
${CMAKE_BINARY_DIR}/libexec/radiance/hfget.sh COPYONLY)
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/radiance)
# rad_add_plugin() and rad_hipify() live in cmake/RadAddPlugin.cmake because the installed package
# config includes that same file: a third party building a plugin from their own repository needs
# the function, and a second copy of it in the package config would drift from this one. The file
# documents the variables it expects; every one of them is set above.
# rad-export (a finetune to a .rad with the stock model's recipe) runs on the host, beside the
# trainer. It is installed with the tools so the image hands it out
# (`docker run --entrypoint busybox <image> cat /opt/radiance/bin/rad-export`), though the image
# has no Python to run it.
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/tools/rad-export
DESTINATION ${CMAKE_INSTALL_BINDIR})
# rad_add_plugin() and rad_hipify(), shared with the installed package config. The variables it
# expects are all set above.
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/RadAddPlugin.cmake)
if(RAD_HIP_FOUND)
string(TOUPPER "${CMAKE_BUILD_TYPE}" RAD_CFG_UPPER)
# NOT `set(CMAKE_CXX_COMPILER hipcc)`. The C++ compiler is fixed by project() and assigning it
# afterwards is silently ignored -- device sources then reach the host C++ compiler with
# --offload-arch, an error that reads like a bad flag rather than a bad compiler.
#
# CMake has had a HIP language since 3.21. Device sources are marked LANGUAGE HIP and the rest of
# the tree stays on the ordinary C++ compiler, which is what we want: only kernels need hipcc.
# CMake refuses hipcc as CMAKE_HIP_COMPILER by design ("use Clang directly"), so this is ROCm's
# own clang++. That needs the address-space cast in libr4d/r4d_common.h: ROCm 7.2 / LLVM 22
# tightened __builtin_amdgcn_global_load_tr_b128_v8i16 to require a global address space, and
# the builtin fails identically under hipcc and clang++ without it.
# The HIP language (CMake >= 3.21): device sources are LANGUAGE HIP and everything else stays on
# the C++ compiler. Do not set CMAKE_CXX_COMPILER to hipcc; after project() it is silently
# ignored. CMake refuses hipcc as CMAKE_HIP_COMPILER, so this is ROCm's clang++. ROCm 7.2 /
# LLVM 22 requires a global address space for __builtin_amdgcn_global_load_tr_b128_v8i16, hence
# the cast in libr4d/r4d_common.h.
enable_language(HIP)
rad_hip_rule_fixes()
# AND CMAKE EMITS NO DEPENDENCY FLAGS FOR HIP, which is the same shape of omission as the two
# below and by far the most dangerous of the three, because it does not fail -- it silently
# builds the wrong thing.
# Device optimisation level for every config. Depending on its version, CMake leaves
# CMAKE_HIP_FLAGS_<CONFIG> empty (device code at -O0 with asserts) or, from CMake 4.4, pre-fills
# the host-style '-O2 -g -DNDEBUG'. At -O0 decode reads weights at ~7 GB/s on a ~640 GB/s card.
# -O3 for kernels; no -g on the device, where it slows compiles and inhibits scheduling.
#
# `CMAKE_DEPFILE_FLAGS_<LANG>` is set by the compiler modules for C and CXX and is EMPTY for HIP.
# Ninja's HIP rule still declares `depfile = $DEP_FILE` and `deps = gcc`, so it WAITS for a
# depfile the command was never told to write, and records nothing:
#
# $ ninja -t deps libr4d/CMakeFiles/libr4d.dir/r4d_model_bf16.hip.o
# ...hip.o: #deps 0, deps mtime ... (VALID)
#
# Zero. No header is a dependency of any .hip object, so editing a header libr4d includes --
# r4d_emit.h, r4d_common.h, r4d_fp8_wmma.h, or the ABI itself -- recompiles nothing and RELINKS
# the plugin around stale objects. The library then exports one signature and the engine calls
# another -- a hook called with more arguments than it takes, which segfaults inside the plugin
# with a stack that blames the kernel -- and every test after the edit runs objects that predate
# it.
#
# It is a one-line omission with no upper bound on what it can hide, so it is fixed here rather
# than worked around with `touch`.
if(NOT CMAKE_DEPFILE_FLAGS_HIP)
set(CMAKE_DEPFILE_FLAGS_HIP "-MD -MT <DEP_TARGET> -MF <DEP_FILE>")
endif()
# AND CMAKE DOES NOT SUPPLY A SYSTEM-INCLUDE FLAG FOR HIP EITHER, which is the same shape of
# omission as the optimisation level below and just as quiet. `CMAKE_INCLUDE_SYSTEM_FLAG_<LANG>`
# is set by the compiler modules for C and CXX and is EMPTY for HIP, and CMake's fallback when it
# is empty is a plain `-I` -- so every SYSTEM include directory reaches a .hip translation unit as
# an ordinary user include and every warning inside it becomes ours. Without this, ONE
# target_include_directories(... SYSTEM ...) call reaches a CXX source as
# `-isystem /opt/rocm/include` and a .hip source as `-I/opt/rocm/include` -- so this is not
# something an author can get right at the call site. It is set once, here, for every HIP target
# in the tree, vendor/ included.
set(CMAKE_INCLUDE_SYSTEM_FLAG_HIP "-isystem ")
# OPTIMISATION LEVEL, SET HERE FOR EVERY CONFIG BECAUSE CMAKE DOES NOT SUPPLY A USABLE ONE FOR
# HIP. Depending on the CMake version `CMAKE_HIP_FLAGS_<CONFIG>` is either EMPTY -- every device
# kernel compiles at -O0 with asserts live while the host half gets -O2 -g -DNDEBUG -- or, from
# CMake 4.4's HIP toolchain on, pre-filled with the host-style '-O2 -g -DNDEBUG'. Nothing in the
# build says so either way: an absent flag reads as the default, a pre-filled one as a choice.
#
# It is the whole performance story. At -O0 decode reads weights at about 7 GB/s against a card
# that does ~640, and no kernel change can fix a build that does not optimise the kernel. -O3 and
# not -O2 because these are the kernels; -g is deliberately NOT carried onto the device side,
# where it costs compile time and inhibits scheduling for a symbol table no profiler here reads.
#
# THE ASSIGNMENT IS UNCONDITIONAL. A guard such as `if(NOT CMAKE_HIP_FLAGS_${cfg})` cannot tell a
# toolchain default from an operator's choice: on a CMake that pre-fills the variable it sees a
# value and leaves every device kernel at -O2 with debug info, and a build tree whose cache still
# holds -O3 from an older CMake hides that until its next fresh configure drops it, with no
# signal in the build output. An operator who genuinely wants other device flags says so BY NAME
# through RAD_HIP_FLAGS_<CONFIG>. A deliberate override is a thing someone typed; a toolchain
# default that happens to be non-empty is not, and the two must not be spelled the same way.
# The assignment is unconditional (FORCE) because a guard cannot tell a toolchain default from an
# operator's choice. Override by name with RAD_HIP_FLAGS_<CONFIG>.
foreach(cfg DEBUG RELEASE RELWITHDEBINFO MINSIZEREL)
if(cfg STREQUAL "DEBUG")
set(lvl "-O0 -g")
@@ -324,10 +268,9 @@ endif()
find_package(Threads REQUIRED)
# ---------------------------------------------------------------- media decoding
# An image, video or audio part of a request is decoded by libavformat/libavcodec and converted by
# libswscale or libswresample (core/mm/media.cpp). Without them the engine builds and serves text, and refuses a
# media part by name -- the same tri-state as HIP, because a machine that has the libraries should
# not silently build without them.
# Image, video and audio request parts are decoded by libavformat/libavcodec and converted by
# libswscale/libswresample (core/mm/media.cpp). Without them the engine serves text and refuses media
# parts. Tri-state like HIP, so a machine with the libraries does not silently build without them.
set(RAD_FFMPEG_FOUND OFF)
if(NOT RAD_WITH_FFMPEG STREQUAL "OFF")
find_package(PkgConfig QUIET)
@@ -346,11 +289,8 @@ endif()
add_subdirectory(vendor)
add_subdirectory(core)
# THE KERNEL PLUGINS, one directory each, at the root, with no `kernels/` grouping: a plugin's
# kernels, row table, layouts and launch adapter all live in its own directory, so it reads as a
# plugin built on abi/ rather than something the engine assembles. Each links rad_abi and nothing
# else, from one directory, exactly like a plugin written out of tree. That is the acceptance test,
# and this is the layout that states it.
# Kernel plugins, one root directory each. Each holds its kernels, row table and layouts and links
# only rad_abi, exactly like a plugin written out of tree.
add_subdirectory(libref)
# libquant: the built-in quantisers, the third plugin kind (spec §4.5). Host C++, built everywhere:
# rad-convert drives it and the oracle decodes through it.
@@ -358,17 +298,33 @@ add_subdirectory(libquant)
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt)
add_subdirectory(libr4d)
endif()
# libavx: the conventional op vocabulary in hand-written x86 SIMD, runtime-dispatched by CPU
# feature -- the production HOST kernels, built wherever libref is, on x86-64. An op the placement
# puts on the host needs a host kernel that is not the oracle (rad_gate_reference_kernels refuses
# to serve on libref), and a model whose table is too large for the card -- the n-gram
# embedding's gather -- puts one there every step. It is not behind an option for that reason: a
# build without it cannot serve such a model. It also builds standalone (`cmake -S libavx -B
# build-avx`) on a box with no ROCm.
# libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP
# toolchain. It declares itself for `^gfx11` and returns without a target when the build's
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it, and
# declines every machine without a gfx11 card (rad_plugin_open). A card with no kernel library of
# its own refuses device-only ops (docs/PLUGIN.md §10).
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt)
add_subdirectory(libr3d)
endif()
# libhalo: the Strix Halo (gfx1151) kernel library, built only when RAD_GPU_TARGETS names gfx1151.
# On a gfx1151 it is preferred over libr3d, which also serves the chip: with no --kernels list the
# loader takes libraries in file-name order (libhalo.so ahead of libr3d.so), the first library with
# a row for an op supplies it, and libhalo declines every machine without a gfx1151
# (rad_plugin_open), so other RDNA3 cards get libr3d alone.
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libhalo/CMakeLists.txt)
add_subdirectory(libhalo)
endif()
# libavx: the production host kernels (x86 SIMD, dispatched by CPU feature), built on every x86-64.
# Not optional: host-placed ops need a kernel other than the oracle (rad_gate_reference_kernels
# refuses libref), and a table too large for the card, such as the n-gram embedding's gather, runs
# on the host every step. Also builds standalone without ROCm (`cmake -S libavx -B build-avx`).
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
add_subdirectory(libavx)
endif()
add_subdirectory(arch)
# spechub: the linear-MTP coupling kernels (--draft-coupling). Built by default; without the flag
# no op resolves to its rows.
add_subdirectory(plugin/spechub)
add_subdirectory(tools)
if(RAD_BUILD_TESTS)
enable_testing()
@@ -376,55 +332,39 @@ if(RAD_BUILD_TESTS)
endif()
# ---------------------------------------------------------------- the installed package
# Everything below is ADDITIVE: it changes nothing about what gets built or where the build tree
# puts it. It is what makes `find_package(radiance)` work: the ABI headers -- the entire documented
# contract with a plugin -- and the package config are installed, so an out-of-tree plugin compiles
# against an installed prefix rather than a hand-copied abi/. Without it the plugin boundary is
# real inside the tree and imaginary outside it.
# Install-only rules for `find_package(radiance)`; they do not affect the build tree.
#
# (a) the ABI headers. They are self-contained -- they include each other and C standard headers,
# and nothing else -- so the directory installs as a unit with no filtering beyond the
# extension. arch/common/ is installed by arch/CMakeLists.txt, which owns those files.
#
# Under include/radiance/ rather than loose in include/: a prefix of /usr shares that directory with
# every other package, and rad_*.h and arch/ are names someone else can have. The include spelling
# does not change -- the target's include path is the radiance/ directory itself.
# (a) The ABI headers, which include only each other and C standard headers. arch/common/ is
# installed by arch/CMakeLists.txt. Under include/radiance/ to avoid clashes in shared prefixes such
# as /usr; the include spelling is unchanged because the target's include path is radiance/ itself.
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/abi/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/radiance
FILES_MATCHING PATTERN "*.h")
# (b) the ABI target itself, as radiance::abi. An INTERFACE library has no artifact to install, but
# it carries the include path, RAD_DEFAULT_HOME, RAD_HAVE_HIP and the ROCm include directory -- and
# those are exactly the flags a plugin has to be compiled with to be loadable by this engine, so
# exporting the target is what stops an out-of-tree author reconstructing them by reading our
# CMakeLists and getting one of them wrong.
# (b) The ABI target as radiance::abi. It carries the include path, RAD_DEFAULT_HOME and RAD_HAVE_HIP,
# the flags a plugin must be compiled with to load in this engine.
install(TARGETS rad_abi EXPORT radianceTargets)
install(EXPORT radianceTargets
NAMESPACE radiance::
FILE radianceTargets.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/radiance)
# (c) the package config. The version IS the ABI version, read out of the header rather than written
# down a second time here: the loader refuses any plugin that does not report exactly
# RAD_ABI_VERSION (core/plugin/loader.cpp), so a package version that could drift from the header
# would let find_package(radiance 3) accept an installation whose plugins the consumer cannot load.
# SameMajorVersion, with the ABI as the major, is that same exact-match rule expressed to CMake.
# (c) The package config. Its version is the ABI version, read from the header: the loader requires
# an exact RAD_ABI_VERSION match (core/plugin/loader.cpp), which SameMajorVersion with the ABI as
# the major expresses to CMake.
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/abi/rad_abi.h" RAD_ABI_VERSION_LINE
REGEX "^#define[ \t]+RAD_ABI_VERSION[ \t]")
string(REGEX MATCH "[0-9]+" RAD_ABI_VERSION "${RAD_ABI_VERSION_LINE}")
if(NOT RAD_ABI_VERSION)
message(FATAL_ERROR
"could not read RAD_ABI_VERSION out of abi/rad_abi.h. That number is the whole "
"compatibility contract with a plugin; a build that cannot find it must not ship a package "
"config that claims one.")
"could not read RAD_ABI_VERSION out of abi/rad_abi.h; the package config cannot state the "
"plugin compatibility it is built for without it.")
endif()
include(CMakePackageConfigHelpers)
# PATH_VARS, so the config resolves these against wherever the package was actually found rather
# than against the prefix it was configured with. A staged install (DESTDIR) or a moved tree would
# otherwise hand a consumer absolute paths into a directory that no longer exists, and the symptom
# is a plugin that compiles and installs into nothing.
# PATH_VARS, so the config resolves these relative to where the package is found, which keeps
# staged (DESTDIR) and relocated installs working.
set(RAD_HOME_RELDIR "${CMAKE_INSTALL_DATADIR}/radiance")
set(RAD_INCLUDE_RELDIR "${CMAKE_INSTALL_INCLUDEDIR}/radiance")
configure_package_config_file(
@@ -440,18 +380,20 @@ write_basic_package_version_file(
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/radiance-config.cmake
${CMAKE_CURRENT_BINARY_DIR}/radiance-config-version.cmake
# The function itself, not a copy of it: the config includes this exact file, so the rule
# that decides what a plugin links and where it lands is one file for both worlds.
# The config includes this exact file, so there is one copy for both builds.
${CMAKE_CURRENT_SOURCE_DIR}/cmake/RadAddPlugin.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/radiance)
# (d) the license and the notices. Apache-2.0 asks that both travel with every copy, and the MIT
# License asks the same of each bundled component's text, so they install beside the binaries and
# anything built from the install (the Docker image) carries them.
# (d) License and notices. Apache-2.0 and the bundled components' licenses require them to travel
# with every copy, including images built from the install.
install(FILES LICENSE NOTICE DESTINATION ${CMAKE_INSTALL_DOCDIR})
install(FILES vendor/llama/LICENSE
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME llama.cpp.LICENSE)
install(FILES vendor/nlohmann/LICENSE.MIT
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME nlohmann-json.LICENSE)
install(FILES vendor/yyjson/LICENSE
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME yyjson.LICENSE)
install(FILES vendor/cpp-httplib/LICENSE
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME cpp-httplib.LICENSE)
install(FILES core/server/LICENSE.lfm
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME liquidai-d1.LICENSE)
install(FILES dashboard/THIRD-PARTY-LICENSES.txt
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME dashboard.LICENSES)
+81
View File
@@ -0,0 +1,81 @@
{
"version": 6,
"cmakeMinimumRequired": { "major": 3, "minor": 25, "patch": 0 },
"configurePresets": [
{
"name": "default",
"displayName": "RelWithDebInfo in build/, HIP when a card is found",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build"
},
{
"name": "asan",
"displayName": "AddressSanitizer + UBSan, host backend, in build-asan/",
"inherits": "default",
"binaryDir": "${sourceDir}/build-asan",
"cacheVariables": { "RAD_ASAN": "ON", "RAD_TSAN": "OFF", "RAD_WITH_HIP": "OFF" }
},
{
"name": "tsan",
"displayName": "ThreadSanitizer, host backend, in build-tsan/",
"inherits": "default",
"binaryDir": "${sourceDir}/build-tsan",
"cacheVariables": { "RAD_TSAN": "ON", "RAD_ASAN": "OFF", "RAD_WITH_HIP": "OFF" }
}
],
"buildPresets": [
{ "name": "default", "configurePreset": "default" },
{ "name": "asan", "configurePreset": "asan" },
{ "name": "tsan", "configurePreset": "tsan" }
],
"testPresets": [
{
"name": "base",
"hidden": true,
"configurePreset": "default",
"output": { "outputOnFailure": true },
"execution": { "jobs": 8, "noTestsAction": "error" }
},
{
"name": "fast",
"displayName": "The inner loop: no slow, gpu, oot or perf test",
"inherits": "base",
"filter": { "include": { "label": "^fast$" } }
},
{
"name": "host",
"displayName": "Everything that runs without a card, except the out-of-tree rebuild",
"inherits": "base",
"filter": { "exclude": { "label": "^(gpu|oot)$" } }
},
{
"name": "full",
"displayName": "Every test",
"inherits": "base"
},
{
"name": "gpu",
"displayName": "The tests that need a card, one at a time",
"inherits": "base",
"filter": { "include": { "label": "^gpu$" } }
},
{
"name": "perf",
"displayName": "The wall-clock checks, one at a time",
"inherits": "base",
"filter": { "include": { "label": "^perf$" } }
},
{
"name": "asan",
"displayName": "The fast tier under AddressSanitizer + UBSan",
"inherits": "fast",
"configurePreset": "asan"
},
{
"name": "tsan",
"displayName": "The fast tier under ThreadSanitizer",
"inherits": "fast",
"configurePreset": "tsan"
}
]
}
+190 -69
View File
@@ -1,39 +1,46 @@
# syntax=docker/dockerfile:1
#
# radiance as a container image: the engine, its plugins and its tools compiled inside the ROCm
# toolchain image, the host test suite run against that build, and a runtime image built FROM
# SCRATCH that holds the install tree and exactly the shared libraries it loads -- no distribution,
# no package manager, no shell beyond a static busybox.
# radiance as a container image: the engine, plugins and tools built in the ROCm toolchain image,
# the host test suite run against that build, and a FROM scratch runtime image holding the install
# tree and exactly the shared libraries it loads (no distribution, no package manager, only a
# static busybox).
#
# docker/build.sh # the usual way (BuildKit / buildx)
# docker buildx build -t radiance . # the same, by hand
# docker buildx build --build-arg GPU_TARGETS="gfx1200;gfx1201" -t radiance .
#
# Stages:
# ffmpeg FFmpeg built with only the demuxers core/mm/media.cpp admits and the decoders their
# streams need (pictures, video, and audio with swresample); the distribution's build
# brings ~200 packages of encoders, filters and display libraries the engine never calls
# build ROCm dev image + cmake/ninja/g++-14; configures, builds, installs to /stage
# test `ctest -LE gpu` on that build -- everything that does not need a card
# rootfs the install tree stripped, and every library its binaries and plugins load, resolved
# by ldd, copied into one directory and checked from inside a chroot
# runtime FROM scratch + rootfs. This is the image that ships
# ffmpeg FFmpeg with only the demuxers core/mm/media.cpp admits, the decoders their streams
# need (pictures, video, audio with swresample) and the three encoders the images API
# writes (png, mjpeg, libwebp); the distribution's build pulls ~200 unused packages
# llvm ROCm's libLLVM rebuilt from ROCm's llvm-project at the commit the image's clang
# reports, with docker/llvm-vopd-pairing.patch, which makes LLVM 24's device code
# repeatable across builds (cmake/RadAddPlugin.cmake, rad_hip_repeatable)
# build ROCm dev image + cmake/ninja/g++-14; configures, builds and installs to /stage, with
# device code compiled by ROCm's clang from a shadow ROCm tree using the llvm stage's
# libLLVM
# test docker/llvm-check.sh, then the host-only ctest suites
# rootfs the stripped install tree plus every library its binaries and plugins load (resolved
# by ldd), copied into one directory and checked from inside a chroot
# runtime FROM scratch + rootfs; the shipped image
#
# Device code is NOT built with --offload-compress: the engine's AQL backend reads the fat binaries
# itself and refuses a compressed bundle.
# Device code is not built with --offload-compress: the AQL backend reads the fat binaries itself
# and refuses a compressed bundle.
#
# GPU_TARGETS must be named. A bare-metal ./build.sh asks the machine which cards it has; a build
# container has no card to ask, and a build that guessed would emit kernels for hardware nobody
# chose. They are the targets the shipped KERNEL LIBRARIES are compiled for -- libr4d serves RDNA4
# only and drops every architecture outside gfx12 on its own. The engine itself runs on every AMD
# GPU family whatever is named (its own kernels carry the generic family targets), so a kernel
# library for another card is added to the image by mounting it on the search path:
# GPU_TARGETS must be named: a build container has no card to detect, unlike a bare-metal
# ./build.sh. They are the targets of the shipped kernel libraries, each of which keeps only its own
# family: libr4d takes gfx1201 (RDNA4), libr3d gfx11-generic (every RDNA3 chip) and gfx1151, and
# libhalo gfx1151 (Strix Halo), where the loader prefers it over libr3d. On any one card the other
# libraries decline or are left out, so the default image serves all three. The engine's own
# kernels carry the generic family targets and run on every AMD GPU family, so a kernel library for
# another card is added by mounting it on the search path:
# docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance
#
# The ROCm userspace in the image must be one the host's amdgpu kernel driver supports. It is
# pinned to the version the serving host runs; move both together.
# The image's ROCm userspace must be supported by the host's amdgpu kernel driver; it is pinned to
# the serving host's version, so move both together. From ROCm 10 on, the dev image is published
# only as the -full tag.
ARG ROCM_VERSION=7.2.4
ARG ROCM_VERSION=10.1.0-full
ARG UBUNTU_VERSION=24.04
ARG FFMPEG_VERSION=8.1.3
ARG FFMPEG_SHA256=7138d28c96d9d3e3af4ee3d8cad72741f8ffb40da90c1112235dea3ecd3178a3
@@ -46,13 +53,17 @@ ARG JOBS=
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
build-essential nasm pkg-config ca-certificates curl xz-utils zlib1g-dev libdav1d-dev \
libwebp-dev libopenh264-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /tmp
# The demuxers are media.cpp's kFormats whitelist, the only containers it opens. The decoders are
# what those containers carry: still images, H.264 and HEVC (MP4, MOV, HEIF), VP8 and VP9 (WebM,
# WebP), AV1 through dav1d (WebM, MP4, AVIF), MPEG-1/2/4, Theora and the FLV/H.263 family. JPEG XL
# is recognised and refused by name: its only decoder is libjxl's. No protocols: media.cpp reads
# from memory through its own I/O context.
# Demuxers: media.cpp's kFormats whitelist. Decoders: what those containers carry -- still
# images, H.264 and HEVC (MP4, MOV, HEIF), VP8 and VP9 (WebM, WebP), AV1 through dav1d (WebM, MP4,
# AVIF), MPEG-1/2/4, Theora and the FLV/H.263 family. JPEG XL is recognised and refused by name
# (its only decoder is libjxl's). Encoders: the image output formats of media.cpp encode_image
# (png, jpeg as mjpeg, webp through libwebp), and a generated video's MP4 (core/mm/mp4.cpp): H.264
# through libopenh264 (BSD-licensed, so the build stays LGPL) and FFmpeg's own AAC, in the mp4
# muxer. No protocols: media.cpp and mp4.cpp read and write memory through their own I/O
# contexts.
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
curl -fsSL "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" -o ffmpeg.tar.xz \
&& echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \
@@ -60,9 +71,10 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
&& ./configure --prefix=/opt/ffmpeg --enable-shared --disable-static --disable-debug \
--disable-programs --disable-doc --disable-network --disable-autodetect --disable-everything \
--disable-avdevice --disable-avfilter --enable-swresample \
--enable-zlib --enable-libdav1d \
--enable-zlib --enable-libdav1d --enable-libwebp \
--enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe,wav,w64,mp3,flac,aac,aiff \
--enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_alaw,pcm_mulaw,mp3float,mp2float,flac,vorbis,opus,aac \
--enable-encoder=png,mjpeg,libwebp,libopenh264,aac --enable-muxer=mp4 --enable-libopenh264 \
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl,mpegaudio,flac,aac,vorbis,opus \
&& make -j"${JOBS:-$(nproc)}" \
&& make install \
@@ -73,41 +85,120 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
&& echo "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz, sha256 ${FFMPEG_SHA256}" \
> /opt/ffmpeg/share/doc/ffmpeg/SOURCE
# ------------------------------------------------------------------------------------------ build
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build
ARG GPU_TARGETS=gfx1201
# Parallel compile jobs. Empty means one per core; a device-kernel translation unit takes 2-3 GB
# of RAM under hipcc, so a host that is also serving wants a lower number.
# ------------------------------------------------------------------------------------------- llvm
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS llvm
ARG JOBS=
# g++-14 rather than the image's default 13: its libstdc++ is the one hipcc then compiles the
# device-side translation units against too, and it is the runtime image's libstdc++ as well.
# gawk because tools/ops_doc_check.sh uses gensub, which Ubuntu's default awk (mawk) lacks.
# libdav1d7 is the runtime half of the AV1 decoder the ffmpeg stage linked; busybox-static goes
# into the runtime image.
# clang, lld and the offload tools all load lib/llvm/lib/libLLVM.so, so this stage rebuilds only
# that file: ROCm's llvm-project at exactly the commit `clang --version` names (the stage stops if
# clang names none or the patch does not apply), configured as ROCm's
# lib/cmake/llvm/LLVMConfig.cmake records -- Release without assertions, AMDGPU;SPIRV;X86, every
# component in the dylib, no RTTI or exceptions, zlib and zstd from rocm_sysdeps -- and compiled
# by ROCm's own clang and lld. With VOPD pairing off it produces
# ROCm's code byte for byte; docker/llvm-check.sh holds the build stage to that. The fetch is
# sparse and depth one: llvm/ plus the cmake/, libc/ and third-party/ directories configure reads,
# without tests or documentation.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
cmake ninja-build pkg-config g++-14 gawk libdav1d7 busybox-static \
git cmake ninja-build ca-certificates \
&& rm -rf /var/lib/apt/lists/*
COPY docker/llvm-vopd-pairing.patch /tmp/
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
set -e; L=/opt/rocm/lib/llvm; S=/opt/rocm/lib/rocm_sysdeps; \
rev=$($L/bin/clang --version | sed -n 's|.*ROCm/llvm-project.git \([0-9a-f]\{40\}\).*|\1|p'); \
[ -n "$rev" ] || { echo "llvm: no ROCm/llvm-project commit in: $($L/bin/clang --version | head -1)" >&2; exit 1; }; \
git init -q /llvm-project; cd /llvm-project; \
git remote add origin https://github.com/ROCm/llvm-project.git; \
git sparse-checkout set --no-cone '/*' '!/*/' /cmake/ /libc/ /llvm/ /third-party/ \
'!/llvm/test/' '!/llvm/unittests/' '!/llvm/docs/' '!/llvm/benchmarks/'; \
git fetch -q --depth 1 --filter=blob:none origin "$rev"; \
git checkout -q FETCH_HEAD; \
git apply /tmp/llvm-vopd-pairing.patch; \
cmake -G Ninja -S llvm -B /build-llvm -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=OFF \
-DLLVM_TARGETS_TO_BUILD="AMDGPU;SPIRV;X86" -DLLVM_BUILD_LLVM_DYLIB=ON -DLLVM_LINK_LLVM_DYLIB=ON \
-DLLVM_DYLIB_COMPONENTS=all -DLLVM_ENABLE_RTTI=OFF -DLLVM_ENABLE_EH=OFF -DLLVM_ENABLE_FFI=OFF \
-DLLVM_ENABLE_LIBXML2=OFF -DLLVM_ENABLE_LIBEDIT=OFF -DLLVM_ENABLE_CURL=OFF \
-DLLVM_ENABLE_HTTPLIB=OFF -DLLVM_ENABLE_TELEMETRY=ON -DLLVM_ENABLE_PLUGINS=ON \
-DLLVM_ENABLE_LIBPFM=OFF \
-DLLVM_ENABLE_ZLIB=FORCE_ON -DZLIB_INCLUDE_DIR=$S/include -DZLIB_LIBRARY=$S/lib/librocm_sysdeps_z.so.1 \
-DLLVM_ENABLE_ZSTD=FORCE_ON -Dzstd_INCLUDE_DIR=$S/include -Dzstd_LIBRARY=$S/lib/librocm_sysdeps_zstd.so.1 \
-DLLVM_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_BENCHMARKS=OFF -DLLVM_INCLUDE_EXAMPLES=OFF \
-DLLVM_INCLUDE_DOCS=OFF -DLLVM_BUILD_TOOLS=OFF -DLLVM_USE_LINKER=lld -DLLVM_PARALLEL_LINK_JOBS=2 \
-DCMAKE_C_COMPILER=$L/bin/clang -DCMAKE_CXX_COMPILER=$L/bin/clang++ > /tmp/llvm-configure.log 2>&1 \
|| { tail -40 /tmp/llvm-configure.log >&2; exit 1; }; \
ninja -C /build-llvm ${JOBS:+-j${JOBS}} LLVM > /tmp/llvm-build.log 2>&1 \
|| { grep -m20 -B2 -A8 'error' /tmp/llvm-build.log >&2; exit 1; }; \
so=$(basename $(readlink -f $L/lib/libLLVM.so)); \
mkdir -p /out; cp /build-llvm/lib/$so /out/; \
rm -rf /build-llvm /llvm-project
# ------------------------------------------------------------------------------------------ build
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build
ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
# Parallel compile jobs; empty means one per core. A device-kernel translation unit takes 2-3 GB
# of RAM under hipcc, so lower it on a host that is also serving.
ARG JOBS=
# g++-14 rather than the default 13: hipcc compiles device-side translation units against its
# libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which
# mawk lacks. libdav1d7, libwebp7 and libopenh264-7 are the runtime libraries of the ffmpeg stage's
# AV1 decoder, WebP encoder and H.264 encoder; busybox-static goes into the runtime image.
# libopenblas-dev: libquant's GPTQ factorises its Hessians through LAPACK where it finds OpenBLAS
# (libquant/CMakeLists.txt); without it rad-convert's gptq rule runs single-threaded loops.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \
libopenblas-dev \
&& rm -rf /var/lib/apt/lists/*
COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf && ldconfig
# Register ROCm's library directory beside FFmpeg's: the ROCm 10 images register none, and the
# rootfs stage resolves the installed binaries' libraries with ldd.
RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf \
&& echo /opt/rocm/lib > /etc/ld.so.conf.d/rocm.conf && ldconfig
ENV ROCM_PATH=/opt/rocm HIP_PATH=/opt/rocm CC=gcc-14 CXX=g++-14 \
PKG_CONFIG_PATH=/opt/ffmpeg/lib/pkgconfig
# The HIP compiler: ROCm's clang loading the llvm stage's libLLVM. ROCm's tools find libraries
# through RPATHs relative to themselves ($ORIGIN/../lib for libLLVM, which LD_LIBRARY_PATH cannot
# override, plus $ORIGIN/../../rocm_sysdeps/lib and $ORIGIN/../../../lib), so the compiler runs
# from /opt/rocm-repeatable, a shadow of the whole ROCm tree at the same depth. Every entry links
# back into /opt/rocm except lib/llvm/bin (real copies of the executables) and the rebuilt
# libLLVM. Only compiling uses it. The build passes --rocm-path=/opt/rocm so headers and device
# libraries are ROCm's and linked plugins record /opt/rocm/lib. Without it clang treats its own
# tree as ROCm, and the HIP runtime would reach comgr through the rebuilt libLLVM, which lacks the
# libstdc++ symbols ROCm's GCC-built one re-exports for comgr. The rootfs stage refuses any
# library resolved through the shadow tree.
COPY --from=llvm /out/ /tmp/llvm-out/
RUN set -e; R=/opt/rocm; D=/opt/rocm-repeatable; L=lib/llvm; \
so=$(basename $(readlink -f $R/$L/lib/libLLVM.so)); \
[ -f /tmp/llvm-out/$so ] || { echo "the llvm stage built no $so" >&2; exit 1; }; \
mkdir -p $D/$L/lib; \
for e in $R/*; do n=${e##*/}; [ $n = lib ] || ln -s $e $D/$n; done; \
for e in $R/lib/*; do n=${e##*/}; [ $n = llvm ] || ln -s $e $D/lib/$n; done; \
for e in $R/$L/*; do n=${e##*/}; [ $n = bin ] || [ $n = lib ] || ln -s $e $D/$L/$n; done; \
cp -a $R/$L/bin $D/$L/; \
for e in $R/$L/lib/*; do n=${e##*/}; \
if [ $n = $so ]; then mv /tmp/llvm-out/$so $D/$L/lib/; \
elif [ -L $e ] && [ "$(readlink $e)" = $so ]; then ln -s $so $D/$L/lib/$n; \
else ln -s $e $D/$L/lib/$n; fi; \
done; \
rm -rf /tmp/llvm-out
WORKDIR /src
COPY . .
# The install prefix is fixed at configure time because the default $RADIANCE_HOME is compiled in
# as <prefix>/share/radiance; DESTDIR then stages the tree without moving that default.
# oom_score_adj 1000: on a host that is also serving, the compiler is what the OOM killer takes,
# not the server.
# The prefix is fixed at configure time because the default $RADIANCE_HOME is compiled in as
# <prefix>/share/radiance; DESTDIR stages the tree without moving that default.
# oom_score_adj 1000: on a host that is also serving, the OOM killer takes the compiler first.
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
cmake -S . -B /build -G Ninja \
-DCMAKE_INSTALL_PREFIX=/opt/radiance \
-DRAD_WITH_HIP=ON -DRAD_WITH_FFMPEG=ON \
"-DRAD_GPU_TARGETS=${GPU_TARGETS}" \
-DCMAKE_HIP_COMPILER=/opt/rocm-repeatable/lib/llvm/bin/clang++ -DCMAKE_HIP_COMPILER_ROCM_ROOT=/opt/rocm \
-DCMAKE_HIP_FLAGS=--rocm-path=/opt/rocm \
-DRAD_HIP_VOPD_REPEATABLE=ON \
&& cmake --build /build ${JOBS:+-j${JOBS}} \
&& DESTDIR=/stage cmake --install /build \
&& mkdir -p /stage/opt/radiance/share/radiance/recipes \
@@ -115,57 +206,87 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
# ------------------------------------------------------------------------------------------- test
FROM build AS test
# Host-only: a build container has no /dev/kfd. The `gpu`-labelled suites (mem_test,
ARG JOBS=
# Tests at a time when it should differ from JOBS (below).
ARG TEST_JOBS=
# A factor on every test's CPU budget (RAD_TEST_CPU_BUDGET_SCALE, tests/rad_test.h), for a host
# slower per thread than the one the budgets were set on: a VM on an EPYC 7302 spends 4.6x the
# quoted CPU time on tokenizer_test's reference pass.
ARG TEST_CPU_BUDGET_SCALE=
# A ctest -E regex of entries to leave out, for a host where a timing assertion does not hold:
# tokenizer_perf_test's one-word ratio reads 10-12 against its 9 on a Zen 2 VM with 512 KiB of L2,
# where the sandbox leaves it CPU time rather than instructions to count.
ARG TEST_EXCLUDE=
# Host-only: a build container has no /dev/kfd. The `gpu`-labelled tests (the *_card entries,
# r4d_selftest, kbench) run against a card from this stage:
# docker buildx build --target build -t radiance-build . && docker run --rm \
# --device /dev/kfd --device /dev/dri --security-opt seccomp=unconfined radiance-build \
# ctest --test-dir /build -L gpu --output-on-failure
# One test at a time: several suites assert that a cost scales linearly, a ratio of two timings
# that tests running beside them would distort. The build sandbox forbids io_uring, so avx_check
# reports its file-backed gather case as skipped here. The `oot` suite -- every shipped plugin
# rebuilt against the installed package, libr4d included -- is the development tree's to run
# (tests/oot_plugins.sh): it re-does this stage's whole compile.
# Tests run TEST_JOBS at a time, else JOBS (default one per two hardware threads, about one per
# core on an SMT machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do
# not share a core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The
# build sandbox forbids io_uring, so avx_check skips its file-backed gather case, and
# perf_event_open, so the tests that bound work count CPU time rather than instructions
# (tests/work_counter.h). The `oot` suite (every shipped plugin rebuilt against the installed
# package) repeats this stage's whole compile, so it runs from the development tree instead
# (tests/oot_plugins.sh). The `parity` entry (halo_parity: libhalo's tables against libr4d's) is
# left out until libhalo has ported the ops libr4d added after it (the test names each one).
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
ctest --test-dir /build -LE 'gpu|oot' --output-on-failure \
bash /src/docker/llvm-check.sh /build \
&& RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \
ctest --test-dir /build -LE 'gpu|oot|parity' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \
-j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \
&& touch /build/host-tests-passed
# ----------------------------------------------------------------------------------------- rootfs
FROM build AS rootfs
# hfget.sh (fetches the Hugging Face repo a --model id names) needs curl, jq and a CA bundle.
# Installed here rather than in `build` so changing them does not recompile the engine.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
curl jq ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# The marker makes this stage, and so the shipped image, depend on the test stage.
COPY --from=test /build/host-tests-passed /rootfs/opt/radiance/share/radiance/.host-tests-passed
# Every library the binaries and plugins load, plus comgr, which the HIP runtime opens at run time
# and cannot initialise a device without, goes into one directory the dynamic loader searches by
# default: no ld.so.cache, no LD_LIBRARY_PATH. libdrm_amdgpu names the card from amdgpu.ids. A
# static busybox provides the health check's wget and a shell for `docker exec`. docker/licenses.sh
# traces each of those files to its package and records its license and source in
# /usr/share/doc/THIRD-PARTY. Then every ELF file is resolved from inside the tree, so nothing can
# depend on a library the image lacks.
# Every library the binaries and plugins load, plus comgr (opened by the HIP runtime at run time
# and required to initialise a device), goes into one directory the loader searches by default:
# no ld.so.cache, no LD_LIBRARY_PATH. ROCm's libdrm_amdgpu has the card name table compiled in, so
# no amdgpu.ids is copied. A static busybox provides the health check's wget and a shell for
# `docker exec`; curl, jq and the CA bundle are for hfget.sh (the bundle is ca-certificates'
# Mozilla set, named by that directory in the license list). docker/licenses.sh records each
# file's package, license and source in /usr/share/doc/THIRD-PARTY. Finally every ELF file is
# resolved from inside the tree, so none depends on a library the image lacks.
RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \
mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/usr/share/libdrm $R/data $R/tmp; \
mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/etc/ssl/certs $R/data $R/tmp; \
chmod 1777 $R/tmp; \
cp -a /stage/opt/radiance $R/opt/; \
elves=$(find $R/opt/radiance -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print); \
strip --strip-unneeded $elves; \
libs=$(for f in $elves /opt/rocm/lib/libamd_comgr.so.3; do ldd "$f"; done \
libs=$(for f in $elves /usr/bin/curl /usr/bin/jq /opt/rocm/lib/libamd_comgr.so.3; do ldd "$f"; done \
| awk '/=> \//{print $3} /^\t\/lib64\//{print $1}' | sort -u); \
if echo "$libs" | grep /opt/rocm-repeatable/; then \
echo "these resolve through the compiler's shadow ROCm tree, not /opt/rocm" >&2; exit 1; fi; \
for lib in $libs; do \
case "$lib" in */ld-linux-x86-64.so.2) cp -L "$lib" $R/lib64/ ;; *) cp -L "$lib" $L/ ;; esac; \
done; \
cp -L /opt/rocm/lib/libamd_comgr.so.3 $L/; \
cp /usr/share/libdrm/amdgpu.ids $R/usr/share/libdrm/; \
cp /bin/busybox $R/usr/bin/busybox; ln -s /usr/bin/busybox $R/bin/sh; \
sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 \
/usr/share/libdrm/amdgpu.ids /bin/busybox; \
for f in $(cd $R && find opt/radiance usr/lib -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print); do \
cp /usr/bin/curl /usr/bin/jq $R/usr/bin/; \
cp /etc/ssl/certs/ca-certificates.crt $R/etc/ssl/certs/; \
sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 /bin/busybox \
/usr/bin/curl /usr/bin/jq /usr/share/ca-certificates/mozilla; \
for f in $(cd $R && find opt/radiance usr/lib -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print) \
usr/bin/curl usr/bin/jq; do \
out=$(chroot $R /lib64/ld-linux-x86-64.so.2 --list "/$f" 2>&1) || { echo "$f: $out" >&2; exit 1; }; \
if echo "$out" | grep -q 'not found'; then echo "$f: $out" >&2; exit 1; fi; \
done; \
chroot $R /opt/radiance/bin/radiance --help > /dev/null; \
chroot $R /usr/bin/curl --version > /dev/null; chroot $R /usr/bin/jq --version > /dev/null; \
du -sh $R $L $R/opt/radiance
# ---------------------------------------------------------------------------------------- runtime
FROM scratch AS runtime
ARG GPU_TARGETS=gfx1201
ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
ARG VERSION=dev
ARG REVISION=unknown
@@ -178,8 +299,8 @@ LABEL org.opencontainers.image.title="radiance" \
COPY --from=rootfs /rootfs/ /
# A single allocation may take the whole card and the HIP heap may grow to all of VRAM; the
# runtime's defaults cap both below what the placement plan hands out.
# Let one allocation take the whole card and the HIP heap grow to all of VRAM; the runtime's
# defaults cap both below what the placement plan hands out.
ENV PATH=/opt/radiance/bin:/usr/bin:/bin \
GPU_MAX_ALLOC_PERCENT=100 \
GPU_MAX_HEAP_SIZE=100
+241 -16
View File
@@ -1,21 +1,194 @@
radiance
Copyright 2026 Deadcode and the radiance contributors
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14 (the
MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake (the
MXFP4 decode and prefill GEMMs, the MXFP4 linear and the DFlash2 drafter's MXFP4 linears, stop
strings after the reasoning block, and the draft refill on a prefix hit), goodman-b (four-rank
tensor parallelism for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the
fused four-rank writes, the n-gram table in RAM, the four-class expert split, the Grafana
dashboard, the routed GEMM's decode loads and run search, the gated residual's prefill read form
and row groups, the fused router launch, the adaptive draft window, the MoE prefill forms and the
sorted operand's decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000
(the n-gram gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor
parallelism, serving any world size from the shipped container, the request log, an uneven world's
per-rank KV and weights split, --rope-scaling, the model entry's context length, root and
capabilities, /props, the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of
the three-rank lossy-wire crash, and cardclock.py), hazyumps (static YaRN for the Qwen rotary
paths) and redxherring (--model taking a Hugging Face repo id).
Written by Deadcode, with contributions from:
- tcclaviger: the N-rank all-reduce kernels
- ggz14: the MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards
- slydlake: the MXFP4 decode and prefill GEMMs, the MXFP4 linear and the DFlash2 drafter's MXFP4
linears, stop strings after the reasoning block, and the draft refill on a prefix hit
- goodman-b: four-rank tensor parallelism for Qwen3.8-Flash-Next, the four-rank collectives ending
the link hold themselves, their selftest cases and the TP4 lever map
- keptn42: the four-rank all-reduce served in place, the fused four-rank writes, the n-gram table in
RAM, the four-class expert split, the Grafana dashboard, the routed GEMM's decode loads and run
search, the gated residual's prefill read form and row groups, the fused router launch, the
adaptive draft window, the MoE prefill forms, the sorted operand's decode kernel, two K blocks a
pass for up to 80 routed rows, --prefill-span, the towers' lookup tables counted once, and for
Gemma 4 its assistant head as a drafter that reads the trunk's cache, bf16 checkpoints, the fused
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, the
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared
layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio
encoder, its i8a8 linears and its KV heads replicated over ranks, 4-bit weights at decode heights
through w4a16_asym, the Ornith-1.5-122B compose files, the Gemma 4 31B's asymmetric int5
linears (w5a8i8 and w5a16), the junctions at quant_act_i8g's grid (rmsnorm_quant_i8g,
gelu_mul_quant_i8g and ar_rmsnorm_quant_i8g) with the prefill overlap on the i8a8, a4 and w5
grids, the 31B's i8g, heretic-ara-i8g and w5 compose files, and Ling-3.0-flash (bailing_hybrid:
KDA, dense latent attention, group-limited sigmoid routing, the clipped SwiGLU and its MTP layer as
a serial drafter) with mla_attn_paged, its w4a8 recipes and compose files, possessive quantifiers
in the tokenizer's patterns, the Grafana dashboard's first screen, and Gemma 4 12B (its picture
and audio embedders, a picture's placeholders read both ways on the sliding layers, the windowed
attention at head_dim 512, suppress_tokens) with its compose files, and
NVIDIA-Nemotron-3.5-Bolt-74B-A9B (nemotronh: Mamba-2 with ssd_update and ple_conv_bias, the
latent MoE's ungated relu^2 experts, NoPE attention with KV heads replicated over ranks, the
paged attention at head_dim 128 and gqa 16, attention sinks) with NVIDIA's LiLiCorr drafter
(RadBatch::anchor_rows, the candidate correlator), the C-RADIO vision tower and video tubelets,
calibration in layer ranges, its recipes and compose files, and the kernel report's fixture
- mechkbfan: the token embedding in the pinned host pool
- Code000: the n-gram gather on the card and the MTP head's history-pass skip, and the MTP draft
coupling with its cooperative verify (--draft-coupling), the W4A8 prefill's tail scale read, the
ISA instruments' VGPR granule, back-edge count and fail-closed parse, scored steps
(rad_declare_scores, RadBatch::score_only), the gated prefill fold, the short-prompt split row and
the rows forms of rmsnorm and rope, LFM2's 8-bit trunk with the d1-3B recipe, the file tier's
routed reads with their own router's counts and its deposit wait, the stop-string hold-back, and
the sampler's planes by the step's token bound, its n-gram ban beside a drafter and no candidate
cut over a top-1 row, and --prefill-interleave auto[:SHARE], sized from measured step times and
served by default
- baKon: three-rank tensor parallelism, serving any world size from the shipped container, the
request log, an uneven world's per-rank KV and weights split, --rope-scaling, the model entry's
context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8
wire, the diagnosis of the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, curl,
jq and a CA bundle in the image with hfget.sh under its busybox, rad-export, --prefill-interleave,
runtime LoRA adapters served beside the base model and picked per request, and the prefix cache's
reserved snapshots held until their save lands, --expert-stats, imatrix entries in llama.cpp's
spelling, typed tool-call argument tags, a chat template refused at load when it cannot render,
rad-chatparse --request, a draft head's routed experts in host memory (--draft-expert-placement
host) and decode-hot residency (--expert-profile, --expert-pin-top), prefix hits over KV groups of
different block sizes and a hybrid's window in the checkpoint slot, --prefix-resume exact,
DeepSeek-V4.1-Flash's conversion from its release (the Engram tables, the fused imatrix, the
UD-IQ1_S recipe and rad-convert --chat-template), a preempted prefill admitted only with its
whole recompute and the running sequences' next blocks free and the bound on its wait
(--preempt-wait-ms), prompt lookup alone (--spec-ngram) with each sequence's n-gram index and
the gate that verifies a proposal only when it pays, and DeepSeek-V4.1's reply format with its
DSML tool calls, and expert_stats_report.py
- hazyumps: static YaRN for the Qwen rotary paths
- malic: ParoQuant, with its MXFP4, int5 and int4 checkpoints imported and served, the Givens
rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and 4-bit
asymmetric GEMMs, and the int8 tiled GEMMs loading the weight a slab ahead
- Perire: Gemma 4 26B-A4B with z-lab's DFlash drafter -- its plugin, its kernels in libr4d (the
windowed paged attention, pair_argmax, the fused sandwich joins and expert_scale) and the host
emulator that tests them, the prefill split into two slices with their all-reduces beside the
compute, and the vocabulary-sharded draft head; Gemma 4 31B on four cards (its all-reduces fused
with the junctions, overlapped with the compute and sent compressed, chained launches with block
drafters), the embedding scale rounded as Hugging Face rounds it, block drafters' drafts
accepted on the card, z-lab's DFlash drafter drafting on after a prefix-cache hit and the 31B's
GPTQ calibration tap, and for speculation the MTP head's first draft read up to where it sits, no
step queued behind one that ends its requests, a step's tokens streamed before the drafter's
passes end, a block drafter's proposals verified as a tree, the 31B's block-16 DFlash2 tree with
its short block under load, a block drafter's window carried in the window snapshot, and window
snapshots from short prompts
- redxherring: --model taking a Hugging Face repo id
- Smellyyyy: the idea behind --prefill-interleave
- gearwave00001: /v1/messages as Claude Code sends it
- devmilan: the NVFP4 and FP8 compressed-tensors imports
- sfjes: Gemma 4 31B dense -- its plugin, its two attention classes and their kernels, and prefix
reuse that leaves a windowed group alone -- and --host-headroom-mib
- zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg
PR 50, Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime, and Fish Audio drama-3 -- its
plugin, its codec encoder and decoder, voice cloning from reference clips, and the torch.save
reader
- mici81: Gemma 3 dense (TranslateGemma 27B) -- its plugin, the windowed h128 attention, the
sandwich junction's all-reduce and its DFlash2 drafter -- the fp8_v4 and k6_v4 KV caches, GPTQ's
factorisations through LAPACK and a column-split linear's Hessian from per-rank parts,
R4D_AR_MAX_BLOCKS for two engines on one set of cards, added tokens decoded as HuggingFace decodes
them, the MXFP4 GEMM rows for one to 64 rows and the tiled prefill GEMM's TN=4 form, the fp8 and
int8 heads read once up to 128 rows, the pipelined prefill of one sequence on a second lane, Gemma
3's junctions under a lossy wire, the block drafter's short block (--draft-short-from), the f16
delta-net state cache, the two-rank all-reduce checking a peer's push has landed, the MXFP4 decode
gate_up folded with its activation and fp8 quantiser, the head-256 split-KV decode attention,
weight reads beside the decode all-reduces (--weight-prefetch), the head-256 prefill attention's
KV split for small launches, the GUIDE's two engines on one pair, DFlash2's coupled acceptance at
T > 0, the prefix cache's snapshot at a head prompts share, tip-only's snapshot a drafter window
below the tip, Gemma 3's fused all-reduce junction on the lossy wire, the three-wave verify's
split by depth, the delta net's out-projection read beside its decode recurrent update, the MXFP4
feed-forward's gated fold up to 16 rows, the three-wave verify floor bounded by the batch's
workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6
paged prefill, the preempted-prefill gate past a KV group that holds no blocks, and the norms'
lane sum issuing its reads eight at a time, chained forms for every kernel of
Qwen3.8-Flash-Next's decode step with hc_read's forms G, S and B3, and a preempted request
publishing its prefix with an overdue one keeping its place
- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the
out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8
linears' operands directly
- davetha: JSON Schema patterns read unanchored, with their shorthand classes and escapes
- Nunze: the eight-rank all-reduce's bands, weighted shards from the PCIe links and pieces, the
sampler's candidate width at eight ranks, the image test stage's parallelism, budgets and
exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose
name the opener opens, GLM-5.3-Flash's vision tower and processor, its decode at a few rows and
its DSA indexer split over the ranks, a host-tier restore that makes room as pressure does, KV
groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA
row form (--tp-attn-split rows), DELETE /sessions, the dispatch stamps of a played pass with
stampgaps.py, one n-gram table for engines on separate cards (--ngram-placement ram=DIR), GGUF
Q8_0, Q4_K and Q6_K tensors imported as their planes, the dense integer rows at the group they
compute, and the GDN conv kernels on an f32 weight
- John McDonough: GLM-5.3-Flash -- its plugin, its blocks (mHC streams, KDA, the DSA indexer and
sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their
reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the
one-sequence KV floor over the live plan, and prefill staging paid by expert residency
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and
the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped
rotation, the dashboard's history line, session extremes, card-count changes and Requests-header
JSON export, with the page's JavaScript driven by tests/js
- C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual
projection, KV streaming for a context bigger than VRAM (--kv-resident), and the dashboard's
request history, KV streaming traffic and one-unit KV meter
- J-Nova: Unlimited-OCR, and Sage-A1.5 with its vision tower and its DFlash2 drafter
- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8)
- lortht: Krea 2's rebalance of the text taps and its presets, MiniMax-H3's modulation rows, and
keyframes carried through a latent upscale
- Quackster: cards with a small PCI BAR, their kernel arguments kept in host memory
- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix
- gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its
BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode
(the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds),
and the head-256 prefill softmax rescaled by row rather than by wave, Spark 2.5 (spark25: bf16 and
rotated-int8 IQ8R checkpoints, tensor parallelism with exact collectives, reasoning and tagged
tool calls) with its DSpark drafter (exact attention and Markov walk ops), the prefill split keyed
by live KV bounds, and --gpu-memory-mib
- launch80_assets: tuning collectives as the exchange they serve at the served configuration, the
per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch
- hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2
drafter -- and the ParoQuant M2XFP4 import
- steki: Gemma 4 E2B's per-layer MLP width and the bf16 descriptor for Google's E2B/E4B
directories, nomic-embed-text-v2-moe (the nomicbert plugin), its config key aliases and
RAD_MAP_TRANSPOSE honouring src_index, an f32 source narrowed to a bf16 declaration at load, and
the snapshot store's floor ahead of --host-headroom-mib
- griffin-warrior: the kernel report's consistency checks and coverage header, collective selftest
cases skipped without a peer path, the build's media capability in the diagnostics, and the
GUIDE's ROCm SDK and ffmpeg notes
- nickreese: GBNF bounded-repetition chains shared across identical operands
- Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid
wait trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS
and its gated three-tile form at 8 waves
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library, and its wave-matrix rewrite: the GEMMs
retiled to 16x128 blocks, the grouped MoE GEMMs, the norms and quantisers, and the QSA and MoE
router rows, its MoE GEMMs at w4a8 and w4a4 with dequant_w4, row_topk_merge, ngram_ids and
the biased and short GEMMs, and w4a4's reference implementation
- fl0l0u: every request entry point bounded, gated and sanitised (JSON parses bounded in depth,
errors safe on invalid UTF-8, control bytes kept off the log, the dashboard's CSP, cross-origin
browsers refused on the loopback-only routes, method-scoped API-key exemptions), prompt ids that
name no vocabulary row refused, and the telemetry the HTTP thread reads made atomic
- Brandon Bertelsen: Cloudflare's clef and clef-flash with their joint schema head on the card
(seg_softmax_pool, a request's words for the plugin), Convai Innovations' Laya decision models,
Mica on /v1/systemone, and Metaspace prepending only to text not already starting with its
replacement
- Gaspa79: NVIDIA's Nemotron 3.5 Embed 1B and 8B -- the nemotron35_embed plugin, its Pixtral
tower and their CPU path -- and Nemotron 3.5 Rerank 8B on /rerank, with its BF16 masked mean
(seg_mean_bf16_sum)
- overchop: the file tier for large MoEs -- routing-aware reads of only the routed experts, the
hot VRAM cache with its deposits and copyless relabels, and GLM-5.3-Flash's experts read
file-direct under expert parallelism -- the stall watch counting drive reads as progress, and
the DMA lane's lists fenced so a stalled read pointer no longer fills its ring
- pokesjw: the n-gram reader refilling its reads as they land, and a decode gather waiting on the
other rank's read of a row instead of reading it again
- AnimusNull: GLM-5.3-Flash on four cards -- its experts split by width, the small-M MXFP4 expert
form at the TP4 slices, the indexer's take-all steps -- its E4M3 latent cache (mla_attn's fp8kv
rows), and the DMA lane's room check over a reused fence slot
- neuromanMD: libr3d's MXFP4 GEMM leaving VRAM exponent planes unscanned from the host, and its
branch-free e4m3_to_f32
- everplays: the paged attention at seven queries a KV head, head_dim 128 (Nanbeige4.3-33B)
- Kezi: the decode tile arms of the int4 and int5 x int8 GEMM
- dschmitz: the two-rank fused writes' host-mailbox twins taking their chained forms
- eniga: the diagnosis of GLM-5.3-Flash's template refused for tools (jinja's unique filter)
This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each.
@@ -24,5 +197,57 @@ license text is in the file named beside each.
vendor/llama/, and the code lifted or ported from it: core/sample/gbnf.*, the
host samplers in core/sample/host_ref.*, the tokenisers in core/text/, and
libquant/lq_ggml_*
nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT
yyjson Copyright (c) 2020 YaoYuan vendor/yyjson/LICENSE
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
The dashboard's page, compiled into the server from core/server/dashboard_page.h, carries
third-party software built into it: React, Base UI and Floating UI, uPlot, shadcn/ui's components
and helpers, Tailwind CSS's generated style and tw-animate-css (MIT), class-variance-authority
(Apache-2.0), the Lucide icons (ISC), and the Geist and Geist Mono typefaces (SIL Open Font License
1.1, Copyright the Geist Project Authors). dashboard/THIRD-PARTY-LICENSES.txt lists every package
with its version and license text, as the page's build wrote it.
tests/data/chat/hyv3/chat_template.jinja is Tencent's Hy-Memory-30B-A3B chat template,
copied unchanged from tencent/Hy-Memory-30B-A3B on Hugging Face.
Copyright (C) 2026 Tencent. All rights reserved. Licensed under Apache-2.0 (LICENSE).
Its source and content checksum are recorded in tests/data/chat/hyv3/README.md.
core/server/systemone.cpp carries text from Liquid AI's d1 (prompt.py and api.py in the
LiquidAI/d1-3B repository): the prompt it renders, its question blocks, the option codes and their
fallback codebook and the answer spellings, unchanged, in code rewritten in C++. That text is Liquid
AI, Inc.'s, under the LFM Open License v1.0, whose terms -- including its limit on commercial use --
apply to it; the license is in core/server/LICENSE.lfm.
data/vectors/qwen4exp-control-vector.gguf and data/vectors/qwen4exp-control-vector.json are the
published refusal-direction vector for Qwen3.8-Flash-Next, by Cudecnik
(huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection), copied unchanged. The directions
were measured out of Qwen3.8-Flash-Next's own residual stream, so they are Qwen's, under the Qwen
Community License 1.0 -- data/vectors/LICENSE.qwen-community-1.0.txt -- which carries the file and
every copy of it, including its condition that a Model-as-a-Service or AI-work-assistant business
needs a separate license from Qwen to use it commercially. radiance's Apache-2.0 grant covers the
code that loads and applies the file; it does not cover the file or its directions.
core/server/clef.cpp carries clef's system prompt, and it and arch/common/rad_block_clef.h follow
clef's released joint head (Cloudflare's clef and clef-flash, Hugging Face, Apache-2.0).
core/server/laya.cpp is a rewrite of the laya package (github.com/NandhaKishorM/laya, Apache-2.0).
core/server/mica.cpp carries Mica's system prompt and option labels and is a rewrite of its
contract.py and native.py, and tests/data/golden/mica_contract_cases.json is its
tests/fixtures/contract_cases.json (github.com/akivet/Mica, Apache-2.0).
Nemotron 3.5 input fixtures
--------------------------
tests/data/chat/nemotron35/template.jinja and tokenizer-subset.json come from NVIDIA's
Nemotron-3.5-Embed-8B-BF16 checkpoint, revision
781e779ee4ca9c2d2a4f38321993556baeab49a1:
https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16/tree/781e779ee4ca9c2d2a4f38321993556baeab49a1
The checkpoint's governing license is OpenMDW-1.1, retained in
tests/data/chat/nemotron35/LICENSE. The tokenizer fixture is a subset preserving source token
IDs and the BPE entries needed by the test corpus; it is not the complete serving tokenizer.
tests/data/chat/nemotron35/rerank-template.jinja comes from NVIDIA's
Nemotron-3.5-Rerank-8B-BF16 checkpoint, revision
f88f8d9104726747791283ab156d2fcdb29e90a7:
https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16/tree/f88f8d9104726747791283ab156d2fcdb29e90a7
It is covered by the same retained OpenMDW-1.1 license.
Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+316 -82
View File
@@ -1,30 +1,73 @@
# radiance
An LLM inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks OpenAI's chat, completions
and Responses APIs, Anthropic's Messages API and llama-server's native one, so their clients and
SDKs work unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built
and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
An inference server for AMD GPUs, in C++ and HIP: language models, and image, video, speech and
music generation. Its HTTP API speaks OpenAI's chat, completions, Responses, images, audio and video
APIs, Anthropic's Messages API and llama-server's native one, so their clients and SDKs work
unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this
tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
The bundled device kernels (`libr4d`) target **AMD RDNA4** (`gfx1200`, `gfx1201`). The serve flags
below are for **two 32 GB cards** (Radeon AI PRO R9700). The engine itself starts on any AMD GPU
family; another card needs a kernel library for it. A machine with no GPU builds the host backend,
which runs the full test suite but does not serve these models at any useful speed.
The bundled device kernels target AMD RDNA4 (`libr4d`: `gfx1200`, `gfx1201`), RDNA3 (`libr3d`:
`gfx11xx`) and Strix Halo (`libhalo`: `gfx1151`). The serve settings
below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family;
another card needs a kernel library for it. A machine with no GPU builds the host backend, whose
AVX-512/AVX2 kernels (`libavx`) serve every model here: the small ones (EmbeddingGemma 2,
Qwen3-ASR, the 0.8B-3B models) at interactive speed on a desktop CPU, the 27B and larger far more
slowly than a card.
If you wish to support the developement of the radiance engine you can do so [here](https://patreon.com/StillDeadCode?utm_medium=unknown&utm_source=join_link&utm_campaign=creatorshare_creator&utm_content=copyLink)
To support the development of radiance: [Patreon](https://patreon.com/StillDeadCode).
## Models
| model | container | get it | compose file |
| model | container | get it | fleet file |
|---|---|---|---|
| Qwen3.8-Flash-Next: 4-bit experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-fp8-iq4r-moe.rad` (114 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe) | `flashnext.yaml` |
| Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` |
| Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` |
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` |
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` |
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
| Qwen3.8-Flash-Next: IQR-V4 experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-iqr-v4.rad` (113 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-iqr-v4) | `tp1.yaml`, `tp2.yaml` |
| Qwen3.8-27B IQ8R (rotated int8), DFlash2 drafter, vision | `qwen3.8-27b-iq8r-dflash.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iq8r-dflash) | `tp2.yaml` |
| Qwen3.8-27B IQR-V4, 2.5 to 8 bits a weight ([docs/IQR.md](docs/IQR.md)), DFlash2 drafter, vision | `qwen3.8-27b-iq2r-v4.rad` .. `qwen3.8-27b-iq8r-v4.rad` (10 to 28 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4) | `tp1.yaml` (IQ4R-L) |
| Qwen3.6-35B-A3B IQ8R, MTP | `qwen3.6-35b-a3b-iq8r.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-iq8r) | — |
| MiniCPM5-2B IQ8R, DSpark drafter | `minicpm5-2b-iq8r.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r) | `tp1.yaml`, `tp2.yaml` |
| MiniCPM5-2B bf16 (served without its drafter) | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | — |
| Spark X2.6 4B bf16: thinking and tool calls, one to four cards | `spark-x2.6-4b-bf16.rad` (8.3 GiB) | [convert](#convert-a-checkpoint) | — |
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | — |
| Gemma 4 31B w5: GPTQ int5 trunk (a scale and a zero point per 128 weights), MTP, vision | `gemma4-31b-w5.rad` (23 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w5) | — |
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | — |
| Gemma 4 31B: int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-i8g) | — |
| Gemma 4 31B heretic-ara (refusals removed): int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-heretic-ara-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-i8g) | — |
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | — |
| Gemma 4 12B bf16: MTP, vision, audio | `gemma4-12b-bf16.rad` (25 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-bf16) | — |
| Gemma 4 12B int8 (i8a8): MTP, vision, audio | `gemma4-12b-i8g.rad` (14 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-i8g) | — |
| Qwen-Image 2.1 IQ8R: text to image and image edits | `qwen-image-2.1-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-iq8r) | `tp1.yaml`, `tp2.yaml` |
| Qwen-Image 2.1 Turbo IQ8R: the same in 8 steps | `qwen-image-2.1-turbo-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-iq8r) | — |
| Krea 2 Turbo IQ8R: text to image, one card | `krea-2-turbo-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-iq8r) | — |
| Krea 2 Raw IQ8R: the same, undistilled | `krea-2-raw-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-iq8r) | — |
| FLUX.3 [klein] IQ8R: text to image and edits from up to ten pictures, one card | `flux-3-klein-iq8r.rad` (9.4 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-iq8r) | — |
| FLUX.3 [klein] base IQ8R | `flux-3-klein-base-iq8r.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-iq8r) | — |
| LTX-2.5 distilled IQ8R: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-iq8r.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-iq8r) | — |
| LTX-2.5 base IQ8R | `ltx-2.5-iq8r.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-iq8r) | — |
| MiniMax-H3, int8 DiT: video with its stereo soundtrack from text | `minimax-h3-i8.rad` (63 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-i8) | `tp2.yaml` |
| FastH3 8-Step V2, int8 DiT: the same in eight steps | `fasth3-8-step-v2-i8.rad` (65 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-i8) | — |
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `tp1.yaml`, `tp2.yaml` |
| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | — |
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `tp1.yaml`, `tp2.yaml` |
| TranslateGemma 27B, int8 trunk: translation | `translategemma-27b-i8.rad` (28 GiB) | [download](https://huggingface.co/StillDeadcode/translategemma-27b-i8) | — |
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | — |
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | — |
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | — |
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `tp1.yaml`, `tp2.yaml` |
| nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | — |
| Nemotron 3.5 Embed 1B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-1B-BF16) | — |
| Nemotron 3.5 Embed 8B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16) | — |
| Nemotron 3.5 Rerank 8B BF16: text/image document relevance, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16) | `tp1.yaml`, `tp2.yaml` |
| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | `tp1.yaml`, `tp2.yaml` |
**Not served by this version.** A container whose weights are block FP8, MXFP4, M2XFP4 or
ParoQuant, or whose experts read E4M3 activations, is refused at startup by the name of the first
such weight. That is every FP8 and MXFP4 container of the models above, and the models that have
no int8 container yet: Ornith-1.5 (35B-A3B and 122B), Sage-A1.5,
NVIDIA-Nemotron-3.5-Bolt-74B-A9B, GLM-5.3-Flash, Ling-3.0-flash-Sante, Fish Audio drama-3 and
Anima's FP8 container (Anima converted to bf16 is served). Each returns with an int8 container.
A container with an int8 or bf16 trunk and a block-FP8 drafter (NVIDIA-Nemotron-3.5-Bolt-E4B,
the Gemma 4 31B DFlash and DFlash2 containers, MiniCPM5-2B bf16) serves without the drafter
under `num-speculative-tokens: 0`.
A container holds everything the server needs: the weights, the tokeniser, the chat template and
any drafter. Each download link's repository has the recipe and the exact command that made the
@@ -32,28 +75,83 @@ file. Download one into your models directory (the transfer resumes if interrupt
```sh
mkdir -p /srv/models/rad && cd /srv/models/rad
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/minicpm5-2b-fp8.rad
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r/resolve/main/minicpm5-2b-iq8r.rad
```
The Gemma 4 container is keptn42's: GPTQ calibrated in transformers, with an int8 lm_head; its
repository has the recipe and the calibration step. To convert Google's bf16 checkpoint yourself,
`data/recipes/gemma4-31b-dense-bf16-w4a8.recipe` quantises without calibration (round-to-nearest
with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkpoint). On two R9700s
that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's,
and accepts 0.46 of its drafts on prose against 0.50.
TranslateGemma 27B is converted from Google's bf16 checkpoint with
`data/recipes/translategemma-27b-i8a8.recipe`, an int8 trunk rounded without calibration data.
Its chat template takes structured turns
naming the two languages and refuses the plain turn the server renders at startup, so its entry
serves a plain Gemma 3 template, `deploy/compose/gemma3.jinja` (`override-chat-template` names it;
in a compose file, mount it into the container), and a client sends on `/v1/completions` the prompt
the checkpoint's template renders.
The Qwen-Image containers serve OpenAI's images API (`/v1/images/generations`, `/v1/images/edits`):
pictures from a prompt, and edits of up to ten pictures with an optional mask, 2048x2048 by default.
On two R9700s a 2048x2048 picture takes 61 s at the base model's 40 steps and 13 s with Turbo (56 and
12 s with `tp-wire: wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research
license, which is non-commercial. Krea 2 is under the Krea 2 Community License and Krea's
acceptable use policy, FLUX.3 [klein] under the FLUX Kommunity License (non-commercial use),
LTX-2.5 under the LTX-2.x Community License, and an SDXL finetune under its checkpoint's own
license.
The MiniMax-H3 containers serve OpenAI's video jobs (`/v1/videos`): a video with its stereo
soundtrack from a prompt, 5 to 14 s, up to 1344x768. On two R9700s a 5.17 s clip at 1344x768 takes
about 68 s with FastH3 and 8.8 minutes at MiniMax-H3's 50 steps; both read about 39 GiB of pinned
host memory. With LBH-123-AI's latent upscaler in the container, `"latent_upscale": 2` runs the first
steps at half the size and refines at the full size: MiniMax-H3's clip then takes 3.4 minutes
(docs/GUIDE.md §5.16). A ComfyUI node, `integrations/comfyui/ComfyUI-Radiance-MiniMax`, renders
through `/v1/videos` from a ComfyUI graph as a client of the server. MiniMax-H3's license, which
FastH3 carries, does not cover the EU, the UK, the Republic of Korea or the USA.
MiniMax-Music3 and Breeze-TTS-2 answer `/v1/audio/speech`, whole or streamed as they are made: a song
from lyrics and a description, 44.1 kHz stereo, made at about the speed it plays on two cards; and
speech in a voice the request describes, made in 0.6 of its playing time on one card, its first
streamed audio 0.21 s after the request. Breeze-TTS-2 also speaks text while it is being written,
over the `/v1/audio/speech/stream` WebSocket; it is licensed for research and non-commercial use
only. Fish Audio's drama-3 speaks a script whose speakers and direction are written in it
(`<|speaker:1|>`, `[laughs]`), each speaker in the model's voice or one cloned from a reference
clip and its transcript, at 0.3 of its playing time on two cards, its first streamed audio
0.23 s after the request; under the Fish Audio Community License a service that lets others
generate speech with it needs a licence from Fish Audio, and imitating a real person's voice needs
their consent.
## Run with Docker
The host needs Docker and an `amdgpu` driver that supports ROCm 7.2; it does not need ROCm. The
image is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its
kernels built for `gfx1201`. Pull it, clone this repository for its compose files, then start a
model from one of them:
The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The
card works best with Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup);
without it the engine keeps kernel arguments in pinned host memory, and every dispatch reads them
over the link. The image
is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels
built for `gfx1201` (RDNA4), `gfx11-generic` (RDNA3) and `gfx1151` (Strix Halo). Pull it, clone
this repository for its compose files, then start one of them:
```sh
docker pull stilldeadcode/radiance
git clone https://codeberg.org/StillDeadcode/radiance.git
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_STATE, RADIANCE_API_KEY, the GIDs
docker compose -f minicpm5-2b.yaml up -d # or any file from the table
docker compose -f minicpm5-2b.yaml logs -f
docker compose -f minicpm5-2b.yaml down
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_API_KEY, the GIDs
docker compose -f tp2.yaml up -d # two cards; tp1.yaml for one (RADIANCE_GPU)
docker compose -f tp2.yaml logs -f
docker compose -f tp2.yaml down
```
Every model uses both cards and the same port, so run one at a time. Running without compose, and
the reason for each `docker run` option, is in [`docs/DOCKER.md`](docs/DOCKER.md).
A file serves all its models from one container behind one port, and brings a model onto the cards
when a request names it ([`docs/MULTIMODEL.md`](docs/MULTIMODEL.md)): a request's `model` is the
entry's name (`flashnext`, `qwen3.8-27b`, `minicpm5-2b`, ...). The entries are in
`tp1.radiance.yaml` and `tp2.radiance.yaml` beside the compose files, the server's configuration as
it reads it. Delete the entries of the containers
you do not have; any other model from the table is added as an entry with its keys from the table
under [Run without Docker](#run-without-docker). The two files take the same port, so run one at a
time. Running without compose, and the reason for each `docker run` option, is in
[`docs/DOCKER.md`](docs/DOCKER.md).
To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'`
in the clone (it needs `docker buildx` and tests the build as it goes). Then set
@@ -62,71 +160,169 @@ in the clone (it needs `docker buildx` and tests the build as it goes). Then set
## Build from source
You need Linux, git, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need
ROCm 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and build in it:
ROCm 10.1 or 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and
build in it:
```sh
git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance
./build.sh # configure, build for the cards present, run the tests
./build.sh # configure, build for the cards present, run the fast tests
./build.sh --no-hip # host backend only
cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # build for cards this machine lacks
cmake --install build --prefix /opt/radiance # optional; bin/, include/, share/radiance/
```
To install, name the prefix when the build directory is first configured
(`-DCMAKE_INSTALL_PREFIX=/opt/radiance`), build, then run `cmake --install build`. The default
plugin path, `<prefix>/share/radiance`, is compiled in from that first configure, so
`cmake --install build --prefix DIR` alone gives a tree that looks for its plugins elsewhere. The
prefix gets `bin/`, `include/radiance/`, `lib/cmake/radiance/`, `libexec/radiance/`,
`share/radiance/` and `share/doc/radiance/`.
With ROCm 10.1 the build turns the compiler's VOPD pairing (dual-issue instruction pairs) off: its
LLVM 24 pairs in an order that follows heap addresses, so two builds of the same source can differ.
The Docker image builds its compiler with the fix and keeps the pairing, which is 1.4-3.5% faster
on prefill GEMMs; a compiler that has the same fix is declared with
`-DRAD_HIP_VOPD_REPEATABLE=ON`. ROCm 7.2 is unaffected.
## Run without Docker
```sh
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an installed prefix finds its own
build/bin/radiance --model /srv/models/rad/minicpm5-2b-fp8.rad --port 8000 <flags>
build/bin/radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000 <flags>
The server reads its settings from a YAML file: `server:` holds the listener, `memory:` the
per-card VRAM budget, and `models:` one entry whose name is the model id requests use. Every key
is named as in the [`docs/GUIDE.md`](docs/GUIDE.md) §4.11 reference; `radiance --help` prints it.
```yaml
# radiance.yaml
server:
port: 8000
models:
minicpm5-2b-iq8r:
model: /srv/models/rad/minicpm5-2b-iq8r.rad # or a Hugging Face repo id: StillDeadcode/minicpm5-2b-iq8r
```
`--model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
and `jq` into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere), serves the container it
holds, and checks it for changes at every start; a start that cannot reach the hub serves the copy
it has. The Docker image has neither tool, so with Docker download the file as shown above.
```sh
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an install finds its own
build/bin/radiance --config radiance.yaml --check # validate the file, serve nothing
build/bin/radiance --config radiance.yaml
```
These are the flags each model is served with. They match its compose file, minus Flash-Next's
prefix-cache tiers:
`model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
and `jq` (`scripts/hfget.sh`) into `~/.cache/radiance/hf` (`server.download-dir` puts it elsewhere),
serves the container it holds, and checks it for changes at every start; a start that cannot reach
the hub serves the copy it has. The Docker image carries both tools; in a container,
`server.download-dir` must name a writable mount, since the compose files mount `/models` read-only.
| model | flags |
The server takes no other command-line options. A command line written for an earlier release
(`radiance --model ... --tp 2`) is refused with the same settings printed as YAML, and
`rad-yaml FLAGS...` prints that file without starting anything:
`rad-yaml --model x.rad --tp 2 > radiance.yaml`. [`docs/MULTIMODEL.md`](docs/MULTIMODEL.md) §4
describes the file's levels.
Each row holds the keys a model is served with in a file of its own (the Flash-Next rows leave out
`prefix-cache-mib`). They go under the model's entry, except `gpu-headroom-mib`, which goes under
`memory:` and in a file of several models holds for all of them. `tp1.radiance.yaml` and
`tp2.radiance.yaml` carry their models' entries as set for sharing the cards; a model added to either takes its row from
here.
| model | keys |
|---|---|
| Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
| Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `--tp 3 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
| Qwen3.8-27B FP8, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` |
| Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` |
| MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` |
| Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` |
| Qwen3.8-Flash-Next | `tp: 2, tp-wire: wht6, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 24576, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
| Qwen3.8-Flash-Next, one card | `tp: 1, max-num-seqs: 4, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 43000, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 4096, checkpoint-interval: 4096` |
| Qwen3.8-Flash-Next, four ranks | `tp: 4, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 49152, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `tp: 3, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 24576, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
| Qwen3.8-27B IQ8R and IQR-V4, Qwen3.6-35B-A3B | `tp: 2, max-num-seqs: 32, max-model-len: 200000, kv-cache-dtype: i8` |
| Qwen3.8-27B bf16 | `tp: 2, max-num-seqs: 8, max-model-len: 200000, kv-cache-dtype: i8` |
| MiniCPM5-2B IQ8R and bf16 | `tp: 2, max-num-seqs: 32, max-model-len: 131072, kv-cache-dtype: i8, gpu-headroom-mib: 160, max-num-batched-tokens: 512` |
| Qwen3.8-Flash-Next bf16 | `tp: 2, max-model-len: 32768, placement: expert_tiered, weights-disk-tier: true, host-pool-mib: 24576, gpu-headroom-mib: 768, deterministic: true, max-num-seqs: 32, max-num-batched-tokens: 32768, num-speculative-tokens: 0` |
| Qwen-Image 2.1 and 2.1 Turbo | `tp: 2, tp-wire: wht6` |
| MiniMax-H3 and FastH3 | `tp: 2, vision-tower-placement: ram` |
| MiniMax-Music3 | `tp: 2`, or `tp: 1` (20.5 GiB of weights on the card) |
| Breeze-TTS-2 | `tp: 1` |
| Gemma 4 31B (GPTQ int4) | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
| Gemma 4 31B w5, heretic-ara int4, int8 and heretic-ara int8 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, vision-tower-placement: ram, num-speculative-tokens: 3, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
| Gemma 4 31B Q8 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 0, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
| Gemma 4 12B bf16 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 3, max-num-batched-tokens: 2048, mm-max-patches: 1120, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}` |
| Gemma 4 12B int8 | `tp: 1, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 3, max-num-batched-tokens: 2048, mm-max-patches: 1120, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}` |
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16, int8 and 4-bit, without the drafter | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 0, mm-max-patches: 2520, vision-tower-placement: ram, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}`; `tp: 1` on one card |
| TranslateGemma 27B | `tp: 2, max-num-seqs: 8, max-model-len: 16384, kv-cache-dtype: i8`, and `override-chat-template` naming `deploy/compose/gemma3.jinja` |
| Unlimited-OCR | `tp: 1, max-num-seqs: 8, max-model-len: 32768, kv-cache-dtype: i8, gpu-headroom-mib: 96`, and `override-chat-template` naming `deploy/chat-templates/unlimited-ocr-parser.jinja` (`/chat-templates/unlimited-ocr-parser.jinja` in the compose files' container) |
| Krea 2 Turbo and Raw, FLUX.3 [klein] and its base, Stable Diffusion XL | `tp: 1` |
| LTX-2.5 distilled and base | `tp: 1, vision-tower-placement: ram` |
| EmbeddingGemma 2 | `tp: 1, max-num-seqs: 64, max-num-batched-tokens: 8192` |
| Qwen3-ASR 1.7B | `tp: 1, max-num-seqs: 16` |
Every model serves up to 32 sequences a step. Two rows keep 8, because on a hybrid model each
sequence holds its own recurrent state, and 32 of them take that memory from the attention cache
and, on Flash-Next, from the expert slab: Flash-Next and the 27B in bf16. See
The 27B in IQ8R and IQR-V4, the 35B-A3B, MiniCPM5 and the Flash-Next bf16 reference run at up to
32 sequences a step. The other Flash-Next rows and the 27B in bf16 keep 8, the one-card Flash-Next
row 4: on a hybrid model each sequence holds its own recurrent state, and 32 of them take that
memory from the attention cache and, on Flash-Next, from the expert slab. See
[`docs/GUIDE.md`](docs/GUIDE.md) §4.4.
At `--tp 4` the gated residual's write carries the exact all-reduce, with the MoE gather in front
of it, on decode and verify steps; a prefill chunk runs the unfused chain. That chain's exact
all-reduce is one-shot up to 1 MiB a message and two-shot above that, which sends half the bytes
on a prefill chunk; both produce the same bits. The row above runs exact.
`--tp-wire wht6` at three and four ranks selects a different lossy wire, tiered int8 over the
two-shot, above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6`
stops at startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate
against `--tp 2` on the same cards has not been measured. The
tiering flags are the tp2 recipe carried over. Above two ranks each rank still owns a **slice of
every expert's width** — each parity's 128-column blocks are cut contiguously over the ranks and the
odd block alternates with the parity, so every rank's share is whole blocks and every block has
exactly one owner — and the resident expert bytes per rank are smaller, so the elastic window is a
different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before
trusting it. **`--host-pool-mib` is pinned on every card**, so the row
above pins 4 × 12 GiB = 48 GiB, and the amdgpu driver caps pinned memory at `ttm.pages_limit`, half
of RAM by default: that row needs 96 GiB of RAM or a raised limit
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
On one card a Flash-Next prefill step copies every pooled expert across the link once, so a
4096-token step shares that copy among twice the tokens of a 2048-token one (26K-token prompts:
2545 against 1413 tok/s); the checkpoint interval matches the step because a prefill chunk never
crosses a checkpoint. At 4 sequences that row's cache holds 301K tokens. The Flash-Next bf16 row
is a reference to calibrate and compare against, a step taking tens of seconds whatever its size;
its 32K of context keeps QSA's score plane for a 32K-token step at 1 GiB.
Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). Add `--debug-graph` to print every op
and the kernel it resolved to, then exit without serving. Then:
At `tp: 4`, decode and verify steps carry the exact all-reduce in the gated residual's write, with
the MoE gather in front of it; a prefill chunk runs the unfused chain. That chain's exact
all-reduce is one-shot up to 1 MiB a message and two-shot above, which sends half the bytes on a
prefill chunk; both produce the same bits. The four-rank row runs exact. At three and four ranks
`tp-wire: wht6` selects a different lossy wire, tiered int8 over the two-shot, above
`tp-wire-min-kb`. Eight ranks have no lossy wire, so `tp: 8` with `tp-wire: wht6` stops at startup
naming the all-reduce.
Four ranks is a capacity configuration: its per-step rate against `tp: 2` on the same cards has
not been measured, and its tiering keys are the two-rank recipe carried over. As at two ranks, each
rank owns a slice of every expert's width: each parity's 128-column blocks are cut contiguously over
the ranks and the odd block alternates with the parity, so every rank's share is whole blocks and
every block has one owner. The resident expert bytes per rank are smaller, so the elastic window
has a different shape: read the boot log's `elastic` line and re-derive `host-pool-mib` before
trusting it.
`host-pool-mib` is what a model pins for its weights in all, each rank an equal share: the
four-rank row pins 48 GiB of RAM (12 GiB a rank) that nothing else can use and the kernel cannot
swap out. The amdgpu driver caps what all processes
together pin at the machine's RAM less 1/64 and 1.5 GiB; the pool is locked user memory, which
`ttm.pages_limit` does not count. A 64 GiB machine serves the one-card Flash-Next row alone, with
`prefix-cache-mib: 4096`, at about 49 GiB pinned ([`docs/GUIDE.md`](docs/GUIDE.md) §7). In
`tp1.yaml` its entry carries `prefix-cache-mib: 1024` so its host pins fit such a host beside the
8 GiB the fleet keeps free; there it is unloaded when another model loads, and on a 61 GB host it
answered its next request after 17 to 19 s, loaded from its container again.
The Gemma 4 rows sample as the checkpoint's `generation_config` states, and a request switches
thinking (`chat_template_kwargs`). `vision-tower-placement: ram` keeps the vision tower in host
memory, so its VRAM goes to the KV cache. The 31B takes its full 262,144-token context at
`max-model-len: 262144, max-num-seqs: 2`. The 12B keeps a bf16 cache because an 8-bit one costs it
more than it saves; on Bolt-E4B an E4M3 cache cost 9x the KL and the int8 cache is unmeasured. The
Bolt-E4B row serves without speculation because the published containers' drafters are block FP8.
EmbeddingGemma 2 takes an input in one step, so its `max-num-batched-tokens` is the longest input
as well as the batch. A live Qwen3-ASR session holds one sequence, so its `max-num-seqs` is the
most sessions served at once. On one card LTX-2.5's adapter slots fit at `max-lora-rank: 16,
max-loras: 1` (433 MiB).
In a file of several models, Qwen-Image's grant counts two sequences of `max-model-len` tokens of
cache, which at the model's own 33600 tokens is 55.8 GiB on one card and 32.6 GiB a card on two,
more than the cards. `tp1.yaml` sets `max-model-len: 8192` (it needs 29.7 GiB; pictures up to
about 1.9 megapixels, 1024x1024 being 4096 tokens) and `tp2.yaml` `20480` (25.4 GiB a card; the
default 2048x2048 is 16384 tokens). Alone in a file it loads at its own length, its cache taking
what the cards have left. It sizes its buffers itself and warns that it does not take
`image-gen-max-pixels` or `image-gen-max-refs`.
Add `server.api-key: KEY` (or `server.api-key-env: VAR`, which reads it from the environment) to
require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `debug-graph: true` on the model
prints every op and the kernel it resolved to, then exits without serving. A chat request:
```sh
curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
-d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
-d '{"model":"minicpm5-2b-iq8r","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
```
An image model answers OpenAI's images API instead, with base64 pictures:
```sh
curl -s localhost:8000/v1/images/generations -H 'Content-Type: application/json' \
-d '{"prompt":"a lighthouse on a cliff at sunset, oil painting","size":"1024x1024"}' \
| python3 -c 'import sys,json,base64; open("out.png","wb").write(base64.b64decode(json.load(sys.stdin)["data"][0]["b64_json"]))'
```
`http://localhost:8000/` is the dashboard. [`docs/GUIDE.md`](docs/GUIDE.md) covers the API, memory
@@ -138,23 +334,60 @@ budgets, long context, speculative decoding and operating a server.
`data/recipes/` names. Download checkpoints with `scripts/hfget.sh <org/repo> <dir>`.
```sh
build/bin/rad-convert ~/models/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \
# Spark X2.6 uses the checkpoint's BF16 weights, tokenizer and chat template; no recipe required.
build/bin/rad-convert /srv/models/hf/XHToken-Spark-X2.6-4B -o spark-x2.6-4b-bf16.rad --max-ctx 4096
build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \
--recipe data/recipes/q38-27b-bf16.recipe
build/bin/rad-convert ~/models/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096
build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096
build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-w4a8.rad \
--recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \
--set quantization_config.quant_method=compressed-tensors \
--draft-model /srv/models/hf/google/gemma-4-31B-it-assistant
build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-w4a8-df.rad \
--recipe data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe \
--set quantization_config.quant_method=compressed-tensors \
--draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash
build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-q8-df.rad \
--recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \
--set quantization_config.quant_method=compressed-tensors \
--draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash
build/bin/rad-convert /srv/models/hf/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ -o swift15-27b-w4a16.rad \
--recipe data/recipes/q38-27b-w4a16.recipe
# Any single-file SDXL checkpoint (SDXL 1.0, Illustrious, NoobAI, Pony, a civitai finetune), with
# CLIP's tokenizer.json from openai/clip-vit-large-patch14
build/bin/rad-convert /srv/models/hf/OnomaAIResearch/Illustrious-XL-v2.0/Illustrious-XL-v2.0.safetensors \
-o illustrious-xl-v2.0-bf16.rad --recipe data/recipes/sdxl-bf16.recipe \
--tokenizer /srv/models/hf/openai/clip-vit-large-patch14/tokenizer.json
```
With Docker, use `docker run --rm -v ~/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`. In
the image the recipes are in `/opt/radiance/share/radiance/recipes/`. A checkpoint served at its own
precision needs no container: `radiance --model ~/models/Qwen/Qwen3.8-27B-FP8`.
With Docker, use `docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`.
In the image the recipes are in `/opt/radiance/share/radiance/recipes/`. A checkpoint served at its
own precision needs no container: its directory is the entry's `model`
(`model: /srv/models/hf/Qwen/Qwen3.8-27B`). A release someone else quantised to an integer grid is
written at its own numbers where the kernels read them (an int4 W4A16 release, compressed-tensors'
AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with `data/recipes/q38-27b-w4a16.recipe`). Block
FP8, MXFP4, NVFP4 and ParoQuant releases are not served: convert the model's bf16 checkpoint with
an int8 recipe. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
with their `rad-convert` commands.
Spark X2.6 runs BF16 at `tp: 1`, `2`, `3` or `4` -- and `8`, the worlds libr4d has an exact
all-reduce for -- without a drafter or quantisation recipe. Its checkpoint's chat template enables
thinking by default; replies return reasoning in `reasoning_content`. Set
`chat_template_kwargs.enable_thinking` to `false` for a non-thinking request. Tool calls use the
checkpoint's tagged format and are returned as OpenAI `tool_calls`.
## Test
```sh
ctest --test-dir build -LE 'gpu|oot' # everything that runs without a card (a few minutes)
ctest --test-dir build -L gpu # device suites; they need the cards to themselves
ctest --test-dir build -L oot # rebuilds every bundled plugin out of tree against an install
ctest --test-dir build -L fast -j8 # the inner loop, under 15 s; build.sh runs it
ctest --test-dir build -LE 'gpu|oot' -j8 # everything that runs without a card (about 5 minutes)
ctest --test-dir build -L gpu # the card tests; they need the cards to themselves
ctest --test-dir build -L oot # rebuilds every bundled plugin out of tree against an install
```
`CMakePresets.json` names the same runs (`ctest --preset fast`, `host`, `gpu`, `full`, `asan`), and
[`docs/GUIDE.md`](docs/GUIDE.md) §1.3 describes the tiers and the test binaries' options.
## Documentation
| | |
@@ -162,6 +395,7 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out of tr
| [`docs/GUIDE.md`](docs/GUIDE.md) | installing, converting, serving, the HTTP API, operating a server |
| [`docs/TOOLS.md`](docs/TOOLS.md) | every flag of every tool, and the recipe syntax |
| [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files |
| [`docs/PREPARING_YOUR_RIG.md`](docs/PREPARING_YOUR_RIG.md) | a two-R9700 machine from firmware setup to a serving model |
| [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card |
| [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | the supported model families and their geometry |
| [`docs/TP3.md`](docs/TP3.md) | any world size: the attention world and uneven delta-net heads; three ranks |
+322 -340
View File
@@ -1,7 +1,6 @@
/* rad_abi.h -- the plugin ABI. This file and rad_types.h are the whole contract between the
* engine and an .so it loads. Everything is C: C++ across an .so boundary is a standing
* invitation to a mismatch that manifests as corruption three frames later, and this boundary is
* exactly where a user is expected to substitute their own build. See spec.md §2.
/* rad_abi.h -- the plugin ABI. This file and rad_types.h are the contract between the engine and
* an .so it loads. The interface is plain C: C++ across an .so boundary invites ABI mismatches,
* and this is the boundary where users substitute their own builds. See spec.md §2.
*/
#ifndef RAD_ABI_H
#define RAD_ABI_H
@@ -13,38 +12,41 @@
extern "C" {
#endif
/* Bumped whenever anything a plugin compiles against changes shape -- this header, rad_types.h,
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h or rad_sample.h. Every
* kind of plugin reports it. A plugin that does not report exactly this is refused at load, by
* name, with both versions printed. An OPTIONAL export added beside the existing ones
* (rad_plugin_reference, say) is not a change of shape: a plugin without it is read as answering
* the default. */
#define RAD_ABI_VERSION 15u
/* Bumped whenever anything a plugin compiles against changes shape: this header, rad_types.h,
* rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h, rad_sample.h or
* rad_spechub.h, a field appended to a struct included; the release that ships the change assigns
* the number. Every kind of plugin reports it, and a plugin that does not report exactly this
* version is refused at load with both versions printed. Each also exports the layout's fingerprint
* (rad_abi_layout.h), so two layouts given one number are refused as well. A new optional export
* (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default. */
#define RAD_ABI_VERSION 39u
/* ================================================================== plugin identity */
/* RAD_PLUGIN_QUANT is a quantiser plugin: rad_quant.h is its whole contract. */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
* rad_quant.h is its whole contract. */
enum { RAD_PLUGIN_KERNEL = 1, RAD_PLUGIN_ARCH = 2, RAD_PLUGIN_QUANT = 3 };
typedef struct RadPluginInfo {
uint32_t kind; /* RAD_PLUGIN_KERNEL | RAD_PLUGIN_ARCH | RAD_PLUGIN_QUANT */
uint32_t kind; /* one of RAD_PLUGIN_KERNEL, _ARCH, _QUANT */
const char* name; /* "libr4d", "libref", "qwen3_dense_bf16" */
const char* version;
const char* description;
/* The devices this build of the plugin can run on, as the backend spells an architecture in
* RadDeviceProps::arch. "host" for a library of CPU kernels, which run anywhere; "" for a
* plugin that claims nothing. Several architectures may be listed, separated by spaces or
* commas, for a binary built to cover more than one. */
/* The devices this build can run on, spelled as RadDeviceProps::arch. "host" for a library of
* CPU kernels, which run anywhere; "" for a plugin that claims nothing. A binary built for
* several architectures lists them separated by spaces or commas. */
const char* build_target;
} RadPluginInfo;
/* Every plugin exports these two. */
/* Every plugin exports these three; rad_plugin_abi_layout is RAD_PLUGIN_ABI_LAYOUT_EXPORT
* (rad_abi_layout.h). */
uint32_t rad_plugin_abi_version(void);
uint64_t rad_plugin_abi_layout(void);
const RadPluginInfo* rad_plugin_info(void);
/* ================================================================== execution domain */
/* A CPU kernel is an ordinary kernel with domain RAD_DOMAIN_HOST, resolved through the same
* hierarchy and the same constraints. Declare resolves both domains where both exist, so the
* core can change execution site at runtime without re-resolving -- spec §5.1. */
* hierarchy and constraints. Declare resolves both domains where both exist, so the core can
* change execution site at runtime without re-resolving (spec §2.1). */
enum { RAD_DOMAIN_DEVICE = 0, RAD_DOMAIN_HOST = 1, RAD_N_DOMAINS = 2 };
/* ================================================================== kernel arguments */
@@ -58,11 +60,20 @@ typedef struct RadArgs {
void* instance; /* whatever init() returned for this resolved instance */
int rank; /* tensor-parallel rank and world size, for collectives */
int world_size;
/* ABI 35: host-side maximum KV length represented by this exact launch operand (a seqused
* span or a supported one-sequence prefill boundary), or -1 when it cannot be proven. In a
* decode, verify or draft pass it is instead the step's context bound plus its longest query,
* which the recorded pass's key holds. Plugins
* must not infer it from a device pointer or synchronously read device memory to get it. */
int32_t kv_used_max_h;
/* The current rank's WGP count (HIP multiProcessorCount on RDNA); lets split launchers use
* exactly the same per-device occupancy as architecture pass-key callbacks without querying
* the process-global current device on the hot path. */
int32_t wgp_count;
} RadArgs;
/* Read a parameter by key. Definitions, not declarations: a plugin links the ABI headers and
* nothing of the engine's, so a function declared here and defined in the core would be
* unlinkable from the plugins that are its only callers. See the note in rad_types.h. */
/* Read a parameter by key. Inline definitions, because a plugin links only the ABI headers and
* nothing of the engine's. See the note in rad_types.h. */
static inline int rad_args_geti(const RadArgs* a, const char* key, long long* out) {
if (!a || !key) return 0;
for (int i = 0; i < a->n_p; ++i)
@@ -82,94 +93,44 @@ static inline const char* rad_args_gets(const RadArgs* a, const char* key) {
}
/* ================================================================== kernel hooks */
/* init/fini exist because some kernels have per-instance state that must be established once and
* not per launch -- libr4d's all-reduce needs its peer signal buffers and IPC handles set up
* across ranks before the first call, and a kernel that JITs or loads a config table wants
* somewhere to do it that is not the hot path.
/* init/fini hold per-instance state that is set up once rather than per launch: libr4d's
* all-reduce exchanges peer signal buffers and IPC handles across ranks before the first call,
* and a kernel that JITs or loads a config table does it here, off the hot path.
*
* init is called once per RESOLVED INSTANCE (one op, one band, one domain), after selection and
* before load, with the frozen geometry. It returns an opaque pointer handed back in
* RadArgs.instance, or null. A negative status aborts startup. */
* init is called once per resolved instance (one op, one band, one domain), after selection and
* before load, with the frozen geometry. The pointer it returns (or null) is handed back in
* RadArgs.instance. A negative status aborts startup. */
typedef int (*RadInitFn) (const RadParam* p, int n_p, int rank, int world_size,
void** out_instance);
typedef void (*RadFiniFn) (void* instance);
/* The launch. Must not allocate and must not synchronise. Returns RAD_OK or negative; a negative
* return aborts the step and fails the requests in it, naming the kernel and the geometry. */
* return aborts the step and fails its requests, naming the kernel and the geometry. A launch
* handed `link_gate` may return RAD_LINK_ENDED instead of RAD_OK (rad_kernel_collective). */
typedef int (*RadLaunchFn) (const RadArgs* a, RadStream stream);
/* ================================================================== the described launch */
/* A KERNEL THAT DESCRIBES ITS LAUNCH INSTEAD OF PERFORMING IT, so the runtime can turn one
* description into either a dispatch or a graph node update.
*
* WHY THIS EXISTS. The engine re-issues a fixed op sequence every step: the topology is identical
* from step to step and only a few of the dispatches carry an operand that moved. The cost of
* launching a graph is roughly flat in the number of nodes, while submitting the same dispatches
* one at a time is linear in it, so replaying such a sequence as a graph is cheaper. What a
* `launch` hook cannot support is the UPDATE: it performs the dispatch itself, marshalling its own
* arguments, so nothing above it knows which argument slot holds which operand -- and a node update
* needs exactly that slot. `describe` reports the dispatch instead of performing it.
*
* IT IS OPTIONAL. `launch` remains the required entry point and every kernel that only implements
* it keeps working unchanged -- it simply never becomes a graph node, and a sequence containing
* one is submitted the ordinary way. Implement `describe` for a kernel that is issued repeatedly
* with a stable shape; there is nothing to gain on one that runs once.
*
* THE TRAP, AND THE ONE WAY TO AVOID IT. `launch` and `describe` must dispatch the SAME kernel
* with the SAME arguments, and nothing can check that for you: a divergence is not a crash, it is
* a wrong number produced only on the graph path, only after a capture, and it will read as a
* numerics bug anywhere but here. Do NOT write the two bodies twice. Write the shape arithmetic
* once and let it emit into a sink that is either a stream or a descriptor -- libr4d does this
* with one macro, and an out-of-tree plugin should do the same.
*
* ALLOCATION-FREE, like `launch`. The runtime owns the RadLaunchDesc storage and keeps it alive
* for as long as the node exists, so the shim writes its argument VALUES into `blob` and points
* `params[i]` at them. Pointing `params[i]` at anything else is legal only if that storage
* outlives the graph -- a string literal or the instance state does, a local does not. */
/* Fill `out[0..cap)` with the dispatches this call WOULD perform and write how many to `n_out`.
* Most kernels emit one; a split-K kernel and its finisher emit two. Returns RAD_E_FULL without
* writing anything if `cap` is too small, so the runtime can retry with a bigger array; returns
* RAD_OK having written `*n_out` otherwise. Must not allocate, must not synchronise and must not
* touch the device -- it is called at capture time, off the step path, and again whenever the
* runtime needs to know whether an argument moved.
*
* IT DESCRIBES A KERNEL DISPATCH AND ONLY THAT. An op whose work is a memory copy -- libr4d's
* `cast` is a hipMemcpy2DAsync, not a launch -- has nothing to put in a RadLaunchDesc and should
* leave `describe` null. A graph can hold copy nodes, but expressing one would need a second
* descriptor shape, and the ops that want it are the ops a graph saves least on.
*
* IT TAKES THE STREAM, because some launches depend on which one they are going onto: libr4d's
* split-K GEMM takes its arrival counter from a per-stream pool, so a description made without
* the stream would name a different counter than the launch would have used -- a divergence of
* exactly the kind the paragraph above says nothing can check for you. The runtime passes the
* stream the dispatch will actually run on, which for a graph node is the stream the graph is
* launched on. */
typedef int (*RadDescribeFn)(const RadArgs* a, RadStream s, RadLaunchDesc* out,
int cap, int* n_out);
/* Bytes of scratch one launch of this shape needs. Null means none. Called at declare with the
* band's upper bound, so the arena is sized for the worst step. */
typedef int64_t (*RadScratchFn)(const RadArgs* a);
/* ================================================================== weight layout
*
* WHAT A KERNEL STORES FOR A WEIGHT, GIVEN WHAT THE WEIGHT IS. spec.md §4.1, §4.3.
* What a kernel stores for a weight, given the weight's encoding. spec.md §4.1, §4.3.
*
* A container holds each weight's ENCODING -- its codes, scales and zero points as canonical planes
* (rad_encoding.h) -- and nothing shaped for a kernel. The kernel that reads a weight says here
* what it wants instead, and the loader turns one into the other when the model loads. Lossless,
* always: a relayout moves bits and derives nothing a reader of the planes could not derive -- a
* fragment order, a scale repeated into a row's tail, a reference exponent that is a row's
* maximum. Choosing numbers is a quantiser's job (rad_quant.h); a kernel that did it here would
* make the served numbers depend on which library loaded the container. So a kernel library may
* change every layout it has and no container is converted again. */
* A container holds each weight's encoding (codes, scales and zero points as canonical planes,
* rad_encoding.h) and nothing shaped for a kernel. The kernel that reads a weight describes the
* form it wants here, and the loader converts when the model loads. The conversion is lossless: a
* relayout moves bits and derives only what a reader of the planes could derive (a fragment order,
* a scale repeated into a row's tail, a reference exponent that is a row's maximum). Choosing
* numbers is the quantiser's job (rad_quant.h); a kernel doing it here would make the served
* numbers depend on which library loaded the container. So a kernel library may change any layout
* without containers being converted again. */
typedef struct RadLayout {
const char* tag; /* stable name of the arrangement, for messages and for checking
* that every kernel reading one weight wants the same bytes */
uint32_t dtype; /* the stored dtype, possibly a plugin-private one */
uint32_t rank;
int64_t shape[RAD_MAX_RANK]; /* the STORED shape, which may differ from the logical one */
int64_t shape[RAD_MAX_RANK]; /* the stored shape, which may differ from the logical one */
int64_t align; /* byte alignment the stored base must satisfy */
int64_t bytes; /* total, including any padding the layout implies */
} RadLayout;
@@ -177,93 +138,110 @@ typedef struct RadLayout {
/* Describe what this kernel stores for operand `operand` of the given geometry.
*
* `enc` is the weight's encoding and `sel[i]` the index into `enc->plane` of planes[i], the planes
* this operand takes, in the order the declaration named them (RadWeightDecl::planes). Each plane
* is THIS RANK'S SLICE, dense: rank 2, [rows, cols] in the plane's own elements, every row starting
* on a byte and rad_dtype_bytes(dtype, cols) long. Here the planes carry their geometry and a null
* `data`.
* this operand takes, in RadWeightDecl::planes order. Each plane is this rank's slice, dense: rank
* 2, [rows, cols] in the plane's own elements, every row starting on a byte and
* rad_dtype_bytes(dtype, cols) long. Here the planes carry their geometry and a null `data`.
*
* RAD_OK `out` describes the stored form, and `relayout` will produce it.
* RAD_E_UNSUPPORTED stored as it is: the one selected plane, its bytes unchanged -- what most
* weights are, and what a kernel with no hook at all gets. Only such a weight
* can be read where it lies in the container (the file and mapped tiers).
* RAD_E_DTYPE THE KERNEL DOES NOT READ THIS ENCODING -- an fp8 GEMM handed int4, a
* rotated weight to a kernel that does not rotate its activation. A
* declare-time error that names the weight, the encoding and the kernel.
* RAD_E_SHAPE the planes selected, or their extents, are not what the kernel reads. */
* RAD_E_UNSUPPORTED stored as is: the one selected plane, bytes unchanged. This is most
* weights, and what a kernel with no hook gets. Only such a weight can be
* read where it lies in the container (the file and mapped tiers).
* RAD_E_DTYPE the kernel does not read this encoding (an fp8 GEMM handed int4, a rotated
* weight to a kernel that does not rotate its activation). A declare-time
* error naming the weight, the encoding and the kernel.
* RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads.
* RAD_LAYOUT_ANY the kernel reads the stored bytes without interpreting them (a prefetch
* into the cache), so it takes whatever form another reader chose and claims
* none: the builder does not count it when settling the stored form, and the
* runtime's layout check accepts it. A weight only such kernels read is
* stored as it is. */
#define RAD_LAYOUT_ANY 1
typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes,
RadLayout* out);
/* Write the stored form `layout` described into `dst`, `dst_bytes` long, from the planes, which
* now carry their bytes. Pure host code, run by the loader -- on a pool, behind the read of the
* container, so it has to keep pace with the disk. */
* now carry their bytes. Pure host code, run by the loader on a pool behind the container read,
* so it has to keep pace with the disk. The planes are read only: the loader may hand them
* straight out of its read buffer, which the copies for other ranks read at the same time. */
typedef int (*RadRelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes, void* dst,
int64_t dst_bytes);
/* ...AND BACK: recover the planes from a stored form. `planes` arrive with their geometry and a
/* The inverse: recover the planes from a stored form. `planes` arrive with their geometry and a
* buffer each.
*
* WHY THE INVERSE HAS TO EXIST, stated from the failure it prevents. A tool that checks a kernel
* against the oracle holds the STORED bytes -- what the kernel reads -- and libref reads canonical
* planes. Handed the stored bytes it computes a correct answer to a permuted question, and the
* comparison is then between two unrelated tensors: a relative error of the size two independent
* draws give, reported against a kernel that is in fact correct. Only the plugin knows its
* permutation, so only the plugin can undo it. A kernel that relayouts and supplies no inverse is
* not a fault -- it is simply not checkable against a dense oracle, and the tools say so BY NAME
* rather than guessing. */
* A tool checking a kernel against the oracle holds the stored bytes, but libref reads canonical
* planes; given the stored bytes it answers a permuted question, and the comparison reports an
* error the size of two unrelated tensors against a correct kernel. Only the plugin knows its
* permutation. A kernel that relayouts without an inverse is not at fault, only not checkable
* against a dense oracle, and the tools report it by name. */
typedef int (*RadUnrelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes,
const RadTensor* planes, int n_planes);
/* ================================================================== operand description */
/* HOW BIG IS OPERAND i OF THIS OP, AND WHAT MAY BE IN IT.
/* How big operand i of an op is, and what values it may hold.
*
* An op's schema names its operands and their roles but not their extents, because the extents
* are not derivable from the parameters in general -- the run phase supplies them at issue. So a
* tool that wants to CALL an op cold, which is what a correctness check and a benchmark both do,
* has to size its buffers somehow. A hand-written table inside `tools/` cannot serve that: it
* covers only the ops someone wrote a row for and skips the rest, it cannot be extended without
* patching the engine, and it is a place where a tool knows something about an op.
* A schema names operands and their roles but not their extents, which are in general not
* derivable from the parameters (the run phase supplies them at issue). A tool that calls an op
* cold, such as a correctness check or a benchmark, asks the kernel through this hook instead of
* keeping its own table of ops.
*
* The kernel is the component that knows. This hook asks it.
*
* WHAT IS IN AN OPERAND MATTERS AS MUCH AS HOW BIG IT IS, and that is why this carries a fill
* domain rather than only a shape. A gated-delta-net `g` is an intra-chunk cumulative sum of
* log-decays: non-increasing and never positive, because every decay the scan forms is
* e^{g_i - g_j} with j <= i and that is <= 1 only because g is monotone. Feed it normals and the
* ORACLE overflows to 2e38 while the kernel does something else, and the comparison then measures
* the test rather than the kernel. The same is true of a sigmoid gate, of a lower-triangular
* factor, and of every index operand: a KV slot indexes n_blocks * block_size positions and a
* block-table entry indexes n_blocks, and drawing either from the wrong range tests the kernel's
* out-of-range handling and calls the result correctness. */
* The fill domain matters as much as the shape. A gated-delta-net `g` is an intra-chunk cumulative
* sum of log-decays: non-increasing and never positive, since each decay e^{g_i - g_j} with j <= i
* is <= 1 only because g is monotone. Fed normals, the oracle overflows to 2e38 and the comparison
* measures the test rather than the kernel. The same holds for a sigmoid gate, a lower-triangular
* factor and every index operand: a KV slot indexes n_blocks * block_size positions and a
* block-table entry n_blocks, and a draw outside that range tests out-of-range handling instead. */
enum {
RAD_FILL_NORMAL = 0, /* standard normals -- the default for a float operand */
RAD_FILL_SIGMOID = 1, /* (0, 1): a gate */
RAD_FILL_GATE_CUMSUM = 2, /* non-increasing and <= 0, reset every `fill_chunk` rows */
RAD_FILL_TRI_LOWER = 3, /* zero above the diagonal within a `fill_chunk` block */
RAD_FILL_INDEX = 4, /* integers; see idx_max / idx_const / the IDX flags */
/* UNIT L2 NORM ALONG THE LAST DIMENSION. The gated-delta-net key is normalised by the
* model's own qk_norm before it reaches the solve, and the solve inverts I + tril(beta k k^T,
* -1): drawn as unit normals over a 128-wide head that matrix has off-diagonals a hundred
* times too large, its inverse is enormous, and two implementations summing an
* ill-conditioned product in different orders disagree by however ill-conditioned it is. What
* that reports is the condition number of the TEST. Same correction as SIGMOID and
* GATE_CUMSUM above: put the operand in the domain the op is only ever handed. */
/* Unit L2 norm along the last dimension. The gated-delta-net key is normalised by qk_norm
* before the solve, which inverts I + tril(beta k k^T, -1). With unit normals over a 128-wide
* head the off-diagonals are ~100x too large, the matrix is ill-conditioned, and two
* summation orders disagree by its condition number. Like SIGMOID and GATE_CUMSUM, this puts
* the operand in the domain the op is actually given. */
RAD_FILL_UNIT_ROW = 5,
/* The samplers' `params` plane: [rows, 24] 32-bit words, each row a RadSampleParams
* (rad_sample.h) as a request sets it, its flags agreeing with its fields. Drawn as numbers,
* the integer fields and `flags` are bit patterns (a window is all or nothing, a mask row is
* never in range, each flag is a coin toss) and XTC's threshold is past any probability, so
* the mask and XTC stages do nothing and the others act on a random part of the rows.
* Row 0 switches every stage on; every other row switches each stage on or leaves it at its
* identity at random, and a minority is greedy. `fill_chunk` is the width of the op's history
* plane (0 when it has none: the window is then empty) and `idx_max` the row count of its
* bitmask plane (0 when it has none: `mask_row` is then -1). A tool that does not know the
* value draws normals. */
RAD_FILL_SAMPLE_PARAMS = 6,
};
enum {
/* An OPTIONAL operand this geometry does not pass. One entry per schema operand is still
* emitted -- that count is what catches a hook that has drifted from its schema -- so absence
* needs a spelling, and a null RadTensor.data is what the ABI already means by it. */
/* An optional operand this geometry does not pass. One entry per schema operand is still
* emitted, since that count catches a hook that drifted from its schema; a null
* RadTensor.data marks the absence. */
RAD_OPD_F_ABSENT = 1u << 0,
/* A SCATTER DESTINATION: no value may repeat. Two tokens drawn onto one slot make the store a
* race, and two implementations resolve it differently -- so the comparison would measure the
* scheduler. A read-side index (a gather row, a block-table entry) may repeat and does. */
/* A scatter destination: no value may repeat. Two tokens on one slot make the store a race
* that two implementations resolve differently. A read-side index (a gather row, a
* block-table entry) may repeat. */
RAD_OPD_F_IDX_UNIQUE = 1u << 1,
/* CUMULATIVE SEQUENCE LENGTHS, [0, ..., T]. Not a draw: it is the batch's shape. */
/* Cumulative sequence lengths, [0, ..., T]: the batch's shape, not a draw. */
RAD_OPD_F_IDX_CU = 1u << 2,
/* A routing histogram's offsets, [0, ..., idx_max - 1]: non-decreasing, first 0, last the row
* count, each bucket a run of random length (moe_scatter's `expert_offset`). A uniform draw is
* a malformed histogram that two correct implementations may read differently. Additive:
* RAD_ABI_VERSION does not move, and a tool that does not know the flag draws as before. */
RAD_OPD_F_IDX_PREFIX = 1u << 3,
/* A token history, [rows, width] ids in [0, idx_max): each row repeats itself as generated
* text does, drawing on a few ids spread over the range and copying runs of its own earlier
* tokens. A uniform draw over a vocabulary never repeats, so a frequency penalty never counts
* past one and DRY (which penalises the token that would extend a repeated suffix) never
* finds a repeat. Additive, as IDX_PREFIX: a tool that does not know the flag draws uniform
* ids. */
RAD_OPD_F_IDX_HISTORY = 1u << 4,
};
typedef struct RadOpdDesc {
@@ -272,14 +250,15 @@ typedef struct RadOpdDesc {
int64_t shape[RAD_MAX_RANK];
uint32_t fill; /* RAD_FILL_* */
int64_t fill_chunk; /* the reset width for GATE_CUMSUM and TRI_LOWER */
/* The reset width for GATE_CUMSUM and TRI_LOWER; the history plane's width for
* SAMPLE_PARAMS. */
int64_t fill_chunk;
/* RAD_FILL_INDEX only. `idx_max` is the EXCLUSIVE upper bound of the draw; 0 means "the
* leading extent of the previous operand", which is the common case and saves every gather
* from restating it. `idx_const` >= 0 makes every element that value rather than a draw --
* `seqused` is the one that needs it, because a random context length shorter than the query
* makes a causal attention read a prefix that does not exist, which both implementations
* would then agree about while neither computed what the model asks for. */
/* RAD_FILL_INDEX only, except that SAMPLE_PARAMS reads `idx_max` as its bitmask plane's row
* count. `idx_max` is the exclusive upper bound of the draw; 0 means the leading extent of the
* previous operand, the common case for a gather. `idx_const` >= 0 sets every element to that
* value instead of drawing. `seqused` needs it: a random context length shorter than the query
* makes causal attention read a prefix that does not exist. */
int64_t idx_max;
int64_t idx_const; /* -1 to draw */
@@ -287,95 +266,75 @@ typedef struct RadOpdDesc {
} RadOpdDesc;
/* Fill `out` for operand `operand` of this op at this geometry. `p`/`n_p` is the resolved
* parameter list, exactly as `launch` would receive it. Return RAD_OK, or RAD_E_UNSUPPORTED when
* this geometry does not carry what the description needs -- a caller SKIPS AND COUNTS that
* rather than guessing an extent, because a tool that invents one tests the kernel's bounds
* handling and calls the result correctness.
* parameter list, exactly as `launch` would receive it. Returns RAD_OK, or RAD_E_UNSUPPORTED when
* this geometry lacks what the description needs; a caller skips and counts that instead of
* guessing an extent.
*
* Pure host code, no device memory, no side effects: it is called before anything is allocated. */
typedef int (*RadShapeFn)(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
/* ================================================================== tunable instantiation */
/* A KERNEL IS A FAMILY, NOT AN IMPLEMENTATION. Tile sizes, split counts, waves per block: which
* member of the family is fastest is a property of the shape and the machine, and the only way to
* know is to measure it on the machine (spec §15). A library declares the AXES here and the core
* takes the cross product.
/* A kernel is a family: tile sizes, split counts, waves per block. Which member is fastest
* depends on the shape and the machine and must be measured there (spec §15). A library declares
* the axes here and the core takes their cross product. Axes rather than a list of named
* combinations, because a hand-enumerated list has holes (a shape with 40 rows of work runs a
* 64-row tile), and because it keeps the tuning policy out of the launch adapter, where an
* out-of-tree author could not write it.
*
* AXES, NOT A LIST OF PRE-NAMED COMBINATIONS. Hand-enumerating the interesting points of a
* multi-axis space -- "wv1_sk8_mb3_npw4" and its twenty-odd siblings -- leaves HOLES, and a hole
* costs step time silently: a ladder that skips a value runs the next tile up, so a shape with
* forty rows of work gets a sixty-four-row tile. A cross product has no holes.
*
* It also keeps the tuning LAW out of the launch adapter, where it would be C++ -- ladders, caps,
* a hand-written picker -- that an out-of-tree author cannot write.
*
* THE CHOSEN VALUES ARRIVE AS ORDINARY PARAMETERS. There is no variant index: once the core has
* picked a point in the space it appends the choices to RadArgs::p, and the kernel reads `sk` with
* the same rad_args_geti() it reads `M` with. One way in, for a value the caller supplied and a
* value the tuner chose. */
* The chosen values arrive as ordinary parameters appended to RadArgs::p, with no variant index:
* the kernel reads `sk` with the same rad_args_geti() it reads `M` with. */
typedef struct RadTunable {
const char* key; /* the kernel's own name for the axis: "sk", "bm", "npw" */
const int64_t* values; /* legal values, ascending; the core tries exactly these */
int n_values;
/* WHAT RUNS WHEN THIS MACHINE HAS NO MEASUREMENT FOR THIS INSTANTIATION -- a fresh install, a
* shape nobody tuned, a cache from another card. There is no fallback beneath it, so it must
* be a value the kernel can actually launch: the loader CHECKS that it appears in `values`
* and refuses the plugin by name if it does not. */
/* The value used when this machine has no measurement for this instantiation (a fresh
* install, an untuned shape, a cache from another card). There is no fallback beneath it, so
* it must be launchable: the loader checks it appears in `values` and refuses the plugin by
* name if not. */
int64_t deflt;
const char* doc; /* what the axis does, for the tuner's report */
} RadTunable;
/* IS THIS COMBINATION LEGAL AT THIS GEOMETRY? Cross-axis rules live here rather than in the axis
* lists, because they are exactly what a product of independent lists cannot say: libr4d's skinny
* GEMM needs `wv * sk * 32` inside the block bound AND `K % (sk * unit) == 0`, and neither is a
* property of `sk` alone.
/* Whether a combination is legal at this geometry. Cross-axis rules live here because independent
* axis lists cannot express them: libr4d's skinny GEMM needs `wv * sk * 32` inside the block bound
* and `K % (sk * unit) == 0`.
*
* `p` is the resolved geometry, `choice` the candidate as key/value parameters. Pure host code,
* called before anything is allocated, once per candidate.
* called once per candidate before anything is allocated.
*
* Returns 1 for legal and 0 for SKIP -- which is not an error. A kernel may serve a subset of its
* own cross product, and the tuner reports a skipped candidate as skipped rather than as a
* failure. Null means every combination is legal. */
* Returns 1 for legal and 0 for skip, which is not an error: a kernel may serve a subset of its
* cross product, and the tuner reports the candidate as skipped. Null means every combination is
* legal. */
typedef int (*RadTuneValidFn)(const RadParam* p, int n_p, const RadParam* choice, int n_choice);
/* ================================================================== op schemas */
/* A parameter is supplied by the caller (REQUIRED), may be (OPTIONAL), or is supplied by the
* KERNEL (DERIVED).
/* A parameter is supplied by the caller (REQUIRED), may be supplied (OPTIONAL), or is supplied by
* the kernel (DERIVED).
*
* DERIVED exists because of a circularity that block_size makes concrete. Spec §7.2 says the
* paged block size comes from the resolved attention kernel and not from a core constant --
* libr4d is compiled for 16 and rejects anything else. But a constraint whose key the geometry
* does not carry does NOT hold (libr4d's rule, and the reason its two-shot all-reduce rows have
* to precede the one-shot ones), so a kernel constrained to block_size == 16 can never be
* selected by a query that omits block_size -- and the resolution the answer was to be read off
* never happens.
* DERIVED breaks a circularity. The paged block size comes from the resolved attention kernel, not
* a core constant (spec §7.2; libr4d is compiled for 16). But a constraint whose key the geometry
* does not carry does not hold (which is also why libr4d's two-shot all-reduce rows must precede
* the one-shot ones), so a kernel constrained to block_size == 16 could never be selected by a
* query that omits block_size.
*
* So: constraints on a DERIVED parameter are SKIPPED during matching, and once a kernel wins,
* its RAD_C_EQ value for that key is written into the resolved geometry. A caller that supplies
* one anyway pins it, and it matches normally -- which is how an operator forces a block size
* and gets a refusal by name rather than a silent substitution. A kernel with no EQ on a derived
* key leaves it unset, and rad_kv_block_size() reports that rather than returning zero. */
* So constraints on a DERIVED parameter are skipped during matching, and the winning kernel's
* RAD_C_EQ value for that key is written into the resolved geometry. A caller that supplies one
* pins it and it matches normally, so a forced block size is refused by name rather than silently
* substituted. A kernel with no EQ on a derived key leaves it unset, and rad_kv_block_size()
* reports that rather than returning zero. */
enum { RAD_OPTIONAL = 0, RAD_REQUIRED = 1, RAD_DERIVED = 2 };
/* WHAT A PARAMETER MEANS TO THE CORE, when the core has to act on one it did not invent.
*
* Almost none of them: a parameter is a key the plugin and the kernel agree on and the core
* carries it opaquely, which is the whole reason a third party can add an op. The exception is
* the SEQUENCE CHUNK. A linear-state scan tiles the token stream, its kernel is compiled for one
* tile length, and the SCHEDULER has to cut its steps on a multiple of that or a chunk straddles
* a sequence boundary -- so the core does need to find that one number in a geometry it otherwise
* does not read.
*
* The schema is where that number is named, and the alternative is worse: a core that found it by
* SPELLING would carry a list of likely keys ("chunk", "chunk_size", "state_chunk", ...) inside
* the scheduler, which makes the core the thing you edit to add a kernel that spells it
* differently. Declaring the role costs a field and keeps the core free of that vocabulary. */
/* RAD_PROLE_CAPACITY is a count the kernel is handed as a BOUND and never writes past its
* operands for: it launches, loops and writes by the extents of the tensors it is given. That is
* what lets the activation arena be declared again at a smaller step (RadBuildCtx::shape_probe) --
* the kernel keeps the geometry it was selected with, including the real declare's value here,
* while its buffers are the smaller step's -- so it is the KERNEL's claim to make, and a fixed
* parameter that differs between the two declares without it refuses the smaller size. */
/* What a parameter means to the core. The core carries almost every parameter opaquely, which is
* what lets a third party add an op. The exception is the sequence chunk: a linear-state scan is
* compiled for one tile length, and the scheduler must cut its steps on a multiple of it or a
* chunk straddles a sequence boundary. The schema names that role so the core does not have to
* find the parameter by guessing its spelling. */
/* RAD_PROLE_CAPACITY marks a count the kernel is handed as a bound and never writes past its
* operands for: it launches, loops and writes by the extents of the tensors it is given. That lets
* the activation arena be declared again at a smaller step (RadBuildCtx::shape_probe) while the
* kernel keeps the geometry it was selected with, including the real declare's value here. It is
* the kernel's claim to make; without it, a fixed parameter that differs between the two declares
* refuses the smaller size. */
enum { RAD_PROLE_NONE = 0, RAD_PROLE_SEQ_CHUNK = 1, RAD_PROLE_CAPACITY = 2 };
typedef struct RadParamSpec {
@@ -385,13 +344,12 @@ typedef struct RadParamSpec {
int role; /* RAD_PROLE_*; 0 for every parameter the core does not interpret */
} RadParamSpec;
/* Positional operand roles. The core needs to know which operands are weights (so issue can
* resolve a handle and wait on the mover) and which are written (so the buffer planner can
* compute liveness). It does not need to know anything else about them. */
/* RAD_OPD_WTAB is a weight operand whose issue names a RUN of weights rather than one -- a MoE
* layer's experts -- and the kernel is handed a device array of pointers. It is a role of its own
* and not a flag on RAD_OPD_WEIGHT so that a tool reading the schema knows the operand is not a
* plane it can describe with one shape: see RAD_WTAB in rad_runtime.h. */
/* Positional operand roles. The core needs to know only which operands are weights (issue resolves
* a handle and waits on the mover) and which are written (the buffer planner computes liveness). */
/* RAD_OPD_WTAB is a weight operand whose issue names a run of weights (a MoE layer's experts);
* the kernel is handed a device array of pointers. It is a separate role, not a flag on
* RAD_OPD_WEIGHT, so a tool reading the schema knows the operand is not one plane it can describe
* with one shape: see RAD_WTAB in rad_runtime.h. */
enum { RAD_OPD_IN = 0, RAD_OPD_OUT = 1, RAD_OPD_INOUT = 2, RAD_OPD_WEIGHT = 3,
RAD_OPD_WTAB = 4 };
@@ -411,46 +369,31 @@ typedef struct RadOpSchema {
/* ================================================================== declared fusions
*
* WHAT CHAIN OF CONVENTIONAL OPS DOES THIS KERNEL COMPUTE?
* Which chain of conventional ops a kernel computes.
*
* The obvious design is for a kernel library to advertise that "kernel A can be used to fuse B
* and C", and for the engine to apply that repeatedly until the graph converges. spec.md §2.3
* refuses the second half -- "a fusion rewriter is a compiler, and a compiler is the thing whose output nobody can
* predict" -- and the declare phase keeps nothing a rewriter could work on in any case: `Program`
* holds no operand edges. The Builder computes them, collapses each buffer's whole use-set to a
* `first_def`/`last_use` pair with reads and writes MERGED, and discards the rest when it returns.
* This is a declaration, not a rewriter. spec.md §2.3 rules out a fusion rewriter, and the
* declare phase keeps nothing one could work on: `Program` holds no operand edges, and the Builder
* collapses each buffer's use-set to a `first_def`/`last_use` pair with reads and writes merged.
* "Op A's output is op B's only input" is not recoverable from that, which is also why
* `--debug-graph` declines to print an edge it cannot prove.
* `--debug-graph` prints no edge it cannot prove. Fusion stays a selection: the architecture asks
* for the fused op and emits the sequence when nothing serves it (rad_op_resolved in
* rad_builder.h is the idiom for a banded or optional fusion).
*
* So this is a DECLARATION, not a rewriter. Fusion stays a selection: the architecture asks for
* the fused op and emits the sequence when nothing serves it (spec.md 2.3, and rad_op_resolved in
* rad_builder.h, which is the idiom an out-of-tree plugin needs for a banded or optional fusion).
* What the declaration adds is that the EQUIVALENCE becomes machine-readable instead of prose in a
* kernel row -- "byte-identical to the two ops it replaces" -- and prose cannot be checked. It
* buys three things:
* The declaration makes the equivalence machine-readable, which gives:
* - an oracle: a fused kernel with no libref counterpart is checked against its chain run on the
* same plugin's unfused rows, and the answer should be byte-identical;
* - an advisory in --debug-graph: these declared ops form a chain some kernel can run in one
* launch, and why it did not fire;
* - the per-library fusion-claim count in rad-kbench's report.
*
* AN ORACLE, which is the one that matters. A fused kernel with no libref counterpart can only
* be skipped by name, and such skips dominate what a coverage run reports on a model built out
* of fusions. A fused kernel that declares its chain can instead be checked against that chain
* run out of the SAME plugin's unfused rows -- which is precisely the claim the row makes, and
* a stronger test than a tolerance against ref, because the answer should be BYTE-IDENTICAL.
* It is a hook rather than a table because a step's geometry is not always derivable from the
* fused op's: `qk_norm_rope_gate` replaces an `rmsnorm` at M = T * n_head, a product that is not
* in its parameter list.
*
* AN ADVISORY in --debug-graph: these N declared ops are a chain some kernel says it can do in
* one launch, and here is why it did not fire.
*
* A COVERAGE METRIC, which spec.md:19 lists.
*
* WHY A HOOK AND NOT A TABLE. A step's geometry is not the fused op's geometry and is not always
* derivable by a caller: `qk_norm_rope_gate` replaces an `rmsnorm` at M = T * n_head, and nothing
* in the fused op's parameter list is that product. The kernel is the component that knows, which
* is the same argument RadShapeFn and RadLayoutFn already make.
*
* OPERAND WIRING. Every operand of every step is either an operand of the FUSED kernel or a
* TEMPORARY the chain passes between its own steps. A temporary needs no description here: it is
* sized and typed by the step's own `opd_shape`, which every kernel that wants to be checked this
* way already publishes. Note how often no temporary is needed at all -- the fp8 folds still WRITE
* their intermediate when `out_bf16` is passed, precisely so the fused and unfused forms leave the
* same buffers behind. */
* Operand wiring: every operand of every step is either an operand of the fused kernel or a
* temporary passed between steps. A temporary needs no description here; the step op's own
* `opd_shape` sizes and types it. Often none is needed: the fp8 folds still write their
* intermediate when `out_bf16` is passed, so the fused and unfused forms leave the same buffers. */
enum {
RAD_FUSE_NONE = -1, /* this step does not pass that optional operand */
};
@@ -464,12 +407,11 @@ enum { RAD_MAX_FUSE_OPD = 16, RAD_MAX_FUSE_PARAMS = 12, RAD_MAX_FUSE_TMP = 8 };
typedef struct RadFuseStep {
const char* op; /* a conventional op name -- see docs/OPS.md */
RadParam p[RAD_MAX_FUSE_PARAMS]; /* this STEP's geometry, not the fused one's */
RadParam p[RAD_MAX_FUSE_PARAMS]; /* this step's geometry, not the fused one's */
int n_p;
/* One entry per operand of `op`, in its schema's order: an operand index of the fused kernel,
* RAD_FUSE_TMP(t), or RAD_FUSE_NONE. The count is checked against the step op's schema, so a
* hook that drifts from the vocabulary is a diagnosable error rather than a silent misfire --
* the same rule RadShapeFn's operand count follows, and for the same reason. */
* hook that drifts from the vocabulary is a diagnosable error (as with RadShapeFn). */
int16_t from[RAD_MAX_FUSE_OPD];
int n_from;
} RadFuseStep;
@@ -477,34 +419,22 @@ typedef struct RadFuseStep {
/* Describe step `step` of the chain this kernel replaces, for this geometry and variant.
*
* RAD_OK `out` is filled; ask again with step + 1.
* RAD_E_NOTFOUND `step` is past the end. This is how a caller learns the chain's LENGTH,
* and it is why there is no count beside the hook: the chain may differ with
* the geometry (an `rmsnorm_quant_fp8` with a residual replaces `rmsnorm_add`
* and without one replaces `rmsnorm`).
* RAD_E_UNSUPPORTED this geometry or variant has no unfused equivalent in the vocabulary. An
* honest answer, and the right one wherever a fusion computes something the
* conventional ops cannot express between them.
* RAD_E_NOTFOUND `step` is past the end. This is how a caller learns the chain's length,
* which may differ with the geometry (an `rmsnorm_quant_fp8` with a residual
* replaces `rmsnorm_add`, without one `rmsnorm`).
* RAD_E_UNSUPPORTED this geometry or variant has no unfused equivalent in the vocabulary.
*
* A chain must be EXACT, not approximate. A kernel that is merely close to the sequence it names
* should publish no hook at all: the whole value of the declaration is that a caller may
* substitute one for the other and compare the bytes. */
/* WHICH OPTIONAL OPERANDS THIS CALL PASSES, one bit per operand of the FUSED op, bit i set when
* operand i is present.
* A chain must be exact. A kernel that is merely close to a sequence publishes no hook, because
* callers substitute one for the other and compare the bytes. */
/* `present` has bit i set when operand i of the fused op is passed. The chain can depend on an
* operand, not only on a parameter: `rmsnorm_quant_fp8` replaces `add` -> `rmsnorm` ->
* `quant_act_fp8` given a residual and `rmsnorm` -> `quant_act_fp8` without. Inferring presence
* from the plugin's own RadShapeFn is right for a checker calling the kernel cold but wrong for a
* caller holding a real issue, such as the graph dump. `RAD_FUSE_NONE` cannot express it, since
* the operands that vary are the step's required ones.
*
* THIS IS NOT DECORATION: without it the chain is not answerable at all.
* `rmsnorm_quant_fp8` replaces `add` -> `rmsnorm` -> `quant_act_fp8` when it is given a residual
* and `rmsnorm` -> `quant_act_fp8` when it is not: THE CHAIN LENGTH ITSELF depends on an operand,
* not on a parameter. Without this the hook has to infer presence, and the only honest inference
* available is "whatever this plugin's own RadShapeFn publishes" -- which is right for a checker
* calling the kernel cold, since that is where its buffers came from, and WRONG for a caller
* holding a real issue, which is what the graph dump has. A fold with no residual would be
* described as three steps and the advisory would be a lie.
*
* Nor could `RAD_FUSE_NONE` express it: the operands that vary are the step's REQUIRED ones.
*
* RAD_FUSE_PRESENT_ALL is what a caller passes when it does not know, and it means exactly "answer
* for every operand your description says exists". That is a contract rather than a coupling: the
* hook may then assume its own RadShapeFn, and a caller that knows better says so. */
* RAD_FUSE_PRESENT_ALL means the caller does not know: answer for every operand your RadShapeFn
* says exists. */
#define RAD_FUSE_PRESENT_ALL ((uint64_t)~0ull)
#define RAD_FUSE_HAS(mask, i) (((mask) >> (i)) & 1ull)
@@ -521,13 +451,13 @@ typedef struct RadKernelInfo {
const char* dtypes;
int domain; /* RAD_DOMAIN_DEVICE | RAD_DOMAIN_HOST */
int priority; /* higher wins WITHIN THIS PLUGIN; ties break on declaration order */
int priority; /* higher wins within this plugin; ties break on declaration order */
const RadConstraint* constraints; int n_constraints;
/* The axes of this kernel's instantiation space, and the cross-axis legality test. Null/0
* means one implementation with nothing to tune, which is the common case and costs nothing:
* the core appends no choices and the kernel reads no tuned key. See RadTunable. */
/* The axes of this kernel's instantiation space and the cross-axis legality test. Null/0
* means one implementation with nothing to tune (the common case): the core appends no
* choices and the kernel reads no tuned key. See RadTunable. */
const RadTunable* tunables; int n_tunables;
RadTuneValidFn tune_valid;
@@ -537,37 +467,35 @@ typedef struct RadKernelInfo {
RadScratchFn scratch;
RadLayoutFn layout;
RadRelayoutFn relayout;
/* How to size and fill each operand, for a tool that calls this kernel cold. Null means this
* kernel cannot describe itself and every tool that needs a buffer for it skips it BY NAME
* rather than guessing. libref supplies it for the whole conventional vocabulary, so an
* op that stays inside docs/OPS.md is describable even when the kernel under test is not. */
/* How to size and fill each operand, for a tool that calls this kernel cold. Null means tools
* that need a buffer for it skip it by name. libref supplies it for the whole conventional
* vocabulary, so an op in docs/OPS.md is describable even when the kernel under test is not. */
RadShapeFn opd_shape;
/* The inverse of `relayout`, for a tool holding the stored bytes rather than the planes.
* Null means this kernel's stored form cannot be read back, and a dense oracle therefore has
* nothing to compare against -- which is a skip, named, and not a failure. */
/* The inverse of `relayout`, for a tool holding the stored bytes rather than the planes. Null
* means the stored form cannot be read back, so a dense oracle has nothing to compare
* against: a named skip, not a failure. */
RadUnrelayoutFn unrelayout;
/* The chain of conventional ops this kernel computes in one launch, or null for a kernel that
* is not a fusion. Non-null is also the fusion-coverage metric's numerator: it is a kernel
* saying "I stand in for these, and you may check me against them". */
/* The chain of conventional ops this kernel computes in one launch, or null if it is not a
* fusion. Non-null also counts in rad-kbench's fusion-claim column. */
RadFuseFn replaces;
/* Optional. The same dispatch, described rather than performed, so a repeatedly issued
* sequence can be replayed as a graph. Null means this kernel is always submitted
* individually, which is correct and merely slower. See RadDescribeFn for the one trap.
/* Flags describing runtime behavior relevant to core safety decisions. Zero means none.
*
* LAST IN THE STRUCT ON PURPOSE. Every kernel table in this tree is a POSITIONAL aggregate
* initialiser -- `{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}` -- so a field
* inserted anywhere else silently shifts every initialiser after it, and `nullptr` converts
* to any function pointer type, so part of that shift would compile. Append here. */
RadDescribeFn describe;
* Keep this field last. Kernel tables are positional aggregate initialisers
* (`{..., nullptr, nullptr, r4d_rad_embed_lookup, nullptr, ...}`), so a field inserted
* anywhere else shifts every later initialiser, and since `nullptr` converts to any function
* pointer type, part of that shift would still compile. Append new fields after this one. */
uint64_t capabilities;
} RadKernelInfo;
/* This row's launch grid can depend on live seqused during prefill. */
#define RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT (1ull << 0)
/* ================================================================== kernel plugin exports */
/* Every kernel plugin exports the whole set. The schemas come first: the first plugin in
* hierarchy order to declare an op fixes its schema, and a later plugin declaring the same op
* name with a different schema is refused at load with both plugins named. Since arguments are
* positional, two disagreeing schemas would make the same call mean different things depending
* on which plugin won selection, and that is not a diagnosable failure -- it is silent
* numerical garbage (spec §2.3). */
/* Every kernel plugin exports the whole set. The first plugin in hierarchy order to declare an op
* fixes its schema; a later plugin declaring the same op name with a different schema is refused
* at load with both plugins named. Arguments are positional, so disagreeing schemas would make
* the same call mean different things depending on which plugin won selection, silently
* (spec §2.3). */
int rad_kernel_schema_count(void);
const RadOpSchema* rad_kernel_schema_at(int i);
int rad_kernel_count(void);
@@ -576,41 +504,95 @@ const RadKernelInfo* rad_kernel_at(int i);
/* Optional. Called once after the plugin is loaded and before any selection, and once at
* shutdown. A plugin with no global state need not export them.
*
* THE SYMBOL NAMES ARE `rad_plugin_open` and `rad_plugin_close`. The types are named here so a
* plugin can declare them with the right signature; the loader resolves them by those exact
* names, and a plugin that spells them differently is silently never initialised.
* The symbol names are `rad_plugin_open` and `rad_plugin_close`; the types exist so a plugin can
* declare them with the right signature. The loader resolves those exact names, so a plugin that
* spells them differently is silently never initialised.
*
* `rad_plugin_open` answering RAD_E_UNSUPPORTED DECLINES this machine: the plugin is unloaded and
* the rest of the installation carries on, which is how one installation ships libraries for
* several cards. Any other negative status refuses the plugin as an error. A kernel library does
* not need to decline a card its device code was not built for -- the loader reads that out of
* the code objects it carries and leaves its device kernels out on its own. */
* `rad_plugin_open` returning RAD_E_UNSUPPORTED declines this machine: the plugin is unloaded and
* the rest of the installation carries on, so one installation can ship libraries for several
* cards. Any other negative status refuses the plugin as an error. A kernel library need not
* decline a card its device code was not built for: the loader reads that from the code objects
* and leaves those device kernels out itself. */
typedef int (*RadPluginOpenFn) (void);
typedef void (*RadPluginCloseFn)(void);
/* Optional, and a promise about kernel `i` of rad_kernel_at: nonzero means every launch of it
* reads and writes no memory but its operands and the scratch it was handed -- no allocation it
* keeps for itself, no counter it keeps between launches -- so two launches may run at the same
* time on one device whenever their operands and scratch do not overlap. The engine then lets a
* launch start before the independent ones in front of it on its queue have finished. A plugin
* that does not export the symbol, or answers 0, has every launch ordered behind everything
* before it, which is always correct. The symbol name is `rad_kernel_concurrent`. */
/* Optional, symbol `rad_plugin_freed`. The core has freed the device memory [base, base + bytes)
* and nothing launched against it runs any more. A kernel library that keeps state keyed by an
* operand's address (a counter block per output buffer, made at the first launch and replayed by
* recorded passes) drops what it keeps for addresses inside the range. A process serving several
* models frees an engine's memory when it unloads the model, so state kept past that would pile
* up with every load. Called from the freeing thread, any number of times, possibly for ranges the
* plugin never saw. */
typedef void (*RadPluginFreedFn)(const void* base, int64_t bytes);
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means every launch reads and writes
* only its operands and the scratch it was handed (no allocation it keeps, no counter kept between
* launches), so two launches may run at once on one device when their operands and scratch do not
* overlap. The engine then lets such a launch start before independent earlier launches on its
* queue finish. Without the symbol, or with 0, every launch is ordered behind everything before
* it, which is always correct. Symbol name: `rad_kernel_concurrent`. */
typedef int (*RadKernelConcurrentFn)(int i);
/* Optional: nonzero declares this kernel library a REFERENCE implementation -- written to be
* plainly correct rather than fast. Three things follow, for any library that says so and for no
* other, whatever it is called:
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it can chain. Chaining replaces
* the packet processor's ordering between dependent launches (the AQL barrier bit) with a wait in
* the kernel. Where chaining is on the engine resolves the row with the parameter `chain` = 1, and
* the launch may then emit chained forms of its kernels, recognised by "r4dchain" in the kernel's
* name; only those get a record and lose the bit. A chained form, before its first read of an
* operand, one lane a block waits until the 64-bit word at the record's `ctr` reaches `target`,
* then the block barriers and acquires at agent scope; after its last write the block releases at
* agent scope, barriers, and one lane adds 1 to `ctr`. Every block, including one with nothing to
* do, adds exactly once. The record is RAD_CHAIN_REC_BYTES at byte RAD_CHAIN_KARG_OFF of the
* kernel's argument segment: { magic, target, ctr, check }, with check = magic ^ target ^ ctr ^
* RAD_CHAIN_CHECK. A record whose magic or check does not match means: run without waiting and do
* not add. Without the symbol, or with 0, the engine never asks. Symbol name: `rad_kernel_chain`. */
typedef int (*RadKernelChainFn)(int i);
#define RAD_CHAIN_KARG_OFF 992
#define RAD_CHAIN_REC_BYTES 32
#define RAD_CHAIN_MAGIC 0x3130434e48434452ull /* "RDCHCN01" */
#define RAD_CHAIN_CHECK 0x9e3779b97f4a7c15ull
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it is a collective. Its
* launches exchange data with the other ranks' cards, so the interconnect carries their bytes
* while they run and the step waits on it. The engine keeps its own bulk traffic on those links
* (weights streamed to the card during compute) out of the way for that time. Without the symbol,
* or with 0, only the conventional `all_reduce` op is treated as a collective. Symbol name:
* `rad_kernel_collective`.
*
* 2 promises more: each launch ends the link hold itself as soon as the last byte the other ranks
* send this card for it has landed, so a kernel that reduces after the exchange frees the link for
* the rest of its run. The engine then passes each launch it holds the link for the parameter
* `link_gate`, the address of a 64-bit word the kernel reaches at system scope; a launch without
* it holds nothing. The kernel reads the word on the device as it starts (not on the host in the
* launch call, where the hold is not yet in effect) and, once those bytes have landed, decrements
* it with a system-scope atomic if it was odd; an even word it leaves alone. A launch that
* decremented returns RAD_LINK_ENDED. Any other success returns RAD_OK and the engine ends the
* hold behind the launch, so a path that ignores the word is always safe. */
typedef int (*RadKernelCollectiveFn)(int i);
#define RAD_LINK_ENDED 1
/* Optional: nonzero declares this kernel library a reference implementation, written to be
* plainly correct rather than fast. For any library that says so, whatever its name:
* - the loader ranks it below every unnamed kernel library, because a reference matches every
* op it declares and would otherwise answer for them ahead of the library serving the card
* (naming it in --kernels still puts it where it is named, and a --kernels list that does
* not name it leaves it out);
* op it declares and would otherwise win over the library serving the card (naming it in
* --kernels still places it where named, and a --kernels list that omits it leaves it out);
* - the engine refuses to serve a model with an op only a reference library implements, unless
* told to with --debug-accept-reference-kernels;
* given --debug-accept-reference-kernels;
* - rad-kbench checks every other library against it.
* A plugin that does not export the symbol, or answers 0, is an ordinary library. The symbol name
* is `rad_plugin_reference`. */
* Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`.
*
* It is a whole-library answer, because a library is usually one implementation of one thing. A
* plugin that ships a device row AND the host oracle beside it is not: marking the library would
* mark its device rows too, and the engine would refuse to serve an op that has a real kernel.
* Such a plugin exports `rad_kernel_reference` below and leaves this one 0. */
typedef int (*RadPluginReferenceFn)(void);
/* Optional, per row: nonzero says kernel `i` of rad_kernel_at is that row's reference
* implementation. Overrides `rad_plugin_reference` for the rows it is exported for, so one
* library can declare a device row (0) and its host oracle (1) side by side. A plugin that
* exports neither leaves every row classified by `rad_plugin_reference`. Symbol name:
* `rad_kernel_reference`. */
typedef int (*RadKernelReferenceFn)(int i);
#ifdef __cplusplus
} /* extern "C" */
#endif
+64
View File
@@ -0,0 +1,64 @@
/* rad_abi_layout.h -- the plugin ABI's layout fingerprint: a hash of the size of every struct abi/
* exports and of the offset and size of each of its fields (rad_abi_layout_rows.h), as the
* translation unit that includes this header sees them.
*
* RAD_ABI_VERSION names a layout, but two trees can give the same number to different layouts, and
* a plugin built against one then reads the other's structs at the wrong offsets, with no error. A
* plugin exports its own fingerprint (RAD_PLUGIN_ABI_LAYOUT_EXPORT, once in the plugin), and the
* loader refuses one whose fingerprint differs from the engine's under the same version. C and C++.
*/
#ifndef RAD_ABI_LAYOUT_H
#define RAD_ABI_LAYOUT_H
#include "rad_abi.h"
#include "rad_builder.h"
#include "rad_device.h"
#include "rad_encoding.h"
#include "rad_format.h"
#include "rad_philox.h"
#include "rad_planes.h"
#include "rad_plugin.h"
#include "rad_quant.h"
#include "rad_runtime.h"
#include "rad_sample.h"
#include "rad_spechub.h"
#include "rad_types.h"
#include "rad_yarn.h"
#include <stddef.h>
#include <stdint.h>
/* FNV-1a over the eight bytes of `v`, little end first. */
static inline uint64_t rad_abi_layout_mix(uint64_t h, uint64_t v) {
for (int i = 0; i < 8; ++i) {
h ^= (v >> (8 * i)) & 0xffu;
h *= 0x100000001b3ull;
}
return h;
}
/* The fingerprint of the abi/ headers this translation unit was compiled against. */
static inline uint64_t rad_abi_layout(void) {
uint64_t h = 0xcbf29ce484222325ull;
h = rad_abi_layout_mix(h, RAD_ABI_VERSION);
#define ABI_STRUCT(T) h = rad_abi_layout_mix(h, sizeof(T));
#define ABI_FIELD(T, f) \
h = rad_abi_layout_mix(h, offsetof(T, f)); \
h = rad_abi_layout_mix(h, sizeof(((T*)0)->f));
#include "rad_abi_layout_rows.h"
#undef ABI_STRUCT
#undef ABI_FIELD
return h;
}
/* The export the loader reads beside rad_plugin_abi_version: written once in a plugin, at file
* scope. */
#ifdef __cplusplus
#define RAD_PLUGIN_ABI_LAYOUT_EXPORT \
extern "C" uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); }
#else
#define RAD_PLUGIN_ABI_LAYOUT_EXPORT \
uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); }
#endif
#endif /* RAD_ABI_LAYOUT_H */
+947
View File
@@ -0,0 +1,947 @@
/* rad_abi_layout_rows.h -- every struct abi/ exports and each of its top-level fields, as
* ABI_STRUCT(type) and ABI_FIELD(type, field) lines; the includer defines both. rad_abi_layout.h
* hashes them into the layout fingerprint every plugin exports, and tests/abi_c_test.c and
* tests/abi_layout_test.cpp list them, so the C and C++ translation units see the same rows.
*
* A struct or field added to abi/ is added here too: abi_layout_test fails on a struct whose
* listed fields do not account for its size. Included once per table, so it has no include guard.
*/
ABI_STRUCT(RadArchProbe)
ABI_FIELD(RadArchProbe, draft_depth)
ABI_FIELD(RadArchProbe, draft_depth_fixed)
ABI_FIELD(RadArchProbe, shape_probe_ok)
ABI_FIELD(RadArchProbe, enc_merge)
ABI_FIELD(RadArchProbe, audio_frames)
ABI_FIELD(RadArchProbe, gen_rows)
ABI_FIELD(RadArchProbe, gen_patches)
ABI_FIELD(RadArchProbe, gen_audio)
ABI_FIELD(RadArchProbe, gen_ctx)
ABI_FIELD(RadArchProbe, gen_video)
ABI_FIELD(RadArchProbe, kv_fp8_ok)
ABI_FIELD(RadArchProbe, chain_pays)
ABI_FIELD(RadArchProbe, kv_stream_ok)
ABI_FIELD(RadArchProbe, control_vector_ok)
ABI_FIELD(RadArchProbe, tp_attn_rows_ok)
ABI_FIELD(RadArchProbe, state_f16_ok)
ABI_FIELD(RadArchProbe, tree_pays)
ABI_FIELD(RadArchProbe, gen_max_pixels)
ABI_FIELD(RadArchProbe, gen_max_refs)
ABI_FIELD(RadArchProbe, gen_shape)
ABI_STRUCT(RadArgs)
ABI_FIELD(RadArgs, t)
ABI_FIELD(RadArgs, n_t)
ABI_FIELD(RadArgs, p)
ABI_FIELD(RadArgs, n_p)
ABI_FIELD(RadArgs, scratch)
ABI_FIELD(RadArgs, scratch_bytes)
ABI_FIELD(RadArgs, instance)
ABI_FIELD(RadArgs, rank)
ABI_FIELD(RadArgs, world_size)
ABI_FIELD(RadArgs, kv_used_max_h)
ABI_FIELD(RadArgs, wgp_count)
ABI_STRUCT(RadBatch)
ABI_FIELD(RadBatch, phase)
ABI_FIELD(RadBatch, step)
ABI_FIELD(RadBatch, n_tok)
ABI_FIELD(RadBatch, n_seq)
ABI_FIELD(RadBatch, token_ids)
ABI_FIELD(RadBatch, positions)
ABI_FIELD(RadBatch, cu_seqlens)
ABI_FIELD(RadBatch, seq_ids)
ABI_FIELD(RadBatch, lora_slot)
ABI_FIELD(RadBatch, n_out)
ABI_FIELD(RadBatch, out_ids)
ABI_FIELD(RadBatch, q_lens)
ABI_FIELD(RadBatch, ctx_lens)
ABI_FIELD(RadBatch, max_q_len)
ABI_FIELD(RadBatch, max_ctx_len)
ABI_FIELD(RadBatch, n_kv_groups)
ABI_FIELD(RadBatch, kv)
ABI_FIELD(RadBatch, n_spec)
ABI_FIELD(RadBatch, num_accepted)
ABI_FIELD(RadBatch, spec_parent)
ABI_FIELD(RadBatch, draft_pass)
ABI_FIELD(RadBatch, n_checkpoints)
ABI_FIELD(RadBatch, checkpoint_tok)
ABI_FIELD(RadBatch, checkpoint_slot)
ABI_FIELD(RadBatch, n_seq_decode)
ABI_FIELD(RadBatch, n_tok_decode)
ABI_FIELD(RadBatch, max_q_len_decode)
ABI_FIELD(RadBatch, max_q_len_prefill)
ABI_FIELD(RadBatch, n_draft_out)
ABI_FIELD(RadBatch, draft_out_ids)
ABI_FIELD(RadBatch, n_ahead)
ABI_FIELD(RadBatch, rope_pos)
ABI_FIELD(RadBatch, rope_mixed)
ABI_FIELD(RadBatch, n_mm_rows)
ABI_FIELD(RadBatch, mm_rows)
ABI_FIELD(RadBatch, mm_embd)
ABI_FIELD(RadBatch, enc)
ABI_FIELD(RadBatch, enc_n_patch)
ABI_FIELD(RadBatch, enc_pixels)
ABI_FIELD(RadBatch, enc_coord)
ABI_FIELD(RadBatch, enc_n_seg)
ABI_FIELD(RadBatch, enc_cu)
ABI_FIELD(RadBatch, enc_max_seg)
ABI_FIELD(RadBatch, gen)
ABI_FIELD(RadBatch, gen_b)
ABI_FIELD(RadBatch, agen_b)
ABI_FIELD(RadBatch, vgen_b)
ABI_FIELD(RadBatch, control_vector)
ABI_FIELD(RadBatch, enc_seg_h)
ABI_FIELD(RadBatch, enc_seg_w)
ABI_FIELD(RadBatch, score_only)
ABI_FIELD(RadBatch, n_plugin_words)
ABI_FIELD(RadBatch, plugin_words)
ABI_FIELD(RadBatch, plugin_cu)
ABI_FIELD(RadBatch, plugin_words_h)
ABI_FIELD(RadBatch, plugin_cu_h)
ABI_FIELD(RadBatch, sgen_b)
ABI_FIELD(RadBatch, kv_used_max_h)
ABI_FIELD(RadBatch, positions_h)
ABI_FIELD(RadBatch, n_bidi)
ABI_FIELD(RadBatch, bidi_row)
ABI_FIELD(RadBatch, bidi_n)
ABI_FIELD(RadBatch, bidi_seq)
ABI_FIELD(RadBatch, bidi_used)
ABI_FIELD(RadBatch, anchor_rows)
ABI_STRUCT(RadBufDecl)
ABI_FIELD(RadBufDecl, dtype)
ABI_FIELD(RadBufDecl, rank)
ABI_FIELD(RadBufDecl, shape)
ABI_FIELD(RadBufDecl, kind)
ABI_FIELD(RadBufDecl, domain)
ABI_FIELD(RadBufDecl, derive)
ABI_FIELD(RadBufDecl, kv)
ABI_STRUCT(RadBuildCtx)
ABI_FIELD(RadBuildCtx, rank)
ABI_FIELD(RadBuildCtx, world_size)
ABI_FIELD(RadBuildCtx, max_tok)
ABI_FIELD(RadBuildCtx, max_seqs)
ABI_FIELD(RadBuildCtx, max_ctx)
ABI_FIELD(RadBuildCtx, max_spec)
ABI_FIELD(RadBuildCtx, tp_wire_lossy)
ABI_FIELD(RadBuildCtx, tp_wire_min_bytes)
ABI_FIELD(RadBuildCtx, kv_dtype)
ABI_FIELD(RadBuildCtx, is_draft)
ABI_FIELD(RadBuildCtx, scope)
ABI_FIELD(RadBuildCtx, shape_probe)
ABI_FIELD(RadBuildCtx, max_enc_patches)
ABI_FIELD(RadBuildCtx, max_out_rows)
ABI_FIELD(RadBuildCtx, max_audio_frames)
ABI_FIELD(RadBuildCtx, max_mixed_tok)
ABI_FIELD(RadBuildCtx, kv_resident_blocks)
ABI_FIELD(RadBuildCtx, kv_stream_ok)
ABI_FIELD(RadBuildCtx, cvec)
ABI_FIELD(RadBuildCtx, tp_attn_rows)
ABI_FIELD(RadBuildCtx, state_dtype)
ABI_FIELD(RadBuildCtx, draft_coupling)
ABI_FIELD(RadBuildCtx, weight_prefetch_off)
ABI_FIELD(RadBuildCtx, draft_tree)
ABI_FIELD(RadBuildCtx, calib_dir)
ABI_FIELD(RadBuildCtx, calib_layer_lo)
ABI_FIELD(RadBuildCtx, calib_layer_hi)
ABI_FIELD(RadBuildCtx, calib_tokens)
ABI_FIELD(RadBuildCtx, gen_max_pixels)
ABI_FIELD(RadBuildCtx, gen_max_refs)
ABI_FIELD(RadBuildCtx, expert_file_tier)
ABI_FIELD(RadBuildCtx, slot_base)
ABI_STRUCT(RadAudioGenBatch)
ABI_FIELD(RadAudioGenBatch, n_lane)
ABI_FIELD(RadAudioGenBatch, lane)
ABI_FIELD(RadAudioGenBatch, lane_h)
ABI_FIELD(RadAudioGenBatch, last)
ABI_FIELD(RadAudioGenBatch, last_h)
ABI_FIELD(RadAudioGenBatch, frame)
ABI_FIELD(RadAudioGenBatch, frame_h)
ABI_FIELD(RadAudioGenBatch, seed)
ABI_FIELD(RadAudioGenBatch, slot)
ABI_FIELD(RadAudioGenBatch, last_row)
ABI_FIELD(RadAudioGenBatch, prefix)
ABI_FIELD(RadAudioGenBatch, t)
ABI_FIELD(RadAudioGenBatch, t_next)
ABI_FIELD(RadAudioGenBatch, cfg)
ABI_FIELD(RadAudioGenBatch, pair)
ABI_FIELD(RadAudioGenBatch, win_lane)
ABI_FIELD(RadAudioGenBatch, win_lane_h)
ABI_FIELD(RadAudioGenBatch, flags)
ABI_FIELD(RadAudioGenBatch, flags_h)
ABI_FIELD(RadAudioGenBatch, win_index)
ABI_FIELD(RadAudioGenBatch, win_index_h)
ABI_FIELD(RadAudioGenBatch, win_frame0)
ABI_FIELD(RadAudioGenBatch, win_frame0_h)
ABI_FIELD(RadAudioGenBatch, win_frames)
ABI_FIELD(RadAudioGenBatch, win_frames_h)
ABI_FIELD(RadAudioGenBatch, lat_rows)
ABI_FIELD(RadAudioGenBatch, lat_cu)
ABI_FIELD(RadAudioGenBatch, lat_cu_h)
ABI_FIELD(RadAudioGenBatch, lat_src)
ABI_FIELD(RadAudioGenBatch, voc_lane)
ABI_FIELD(RadAudioGenBatch, voc_window)
ABI_FIELD(RadAudioGenBatch, voc_latents)
ABI_FIELD(RadAudioGenBatch, voc_left)
ABI_FIELD(RadAudioGenBatch, voc_right)
ABI_FIELD(RadAudioGenBatch, voc_frame0)
ABI_FIELD(RadAudioGenBatch, prev_slot)
ABI_FIELD(RadAudioGenBatch, prev_pos)
ABI_FIELD(RadAudioGenBatch, prev_used)
ABI_FIELD(RadAudioGenBatch, n_ref)
ABI_FIELD(RadAudioGenBatch, ref_samples)
ABI_FIELD(RadAudioGenBatch, ref_audio)
ABI_FIELD(RadAudioGenBatch, ref_cu)
ABI_FIELD(RadAudioGenBatch, ref_cu_h)
ABI_FIELD(RadAudioGenBatch, ref_frame)
ABI_FIELD(RadAudioGenBatch, ref_frame_h)
ABI_STRUCT(RadAudioGenDecl)
ABI_FIELD(RadAudioGenDecl, name)
ABI_FIELD(RadAudioGenDecl, tmpl)
ABI_FIELD(RadAudioGenDecl, neg_token)
ABI_FIELD(RadAudioGenDecl, neg_keep_head)
ABI_FIELD(RadAudioGenDecl, neg_keep_tail)
ABI_FIELD(RadAudioGenDecl, max_prompt)
ABI_FIELD(RadAudioGenDecl, max_frames)
ABI_FIELD(RadAudioGenDecl, frame_rate_num)
ABI_FIELD(RadAudioGenDecl, frame_rate_den)
ABI_FIELD(RadAudioGenDecl, win_frames)
ABI_FIELD(RadAudioGenDecl, win_hop)
ABI_FIELD(RadAudioGenDecl, win_lead)
ABI_FIELD(RadAudioGenDecl, lat_num)
ABI_FIELD(RadAudioGenDecl, lat_den)
ABI_FIELD(RadAudioGenDecl, latent_channels)
ABI_FIELD(RadAudioGenDecl, win_crop_left)
ABI_FIELD(RadAudioGenDecl, win_crop_right)
ABI_FIELD(RadAudioGenDecl, samples_per_latent)
ABI_FIELD(RadAudioGenDecl, sample_rate)
ABI_FIELD(RadAudioGenDecl, channels)
ABI_FIELD(RadAudioGenDecl, default_steps)
ABI_FIELD(RadAudioGenDecl, default_cfg)
ABI_FIELD(RadAudioGenDecl, max_lanes)
ABI_FIELD(RadAudioGenDecl, status)
ABI_FIELD(RadAudioGenDecl, audio_out)
ABI_FIELD(RadAudioGenDecl, tmpl_plain)
ABI_FIELD(RadAudioGenDecl, neg_tmpl)
ABI_FIELD(RadAudioGenDecl, prompt_whole)
ABI_FIELD(RadAudioGenDecl, first_frame)
ABI_FIELD(RadAudioGenDecl, voc_chunk)
ABI_FIELD(RadAudioGenDecl, voc_context)
ABI_FIELD(RadAudioGenDecl, branches)
ABI_FIELD(RadAudioGenDecl, input_special)
ABI_FIELD(RadAudioGenDecl, tmpl_ref)
ABI_FIELD(RadAudioGenDecl, ref_item)
ABI_FIELD(RadAudioGenDecl, ref_rate)
ABI_FIELD(RadAudioGenDecl, ref_hop)
ABI_FIELD(RadAudioGenDecl, ref_max_samples)
ABI_FIELD(RadAudioGenDecl, ref_max)
ABI_STRUCT(RadControlVector)
ABI_FIELD(RadControlVector, dir)
ABI_FIELD(RadControlVector, scales)
ABI_FIELD(RadControlVector, n_embd)
ABI_FIELD(RadControlVector, n_layers)
ABI_STRUCT(RadAudioFormat)
ABI_FIELD(RadAudioFormat, struct_size)
ABI_FIELD(RadAudioFormat, audio_open)
ABI_FIELD(RadAudioFormat, audio_close)
ABI_FIELD(RadAudioFormat, transcribe_prompt)
ABI_FIELD(RadAudioFormat, language_prompt)
ABI_FIELD(RadAudioFormat, transcript_open)
ABI_FIELD(RadAudioFormat, language_lead)
ABI_FIELD(RadAudioFormat, languages)
ABI_FIELD(RadAudioFormat, n_languages)
ABI_STRUCT(RadChatFormat)
ABI_FIELD(RadChatFormat, struct_size)
ABI_FIELD(RadChatFormat, name)
ABI_FIELD(RadChatFormat, reasoning_open)
ABI_FIELD(RadChatFormat, reasoning_close)
ABI_FIELD(RadChatFormat, reasoning_breaks)
ABI_FIELD(RadChatFormat, n_reasoning_breaks)
ABI_FIELD(RadChatFormat, reasoning_in_prompt)
ABI_FIELD(RadChatFormat, section_open)
ABI_FIELD(RadChatFormat, section_close)
ABI_FIELD(RadChatFormat, call_separator)
ABI_FIELD(RadChatFormat, call_open)
ABI_FIELD(RadChatFormat, call_close)
ABI_FIELD(RadChatFormat, name_prefix)
ABI_FIELD(RadChatFormat, name_suffix)
ABI_FIELD(RadChatFormat, call_end)
ABI_FIELD(RadChatFormat, arg_prefix)
ABI_FIELD(RadChatFormat, arg_name_suffix)
ABI_FIELD(RadChatFormat, arg_value_prefix)
ABI_FIELD(RadChatFormat, arg_value_suffix)
ABI_FIELD(RadChatFormat, string_value)
ABI_FIELD(RadChatFormat, other_value)
ABI_FIELD(RadChatFormat, value_newlines)
ABI_FIELD(RadChatFormat, triggers)
ABI_FIELD(RadChatFormat, n_triggers)
ABI_FIELD(RadChatFormat, args_form)
ABI_FIELD(RadChatFormat, object_string_open)
ABI_FIELD(RadChatFormat, object_string_close)
ABI_FIELD(RadChatFormat, object_bare_keys)
ABI_FIELD(RadChatFormat, reasoning_anywhere)
ABI_FIELD(RadChatFormat, arg_json_value_prefix)
ABI_STRUCT(RadConstraint)
ABI_FIELD(RadConstraint, key)
ABI_FIELD(RadConstraint, op)
ABI_FIELD(RadConstraint, ival)
ABI_FIELD(RadConstraint, sval)
ABI_STRUCT(RadDeviceProps)
ABI_FIELD(RadDeviceProps, name)
ABI_FIELD(RadDeviceProps, arch)
ABI_FIELD(RadDeviceProps, device_id)
ABI_FIELD(RadDeviceProps, n_cu)
ABI_FIELD(RadDeviceProps, warp_size)
ABI_FIELD(RadDeviceProps, vram_bytes)
ABI_FIELD(RadDeviceProps, vram_free)
ABI_FIELD(RadDeviceProps, lds_bytes)
ABI_FIELD(RadDeviceProps, supports_p2p)
ABI_FIELD(RadDeviceProps, is_host_backend)
ABI_FIELD(RadDeviceProps, unified)
ABI_STRUCT(RadDrafterDecl)
ABI_FIELD(RadDrafterDecl, name)
ABI_FIELD(RadDrafterDecl, kind)
ABI_FIELD(RadDrafterDecl, depth)
ABI_FIELD(RadDrafterDecl, proposal)
ABI_FIELD(RadDrafterDecl, proposal_pitch)
ABI_FIELD(RadDrafterDecl, mask_token)
ABI_FIELD(RadDrafterDecl, window)
ABI_FIELD(RadDrafterDecl, block)
ABI_STRUCT(RadDtRow)
ABI_FIELD(RadDtRow, dt)
ABI_FIELD(RadDtRow, name)
ABI_FIELD(RadDtRow, bits)
ABI_STRUCT(RadEncPlane)
ABI_FIELD(RadEncPlane, role)
ABI_FIELD(RadEncPlane, dtype)
ABI_FIELD(RadEncPlane, kind)
ABI_FIELD(RadEncPlane, block)
ABI_FIELD(RadEncPlane, extent)
ABI_STRUCT(RadEncoderDecl)
ABI_FIELD(RadEncoderDecl, name)
ABI_FIELD(RadEncoderDecl, modalities)
ABI_FIELD(RadEncoderDecl, patch_dim)
ABI_FIELD(RadEncoderDecl, merge)
ABI_FIELD(RadEncoderDecl, max_patches)
ABI_FIELD(RadEncoderDecl, n_embd)
ABI_FIELD(RadEncoderDecl, out)
ABI_FIELD(RadEncoderDecl, one_grid)
ABI_FIELD(RadEncoderDecl, bidirectional)
ABI_STRUCT(RadEncoding)
ABI_FIELD(RadEncoding, scheme)
ABI_FIELD(RadEncoding, transform)
ABI_FIELD(RadEncoding, n_planes)
ABI_FIELD(RadEncoding, reserved)
ABI_FIELD(RadEncoding, plane)
ABI_STRUCT(RadFileEntry)
ABI_FIELD(RadFileEntry, name)
ABI_FIELD(RadFileEntry, quantizer)
ABI_FIELD(RadFileEntry, options)
ABI_FIELD(RadFileEntry, enc)
ABI_FIELD(RadFileEntry, rank)
ABI_FIELD(RadFileEntry, shape)
ABI_FIELD(RadFileEntry, layer)
ABI_FIELD(RadFileEntry, expert)
ABI_FIELD(RadFileEntry, slot)
ABI_FIELD(RadFileEntry, n_planes)
ABI_FIELD(RadFileEntry, plane_first)
ABI_FIELD(RadFileEntry, offset)
ABI_FIELD(RadFileEntry, bytes)
ABI_FIELD(RadFileEntry, reserved)
ABI_STRUCT(RadFileHeader)
ABI_FIELD(RadFileHeader, magic)
ABI_FIELD(RadFileHeader, version)
ABI_FIELD(RadFileHeader, file_bytes)
ABI_FIELD(RadFileHeader, arch_id)
ABI_FIELD(RadFileHeader, model_name)
ABI_FIELD(RadFileHeader, quant)
ABI_FIELD(RadFileHeader, recipe)
ABI_FIELD(RadFileHeader, created_by)
ABI_FIELD(RadFileHeader, str_off)
ABI_FIELD(RadFileHeader, str_bytes)
ABI_FIELD(RadFileHeader, meta_off)
ABI_FIELD(RadFileHeader, meta_count)
ABI_FIELD(RadFileHeader, dir_off)
ABI_FIELD(RadFileHeader, dir_count)
ABI_FIELD(RadFileHeader, plane_off)
ABI_FIELD(RadFileHeader, plane_count)
ABI_FIELD(RadFileHeader, enc_off)
ABI_FIELD(RadFileHeader, enc_count)
ABI_FIELD(RadFileHeader, vocab_off)
ABI_FIELD(RadFileHeader, vocab_bytes)
ABI_FIELD(RadFileHeader, prof_off)
ABI_FIELD(RadFileHeader, prof_count)
ABI_FIELD(RadFileHeader, data_off)
ABI_FIELD(RadFileHeader, data_bytes)
ABI_FIELD(RadFileHeader, reserved)
ABI_STRUCT(RadFileKV)
ABI_FIELD(RadFileKV, key)
ABI_FIELD(RadFileKV, type)
ABI_FIELD(RadFileKV, pad)
ABI_FIELD(RadFileKV, v)
ABI_STRUCT(RadFilePlane)
ABI_FIELD(RadFilePlane, offset)
ABI_FIELD(RadFilePlane, bytes)
ABI_STRUCT(RadFileProfile)
ABI_FIELD(RadFileProfile, layer)
ABI_FIELD(RadFileProfile, expert)
ABI_FIELD(RadFileProfile, share)
ABI_FIELD(RadFileProfile, reserved)
ABI_STRUCT(RadFuseStep)
ABI_FIELD(RadFuseStep, op)
ABI_FIELD(RadFuseStep, p)
ABI_FIELD(RadFuseStep, n_p)
ABI_FIELD(RadFuseStep, from)
ABI_FIELD(RadFuseStep, n_from)
ABI_STRUCT(RadGenBatch)
ABI_FIELD(RadGenBatch, rows)
ABI_FIELD(RadGenBatch, src)
ABI_FIELD(RadGenBatch, rope)
ABI_FIELD(RadGenBatch, n_seg)
ABI_FIELD(RadGenBatch, seg)
ABI_FIELD(RadGenBatch, seg_h)
ABI_FIELD(RadGenBatch, seg_bidi_h)
ABI_FIELD(RadGenBatch, seg_cu)
ABI_FIELD(RadGenBatch, seg_start)
ABI_FIELD(RadGenBatch, slot_mapping)
ABI_FIELD(RadGenBatch, n_px)
ABI_FIELD(RadGenBatch, px)
ABI_FIELD(RadGenBatch, px_h)
ABI_FIELD(RadGenBatch, px_cu)
ABI_FIELD(RadGenBatch, inpaint)
ABI_FIELD(RadGenBatch, inp_mask)
ABI_FIELD(RadGenBatch, n_lane)
ABI_FIELD(RadGenBatch, lane_h)
ABI_FIELD(RadGenBatch, sigma)
ABI_FIELD(RadGenBatch, sigma_next)
ABI_FIELD(RadGenBatch, cfg)
ABI_FIELD(RadGenBatch, pair)
ABI_FIELD(RadGenBatch, lane)
ABI_FIELD(RadGenBatch, lane_dh)
ABI_FIELD(RadGenBatch, flags)
ABI_FIELD(RadGenBatch, seed)
ABI_FIELD(RadGenBatch, dec_lane)
ABI_FIELD(RadGenBatch, dec_height)
ABI_FIELD(RadGenBatch, dec_width)
ABI_FIELD(RadGenBatch, dec_preview)
ABI_FIELD(RadGenBatch, branch)
ABI_FIELD(RadGenBatch, n_pad)
ABI_FIELD(RadGenBatch, valid_cu)
ABI_FIELD(RadGenBatch, n_img)
ABI_FIELD(RadGenBatch, img_cu)
ABI_FIELD(RadGenBatch, img_rows)
ABI_FIELD(RadGenBatch, mode_cu)
ABI_FIELD(RadGenBatch, rope_f)
ABI_FIELD(RadGenBatch, mode_rows)
ABI_FIELD(RadGenBatch, mode_src)
ABI_FIELD(RadGenBatch, mode_ccu)
ABI_FIELD(RadGenBatch, n_mode_h)
ABI_FIELD(RadGenBatch, mode_rope_f)
ABI_FIELD(RadGenBatch, n_aux)
ABI_FIELD(RadGenBatch, aux_ids)
ABI_FIELD(RadGenBatch, aux_cu)
ABI_FIELD(RadGenBatch, sigma_prev)
ABI_FIELD(RadGenBatch, timestep)
ABI_FIELD(RadGenBatch, sampler)
ABI_FIELD(RadGenBatch, step)
ABI_FIELD(RadGenBatch, size_px)
ABI_FIELD(RadGenBatch, entry_h)
ABI_FIELD(RadGenBatch, tokens_h)
ABI_FIELD(RadGenBatch, cond_opts)
ABI_STRUCT(RadGeneratorDecl)
ABI_FIELD(RadGeneratorDecl, name)
ABI_FIELD(RadGeneratorDecl, layout)
ABI_FIELD(RadGeneratorDecl, tmpl_text)
ABI_FIELD(RadGeneratorDecl, tmpl_edit)
ABI_FIELD(RadGeneratorDecl, tmpl_image)
ABI_FIELD(RadGeneratorDecl, tmpl_image_sep)
ABI_FIELD(RadGeneratorDecl, drop_prefix)
ABI_FIELD(RadGeneratorDecl, tmpl_transparent)
ABI_FIELD(RadGeneratorDecl, latent_channels)
ABI_FIELD(RadGeneratorDecl, latent_scale)
ABI_FIELD(RadGeneratorDecl, size_multiple)
ABI_FIELD(RadGeneratorDecl, pixel_channels)
ABI_FIELD(RadGeneratorDecl, slot_rows)
ABI_FIELD(RadGeneratorDecl, max_tokens)
ABI_FIELD(RadGeneratorDecl, max_refs)
ABI_FIELD(RadGeneratorDecl, ref_area)
ABI_FIELD(RadGeneratorDecl, default_width)
ABI_FIELD(RadGeneratorDecl, default_height)
ABI_FIELD(RadGeneratorDecl, default_steps)
ABI_FIELD(RadGeneratorDecl, n_sigmas)
ABI_FIELD(RadGeneratorDecl, sigmas)
ABI_FIELD(RadGeneratorDecl, shift)
ABI_FIELD(RadGeneratorDecl, dyn_shift)
ABI_FIELD(RadGeneratorDecl, shift_exp)
ABI_FIELD(RadGeneratorDecl, base_shift)
ABI_FIELD(RadGeneratorDecl, max_shift)
ABI_FIELD(RadGeneratorDecl, base_seq)
ABI_FIELD(RadGeneratorDecl, max_seq)
ABI_FIELD(RadGeneratorDecl, shift_terminal)
ABI_FIELD(RadGeneratorDecl, default_cfg)
ABI_FIELD(RadGeneratorDecl, max_lanes)
ABI_FIELD(RadGeneratorDecl, image_out)
ABI_FIELD(RadGeneratorDecl, cond_rows)
ABI_FIELD(RadGeneratorDecl, rope_hw_scale)
ABI_FIELD(RadGeneratorDecl, rope_text_l)
ABI_FIELD(RadGeneratorDecl, pad_multiple)
ABI_FIELD(RadGeneratorDecl, pad_token)
ABI_FIELD(RadGeneratorDecl, cfg_original)
ABI_FIELD(RadGeneratorDecl, default_negative)
ABI_FIELD(RadGeneratorDecl, ref_shrink_only)
ABI_FIELD(RadGeneratorDecl, aux_max_tokens)
ABI_FIELD(RadGeneratorDecl, sigma_grid)
ABI_FIELD(RadGeneratorDecl, min_tokens)
ABI_FIELD(RadGeneratorDecl, aux_tokens)
ABI_FIELD(RadGeneratorDecl, beta_start)
ABI_FIELD(RadGeneratorDecl, beta_end)
ABI_FIELD(RadGeneratorDecl, train_steps)
ABI_FIELD(RadGeneratorDecl, beta_schedule)
ABI_FIELD(RadGeneratorDecl, zero_snr)
ABI_FIELD(RadGeneratorDecl, samplers)
ABI_FIELD(RadGeneratorDecl, default_sampler)
ABI_FIELD(RadGeneratorDecl, default_scheduler)
ABI_FIELD(RadGeneratorDecl, chunk_tokens)
ABI_FIELD(RadGeneratorDecl, chunk_bos)
ABI_FIELD(RadGeneratorDecl, chunk_eos)
ABI_FIELD(RadGeneratorDecl, cond_opts)
ABI_STRUCT(RadKVGroupBatch)
ABI_FIELD(RadKVGroupBatch, group)
ABI_FIELD(RadKVGroupBatch, slot_mapping)
ABI_FIELD(RadKVGroupBatch, block_table)
ABI_FIELD(RadKVGroupBatch, block_table_pitch)
ABI_FIELD(RadKVGroupBatch, seqused)
ABI_FIELD(RadKVGroupBatch, state_index)
ABI_FIELD(RadKVGroupBatch, state_index_pitch)
ABI_FIELD(RadKVGroupBatch, block_size)
ABI_FIELD(RadKVGroupBatch, max_blocks)
ABI_FIELD(RadKVGroupBatch, stream)
ABI_FIELD(RadKVGroupBatch, seqused_h)
ABI_STRUCT(RadKVGroupDecl)
ABI_FIELD(RadKVGroupDecl, kind)
ABI_FIELD(RadKVGroupDecl, dtype)
ABI_FIELD(RadKVGroupDecl, window)
ABI_FIELD(RadKVGroupDecl, n_head_kv)
ABI_FIELD(RadKVGroupDecl, head_dim)
ABI_FIELD(RadKVGroupDecl, state_dim)
ABI_FIELD(RadKVGroupDecl, conv_width)
ABI_STRUCT(RadKVStream)
ABI_FIELD(RadKVStream, host)
ABI_FIELD(RadKVStream, res)
ABI_FIELD(RadKVStream, slot_block)
ABI_FIELD(RadKVStream, slot_state)
ABI_FIELD(RadKVStream, ctl)
ABI_FIELD(RadKVStream, block_bytes)
ABI_FIELD(RadKVStream, host_layer_stride)
ABI_FIELD(RadKVStream, slots)
ABI_FIELD(RadKVStream, host_bytes)
ABI_STRUCT(RadKernelInfo)
ABI_FIELD(RadKernelInfo, name)
ABI_FIELD(RadKernelInfo, op)
ABI_FIELD(RadKernelInfo, family)
ABI_FIELD(RadKernelInfo, computes)
ABI_FIELD(RadKernelInfo, shape)
ABI_FIELD(RadKernelInfo, dtypes)
ABI_FIELD(RadKernelInfo, domain)
ABI_FIELD(RadKernelInfo, priority)
ABI_FIELD(RadKernelInfo, constraints)
ABI_FIELD(RadKernelInfo, n_constraints)
ABI_FIELD(RadKernelInfo, tunables)
ABI_FIELD(RadKernelInfo, n_tunables)
ABI_FIELD(RadKernelInfo, tune_valid)
ABI_FIELD(RadKernelInfo, init)
ABI_FIELD(RadKernelInfo, fini)
ABI_FIELD(RadKernelInfo, launch)
ABI_FIELD(RadKernelInfo, scratch)
ABI_FIELD(RadKernelInfo, layout)
ABI_FIELD(RadKernelInfo, relayout)
ABI_FIELD(RadKernelInfo, opd_shape)
ABI_FIELD(RadKernelInfo, unrelayout)
ABI_FIELD(RadKernelInfo, replaces)
ABI_FIELD(RadKernelInfo, capabilities)
ABI_STRUCT(RadLayout)
ABI_FIELD(RadLayout, tag)
ABI_FIELD(RadLayout, dtype)
ABI_FIELD(RadLayout, rank)
ABI_FIELD(RadLayout, shape)
ABI_FIELD(RadLayout, align)
ABI_FIELD(RadLayout, bytes)
ABI_STRUCT(RadModelMeta)
ABI_FIELD(RadModelMeta, arch_id)
ABI_FIELD(RadModelMeta, name)
ABI_FIELD(RadModelMeta, quant)
ABI_FIELD(RadModelMeta, n_layers)
ABI_FIELD(RadModelMeta, n_embd)
ABI_FIELD(RadModelMeta, n_head)
ABI_FIELD(RadModelMeta, n_head_kv)
ABI_FIELD(RadModelMeta, head_dim)
ABI_FIELD(RadModelMeta, n_ff)
ABI_FIELD(RadModelMeta, n_vocab)
ABI_FIELD(RadModelMeta, n_ctx_train)
ABI_FIELD(RadModelMeta, n_expert)
ABI_FIELD(RadModelMeta, n_expert_used)
ABI_FIELD(RadModelMeta, n_expert_shared)
ABI_FIELD(RadModelMeta, rms_eps)
ABI_FIELD(RadModelMeta, rope_theta)
ABI_FIELD(RadModelMeta, rope_scale)
ABI_FIELD(RadModelMeta, n_kv)
ABI_FIELD(RadModelMeta, kv_key)
ABI_FIELD(RadModelMeta, kv_val)
ABI_STRUCT(RadNameMap)
ABI_FIELD(RadNameMap, declared)
ABI_FIELD(RadNameMap, mode)
ABI_FIELD(RadNameMap, n_src)
ABI_FIELD(RadNameMap, src)
ABI_FIELD(RadNameMap, concat_dim)
ABI_FIELD(RadNameMap, src_index)
ABI_FIELD(RadNameMap, src_rows)
ABI_STRUCT(RadOpSchema)
ABI_FIELD(RadOpSchema, op)
ABI_FIELD(RadOpSchema, params)
ABI_FIELD(RadOpSchema, n_params)
ABI_FIELD(RadOpSchema, operands)
ABI_FIELD(RadOpSchema, n_operands)
ABI_FIELD(RadOpSchema, doc)
ABI_STRUCT(RadOpdDesc)
ABI_FIELD(RadOpdDesc, dtype)
ABI_FIELD(RadOpdDesc, rank)
ABI_FIELD(RadOpdDesc, shape)
ABI_FIELD(RadOpdDesc, fill)
ABI_FIELD(RadOpdDesc, fill_chunk)
ABI_FIELD(RadOpdDesc, idx_max)
ABI_FIELD(RadOpdDesc, idx_const)
ABI_FIELD(RadOpdDesc, flags)
ABI_STRUCT(RadOperand)
ABI_FIELD(RadOperand, kind)
ABI_FIELD(RadOperand, dtype)
ABI_FIELD(RadOperand, handle)
ABI_FIELD(RadOperand, raw)
ABI_FIELD(RadOperand, offset)
ABI_FIELD(RadOperand, rows)
ABI_FIELD(RadOperand, cols)
ABI_STRUCT(RadOperandSpec)
ABI_FIELD(RadOperandSpec, name)
ABI_FIELD(RadOperandSpec, role)
ABI_FIELD(RadOperandSpec, optional)
ABI_STRUCT(RadParam)
ABI_FIELD(RadParam, key)
ABI_FIELD(RadParam, kind)
ABI_FIELD(RadParam, ival)
ABI_FIELD(RadParam, ihi)
ABI_FIELD(RadParam, sval)
ABI_FIELD(RadParam, dval)
ABI_STRUCT(RadParamSpec)
ABI_FIELD(RadParamSpec, key)
ABI_FIELD(RadParamSpec, type)
ABI_FIELD(RadParamSpec, required)
ABI_FIELD(RadParamSpec, role)
ABI_STRUCT(RadPlanesEntry)
ABI_FIELD(RadPlanesEntry, role)
ABI_FIELD(RadPlanesEntry, dtype)
ABI_FIELD(RadPlanesEntry, kind)
ABI_FIELD(RadPlanesEntry, block)
ABI_FIELD(RadPlanesEntry, rows)
ABI_FIELD(RadPlanesEntry, cols)
ABI_FIELD(RadPlanesEntry, row_bytes)
ABI_FIELD(RadPlanesEntry, offset)
ABI_STRUCT(RadPlanesHeader)
ABI_FIELD(RadPlanesHeader, magic)
ABI_FIELD(RadPlanesHeader, n_planes)
ABI_FIELD(RadPlanesHeader, transform)
ABI_FIELD(RadPlanesHeader, bytes)
ABI_STRUCT(RadPluginInfo)
ABI_FIELD(RadPluginInfo, kind)
ABI_FIELD(RadPluginInfo, name)
ABI_FIELD(RadPluginInfo, version)
ABI_FIELD(RadPluginInfo, description)
ABI_FIELD(RadPluginInfo, build_target)
ABI_STRUCT(RadPrefetchNext)
ABI_FIELD(RadPrefetchNext, layer)
ABI_FIELD(RadPrefetchNext, router)
ABI_FIELD(RadPrefetchNext, n_expert)
ABI_FIELD(RadPrefetchNext, top_k)
ABI_FIELD(RadPrefetchNext, n_parts)
ABI_FIELD(RadPrefetchNext, parts)
ABI_FIELD(RadPrefetchNext, count_at)
ABI_STRUCT(RadQuantOption)
ABI_FIELD(RadQuantOption, key)
ABI_FIELD(RadQuantOption, type)
ABI_FIELD(RadQuantOption, deflt)
ABI_FIELD(RadQuantOption, doc)
ABI_STRUCT(RadQuantWeight)
ABI_FIELD(RadQuantWeight, name)
ABI_FIELD(RadQuantWeight, rank)
ABI_FIELD(RadQuantWeight, shape)
ABI_FIELD(RadQuantWeight, rows)
ABI_FIELD(RadQuantWeight, cols)
ABI_FIELD(RadQuantWeight, layer)
ABI_FIELD(RadQuantWeight, expert)
ABI_FIELD(RadQuantWeight, importance)
ABI_STRUCT(RadQuantizerInfo)
ABI_FIELD(RadQuantizerInfo, name)
ABI_FIELD(RadQuantizerInfo, doc)
ABI_FIELD(RadQuantizerInfo, options)
ABI_FIELD(RadQuantizerInfo, n_options)
ABI_FIELD(RadQuantizerInfo, encoding)
ABI_FIELD(RadQuantizerInfo, row_block)
ABI_FIELD(RadQuantizerInfo, quantize)
ABI_FIELD(RadQuantizerInfo, decode)
ABI_STRUCT(RadRouting)
ABI_FIELD(RadRouting, expert_ids)
ABI_FIELD(RadRouting, expert_w)
ABI_FIELD(RadRouting, expert_count)
ABI_FIELD(RadRouting, sorted_tok)
ABI_FIELD(RadRouting, expert_offset)
ABI_FIELD(RadRouting, top_k)
ABI_FIELD(RadRouting, n_expert)
ABI_STRUCT(RadSampleParams)
ABI_FIELD(RadSampleParams, seed)
ABI_FIELD(RadSampleParams, pos)
ABI_FIELD(RadSampleParams, temp)
ABI_FIELD(RadSampleParams, top_p)
ABI_FIELD(RadSampleParams, min_p)
ABI_FIELD(RadSampleParams, typical_p)
ABI_FIELD(RadSampleParams, rep_penalty)
ABI_FIELD(RadSampleParams, freq_penalty)
ABI_FIELD(RadSampleParams, pres_penalty)
ABI_FIELD(RadSampleParams, xtc_probability)
ABI_FIELD(RadSampleParams, xtc_threshold)
ABI_FIELD(RadSampleParams, dry_multiplier)
ABI_FIELD(RadSampleParams, dry_base)
ABI_FIELD(RadSampleParams, top_k)
ABI_FIELD(RadSampleParams, penalty_last_n)
ABI_FIELD(RadSampleParams, dry_allowed_length)
ABI_FIELD(RadSampleParams, dry_penalty_last_n)
ABI_FIELD(RadSampleParams, hist_off)
ABI_FIELD(RadSampleParams, hist_len)
ABI_FIELD(RadSampleParams, mask_row)
ABI_FIELD(RadSampleParams, flags)
ABI_FIELD(RadSampleParams, dry_rep_limit)
ABI_STRUCT(RadShapeGenBatch)
ABI_FIELD(RadShapeGenBatch, lane)
ABI_FIELD(RadShapeGenBatch, patches)
ABI_FIELD(RadShapeGenBatch, step)
ABI_FIELD(RadShapeGenBatch, n_steps)
ABI_FIELD(RadShapeGenBatch, sigma)
ABI_FIELD(RadShapeGenBatch, sigma_next)
ABI_FIELD(RadShapeGenBatch, cfg)
ABI_FIELD(RadShapeGenBatch, pair)
ABI_FIELD(RadShapeGenBatch, lanes)
ABI_FIELD(RadShapeGenBatch, flags)
ABI_FIELD(RadShapeGenBatch, seed)
ABI_FIELD(RadShapeGenBatch, lat_cu)
ABI_FIELD(RadShapeGenBatch, n_query)
ABI_FIELD(RadShapeGenBatch, query)
ABI_FIELD(RadShapeGenBatch, query_cu)
ABI_STRUCT(RadShapeGenDecl)
ABI_FIELD(RadShapeGenDecl, name)
ABI_FIELD(RadShapeGenDecl, canvas)
ABI_FIELD(RadShapeGenDecl, border_ratio)
ABI_FIELD(RadShapeGenDecl, enc_size)
ABI_FIELD(RadShapeGenDecl, enc_patch)
ABI_FIELD(RadShapeGenDecl, pix_mean)
ABI_FIELD(RadShapeGenDecl, pix_std)
ABI_FIELD(RadShapeGenDecl, latent_rows)
ABI_FIELD(RadShapeGenDecl, latent_channels)
ABI_FIELD(RadShapeGenDecl, step_rows)
ABI_FIELD(RadShapeGenDecl, default_steps)
ABI_FIELD(RadShapeGenDecl, max_steps)
ABI_FIELD(RadShapeGenDecl, default_guidance)
ABI_FIELD(RadShapeGenDecl, bounds)
ABI_FIELD(RadShapeGenDecl, level)
ABI_FIELD(RadShapeGenDecl, default_resolution)
ABI_FIELD(RadShapeGenDecl, min_resolution)
ABI_FIELD(RadShapeGenDecl, max_resolution)
ABI_FIELD(RadShapeGenDecl, max_lanes)
ABI_FIELD(RadShapeGenDecl, max_query)
ABI_FIELD(RadShapeGenDecl, field_out)
ABI_STRUCT(RadTensor)
ABI_FIELD(RadTensor, data)
ABI_FIELD(RadTensor, dtype)
ABI_FIELD(RadTensor, rank)
ABI_FIELD(RadTensor, shape)
ABI_FIELD(RadTensor, stride)
ABI_STRUCT(RadTunable)
ABI_FIELD(RadTunable, key)
ABI_FIELD(RadTunable, values)
ABI_FIELD(RadTunable, n_values)
ABI_FIELD(RadTunable, deflt)
ABI_FIELD(RadTunable, doc)
ABI_STRUCT(RadVideoGenBatch)
ABI_FIELD(RadVideoGenBatch, lane)
ABI_FIELD(RadVideoGenBatch, geom)
ABI_FIELD(RadVideoGenBatch, geom_d)
ABI_FIELD(RadVideoGenBatch, lane_d)
ABI_FIELD(RadVideoGenBatch, first_d)
ABI_FIELD(RadVideoGenBatch, seg_cu)
ABI_FIELD(RadVideoGenBatch, lat_cu)
ABI_FIELD(RadVideoGenBatch, n_steps)
ABI_FIELD(RadVideoGenBatch, t_video)
ABI_FIELD(RadVideoGenBatch, t_audio)
ABI_FIELD(RadVideoGenBatch, step)
ABI_FIELD(RadVideoGenBatch, sched)
ABI_FIELD(RadVideoGenBatch, pos)
ABI_FIELD(RadVideoGenBatch, seed)
ABI_FIELD(RadVideoGenBatch, chunk)
ABI_FIELD(RadVideoGenBatch, n_chunks)
ABI_FIELD(RadVideoGenBatch, dec_rows)
ABI_FIELD(RadVideoGenBatch, n_frames_out)
ABI_FIELD(RadVideoGenBatch, n_samples)
ABI_FIELD(RadVideoGenBatch, geom_from)
ABI_FIELD(RadVideoGenBatch, upscale)
ABI_FIELD(RadVideoGenBatch, n_neg)
ABI_FIELD(RadVideoGenBatch, guidance_h)
ABI_FIELD(RadVideoGenBatch, image)
ABI_FIELD(RadVideoGenBatch, has_image)
ABI_FIELD(RadVideoGenBatch, guidance)
ABI_FIELD(RadVideoGenBatch, decoder)
ABI_FIELD(RadVideoGenBatch, sampler)
ABI_FIELD(RadVideoGenBatch, enc_pixels)
ABI_FIELD(RadVideoGenBatch, enc_frames)
ABI_FIELD(RadVideoGenBatch, enc_height)
ABI_FIELD(RadVideoGenBatch, enc_width)
ABI_FIELD(RadVideoGenBatch, enc_samples)
ABI_FIELD(RadVideoGenBatch, enc_n_samples)
ABI_FIELD(RadVideoGenBatch, enc_channels)
ABI_FIELD(RadVideoGenBatch, enc_geom_d)
ABI_FIELD(RadVideoGenBatch, enc_kind)
ABI_FIELD(RadVideoGenBatch, enc_slot)
ABI_FIELD(RadVideoGenBatch, ref_tab)
ABI_FIELD(RadVideoGenBatch, mod_cu)
ABI_STRUCT(RadVideoGenDecl)
ABI_FIELD(RadVideoGenDecl, name)
ABI_FIELD(RadVideoGenDecl, tmpl)
ABI_FIELD(RadVideoGenDecl, max_text)
ABI_FIELD(RadVideoGenDecl, fps_num)
ABI_FIELD(RadVideoGenDecl, fps_den)
ABI_FIELD(RadVideoGenDecl, frames_per_chunk)
ABI_FIELD(RadVideoGenDecl, frames_tail)
ABI_FIELD(RadVideoGenDecl, latents_per_chunk)
ABI_FIELD(RadVideoGenDecl, latents_tail)
ABI_FIELD(RadVideoGenDecl, dec_latents)
ABI_FIELD(RadVideoGenDecl, min_chunks)
ABI_FIELD(RadVideoGenDecl, max_chunks)
ABI_FIELD(RadVideoGenDecl, latent_scale)
ABI_FIELD(RadVideoGenDecl, latent_channels)
ABI_FIELD(RadVideoGenDecl, patch)
ABI_FIELD(RadVideoGenDecl, size_multiple)
ABI_FIELD(RadVideoGenDecl, min_side)
ABI_FIELD(RadVideoGenDecl, max_area)
ABI_FIELD(RadVideoGenDecl, max_aspect)
ABI_FIELD(RadVideoGenDecl, default_width)
ABI_FIELD(RadVideoGenDecl, default_height)
ABI_FIELD(RadVideoGenDecl, default_chunks)
ABI_FIELD(RadVideoGenDecl, sample_rate)
ABI_FIELD(RadVideoGenDecl, audio_rate)
ABI_FIELD(RadVideoGenDecl, audio_channels)
ABI_FIELD(RadVideoGenDecl, audio_latent_channels)
ABI_FIELD(RadVideoGenDecl, default_steps)
ABI_FIELD(RadVideoGenDecl, max_steps)
ABI_FIELD(RadVideoGenDecl, shift_video)
ABI_FIELD(RadVideoGenDecl, shift_audio)
ABI_FIELD(RadVideoGenDecl, max_lanes)
ABI_FIELD(RadVideoGenDecl, frames_out)
ABI_FIELD(RadVideoGenDecl, audio_out)
ABI_FIELD(RadVideoGenDecl, n_rungs)
ABI_FIELD(RadVideoGenDecl, rungs)
ABI_FIELD(RadVideoGenDecl, upscale_max)
ABI_FIELD(RadVideoGenDecl, upscale_refine)
ABI_FIELD(RadVideoGenDecl, sched_kind)
ABI_FIELD(RadVideoGenDecl, dyn_shift)
ABI_FIELD(RadVideoGenDecl, base_shift)
ABI_FIELD(RadVideoGenDecl, max_shift)
ABI_FIELD(RadVideoGenDecl, base_seq)
ABI_FIELD(RadVideoGenDecl, max_seq)
ABI_FIELD(RadVideoGenDecl, shift_terminal)
ABI_FIELD(RadVideoGenDecl, n_refine_rungs)
ABI_FIELD(RadVideoGenDecl, refine_rungs)
ABI_FIELD(RadVideoGenDecl, step_text_rows)
ABI_FIELD(RadVideoGenDecl, guidance)
ABI_FIELD(RadVideoGenDecl, guidance_default)
ABI_FIELD(RadVideoGenDecl, default_negative)
ABI_FIELD(RadVideoGenDecl, image_cond)
ABI_FIELD(RadVideoGenDecl, image_crf)
ABI_FIELD(RadVideoGenDecl, text_left_pad)
ABI_FIELD(RadVideoGenDecl, audio_streams)
ABI_FIELD(RadVideoGenDecl, upscale_exact)
ABI_FIELD(RadVideoGenDecl, duration_out)
ABI_FIELD(RadVideoGenDecl, duration_min)
ABI_FIELD(RadVideoGenDecl, duration_max)
ABI_FIELD(RadVideoGenDecl, duration_dtype)
ABI_FIELD(RadVideoGenDecl, decoders)
ABI_FIELD(RadVideoGenDecl, decoder_max_area)
ABI_FIELD(RadVideoGenDecl, max_ref_images)
ABI_FIELD(RadVideoGenDecl, max_ref_videos)
ABI_FIELD(RadVideoGenDecl, max_ref_audios)
ABI_FIELD(RadVideoGenDecl, max_enc_frames)
ABI_FIELD(RadVideoGenDecl, max_enc_side)
ABI_FIELD(RadVideoGenDecl, max_enc_samples)
ABI_FIELD(RadVideoGenDecl, enc_ratio)
ABI_FIELD(RadVideoGenDecl, max_mod_cells)
ABI_STRUCT(RadVideoGeom)
ABI_FIELD(RadVideoGeom, n_text)
ABI_FIELD(RadVideoGeom, frames)
ABI_FIELD(RadVideoGeom, lat_frames)
ABI_FIELD(RadVideoGeom, lat_h)
ABI_FIELD(RadVideoGeom, lat_w)
ABI_FIELD(RadVideoGeom, n_audio)
ABI_STRUCT(RadVocabHeader)
ABI_FIELD(RadVocabHeader, kind)
ABI_FIELD(RadVocabHeader, n_tokens)
ABI_FIELD(RadVocabHeader, n_merges)
ABI_FIELD(RadVocabHeader, n_steps)
ABI_FIELD(RadVocabHeader, tok_text_off)
ABI_FIELD(RadVocabHeader, tok_score_off)
ABI_FIELD(RadVocabHeader, tok_type_off)
ABI_FIELD(RadVocabHeader, merge_off)
ABI_FIELD(RadVocabHeader, step_off)
ABI_FIELD(RadVocabHeader, bos)
ABI_FIELD(RadVocabHeader, eos)
ABI_FIELD(RadVocabHeader, eot)
ABI_FIELD(RadVocabHeader, pad_id)
ABI_FIELD(RadVocabHeader, unk)
ABI_FIELD(RadVocabHeader, sep)
ABI_FIELD(RadVocabHeader, add_bos)
ABI_FIELD(RadVocabHeader, add_eos)
ABI_FIELD(RadVocabHeader, chat_template)
ABI_FIELD(RadVocabHeader, flags)
ABI_FIELD(RadVocabHeader, reserved)
ABI_STRUCT(RadVocabStep)
ABI_FIELD(RadVocabStep, kind)
ABI_FIELD(RadVocabStep, flags)
ABI_FIELD(RadVocabStep, arg0)
ABI_FIELD(RadVocabStep, arg1)
ABI_FIELD(RadVocabStep, iarg)
ABI_STRUCT(RadWeightDecl)
ABI_FIELD(RadWeightDecl, dtype)
ABI_FIELD(RadWeightDecl, rank)
ABI_FIELD(RadWeightDecl, shape)
ABI_FIELD(RadWeightDecl, access)
ABI_FIELD(RadWeightDecl, shard)
ABI_FIELD(RadWeightDecl, group)
ABI_FIELD(RadWeightDecl, optional)
ABI_FIELD(RadWeightDecl, n_row_parts)
ABI_FIELD(RadWeightDecl, row_parts)
ABI_FIELD(RadWeightDecl, source)
ABI_FIELD(RadWeightDecl, planes)
ABI_STRUCT(RadWeightGroup)
ABI_FIELD(RadWeightGroup, layer)
ABI_FIELD(RadWeightGroup, expert)
ABI_FIELD(RadWeightGroup, slot)
ABI_STRUCT(RadYarn)
ABI_FIELD(RadYarn, factor)
ABI_FIELD(RadYarn, low)
ABI_FIELD(RadYarn, high)
ABI_FIELD(RadYarn, magnitude)
ABI_STRUCT(RadMtpCoupleDraw)
ABI_FIELD(RadMtpCoupleDraw, seed)
ABI_FIELD(RadMtpCoupleDraw, base)
ABI_FIELD(RadMtpCoupleDraw, seq)
ABI_FIELD(RadMtpCoupleDraw, card)
ABI_FIELD(RadMtpCoupleDraw, mode)
ABI_STRUCT(RadMtpCoupleState)
ABI_FIELD(RadMtpCoupleState, draw)
ABI_FIELD(RadMtpCoupleState, pos)
ABI_FIELD(RadMtpCoupleState, status)
ABI_FIELD(RadMtpCoupleState, round)
ABI_FIELD(RadMtpCoupleState, x)
ABI_FIELD(RadMtpCoupleState, count)
ABI_FIELD(RadMtpCoupleState, ids)
ABI_FIELD(RadMtpCoupleState, q)
+1562 -344
View File
File diff suppressed because it is too large. Load diff
+102
View File
@@ -0,0 +1,102 @@
/* rad_clef.h -- the words a clef request hands its head (RadBatch::plugin_words).
*
* clef's joint schema head (arch/common/rad_block_clef.h) reads more of a request than its
* tokens: which prompt positions hold each question's instructions and each option's text, each
* option's token ids (the lm_head rows it averages), and each question's type. The server lays
* them out with the functions below, in the forms the head's kernels read (a cu_seqlens here, a
* gather index there), and the engine carries them to the plugin as one range of int32 words.
* Both sides include this header, so the layout is stated once.
*
* Plain C, like every abi/ header: the plugin is built apart from the engine.
*/
#ifndef RAD_CLEF_H
#define RAD_CLEF_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* The bounds the head's buffers are declared at. A request past one is refused by the server. */
enum {
RAD_CLEF_MAX_QUESTIONS = 64,
RAD_CLEF_MAX_OPTIONS = 512, /* every question's options together */
RAD_CLEF_MAX_LEX = 8192, /* every option's tokens together */
/* Prompt tokens. The head gathers every row of a prompt into buffers of its own, so this,
* not the deployment's context, sizes them: at the model's own 262144 they would take
* 4.5 GiB of the card for prompts that never pass a fifth of it. */
RAD_CLEF_MAX_PROMPT = 32768
};
/* The header: word 0 is the engine's (RadBatch::plugin_words), the rest the counts the layout is
* computed from. */
enum {
RAD_CLEF_W_ROW = 0, /* the sequence's logits row this step, written by the engine */
RAD_CLEF_W_N = 1, /* prompt tokens */
RAD_CLEF_W_Q = 2, /* questions */
RAD_CLEF_W_O = 3, /* options, every question together, in head order */
RAD_CLEF_W_L = 4, /* option tokens, every option together */
RAD_CLEF_W_S = 5, /* segments the prompt is cut into at every span's edges */
RAD_CLEF_HDR = 8
};
/* Where each array starts, in words from the range's start. Every array is int32. */
typedef struct RadClefWords {
int32_t n, q, o, l, s;
int32_t seg_cu; /* [s + 1]: a partition of [0, n) with a boundary at every span's edges */
int32_t q_seg; /* [q]: the segment holding each question's instructions */
int32_t o_seg; /* [o]: the segment holding each option's text */
int32_t o_q; /* [o]: each option's question */
int32_t opt_cu; /* [q + 1]: each question's options, consecutive */
int32_t type; /* [q]: 0 noul, 1 choice, 2 score */
int32_t lex_cu; /* [o + 1]: each option's tokens in lex_ids, consecutive */
int32_t lex_ids; /* [l]: the option tokens, as the prompt holds them */
int32_t last; /* [1]: n - 1, the prompt's last position */
int32_t cu_q; /* [2]: {0, q} */
int32_t cu_o; /* [2]: {0, o} */
int32_t cu_k; /* [2]: {0, n} */
int32_t total; /* words in all */
} RadClefWords;
static inline RadClefWords rad_clef_words_layout(int32_t n, int32_t q, int32_t o, int32_t l,
int32_t s) {
RadClefWords w;
int32_t at = RAD_CLEF_HDR;
w.n = n; w.q = q; w.o = o; w.l = l; w.s = s;
w.seg_cu = at; at += s + 1;
w.q_seg = at; at += q;
w.o_seg = at; at += o;
w.o_q = at; at += o;
w.opt_cu = at; at += q + 1;
w.type = at; at += q;
w.lex_cu = at; at += o + 1;
w.lex_ids = at; at += l;
w.last = at; at += 1;
w.cu_q = at; at += 2;
w.cu_o = at; at += 2;
w.cu_k = at; at += 2;
w.total = at;
return w;
}
/* The layout a range of words carries, read off its header. */
static inline RadClefWords rad_clef_words_read(const int32_t* words) {
return rad_clef_words_layout(words[RAD_CLEF_W_N], words[RAD_CLEF_W_Q], words[RAD_CLEF_W_O],
words[RAD_CLEF_W_L], words[RAD_CLEF_W_S]);
}
/* The most words a request can carry within the bounds: what the head declares
* (rad_declare_plugin_words). A span's two edges each cut the prompt, so the segments are at most
* two a span plus one. */
static inline int32_t rad_clef_max_words(void) {
const int32_t spans = RAD_CLEF_MAX_QUESTIONS + RAD_CLEF_MAX_OPTIONS;
return rad_clef_words_layout(0, RAD_CLEF_MAX_QUESTIONS, RAD_CLEF_MAX_OPTIONS,
RAD_CLEF_MAX_LEX, 2 * spans + 1).total;
}
#ifdef __cplusplus
}
#endif
#endif /* RAD_CLEF_H */
+18 -11
View File
@@ -1,10 +1,9 @@
/* rad_device.h -- the device layer. Thin on purpose: everything above it is written once, and
* every backend implements exactly the small set of calls below.
/* rad_device.h -- the device layer. Deliberately thin: everything above it is written once, and
* every backend implements the small set of calls below.
*
* The host backend is not a toy. It is what lets the core, the scheduler, the planner, the
* tokeniser, the server and libref be built and tested on a machine with no accelerator, and it
* is the same code path RAD_DOMAIN_HOST kernels run on when the planner puts a layer on the CPU
* (spec §5.1).
* The host backend is a full backend. It lets the core, scheduler, planner, tokeniser, server and
* libref be built and tested without an accelerator, and RAD_DOMAIN_HOST kernels run on it when the
* planner puts a layer on the CPU (spec §5.1).
*/
#ifndef RAD_DEVICE_H
#define RAD_DEVICE_H
@@ -19,12 +18,11 @@ typedef void* RadEvent;
enum { RAD_MEM_DEVICE = 0, RAD_MEM_HOST_PINNED = 1, RAD_MEM_HOST = 2, RAD_MEM_HOST_MAPPED = 3 };
/* WHAT THE ENGINE KNOWS ABOUT A DEVICE, AND IT IS ONLY THIS. Nothing above this layer names a
* vendor, a product or an instruction set: the scheduler, the planner and the budgets are written
* against these fields and learn the machine from them at run time. A kernel library is where
* hardware knowledge belongs, and it declares which devices it serves.
/* Everything the engine knows about a device. Nothing above this layer names a vendor, product or
* instruction set: the scheduler, planner and budgets learn the machine from these fields at run
* time. Hardware knowledge belongs in kernel libraries, which declare the devices they serve.
*
* Every field carries whatever the backend reports, in the backend's own vocabulary. */
* Every field carries what the backend reports, in the backend's own vocabulary. */
typedef struct RadDeviceProps {
char name[128]; /* the product name, for logs and for the tuning cache's key */
char arch[32]; /* the backend's name for the architecture, with any feature
@@ -38,12 +36,21 @@ typedef struct RadDeviceProps {
int64_t lds_bytes; /* per-workgroup scratch, for occupancy arithmetic only */
int supports_p2p;
int is_host_backend; /* 1 when there is no accelerator behind this device */
int unified; /* 1 when device memory is host memory (integrated graphics):
* one address space and one RAM ledger -- the device pools and
* the pinned host pools are charged against the same bytes,
* KV tiers collapse to resident, and a copy whose source and
* destination are the same address is a no-op */
} RadDeviceProps;
int rad_dev_count(void);
int rad_dev_set(int device);
int rad_dev_props(int device, RadDeviceProps* out);
int rad_dev_enable_peer(int self, int peer);
/* 1 when the driver reports that `self` can reach `peer`'s memory, 0 when not, negative on a
* device error. A tool that declares a multi-rank graph sets the device.p2p fact from it, as the
* engine does (RAD_FACT_P2P). */
int rad_dev_peer_access(int self, int peer);
void* rad_dev_alloc(int64_t bytes, int kind);
void rad_dev_free(void* p, int kind);
+69 -33
View File
@@ -1,24 +1,24 @@
/* rad_encoding.h -- what a stored weight's numbers ARE, independently of how any kernel wants them
/* rad_encoding.h -- what a stored weight's numbers are, independent of how any kernel wants them
* arranged. spec.md §4.1.
*
* An ENCODING is the code type, the codebook the codes index if any, the grouping of the scales,
* zero points and minimums over the weight, and the transform the weight went through before it
* was quantised. It is a property of the model: choosing one is lossy and can be expensive (GPTQ
* wants a calibration run), and changing one means quantising again. A LAYOUT -- fragment order, a
* scale carried in each row's tail, a nibble order that suits one unpack -- is a property of a
* kernel, lossless and cheap, and it is applied when the model loads (rad_abi.h). A container holds
* encodings only, so a kernel library can change every layout it has without a reconvert.
* An encoding is the code type, the codebook the codes index (if any), the grouping of the scales,
* zero points and minimums over the weight, and the transform applied before quantisation. It is a
* property of the model: choosing one is lossy and can be expensive (GPTQ needs a calibration
* run), and changing one means quantising again. A layout (fragment order, a scale carried in each
* row's tail, a nibble order that suits one unpack) is a property of a kernel, lossless and cheap,
* applied when the model loads (rad_abi.h). A container holds encodings only, so a kernel library
* can change any layout without a reconvert.
*
* AN ENCODING IS DATA RATHER THAN A NAME IN AN ENUM, so a quantiser plugin can invent one without
* the core learning about it: the core can size, slice and place any encoding from this struct
* alone, and it decodes every encoding of the one scheme it defines, "affine", which is wide enough
* to hold every format in common use -- per-channel and grouped integers of any width, block FP8,
* MXFP4/6/8, NVFP4, llama.cpp's legacy, K- and I-quants, AWQ's column scales, GPTQ's act-order
* permutation, Hadamard and Givens rotations.
* An encoding is data rather than an enum value, so a quantiser plugin can invent one without the
* core knowing it. The core can size, slice and place any encoding from this struct alone, and
* decodes every encoding of the one scheme it defines, "affine". That scheme covers the common
* formats: per-channel and grouped integers of any width, block FP8, MXFP4/6/8, NVFP4, llama.cpp's
* legacy, K- and I-quants, AWQ's column scales, GPTQ's act-order permutation, Hadamard and Givens
* rotations.
*
* ===================================================================== PLANES
*
* An encoding is up to RAD_ENC_MAX_PLANES planes, each a dense ROW-MAJOR array of one core dtype.
* An encoding is up to RAD_ENC_MAX_PLANES planes, each a dense row-major array of one core dtype.
* A plane is one of two kinds:
*
* TILED it covers the weight. A weight of logical shape [d0, ..., dn] is seen as [rows, cols]
@@ -30,25 +30,24 @@
* TABLE it does not: a codebook, a lattice grid, a rotation's parameters. Its extents are its
* own, [extent0 x extent1], and every slice of the weight carries all of it.
*
* SUB-BYTE AND ODD-WIDTH ELEMENTS ARE A BIT STREAM ALONG THE ROW, lowest bits first: element j of a
* b-bit row occupies bits [j*b, (j+1)*b) counted from bit 0 of the row's first byte, so two 4-bit
* codes share a byte with element 0 in bits 0-3, and a 3-bit code may straddle a byte. Every row
* starts on a byte. That is the order a reference implementation and a person reading a hex dump
* assume; a kernel that wants its nibbles permuted for its own unpack does it in its relayout.
* Sub-byte and odd-width elements are a bit stream along the row, lowest bits first: element j of a
* b-bit row occupies bits [j*b, (j+1)*b) from bit 0 of the row's first byte, so two 4-bit codes
* share a byte with element 0 in bits 0-3, and a 3-bit code may straddle a byte. Every row starts
* on a byte. A kernel that wants its nibbles permuted for its own unpack does so in its relayout.
*
* ===================================================================== THE AFFINE SCHEME
*
* The planes are found by ROLE, and only "codes" is required. A weight element decodes as
* The planes are found by role, and only "codes" is required. A weight element decodes as
*
* q = code codes is TILED; its block is [1 x 1] -- one code a value -- or
* [1 x V] with a "grid", one code a V-vector
* q = grid[code][k] grid TABLE [entries x V]: a VECTOR codebook (the IQ2/IQ3/IQ1
* q = grid[code][k] grid TABLE [entries x V]: a vector codebook (the IQ2/IQ3/IQ1
* lattices); value k of the code's V-vector
* q = table[code] table TABLE [1 x entries]: a SCALAR codebook (IQ4_NL)
* q = table[code] table TABLE [1 x entries]: a scalar codebook (IQ4_NL)
* q = -q if the sign bit is set signs TILED u1 [1 x 1], one bit a value
* q = q - zero zero TILED; an integer or real offset in the CODE's domain
* q = q - zero zero TILED; an integer or real offset in the code's domain
* v = q * scale * scale.1 * ... scale, scale.1, ... TILED: every scale level, multiplied
* v = v - min * min.1 * ... min, min.1, ... TILED: a minimum in the VALUE's domain
* v = v - min * min.1 * ... min, min.1, ... TILED: a minimum in the value's domain
* w = v . T^-1 the transform, per row, over the columns (below)
*
* so NVFP4 is fp4 codes, an e4m3 scale per [1 x 16] and an f32 scale.1 per tensor; Q4_K is u4
@@ -59,20 +58,31 @@
* ===================================================================== TRANSFORMS
*
* `transform` names what was done to each row before it was quantised: the stored row is v = w . T,
* so a kernel computes <w, x> = <v, x . T^-T> and transforms its ACTIVATION, never the weight.
* so a kernel computes <w, x> = <v, x . T^-T> and transforms its activation, never the weight.
*
* "" none.
* "fwhtN" T = H_N / N block-diagonally over groups of N columns, H_N the UNNORMALISED
* "fwhtN" T = H_N / N block-diagonally over groups of N columns, H_N the unnormalised
* Sylvester Hadamard (entries +-1, H H = N I). Decoding applies H_N once (w = H v);
* the activation is rotated by H_N, unnormalised, with nothing folded at runtime --
* the activation is rotated by the unnormalised H_N with nothing folded at runtime:
* the 1/N lives in the stored scale.
* "perm" T is a column permutation: TABLE "t.perm" i32 [1 x cols], v[j] = w[perm[j]] --
* GPTQ's act-order, which quantises the columns in a different order than they sit.
* GPTQ's act-order, which quantises the columns in a different order than stored.
* "givens" T = D . G_1 . ... . G_S: D = diag(t.scale) when TABLE "t.scale" f32 [1 x cols]
* is present, and G_s a stage of disjoint Givens rotations -- TABLE "t.pairs" i32
* [S x cols] lists stage s's pairs as (pairs[s][2p], pairs[s][2p+1]), TABLE "t.angle"
* f32 [S x cols/2] their angles, and a row vector's pair (a, b) at angle t becomes
* (a cos t + b sin t, b cos t - a sin t). ParoQuant's scaled pairwise rotation.
* A weight whose row parts were rotated independently (a fused gate_up, a fused
* q|k|v: each projection has its own rotation) carries P parts: TABLE "t.part" i32
* [1 x P] holds the end row (exclusive) of each part, and the other tables stack the
* parts in order -- t.pairs and t.angle S rows a part (P*S rows), t.scale one row a
* part (P rows). Without "t.part" the weight is one part. The stages of a part are
* applied in table order, and a part's pairs address columns of the whole row.
* TABLE "t.dense" f16 [P * cols/128 x 128*128], where a weight carries it, is the same
* rotation composed: row p * (cols/128) + g holds part p's stages over the 128 columns
* of group g as one matrix, element j * 128 + i the output j for the unit input e_i,
* composed exactly (f64) and rounded to f16. It is stored because a kernel that
* applies the rotation as a matrix must not compute one at load (rad_abi.h).
*
* Pure C, header-only, like the rest of abi/.
*/
@@ -213,8 +223,17 @@ static inline int64_t rad_enc_fwht(const RadEncoding* e) {
return (int64_t)n;
}
/* Byte-for-byte equality, which is what two encodings agreeing means: the strings are
* zero-padded by construction, so there is nothing a memcmp could see that a reader cannot. */
/* The number of independently rotated row parts of a "givens" weight: the width of its "t.part"
* table, or 1 without one. 0 when the table is malformed. */
static inline int64_t rad_enc_givens_parts(const RadEncoding* e) {
const int i = rad_enc_find(e, "t.part");
if (i < 0) return 1;
return e->plane[i].kind == RAD_PLANE_TABLE && e->plane[i].extent[0] == 1 &&
e->plane[i].extent[1] >= 1 ? e->plane[i].extent[1] : 0;
}
/* Byte-for-byte equality. Valid because the strings are always zero-padded, so memcmp sees only
* meaningful bytes. */
static inline int rad_enc_equal(const RadEncoding* a, const RadEncoding* b) {
return a && b && memcmp(a, b, sizeof *a) == 0;
}
@@ -329,8 +348,25 @@ static inline int rad_enc_valid(const RadEncoding* e) {
if (!t[0]) return 1;
if (!strncmp(t, "fwht", 4)) return rad_enc_fwht(e) > 0;
if (!strcmp(t, "perm")) return rad_enc_find(e, "t.perm") > 0;
if (!strcmp(t, "givens"))
return rad_enc_find(e, "t.pairs") > 0 && rad_enc_find(e, "t.angle") > 0;
if (!strcmp(t, "givens")) {
const int ip = rad_enc_find(e, "t.pairs"), ia = rad_enc_find(e, "t.angle");
const int is = rad_enc_find(e, "t.scale");
const int64_t np = rad_enc_givens_parts(e);
if (ip <= 0 || ia <= 0 || np < 1) return 0;
if (e->plane[ip].kind != RAD_PLANE_TABLE || e->plane[ia].kind != RAD_PLANE_TABLE) return 0;
if (e->plane[ip].extent[0] % np || e->plane[ia].extent[0] != e->plane[ip].extent[0]) return 0;
if (e->plane[ia].extent[1] * 2 != e->plane[ip].extent[1]) return 0;
if (is > 0 && (e->plane[is].kind != RAD_PLANE_TABLE || e->plane[is].extent[0] != np ||
e->plane[is].extent[1] != e->plane[ip].extent[1])) return 0;
{
const int id = rad_enc_find(e, "t.dense");
if (id > 0 && (e->plane[id].kind != RAD_PLANE_TABLE || e->plane[id].dtype != RAD_F16 ||
e->plane[ip].extent[1] % 128 ||
e->plane[id].extent[0] != np * (e->plane[ip].extent[1] / 128) ||
e->plane[id].extent[1] != 128 * 128)) return 0;
}
return 1;
}
return 0;
}
+31 -11
View File
@@ -1,6 +1,6 @@
/* rad_format.h -- the .rad container (spec.md §4.2).
*
* canonical, not kernel-shaped -- an entry is a LOGICAL weight holding the planes of its
* canonical, not kernel-shaped -- an entry is a logical weight holding the planes of its
* encoding (rad_encoding.h), row-major; no kernel library
* is named anywhere in the file, and the kernel that reads a
* weight rearranges it at load (spec §4.3)
@@ -13,8 +13,8 @@
* Little-endian only. Every offset is from the start of the file. Every string is an offset into
* the string blob, so the directory is fixed-stride and mmap-walkable without a parse.
*
* THERE IS ONE VERSION. A file in any other is refused with the instruction to convert again: the
* product has no installed base, and a second reader would be a second set of invariants. */
* There is one format version. A file in any other is refused with an instruction to convert
* again, so there is a single reader with a single set of invariants. */
#ifndef RAD_FORMAT_H
#define RAD_FORMAT_H
@@ -56,9 +56,16 @@ typedef struct RadFileHeader {
uint64_t prof_off, prof_count; /* RadFileProfile[] -- expert popularity */
uint64_t data_off, data_bytes; /* the blob; RAD_ALIGN_POOL-aligned */
/* reserved[RAD_HDR_AUX_VOCAB_OFF] and reserved[RAD_HDR_AUX_VOCAB_BYTES] place a second vocab
* section, laid out as the first (RadVocabHeader + its payload, its strings in the one string
* blob): a tokenizer a generator reads its prompt through beside the model's own
* (RadGeneratorDecl::aux_tokens). Both zero when there is none, as in a file written before
* the section existed; the rest are zero. */
uint64_t reserved[8];
} RadFileHeader;
enum { RAD_HDR_AUX_VOCAB_OFF = 0, RAD_HDR_AUX_VOCAB_BYTES = 1 };
/* ------------------------------------------------------------------ metadata */
typedef struct RadFileKV {
rad_stroff key;
@@ -74,7 +81,7 @@ typedef struct RadFileKV {
enum { RAD_KV_F64 = 100 };
/* ------------------------------------------------------------------ weight directory */
/* One LOGICAL weight: what a declaration's `source` names (RadWeightDecl). Fixed stride, so an
/* One logical weight: what a declaration's `source` names (RadWeightDecl). Fixed stride, so an
* expert's address inside a layer is base + id*stride and no table is walked on the critical
* path. */
typedef struct RadFileEntry {
@@ -84,7 +91,7 @@ typedef struct RadFileEntry {
uint32_t enc; /* index into the encoding table */
uint32_t rank;
int64_t shape[RAD_MAX_RANK]; /* the LOGICAL shape */
int64_t shape[RAD_MAX_RANK]; /* the logical shape */
int32_t layer; /* RadWeightGroup, flattened: the movement unit */
int32_t expert;
@@ -105,9 +112,9 @@ typedef struct RadFilePlane {
} RadFilePlane;
/* ------------------------------------------------------------------ expert profile */
/* Derived from the imatrix's activation counts. A WARM START, not a policy (spec §5.3): what a
* calibration set routes to is not what decoding routes to, so this is worth a small improvement
* in residency hit rate over starting cold and no more. */
/* Derived from the imatrix's activation counts. A warm start, not a policy (spec §5.3): a
* calibration set routes differently from decoding, so this gives only a small residency hit-rate
* gain over starting cold. */
typedef struct RadFileProfile {
int32_t layer;
int32_t expert;
@@ -116,17 +123,25 @@ typedef struct RadFileProfile {
} RadFileProfile;
/* ------------------------------------------------------------------ vocab */
/* rad-convert interprets tokenizer.json properly and bakes the result here, rather than hashing
* the file against a hardcoded enum the way llama.cpp does (spec §12). */
/* rad-convert interprets tokenizer.json and bakes the result here, rather than hashing the file
* against a hardcoded enum as llama.cpp does (spec §12). */
enum { RAD_TOK_BPE = 1, RAD_TOK_UNIGRAM = 2, RAD_TOK_WORDPIECE = 3, RAD_TOK_RWKV = 4 };
/* Normaliser / pre-tokeniser / decoder steps, in declared order. */
enum {
RAD_NORM_NFC = 1, RAD_NORM_NFKC = 2, RAD_NORM_NFD = 3, RAD_NORM_NFKD = 4,
RAD_NORM_LOWERCASE = 5, RAD_NORM_STRIP = 6, RAD_NORM_REPLACE = 7, RAD_NORM_PREPEND = 8,
RAD_NORM_PRECOMPILED = 9,
RAD_PRE_BYTELEVEL = 32, RAD_PRE_SPLIT = 33, RAD_PRE_METASPACE = 34,
RAD_PRE_WHITESPACE = 35, RAD_PRE_PUNCTUATION = 36, RAD_PRE_DIGITS = 37,
RAD_PRE_BYTE_FALLBACK = 38,
/* BPE's end-of-word suffix (arg0, CLIP's "</w>"): a word's last symbol carries it, so the
* merges and the vocabulary tell a word's end from its middle. */
RAD_PRE_END_OF_WORD = 39,
/* An added token matched in the normalised text rather than the raw one (tokenizers'
* `normalized`): arg0 its spelling, iarg its id. Cut out after the normalisers and before
* the other pre-tokenisers. */
RAD_PRE_ADDED_NORMALIZED = 40,
RAD_DEC_BYTELEVEL = 64, RAD_DEC_METASPACE = 65, RAD_DEC_REPLACE = 66,
RAD_DEC_STRIP = 67, RAD_DEC_FUSE = 68, RAD_DEC_BYTE_FALLBACK = 69
};
@@ -152,9 +167,14 @@ typedef struct RadVocabHeader {
int32_t bos, eos, eot, pad_id, unk, sep;
uint32_t add_bos, add_eos;
rad_stroff chat_template;
uint64_t reserved[4];
uint64_t flags; /* RAD_VOCAB_*; zero in a file written before the field existed */
uint64_t reserved[3];
} RadVocabHeader;
/* BPE: a pre-token that is already a vocabulary entry is emitted whole instead of merged
* (tokenizers' `ignore_merges`). LFM2's vocabulary sets it. */
enum { RAD_VOCAB_IGNORE_MERGES = 1u << 0 };
enum { RAD_TT_NORMAL = 1, RAD_TT_UNKNOWN = 2, RAD_TT_CONTROL = 3,
RAD_TT_USER_DEFINED = 4, RAD_TT_BYTE = 6 };
+44
View File
@@ -0,0 +1,44 @@
/* rad_laya.h -- the words a Laya request hands its plugin (RadBatch::plugin_words), and the pooled
* row the plugin answers in.
*
* Laya (arch/laya) reads one sequence a question, `[CLS] <type> question: <instructions> [SEP]
* [MASK] opt0 [MASK] opt1 ... [SEP] <state> [SEP]`, and scores each option at its [MASK]. The
* server builds the sequence (core/server/laya.cpp) and hands the plugin what the tokens do not
* say: the question's type, which picks the head's type embedding, and where the markers are. The
* plugin answers in the sequence's pooled row: one logit an option, in marker order.
*
* Plain C, like every abi/ header: the plugin is built apart from the engine.
*/
#ifndef RAD_LAYA_H
#define RAD_LAYA_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
enum {
/* Options a question, llama.cpp's bound for laya. The pooled row holds one logit an option. */
RAD_LAYA_MAX_OPTIONS = 255,
RAD_LAYA_POOLED = 256
};
/* The question types in the order of the head's type embedding rows (laya's QTYPES). */
enum { RAD_LAYA_CHOICE = 0, RAD_LAYA_SCORE = 1, RAD_LAYA_NOUL = 2 };
/* A sequence's words. Word 0 is the engine's (RadBatch::plugin_words). */
enum {
RAD_LAYA_W_ROW = 0, /* written by the engine */
RAD_LAYA_W_N = 1, /* the sequence's tokens */
RAD_LAYA_W_TYPE = 2, /* RAD_LAYA_CHOICE, RAD_LAYA_SCORE or RAD_LAYA_NOUL */
RAD_LAYA_W_K = 3, /* options, so markers */
RAD_LAYA_W_MARKERS = 4, /* [k]: each option's [MASK] position in the sequence, in order */
RAD_LAYA_MAX_WORDS = RAD_LAYA_W_MARKERS + RAD_LAYA_MAX_OPTIONS
};
#ifdef __cplusplus
}
#endif
#endif /* RAD_LAYA_H */
+75
View File
@@ -0,0 +1,75 @@
#ifndef RAD_PHILOX_H
#define RAD_PHILOX_H
/* Counter-based Gaussian noise, the single definition every kernel library uses, so an image's
* starting latent depends only on its seed: not on the batch it shares a pass with, the rank
* count, or the order its rows are visited in.
*
* Element e of a seed's stream is Philox4x32-10 at counter (e / 4, 0) keyed by the 64-bit seed,
* its four words made uniform in (0, 1) as ((w >> 8) + 0.5) * 2^-24 and paired by Box-Muller --
* words 0 and 1 give elements 4g and 4g+1 (r cos t, r sin t), words 2 and 3 give 4g+2 and 4g+3.
* f32 throughout. A library's libm may differ from another's in the last place of log, cos and
* sin, so two libraries agree to a tolerance and each agrees with itself exactly. */
#include <stdint.h>
#include <math.h>
#if defined(__HIPCC__)
#define RAD_PHILOX_HD __host__ __device__ __forceinline__
#else
#define RAD_PHILOX_HD static inline
#endif
RAD_PHILOX_HD void rad_philox4x32_10(uint32_t c[4], uint32_t k0, uint32_t k1) {
const uint32_t M0 = 0xD2511F53u, M1 = 0xCD9E8D57u, W0 = 0x9E3779B9u, W1 = 0xBB67AE85u;
for (int r = 0; r < 10; ++r) {
const uint64_t p0 = (uint64_t)M0 * c[0], p1 = (uint64_t)M1 * c[2];
const uint32_t hi0 = (uint32_t)(p0 >> 32), lo0 = (uint32_t)p0;
const uint32_t hi1 = (uint32_t)(p1 >> 32), lo1 = (uint32_t)p1;
const uint32_t n0 = hi1 ^ c[1] ^ k0, n2 = hi0 ^ c[3] ^ k1;
c[0] = n0; c[1] = lo1; c[2] = n2; c[3] = lo0;
k0 += W0;
k1 += W1;
}
}
/* Element `e` of the standard-normal stream of `seed`. */
RAD_PHILOX_HD float rad_philox_normal(uint64_t seed, uint64_t e) {
const uint64_t g = e >> 2;
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), 0u, 0u };
rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32));
const int j = (int)(e & 3u);
const uint32_t wa = c[(j >> 1) * 2], wb = c[(j >> 1) * 2 + 1];
const float ua = ((float)(wa >> 8) + 0.5f) * (1.0f / 16777216.0f);
const float ub = ((float)(wb >> 8) + 0.5f) * (1.0f / 16777216.0f);
const float r = sqrtf(-2.0f * logf(ua));
const float t = 6.28318530717958647692f * ub;
return (j & 1) ? r * sinf(t) : r * cosf(t);
}
/* Element `e` of the standard-normal stream (seed, stream): the counter's upper half is `stream`,
* so stream 0 is rad_philox_normal and each other value an independent stream of the same seed
* (an audio window's noise is stream 1 + its index). */
RAD_PHILOX_HD float rad_philox_normal_s(uint64_t seed, uint64_t stream, uint64_t e) {
const uint64_t g = e >> 2;
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream, (uint32_t)(stream >> 32) };
rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32));
const int j = (int)(e & 3u);
const uint32_t wa = c[(j >> 1) * 2], wb = c[(j >> 1) * 2 + 1];
const float ua = ((float)(wa >> 8) + 0.5f) * (1.0f / 16777216.0f);
const float ub = ((float)(wb >> 8) + 0.5f) * (1.0f / 16777216.0f);
const float r = sqrtf(-2.0f * logf(ua));
const float t = 6.28318530717958647692f * ub;
return (j & 1) ? r * sinf(t) : r * cosf(t);
}
/* Element `e` of the uniform stream (seed, stream), in (0, 1): word e % 4 of the counter
* (e / 4, stream) made uniform as the normal stream's words are. A sampler draws its pick from
* it. */
RAD_PHILOX_HD float rad_philox_uniform_s(uint64_t seed, uint64_t stream, uint64_t e) {
const uint64_t g = e >> 2;
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream, (uint32_t)(stream >> 32) };
rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32));
return ((float)(c[e & 3u] >> 8) + 0.5f) * (1.0f / 16777216.0f);
}
#endif /* RAD_PHILOX_H */
+197
View File
@@ -0,0 +1,197 @@
/* rad_planes.h -- the joined form of a weight operand that takes several planes, for kernels that
* read the planes as the container stores them. spec.md §4.3.
*
* A weight can be declared over several planes of one stored tensor (RadWeightDecl::planes:
* "scale,zero", "codes,table", or every plane of an fp8 lm head), and it reaches a kernel as one
* operand, so something has to say where each plane lies. A kernel that wants the planes
* rearranged for its own reads says so in its layout hook (rad_abi.h, RadLayoutFn). One that reads
* them unchanged uses this form instead:
*
* [header][entry 0][entry 1]... padded to RAD_PLANES_ALIGN
* plane 0 dense rows, padded to RAD_PLANES_ALIGN
* plane 1 ...
*
* The header and the entries describe each selected plane (its role, dtype, block, this rank's
* extents and where its bytes start), so a launch finds its planes from the operand alone, without
* the encoding. Each plane is the canonical bytes (rad_encoding.h), unchanged: the conversion is a
* copy and its inverse is one too.
*
* A library implements its layout, relayout and unrelayout hooks with the three functions below
* and reads at launch with rad_planes_find. Every library that uses this form stores the same bytes
* under the same tag, so two such libraries serving different bands of one op read one stored
* weight. A selection of one plane is not joined: rad_planes_layout declines it, and the weight is
* stored as it is.
*
* Pure C, header-only, like the rest of abi/.
*/
#ifndef RAD_PLANES_H
#define RAD_PLANES_H
#include "rad_abi.h"
#include "rad_encoding.h"
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
#define RAD_PLANES_TAG "rad.planes"
#define RAD_PLANES_MAGIC 0x534e4c50u /* "PLNS" */
enum { RAD_PLANES_ALIGN = 64 };
/* One selected plane. `offset` counts from the start of the joined bytes. */
typedef struct RadPlanesEntry {
char role[RAD_ENC_STR];
uint32_t dtype;
uint32_t kind; /* RAD_PLANE_TILED | RAD_PLANE_TABLE */
int64_t block[2]; /* the encoding's block (TILED) or extent (TABLE) */
int64_t rows, cols; /* this rank's extents of the plane, in its own elements */
int64_t row_bytes; /* rad_dtype_bytes(dtype, cols): every row starts on a byte */
int64_t offset;
} RadPlanesEntry;
typedef struct RadPlanesHeader {
uint32_t magic;
int32_t n_planes;
char transform[RAD_ENC_STR]; /* the encoding's, for a kernel that checks it */
int64_t bytes; /* the whole joined form, padding included */
} RadPlanesHeader;
static inline int64_t rad_planes_round(int64_t n) {
return (n + RAD_PLANES_ALIGN - 1) / RAD_PLANES_ALIGN * RAD_PLANES_ALIGN;
}
/* The joined form's entries for the planes a layout hook was handed, and its total size; -1 when
* the planes cannot be joined (no planes, more than RAD_ENC_MAX_PLANES, an index outside the
* encoding, or a plane with no byte size). */
static inline int64_t rad_planes_plan(const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n_planes, RadPlanesEntry* e) {
int64_t off;
int i;
if (!enc || !sel || !planes || n_planes < 1 || n_planes > RAD_ENC_MAX_PLANES) return -1;
off = rad_planes_round((int64_t)sizeof(RadPlanesHeader) +
(int64_t)n_planes * (int64_t)sizeof(RadPlanesEntry));
for (i = 0; i < n_planes; ++i) {
const RadEncPlane* p;
if (sel[i] < 0 || sel[i] >= enc->n_planes) return -1;
p = &enc->plane[sel[i]];
memset(&e[i], 0, sizeof e[i]);
memcpy(e[i].role, p->role, RAD_ENC_STR);
e[i].dtype = planes[i].dtype;
e[i].kind = p->kind;
e[i].block[0] = p->kind == RAD_PLANE_TABLE ? p->extent[0] : p->block[0];
e[i].block[1] = p->kind == RAD_PLANE_TABLE ? p->extent[1] : p->block[1];
e[i].rows = planes[i].rank >= 2 ? planes[i].shape[0] : 1;
e[i].cols = planes[i].rank >= 2 ? planes[i].shape[1]
: (planes[i].rank == 1 ? planes[i].shape[0] : 0);
e[i].row_bytes = rad_dtype_bytes(e[i].dtype, e[i].cols);
if (e[i].rows < 0 || e[i].row_bytes <= 0) return -1;
e[i].offset = off;
off = rad_planes_round(off + e[i].rows * e[i].row_bytes);
}
return off;
}
/* RadLayoutFn's answer for the joined form. RAD_E_UNSUPPORTED for a single plane, which is stored
* as it is. The stored dtype is the first plane's, so a launch that dispatches on the operand's
* dtype still sees the codes' (or the scale's) type; the stored shape is the byte count. */
static inline int rad_planes_layout(const RadEncoding* enc, const int* sel, const RadTensor* planes,
int n_planes, RadLayout* out) {
RadPlanesEntry e[RAD_ENC_MAX_PLANES];
int64_t bytes;
if (n_planes == 1) return RAD_E_UNSUPPORTED;
bytes = rad_planes_plan(enc, sel, planes, n_planes, e);
if (bytes < 0 || !out) return RAD_E_SHAPE;
memset(out, 0, sizeof *out);
out->tag = RAD_PLANES_TAG;
out->dtype = planes[0].dtype;
out->rank = 1;
out->shape[0] = bytes;
out->align = RAD_PLANES_ALIGN;
out->bytes = bytes;
return RAD_OK;
}
/* RadRelayoutFn: the header, the entries and each plane's rows, copied. The planes are dense, as
* the loader hands them. */
static inline int rad_planes_relayout(const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n_planes, void* dst,
int64_t dst_bytes) {
RadPlanesEntry e[RAD_ENC_MAX_PLANES];
RadPlanesHeader h;
uint8_t* d = (uint8_t*)dst;
int i;
const int64_t bytes = rad_planes_plan(enc, sel, planes, n_planes, e);
if (bytes < 0 || !dst || dst_bytes < bytes) return RAD_E_SHAPE;
memset(d, 0, (size_t)bytes);
memset(&h, 0, sizeof h);
h.magic = RAD_PLANES_MAGIC;
h.n_planes = n_planes;
memcpy(h.transform, enc->transform, RAD_ENC_STR);
h.bytes = bytes;
memcpy(d, &h, sizeof h);
memcpy(d + sizeof h, e, (size_t)n_planes * sizeof e[0]);
for (i = 0; i < n_planes; ++i) {
if (!planes[i].data && e[i].rows * e[i].row_bytes > 0) return RAD_E_INVAL;
if (e[i].rows * e[i].row_bytes > 0)
memcpy(d + e[i].offset, planes[i].data, (size_t)(e[i].rows * e[i].row_bytes));
}
return RAD_OK;
}
/* RadUnrelayoutFn: the planes back out of the joined form, into the buffers `planes` carry. */
static inline int rad_planes_unrelayout(const RadEncoding* enc, const int* sel, const void* src,
int64_t src_bytes, const RadTensor* planes, int n_planes) {
RadPlanesEntry e[RAD_ENC_MAX_PLANES];
const uint8_t* s = (const uint8_t*)src;
int i;
const int64_t bytes = rad_planes_plan(enc, sel, planes, n_planes, e);
if (bytes < 0 || !src || src_bytes < bytes) return RAD_E_SHAPE;
for (i = 0; i < n_planes; ++i) {
if (!planes[i].data && e[i].rows * e[i].row_bytes > 0) return RAD_E_INVAL;
if (e[i].rows * e[i].row_bytes > 0)
memcpy(planes[i].data, s + e[i].offset, (size_t)(e[i].rows * e[i].row_bytes));
}
return RAD_OK;
}
/* ================================================================== reading one at launch */
/* The joined form's header, or null when `base` does not hold one. */
static inline const RadPlanesHeader* rad_planes_header(const void* base) {
const RadPlanesHeader* h = (const RadPlanesHeader*)base;
if (!h || h->magic != RAD_PLANES_MAGIC || h->n_planes < 1 ||
h->n_planes > RAD_ENC_MAX_PLANES)
return 0;
return h;
}
/* Entry `i`, or null. */
static inline const RadPlanesEntry* rad_planes_entry(const void* base, int i) {
const RadPlanesHeader* h = rad_planes_header(base);
if (!h || i < 0 || i >= h->n_planes) return 0;
return (const RadPlanesEntry*)((const uint8_t*)base + sizeof(RadPlanesHeader)) + i;
}
/* The plane with this role: its bytes, and its entry through `out` when given; null when the
* joined form has no such plane. */
static inline const void* rad_planes_find(const void* base, const char* role,
const RadPlanesEntry** out) {
const RadPlanesHeader* h = rad_planes_header(base);
int i;
if (!h || !role) return 0;
for (i = 0; i < h->n_planes; ++i) {
const RadPlanesEntry* e = rad_planes_entry(base, i);
if (strncmp(e->role, role, RAD_ENC_STR) == 0) {
if (out) *out = e;
return (const uint8_t*)base + e->offset;
}
}
return 0;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* RAD_PLANES_H */
+136 -115
View File
@@ -2,32 +2,28 @@
*
* ===================================================================== WHY THIS FILE EXISTS
*
* A plugin is a shared object that exports the symbols in rad_abi.h and links NOTHING of
* radiance's. That boundary is fixed. What it leaves an author with, though, is the raw structs
* and nothing else -- so without this header every plugin arrives independently at the same dozen
* helpers: an optional-operand fetch, a parameter-with-default, a contiguity test, a row pitch,
* and f32<->bf16, f32<->f16 and f32<->fp8 conversions.
* A plugin exports the symbols in rad_abi.h and links nothing of radiance's, so it has only the
* raw structs. This header supplies the helpers every plugin would otherwise rewrite: an
* optional-operand fetch, parameters with defaults, row pitch, and f32<->bf16/f16/fp8
* conversions.
*
* Two of those are not merely a duplication of effort. The narrowing conversions define what a
* result IS: libref's contract is f32 accumulation, IEEE round-to-nearest-even, no FMA and
* no reassociation, and a plugin whose bf16 rounding truncates instead of rounding to even does
* not reproduce the reference and cannot be checked against it. That convention belongs in the
* ABI, stated once, not rediscovered per plugin. And the meaning of an ABSENT OPTIONAL OPERAND --
* a null RadTensor.data, not a short operand count -- is a rule you get wrong silently: read the
* operand after it and every weight in the model shifts by one.
* Two of them are contracts, not conveniences. The narrowing conversions define what a result is:
* libref's contract is f32 accumulation, IEEE round-to-nearest-even, no FMA and no reassociation,
* and a plugin whose bf16 rounding truncates cannot be checked against the reference. And an
* absent optional operand is a null RadTensor.data, not a short operand count; getting that wrong
* silently shifts every later operand by one.
*
* ===================================================================== WHAT IS AND IS NOT HERE
*
* Here: pure, total, header-only functions over the ABI's own types. Nothing allocates, nothing
* has state, nothing calls back into the core, and nothing may ever start.
* Here: pure, total, header-only functions over the ABI's own types. Nothing allocates, holds
* state or calls back into the core, and nothing may start to.
*
* Not here: anything that needs the core. A plugin that wants a device allocation, a stream or a
* builder handle calls the functions in rad_device.h / rad_builder.h / rad_runtime.h, which the
* host exports because it must -- those genuinely cannot be inlined, and the loader's ABI check
* is what keeps them honest.
* Not here: anything that needs the core. Device allocations, streams and builder handles come
* from rad_device.h / rad_builder.h / rad_runtime.h, which the host exports; the loader's ABI
* check covers them.
*
* This header is OPTIONAL. A plugin that includes only rad_abi.h is complete and correct; this
* is convenience and one shared definition of the rounding, not a requirement.
* This header is optional. A plugin that includes only rad_abi.h is complete; this is
* convenience plus one shared definition of the rounding.
*
* Pure C, like the rest of abi/. See spec.md 2.
*/
@@ -44,9 +40,8 @@ extern "C" {
/* ================================================================== parameters
*
* Two families, because a plugin is asked for things in two shapes. `launch` and `scratch` get a
* RadArgs; `layout`, `relayout`, `unrelayout` and `opd_shape` get a bare (const RadParam*, int)
* pair with no tensors at all. Both are the same lookup and neither should be written twice. */
* Two families: `launch` and `scratch` get a RadArgs; `layout`, `relayout`, `unrelayout` and
* `opd_shape` get a bare (const RadParam*, int) pair with no tensors. */
static inline const RadParam* rad_param_find(const RadParam* p, int n_p, const char* key) {
if (!p || !key) return 0;
@@ -55,27 +50,20 @@ static inline const RadParam* rad_param_find(const RadParam* p, int n_p, const c
return 0;
}
/* An int parameter, or `dflt` if the key is absent or is not an int.
/* An int parameter, or `dflt` if the key is absent or not an int.
*
* A RANGE is deliberately NOT accepted here. A ranged parameter is the one axis a declared op is
* bucketed over, and by the time a kernel runs it has been resolved to a value -- so a range
* arriving at a launch is a selection bug, and quietly returning its low bound would hide it. */
* A range is deliberately not accepted: by the time a kernel runs, the ranged axis has been
* resolved to a value, so a range reaching a launch is a selection bug that returning its low
* bound would hide. */
static inline long long rad_param_geti(const RadParam* p, int n_p, const char* key,
long long dflt) {
const RadParam* f = rad_param_find(p, n_p, key);
return (f && f->kind == RAD_P_INT) ? f->ival : dflt;
}
/* THE SAME PARAMETER READ BY A SHAPE HOOK RATHER THAN BY A LAUNCH, which is the one place a range
* is legitimate and must be read as its HIGH bound.
*
* `opd_shape` is called to size buffers BEFORE selection has collapsed anything: a tool asking
* "how big is this operand" over a banded op is describing the whole band, and the arena has to
* hold it. The low end fits inside the high end, so ihi is the answer and rad_param_geti's refusal
* -- correct for a launch, where a surviving range is a selection bug -- is wrong here.
*
* Anyone writing a shape hook needs this on the first one they write, which is why it belongs in
* the ABI rather than once per plugin. */
/* The same read for a shape hook, the one place a range is legitimate; it reads as its high
* bound. `opd_shape` sizes buffers before selection has collapsed anything, so over a banded op it
* describes the whole band, and the high end covers the low. */
static inline long long rad_param_getdim(const RadParam* p, int n_p, const char* key,
long long dflt) {
const RadParam* f = rad_param_find(p, n_p, key);
@@ -96,9 +84,8 @@ static inline double rad_param_getf(const RadParam* p, int n_p, const char* key,
return (f && f->kind == RAD_P_F64) ? f->dval : dflt;
}
/* The dtype a parameter names, parsed. RAD_DT_INVALID if the key is absent or unrecognised --
* which a kernel should treat as a refusal, because a dtype it cannot name is one it cannot
* read. */
/* The dtype a parameter names, parsed. RAD_DT_INVALID if the key is absent or unrecognised, which
* a kernel should treat as a refusal. */
static inline uint32_t rad_param_getdt(const RadParam* p, int n_p, const char* key) {
return rad_dtype_parse(rad_param_gets(p, n_p, key, 0));
}
@@ -121,31 +108,23 @@ static inline double rad_args_getf_or(const RadArgs* a, const char* key, double
/* ================================================================== operands
*
* THE ABSENT-OPERAND RULE, WHICH IS THE EASIEST THING IN THIS ABI TO GET WRONG.
* The absent-operand rule: an optional operand a call does not pass is a RadTensor whose `data`
* is null, not a shorter `n_t`. Operands are positional, so treating absence as a shorter array
* would read operand i+1 for operand i and produce wrong numbers without a fault.
*
* An optional operand a call does not pass is a RadTensor whose `data` is null -- NOT a shorter
* `n_t`. The distinction is load-bearing because operands are POSITIONAL: if a plugin treated
* absence as "the array is shorter" it would read operand i+1 where operand i was meant, and for
* a weight that means every weight after it is off by one. Nothing in the arithmetic would fault;
* the model would simply produce wrong numbers.
*
* So: one entry per schema operand, always, and this returns null for both spellings of absent --
* past the end, or present with no data. A caller that needs to tell those apart has a schema
* disagreement rather than an absent operand, and should say so. */
* There is always one entry per schema operand. This returns null both past the end and for a
* null `data`; a caller that sees the former has a schema disagreement, not an absent operand. */
static inline const RadTensor* rad_arg_in(const RadArgs* a, int i) {
if (!a || !a->t || i < 0 || i >= a->n_t) return 0;
return a->t[i].data ? &a->t[i] : 0;
}
/* THERE IS NO rad_arg_out, AND THAT IS THE ABI SPEAKING RATHER THAN AN OMISSION. RadArgs::t is a
* `const RadTensor*`: the DESCRIPTORS are const, and a kernel writes an output through the
* non-const `void* data` inside one. So an output operand is fetched exactly like an input and
* the constness a caller sees is the same either way. A separate accessor would have to cast the
* descriptor's constness away and would be advertising a promise the ABI does not make. */
/* There is deliberately no rad_arg_out. RadArgs::t is a `const RadTensor*`: the descriptors are
* const, and a kernel writes an output through the non-const `void* data` inside one, so outputs
* are fetched with rad_arg_in too. */
/* Are the first `n` operands all present? The usual opening line of a launch, where the required
* ones are a prefix. */
/* Are the first `n` operands all present? For a launch whose required operands are a prefix. */
static inline int rad_args_have(const RadArgs* a, int n) {
for (int i = 0; i < n; ++i) if (!rad_arg_in(a, i)) return 0;
return 1;
@@ -154,8 +133,8 @@ static inline int rad_args_have(const RadArgs* a, int n) {
/* ================================================================== tensor shape helpers */
/* [rows..., K] flattened to (M, K): every leading axis is a row count and only the last is
* structural. This is what a kernel that owns whole rows -- one workgroup per row -- wants.
* Returns 0 on a rank-0 tensor. */
* structural, as a row-owning kernel (one workgroup per row) wants. Returns 0 on a rank-0
* tensor. */
static inline int64_t rad_tensor_rows(const RadTensor* t) {
if (!t || t->rank == 0) return 0;
int64_t m = 1;
@@ -167,36 +146,32 @@ static inline int64_t rad_tensor_lastdim(const RadTensor* t) {
return (t && t->rank > 0) ? t->shape[t->rank - 1] : 0;
}
/* The element distance between consecutive rows. For a contiguous tensor this is the last extent;
* for a strided one it is the stride of the second-to-last axis, which is the pitch a row-owning
* kernel has to honour. Strides are in ELEMENTS, not bytes (rad_types.h). */
/* The element distance between consecutive rows: the stride of the second-to-last axis (the last
* extent when contiguous). Strides are in elements, not bytes (rad_types.h). */
static inline int64_t rad_tensor_row_pitch(const RadTensor* t) {
if (!t || t->rank == 0) return 0;
if (t->rank == 1) return t->shape[0];
return t->stride[t->rank - 2];
}
/* Is `p` aligned to `bytes`? Kernels that issue wide loads need this and the ABI does not promise
* it -- alignment is one of the things a constraint row cannot express, so it is checked in the
* entry point (rad_types.h: constraints are necessary, not sufficient). */
/* Is `p` aligned to `bytes`? The ABI does not promise alignment and a constraint row cannot
* express it, so a kernel issuing wide loads checks it in the entry point (rad_types.h). */
static inline int rad_ptr_aligned(const void* p, int64_t bytes) {
return bytes > 0 && ((uintptr_t)p % (uintptr_t)bytes) == 0;
}
/* ================================================================== narrowing conversions
*
* THESE DEFINE WHAT A RESULT IS, so they are stated once here rather than per plugin.
* These define what a result is, so they are stated once here.
*
* libref's contract -- and therefore the definition every kernel is checked against -- is
* f32 accumulation, IEEE round-to-nearest-ties-to-even, no fused multiply-add and no
* reassociation. `-ffp-contract=off` is a CORRECTNESS flag in this project, not a tuning one. A
* plugin whose bf16 narrowing truncates instead of rounding to even is off by up to one ulp on
* every element, which is not a tolerance question: it means the plugin cannot reproduce the
* reference and cannot be checked against it.
* libref's contract, which every kernel is checked against, is f32 accumulation, IEEE
* round-to-nearest-ties-to-even, no fused multiply-add and no reassociation; `-ffp-contract=off`
* is a correctness flag in this project. A plugin whose bf16 narrowing truncates is off by up to
* one ulp on every element and cannot be checked against the reference.
*
* Every one of these is exact in the widening direction and RTNE in the narrowing direction, and
* each handles subnormals rather than flushing them -- the hardware decodes subnormals correctly,
* and flushing loses the smallest block of every quantised weight. */
* Every conversion is exact when widening and RTNE when narrowing, and keeps subnormals rather
* than flushing them: the hardware decodes subnormals, and flushing loses the smallest block of
* every quantised weight. */
static inline float rad_bf16_to_f32(uint16_t h) {
uint32_t u = (uint32_t)h << 16;
@@ -205,10 +180,9 @@ static inline float rad_bf16_to_f32(uint16_t h) {
return f;
}
/* The `(u >> 16) & 1` is the tie-break: it adds one more than the halfway point exactly when the
* surviving bit is odd, which is what sends a tie up rather than down. Overflow falls out --
* 0x7f7fffff plus the rounding carries into 0x7f80, the bf16 infinity -- and a NaN is forced
* quiet rather than allowed to round into an infinity. */
/* `(u >> 16) & 1` is the tie-break: it adds one more than the halfway point when the surviving
* bit is odd, so ties go to even. Overflow carries into 0x7f80, the bf16 infinity. A NaN is forced
* quiet so it cannot round into an infinity. */
static inline uint16_t rad_f32_to_bf16(float f) {
uint32_t u;
memcpy(&u, &f, 4);
@@ -240,8 +214,8 @@ static inline float rad_f16_to_f32(uint16_t h) {
return f;
}
/* RTNE, with subnormals and overflow-to-infinity handled explicitly rather than by leaning on a
* hardware convert whose mode a caller could have changed. */
/* RTNE, with subnormals and overflow-to-infinity handled explicitly rather than by a hardware
* convert whose rounding mode a caller could have changed. */
static inline uint16_t rad_f32_to_f16(float f) {
uint32_t u;
memcpy(&u, &f, 4);
@@ -279,9 +253,9 @@ static inline uint16_t rad_f32_to_f16(float f) {
}
}
/* OCP fp8 e4m3 ("e4m3fn"): 1-4-3, bias 7, NO infinity, S1111111 is the only NaN, max 448. This is
* the KV-cache format and the block-scaled weight format, so its rounding sits on the attention
* oracle's critical path and on every fp8 GEMM's. */
/* OCP fp8 e4m3 ("e4m3fn"): 1-4-3, bias 7, no infinity, S1111111 is the only NaN, max 448. The
* KV-cache and block-scaled weight format, so the attention oracle and every fp8 GEMM depend on
* its rounding. */
static inline float rad_fp8e4m3_to_f32(uint8_t b) {
uint32_t s = (uint32_t)(b >> 7) << 31;
uint32_t e = (uint32_t)(b >> 3) & 0xfu;
@@ -306,9 +280,8 @@ static inline float rad_fp8e4m3_to_f32(uint8_t b) {
return f;
}
/* SATURATES at 448 rather than overflowing. Returning a NaN for a large activation would turn one
* outlier into a poison that spreads through the whole row, and every fp8 cast in this project
* clamps for that reason. */
/* Saturates at 448 rather than overflowing: a NaN for one large activation would spread through
* the whole row. Every fp8 cast in this project clamps for that reason. */
static inline uint8_t rad_f32_to_fp8e4m3(float f) {
uint32_t u;
memcpy(&u, &f, 4);
@@ -321,10 +294,10 @@ static inline uint8_t rad_f32_to_fp8e4m3(float f) {
if (a >= 0x43e00000u) return (uint8_t)(s | 0x7eu); /* >= 448: clamp to the largest */
e = (int)(a >> 23) - 127;
m = a & 0x7fffffu;
/* The smallest subnormal is 2^-9, so everything under HALF of it -- exponent -11 and
* below -- rounds to zero. Exponent -10 is [2^-10, 2^-9): its tie point 2^-10 rounds to
* the even zero and the rest of it up to 2^-9, which the subnormal branch does with a
* 24-bit shift. */
/* The smallest subnormal is 2^-9, so everything below half of it (exponent -11 and
* below) rounds to zero. Exponent -10 is [2^-10, 2^-9): its tie point 2^-10 rounds to the
* even zero and the rest up to 2^-9, which the subnormal branch does with a 24-bit
* shift. */
if (e < -10) return s;
if (e < -6) { /* subnormal fp8 */
int sh = -6 - e + 20;
@@ -349,9 +322,12 @@ static inline uint8_t rad_f32_to_fp8e4m3(float f) {
}
}
/* fp8 e5m2: 1-5-2, bias 15, IEEE-shaped -- it has infinities and NaNs, unlike e4m3fn. It is the
* top byte of an f16, so both directions go through the f16 path and the narrowing rounds to even
* a SECOND time on the way down. */
/* fp8 e5m2: 1-5-2, bias 15, IEEE-shaped (it has infinities and NaNs, unlike e4m3fn). It is the
* top byte of an f16, so both directions go through the f16 path.
*
* Narrowing rounds to f16 and then drops the low byte. Every e5m2 tie point is an f16 value, so
* the f16 step can move `f` onto a tie but never across one; when it lands on a tie, `f`'s side
* of it decides, and only an exact tie goes to even. That makes the result one RTNE of `f`. */
static inline float rad_fp8e5m2_to_f32(uint8_t b) {
return rad_f16_to_f32((uint16_t)((uint16_t)b << 8));
}
@@ -360,19 +336,30 @@ static inline uint8_t rad_f32_to_fp8e5m2(float f) {
uint16_t h = rad_f32_to_f16(f);
uint16_t lo = (uint16_t)(h & 0xffu);
uint16_t q = (uint16_t)(h >> 8);
/* A NaN keeps its top payload bits and stays quiet; rounding its low byte could carry it out
* of the exponent into a zero of the other sign. */
if ((h & 0x7fffu) > 0x7c00u) return (uint8_t)(q | 0x02u);
if (lo == 0x80u && (h & 0x7c00u) != 0x7c00u) {
/* Magnitudes of non-negative floats order as their bit patterns. */
float t = rad_f16_to_f32(h);
uint32_t uf, ut;
memcpy(&uf, &f, 4);
memcpy(&ut, &t, 4);
uf &= 0x7fffffffu;
ut &= 0x7fffffffu;
if (uf != ut) return (uint8_t)(uf > ut ? q + 1u : q);
}
if (lo > 0x80u || (lo == 0x80u && (q & 1u))) ++q;
return (uint8_t)q;
}
/* OCP FP4 e2m1: 1-2-1, bias 1, no infinity and no NaN, so every one of the sixteen codes is a
* number and the largest is 6. */
/* OCP FP4 e2m1: 1-2-1, bias 1, no infinity or NaN; all sixteen codes are numbers, max 6. */
static inline float rad_fp4e2m1_to_f32(uint8_t nib) {
static const float mag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
return (nib & 8u) ? -mag[nib & 7u] : mag[nib & 7u];
}
/* OCP FP6, both forms. No infinity and no NaN; e2m3 has bias 1 and tops out at 7.5, e3m2 has
* bias 3 and tops out at 28. */
/* OCP FP6, both forms. No infinity or NaN; e2m3 has bias 1 and max 7.5, e3m2 bias 3 and max 28. */
static inline float rad_fp6_to_f32(uint8_t c, int ebits) {
const int mbits = 5 - ebits, bias = ebits == 2 ? 1 : 3;
const int e = (c >> mbits) & ((1 << ebits) - 1), m = c & ((1 << mbits) - 1);
@@ -382,7 +369,7 @@ static inline float rad_fp6_to_f32(uint8_t c, int ebits) {
return (c & 0x20) ? -mag : mag;
}
/* THE BIT STREAM, for every element narrower than a byte or not a power of two wide.
/* The bit stream, for every element narrower than a byte or not a power of two wide.
*
* Element `i` of a b-bit row occupies bits [i*b, (i+1)*b) counted from bit 0 of `base`, lowest
* first, so it may straddle a byte; the read touches only the bytes the element is in. Widths to
@@ -444,13 +431,11 @@ static inline float rad_e8m0_to_f32(uint8_t e) {
/* ================================================================== dtype-generic access
*
* Load or store element `i` of a plane as f32, whatever it is stored as. This is what a host
* kernel and a converter both need, and it is the one place the dtype enum and the conversions
* above are wired together -- so a plugin that adds support for a dtype adds it once. Returns 0
* for a dtype it cannot read, which a caller must treat as a refusal rather than as a value.
* kernel and a converter both need, and the one place the dtype enum and the conversions above
* meet. Returns 0 for a dtype it cannot read, which a caller must treat as a refusal, not a value.
*
* A SUB-BYTE `i` COUNTS ELEMENTS FROM `base`, which is right inside one row and wrong across rows
* whose element count does not fill their last byte: a row starts on a byte (rad_encoding.h), so
* a caller crossing rows steps `base` a row's bytes at a time. */
* For sub-byte dtypes `i` counts elements from `base`, which is valid only within one row: rows
* start on a byte (rad_encoding.h), so a caller crossing rows steps `base` by a row's bytes. */
static inline float rad_load_f32(const void* base, uint32_t dtype, int64_t i) {
const uint8_t* b8 = (const uint8_t*)base;
int sgn = 0;
@@ -482,10 +467,10 @@ static inline float rad_load_f32(const void* base, uint32_t dtype, int64_t i) {
}
}
/* Store the raw CODE of element `i` of a sub-byte or byte plane -- the bit pattern, already
* chosen, masked to the dtype's width -- leaving its neighbours in the same byte alone. A signed
* code is passed as its value (-8..7 for i4) and stored two's complement. The quantisers' half of
* rad_load_f32; nothing rounds here. Returns 0 for a dtype wider than 16 bits. */
/* Store the raw code of element `i` of a sub-byte or byte plane (the chosen bit pattern, masked to
* the dtype's width), leaving neighbours in the same byte alone. A signed code is passed as its
* value (-8..7 for i4) and stored two's complement. The quantisers' counterpart to rad_load_f32;
* nothing rounds here. Returns 0 for a dtype wider than 16 bits. */
static inline int rad_store_code(void* base, uint32_t dtype, int64_t i, int code) {
const int bits = rad_dtype_bits(dtype);
if (bits < 1 || bits > 16) return 0;
@@ -495,6 +480,28 @@ static inline int rad_store_code(void* base, uint32_t dtype, int64_t i, int code
return 1;
}
/* `v` rounded to the nearest integer, ties to even, and clamped to [lo, hi]; NaN is 0. Exact and
* independent of the rounding mode: a float of magnitude 2^23 or more is already an integer, and
* below that its fraction is exact in a double. */
static inline double rad_round_even_sat(float v, double lo, double hi) {
double d = (double)v, r;
if (v != v) return 0.0;
if (d >= 8388608.0 || d <= -8388608.0) {
r = d;
} else {
const long long t = (long long)d; /* toward zero */
const double f = d - (double)t;
long long n = t;
if (f > 0.5 || (f == 0.5 && (t & 1))) ++n;
else if (f < -0.5 || (f == -0.5 && (t & 1))) --n;
r = (double)n;
}
return r < lo ? lo : (r > hi ? hi : r);
}
/* Store `v` as element `i` of a byte-aligned plane. A float dtype rounds as the narrowings above
* do; an integer dtype rounds to nearest, ties to even, and saturates to its range, NaN storing 0.
* Sub-byte dtypes are stored with rad_store_code; any other dtype is left unwritten. */
static inline void rad_store_f32(void* base, uint32_t dtype, int64_t i, float v) {
switch (dtype) {
case RAD_F32: ((float*)base)[i] = v; break;
@@ -502,12 +509,26 @@ static inline void rad_store_f32(void* base, uint32_t dtype, int64_t i, float v)
case RAD_BF16: ((uint16_t*)base)[i] = rad_f32_to_bf16(v); break;
case RAD_F8E4M3: ((uint8_t*)base)[i] = rad_f32_to_fp8e4m3(v); break;
case RAD_F8E5M2: ((uint8_t*)base)[i] = rad_f32_to_fp8e5m2(v); break;
case RAD_I8: ((int8_t*)base)[i] = (int8_t)v; break;
case RAD_U8: ((uint8_t*)base)[i] = (uint8_t)v; break;
case RAD_I16: ((int16_t*)base)[i] = (int16_t)v; break;
case RAD_I32: ((int32_t*)base)[i] = (int32_t)v; break;
case RAD_U32: ((uint32_t*)base)[i] = (uint32_t)v; break;
case RAD_I64: ((int64_t*)base)[i] = (int64_t)v; break;
case RAD_I8: ((int8_t*)base)[i] = (int8_t)rad_round_even_sat(v, -128.0, 127.0); break;
case RAD_U8: ((uint8_t*)base)[i] = (uint8_t)rad_round_even_sat(v, 0.0, 255.0); break;
case RAD_U16:
((uint16_t*)base)[i] = (uint16_t)rad_round_even_sat(v, 0.0, 65535.0);
break;
case RAD_I16:
((int16_t*)base)[i] = (int16_t)rad_round_even_sat(v, -32768.0, 32767.0);
break;
case RAD_I32:
((int32_t*)base)[i] = (int32_t)rad_round_even_sat(v, -2147483648.0, 2147483647.0);
break;
case RAD_U32:
((uint32_t*)base)[i] = (uint32_t)rad_round_even_sat(v, 0.0, 4294967295.0);
break;
case RAD_I64: {
/* 2^63 is the first float past the range, so it is compared, not clamped to. */
const double r = rad_round_even_sat(v, -9223372036854775808.0, 9223372036854775808.0);
((int64_t*)base)[i] = r >= 9223372036854775808.0 ? INT64_MAX : (int64_t)r;
break;
}
case RAD_BOOL: ((uint8_t*)base)[i] = v != 0.0f ? 1u : 0u; break;
default: break;
}
+55
View File
@@ -0,0 +1,55 @@
/* rad_prefill_split.h -- host-pure live-KV prefill split law shared by libr4d launchers and
* architecture pass-key callbacks. Keep this independent of HIP so callbacks can run before tape
* lookup without a device copy or launch.
*/
#pragma once
#include <algorithm>
#include <cstdint>
/* `bq` query positions per workgroup, `tile` keys per KV tile. `units` counts the workgroups that
* do work: a ragged batch's grid is sized from its longest sequence, but a shorter sequence's
* tiles past its end exit at once. Each split keeps at least eight tiles of the supplied context.
*/
static inline int rad_prefill_splits_law(int bq, int tile, int q_len, int total_q, int num_seqs,
int kv_heads, int max_ctx, int wgps) {
const long n = std::max(1, num_seqs);
const long qt = std::min(n * ((std::max(1, q_len) + bq - 1) / bq),
(std::max(1, total_q) + (long)(bq - 1) * n) / bq);
const long units = (long)std::max(1, kv_heads) * std::max(1L, qt);
if (units >= wgps) return 1;
const int s1 = (int)(wgps / units), s2 = (int)(2L * wgps / units);
int sp = s2 > 2 * s1 ? s2 : s1;
const int cap = ((max_ctx > 0 ? max_ctx : (1 << 30) - 1) + tile - 1) / tile / 8;
sp = std::min(sp, std::max(1, cap));
return std::max(1, std::min(sp, 64));
}
/* The launcher's live-context refinement of the initial model-bound law. */
static inline int rad_prefill_splits_for_live(int bq, int tile, int q_len, int total_q,
int num_seqs, int kv_heads, int max_ctx,
int used_ctx, int wgps) {
int splits = rad_prefill_splits_law(bq, tile, q_len, total_q, num_seqs, kv_heads, max_ctx,
wgps);
if (splits > 1 && used_ctx > 0 && (max_ctx <= 0 || used_ctx < max_ctx))
splits = rad_prefill_splits_law(bq, tile, q_len, total_q, num_seqs, kv_heads, used_ctx,
wgps);
return splits;
}
/* Fingerprint one actual launch tuple in packet-global sizes. Use this instead of the raw context
* so equal split grids share a recording key as live context advances. */
static inline uint64_t rad_prefill_grid_key(int q_len, int bq, int splits, int kv_heads,
int num_seqs, int threads) {
const uint64_t gx = (uint64_t)((std::max(1, q_len) + bq - 1) / bq) *
(uint64_t)std::max(1, splits) * (uint64_t)threads;
const uint64_t gy = (uint64_t)std::max(1, kv_heads);
const uint64_t gz = (uint64_t)std::max(1, num_seqs);
uint64_t h = 0x9e3779b97f4a7c15ull;
const uint64_t grid[3] = {gx, gy, gz};
for (uint64_t v : grid) {
h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
h *= 0xbf58476d1ce4e5b9ull;
}
return h | 1;
}
+42 -36
View File
@@ -1,23 +1,22 @@
/* rad_quant.h -- the quantiser plugin ABI. spec.md §4.5.
*
* A quantiser turns a weight, handed to it in f32, into the planes of an ENCODING (rad_encoding.h).
* A quantiser turns a weight, handed to it in f32, into the planes of an encoding (rad_encoding.h).
* It is the third plugin kind beside kernels and architectures, loaded from
* $RADIANCE_HOME/quantizers, and it is the only place a weight's numbers are chosen: a kernel
* rearranges planes it is given (rad_abi.h, RadRelayoutFn) and never quantises.
* $RADIANCE_HOME/quantizers, and the only place a weight's numbers are chosen: a kernel only
* rearranges the planes it is given (rad_abi.h, RadRelayoutFn).
*
* rad-convert drives quantisers through a RECIPE -- ordered rules from a logical weight name to a
* rad-convert drives quantisers through a recipe: ordered rules from a logical weight name to a
* quantiser and its options (spec §4.4). For each weight a rule picks, it asks the quantiser which
* encoding it would write (`encoding`), lets the architecture plugin declare against that, and
* then hands the weight over in row blocks (`row_block`, `quantize`), so a 51 GB table streams.
* encoding it would write (`encoding`), lets the architecture plugin declare against that, then
* hands the weight over in row blocks (`row_block`, `quantize`), so a 51 GB table streams.
*
* WHAT A QUANTISER IS GIVEN. The weight's logical name, shape and movement group, and when the
* converter has an imatrix, the weight's column importances. Anything else it calibrates on -- a
* GPTQ Hessian, AutoRound's activations -- is an option it reads itself (`calib=DIR`): what a
* Hessian is and how it is stored is the quantiser's business, exactly as a layout is a kernel's.
* Input: the weight's logical name, shape and movement group, and the column importances when the
* converter has an imatrix. Other calibration data (a GPTQ Hessian, AutoRound's activations) is an
* option the quantiser reads itself (`calib=DIR`); its format is the quantiser's business.
*
* WHAT IT HANDS BACK is the canonical planes and nothing else, so its output is readable by every
* kernel library that accepts the encoding and by the core's own decoder -- which is how rad-convert
* measures its error without knowing what it did.
* Output: the canonical planes only, so every kernel library that accepts the encoding and the
* core's own decoder can read it. That is how rad-convert measures the error without knowing the
* method.
*
* Pure C, like the rest of abi/.
*/
@@ -37,12 +36,12 @@ typedef struct RadQuantWeight {
uint32_t rank;
int64_t shape[RAD_MAX_RANK]; /* the logical shape */
int64_t rows, cols; /* the [rows, cols] view every plane is laid over */
/* The movement group; -1 for none. -1 also when `encoding` is asked at declare, which runs
* before the weight's group exists -- so an encoding may depend on the name and the shape and
* not on these, and rad-convert refuses a quantiser whose answer moves once it is told. */
/* The movement group; -1 for none. Also -1 when `encoding` is asked at declare, before the
* group exists, so an encoding may depend on the name and shape but not on these; rad-convert
* refuses a quantiser whose answer changes once it is told. */
int32_t layer, expert;
/* The imatrix's column importances for this weight -- a second moment of its input, one a
* column -- or null when the converter has none. Per expert where the imatrix has the form. */
/* The imatrix's column importances for this weight (the second moment of its input, one per
* column), or null when the converter has none. Per expert where the imatrix has that form. */
const float* importance;
} RadQuantWeight;
@@ -57,22 +56,22 @@ typedef struct RadQuantOption {
const char* doc;
} RadQuantOption;
/* The encoding this quantiser writes for `w` under options `o`. RAD_E_UNSUPPORTED declines -- a
* weight it does not quantise, like a rank-1 norm -- and the converter moves on to the next rule;
* any other failure is an error in the recipe, said with the weight's name. */
/* The encoding this quantiser writes for `w` under options `o`. RAD_E_UNSUPPORTED declines (a
* weight it does not quantise, like a rank-1 norm) and the converter moves on to the next rule;
* any other failure is a recipe error reported with the weight's name. */
typedef int (*RadQuantEncodingFn)(const RadParam* o, int n_o, const RadQuantWeight* w,
RadEncoding* out);
/* The rows one `quantize` call may take: every call but the last gets a multiple of this, starting
* on a multiple of it. 0 means the whole weight in one call -- what anything with a cross-row
* decision needs (a per-tensor scale it derives, a rotation it learns, a Hessian it shares). It must
* be a multiple of every TILED plane's block rows. */
* on a multiple of it. 0 means the whole weight in one call, needed for any cross-row decision (a
* derived per-tensor scale, a learned rotation, a shared Hessian). Must be a multiple of every
* TILED plane's block rows. */
typedef int64_t (*RadQuantRowBlockFn)(const RadParam* o, int n_o, const RadQuantWeight* w);
/* Quantise logical rows [row0, row0 + rows) of `w`, given as f32 [rows, cols] in `src`, into the
* planes. `planes[i]` points at the element row of plane i that covers logical row `row0` -- for a
* TILED plane of block rows br that is row row0 / br, for a plane covering the whole extent and for
* a TABLE plane it is the plane's start -- and the call writes exactly the rows its block covers.
* planes. `planes[i]` points at the element row of plane i that covers logical row `row0` (row
* row0 / br for a TILED plane of block rows br; the plane's start for a whole-extent or TABLE
* plane), and the call writes exactly the rows its block covers.
* The buffers arrive zeroed. `src` may be modified. */
typedef int (*RadQuantizeFn)(const RadParam* o, int n_o, const RadQuantWeight* w,
float* src, int64_t row0, int64_t rows, void* const* planes);
@@ -81,12 +80,11 @@ typedef int (*RadQuantizeFn)(const RadParam* o, int n_o, const RadQuantWeight* w
* does not decode. Null for a quantiser that writes only "plain" and "affine", which the core
* decodes itself. `planes[i]` points at plane i's start.
*
* It is how a scheme of a quantiser's own is READ: the oracle checking a kernel against the
* reference, rad-kbench drawing a weight, rad-convert measuring the quantiser's error all decode
* The oracle, rad-kbench and rad-convert's error measurement all read a quantiser's own scheme
* through it. The core asks every loaded quantiser that has one, in load order, and takes the
* first answer that is not RAD_E_UNSUPPORTED -- so a decoder answers RAD_E_UNSUPPORTED for an
* encoding it did not write. `w` names the weight where the caller knows it; a decoder must not
* need more than the encoding, `rows` and `cols`, because the oracle knows no more. */
* first answer that is not RAD_E_UNSUPPORTED, so a decoder must return RAD_E_UNSUPPORTED for an
* encoding it did not write. `w` names the weight where the caller knows it; a decoder must need
* nothing beyond the encoding, `rows` and `cols`, because the oracle knows no more. */
typedef int (*RadQuantDecodeFn)(const RadEncoding* e, const RadQuantWeight* w,
const void* const* planes, int64_t row0, int64_t rows,
float* out);
@@ -102,13 +100,21 @@ typedef struct RadQuantizerInfo {
RadQuantDecodeFn decode; /* optional */
} RadQuantizerInfo;
/* Every quantiser plugin exports these, beside rad_plugin_abi_version and rad_plugin_info (whose
* kind is RAD_PLUGIN_QUANT). Two plugins naming the same quantiser is refused at load, both named,
* for the reason two kernel plugins may not disagree about an op's schema: a recipe that names it
* would mean different numbers depending on load order. */
/* Every quantiser plugin exports these, beside rad_plugin_abi_version and rad_plugin_info (kind
* RAD_PLUGIN_QUANT). Two plugins naming the same quantiser are refused at load, both named, since
* a recipe naming it would otherwise give different numbers depending on load order. */
int rad_quant_count(void);
const RadQuantizerInfo* rad_quant_at(int i);
/* Optional: the cards a quantiser may run on, as the HIP runtime numbers them (after
* HIP_VISIBLE_DEVICES); none is the host alone, the state before any call. rad-convert calls it
* once, after loading and before the first weight, with its --gpus list. A quantiser that uses a
* card writes the same bytes it writes on the host, so a container does not depend on the machine
* that converted it, and --reuse matches it either way. RAD_E_UNSUPPORTED: this build has no
* device path; any other negative status refuses the list (a card that is not there). Symbol
* name: `rad_quant_devices`. */
typedef int (*RadQuantDevicesFn)(const int* ids, int n);
#ifdef __cplusplus
} /* extern "C" */
#endif
+824 -193
View File
File diff suppressed because it is too large. Load diff
+31 -38
View File
@@ -1,22 +1,17 @@
/* rad_sample.h -- the per-sequence sampling row, and why it is part of the ABI.
/* rad_sample.h -- the per-sequence sampling row.
*
* Every sampler op takes `params` as an OPERAND: an array of the struct below, one row per sampled
* position, uploaded once per step. That makes its layout a wire format between the core and every
* kernel plugin, so it belongs here beside RadTensor rather than in core/sample/ where it started
* -- a kernel plugin cannot include a core header, and a struct the host writes and the device
* reads is a struct whose layout has to be STATED, not inferred.
* Every sampler op takes `params` as an operand: an array of the struct below, one row per sampled
* position, uploaded once per step. Its layout is therefore a wire format between the core and
* every kernel plugin, stated here because a plugin cannot include a core header.
*
* ============================== WHY NOT PARAMETERS ==============================
*
* `rep`, `freq`, `pres`, `k` and `p` read like op PARAMETERS, and docs/OPS.md names them that way.
* They cannot be. Parameters are geometry: the selector matches constraints against them and they
* are frozen at declare (spec §2.2). A per-sequence value cannot live there, and the failure is
* not subtle -- two requests in one batch with different top_p would be two different geometries
* and therefore two different resolutions of the same op, which is not something a batch can
* contain. A deployment would have one top_p.
*
* So the values are DATA and they travel as an operand. `seed` and `offset`, which docs/OPS.md
* gives `sample_pick` as two more operands, are fields of the row for the same reason.
* `rep`, `freq`, `pres`, `k` and `p` read like op parameters, and docs/OPS.md names them that way,
* but parameters are geometry: the selector matches constraints against them and they are frozen
* at declare (spec §2.2). Two requests in one batch with different top_p would need two
* resolutions of the same op. So the values are data and travel as an operand. `seed` and
* `offset`, which docs/OPS.md gives `sample_pick` as two more operands, are row fields for the
* same reason.
*
* core/sample/sampler.h carries the full schema table this implies; libref implements it.
*/
@@ -29,16 +24,15 @@
extern "C" {
#endif
/* Flags, so a kernel can skip a stage for a sequence without reading five floats to discover they
* are the identity. One integer test beats five float comparisons per row per stage.
/* Flags, so a kernel can skip a stage for a sequence with one integer test instead of reading
* five floats to find they are the identity.
*
* RAD_SP_GREEDY OWNS THE ROW'S TOKEN. `sample_argmax` writes it, and every candidate stage after
* it -- `sample_topk`, the narrowing stages, `sample_merge_topk` and `sample_pick` -- treats the
* row as having no candidates and leaves `token` alone. A batch mixing greedy and sampled rows
* issues both paths over every row, so a stage that ignored the flag would overwrite the argmax
* with a draw. A greedy row that has to go through the candidate chain instead -- a split
* vocabulary, where the argmax's column is not a token id -- is staged at top_k = 1 WITHOUT this
* flag. */
* RAD_SP_GREEDY owns the row's token. `sample_argmax` writes it, and every later candidate stage
* (`sample_topk`, the narrowing stages, `sample_merge_topk`, `sample_pick`) treats the row as
* having no candidates and leaves `token` alone. A batch mixing greedy and sampled rows issues
* both paths over every row, so a stage that ignored the flag would overwrite the argmax with a
* draw. A greedy row that must go through the candidate chain (a split vocabulary, where the
* argmax column is not a token id) is staged at top_k = 1 without this flag. */
enum {
RAD_SP_GREEDY = 1 << 0, /* argmax path; the candidate chain is not run for this sequence */
RAD_SP_PENALTY = 1 << 1, /* any of rep / freq / pres is non-identity */
@@ -51,14 +45,14 @@ enum {
/* One row per sampled position. Laid out so the 8-byte fields are aligned and the struct has no
* padding anywhere, including at the tail.
*
* THE HISTORY WINDOW. `hist_off` and `hist_len` address the row's OWN row of the history plane,
* [M, max_hist] int32 with row m belonging to sampled position m: the window is
* history[m][hist_off .. hist_off + hist_len), clamped to the row. Token ids in it are GLOBAL
* History window: `hist_off` and `hist_len` address the row's own row of the history plane,
* [M, max_hist] int32 with row m belonging to sampled position m; the window is
* history[m][hist_off .. hist_off + hist_len), clamped to the row. Token ids in it are global
* vocabulary ids; a stage over a vocabulary shard subtracts its `vocab_off` parameter.
*
* `penalty_last_n` and `dry_penalty_last_n` window the TAIL of that span: 0 turns the stage off
* for the row, a negative value takes the whole span, and n > 0 takes the last n tokens -- the
* meaning llama.cpp gives `repeat_last_n` and `dry_penalty_last_n`.
* `penalty_last_n` and `dry_penalty_last_n` window the tail of that span: 0 turns the stage off
* for the row, a negative value takes the whole span, and n > 0 the last n tokens (llama.cpp's
* meaning for `repeat_last_n` and `dry_penalty_last_n`).
*
* `dry_rep_limit` is the longest repeat DRY may count for the row, fixed by the most recent
* sequence breaker in the DRY window (llama.cpp's `rep_limit`), or 0 when no breaker occurs there
@@ -104,15 +98,14 @@ static_assert(offsetof(RadSampleParams, dry_rep_limit) + sizeof(int32_t) == size
"RadSampleParams must pack without a tail hole");
#endif
/* THE RANDOM DRAW IS SPECIFIED, not left to a library, because the same stream has to come out of
* a host reference, a device kernel and a rerun (spec §17). splitmix64 over
* (seed * golden ratio + pos), taking 24 bits as a float in [0, 1) -- exactly f32's mantissa, so
* the draw is representable without a double anywhere in the chain.
/* The random draw is specified here, not left to a library, because a host reference, a device
* kernel and a rerun must produce the same stream (spec §13). splitmix64 over
* (seed * golden ratio + pos), taking 24 bits as a float in [0, 1): exactly f32's mantissa, so no
* double is needed anywhere.
*
* INDEPENDENT DRAWS AT ONE POSITION TAKE INDEPENDENT STREAMS, and a stream is the request's seed
* XORed with a key before the draw: `rad_sample_uniform01(seed ^ key, pos)`. The pick draws on the
* seed itself. XTC's "does it fire" coin has its own key, so a row whose XTC fired is not a row
* whose pick is correlated with that fact; speculative acceptance and its residual draw have
* Independent draws at one position use independent streams: the request's seed XORed with a key,
* `rad_sample_uniform01(seed ^ key, pos)`. The pick uses the seed itself. XTC's firing coin has its
* own key so the pick is not correlated with it; speculative acceptance and its residual draw have
* theirs. Every implementation of a stage takes its key from here. */
#define RAD_SAMPLE_KEY_PICK 0x0ull
#define RAD_SAMPLE_KEY_XTC 0x58544311ull
+413
View File
@@ -0,0 +1,413 @@
/* rad_spechub.h -- the speculative coupling (linear MTP and DFlash2's block walk): wire rows and
* the shared arithmetic.
*
* The core writes these rows and a kernel plugin reads them, so their layout is ABI. The helpers
* are header-only and stateless, so the host reference, the device kernel and the sampler share
* one definition of the wire and of the arithmetic that turns it into a token.
*
* A row lives in a U32 plane whose base and row stride are eight-byte aligned, so a state can be
* loaded whole on the device.
*/
#ifndef RAD_SPECHUB_H
#define RAD_SPECHUB_H
#include <math.h>
#include <stddef.h>
#include <stdint.h>
/* The verify reads a RadSampleParams row. */
#include "rad_sample.h"
/* Linear MTP coupling (--draft-coupling on). One draw per drafting row, staged before the
* serial passes; one state per (temporal round, row). `base` is the request's PRE-commit output
* size, so (base, round) names one draft stream that no later step reuses. `card` is the step slot
* the advance writes, checked against RadBatch::seq_ids. `mode` 1 samples x~Q; 0 keeps the greedy
* proposal (temperature 0 or top_k 1). */
typedef struct RadMtpCoupleDraw {
uint64_t seed, base, seq;
int32_t card;
uint32_t mode;
} RadMtpCoupleDraw;
/* status 1: x sampled from the exact q[] stored here; 0: greedy proposal kept; -1: malformed
* shortlist or row identity, greedy proposal kept. `pos` is the verify row's output position, bound
* by the host after commit; the device writes 0. ids[count..7] = -1, q[count..7] = 0. */
typedef struct RadMtpCoupleState {
RadMtpCoupleDraw draw;
uint64_t pos;
int32_t status, round, x, count;
int32_t ids[8];
double q[8];
} RadMtpCoupleState;
#define RAD_MTP_COUPLE_DRAW_WORDS (sizeof(RadMtpCoupleDraw) / 4)
#define RAD_MTP_COUPLE_STATE_WORDS (sizeof(RadMtpCoupleState) / 4)
#define RAD_MTP_COUPLE_MAX_ROUNDS 8
/* Draft stream of round r: seed ^ (KEY_DRAFT + r) at coordinate `base`. Acceptance and the
* residual draw use RAD_SAMPLE_KEY_ACCEPT / RAD_SAMPLE_KEY_RESID at the verify position. */
#define RAD_MTP_COUPLE_KEY_DRAFT 0x4d5450434f55504cull
#ifdef __cplusplus
static_assert(sizeof(RadMtpCoupleDraw) == 32, "MTP coupling draw wire");
static_assert(sizeof(RadMtpCoupleState) == 152, "MTP coupling state wire");
static_assert(offsetof(RadMtpCoupleState, q) % 8 == 0, "MTP coupling q alignment");
#endif
/* ================================================================== the shared arithmetic
*
* Q is the FP64 softmax of an FP32 shortlist at temperature 1; P is the FP64 softmax of the
* sampler's FP32 candidate logits; uniforms are 53-bit. A coupled row therefore realises the
* filtered target law to FP64 rounding rather than sample_pick's FP32/24-bit law, and is not
* seed-identical to the ordinary pick.
*/
#ifdef __cplusplus
#if defined(__HIPCC__)
#define RAD_SPECHUB_HD __host__ __device__
#else
#define RAD_SPECHUB_HD
#endif
static inline RAD_SPECHUB_HD double rad_spechub_positive(double a) { return a > 0 ? a : 0; }
static inline RAD_SPECHUB_HD bool rad_spechub_finite(double x) {
return x == x && x <= 1.7976931348623157e308 && x >= -1.7976931348623157e308;
}
/* A 53-bit uniform in [0, 1): splitmix64 over (seed ^ key, pos), top 53 bits scaled by 2^-53. */
static inline RAD_SPECHUB_HD double rad_spechub_uniform(uint64_t seed, uint64_t pos, uint64_t key) {
uint64_t z = (seed ^ key) * 0x9e3779b97f4a7c15ull + pos + 0x9e3779b97f4a7c15ull;
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
z ^= z >> 31;
return (double)(z >> 11) * 0x1p-53;
}
/* Is `s` a state the coupling's propose kernel could have written for a sampled row? The verifier
* and the engine's bind check refuse a row by this rule, on the device and on the host. */
static inline RAD_SPECHUB_HD bool rad_mtp_couple_state_valid(const RadMtpCoupleState& s,
int64_t vocab) {
if (s.status != 1 || s.draw.mode != 1 || s.count < 1 || s.count > 8 || s.round < 1 ||
s.round > RAD_MTP_COUPLE_MAX_ROUNDS)
return false;
double sum = 0;
bool has_x = false;
for (int i = 0; i < 8; ++i) {
if (i >= s.count) {
if (s.ids[i] != -1 || s.q[i] != 0) return false;
continue;
}
if (s.ids[i] < 0 || s.ids[i] >= vocab || !rad_spechub_finite(s.q[i]) || !(s.q[i] > 0) ||
s.q[i] > 1)
return false;
for (int j = 0; j < i; ++j)
if (s.ids[j] == s.ids[i]) return false;
sum += s.q[i];
has_x |= s.ids[i] == s.x;
}
return has_x && (sum - 1) <= 1e-12 && (1 - sum) <= 1e-12;
}
/* The verify position of coupled round r (1-based): the coordinate the engine's bind and the
* sampler's row check must agree on.
*
* The sampler stages row k of a request at output position `n_out + k`, where `n_out` is the
* request's committed output length when the step is built; round r is verified at row r - 1. The
* acceptance and residual uniforms are drawn at this position.
*
* `n_out` is read from the request after the drafting step's commit. It is not rebuilt from the
* draft's pre-commit `base` plus the accepted count: the two differ when the commit emits fewer
* tokens than the card accepted (a max_tokens or context cut) or a step is carried. */
static inline RAD_SPECHUB_HD uint64_t rad_mtp_couple_verify_pos(uint64_t n_out, int round) {
return n_out + (round > 0 ? (uint64_t)(round - 1) : 0);
}
/* Would the verify row for draft index `k` (0-based) of a request with committed output length
* `n_out` take `c` as its coupled state? Same request and seed, the round this row's draft came
* from, the position it samples, the very token it proposes, and a state the proposer could have
* written. Anything else is a stale state from another step, and coupling against it would apply a
* law this step never drew.
*
* Asked by the sampler's step build, against the state the engine bound. The engine's own bind
* does not call it: it checks the readback against the card (draw, round, x, status) and writes
* the position with rad_mtp_couple_verify_pos, the formula here that both sides must agree on. */
static inline RAD_SPECHUB_HD bool rad_mtp_couple_binds(const RadMtpCoupleState& c, uint64_t seq,
uint64_t seed, uint64_t n_out, int k,
int32_t draft_x, int64_t vocab) {
return c.status == 1 && c.draw.seq == seq && c.draw.seed == seed && c.round == k + 1 &&
c.pos == rad_mtp_couple_verify_pos(n_out, k + 1) && c.x == draft_x &&
rad_mtp_couple_state_valid(c, vocab);
}
/* Build the stored Q from a shortlist of eight (id, score) slots.
*
* Holes (id < 0) and -inf scores carry no mass. An entry whose FP64 weight or normalized q
* underflows to zero is dropped, so the stored q[] is exactly the law the draw walks. False on an
* out-of-range id, NaN/+inf score, duplicate id or empty support (s->count = 0). */
static inline RAD_SPECHUB_HD bool rad_mtp_couple_build_q(const int32_t* ids, const float* val,
int64_t vocab, RadMtpCoupleState* s) {
int32_t kid[8];
float kv[8];
int n = 0;
s->count = 0;
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
for (int i = 0; i < 8; ++i) {
if (ids[i] < 0) continue;
if (ids[i] >= vocab || val[i] != val[i] || val[i] == INFINITY) return false;
if (val[i] == -INFINITY) continue;
for (int j = 0; j < n; ++j)
if (kid[j] == ids[i]) return false;
kid[n] = ids[i];
kv[n++] = val[i];
}
if (!n) return false;
float top = kv[0];
for (int j = 1; j < n; ++j)
if (kv[j] > top) top = kv[j];
double w[8], sum = 0;
for (int j = 0; j < n; ++j) { w[j] = ::exp((double)kv[j] - top); sum += w[j]; }
for (int j = 0; j < n; ++j) {
const double q = w[j] / sum;
if (q > 0) { s->ids[s->count] = kid[j]; s->q[s->count++] = q; }
}
return s->count > 0;
}
/* Inverse CDF over the stored q with a uniform in [0, 1); index into ids. */
static inline RAD_SPECHUB_HD int rad_mtp_couple_pick(const RadMtpCoupleState& s, double u) {
double total = 0;
for (int i = 0; i < s.count; ++i) total += s.q[i];
double c = u * total;
for (int i = 0; i < s.count; ++i) { c -= s.q[i]; if (c < 0) return i; }
return s.count - 1;
}
/* Residual mass r(y) = max(0, P(y) - Q(y)) of one candidate. Q tokens use their P aggregated over
* duplicate candidates, counted once at the first occurrence (`seen`). */
static inline RAD_SPECHUB_HD double rad_mtp_couple_mass(const RadMtpCoupleState& s, const double* pq,
int32_t id, float v, float top, double sum,
unsigned* seen) {
if (id < 0 || v == -INFINITY) return 0;
for (int k = 0; k < s.count; ++k)
if (s.ids[k] == id) {
if (*seen & (1u << k)) return 0;
*seen |= 1u << k;
return rad_spechub_positive(pq[k] - s.q[k]);
}
return ::exp((double)v - top) / sum;
}
/* The maximal coupling of the target's law P (over the surviving candidates) with the draft's Q.
* Writes the emitted token to *out and returns true, or returns false for an invalid or empty
* target. u_accept and u_resid are independent uniforms in [0, 1).
*
* The draft x is kept when P dominates Q on every Q token or when u_accept * Q(x) < P(x); otherwise
* the token is drawn from the residual (P - Q)+. The emitted token is distributed as P, and it
* equals x with probability sum min(P, Q).
*
* If FP64 cancellation leaves the residual total R at 0 while some Q token has P < Q, P is sampled
* directly in FP64 with u_resid. That branch depends on (P, Q) only, never on x or a uniform.
*
* R sums r over every candidate including x. The residual walk runs only when P(x) < Q(x), where
* r(x) is exactly +0, so skipping x in the walk leaves its total equal to R bit for bit. */
static inline RAD_SPECHUB_HD bool rad_mtp_couple_decide(const RadMtpCoupleState& s,
const int32_t* ids, const float* val,
int64_t n, int64_t vocab, double u_accept,
double u_resid, int32_t* out) {
float top = -INFINITY;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
if (val[j] > top) top = val[j];
}
if (top == -INFINITY) return false;
double sum = 0, pq[8] = {};
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
const double w = ::exp((double)val[j] - top);
sum += w;
for (int k = 0; k < s.count; ++k)
if (ids[j] == s.ids[k]) { pq[k] += w; break; }
}
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
int ix = -1;
bool dominated = true;
for (int k = 0; k < s.count; ++k) {
pq[k] /= sum;
dominated = dominated && pq[k] >= s.q[k];
if (s.ids[k] == s.x) ix = k;
}
if (ix < 0) return false; /* unreachable for a rad_mtp_couple_state_valid state */
unsigned seen = 0;
double resid = 0;
for (int64_t j = 0; j < n; ++j)
resid += rad_mtp_couple_mass(s, pq, ids[j], val[j], top, sum, &seen);
if (!dominated && !(resid > 0 && rad_spechub_finite(resid))) {
double c = u_resid * sum;
int32_t last = -1;
for (int64_t j = 0; j < n; ++j)
if (ids[j] >= 0 && val[j] != -INFINITY) {
const double w = ::exp((double)val[j] - top);
if (w > 0) { last = ids[j]; c -= w; if (c < 0) { *out = last; return true; } }
}
*out = last;
return true;
}
if (pq[ix] >= s.q[ix] || u_accept * s.q[ix] < pq[ix]) { *out = s.x; return true; }
/* Rejected, so P(x) < Q(x): not dominated, resid > 0, and some y != x has mass > 0 below. */
double c = u_resid * resid;
int32_t last = -1;
seen = 0;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] == s.x) continue;
const double m = rad_mtp_couple_mass(s, pq, ids[j], val[j], top, sum, &seen);
if (m > 0) { last = ids[j]; c -= m; if (c < 0) { *out = last; return true; } }
}
*out = last;
return true;
}
/* ================================================================== DFlash2's coupled walk
*
* The block drafter's counterpart of mtp_couple_propose (`dflash_couple_propose`). DFlash2 proposes
* a block in one pass and `dflash_select` walks its candidate lattice greedily: at draft position l
* every candidate c of that position scores
*
* score[l, c] = unary[l, c] + sum_r pred[pid][r] * hp[l][r] * succ[cand[l, c]][r]
*
* with pid the anchor at l = 0 and the walk's own previous token after it. The coupled walk scores
* the same lattice but SAMPLES each position instead of taking its argmax:
*
* Q_l = the FP64 softmax of score[l, c] / q_temp over the eight best-scoring candidates whose
* ids are in the vocabulary (rad_mtp_couple_build_q), x_l ~ Q_l at the draw's
* (seed, base, KEY_DRAFT + l + 1), and pid = x_l for position l + 1.
*
* Q_l depends on the committed text (through the drafter's pass and the anchor) and on x_0..x_{l-1},
* never on the target's verification, and it is stored exactly in the state row the verify reads,
* which is all the maximal coupling needs to be exact (rad_mtp_couple_decide). The pairwise term is
* what makes Q_l follow the walk's own earlier samples rather than the drafter's marginal.
*
* Bit-identical on host and device: each candidate's edge is RAD_DFLASH_EDGE_PARTS partial sums,
* each a serial fmaf chain over a contiguous slice of the rank, added in order and then to the unary
* score. The plugin builds with -ffp-contract=off, so nothing else is fused. */
#define RAD_DFLASH_EDGE_PARTS 8
#define RAD_DFLASH_COUPLE_MAX_K 32
#define RAD_DFLASH_COUPLE_MAX_R 512
static inline RAD_SPECHUB_HD float rad_dflash_bf2f(uint16_t h) {
union { uint32_t u; float f; } c;
c.u = (uint32_t)h << 16;
return c.f;
}
/* Part `j` of one candidate's edge: a[r] * succ_row[r] over r in [j*R/P, (j+1)*R/P), fmaf in order.
* `a` is the candidate-independent half, pred[pid][r] * hp[r] (or pred[pid][r] with no hp, 0 for a
* predecessor outside the vocabulary). */
static inline RAD_SPECHUB_HD float rad_dflash_edge_part(const float* a, const uint16_t* succ_row,
int64_t R, int j) {
const int64_t w = R / RAD_DFLASH_EDGE_PARTS;
float acc = 0.0f;
for (int64_t r = (int64_t)j * w; r < (int64_t)(j + 1) * w; ++r)
acc = fmaf(a[r], rad_dflash_bf2f(succ_row[r]), acc);
return acc;
}
/* One position of the walk, given its K scores and ids (the ids as the candidate plane holds them).
* Fills `*s` as mtp_couple_propose fills a round's state and returns the proposed token:
*
* mode 0 (a greedy request): status 0, x = `greedy_x`, the token dflash_select already wrote;
* mode 1, its card's draw and a Q that builds: status 1, x ~ Q;
* mode 1 otherwise: status -1, x = the walk's argmax (ties to the lower index, dflash_select's
* rule over these scores), and the ordinary verify applies to it.
*
* The eight are taken in descending score, ties to the lower index, among candidates with an id
* in [0, vocab); a NaN score is never taken (build_q would refuse it). */
static inline RAD_SPECHUB_HD int32_t rad_dflash_couple_step(const float* sc, const int32_t* id,
int K, float q_temp,
const RadMtpCoupleDraw& d, bool card_ok,
int round, int64_t vocab,
int32_t greedy_x, RadMtpCoupleState* s) {
s->draw = d;
s->pos = 0;
s->round = round;
s->count = 0;
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
if (d.mode != 1) {
s->status = 0;
s->x = greedy_x;
return greedy_x;
}
s->status = -1;
if (card_ok) {
int32_t kid[8];
float kv[8];
unsigned taken = 0;
int n = 0;
for (; n < 8; ++n) {
int best = -1;
for (int c = 0; c < K; ++c) {
if ((taken >> c) & 1u) continue;
if (id[c] < 0 || id[c] >= vocab || sc[c] != sc[c]) continue;
if (best < 0 || sc[c] > sc[best]) best = c;
}
if (best < 0) break;
taken |= 1u << best;
kid[n] = id[best];
kv[n] = sc[best] / q_temp;
}
for (int i = n; i < 8; ++i) { kid[i] = -1; kv[i] = -INFINITY; }
if (n > 0 && rad_mtp_couple_build_q(kid, kv, vocab, s)) {
const double u = rad_spechub_uniform(d.seed, d.base,
RAD_MTP_COUPLE_KEY_DRAFT + (uint64_t)round);
s->x = s->ids[rad_mtp_couple_pick(*s, u)];
s->status = 1;
return s->x;
}
s->count = 0;
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
}
int best = 0;
float bv = -INFINITY;
for (int c = 0; c < K; ++c)
if (sc[c] > bv) { bv = sc[c]; best = c; }
s->x = id[best];
return s->x;
}
/* One sequence's whole walk on the host: the reference the device kernel is checked against, and
* what the tests drive. `cand`/`unary` are `steps` rows at pitches `ld_cand`/`ld_unary`, `hp`
* `steps` rows at `ld_hp` (null: ones), `tokens` the `steps` tokens dflash_select wrote (rewritten
* for a sampled row), `state` round 1's row with `st_round` u32 words between rounds. K <= 32, R a
* multiple of RAD_DFLASH_EDGE_PARTS and at most RAD_DFLASH_COUPLE_MAX_R (the plugin's validation).
* `pred`/`succ` are [vocab, R]. */
static inline void rad_dflash_couple_walk(const int32_t* cand, const float* unary, int64_t ld_cand,
int64_t ld_unary, const uint16_t* hp, int64_t ld_hp,
int32_t anchor, const uint16_t* pred,
const uint16_t* succ, int K,
int64_t R, int64_t vocab, int64_t steps, float q_temp,
const RadMtpCoupleDraw& d, bool card_ok, int32_t* tokens,
uint32_t* state, int64_t st_round) {
float a[RAD_DFLASH_COUPLE_MAX_R], sc[RAD_DFLASH_COUPLE_MAX_K] = {};
int32_t pid = anchor;
for (int64_t l = 0; l < steps; ++l) {
RadMtpCoupleState* s = reinterpret_cast<RadMtpCoupleState*>(state + l * st_round);
const int32_t* id = cand + l * ld_cand;
if (d.mode == 1) {
const float* un = unary + l * ld_unary;
const bool ok = pid >= 0 && pid < vocab;
for (int64_t r = 0; r < R; ++r)
a[r] = ok ? rad_dflash_bf2f(pred[(int64_t)pid * R + r]) *
(hp ? rad_dflash_bf2f(hp[l * ld_hp + r]) : 1.0f)
: 0.0f;
for (int c = 0; c < K; ++c) {
float acc = 0.0f;
if (id[c] >= 0 && id[c] < vocab)
for (int j = 0; j < RAD_DFLASH_EDGE_PARTS; ++j)
acc += rad_dflash_edge_part(a, succ + (int64_t)id[c] * R, R, j);
sc[c] = un[c] + acc;
}
}
pid = rad_dflash_couple_step(sc, id, K, q_temp, d, card_ok, (int)l + 1, vocab, tokens[l], s);
tokens[l] = pid;
}
}
#undef RAD_SPECHUB_HD
#endif /* __cplusplus */
#endif /* RAD_SPECHUB_H */
+49 -89
View File
@@ -15,9 +15,8 @@ extern "C" {
#endif
/* ------------------------------------------------------------------ status */
/* Zero is success. Negative is failure, and the value names the class of failure so a caller
* can report something better than "it returned -1". A kernel returning negative at issue is a
* bug in selection, not a runtime condition -- spec.md §17. */
/* Zero is success. Negative is failure, and the value names its class so a caller can report it.
* A kernel returning negative at issue is a selection bug, not a runtime condition (spec.md §17). */
enum {
RAD_OK = 0,
RAD_E_SHAPE = -1, /* geometry this instantiation does not serve */
@@ -42,24 +41,19 @@ enum {
RAD_E_CANCELLED = -20
};
/* ------------------------------------------------------------------ the helpers, INLINE
/* ------------------------------------------------------------------ the helpers, inline
*
* WHY EVERY FREE FUNCTION IN THIS HEADER IS A DEFINITION AND NOT A DECLARATION.
* Every free function in this header is a `static inline` definition, not a declaration. A plugin
* links these headers and nothing of the engine's, so a function defined in the core would
* resolve at dlopen only if the host happened to export it (ENABLE_EXPORTS/-rdynamic); otherwise
* RTLD_NOW fails the plugin.
*
* A plugin links these headers and nothing of the engine's. A function merely DECLARED here and
* defined inside the core is therefore not linkable from a plugin, which is the only caller that
* wants it -- and whether it happens to resolve at dlopen time is a property of the HOST, not of
* the ABI: a host that links the core with ENABLE_EXPORTS/-rdynamic exports the symbol and one
* that does not fails the plugin under RTLD_NOW. A capability that depends on a link flag of
* whoever dlopens you is not a capability.
* The helpers are therefore part of the ABI by value: a plugin carries the dtype table it was
* built against, and RAD_ABI_VERSION enforces the match (the loader refuses a mismatch by name,
* with both versions printed).
*
* So they are `static inline` and the plugin compiles its own. That makes them part of the ABI
* BY VALUE rather than by linkage: a plugin carries the dtype table it was built against. That
* is the correct trade here, and RAD_ABI_VERSION is what enforces it -- the loader refuses a
* plugin built against a different one, by name, with both versions printed.
*
* Everything here is pure, small and total. Nothing allocates, nothing has state, and nothing
* may ever acquire either. */
* Everything here is pure, small and total: nothing allocates or holds state, and nothing may
* start to. */
static inline const char* rad_strerror(int status) {
switch (status) {
case RAD_OK: return "ok";
@@ -88,14 +82,12 @@ static inline const char* rad_strerror(int status) {
}
/* ------------------------------------------------------------------ dtypes */
/* The core understands dtypes. Spec §19.6 asked whether it had to; it does -- libref has to
* interpret a tensor to compute on it, rad-kbench has to compare two of them elementwise, the
* buffer planner has to size a buffer from its shape, and rad-convert has to write bytes. An
* opaque dtype would push all four back into the plugin, which is the opposite of the point.
/* The core understands dtypes (spec §19.6): libref computes on tensors, rad-kbench compares them
* elementwise, the buffer planner sizes buffers from shapes, and rad-convert writes bytes.
*
* The enum is open at the top: values >= RAD_DT_PLUGIN_BASE are kernel-plugin private, sized by
* the plugin's own layout hook, and never interpreted by the core. That is where a format
* invented for one kernel lives (spec §4.3) without the core learning about it. */
* the plugin's own layout hook and never interpreted by the core. A format invented for one kernel
* lives there (spec §19.6). */
enum {
RAD_DT_INVALID = 0,
@@ -115,11 +107,10 @@ enum {
RAD_U32 = 13,
RAD_BOOL = 14,
/* SUB-BYTE CODES AND THE EXPONENT SCALE. The element count is the count of LOGICAL elements
* and the byte size comes from rad_dtype_bits(), which is why it is expressed in bits. They
* pack along a row, lowest bits first -- element 2j of a 4-bit row in bits 0-3 of byte j --
* and a row starts on a byte (rad_encoding.h). What a code MEANS is its encoding's business;
* these say only how many bits it is and whether it is signed. */
/* Sub-byte codes and the exponent scale. Element counts are logical elements; byte sizes
* come from rad_dtype_bits(). They pack along a row, lowest bits first (element 2j of a 4-bit
* row in bits 0-3 of byte j), and a row starts on a byte (rad_encoding.h). What a code means
* is its encoding's business; these give only its width and signedness. */
RAD_I4 = 16, /* two's complement, -8..7 */
RAD_I2 = 17, /* two's complement, -2..1 */
RAD_FP4E2M1 = 18, /* OCP FP4: 1-2-1, no inf or nan, max 6 */
@@ -145,10 +136,10 @@ enum {
RAD_DT_PLUGIN_BASE = 256
};
/* THE DTYPE TABLE, and it lives in the header for the reason the block above rad_strerror gives.
/* The dtype table, in the header for the reason given above rad_strerror.
*
* Sub-byte formats carry their packed width here. A shared scale is never folded into a code's
* width: it is a plane of its own (rad_encoding.h), so every width below is exact. */
* width (it is a plane of its own, rad_encoding.h), so every width below is exact. */
typedef struct RadDtRow { uint32_t dt; const char* name; int bits; } RadDtRow;
static const RadDtRow rad_dt_table[] = {
@@ -202,8 +193,8 @@ static inline const char* rad_dtype_name(uint32_t dtype) {
return dtype >= RAD_DT_PLUGIN_BASE ? "plugin-private" : "invalid";
}
/* RAD_DT_INVALID if unknown. The alternate spellings are the ones that appear in checkpoints and
* in kernel dtype strings; a converter reading safetensors meets every one of them. */
/* RAD_DT_INVALID if unknown. The alternate spellings are those found in checkpoints (safetensors)
* and kernel dtype strings. */
static inline uint32_t rad_dtype_parse(const char* name) {
if (!name) return RAD_DT_INVALID;
for (int i = 0; i < RAD_DT_TABLE_N; ++i)
@@ -228,8 +219,8 @@ static inline int64_t rad_dtype_bytes(uint32_t dtype, int64_t n) {
/* ------------------------------------------------------------------ tensors */
enum { RAD_MAX_RANK = 6 };
/* Strides are in ELEMENTS, not bytes -- the convention that survives contact with sub-byte
* dtypes, where a byte stride would be fractional. */
/* Strides are in elements, not bytes, since a byte stride would be fractional for sub-byte
* dtypes. */
typedef struct RadTensor {
void* data;
uint32_t dtype;
@@ -245,9 +236,8 @@ static inline int64_t rad_tensor_numel(const RadTensor* t) {
return n;
}
/* A rank-0 tensor and a tensor whose only non-unit axes are already dense are both contiguous.
* The unit-extent test matters: a shape-1 axis may carry any stride at all and still describe the
* same bytes, so demanding the packed value there rejects tensors that are in fact dense. */
/* A rank-0 tensor and a tensor whose non-unit axes are dense are both contiguous. A shape-1 axis
* may carry any stride and still describe the same bytes, so its stride is not checked. */
static inline int rad_tensor_is_contiguous(const RadTensor* t) {
if (!t || t->rank == 0) return 1;
int64_t acc = 1;
@@ -267,8 +257,8 @@ static inline void rad_tensor_pack(RadTensor* t) {
/* ------------------------------------------------------------------ parameters */
/* An op's parameters are named scalars: the geometry the selector matches constraints against.
* A parameter may be a fixed value or a RANGE, which is what turns one declared op into a
* bucket table (spec §2.2). At most one parameter per op may be ranged. */
* A parameter may be a fixed value or a range, which turns one declared op into a bucket table
* (spec §2.2). At most one parameter per op may be ranged. */
enum { RAD_P_INT = 1, RAD_P_STR = 2, RAD_P_RANGE = 3, RAD_P_F64 = 4 };
typedef struct RadParam {
@@ -277,11 +267,10 @@ typedef struct RadParam {
long long ival; /* RAD_P_INT, and the low bound of RAD_P_RANGE */
long long ihi; /* RAD_P_RANGE: the high bound, inclusive */
const char* sval; /* RAD_P_STR */
double dval; /* RAD_P_F64 -- eps, rope theta, an attention scale. Carried as a
* double rather than round-tripped through a "%.9g" string, which is
* exact for an IEEE single but unreadable in a graph dump. Constraints
* do not match on a float: a tolerance is not a predicate, and a kernel
* that cares about eps to that precision is a kernel with a bug. */
double dval; /* RAD_P_F64: eps, rope theta, an attention scale. A double rather
* than a "%.9g" string, which would be exact for an IEEE single but
* unreadable in a graph dump. Constraints never match on a float:
* a tolerance is not a predicate. */
} RadParam;
/* Builders. RAD_PARAMS below wraps these into a positional list. */
@@ -291,9 +280,9 @@ typedef struct RadParam {
#define RAD_RANGE(k, lo, hi) ((RadParam){ (k), RAD_P_RANGE, (long long)(lo), (long long)(hi), 0, 0.0 })
/* ------------------------------------------------------------------ constraints */
/* A kernel's necessary condition on a geometry. Deliberately NOT sufficient: strides,
* contiguity, alignment and buffer sizes are properties of a call rather than of a model, and
* they stay in the entry point, which still rejects what it cannot run -- spec §2.1. */
/* A kernel's necessary condition on a geometry, deliberately not sufficient: strides,
* contiguity, alignment and buffer sizes are properties of a call rather than of a model, and the
* entry point still rejects what it cannot run (spec §2.1). */
enum { RAD_C_EQ = 0, RAD_C_LE = 1, RAD_C_GE = 2, RAD_C_DIV = 3, RAD_C_IN = 4 };
typedef struct RadConstraint {
@@ -303,13 +292,11 @@ typedef struct RadConstraint {
const char* sval; /* IN: space-separated set of admissible strings */
} RadConstraint;
/* A CONSTRAINT ON THE MACHINE rather than on the geometry. A key that starts "device." is matched
* against what the engine measured about the ranks' devices at launch, not against the op's
* parameters: a capability such as reaching another card's memory belongs to the machine, and
* carrying it as a parameter would have every architecture plugin declare it on every op and
* every schema grow a field for it. Such a key is in no geometry, so it changes no tuning key
* and no selection fold. Where nothing measured it -- a tool selecting without an engine -- it is
* absent, and a constraint on an absent key does not hold.
/* A constraint on the machine rather than the geometry. A key starting "device." is matched
* against what the engine measured about the ranks' devices at launch, not against op parameters,
* so architecture plugins and schemas need not carry machine capabilities. Such a key is in no
* geometry, so it changes no tuning key and no selection fold. Where nothing measured it (a tool
* selecting without an engine) it is absent, and a constraint on an absent key does not hold.
*
* device.p2p 1 when every rank's device can read and write every other rank's memory
* directly; 0 when some pair cannot. One rank has no peer to reach, and is 1. */
@@ -329,47 +316,20 @@ typedef struct RadConstraint {
typedef uint32_t rad_weight;
typedef uint32_t rad_buf;
typedef uint32_t rad_op;
/* A KV group handle. It lives here with the other handles because a declaration in rad_builder.h
* carries one: a derived buffer names the KV group its derivation is about. */
/* A KV group handle. Here with the other handles because RadBufDecl in rad_builder.h carries
* one. */
typedef uint32_t rad_kvgroup;
#define RAD_NULL_HANDLE 0u
/* ------------------------------------------------------------------ streams */
/* Opaque to the core in the sense that it never dereferences one. On a card it is a queue of the
* engine's own, NOT a hipStream_t: a kernel plugin launches onto it with hipLaunchKernel (and so
* <<<>>>), hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync, which the engine answers itself,
* and hands it to nothing else in HIP (docs/PLUGIN.md, "What a launch may do"). Under the host
* backend it is a queue the host kernels ignore. */
/* Opaque: the core never dereferences one. On a card it is the engine's own queue, not a
* hipStream_t. A kernel plugin may use it only with hipLaunchKernel (and so <<<>>>),
* hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync, which the engine implements itself, and
* must pass it to nothing else in HIP (docs/PLUGIN.md, "What a launch may do"). Under the host
* backend the host kernels ignore it. */
typedef void* RadStream;
enum { RAD_MAX_KPARAMS = 24, RAD_KPARAM_BLOB = 256 };
typedef struct RadLaunchDesc {
/* The entry symbol, as the launch API takes it. A template instantiation resolves to its own
* symbol, which is the point: `heads` picking a different instantiation moves the FUNCTION,
* not just an argument, and a node whose function moved has to be rebuilt rather than
* updated. The runtime compares this across steps and recaptures when it changes. */
const void* func;
uint32_t grid[3];
uint32_t block[3];
uint32_t shared_bytes;
uint32_t n_params;
/* Pointers to the argument values, in the kernel's declared order -- the `kernelParams`
* convention, so slot i is parameter i and the runtime can rewrite exactly the ones that
* moved. */
void* params[RAD_MAX_KPARAMS];
/* The width of each slot, which the runtime needs for two things it cannot otherwise do:
* compare a slot against the previous step's to see whether it moved, and recognise a slot
* that holds an OPERAND ADDRESS by matching its value against the operands it just passed in.
* That second one is what lets a replay update ten pointers without re-entering the shim --
* the mapping is inferred, so no kernel has to declare it and no out-of-tree author has to
* know it exists. */
uint16_t param_size[RAD_MAX_KPARAMS];
/* Where the values live. The shim writes into this and points `params` here. */
unsigned char blob[RAD_KPARAM_BLOB];
} RadLaunchDesc;
#ifdef __cplusplus
} /* extern "C" */
#endif
+99 -4
View File
@@ -1,10 +1,16 @@
#ifndef RAD_YARN_H
#define RAD_YARN_H
/* Static YaRN coefficients. The architecture resolves the correction bounds using
* the ORIGINAL training length, never the deployment/table length. Kernels share
* the resolved coefficients so direct and table-backed RoPE cannot disagree. */
/* Static YaRN coefficients. The architecture resolves the correction bounds from the original
* training length, never the deployment or table length. Kernels share the resolved coefficients
* so direct and table-backed RoPE cannot disagree.
*
* C++ gets RadYarn with a member frequency() (callable from HIP device code) and default member
* values; C gets the same four-float struct and rad_yarn_frequency(). The two definitions must
* compute the same frequencies; tests/abi_layout_test.cpp compares them. */
#include "rad_plugin.h"
#ifdef __cplusplus
#include <cmath>
#if defined(__HIPCC__)
@@ -14,7 +20,7 @@
#endif
struct RadYarn {
float factor = 0.0f; /* zero: keep the legacy arithmetic exactly */
float factor = 0.0f; /* zero: YaRN off, frequency() returns `inv` unchanged */
float low = 0.0f;
float high = 0.0f;
float magnitude = 1.0f;
@@ -45,5 +51,94 @@ inline bool rad_yarn_valid(const RadYarn& y) {
y.high >= y.low && std::isfinite(y.magnitude) && y.magnitude > 0.0f));
}
/* Llama 3's frequency scaling (transformers' rope_type "llama3"), the other static scaling a
* checkpoint may name: a frequency whose wavelength 2 pi / inv is shorter than orig / high is
* kept, one longer than orig / low is divided by `factor`, and those between are blended,
* s = (orig / wavelength - low) / (high - low), (1 - s) inv / factor + s inv. f32 throughout, as
* transformers computes it. `factor` zero is off. */
struct RadLlama3 {
float factor = 0.0f;
float low = 0.0f; /* low_freq_factor */
float high = 0.0f; /* high_freq_factor */
float orig = 0.0f; /* original_max_position_embeddings */
RAD_YARN_HD float frequency(float inv) const {
if (factor == 0.0f) return inv;
const float wavelen = 6.28318530717958647692f / inv;
if (wavelen < orig / high) return inv;
if (wavelen > orig / low) return inv / factor;
const float sm = (orig / wavelen - low) / (high - low);
return (1.0f - sm) * inv / factor + sm * inv;
}
};
inline RadLlama3 rad_llama3_args(const RadArgs* a) {
const float factor = (float)rad_args_getf_or(a, "llama3_factor", 0.0);
if (factor == 0.0f) return {};
return { factor, (float)rad_args_getf_or(a, "llama3_low", 0.0),
(float)rad_args_getf_or(a, "llama3_high", 0.0),
(float)rad_args_getf_or(a, "llama3_orig", 0.0) };
}
inline bool rad_llama3_valid(const RadLlama3& l) {
return std::isfinite(l.factor) &&
(l.factor == 0.0f || (l.factor >= 1.0f && l.low > 0.0f && l.high > l.low &&
std::isfinite(l.high) && l.orig > 0.0f && std::isfinite(l.orig)));
}
#undef RAD_YARN_HD
#else /* C */
#include <math.h>
typedef struct RadYarn {
float factor; /* zero: YaRN off, rad_yarn_frequency() returns `inv` unchanged */
float low;
float high;
float magnitude; /* 1 when off */
} RadYarn;
static inline float rad_yarn_frequency(const RadYarn* y, float inv, int i) {
float width, ramp, mask;
if (y->factor == 0.0f) return inv;
width = y->high == y->low ? 0.001f : y->high - y->low;
ramp = fminf(1.0f, fmaxf(0.0f, ((float)i - y->low) / width));
mask = 1.0f - ramp;
return (inv / y->factor) * (1.0f - mask) + inv * mask;
}
static inline RadYarn rad_yarn_args(const RadArgs* a) {
RadYarn y = { 0.0f, 0.0f, 0.0f, 1.0f };
y.factor = (float)rad_args_getf_or(a, "yarn_factor", 0.0);
if (y.factor == 0.0f) return y;
y.low = (float)rad_args_getf_or(a, "yarn_low", 0.0);
y.high = (float)rad_args_getf_or(a, "yarn_high", 0.0);
y.magnitude = (float)rad_args_getf_or(a, "yarn_magnitude", 1.0);
return y;
}
typedef struct RadLlama3 {
float factor; /* zero: off */
float low;
float high;
float orig;
} RadLlama3;
static inline float rad_llama3_frequency(const RadLlama3* l, float inv) {
float wavelen, sm;
if (l->factor == 0.0f) return inv;
wavelen = 6.28318530717958647692f / inv;
if (wavelen < l->orig / l->high) return inv;
if (wavelen > l->orig / l->low) return inv / l->factor;
sm = (l->orig / wavelen - l->low) / (l->high - l->low);
return (1.0f - sm) * inv / l->factor + sm * inv;
}
static inline int rad_yarn_valid(const RadYarn* y) {
return isfinite(y->factor) && (y->factor == 0.0f ||
(y->factor >= 1.0f && isfinite(y->low) && isfinite(y->high) && y->high >= y->low &&
isfinite(y->magnitude) && y->magnitude > 0.0f));
}
#endif
#endif
+22 -40
View File
@@ -1,29 +1,20 @@
# Architecture plugins. One directory each, one .so each, linking only rad_abi -- an architecture
# plugin does not link the core.
# Architecture plugins: one directory and one .so each, linking only rad_abi, never the core.
#
# qwen35 covers the Qwen3.5, Qwen3.6 and Qwen3.8 dense models, which all report that id, and
# qwen35moe is the same graph with a routed FFN. See docs/ARCHITECTURES.md for the geometry.
# One plugin per (architecture, quantisation) -- spec §2.4, and the pair is the selection key, so
# qwen35_bf16 and qwen35_fp8 both claim "qwen35" and are told apart by the container's quantisation
# descriptor. See rad_arch_quant in abi/rad_builder.h.
# qwen35 covers the Qwen3.5, Qwen3.6 and Qwen3.8 dense models, which all report that id; qwen35moe
# is the same graph with a routed FFN (docs/ARCHITECTURES.md). There is one plugin per
# (architecture, quantisation) pair, which is the selection key (spec §2.4): qwen35_bf16 and
# qwen35_fp8 both claim "qwen35" and are told apart by the container's quantisation descriptor
# (rad_arch_quant in abi/rad_builder.h).
#
# The plugins are discovered, not listed. A hand-written list can name a plugin that has no
# directory, and a name in a build file that resolves to nothing is worse than no name: it is a
# plugin an operator will look for and not find, with no error anywhere to say it was never built.
# With discovery, what is in the tree is what is built, and what is not in the tree does not appear
# in a list.
#
# Globbed the way libref/CMakeLists.txt globs its translation units, and SORTED, because
# file(GLOB) returns directory order and an unsorted list makes the link order -- and therefore the
# plugin load order, which is the hierarchy that decides which architecture wins a tie -- depend on
# the filesystem.
# Plugins are discovered, not listed, so the build is exactly what is in the tree. The glob is
# sorted because file(GLOB) returns directory order, and the link order sets the plugin load order,
# which decides which architecture wins a tie.
file(GLOB RAD_ARCH_DIRS CONFIGURE_DEPENDS LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/*)
list(SORT RAD_ARCH_DIRS)
# THE INCLUDE SPELLING IS THE INSTALLED ONE. arch/common/ installs as <include>/radiance/arch/, so a
# plugin built against an installed radiance writes `#include <arch/rad_arch.h>`; the plugins in
# this tree write the same, through a directory in the build tree whose arch/ is this common/.
# A plugin here that could only be built here would not be a plugin like any other.
# In-tree plugins use the installed include spelling. arch/common/ installs as
# <include>/radiance/arch/, so plugins write `#include <arch/rad_arch.h>`; in this tree that
# resolves through a build-tree directory whose arch/ links to common/.
set(RAD_ARCH_INCLUDE_ROOT ${CMAKE_BINARY_DIR}/rad_include)
file(MAKE_DIRECTORY ${RAD_ARCH_INCLUDE_ROOT})
if(NOT EXISTS ${RAD_ARCH_INCLUDE_ROOT}/arch)
@@ -36,37 +27,28 @@ foreach(d ${RAD_ARCH_DIRS})
continue()
endif()
get_filename_component(a ${d} NAME)
# common/ is the shared header library every plugin includes, not a plugin. It is excluded by
# name, and that is the only directory with special treatment.
# common/ is the shared header library, not a plugin.
if(a STREQUAL "common")
continue()
endif()
if(EXISTS ${d}/CMakeLists.txt)
# Every plugin carries its own build rules, the ones it would be built with out of this tree.
# Each plugin's own build rules, the same ones it uses out of tree.
add_subdirectory(${a})
else()
# Named rather than skipped in silence. A directory under arch/ with no CMakeLists.txt is
# either a plugin missing its build file or a directory that does not belong here, and both of
# those are things somebody wants to be told about at configure time rather than discovering
# from an architecture the engine cannot find.
# Reported at configure time rather than skipped silently: either a plugin is missing its build
# file or the directory does not belong here.
message(STATUS
"arch: '${a}' has no CMakeLists.txt -- not an architecture plugin, skipped")
endif()
endforeach()
# arch/common/ ships. abi/rad_builder.h tells a plugin author, in the ABI header itself, to use the
# grp_layer()/grp_expert()/grp_model() inline functions in arch/common/rad_arch.h rather than the
# rad_group_*() macros beneath that note, because those macros are C compound literals and C++
# accepts them only as a GNU extension -- and an architecture plugin in C++ is the norm. Without
# this install the shipped header would point at a file that is not shipped, and the one documented
# way to write a conforming plugin would be available only inside this tree.
# arch/common/ ships: abi/rad_builder.h directs C++ plugin authors to the grp_*() helpers in
# arch/common/rad_arch.h instead of the rad_group_*() compound-literal macros (a GNU extension in
# C++).
#
# Installed FLAT into arch/, which is what makes it work without touching a single #include:
# these headers include each other by bare basename ("rad_arch.h", "rad_fp8.h"), which resolves
# relative to the including file in both trees, and rad_arch.h's own "rad_builder.h" resolves
# against the include root that radiance::abi puts on the path. Every plugin, in this tree or out of
# it, writes `#include <arch/rad_arch.h>` -- see RAD_ARCH_INCLUDE_ROOT above for how that resolves
# here.
# Installed flat into arch/. These headers include each other by bare basename, which resolves
# relative to the including file in both trees, and rad_arch.h's "rad_builder.h" resolves against
# the include root that radiance::abi provides.
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/common/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/radiance/arch
FILES_MATCHING PATTERN "*.h")
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/anima -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(anima LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(anima architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/anima.cpp)
+1370
View File
File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/bailing_hybrid -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(bailing_hybrid LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(bailing_hybrid architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid.cpp)
+888
View File
@@ -0,0 +1,888 @@
/* bailing_hybrid -- Ling-3.0-flash and its fine-tunes (`model_type: bailing_hybrid`,
* BailingMoeV3ForCausalLM), from the bf16 checkpoint, the routed experts as a recipe stores them
* (data/recipes/ling3-w4a8-rtn.recipe, ling3-w4a8-gptq.recipe).
*
* ============================== WHAT IT SERVES ==============================
*
* layers 42 in groups of six: five Kimi delta attention (KDA) layers, then one dense
* latent attention (MLA) layer, so layers 5, 11, ..., 41 are MLA
* KDA 32 heads of 128, separate q/k/v projections each with its own causal
* convolution, a full-rank per-channel forget gate (`f_proj`) and output gate
* (`g_proj`), lower bound -5
* MLA no query LoRA, a 512-wide latent and a 64-wide rotary part (interleaved pairs),
* heads of 128 + 64, values of 128, a sigmoid gate per head
* feed-forward layers 0-1 dense (6144); from layer 2, 512 experts of 768 at top-8 under
* group-limited sigmoid routing (8 groups, 4 kept, a correction bias, x2.5), an
* ungated shared expert, and a SwiGLU clipped after the SiLU in the last layers
* (`expert_swiglu_limit_list`, `share_expert_swiglu_limit_list`, as vLLM and
* SGLang serve it; HF's reference ignores it)
*
* The KDA core is GLM-5.3's (KdaState), the router GLM-5.3's with groups (GlmRouter), the
* feed-forward MoeFP8. The KDA and MLA blocks around them are in this file.
*
* ============================== THE LATENT ATTENTION ==============================
*
* The MLA attends in the latent. The query projection is served as two, its heads' rotary rows and
* their nope rows (row maps over q_proj), so each is a plain [T, heads * width] plane: `rope` turns
* the first, and the second is absorbed into the latent through kv_b's key rows (mla_project).
* `mla_attn_paged` scores against a cache row of [normed latent 512 | rotated key 64] and returns
* the latent, gated per head; kv_b's value rows expand it. The cache row is stored as one KV head
* of 288, the latent's first 288 values in the K slot and the rest in the V slot.
*
* ============================== THE DRAFTER ==============================
*
* The MTP layer (checkpoint layer 42: an MLA layer with the full routed feed-forward) is a serial
* drafter around GlmMtp, declared when the deployment speculates.
*
* docs/ARCHITECTURES.md describes the model and its traps. */
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <arch/rad_arch.h>
#include <arch/rad_block_glm_kda.h>
#include <arch/rad_block_glm_mtp.h>
#include <arch/rad_block_mlp_fp8.h>
#include <arch/rad_block_moe_fp8.h>
namespace bailing_hybrid {
using namespace rad::arch;
/* The released geometry this graph is written for; a checkpoint that differs is refused by name. */
struct Shape {
int64_t n_embd = 0, n_layer = 0, heads = 0, head_dim = 0, nope = 0, rope = 0, v_dim = 0,
latent = 0, experts = 0, top_k = 0, groups = 0, topk_groups = 0, ff_exp = 0,
ff_shared = 0, ff_dense = 0, dense_layers = 0, group_size = 0, conv = 0;
double lower = -5, route_scale = 1;
std::vector<double> lim_exp, lim_shared;
};
/* A KDA layer: the q/k/v, beta, forget and output-gate projections into KdaState, then o_proj and
* its all-reduce. */
struct LingKda {
struct Wire {
ActFP8 input{};
rad_buf out = 0;
ActFP8 core_out{};
KdaState::Wire core{};
};
Geom g{};
Wire w{};
KdaState core{};
LinearFP8 qkv{}, beta{}, forget{}, gate{}, output{};
QuantFP8 out_quant{};
rad_op op_ar = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& sh, int l,
const Wire& wire, const char* pre, rad_kvgroup state, rad_kvgroup history) {
g = geom;
w = wire;
const int64_t heads = sh.heads / g.world, width = heads * sh.head_dim;
const auto grp = grp_layer(l);
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), 3 * width, g.n_embd,
RAD_SHARD_ROW, grp,
{ nm.ckpt("%s.q_proj.weight", pre), nm.ckpt("%s.k_proj.weight", pre),
nm.ckpt("%s.v_proj.weight", pre) },
w.input, w.core.qkv, 0, { width, width, width }));
RAD_ARCH_TRY(beta.declare(b, nm, g, nm.f("blk.%d.attn_beta", l), heads, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.b_proj.weight", pre) },
w.input, w.core.beta));
RAD_ARCH_TRY(forget.declare(b, nm, g, nm.f("blk.%d.attn_forget", l), width, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.f_proj.weight", pre) },
w.input, w.core.a));
RAD_ARCH_TRY(gate.declare(b, nm, g, nm.f("blk.%d.attn_gate", l), width, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) },
w.input, w.core.gate));
KdaState::Config kc;
kc.heads = heads;
kc.dim = sh.head_dim;
kc.width = sh.conv;
kc.lower = sh.lower;
KdaState::Src ks{ nm.ckpt("%s.q_conv1d.weight", pre), nm.ckpt("%s.k_conv1d.weight", pre),
nm.ckpt("%s.v_conv1d.weight", pre), nm.ckpt("%s.A_log", pre),
nm.ckpt("%s.dt_bias", pre), nm.ckpt("%s.o_norm.weight", pre) };
RAD_ARCH_TRY(core.declare(b, nm, g, l, state, history, kc, w.core, ks));
const char* on = nm.f("blk.%d.attn_output", l);
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.o_proj.weight", pre) }));
if (!output.reads_x) RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, width));
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, width, RAD_SHARD_COL, grp,
{ nm.ckpt("%s.o_proj.weight", pre) }, w.core_out, w.out));
op_ar = GlmTp::reduce(b, g, w.out);
return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
qkv.step(c, w.input, w.core.qkv, T);
beta.step(c, w.input, w.core.beta, T);
forget.step(c, w.input, w.core.a, T);
gate.step(c, w.input, w.core.gate, T);
core.step(c, batch);
out_quant.step(c, T);
output.step(c, w.core_out, w.out, T);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.out, T), RAD_NONE);
}
};
/* A dense MLA layer, attending in the latent (the file's head comment). The latent cache is
* replicated: every rank projects and stores the whole row, and splits the heads. */
struct LingMla {
struct Wire {
ActFP8 input{};
rad_buf q_rope = 0; /* [T, heads * rope] */
rad_buf q_nope = 0; /* [T, heads * nope] */
rad_buf row = 0; /* [T, latent + rope], the cache row */
rad_buf q_lat = 0; /* [T, heads, latent] */
rad_buf gate = 0; /* [T, heads] */
rad_buf attn = 0; /* [T, heads, latent] */
ActFP8 value{}; /* [T, heads * v] */
rad_buf out = 0;
};
Geom g{};
Shape s{};
Wire w{};
int layer = 0;
int64_t heads = 0, qw = 0, cw = 0;
rad_kvgroup kv = 0;
LinearFP8 q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{};
QuantFP8 value_quant{};
rad_weight kv_gain = 0, kv_b = 0;
rad_op op_kv_norm = 0, op_q_rope = 0, op_k_rope = 0, op_store = 0, op_absorb = 0, op_attn = 0,
op_expand = 0, op_ar = 0;
int64_t block = 0;
static constexpr int64_t kBlock = 16;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& shape, int l,
const Wire& wire, const char* pre, rad_kvgroup group) {
g = geom;
s = shape;
w = wire;
layer = l;
kv = group;
heads = s.heads / g.world;
qw = s.rope + s.nope;
cw = s.latent + s.rope;
const auto grp = grp_layer(l);
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
/* One row map a part, a piece a head: [h * (nope + rope) + off, + width). Successive ROWS
* maps for one name extend it in call order (rad_builder.h), eight pieces a map. */
const char* qsrc = nm.ckpt("%s.q_proj.weight", pre);
auto part = [&](const char* name, int64_t off, int64_t width) -> int {
for (int64_t h0 = 0; h0 < s.heads; h0 += 8) {
RadNameMap m = map_base(name, RAD_MAP_ROWS);
for (int64_t h = h0; h < std::min(h0 + 8, s.heads); ++h) {
m.src[m.n_src] = qsrc;
m.src_index[m.n_src] = (int)(h * qw + off);
m.src_rows[m.n_src] = width;
++m.n_src;
}
RAD_ARCH_TRY(rad_decl_name_map(b, &m));
}
return RAD_OK;
};
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_rope.weight", l), s.nope, s.rope));
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_nope.weight", l), 0, s.nope));
q_rope_proj.mapped = q_nope_proj.mapped = true;
RAD_ARCH_TRY(q_rope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_rope", l), heads * s.rope,
g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_rope));
RAD_ARCH_TRY(q_nope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_nope", l), heads * s.nope,
g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_nope));
RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), cw, g.n_embd,
RAD_SHARD_NONE, grp, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", pre) },
w.input, w.row));
const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", pre)));
kv_gain = decl_w(b, kn, RAD_F32, { s.latent }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
if (!kv_gain) return RAD_E_INVAL;
op_kv_norm = rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", s.latent),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(kv_gain)),
{ w.row }, { w.row });
op_q_rope = rw(b, decl_rope(b, g, g.max_tok, s.rope, heads, 0, s.rope, "gptj"), { w.q_rope },
{ w.q_rope });
op_k_rope = rw(b, decl_rope(b, g, g.max_tok, s.rope, 1, 0, s.rope, "gptj"), { w.row },
{ w.row });
/* The first op after the group to carry a block size claims it (rad_builder.cpp,
* find_kv_consumer). */
op_store = rw(b,
RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cw / 2),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", kBlock),
RAD_STR("kv_dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.row }, {});
const char* bn = nm.f("blk.%d.attn_kv_b.weight", l);
RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.kv_b_proj.weight", pre)));
kv_b = decl_w(b, bn, RAD_BF16, { heads * (s.nope + s.v_dim), s.latent }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_ROW, grp);
if (!op_kv_norm || !op_q_rope || !op_k_rope || !op_store || !kv_b) return RAD_E_INVAL;
op_absorb = rw(b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", heads),
RAD_INT("head_dim", s.nope), RAD_INT("latent_dim", s.latent),
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(kv_b)),
{ w.q_nope }, { w.q_lat });
RAD_ARCH_TRY(g_proj.declare(b, nm, g, nm.f("blk.%d.attn_head_gate", l), heads, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) },
w.input, w.gate));
op_attn = rw(b,
RAD_OP(b, "mla_attn_paged",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", heads),
RAD_INT("latent_dim", s.latent), RAD_INT("rope_dim", s.rope),
RAD_INT("block_size", kBlock),
RAD_F64("scale", 1.0 / std::sqrt((double)qw)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.q_lat, w.q_rope, w.gate }, { w.attn });
op_expand = rw(b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", heads),
RAD_INT("head_dim", s.v_dim), RAD_INT("latent_dim", s.latent),
RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(kv_b)),
{ w.attn }, { w.value.x });
if (!op_absorb || !op_attn || !op_expand) return RAD_E_INVAL;
block = rad_kv_block_size(b, kv);
if (block != kBlock) {
fprintf(stderr, "radiance: bailing_hybrid: the latent cache's block is %lld tokens and "
"its ops are declared at %lld\n", (long long)block, (long long)kBlock);
return RAD_E_INVAL;
}
const char* on = nm.f("blk.%d.attn_output", l);
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.dense.weight", pre) }));
if (!output.reads_x) RAD_ARCH_TRY(value_quant.declare(b, g, w.value, heads * s.v_dim));
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, heads * s.v_dim, RAD_SHARD_COL, grp,
{ nm.ckpt("%s.dense.weight", pre) }, w.value, w.out));
op_ar = GlmTp::reduce(b, g, w.out);
return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const auto* kb = kv_batch(batch, kv);
if (!kb || !kb->slot_mapping || !kb->block_table || !kb->seqused) {
rad_step_fail(c, "bailing_hybrid MLA requires the latent cache's slot mapping, block "
"table and sequence lengths");
return;
}
const int64_t T = batch->n_tok, S = batch->n_seq;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
q_rope_proj.step(c, w.input, w.q_rope, T);
q_nope_proj.step(c, w.input, w.q_nope, T);
kv_a.step(c, w.input, w.row, T);
g_proj.step(c, w.input, w.gate, T);
RAD_ISSUE_N(c, op_kv_norm, T, bcol(w.row, 0, s.latent, T), RAD_W(kv_gain),
bcol(w.row, 0, s.latent, T));
RAD_ISSUE_N(c, op_q_rope, T, brows(w.q_rope, T), pos);
RAD_ISSUE_N(c, op_k_rope, T, bcol(w.row, s.latent, s.rope, T), pos);
RAD_ISSUE_N(c, op_store, T, bcol(w.row, 0, cw / 2, T), bcol(w.row, cw / 2, cw / 2, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
RAD_ISSUE_N(c, op_absorb, T, brows(w.q_nope, T), RAD_W(kv_b), brows(w.q_lat, T));
RAD_ISSUE_N(c, op_attn, T, brows(w.q_lat, T), brows(w.q_rope, T), kv_cache(kv, layer),
praw2(kb->block_table, RAD_I32, S, kb->block_table_pitch),
praw(kb->seqused, RAD_I32, S), praw(batch->cu_seqlens, RAD_I32, S + 1),
brows(w.gate, T), brows(w.attn, T));
RAD_ISSUE_N(c, op_expand, T, brows(w.attn, T), RAD_W(kv_b), brows(w.value.x, T));
value_quant.step(c, T);
output.step(c, w.value, w.out, T);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.out, T), RAD_NONE);
}
};
struct Layer {
bool mla = false, dense = false;
rad_weight gain = 0;
NormQuantFP8 norm{};
LingKda kda{};
LingMla attn{};
rad_op op_add = 0;
MlpFP8 mlp{};
MoeFP8 moe{};
};
struct Model {
Names nm{};
Geom g{};
Shape s{};
std::vector<Layer> layers;
rad_kvgroup latent = 0, state = 0, conv = 0;
rad_buf x = 0, y = 0, final_hidden = 0, logit_input = 0, logits = 0;
ActFP8 act{};
LingKda::Wire kw{};
LingMla::Wire aw{};
MlpFP8::Wire dw{};
MoeFP8::Wire mw{};
rad_weight token = 0, head = 0, final_gain = 0;
rad_op embed = 0, embed_ar = 0, norm = 0, gather = 0, head_op = 0;
/* The draft head and its layer, declared only when the deployment speculates. */
bool have_mtp = false;
GlmMtp mtp{};
Layer draft{};
};
static Model g_model[MAX_SLOTS];
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
return rad_meta_geti(m, key, fallback);
}
static std::vector<double> cfg_list(const RadModelMeta* m, const char* key) {
std::vector<double> v;
for_each_token(rad_meta_gets(m, key, ""), [&](const char* t, size_t) {
v.push_back(std::strtod(t, nullptr));
return true;
});
return v;
}
/* Layer l's SwiGLU clamp from a per-layer list; 0 (none) past its end or where it says 0. */
static double limit_at(const std::vector<double>& v, int64_t l) {
return l < (int64_t)v.size() && v[(size_t)l] > 0 ? v[(size_t)l] : 0;
}
/* The last layer of each group of `layer_group_size` is MLA, and so is every layer of an
* incomplete last group. */
static bool is_mla(const Shape& s, int64_t l) {
return (l + 1) % s.group_size == 0 || l >= s.n_layer / s.group_size * s.group_size;
}
static int read_shape(const RadModelMeta* meta, Shape& s) {
s.n_embd = meta->n_embd;
s.n_layer = meta->n_layers;
s.heads = cfg(meta, "num_attention_heads", 0);
s.head_dim = cfg(meta, "head_dim", 0);
s.nope = cfg(meta, "qk_nope_head_dim", 0);
s.rope = cfg(meta, "qk_rope_head_dim", 0);
s.v_dim = cfg(meta, "v_head_dim", 0);
s.latent = cfg(meta, "kv_lora_rank", 0);
s.experts = cfg(meta, "num_experts", 0);
s.top_k = cfg(meta, "num_experts_per_tok", 0);
s.groups = cfg(meta, "n_group", 1);
s.topk_groups = cfg(meta, "topk_group", s.groups);
s.ff_exp = cfg(meta, "moe_intermediate_size", 0);
s.ff_shared = cfg(meta, "moe_shared_expert_intermediate_size", 0) *
cfg(meta, "num_shared_experts", 0);
s.ff_dense = cfg(meta, "intermediate_size", 0);
s.dense_layers = cfg(meta, "first_k_dense_replace", 0);
s.group_size = cfg(meta, "layer_group_size", 0);
s.conv = cfg(meta, "short_conv_kernel_size", 0);
s.lower = rad_meta_getf(meta, "kda_lower_bound", 0.0);
s.route_scale = rad_meta_getf(meta, "routed_scaling_factor", 0.0);
s.lim_exp = cfg_list(meta, "expert_swiglu_limit_list");
s.lim_shared = cfg_list(meta, "share_expert_swiglu_limit_list");
const struct {
const char* what;
bool ok;
} need[] = {
{ "head_dim 128 (KDA)", s.head_dim == 128 },
{ "qk_nope_head_dim == v_head_dim (mla_project's head)", s.nope > 0 && s.nope == s.v_dim },
{ "an even qk_rope_head_dim", s.rope > 0 && !(s.rope & 1) },
{ "an even kv_lora_rank + qk_rope_head_dim", s.latent > 0 && !((s.latent + s.rope) & 1) },
{ "q_lora_rank null", cfg(meta, "q_lora_rank", 0) == 0 },
{ "no_kda_lora", cfg(meta, "no_kda_lora", 0) != 0 },
{ "kda_safe_gate", cfg(meta, "kda_safe_gate", 1) != 0 },
{ "a negative kda_lower_bound", s.lower < 0 && std::isfinite(s.lower) },
{ "rope_interleave", cfg(meta, "rope_interleave", 0) != 0 },
{ "head-wise gated attention",
!std::strcmp(rad_meta_gets(meta, "gated_attention_proj_granularity_type", ""),
"head_wise") },
{ "sigmoid scoring", !std::strcmp(rad_meta_gets(meta, "score_function",
rad_meta_gets(meta, "scoring_func", "")),
"sigmoid") },
{ "one shared expert", cfg(meta, "num_shared_experts", 0) == 1 },
{ "a layer group", s.group_size > 1 },
{ "a 4-tap short convolution", s.conv == 4 },
{ "experts, top-k and groups", s.experts > 0 && s.top_k > 0 && s.groups >= 1 &&
s.experts % s.groups == 0 && s.topk_groups >= 1 &&
s.topk_groups <= s.groups },
{ "a positive routed_scaling_factor", s.route_scale > 0 },
{ "no rope scaling", !rad_meta_gets(meta, "rope_scaling.type", nullptr) &&
!rad_meta_gets(meta, "rope_scaling.rope_type", nullptr) },
};
for (const auto& n : need)
if (!n.ok) {
fprintf(stderr, "radiance: bailing_hybrid: this plugin serves %s, and the checkpoint "
"differs\n", n.what);
return RAD_E_UNSUPPORTED;
}
return RAD_OK;
}
/* A rank's slice of a width of `blocks` 128-column blocks: blocks [lo, hi) in the order of the
* ranks starting at `first`, the first `blocks % world` ranks of that order one block wider. */
static void slice_of(int64_t blocks, int world, int rank, int first, int64_t* lo, int64_t* hi) {
const int p = ((rank - first) % world + world) % world;
const int64_t base = blocks / world, extra = blocks % world;
*lo = p * base + std::min<int64_t>(p, extra);
*hi = *lo + base + (p < extra ? 1 : 0);
}
/* ============================== The trunk's buffers ============================== */
static int buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& s = m.s;
auto& nm = m.nm;
const int64_t T = g.max_tok, E = g.n_embd, H = s.heads / g.world, W = H * s.head_dim;
auto bf = [&](const char* n, std::initializer_list<int64_t> shape) {
return decl_b(b, nm.f("%s", n), RAD_BF16, shape);
};
m.x = bf("residual", { T, E });
m.y = bf("attn_delta", { T, E });
m.act.x = bf("normed", { T, E });
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E));
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, E }, RAD_BUF_PERSIST);
m.logit_input = bf("logit_input", { g.max_logit_rows, E });
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
auto& kw = m.kw;
kw.input = m.act;
kw.out = m.y;
kw.core.qkv = bf("kda_qkv", { T, 3 * W });
kw.core.conv = bf("kda_convolved", { T, 3 * W });
kw.core.a = bf("kda_forget", { T, W });
kw.core.beta = bf("kda_beta", { T, H });
kw.core.gate = bf("kda_gate", { T, W });
kw.core.out = bf("kda_out", { T, W });
kw.core_out.x = kw.core.out;
RAD_ARCH_TRY(kw.core_out.declare_qs(b, nm, g, "kda_out", W));
auto& aw = m.aw;
aw.input = m.act;
aw.out = m.y;
aw.q_rope = bf("mla_q_rope", { T, H * s.rope });
aw.q_nope = bf("mla_q_nope", { T, H * s.nope });
aw.row = bf("mla_row", { T, s.latent + s.rope });
aw.q_lat = bf("mla_q_latent", { T, H * s.latent });
aw.gate = bf("mla_gate", { T, H });
aw.attn = bf("mla_attn_latent", { T, H * s.latent });
aw.value.x = bf("mla_value", { T, H * s.v_dim });
RAD_ARCH_TRY(aw.value.declare_qs(b, nm, g, "mla_value", H * s.v_dim));
auto& dw = m.dw;
dw.x = m.x;
dw.h = m.act;
dw.gate_up = bf("dense_gate_up", { T, 2 * g.n_ff });
dw.ffn.x = bf("dense_ff", { T, g.n_ff });
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
return RAD_OK;
}
static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, E = g.n_embd, F = mc.n_ff_exp, k = mc.top_k;
auto bf = [&](const char* n, std::initializer_list<int64_t> shape) {
return decl_b(b, nm.f("%s", n), RAD_BF16, shape);
};
auto& mw = m.mw;
mw.x = m.x;
mw.h = m.act;
mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, mc.n_expert_all });
mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, k });
mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, k });
mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { mc.n_expert + 1 });
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { mc.n_expert });
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * k });
mw.egu = bf("expert_gate_up", { T * k, 2 * F });
mw.eff.x = bf("expert_ff", { T * k, F });
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k));
mw.edn = bf("expert_down", { T * k, E });
if (mc.expert_rot) {
mw.hr.q = decl_b(b, nm.f("normed_rot.q"), RAD_F8E4M3, { T, E });
mw.hr.s = decl_b(b, nm.f("normed_rot.s"), RAD_F32, { T, E / RAD_FP8_BLOCK });
if (!mw.hr.q || !mw.hr.s) return RAD_E_INVAL;
}
if (mc.n_ff_shared > 0) {
mw.sgu = bf("shared_gate_up", { T, 2 * mc.n_ff_shared });
mw.sff.x = bf("shared_ff", { T, mc.n_ff_shared });
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", mc.n_ff_shared));
mw.sout = bf("shared_out", { T, E });
mw.sgate = bf("shared_one", { T, 1 });
}
return RAD_OK;
}
/* ============================== declare ============================== */
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
const int world = ctx->world_size ? ctx->world_size : 1;
/* A sizing declare writes scratch: the step reads g_model, filled by the real declare at the
* real max_tok (RadBuildCtx::shape_probe). */
static thread_local Model probe_model;
Model& m = ctx->shape_probe ? probe_model : g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
auto& g = m.g;
auto& s = m.s;
auto& nm = m.nm;
RAD_ARCH_TRY(read_shape(meta, s));
if (world != 1 && world != 2 && world != 4) {
fprintf(stderr, "radiance: bailing_hybrid: --tp %d; the head and expert splits are built "
"for 1, 2 or 4 ranks\n", world);
return RAD_E_UNSUPPORTED;
}
if (s.heads % world || s.ff_exp % RAD_FP8_BLOCK || s.ff_shared % RAD_FP8_BLOCK ||
s.ff_exp / RAD_FP8_BLOCK < world) {
fprintf(stderr, "radiance: bailing_hybrid: %lld heads and experts of %lld do not split "
"over %d ranks in whole heads and 128-column blocks\n",
(long long)s.heads, (long long)s.ff_exp, world);
return RAD_E_UNSUPPORTED;
}
if (ctx->max_spec > 31) {
fprintf(stderr, "radiance: bailing_hybrid: the KDA verify pass takes at most 32 rows a "
"sequence, so --num-speculative-tokens is at most 31\n");
return RAD_E_UNSUPPORTED;
}
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) {
fprintf(stderr, "radiance: bailing_hybrid: the latent and KDA caches are bf16; run with "
"--kv-cache-dtype bf16\n");
return RAD_E_UNSUPPORTED;
}
RAD_ARCH_TRY(geom_from(g, meta, ctx, "bf16", RAD_BF16));
g.head_dim = s.head_dim;
/* ---- the routed experts' slice of this rank: whole at one rank, halves at two, and at four
* the six 128-column blocks of an expert split 2, 2, 1, 1 over the ranks, rotated by the
* expert's number mod 4, so every rank carries six blocks per four experts (moe_gemm_q_mod4).
* The shared expert splits the same way, unrotated. */
MoeFP8::Config mc;
mc.n_expert = mc.n_expert_all = s.experts;
mc.top_k = s.top_k;
mc.sigmoid_router = 1;
mc.route_scale = s.route_scale;
mc.norm_topk = cfg(meta, "norm_topk_prob", 1) != 0;
mc.n_group = s.groups;
mc.topk_group = s.topk_groups;
mc.shared_ungated = 1;
mc.swiglu_step = 1;
mc.rows = g.max_tok;
/* GPTQ calibration (RADIANCE_CALIB_DIR): the tap writes each expert's down Hessian over its
* whole width, so a calibration run gives every rank whole experts (below). */
mc.calib = calib_dir() != nullptr ? 1 : 0;
mc.probed_expert = (int64_t)g.rank * (s.experts / world);
const int64_t eb = s.ff_exp / RAD_FP8_BLOCK, sb = s.ff_shared / RAD_FP8_BLOCK;
if (world == 4) {
int64_t widest = 0;
for (int q = 0; q < 4; ++q) {
int64_t lo, hi;
slice_of(eb, world, g.rank, q, &lo, &hi);
mc.ff_lo4[q] = lo * RAD_FP8_BLOCK;
mc.ff_hi4[q] = hi * RAD_FP8_BLOCK;
widest = std::max(widest, mc.ff_hi4[q] - mc.ff_lo4[q]);
}
mc.n_ff_exp = widest;
} else if (eb % world == 0) {
mc.n_ff_exp = s.ff_exp / world;
} else {
fprintf(stderr, "radiance: bailing_hybrid: experts of %lld do not halve into 128-column "
"blocks\n", (long long)s.ff_exp);
return RAD_E_UNSUPPORTED;
}
if (sb % world == 0) {
mc.n_ff_shared = s.ff_shared / world;
} else {
int64_t lo, hi;
slice_of(sb, world, g.rank, 0, &lo, &hi);
mc.shared_lo = lo * RAD_FP8_BLOCK;
mc.shared_hi = hi * RAD_FP8_BLOCK;
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
}
if (s.ff_dense % (world * RAD_FP8_BLOCK)) {
fprintf(stderr, "radiance: bailing_hybrid: the dense feed-forward's %lld columns do not "
"split over %d ranks in 128-column blocks\n", (long long)s.ff_dense, world);
return RAD_E_UNSUPPORTED;
}
g.n_ff_all = s.ff_dense;
g.n_ff = s.ff_dense / world;
/* ---- each routed layer's expert format, read before any buffer is declared: rotated experts
* need the rotated activation pair, sized here. The MTP layer follows the trunk's. */
const bool mtp = ctx->max_spec > 0 && cfg(meta, "num_nextn_predict_layers", 0) == 1;
std::vector<MoeFP8::Src> msrc((size_t)s.n_layer + 1);
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
const char* pre = nm.ckpt("model.layers.%d", l);
MoeFP8::Src& ms = msrc[(size_t)l];
ms.cfg = mc;
ms.cfg.swiglu_limit = limit_at(s.lim_exp, l);
ms.cfg.shared_swiglu_limit = limit_at(s.lim_shared, l);
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
ms.router = nm.ckpt("%s.mlp.gate.weight", pre);
ms.router_bias = nm.ckpt("%s.mlp.gate.expert_bias", pre);
ms.experts = nm.ckpt("%s.mlp.experts", pre);
ms.shared = nm.ckpt("%s.mlp.shared_experts", pre);
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, ms, &ms.cfg));
if (ms.cfg.expert_rot) mc.expert_rot = 1;
if (ms.cfg.expert_bf16) mc.expert_bf16 = 1;
}
/* ---- whole experts per rank for a calibration run and for bf16 experts (a slice of a bf16
* expert is not one container run), as qwen4exp does: rank r owns experts [r E/W, (r+1) E/W).
* Served to calibrate and compare, not for decode speed. */
if (world > 1 && (mc.calib || mc.expert_bf16)) {
int64_t per = 0;
RAD_ARCH_TRY(divide_or_fail(s.experts, world, "num_experts", &per));
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
auto& c = msrc[(size_t)l].cfg;
c.n_expert = per;
c.expert_base = (int64_t)g.rank * per;
c.n_ff_exp = s.ff_exp;
for (int q = 0; q < 4; ++q) c.ff_lo4[q] = c.ff_hi4[q] = 0;
}
mc.n_expert = per;
mc.expert_base = (int64_t)g.rank * per;
mc.n_ff_exp = s.ff_exp;
rad_note(b, "%s: rank %d owns experts [%lld, %lld) of %lld whole",
mc.calib ? "calibration (each expert's Hessian is over its whole width)"
: "bf16 experts",
g.rank, (long long)mc.expert_base, (long long)(mc.expert_base + per),
(long long)s.experts);
}
RAD_ARCH_TRY(buffers(b, m));
RAD_ARCH_TRY(moe_buffers(b, m, mc));
/* ---- the caches: the MLA layers' latent rows, the KDA layers' state and convolution
* history. */
{
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.head_dim = (s.latent + s.rope) / 2;
m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d);
d = {};
d.kind = RAD_KV_LINEAR;
d.dtype = RAD_F32;
d.n_head_kv = s.heads / world;
d.state_dim[0] = d.state_dim[1] = s.head_dim;
m.state = rad_decl_kv_group(b, nm.f("kv_kda"), &d);
d = {};
d.kind = RAD_KV_CONV;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.head_dim = 3 * (s.heads / world) * s.head_dim;
d.conv_width = s.conv;
m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d);
if (!m.latent || !m.state || !m.conv) return RAD_E_INVAL;
}
/* ---- the embedding, the layers, the final norm and the head. */
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.word_embeddings.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, { g.n_vocab, g.n_embd },
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, g.n_embd }, RAD_ACCESS_VOCAB,
RAD_SHARD_ROW, grp_model());
m.final_gain = decl_w(b, nm.f("output_norm.weight"), RAD_F32, { g.n_embd },
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.embed = rw(b,
RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(m.token)),
{}, { m.x });
m.embed_ar = GlmTp::reduce(b, g, m.x, true);
m.layers.resize((size_t)s.n_layer);
for (int l = 0; l < (int)s.n_layer; ++l) {
Layer& lay = m.layers[(size_t)l];
lay.mla = is_mla(s, l);
lay.dense = l < s.dense_layers;
const char* pre = nm.ckpt("model.layers.%d", l);
const char* nn = nm.f("blk.%d.attn_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre)));
lay.gain = decl_w(b, nn, RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
RAD_ARCH_TRY(lay.norm.declare(b, g, lay.gain, m.x, m.act, g.n_embd));
const char* ap = nm.ckpt("%s.attention", pre);
if (lay.mla) {
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, s, l, m.aw, ap, m.latent));
} else {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.state));
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.conv));
RAD_ARCH_TRY(lay.kda.declare(b, nm, g, s, l, m.kw, ap, m.state, m.conv));
}
lay.op_add = rw(b,
RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.x, m.y }, { m.x });
if (!lay.op_add) return RAD_E_INVAL;
if (lay.dense) {
MlpFP8::Src ds{ nm.ckpt("%s.post_attention_layernorm.weight", pre),
nm.ckpt("%s.mlp.gate_proj.weight", pre),
nm.ckpt("%s.mlp.up_proj.weight", pre),
nm.ckpt("%s.mlp.down_proj.weight", pre) };
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, l, m.dw, ds));
} else {
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, m.mw, msrc[(size_t)l]));
}
}
RAD_ARCH_TRY(rad_kv_group_replicated(b, m.latent));
m.norm = rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(m.final_gain)),
{ m.x }, { m.final_hidden });
m.gather = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.final_hidden }, { m.logit_input });
m.head_op =
rw(b,
RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(m.head)),
{ m.logit_input }, { m.logits });
if (!m.embed || !m.norm || !m.gather || !m.head_op) return RAD_E_INVAL;
/* ---- the drafter: GlmMtp at Ling's width and checkpoint names around one more MLA layer
* with the routed feed-forward. It shares the trunk's buffers, latent cache, embedding and
* head. */
if (mtp) {
const int l = (int)s.n_layer;
auto& mt = m.mtp;
mt.width = g.n_embd;
mt.prefix = nm.ckpt("model.layers.%d", l);
mt.layer = l;
mt.norm_src = "final_layernorm.weight";
const GlmMtp::Wire tw{ m.final_hidden, m.logits, m.token, m.head };
RAD_ARCH_TRY(mt.declare_inputs(b, g, tw, false));
Layer& d = m.draft;
d.mla = true;
const char* pre = mt.prefix;
const char* nn = nm.f("blk.%d.attn_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre)));
d.gain = decl_w(b, nn, RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
RAD_ARCH_TRY(d.norm.declare(b, g, d.gain, mt.x, m.act, g.n_embd));
RAD_ARCH_TRY(d.attn.declare(b, nm, g, s, l, m.aw, nm.ckpt("%s.attention", pre), m.latent));
RAD_ARCH_TRY(mt.declare_join(b, m.y));
auto mw = m.mw;
mw.x = mt.x;
RAD_ARCH_TRY(d.moe.declare(b, nm, g, l, mw, msrc[(size_t)l]));
RAD_ARCH_TRY(mt.declare_head(b));
m.have_mtp = true;
}
rad_note(b,
"Ling-3.0 (bailing_hybrid): TP%d, %lld layers, %lld KDA + %lld dense MLA, %lld experts "
"top-%lld in %lld groups (%lld kept), MTP %s",
world, (long long)s.n_layer, (long long)(s.n_layer - s.n_layer / s.group_size),
(long long)(s.n_layer / s.group_size), (long long)s.experts, (long long)s.top_k,
(long long)s.groups, (long long)s.topk_groups, m.have_mtp ? "enabled" : "not declared");
return RAD_OK;
}
/* ============================== step ============================== */
/* RADIANCE_LING_DUMP=DIR: the residual stream after each layer's attention and feed-forward, every
* row of every step, as `<DIR>/s<step>.t<rows>.l<layer>.<attn|ffn>.r<rank>.bf16` ([rows, n_embd]
* bf16). A diagnostic for comparing against a reference model layer by layer; it synchronises the
* stream. */
static void dump(RadCtx* c, const RadBatch* batch, rad_buf x, int64_t E, int layer,
const char* site) {
static const char* dir = std::getenv("RADIANCE_LING_DUMP");
if (!dir || !*dir) return;
const int64_t T = batch->n_tok;
void* p = rad_buf_ptr(c, x);
if (!p) return;
std::vector<uint16_t> h((size_t)(T * E));
if (rad_memcpy_async(h.data(), p, T * E * 2, rad_stream(c)) < 0) return;
rad_stream_sync(rad_stream(c));
char path[512];
std::snprintf(path, sizeof path, "%s/s%d.t%lld.l%d.%s.r%d.bf16", dir, batch->step,
(long long)T, layer, site, rad_rank(c));
if (FILE* f = std::fopen(path, "wb")) {
std::fwrite(h.data(), 2, h.size(), f);
std::fclose(f);
}
}
/* A draft pass as GLM-5.3's (glm5next.cpp): the head's inputs, its MLA layer over every row (a
* history pass fills the draft layer's latent cache for all of them), then on the proposal rows the
* residual join, the routed feed-forward and the head. */
static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
if (!m.have_mtp || batch->draft_pass == 1) {
rad_step_fail(c, "bailing_hybrid MTP pass is not declared or has invalid round 1");
return;
}
const int64_t T = batch->n_tok;
m.mtp.step_inputs(c, batch);
auto& l = m.draft;
l.norm.step(c, T);
l.attn.step(c, batch);
if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return;
m.mtp.step_join(c, batch, m.y);
l.moe.step_rows(c, GlmMtp::head_rows(batch));
m.mtp.step_head(c, batch);
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = g_model[rad_slot(c)];
const int64_t T = batch->n_tok, E = m.g.n_embd;
if (batch->enc) {
rad_step_fail(c, "bailing_hybrid serves text");
return;
}
if (batch->draft_pass) {
draft_pass(c, m, batch);
return;
}
RAD_ISSUE_N(c, m.embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), brows(m.x, T));
if (m.embed_ar) RAD_ISSUE_N(c, m.embed_ar, T * E, brows(m.x, T), RAD_NONE);
for (size_t i = 0; i < m.layers.size(); ++i) {
const Layer& l = m.layers[i];
l.norm.step(c, T);
if (l.mla)
l.attn.step(c, batch);
else
l.kda.step(c, batch);
RAD_ISSUE_N(c, l.op_add, T, brows(m.x, T), brows(m.y, T), brows(m.x, T));
dump(c, batch, m.x, E, (int)i, "attn");
if (l.dense)
l.mlp.step(c, batch);
else
l.moe.step(c, batch);
dump(c, batch, m.x, E, (int)i, "ffn");
}
RAD_ISSUE_N(c, m.norm, T, brows(m.x, T), RAD_W(m.final_gain), brows(m.final_hidden, T));
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.final_hidden, T),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.logit_input, batch->n_out));
RAD_ISSUE_N(c, m.head_op, batch->n_out, brows(m.logit_input, batch->n_out), RAD_W(m.head),
brows(m.logits, batch->n_out));
}
}
/* The default draft depth for `--num-speculative-tokens auto`: GlmMtp's operating point, when the
* checkpoint carries its one MTP layer. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth;
out->shape_probe_ok = 1; /* declare() writes scratch under shape_probe */
return RAD_OK;
}
} /* namespace bailing_hybrid */
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(bailing_hybrid)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(bailing_hybrid, "bailinghybrid", "", "0.1.0",
"Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts")
#endif
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/breeze -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(breeze LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(breeze architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/breeze.cpp)
File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/clef_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(clef_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(clef_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/clef_bf16.cpp)
+70
View File
@@ -0,0 +1,70 @@
/* clef_bf16 -- Cloudflare's clef and clef-flash decision models, bf16: the qwen35_bf16 trunk with
* the joint schema head on the card (arch/common/rad_block_clef.h), served on /v1/systemone.
*
* This is arch/qwen35_bf16/qwen35_bf16.cpp built again under its own architecture id, as
* qwen35_w8a8 is qwen35_fp8 built again: the trunk's declare and step are that file's, untouched,
* and this file adds the head after them. A container selects it with `rad-convert --arch clef`,
* so a plain qwen35 container never pays for the head and the qwen35 plugins carry no decision
* code. The head needs `decision.type=clef` and the head's geometry in the container header,
* which rad-convert writes from joint_head_config.json and joint_head.safetensors (--add).
*/
#define RAD_ARCH_NO_EXPORTS 1
#include "../qwen35_bf16/qwen35_bf16.cpp"
#undef RAD_ARCH_NO_EXPORTS
#include <arch/rad_block_clef.h>
#include <cstdio>
namespace clef_bf16 {
using namespace rad::arch;
/* One head per rank beside the trunk's own per-rank state (qwen35_bf16::g_model). */
static ClefHead g_head[MAX_SLOTS];
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
if (!ClefHead::present(meta)) {
std::fprintf(stderr, "radiance: clef_bf16 serves a container converted with "
"--set decision.type=clef and the head added (--add "
"joint_head.safetensors); this one declares no decision model\n");
return RAD_E_INVAL;
}
RAD_ARCH_TRY(qwen35_bf16::declare(b, meta, ctx));
/* The trunk's declare does not take part in sizing declares (no probe), so its state and the
* head's are the real ones. The head goes after the vision tower: its buffers join the same
* arena, and it reads the final norm's rows, the lm_head and the trunk's cache block size. */
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_build_slot(ctx)];
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
* skips the lm_head on a step every sampled row of which carries a request's words
* (plugin_words_cover_rows) and leaves zero rows instead. */
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
if (!m.op_logits_fill) return RAD_E_INVAL;
ClefHead& h = g_head[rad_build_slot(ctx)];
h = ClefHead{};
return h.declare(b, meta, ctx, m.nm, m.g, m.b_h, m.b_logits, m.w_lm_head, m.kv_full,
(int)m.g.n_layer + 256);
}
static void step(RadCtx* c, const RadBatch* batch) {
qwen35_bf16::step(c, batch);
/* An encoder pass runs the tower alone and leaves no rows for the head. */
if (batch->enc) return;
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_slot(c)];
ClefHead& h = g_head[rad_slot(c)];
/* The final norm's rows are still in `h` after the trunk's step; the logits row of each
* sampled sequence has been written, and the head adds its values beside it. */
h.step_tokens(c, batch, m.b_h);
if (batch->n_out > 0) h.step_heads(c, batch, m.b_logits, m.w_lm_head);
}
} /* namespace clef_bf16 */
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(clef_bf16, "clef", "", "0.1.0",
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_bf16, bf16, "
"with the joint schema head on the card for /v1/systemone")
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/clef_fp8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(clef_fp8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(clef_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/clef_fp8.cpp)
+67
View File
@@ -0,0 +1,67 @@
/* clef_fp8 -- Cloudflare's clef and clef-flash decision models, block fp8: the qwen35_fp8 trunk
* with the joint schema head on the card (arch/common/rad_block_clef.h), served on
* /v1/systemone.
*
* This is arch/qwen35_fp8/qwen35_fp8.cpp built again under its own namespace and architecture
* id, as qwen35_w8a8 and qwen35moe_fp8 are: the trunk's declare, step and probe are that file's,
* untouched, and this file adds the head after them. A container selects it with `rad-convert
* --arch clef` and the fp8 recipe; the lm_head stays bf16, which the head reads.
*/
#define QWEN35_NS qwen35_clef_fp8
#define QWEN35_ARCH_ID "clef"
#define RAD_ARCH_NO_EXPORTS 1
#include "../qwen35_fp8/qwen35_fp8.cpp"
#undef RAD_ARCH_NO_EXPORTS
#include <arch/rad_block_clef.h>
#include <cstdio>
namespace clef_fp8 {
using namespace rad::arch;
static ClefHead g_head[MAX_SLOTS];
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
if (!ClefHead::present(meta)) {
std::fprintf(stderr, "radiance: clef_fp8 serves a container converted with "
"--set decision.type=clef and the head added (--add "
"joint_head.safetensors); this one declares no decision model\n");
return RAD_E_INVAL;
}
RAD_ARCH_TRY(qwen35_clef_fp8::declare(b, meta, ctx));
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_build_slot(ctx)];
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
* skips the lm_head on a step every sampled row of which carries a request's words
* (plugin_words_cover_rows) and leaves zero rows instead. */
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
if (!m.op_logits_fill) return RAD_E_INVAL;
ClefHead& h = g_head[rad_build_slot(ctx)];
h = ClefHead{};
return h.declare(b, meta, ctx, m.nm, m.g, m.a_h.x, m.b_logits, m.w_lm_head, m.kv_full,
(int)m.g.n_layer + 256);
}
static void step(RadCtx* c, const RadBatch* batch) {
qwen35_clef_fp8::step(c, batch);
/* An encoder pass leaves no rows for the head, and a drafter's pass is not a trunk step. */
if (batch->enc || batch->draft_pass != 0) return;
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_slot(c)];
ClefHead& h = g_head[rad_slot(c)];
/* The final norm's rows are in `a_h.x` after either of the trunk's step paths. */
h.step_tokens(c, batch, m.a_h.x);
if (batch->n_out > 0) h.step_heads(c, batch, m.b_logits, m.w_lm_head);
}
} /* namespace clef_fp8 */
RAD_ARCH_PROBE(qwen35_clef_fp8)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(clef_fp8, "clef", "fp8_e4m3", "0.1.0",
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_fp8, "
"block-scaled fp8, with the joint schema head on the card for /v1/systemone")
+851 -454
View File
File diff suppressed because it is too large. Load diff
+210
View File
@@ -0,0 +1,210 @@
/* rad_block_attn.h -- one grouped-query attention block with per-head q/k RMS norms, bf16
* operands, paged KV: Qwen3's attention.
*
* rmsnorm -> q gemm, k gemm, v gemm -> q norm, k norm (per head) -> rope (NeoX)
* -> kv_store -> paged attention -> o gemm -> [all_reduce] -> residual
*
* rad_block_attn_gated.h without the output gate, and more than a flag apart: Qwen3's q_proj is
* [n_head * head_dim, n_embd] (queries only, no interleaved gate), the rotary covers every head
* dimension as plain NeoX over the token's position, and the norms are plain RMS norms,
* `x_hat * w` (Qwen3RMSNorm), not Gemma's `1 + w`. Qwen3-1.7B is Qwen3-ASR's decoder
* (arch/qwen3asr_bf16).
*
* q, k and v are three projections into three contiguous buffers: paged attention reads `q`
* contiguous (libr4d's fill_paged refuses a pitched query), so a fused [q|k|v] row would need a
* copy before attention. Each per-head norm is an ordinary `rmsnorm` with M = tokens x heads and
* n = head_dim, and the rotary is `rope` over q and over k, which every kernel library serves.
*
* Positions are RadBatch::positions, one component a token. A media span in the prompt (an audio
* clip's placeholders) counts up like text, as the reference's position ids do; this block never
* reads the M-RoPE planes.
*/
#ifndef RAD_BLOCK_ATTN_H
#define RAD_BLOCK_ATTN_H
#include "rad_arch.h"
namespace rad {
namespace arch {
struct AttnBF16 {
/* The activation buffers, declared once by the plugin and shared by every layer: layers that
* share a geometry share the buffer (spec §8). */
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the o output */
rad_buf q = 0; /* [max_tok, q_dim] projected, normed, rotated */
rad_buf k = 0; /* [max_tok, kv_dim] */
rad_buf v = 0; /* [max_tok, kv_dim] */
rad_buf attn = 0; /* [max_tok, q_dim] attention output */
};
/* The checkpoint-side names for one layer; the plugin owns the spelling (spec §2.4). */
struct Src {
const char* norm = nullptr; /* input_layernorm.weight */
const char* q = nullptr;
const char* k = nullptr;
const char* v = nullptr;
const char* q_norm = nullptr;
const char* k_norm = nullptr;
const char* o = nullptr;
};
Geom g{};
Wire w{};
int layer = 0;
rad_kvgroup kv = 0;
rad_weight w_norm = 0, w_q = 0, w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0, w_o = 0;
rad_op op_norm = 0, op_q = 0, op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0;
rad_op op_rope_q = 0, op_rope_k = 0, op_kv_store = 0, op_attn = 0, op_o = 0, op_ar = 0;
rad_op op_add = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
const Wire& wire, const Src& src);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
const Wire& wire, const Src& src) {
g = geom; w = wire; layer = l; kv = group;
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
/* KV-head replication is not plumbed here, for the reason rad_block_attn_gated.h gives: the
* plain row-shard of k and v would hand a rank part of one KV head. Refused by name. */
if (g.world > g.n_head_kv_all) {
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
"with n_head_kv = %lld\n", __func__, g.world, (long long)g.n_head_kv_all);
return RAD_E_UNSUPPORTED;
}
/* ---- weights. [out, in], so nothing is transposed at load. q, k and v row-shard by head;
* o column-shards, so each rank holds a partial sum of the residual update. */
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), src.q));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), src.k));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), src.v));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), src.o));
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_q = decl_w(b, nm.f("blk.%d.attn_q.weight", l), RAD_BF16, {q_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
w_k = decl_w(b, nm.f("blk.%d.attn_k.weight", l), RAD_BF16, {kv_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
w_v = decl_w(b, nm.f("blk.%d.attn_v.weight", l), RAD_BF16, {kv_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
/* One gain shared by every head, replicated across ranks though the heads are not. */
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_o = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
auto gemm = [&](int64_t N, int64_t K, rad_weight wt) {
return RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(wt));
};
auto head_norm = [&](int64_t heads, rad_weight wt) {
return RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(wt));
};
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
op_q = rw(b, gemm(q_dim, g.n_embd, w_q), {w.h}, {w.q});
op_k = rw(b, gemm(kv_dim, g.n_embd, w_k), {w.h}, {w.k});
op_v = rw(b, gemm(kv_dim, g.n_embd, w_v), {w.h}, {w.v});
/* Each norm runs in place: a row's scale is computed before the row is written. */
op_q_norm = rw(b, head_norm(g.n_head, w_q_norm), {w.q}, {w.q});
op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k});
/* Two rope calls because q and k are two buffers: a `rope` that names only q heads is a fused
* row with an empty k and v. The full head dim rotates. */
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"),
{w.q}, {w.q});
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim, "neox"),
{w.k}, {w.k});
/* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention
* kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */
op_attn = rw(b, rad_decl_op(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
op_kv_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.k, w.v}, {});
op_o = rw(b, gemm(g.n_embd, q_dim, w_o), {w.attn}, {w.h});
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{w.h}, {w.h});
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h}, {w.x});
return RAD_OK;
}
inline void AttnBF16::step(RadCtx* c, const RadBatch* batch) const {
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
const int64_t T = batch->n_tok;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
RAD_ISSUE(c, op_q, brows(w.h, T), RAD_W(w_q), brows(w.q, T));
RAD_ISSUE(c, op_k, brows(w.h, T), RAD_W(w_k), brows(w.k, T));
RAD_ISSUE(c, op_v, brows(w.h, T), RAD_W(w_v), brows(w.v, T));
RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
RAD_ISSUE(c, op_rope_q, brows(w.q, T), pos);
RAD_ISSUE(c, op_rope_k, brows(w.k, T), pos);
RAD_ISSUE(c, op_kv_store,
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
/* The actual query length selects the band; cu_seqlens carries a ragged step. */
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
brows(w.q, T), kv_cache(kv, layer),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn, T));
RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T));
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_ATTN_H */
+56 -70
View File
@@ -1,42 +1,34 @@
/* rad_block_attn_fp8.h -- the PLAIN GQA attention block with block-scaled FP8 projections.
/* rad_block_attn_fp8.h -- plain GQA attention with block-scaled FP8 projections.
*
* rmsnorm -> quant_act_fp8 -> fused q|k|v gemm_nt_q -> rope -> kv_store -> attn_paged
* -> quant_act_fp8 -> o gemm_nt_q -> [all_reduce] -> residual add
*
* IT IS rad_block_attn_gated_fp8.h WITHOUT THE TWO THINGS THAT MAKE THAT ONE GATED, and those two
* are what a family answers differently rather than what a model tunes:
* rad_block_attn_gated_fp8.h without its two family-specific features:
*
* - NO PER-HEAD Q/K NORM. Qwen3.5 norms each head against its own gain before rotating; LLaMA
* and MiniCPM5 rotate the projection as it comes out of the GEMM. A block that normed anyway
* against an absent gain would be a different model, and one that normed against a gain of
* ones would be a wasted launch a layer.
* - NO OUTPUT GATE. There is no second half of the query projection and no sigmoid: the
* attention output goes straight into the out-projection.
* - No per-head q/k norm. Qwen3.5 norms each head before rotating; LLaMA and MiniCPM5 rotate
* the GEMM output directly.
* - No output gate. The attention output goes straight into the out-projection.
*
* WHAT THAT BUYS is the fused q|k|v, which the gated block cannot have: its query projection is
* [q|gate] interleaved per head and k and v are separate tensors, so there are three GEMMs a layer.
* Here the three weights concatenate along dim 0 into one [q_dim + 2*kv_dim, n_embd] and `rope`
* takes exactly that row -- q heads then k heads, v left alone, which is the operand shape the op
* was written for (docs/OPS.md). One GEMM, one rope, one quantise in front of all of it.
* `rotary_dim` 0 is attention without positions (NoPE, Nemotron-H's attention layers): no `rope`
* is declared, and position reaches the model through its recurrent layers alone.
*
* THE ROW PARTS ARE NOT DECORATION. A tensor-parallel rank owns a slice of EACH of the three
* projections, not a contiguous slice of the stack; without `row_parts` rank 0 gets the whole query
* and rank 1 the whole key and value, and both ranks then compute a perfectly well-formed wrong
* thing. LinearFP8 also checks that each part is a whole number of 128-row scale blocks, which is
* what makes a block-scaled fusion expressible at all.
* That allows a fused q|k|v, which the gated block cannot have (its query projection is [q|gate]
* interleaved per head). The three weights concatenate along dim 0 into one
* [q_dim + 2*kv_dim, n_embd], and `rope` takes that row as is: q heads, then k heads, v untouched
* (docs/OPS.md). One GEMM, one rope and one quantise.
*
* Everything else -- the fused norm/quantise/residual/all-reduce op at the front, the KV group's
* own dtype, the fold flags -- is rad_fp8.h's and rad_block_attn_gated_fp8.h's and is documented
* there.
* `row_parts` is required: a tensor-parallel rank owns a slice of each of the three projections,
* not a contiguous slice of the stack. LinearFP8 checks that each part is a whole number of
* 128-row scale blocks.
*
* The fused front op, the KV dtype and the fold flags are documented in rad_fp8.h and
* rad_block_attn_gated_fp8.h.
*/
#ifndef RAD_BLOCK_ATTN_FP8_H
#define RAD_BLOCK_ATTN_FP8_H
#include "rad_fp8.h"
#include <cstdlib>
#include <cstring>
namespace rad {
namespace arch {
@@ -49,8 +41,8 @@ struct AttnFP8 {
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
};
/* The checkpoint's tensor names. Whether they hold block fp8 already or a dense tensor the
* recipe quantises is the container's business; the declaration is the same either way. */
/* Checkpoint tensor names; the declaration is the same whether they hold block fp8 or a dense
* tensor the recipe quantises. */
struct Src {
const char* norm = nullptr;
const char* q = nullptr;
@@ -64,9 +56,8 @@ struct AttnFP8 {
int layer = 0;
rad_kvgroup kv = 0;
int64_t n_rot = 0;
/* The rotation pairs HALVES (NeoX), which is what HF's rotate_half does and what every LLaMA
* derivative ships. GPT-J's adjacent pairs would be arithmetically silent too -- no per-op
* check tells the two apart -- so this is stated rather than inferred. */
/* The rotation pairs halves (NeoX, HF's rotate_half), as LLaMA derivatives ship. Stated
* explicitly: GPT-J's adjacent pairs would pass every per-op check too. */
const char* mode = "neox";
rad_weight w_norm = 0;
@@ -93,20 +84,21 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
const int64_t q_dim = g.q_dim();
const int64_t kv_dim = g.kv_dim();
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
if (n_rot < 0 || n_rot > g.head_dim || (n_rot & 1)) {
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
(long long)n_rot, (long long)g.head_dim);
return RAD_E_INVAL;
}
/* NO KV-HEAD REPLICATION HERE. The fused [q|k|v] row-shards by head with the plain even shard,
* so above the KV head count a rank would get a slice of one KV head and declare fine while
* reading the wrong rows. rad_block_attn_gated.h refuses for the same reason; the block that
* plumbs geom_from's `kv_off` is rad_block_attn_gated_fp8.h. */
if (g.world > g.n_head_kv_all) {
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
"with n_head_kv = %lld.\n", __func__, g.world,
(long long)g.n_head_kv_all);
/* Above the KV head count geom_from replicates KV heads (rad_arch.h): each of the fused row's
* three parts takes its own span (as gemma4's q|k|v does), q this rank's heads and k and v the
* shared head at `kv_off`, where the even shard would hand a rank part of a head. A smaller
* attention world (Geom::attn_world) is not served here. */
const bool kv_repl = g.world > g.n_head_kv_all;
if (kv_repl && g.attn_world != g.world) {
fprintf(stderr, "radiance: %s replicates KV heads but declares no attention-zero ranks; "
"world_size = %d must be a multiple of n_head_kv = %lld.\n", __func__,
g.world, (long long)g.n_head_kv_all);
return RAD_E_UNSUPPORTED;
}
@@ -114,44 +106,38 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
/* One norm, one quantise, one consumer -- and one op, see rad_fp8.h's NormQuantFP8. */
/* Norm and quantise in one op (rad_fp8.h: NormQuantFP8). */
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
fold ? w.x : 0, 0, ar_in));
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
0, { q_dim, kv_dim, kv_dim }));
if (kv_repl) {
const int64_t lo[3] = { g.rank * q_dim, g.kv_off, g.kv_off };
const int64_t hi[3] = { lo[0] + q_dim, lo[1] + kv_dim, lo[2] + kv_dim };
const int64_t tot[3] = { g.n_head_all * g.head_dim, g.n_head_kv_all * g.head_dim,
g.n_head_kv_all * g.head_dim };
RAD_ARCH_TRY(qkv.span_parts(b, lo, hi, tot, 3));
}
op_rope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", mode), RAD_INT("rotary_dim", n_rot)),
RAD_NOWEIGHTS),
{w.qkv}, {w.qkv});
if (n_rot > 0)
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
{w.qkv}, {w.qkv});
/* THE QUERY IS LIFTED OUT OF THE FUSED ROW, and this op is here because libr4d's paged
* attention indexes `q` as one dense [total_q, n_head, head_dim] block and has no pitch
* argument for it (r4d_attn_args.h, fill_paged). A column slice of the fused projection has a
* row pitch of q_dim + 2*kv_dim, so passing it is refused at issue -- correctly, and loudly.
*
* The gated block beside this one never needs it: its q comes out of a q|gate de-interleave
* that writes a buffer of its own. A plain LLaMA attention has no de-interleave, so the choice
* is one `cast` a layer (this) or splitting the projection into q and kv (two more launches a
* layer, one GEMM and one rope). The copy is the cheaper of the two at decode, which is the
* step that matters, and it is one line to delete if the kernels ever take a q pitch.
*
* `from` and `to` are the same dtype: `cast` with no conversion is this tree's row copy, and
* the drafter tap uses it the same way. */
/* Copies the query out of the fused row: libr4d's paged attention reads `q` as a dense
* [total_q, n_head, head_dim] block with no pitch argument (r4d_attn_args.h, fill_paged), so a
* column slice with pitch q_dim + 2*kv_dim is refused at issue. One copy per layer is cheaper
* at decode than splitting the projection (one more GEMM and one more rope). Remove it if the
* kernels gain a q pitch. `cast` with from == to is this tree's row copy. */
op_qlift = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.qkv}, {w.q});
/* Declared before kv_store because `block_size` is RAD_DERIVED and kv_store reads the resolved
* kernel's value back; see rad_block_attn_gated.h on why the declared order differs from the
* issue order. */
op_attn = rw(b, RAD_OP(b, "attn_paged",
/* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
* explains declare vs issue order). */
op_attn = rw(b, rad_decl_op(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
@@ -169,8 +155,8 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
RAD_NOWEIGHTS),
{w.qkv}, {});
/* The out-projection's input quantiser. The gated block folds this into its gate pass; there
* is no gate here, so it is the plain `quant_act_fp8` over the attention output. */
/* The out-projection's input quantiser; a plain `quant_act_fp8`, as there is no gate pass to
* fold it into. */
RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
RAD_SHARD_COL, grp_layer(l), { src.o }, w.attn, w.h.x));
@@ -204,11 +190,11 @@ inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
nq_h.step(c, T);
qkv.step(c, w.h, w.qkv, T);
/* IN PLACE OVER THE FUSED ROW, which is what makes one launch do both halves: `rope` rotates
* `n_head` query heads then `n_head_kv` key heads and leaves the value heads alone. */
RAD_ISSUE(c, op_rope, brows(w.qkv, T), praw(batch->positions, RAD_I32, T));
/* In place over the fused row: rotates n_head query heads, then n_head_kv key heads, and
* leaves the value heads alone. */
if (op_rope) RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
/* k and v are COLUMN SLICES of the same row, at q_dim and q_dim + kv_dim. */
/* k and v are column slices of the fused row, at q_dim and q_dim + kv_dim. */
RAD_ISSUE(c, op_kv_store,
bcol(w.qkv, q_dim, kv_dim, T), bcol(w.qkv, q_dim + kv_dim, kv_dim, T),
praw(slot, RAD_I32, T), kv_cache(kv, layer));
+100 -171
View File
@@ -1,35 +1,26 @@
/* rad_block_attn_gated.h -- one GATED grouped-query attention block, bf16 operands, paged KV.
/* rad_block_attn_gated.h -- gated grouped-query attention, bf16 operands, paged KV.
*
* rmsnorm -> q|gate gemm, k gemm, v gemm -> qk-norm + rope + gate extraction
* -> kv_store -> paged attention -> attn * sigmoid(gate) -> o gemm -> [all_reduce] -> residual
* rmsnorm -> q|gate gemm, k gemm, v gemm -> qk-norm + rope -> kv_store -> paged attention
* -> attn * sigmoid(gate) -> o gemm -> [all_reduce] -> residual
*
* This is Qwen3.5's attention and not Qwen3's, and the difference is not a flag:
* Qwen3.5's attention, which differs from Qwen3's in three ways:
*
* * `q_proj` emits the query AND a per-head output gate INTERLEAVED at a pitch of 2*head_dim.
* Head h's query is at h*2*head_dim and its gate at h*2*head_dim + head_dim, so neither is a
* contiguous half of the projection and both are strided views of one buffer. libr4d's
* `qk_norm_rope_gate` splits [q|gate] per head and takes the stride off the `qg` OPERAND's own
* row pitch, so the interleaved layout is the one to declare rather than to convert away at
* load. There is no `qg_pitch` PARAMETER to pass -- see pQkNormRopeGate in
* libr4d/r4d_rows.cpp -- the stride comes from the operand.
* * The gate multiplies the attention OUTPUT -- `out = attn * sigmoid(gate)` -- so it is
* extracted before attention and consumed after it. `output_gate_type: "swish"` in the config
* names the GDN block's gate, not this one; llama.cpp uses sigmoid here and it is ground truth
* (../llama.cpp/src/models/qwen35.cpp, build_layer_attn).
* * RoPE is PARTIAL -- `partial_rotary_factor` 0.25 rotates the first 64 of 256 head dims -- and
* it is MROPE. See the note on `mode` in declare(): with one position component per token,
* which is all RadBatch carries, mrope and neox are the same arithmetic, and that equality is
* what makes this declaration honest for text and wrong for an image span.
* * `q_proj` emits the query and a per-head output gate interleaved at a pitch of 2*head_dim:
* head h's query at h*2*head_dim, its gate at h*2*head_dim + head_dim. Both are strided views
* of one buffer. libr4d's `qk_norm_rope_gate` takes the stride from the `qg` operand's row
* pitch (there is no `qg_pitch` parameter; pQkNormRopeGate in libr4d/r4d_rows.cpp), so the
* interleaved layout is declared as is.
* * The gate multiplies the attention output, `out = attn * sigmoid(gate)`. The config's `output_gate_type: "swish"` refers to the
* GDN block's gate; this one is sigmoid, as in llama.cpp (src/models/qwen35.cpp,
* build_layer_attn).
* * RoPE is partial (`partial_rotary_factor` 0.25 rotates the first 64 of 256 head dims) and is
* M-RoPE; see `mode` in declare().
*
* K AND V ARE NOT FUSED INTO ONE PROJECTION, and that is a decision with a cost: two GEMM launches
* a layer instead of one, and two movement units instead of one. It buys every consumer a
* CONTIGUOUS operand. A fused [k|v] row makes the per-head k norm a rank-2 column slice whose last
* dimension is kv_dim while the norm's width is head_dim, and a kernel that reads extents off its
* operands -- libref does, by rule -- then walks it as if it were contiguous and normalises
* across the k/v seam. The fused form is expressible the moment the slice carries the head
* dimension in its own right; until then this is correct and slightly slow rather than fast and
* silently wrong. libr4d's kernel takes a `k_pitch` for the fused form, so the w8a8 sibling can
* make the other choice without changing this block's shape.
* k and v are separate projections (two GEMMs, two movement units) so every consumer gets a
* contiguous operand. With a fused [k|v] row the per-head k norm would be a column slice whose
* last dimension is kv_dim, not head_dim, and a kernel reading extents from its operands (libref
* does) would normalise across the k/v seam. libr4d's kernel takes a `k_pitch` for the fused
* form, so a quantised sibling can fuse without changing this block's shape.
*/
#ifndef RAD_BLOCK_ATTN_GATED_H
#define RAD_BLOCK_ATTN_GATED_H
@@ -40,9 +31,8 @@ namespace rad {
namespace arch {
struct AttnGatedBF16 {
/* The activation buffers this block reads and writes. Declared once by the plugin and shared
* by every layer of this kind: layers that share a geometry share the buffer (spec §8), and
* the liveness analysis over the declared read and write sets is what makes that safe. */
/* Activation buffers, declared once by the plugin and shared by every layer of this kind
* (spec §3.1); liveness over the declared read/write sets makes the sharing safe. */
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the o output */
@@ -50,14 +40,12 @@ struct AttnGatedBF16 {
rad_buf k = 0; /* [max_tok, kv_dim] */
rad_buf v = 0; /* [max_tok, kv_dim] */
rad_buf q = 0; /* [max_tok, q_dim] de-interleaved, normed, rotated */
rad_buf gate = 0; /* [max_tok, q_dim] de-interleaved, then sigmoid in place */
rad_buf gate = 0; /* [max_tok, q_dim] sigmoid of the de-interleaved gate */
rad_buf attn = 0; /* [max_tok, q_dim] attention output, then gated in place */
};
/* The checkpoint-side names for one layer. The plugin owns both sides of the map and is the
* only component that knows both (spec §2.4), so the block takes the spelling rather than
* inventing one -- this architecture arrives as `model.language_model.layers.N.*` from the
* safetensors checkpoint and as `blk.N.*` from a GGUF. */
/* Checkpoint-side names for one layer, supplied by the plugin, which owns the map (spec §2.4):
* `model.language_model.layers.N.*` from safetensors, `blk.N.*` from GGUF. */
struct Src {
const char* norm = nullptr; /* input_layernorm.weight */
const char* qg = nullptr; /* self_attn.q_proj.weight -- query AND gate */
@@ -78,8 +66,7 @@ struct AttnGatedBF16 {
rad_weight w_norm = 0, w_qg = 0, w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0, w_o = 0;
rad_op op_norm = 0, op_qg = 0, op_kp = 0, op_vp = 0;
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0; /* the fallback */
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
rad_op op_attn = 0, op_kv_store = 0, op_sigmoid = 0, op_gate = 0;
rad_op op_o = 0, op_ar = 0, op_add = 0;
@@ -103,13 +90,10 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
return RAD_E_INVAL;
}
/* KV-HEAD REPLICATION IS NOT PLUMBED HERE. `geom_from` answers a world size above the KV head
* count by giving every rank ONE kv head and a `kv_off` row span into a projection that stays
* `n_head_kv_all * head_dim` rows in the container -- and this block declares its k and v with
* the plain even row-shard, which at four ranks would hand a rank half of one KV head. The
* shapes would declare, the numbers would be wrong, and the text would be fluent. Refuse by
* name instead: rad_block_attn_gated_fp8.h is the block that passes the span, and a bf16 model
* that needs TP4 plumbs it the same way. */
/* KV-head replication is not supported here. Above the KV head count geom_from gives each rank
* one KV head and a `kv_off` row span, but this block declares k and v with the plain even
* row shard, which would hand a rank part of one head and compute wrong values. The span is
* passed in rad_block_attn_gated_fp8.h. */
if (g.world > g.n_head_kv_all) {
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
"with n_head_kv = %lld; the KV-head replication in geom_from needs the "
@@ -118,13 +102,12 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
return RAD_E_UNSUPPORTED;
}
/* ---- weights. Shapes are [out, in]: gemm_nt is A[M,K] times B transposed [N,K], the layout
* every transformer weight already has, so nothing is transposed at load.
/* ---- weights. Shapes are [out, in]: gemm_nt multiplies A[M,K] by B[N,K] transposed, the
* layout checkpoints already use.
*
* The q|gate projection row-shards by HEAD, and that works only because each head's query and
* gate are adjacent: rows [h*2*head_dim, (h+1)*2*head_dim) are one head's pair, so a rank's
* slice of the head range is a contiguous row range. A projection that put all queries before
* all gates would not shard this way. */
* The q|gate projection row-shards by head because each head's query and gate are adjacent:
* rows [h*2*head_dim, (h+1)*2*head_dim) are one head's pair, so a rank's heads form a
* contiguous row range. */
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_qg.weight", l), src.qg));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), src.k));
@@ -141,8 +124,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
w_v = decl_w(b, nm.f("blk.%d.attn_v.weight", l), RAD_BF16, {kv_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
/* One gain vector shared by every head, so it is replicated across ranks even though the heads
* are not. */
/* One gain vector shared by every head, so replicated across ranks. */
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
@@ -150,10 +132,8 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
w_o = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
/* ---- ops, in the order they run, with the one exception noted at attn_paged. Each states the
* buffers it reads and writes, because that is what the buffer planner computes liveness
* from -- and a gated attention layer has six activation buffers where a plain one has three,
* so an undeclared use here costs an arena, not a rounding error. */
/* ---- ops, in run order except attn_paged (see there). Each states its read and write sets,
* from which the buffer planner computes liveness. */
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
@@ -176,89 +156,59 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
RAD_WEIGHTS(w_v)),
{w.h}, {w.v});
/* Fusion is a selection, not a compiler pass (spec §2.3): ask for the fused op, and emit the
* sequence it stands for when nothing in the hierarchy serves it.
/* The fused qk_norm_rope_gate is not declared: libr4d's version (libr4d/r4d_rows.cpp,
* pQkNormRopeGate) takes a precomputed cos/sin table operand, and this block has no PERSIST
* [max_ctx, rot] table to give it. The unfused sequence below runs everywhere, including
* without libr4d.
*
* THE PROBE IS NOT MADE, because this block cannot fill the fused op's schema. libr4d's
* r4d_qk_norm_rope_gate (libr4d/r4d_rows.cpp, pQkNormRopeGate) names the rotary width `rot`,
* takes `q_dtype`, and -- the part that matters -- takes a PRECOMPUTED COS/SIN TABLE as a
* required input operand instead of `theta`. Nothing in arch/ or core/ builds such a table.
* Declaring the op with parameters the schema does not have is a STRUCTURAL error and fails
* declare outright; it is not a miss that falls through to the sequence below, because an
* unknown parameter is a caller bug and the builder is right to say so.
* `mode` is "mrope" (mrope_section [11,11,10], interleaved). Each rotary dimension has its own
* frequency and the section only chooses which position component feeds it, so with equal
* components (text) mrope is bit-identical to neox.
*
* What making the probe needs, precisely: a PERSIST buffer of [max_ctx, rot] filled once from
* theta, and a way for a plugin to fill a declared buffer at load -- which the ABI has no hook
* for, since buffers are arena storage and weights come from the container. Both are real work
* and neither belongs in a probe. Until then this model runs the unfused sequence, which is
* correct everywhere and is what makes it run on an install with no libr4d at all.
*
* `mode` would be "mrope" because that is what the model does: mrope_section [11,11,10] over
* an interleaved layout. TWO THINGS ABOUT THAT ARE NOT EXPRESSIBLE and both stay true of the
* unfused path. The sections have no parameter in any op schema, and RadBatch carries ONE
* position component per token, so all three sections would receive the same position. For
* text that is not an approximation: every rotary dimension has its own frequency and the
* section only decides which position component feeds it, so mrope over equal components is
* bit-identical to neox. It stops being identical the moment an image span gives the
* components different values, which is why the vision tower needs both a sections parameter
* and a 3-row position array before it can be correct. */
op_fused = RAD_NULL_HANDLE;
{
* Per-head RMS norm is a rmsnorm with M = tokens x heads, n = head_dim. The q norm reads the
* strided view of the interleaved projection and writes the contiguous q buffer, so it
* de-interleaves in the same pass. The k norm runs in place, which is safe because a row's
* scale is computed before the row is written. */
op_q_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_q_norm)),
{w.qg}, {w.q});
op_k_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head_kv),
RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_k_norm)),
{w.k}, {w.k});
/* Two rope calls because q and k are separate buffers. `rope` describes a fused [q|k|v] row by
* n_head and n_head_kv; n_head_kv 0 makes it a q-only (or k-only) row. */
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, mode),
{w.q}, {w.q});
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, mode),
{w.k}, {w.k});
/* Per-head RMS norm is an ordinary rmsnorm with M = tokens x heads and n = head_dim. The q
* one reads the STRIDED view of the interleaved projection and writes the contiguous q
* buffer, so it de-interleaves and normalises in one pass: the copy llama.cpp spends a
* ggml_cont on is this op's output operand. The k one runs in place, which is safe for any
* implementation that computes a row's scale before writing the row -- and none can do
* otherwise. */
op_q_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_q_norm)),
{w.qg}, {w.q});
op_k_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head_kv),
RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_k_norm)),
{w.k}, {w.k});
/* Two rope calls rather than one, because q and k are two buffers here. `rope` describes a
* fused [q|k|v] row through n_head and n_head_kv; a call that names only q heads is that
* row with an empty k and v, which is what a separate q buffer is. */
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, mode),
{w.q}, {w.q});
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, mode),
{w.k}, {w.k});
}
/* attn_paged is declared BEFORE kv_store even though it runs after it. block_size is
* RAD_DERIVED -- the KV block size is a property of the resolved attention kernel and not a
* number anyone gets to choose (spec §7.2) -- so it is OMITTED here, the selector skips
* constraints on it while matching, writes the winner's value into the resolved geometry, and
* kv_store reads it back with rad_kv_block_size(). The two ops touch disjoint buffers, so the
* declared order differing from the issue order costs the buffer planner nothing.
/* attn_paged is declared before kv_store although it runs after it. `block_size` is
* RAD_DERIVED, a property of the resolved attention kernel (spec §7.2): the selector writes the
* winner's value into the resolved geometry and kv_store reads it with rad_kv_block_size().
* The ops touch disjoint buffers, so the order mismatch does not affect buffer planning.
*
* The ranged parameter is q_len, not M: one query row at decode, up to n_spec+1 at a
* speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each
* band. `scale` is left off: 1/sqrt(head_dim) is the default and is what this model uses. */
op_attn = rw(b, RAD_OP(b, "attn_paged",
* The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in
* a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */
op_attn = rw(b, rad_decl_op(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0),
/* n_head, max_seqs and max_ctx are what the resolved kernel's SCRATCH HOOK
* needs at declare: libr4d sizes a split-KV partial buffer of
* num_seqs * q_len * q_heads * splits rows, and gqa gives the head
* ratio rather than the count. All three are bounds, which is the
* right kind of number for an arena sized once for the worst step. */
/* Bounds for the kernel's scratch hook: libr4d sizes a split-KV
* partial buffer of num_seqs * q_len * q_heads * splits rows. */
RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK), RAD_INT("max_seqs", g.max_seqs),
RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
/* kv_store writes the group's pool, which is not a declared buffer -- so its write set is
* empty and its read set is the two projections it stores. */
/* kv_store writes the group's pool, which is not a declared buffer, so its write set is
* empty. */
op_kv_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
@@ -267,19 +217,14 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
RAD_NOWEIGHTS),
{w.k, w.v}, {});
/* The gate. Two ops rather than one fused `mul(attn, sigmoid(gate))`, because the vocabulary
* has no gated multiply for a bf16 output -- `gated_had_quant_i8` is the same arithmetic with
* an int8 epilogue and is what the w8a8 sibling will use instead of this pair.
*
* The sigmoid's INPUT differs between the two paths and its output does not: the fused kernel
* has already written a contiguous gate, and the fallback reads the strided view of the
* interleaved projection. Same op, same geometry, one operand spelled two ways -- which is why
* there is no second declaration and no branch after this point. */
/* The gate, as two ops: the op vocabulary has no gated multiply with a bf16 output
* (`gated_had_quant_i8` is the same arithmetic with an int8 epilogue). The sigmoid reads the
* strided gate view of the interleaved projection into the contiguous gate buffer. */
op_sigmoid = rw(b, RAD_OP(b, "sigmoid",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
RAD_INT("n", g.head_dim), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.qg, w.gate}, {w.gate});
{w.qg}, {w.gate});
op_gate = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
@@ -293,12 +238,10 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
RAD_WEIGHTS(w_o)),
{w.attn}, {w.h});
/* The output projection is column-sharded, so each rank holds a partial sum of the residual
* update and the ranks must agree before the add. The core inserts nothing: this collective is
* here because the plugin put it here, and --debug-graph shows it exactly here (spec §9).
* `exact` is stated rather than defaulted -- a caller that does not say it will accept a
* quantised wire gets the exact kernel or no kernel. `hops` is not stated: one-shot against
* two-shot is the kernel library's choice, by message size. */
/* The column-sharded output projection leaves a partial sum on each rank. The plugin emits the
* collective itself, so --debug-graph shows it here (spec §9). `exact` is always stated, so a
* deployment that has not accepted a lossy wire gets the exact kernel. `hops` (one-shot vs
* two-shot) is left to the kernel library, by message size. */
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -318,9 +261,8 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
}
inline void AttnGatedBF16::step(RadCtx* c, const RadBatch* batch) const {
/* rad_issue records its own failure and the core aborts the step and fails the requests in it,
* naming the kernel and the geometry (spec §17). There is nothing a plugin can usefully do
* with the status, and ignoring it is what keeps the run phase a flat readable list. */
/* Issue statuses are ignored: rad_issue records a failure and the core aborts the step and
* fails its requests, naming the kernel and geometry (spec §17). */
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
@@ -333,44 +275,31 @@ inline void AttnGatedBF16::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE(c, op_kp, brows(w.h, T), RAD_W(w_k), brows(w.k, T));
RAD_ISSUE(c, op_vp, brows(w.h, T), RAD_W(w_v), brows(w.v, T));
if (op_fused) {
RAD_ISSUE(c, op_fused,
brows(w.qg, T), brows(w.k, T), praw(batch->positions, RAD_I32, T),
RAD_W(w_q_norm), RAD_W(w_k_norm),
brows(w.q, T), brows(w.gate, T));
} else {
/* The q view of the interleaved projection: head_dim columns out of every 2*head_dim, the
* declared width kept as the stride. */
RAD_ISSUE_N(c, op_q_norm, T * g.n_head,
bcol(w.qg, 0, g.head_dim, T), RAD_W(w_q_norm), brows(w.q, T));
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv,
brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
}
/* The q view of the interleaved projection: head_dim columns of every 2*head_dim. */
RAD_ISSUE_N(c, op_q_norm, T * g.n_head,
bcol(w.qg, 0, g.head_dim, T), RAD_W(w_q_norm), brows(w.q, T));
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv,
brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_kv_store,
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
/* The actual query length, not the batch's token count: it is what selects the attention band,
* and a verify step and a prefill chunk can carry the same token count at very different
* q_len. */
/* The longest query length, not the token count, selects the attention band: a verify step and
* a prefill chunk can have the same token count at very different q_len. */
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
brows(w.q, T), kv_cache(kv, layer),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
/* cu_seqlens. The batch may be ragged -- one prefill chunk beside other
* sequences one decode row each -- and without it the kernel has to
* assume a single q_len for the whole step, which it cannot. */
/* cu_seqlens: the batch may be ragged (a prefill chunk beside decode rows). */
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn, T));
/* out = attn * sigmoid(gate). The fused kernel wrote the gate contiguously; the fallback left
* it interleaved and this is where it is read out. */
if (op_fused) RAD_ISSUE_N(c, op_sigmoid, T * g.n_head, brows(w.gate, T), brows(w.gate, T));
else RAD_ISSUE_N(c, op_sigmoid, T * g.n_head,
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.gate, T));
/* out = attn * sigmoid(gate), the gate read out of the interleaved projection. */
RAD_ISSUE_N(c, op_sigmoid, T * g.n_head,
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.gate, T));
RAD_ISSUE(c, op_gate, brows(w.attn, T), brows(w.gate, T), brows(w.attn, T));
RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T));
File diff suppressed because it is too large. Load diff
+666
View File
@@ -0,0 +1,666 @@
/* rad_block_clef.h -- clef's joint schema head, inside the backbone's plugin.
*
* Cloudflare's clef and clef-flash decide every question of a request jointly from the backbone's
* final hidden state at EVERY prompt position (joint_schema_model.py, JointSchemaHead). This block
* runs that head on the card, after the trunk, so /v1/systemone needs no second process:
*
* per token, every step hn = layernorm(h); hn is stored in a paged KV group of its own,
* so a prefix hit keeps the rows the trunk did not recompute
* per request, once every row of hn is gathered back out of the group's blocks, the
* memory projection and the six cross-attention layers run over all
* of them, the question and option spans are averaged, and the
* routing, decoder layers and scorer give three numbers an option
* (its lexical prior, its cosine and its residual) into the request's
* logits row, where the server reads them (core/server/clef.cpp)
*
* The spans, the option tokens and the question types come as the request's words
* (abi/rad_clef.h, RadBatch::plugin_words), laid out as the kernels read them. The head's own
* tensors are the release's joint_head.safetensors, added to the container at convert, under their
* own names. Every op here has a device kernel and a host reference, so the same block serves
* the tiny CPU test and the card.
*
* Differences from the reference, all within bf16: the cosine and the prior are means of
* products of RMS-normalised rows (an identity, with eps 1e-12 against torch's max(norm, 1e-12));
* the routing softmax is formed in f32 (seg_softmax_pool). The learned scalars (prior_logit_scale,
* joint_logit_scale, residual_gate) are applied by the server from the container header.
*/
#pragma once
#include <arch/rad_arch.h>
#include <rad_clef.h>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct ClefHead {
bool on = false;
int64_t E = 0; /* the backbone's hidden size: the head's input width */
int64_t W = 0; /* the head's width */
int64_t H = 0; /* heads */
int64_t HD = 0; /* W / H */
int64_t F = 0; /* feedforward */
int64_t bs = 0; /* the cache's block size */
int64_t nblk = 0; /* blocks a context holds at most */
int64_t NM = 0; /* nblk * bs: rows a request holds at most */
int64_t n_vocab = 0; /* this rank's logits width */
int layer = 0; /* the group's bound layer index */
double eps = 1e-5; /* torch.nn.LayerNorm's default */
rad_kvgroup kv = 0;
/* ---- weights */
rad_weight hn_w = 0, hn_b = 0, w_mem = 0, w_q = 0, w_oq = 0, w_glob = 0, w_octx = 0,
w_olex = 0, w_type = 0, osn_w = 0, osn_b = 0, fn_w = 0, fn_b = 0, on_w = 0,
on_b = 0, rs1_w = 0, rs1_b = 0, rs2_w = 0, rs2_b = 0;
struct Ev {
rad_weight qn_w = 0, qn_b = 0, mn_w = 0, mn_b = 0, wq = 0, bq = 0, wk = 0, bk = 0, wv = 0,
bv = 0, wo = 0, bo = 0, fn_w = 0, fn_b = 0, w1 = 0, b1 = 0, w2 = 0, b2 = 0;
rad_op ln_q = 0, ln_m = 0, pq = 0, pk = 0, pv = 0, attn = 0, po = 0, ln_f = 0, f1 = 0,
f2 = 0;
};
struct Dec {
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0, n3w = 0, n3b = 0, sa_w = 0, sa_b = 0,
so_w = 0, so_b = 0, cq_w = 0, cq_b = 0, ck_w = 0, ck_b = 0, cv_w = 0, cv_b = 0,
co_w = 0, co_b = 0, w1 = 0, b1 = 0, w2 = 0, b2 = 0;
rad_op ln1 = 0, qkv = 0, sattn = 0, so = 0, ln2 = 0, pq = 0, pk = 0, pv = 0, cattn = 0,
co = 0, ln3 = 0, f1 = 0, f2 = 0;
};
std::vector<Ev> ev;
std::vector<Dec> dec;
/* ---- buffers */
rad_buf b_hn = 0, b_all = 0, b_mem = 0, b_mn = 0, b_k = 0, b_v = 0, b_seg = 0, b_qv = 0,
b_oc = 0, b_g = 0, b_lx = 0, b_lex = 0, b_x = 0, b_t1 = 0, b_t2 = 0, b_ff = 0,
b_qq = 0, b_bf = 0, b_fr = 0, b_sc = 0, b_sum = 0, b_f = 0, b_fq = 0, b_f1 = 0,
b_f2 = 0, b_gw = 0, b_fn = 0, b_on = 0, b_na = 0, b_nb = 0, b_an = 0, b_ln = 0,
b_p = 0, b_neg1 = 0, b_d = 0, b_nd = 0, b_abs = 0, b_prod = 0, b_feat = 0, b_r = 0,
b_out3 = 0;
/* ---- ops, one a use site: the arena plans from each op's read and write sets */
rad_op op_hn = 0, op_store = 0, op_gather = 0, op_mem = 0, op_seg = 0, op_g_q = 0, op_g_o = 0,
op_g_last = 0, op_lex = 0, op_lexmean = 0, op_octx = 0, op_olex = 0, op_add_x1 = 0,
op_oq = 0, op_g_oq = 0, op_add_x2 = 0, op_qproj = 0, op_g_fr = 0, op_mul_sc = 0,
op_score = 0, op_route = 0, op_ln_osn = 0, op_add_f1 = 0, op_glob = 0, op_add_fg = 0,
op_type = 0, op_add_f2 = 0, op_ln_fn = 0, op_g_fr2 = 0, op_ln_on = 0, op_rms_a = 0,
op_rms_b = 0, op_mul_cos = 0, op_mean_cos = 0, op_g_an = 0, op_add_an = 0,
op_rms_an = 0, op_rms_lex = 0, op_mul_pri = 0, op_mean_pri = 0, op_neg1 = 0,
op_nd = 0, op_d = 0, op_relu_d = 0, op_nd2 = 0, op_relu_nd = 0, op_abs = 0,
op_prod = 0, op_cp_fr = 0, op_cp_on = 0, op_cp_prod = 0, op_cp_abs = 0, op_rs1 = 0,
op_rs2 = 0, op_cast = 0;
static bool present(const RadModelMeta* meta) {
const char* t = rad_meta_gets(meta, "decision.type", "");
return t && !std::strcmp(t, "clef");
}
/* Declared after the trunk's layers and lm_head: the trunk's cache block size is known then,
* and the head's rows read the final norm's output `b_h` and write `b_logits`. */
int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Names& nm,
const Geom& g, rad_buf b_h, rad_buf b_logits, rad_weight w_lm_head,
rad_kvgroup kv_trunk, int bind_layer);
/* Every trunk step: the final norm's rows into the head's cache. */
void step_tokens(RadCtx* c, const RadBatch* batch, rad_buf b_h);
/* After the lm_head: the head over every sequence that carries words. */
void step_heads(RadCtx* c, const RadBatch* batch, rad_buf b_logits, rad_weight w_lm_head);
private:
const RadKVGroupBatch* group_of(const RadBatch* batch) const {
for (int i = 0; i < batch->n_kv_groups; ++i)
if (batch->kv[i].group == kv) return &batch->kv[i];
return nullptr;
}
};
inline int ClefHead::declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
Names& nm, const Geom& g, rad_buf b_h, rad_buf b_logits,
rad_weight w_lm_head, rad_kvgroup kv_trunk, int bind_layer) {
(void)ctx;
E = g.n_embd;
W = rad_meta_geti(meta, "decision.clef.width", 0);
H = rad_meta_geti(meta, "decision.clef.heads", 0);
F = rad_meta_geti(meta, "decision.clef.feedforward", 0);
const long long R = rad_meta_geti(meta, "decision.clef.routing_layers", 0);
const long long D = rad_meta_geti(meta, "decision.clef.layers", 0);
const long long hidden = rad_meta_geti(meta, "decision.clef.hidden_size", 0);
if (W <= 0 || H <= 0 || F <= 0 || R <= 0 || D <= 0 || W % H || hidden != E) {
std::fprintf(stderr, "radiance: clef: the container's decision.clef.* keys do not describe "
"the head (hidden_size %lld against the backbone's %lld, width %lld, "
"heads %lld, feedforward %lld, routing_layers %lld, layers %lld); "
"rad-convert sets them from joint_head_config.json\n",
hidden, (long long)E, (long long)W, (long long)H, (long long)F, R, D);
return RAD_E_INVAL;
}
HD = W / H;
if (g.world != 1) {
std::fprintf(stderr, "radiance: clef's head runs on one rank: its rows are replicated and "
"the option tokens read the whole lm_head\n");
return RAD_E_UNSUPPORTED;
}
if (weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16) != RAD_BF16) {
std::fprintf(stderr, "radiance: clef's head averages lm_head rows as bf16; this container's "
"lm_head is quantised. Keep output.weight bf16 in the recipe\n");
return RAD_E_UNSUPPORTED;
}
if (E % 2) return RAD_E_INVAL;
bs = rad_kv_block_size(b, kv_trunk);
if (bs <= 0) return RAD_E_STATE;
/* Rows a request may hold: the context, or the head's own bound where that is less (the
* server refuses a longer prompt before it is admitted). */
const int64_t rows = g.max_ctx < RAD_CLEF_MAX_PROMPT ? g.max_ctx : RAD_CLEF_MAX_PROMPT;
nblk = (rows + bs - 1) / bs;
NM = nblk * bs;
n_vocab = g.n_vocab;
layer = bind_layer;
const int64_t QM = RAD_CLEF_MAX_QUESTIONS, OM = RAD_CLEF_MAX_OPTIONS, LM = RAD_CLEF_MAX_LEX;
const int64_t SM = 2 * (QM + OM) + 1;
if (n_vocab < 3 * OM) {
std::fprintf(stderr, "radiance: clef's head writes %lld values into a logits row of %lld\n",
(long long)(3 * OM), (long long)n_vocab);
return RAD_E_UNSUPPORTED;
}
/* ---- the cache: one FULL group, hn's two halves as a slot's K and V, so a block holds
* bs rows of E in position order and a gather of a sequence's blocks is its rows. Bound past
* the trunk, so the scheduler counts it as the head's; cached with the trunk's groups because
* its block size is theirs (core/mem/prefix.cpp). */
RadKVGroupDecl kd{};
kd.kind = RAD_KV_FULL;
kd.dtype = RAD_BF16;
kd.n_head_kv = 1;
kd.head_dim = E / 2;
kv = rad_decl_kv_group(b, nm.f("clef.kv"), &kd);
if (!kv) return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, layer, kv));
RAD_ARCH_TRY(rad_declare_plugin_words(b, rad_clef_max_words()));
/* ---- weights: the release's names, bf16, read once a request. */
const int ACC = RAD_ACCESS_PER_REQUEST;
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, grp_model());
};
/* A packed in_proj's third: rows [k W, (k+1) W) of the weight, and of the bias. */
auto bw_rows = [&](const char* dn, const char* src, int k, int64_t cols) -> rad_weight {
if (map_rows(b, dn, { { src, (int)(k * W), W } }) < 0) return 0;
return cols ? decl_w(b, dn, RAD_BF16, { W, cols }, ACC, RAD_SHARD_NONE, grp_model())
: decl_w(b, dn, RAD_BF16, { W }, ACC, RAD_SHARD_NONE, grp_model());
};
hn_w = bw(nm.f("clef.hidden_norm.weight"), nm.ckpt("hidden_norm.weight"), { E });
hn_b = bw(nm.f("clef.hidden_norm.bias"), nm.ckpt("hidden_norm.bias"), { E });
w_mem = bw(nm.f("clef.memory_projection.weight"), nm.ckpt("memory_projection.weight"), { W, E });
w_q = bw(nm.f("clef.question_projection.weight"), nm.ckpt("question_projection.weight"), { W, E });
w_oq = bw(nm.f("clef.option_question_projection.weight"), nm.ckpt("option_question_projection.weight"), { W, E });
w_glob = bw(nm.f("clef.global_projection.weight"), nm.ckpt("global_projection.weight"), { W, E });
w_octx = bw(nm.f("clef.option_context_projection.weight"), nm.ckpt("option_context_projection.weight"), { W, E });
w_olex = bw(nm.f("clef.option_lexical_projection.weight"), nm.ckpt("option_lexical_projection.weight"), { W, E });
w_type = bw(nm.f("clef.type_embedding.weight"), nm.ckpt("type_embedding.weight"), { 3, W });
osn_w = bw(nm.f("clef.option_summary_norm.weight"), nm.ckpt("option_summary_norm.weight"), { W });
osn_b = bw(nm.f("clef.option_summary_norm.bias"), nm.ckpt("option_summary_norm.bias"), { W });
fn_w = bw(nm.f("clef.field_norm.weight"), nm.ckpt("field_norm.weight"), { W });
fn_b = bw(nm.f("clef.field_norm.bias"), nm.ckpt("field_norm.bias"), { W });
on_w = bw(nm.f("clef.option_norm.weight"), nm.ckpt("option_norm.weight"), { W });
on_b = bw(nm.f("clef.option_norm.bias"), nm.ckpt("option_norm.bias"), { W });
/* The scorer's first linear reads [field | option | field*option | |field-option|], one row
* of 4 W an option, which the blocks below assemble in `feat`. */
rs1_w = bw(nm.f("clef.residual_scorer.0.weight"), nm.ckpt("residual_scorer.0.weight"), { W, 4 * W });
rs1_b = bw(nm.f("clef.residual_scorer.0.bias"), nm.ckpt("residual_scorer.0.bias"), { W });
rs2_w = bw(nm.f("clef.residual_scorer.3.weight"), nm.ckpt("residual_scorer.3.weight"), { 1, W });
rs2_b = bw(nm.f("clef.residual_scorer.3.bias"), nm.ckpt("residual_scorer.3.bias"), { 1 });
if (!hn_w || !hn_b || !w_mem || !w_q || !w_oq || !w_glob || !w_octx || !w_olex || !w_type ||
!osn_w || !osn_b || !fn_w || !fn_b || !on_w || !on_b || !rs1_w || !rs1_b || !rs2_w || !rs2_b)
return RAD_E_INVAL;
ev.assign((size_t)R, Ev{});
for (int i = 0; i < (int)R; ++i) {
Ev& e = ev[(size_t)i];
const char* p = "evidence_layers";
e.qn_w = bw(nm.f("clef.ev.%d.query_norm.weight", i), nm.ckpt("%s.%d.query_norm.weight", p, i), { W });
e.qn_b = bw(nm.f("clef.ev.%d.query_norm.bias", i), nm.ckpt("%s.%d.query_norm.bias", p, i), { W });
e.mn_w = bw(nm.f("clef.ev.%d.memory_norm.weight", i), nm.ckpt("%s.%d.memory_norm.weight", p, i), { W });
e.mn_b = bw(nm.f("clef.ev.%d.memory_norm.bias", i), nm.ckpt("%s.%d.memory_norm.bias", p, i), { W });
e.wq = bw_rows(nm.f("clef.ev.%d.q.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 0, W);
e.wk = bw_rows(nm.f("clef.ev.%d.k.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 1, W);
e.wv = bw_rows(nm.f("clef.ev.%d.v.weight", i), nm.ckpt("%s.%d.attention.in_proj_weight", p, i), 2, W);
e.bq = bw_rows(nm.f("clef.ev.%d.q.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 0, 0);
e.bk = bw_rows(nm.f("clef.ev.%d.k.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 1, 0);
e.bv = bw_rows(nm.f("clef.ev.%d.v.bias", i), nm.ckpt("%s.%d.attention.in_proj_bias", p, i), 2, 0);
e.wo = bw(nm.f("clef.ev.%d.o.weight", i), nm.ckpt("%s.%d.attention.out_proj.weight", p, i), { W, W });
e.bo = bw(nm.f("clef.ev.%d.o.bias", i), nm.ckpt("%s.%d.attention.out_proj.bias", p, i), { W });
e.fn_w = bw(nm.f("clef.ev.%d.ff_norm.weight", i), nm.ckpt("%s.%d.feedforward_norm.weight", p, i), { W });
e.fn_b = bw(nm.f("clef.ev.%d.ff_norm.bias", i), nm.ckpt("%s.%d.feedforward_norm.bias", p, i), { W });
e.w1 = bw(nm.f("clef.ev.%d.ff1.weight", i), nm.ckpt("%s.%d.feedforward.0.weight", p, i), { F, W });
e.b1 = bw(nm.f("clef.ev.%d.ff1.bias", i), nm.ckpt("%s.%d.feedforward.0.bias", p, i), { F });
e.w2 = bw(nm.f("clef.ev.%d.ff2.weight", i), nm.ckpt("%s.%d.feedforward.3.weight", p, i), { W, F });
e.b2 = bw(nm.f("clef.ev.%d.ff2.bias", i), nm.ckpt("%s.%d.feedforward.3.bias", p, i), { W });
if (!e.qn_w || !e.qn_b || !e.mn_w || !e.mn_b || !e.wq || !e.wk || !e.wv || !e.bq || !e.bk ||
!e.bv || !e.wo || !e.bo || !e.fn_w || !e.fn_b || !e.w1 || !e.b1 || !e.w2 || !e.b2)
return RAD_E_INVAL;
}
dec.assign((size_t)D, Dec{});
for (int i = 0; i < (int)D; ++i) {
Dec& d = dec[(size_t)i];
const char* p = "layers";
d.n1w = bw(nm.f("clef.dec.%d.norm1.weight", i), nm.ckpt("%s.%d.norm1.weight", p, i), { W });
d.n1b = bw(nm.f("clef.dec.%d.norm1.bias", i), nm.ckpt("%s.%d.norm1.bias", p, i), { W });
d.n2w = bw(nm.f("clef.dec.%d.norm2.weight", i), nm.ckpt("%s.%d.norm2.weight", p, i), { W });
d.n2b = bw(nm.f("clef.dec.%d.norm2.bias", i), nm.ckpt("%s.%d.norm2.bias", p, i), { W });
d.n3w = bw(nm.f("clef.dec.%d.norm3.weight", i), nm.ckpt("%s.%d.norm3.weight", p, i), { W });
d.n3b = bw(nm.f("clef.dec.%d.norm3.bias", i), nm.ckpt("%s.%d.norm3.bias", p, i), { W });
/* Self-attention keeps its packed in_proj: one GEMM, then column slices. */
d.sa_w = bw(nm.f("clef.dec.%d.sa.in.weight", i), nm.ckpt("%s.%d.self_attn.in_proj_weight", p, i), { 3 * W, W });
d.sa_b = bw(nm.f("clef.dec.%d.sa.in.bias", i), nm.ckpt("%s.%d.self_attn.in_proj_bias", p, i), { 3 * W });
d.so_w = bw(nm.f("clef.dec.%d.sa.o.weight", i), nm.ckpt("%s.%d.self_attn.out_proj.weight", p, i), { W, W });
d.so_b = bw(nm.f("clef.dec.%d.sa.o.bias", i), nm.ckpt("%s.%d.self_attn.out_proj.bias", p, i), { W });
d.cq_w = bw_rows(nm.f("clef.dec.%d.ca.q.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 0, W);
d.ck_w = bw_rows(nm.f("clef.dec.%d.ca.k.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 1, W);
d.cv_w = bw_rows(nm.f("clef.dec.%d.ca.v.weight", i), nm.ckpt("%s.%d.multihead_attn.in_proj_weight", p, i), 2, W);
d.cq_b = bw_rows(nm.f("clef.dec.%d.ca.q.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 0, 0);
d.ck_b = bw_rows(nm.f("clef.dec.%d.ca.k.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 1, 0);
d.cv_b = bw_rows(nm.f("clef.dec.%d.ca.v.bias", i), nm.ckpt("%s.%d.multihead_attn.in_proj_bias", p, i), 2, 0);
d.co_w = bw(nm.f("clef.dec.%d.ca.o.weight", i), nm.ckpt("%s.%d.multihead_attn.out_proj.weight", p, i), { W, W });
d.co_b = bw(nm.f("clef.dec.%d.ca.o.bias", i), nm.ckpt("%s.%d.multihead_attn.out_proj.bias", p, i), { W });
d.w1 = bw(nm.f("clef.dec.%d.ff1.weight", i), nm.ckpt("%s.%d.linear1.weight", p, i), { F, W });
d.b1 = bw(nm.f("clef.dec.%d.ff1.bias", i), nm.ckpt("%s.%d.linear1.bias", p, i), { F });
d.w2 = bw(nm.f("clef.dec.%d.ff2.weight", i), nm.ckpt("%s.%d.linear2.weight", p, i), { W, F });
d.b2 = bw(nm.f("clef.dec.%d.ff2.bias", i), nm.ckpt("%s.%d.linear2.bias", p, i), { W });
if (!d.n1w || !d.n1b || !d.n2w || !d.n2b || !d.n3w || !d.n3b || !d.sa_w || !d.sa_b ||
!d.so_w || !d.so_b || !d.cq_w || !d.ck_w || !d.cv_w || !d.cq_b || !d.ck_b || !d.cv_b ||
!d.co_w || !d.co_b || !d.w1 || !d.b1 || !d.w2 || !d.b2)
return RAD_E_INVAL;
}
/* ---- buffers, bf16, at the bounds the words are refused past. */
b_hn = decl_b(b, nm.f("clef.hn"), RAD_BF16, { g.max_tok, E });
b_all = decl_b(b, nm.f("clef.all"), RAD_BF16, { NM, E });
b_mem = decl_b(b, nm.f("clef.mem"), RAD_BF16, { NM, W });
b_mn = decl_b(b, nm.f("clef.mn"), RAD_BF16, { NM, W });
b_k = decl_b(b, nm.f("clef.k"), RAD_BF16, { NM, W });
b_v = decl_b(b, nm.f("clef.v"), RAD_BF16, { NM, W });
b_seg = decl_b(b, nm.f("clef.seg"), RAD_BF16, { SM, E });
b_qv = decl_b(b, nm.f("clef.qv"), RAD_BF16, { QM, E });
b_oc = decl_b(b, nm.f("clef.oc"), RAD_BF16, { OM, E });
b_g = decl_b(b, nm.f("clef.g"), RAD_BF16, { 1, E });
b_lx = decl_b(b, nm.f("clef.lx"), RAD_BF16, { LM, E });
b_lex = decl_b(b, nm.f("clef.lex"), RAD_BF16, { OM, E });
b_x = decl_b(b, nm.f("clef.x"), RAD_BF16, { OM, W });
b_t1 = decl_b(b, nm.f("clef.t1"), RAD_BF16, { OM, W });
b_t2 = decl_b(b, nm.f("clef.t2"), RAD_BF16, { OM, W });
b_ff = decl_b(b, nm.f("clef.ff"), RAD_BF16, { OM, F });
b_qq = decl_b(b, nm.f("clef.qq"), RAD_BF16, { QM, W });
b_bf = decl_b(b, nm.f("clef.bf"), RAD_BF16, { QM, W });
b_fr = decl_b(b, nm.f("clef.fr"), RAD_BF16, { OM, W });
b_sc = decl_b(b, nm.f("clef.sc"), RAD_BF16, { OM, 1 });
b_sum = decl_b(b, nm.f("clef.sum"), RAD_BF16, { QM, W });
b_f = decl_b(b, nm.f("clef.f"), RAD_BF16, { QM, W });
b_fq = decl_b(b, nm.f("clef.fq"), RAD_BF16, { QM, 3 * W });
b_f1 = decl_b(b, nm.f("clef.f1"), RAD_BF16, { QM, W });
b_f2 = decl_b(b, nm.f("clef.f2"), RAD_BF16, { QM, W });
b_gw = decl_b(b, nm.f("clef.gw"), RAD_BF16, { 1, W });
b_fn = decl_b(b, nm.f("clef.fn"), RAD_BF16, { QM, W });
b_on = decl_b(b, nm.f("clef.on"), RAD_BF16, { OM, W });
b_na = decl_b(b, nm.f("clef.na"), RAD_BF16, { OM, W });
b_nb = decl_b(b, nm.f("clef.nb"), RAD_BF16, { OM, W });
b_an = decl_b(b, nm.f("clef.an"), RAD_BF16, { OM, E });
b_ln = decl_b(b, nm.f("clef.ln"), RAD_BF16, { OM, E });
b_p = decl_b(b, nm.f("clef.p"), RAD_BF16, { OM, E });
b_neg1 = decl_b(b, nm.f("clef.neg1"), RAD_BF16, { 1, W });
b_d = decl_b(b, nm.f("clef.d"), RAD_BF16, { OM, W });
b_nd = decl_b(b, nm.f("clef.nd"), RAD_BF16, { OM, W });
b_abs = decl_b(b, nm.f("clef.abs"), RAD_BF16, { OM, W });
b_prod = decl_b(b, nm.f("clef.prod"), RAD_BF16, { OM, W });
b_feat = decl_b(b, nm.f("clef.feat"), RAD_BF16, { OM, 4 * W });
b_r = decl_b(b, nm.f("clef.r"), RAD_BF16, { OM, W });
b_out3 = decl_b(b, nm.f("clef.out3"), RAD_BF16, { 3 * OM, 1 });
if (!b_hn || !b_all || !b_mem || !b_mn || !b_k || !b_v || !b_seg || !b_qv || !b_oc || !b_g ||
!b_lx || !b_lex || !b_x || !b_t1 || !b_t2 || !b_ff || !b_qq || !b_bf || !b_fr || !b_sc ||
!b_sum || !b_f || !b_fq || !b_f1 || !b_f2 || !b_gw || !b_fn || !b_on || !b_na || !b_nb ||
!b_an || !b_ln || !b_p || !b_neg1 || !b_d || !b_nd || !b_abs || !b_prod || !b_feat || !b_r ||
!b_out3)
return RAD_E_INVAL;
/* ---- ops. The lambdas state each kind once; the row bound is the op's band. */
auto lnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_weight bias) {
return RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) {
return RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto gemmb = [&](int64_t rows, int64_t N, int64_t K, const char* act, rad_weight w,
rad_weight bias) {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", act)),
RAD_WEIGHTS(w, bias));
};
auto unary = [&](const char* op, int64_t rows, int64_t n) {
return RAD_OP(b, op,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
auto gather = [&](int64_t rows, int64_t n) { return unary("gather_rows", rows, n); };
auto cross = [&](int64_t rows) {
return RAD_OP(b, "attn_cross",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", HD), RAD_INT("gqa", 1),
RAD_INT("causal", 0), RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)HD))),
RAD_NOWEIGHTS);
};
auto rmsp = [&](int64_t rows, int64_t n) {
return RAD_OP(b, "rmsnorm_p",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", 1e-12),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
/* The mean of a row: a cosine from two RMS-normed rows, or with `mult` the dot product
* scaled (mult = n / sqrt(W) gives options . field / sqrt(W)). */
auto rowmean = [&](int64_t rows, int64_t n, double mult) {
return RAD_OP(b, "pool_cols",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_INT("k", n),
RAD_F64("mult", mult), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
/* Every step: the final norm's rows into the cache. kv_store carries the block size and so is
* the group's consumer (core/build/rad_builder.cpp, find_kv_consumer); its write is the pool. */
op_hn = rw(b, lnorm(g.max_tok, E, hn_w, hn_b), { b_h }, { b_hn });
op_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", E / 2),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", bs),
RAD_STR("kv_dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_hn }, {});
if (rad_kv_block_size(b, kv) != bs) {
std::fprintf(stderr, "radiance: clef's cache took block size %lld, the trunk's is %lld\n",
(long long)rad_kv_block_size(b, kv), (long long)bs);
return RAD_E_STATE;
}
/* Per request. A sequence's blocks are rows of bs * E: the gather reads the pool as
* [n_blocks, bs * E] and writes `all` as [nblk, bs * E], which the ops below read as rows of E
* (a contiguous buffer at another width, core/runtime and libr4d's r4d_rows_pitch). */
op_gather = rw(b, gather(nblk, bs * E), {}, { b_all });
op_mem = rw(b, gemm(NM, W, E, w_mem), { b_all }, { b_mem });
op_seg = rw(b, unary("seg_mean", NM, E), { b_all }, { b_seg });
op_g_q = rw(b, gather(QM, E), { b_seg }, { b_qv });
op_g_o = rw(b, gather(OM, E), { b_seg }, { b_oc });
op_g_last = rw(b, gather(1, E), { b_all }, { b_g });
op_lex = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, LM), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_lm_head)),
{}, { b_lx });
op_lexmean = rw(b, unary("seg_mean", LM, E), { b_lx }, { b_lex });
op_octx = rw(b, gemm(OM, W, E, w_octx), { b_oc }, { b_x });
op_olex = rw(b, gemm(OM, W, E, w_olex), { b_lex }, { b_t1 });
op_add_x1 = rw(b, unary("add", OM, W), { b_x, b_t1 }, { b_x });
op_oq = rw(b, gemm(QM, W, E, w_oq), { b_qv }, { b_qq });
op_g_oq = rw(b, gather(OM, W), { b_qq }, { b_t1 });
op_add_x2 = rw(b, unary("add", OM, W), { b_x, b_t1 }, { b_x });
for (Ev& e : ev) {
e.ln_q = rw(b, lnorm(OM, W, e.qn_w, e.qn_b), { b_x }, { b_t1 });
e.ln_m = rw(b, lnorm(NM, W, e.mn_w, e.mn_b), { b_mem }, { b_mn });
e.pq = rw(b, gemmb(OM, W, W, "none", e.wq, e.bq), { b_t1 }, { b_t2 });
e.pk = rw(b, gemmb(NM, W, W, "none", e.wk, e.bk), { b_mn }, { b_k });
e.pv = rw(b, gemmb(NM, W, W, "none", e.wv, e.bv), { b_mn }, { b_v });
e.attn = rw(b, cross(OM), { b_t2, b_k, b_v }, { b_t1 });
e.po = rw(b, gemmb(OM, W, W, "none", e.wo, e.bo), { b_t1, b_x }, { b_x });
e.ln_f = rw(b, lnorm(OM, W, e.fn_w, e.fn_b), { b_x }, { b_t1 });
e.f1 = rw(b, gemmb(OM, F, W, "gelu", e.w1, e.b1), { b_t1 }, { b_ff });
e.f2 = rw(b, gemmb(OM, W, F, "none", e.w2, e.b2), { b_ff, b_x }, { b_x });
}
op_qproj = rw(b, gemm(QM, W, E, w_q), { b_qv }, { b_bf });
op_g_fr = rw(b, gather(OM, W), { b_bf }, { b_fr });
op_mul_sc = rw(b, unary("mul", OM, W), { b_x, b_fr }, { b_t1 });
op_score = rw(b, rowmean(OM, W, (double)W / std::sqrt((double)W)), { b_t1 }, { b_sc });
op_route = rw(b, unary("seg_softmax_pool", OM, W), { b_sc, b_x }, { b_sum });
op_ln_osn = rw(b, lnorm(QM, W, osn_w, osn_b), { b_sum }, { b_f1 });
op_add_f1 = rw(b, unary("add", QM, W), { b_bf, b_f1 }, { b_f });
op_glob = rw(b, gemm(1, W, E, w_glob), { b_g }, { b_gw });
op_add_fg = rw(b, unary("add", QM, W), { b_f, b_gw }, { b_f });
op_type = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, QM), RAD_INT("n_embd", W),
RAD_INT("n_vocab", 3), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", 0)),
RAD_WEIGHTS(w_type)),
{}, { b_f1 });
op_add_f2 = rw(b, unary("add", QM, W), { b_f, b_f1 }, { b_f });
for (Dec& d : dec) {
d.ln1 = rw(b, lnorm(QM, W, d.n1w, d.n1b), { b_f }, { b_f1 });
d.qkv = rw(b, gemmb(QM, 3 * W, W, "none", d.sa_w, d.sa_b), { b_f1 }, { b_fq });
d.sattn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, QM), RAD_INT("head_dim", HD),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)HD)),
RAD_INT("max_seqlen", QM)),
RAD_NOWEIGHTS),
{ b_fq }, { b_f1 });
d.so = rw(b, gemmb(QM, W, W, "none", d.so_w, d.so_b), { b_f1, b_f }, { b_f });
d.ln2 = rw(b, lnorm(QM, W, d.n2w, d.n2b), { b_f }, { b_f1 });
d.pq = rw(b, gemmb(QM, W, W, "none", d.cq_w, d.cq_b), { b_f1 }, { b_f2 });
d.pk = rw(b, gemmb(NM, W, W, "none", d.ck_w, d.ck_b), { b_mem }, { b_k });
d.pv = rw(b, gemmb(NM, W, W, "none", d.cv_w, d.cv_b), { b_mem }, { b_v });
d.cattn = rw(b, cross(QM), { b_f2, b_k, b_v }, { b_f1 });
d.co = rw(b, gemmb(QM, W, W, "none", d.co_w, d.co_b), { b_f1, b_f }, { b_f });
d.ln3 = rw(b, lnorm(QM, W, d.n3w, d.n3b), { b_f }, { b_f1 });
d.f1 = rw(b, gemmb(QM, F, W, "gelu", d.w1, d.b1), { b_f1 }, { b_ff });
d.f2 = rw(b, gemmb(QM, W, F, "none", d.w2, d.b2), { b_ff, b_f }, { b_f });
}
op_ln_fn = rw(b, lnorm(QM, W, fn_w, fn_b), { b_f }, { b_fn });
/* The scorer, an option at a time against its question's field. */
op_g_fr2 = rw(b, gather(OM, W), { b_fn }, { b_fr });
op_ln_on = rw(b, lnorm(OM, W, on_w, on_b), { b_x }, { b_on });
op_rms_a = rw(b, rmsp(OM, W), { b_fr }, { b_na });
op_rms_b = rw(b, rmsp(OM, W), { b_on }, { b_nb });
op_mul_cos = rw(b, unary("mul", OM, W), { b_na, b_nb }, { b_t1 });
op_mean_cos = rw(b, rowmean(OM, W, 1.0), { b_t1 }, { b_out3 });
op_g_an = rw(b, gather(OM, E), { b_qv }, { b_an });
op_add_an = rw(b, unary("add", OM, E), { b_an, b_g }, { b_an });
op_rms_an = rw(b, rmsp(OM, E), { b_an }, { b_p });
op_rms_lex = rw(b, rmsp(OM, E), { b_lex }, { b_ln });
op_mul_pri = rw(b, unary("mul", OM, E), { b_p, b_ln }, { b_an });
op_mean_pri = rw(b, rowmean(OM, E, 1.0), { b_an }, { b_out3 });
op_neg1 = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", W),
RAD_STR("dtype", "bf16"), RAD_F64("value", -1.0)),
RAD_NOWEIGHTS),
{}, { b_neg1 });
op_nd = rw(b, unary("mul", OM, W), { b_on, b_neg1 }, { b_nd });
op_d = rw(b, unary("add", OM, W), { b_fr, b_nd }, { b_d });
op_relu_d = rw(b, unary("relu", OM, W), { b_d }, { b_abs });
op_nd2 = rw(b, unary("mul", OM, W), { b_d, b_neg1 }, { b_nd });
op_relu_nd = rw(b, unary("relu", OM, W), { b_nd }, { b_nd });
op_abs = rw(b, unary("add", OM, W), { b_abs, b_nd }, { b_abs });
op_prod = rw(b, unary("mul", OM, W), { b_fr, b_on }, { b_prod });
/* The four feature blocks side by side in `feat`: the field rows are gathered straight into
* the first, the other three copied in (cast at one dtype is the copy op), so the scorer's
* first linear is one GEMM over 4 W, rounded once as the reference rounds it. */
auto copy = [&]() {
return RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, OM), RAD_INT("n", W), RAD_STR("from", "bf16"),
RAD_STR("to", "bf16")),
RAD_NOWEIGHTS);
};
op_cp_fr = rw(b, copy(), { b_fr }, { b_feat });
op_cp_on = rw(b, copy(), { b_on }, { b_feat });
op_cp_prod = rw(b, copy(), { b_prod }, { b_feat });
op_cp_abs = rw(b, copy(), { b_abs }, { b_feat });
op_rs1 = rw(b, gemmb(OM, W, 4 * W, "gelu", rs1_w, rs1_b), { b_feat }, { b_r });
op_rs2 = rw(b, gemmb(OM, 1, W, "none", rs2_w, rs2_b), { b_r }, { b_out3 });
op_cast = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 3 * OM),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{ b_out3 }, { b_logits });
rad_note(b, "clef's joint schema head on the card: width %lld, %lld heads of %lld, "
"feedforward %lld, %lld routing + %lld decoder layers; hn cached as a FULL group "
"of block %lld (%lld rows a context); at most %d questions, %d options, %d option "
"tokens a request; three values an option into the logits row",
(long long)W, (long long)H, (long long)HD, (long long)F, R, D, (long long)bs,
(long long)NM, (int)QM, (int)OM, (int)LM);
on = true;
return RAD_OK;
}
inline void ClefHead::step_tokens(RadCtx* c, const RadBatch* batch, rad_buf b_h) {
if (!on || batch->n_tok <= 0) return;
const RadKVGroupBatch* kb = group_of(batch);
if (!kb) { rad_step_fail(c, "clef: the head's cache group is not in the step batch"); return; }
const int64_t T = batch->n_tok;
RAD_ISSUE_N(c, op_hn, T, brows(b_h, T), RAD_W(hn_w), RAD_W(hn_b), brows(b_hn, T));
RAD_ISSUE_N(c, op_store, T, bcol(b_hn, 0, E / 2, T), bcol(b_hn, E / 2, E / 2, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
}
inline void ClefHead::step_heads(RadCtx* c, const RadBatch* batch, rad_buf b_logits,
rad_weight w_lm_head) {
if (!on || !batch->plugin_cu_h || !batch->plugin_words_h) return;
const RadKVGroupBatch* kb = group_of(batch);
if (!kb) { rad_step_fail(c, "clef: the head's cache group is not in the step batch"); return; }
const int64_t QM = RAD_CLEF_MAX_QUESTIONS, OM = RAD_CLEF_MAX_OPTIONS, LM = RAD_CLEF_MAX_LEX;
const int64_t SM = 2 * (QM + OM) + 1;
for (int64_t s = 0; s < batch->n_seq; ++s) {
const int32_t w0 = batch->plugin_cu_h[s], w1 = batch->plugin_cu_h[s + 1];
if (w1 <= w0) continue;
if (w1 - w0 < RAD_CLEF_HDR) { rad_step_fail(c, "clef: a request's words have no header"); return; }
const int32_t* hw = batch->plugin_words_h + w0;
const int32_t* dw = batch->plugin_words + w0;
const RadClefWords L = rad_clef_words_read(hw);
const int64_t N = L.n, Q = L.q, O = L.o, Lx = L.l, S = L.s;
const int32_t row = hw[RAD_CLEF_W_ROW];
const int64_t nb = (N + bs - 1) / bs;
if (w1 - w0 < L.total || N < 1 || N > NM || Q < 1 || Q > QM || O < 1 || O > OM ||
Lx < 1 || Lx > LM || S < 1 || S > SM || row < 0 || row >= batch->n_out ||
nb > kb->max_blocks) {
rad_step_fail(c, "clef: a request's words are out of the head's bounds");
return;
}
auto dev = [&](int32_t off, int64_t n) { return praw(dw + off, RAD_I32, n); };
auto out3 = [&](int64_t at, int64_t rows) { return bcol_at(b_out3, at, 1, 0, 1, rows); };
const int32_t* bt = kb->block_table + s * kb->block_table_pitch;
/* Every row of hn, from the sequence's blocks. */
RAD_ISSUE_N(c, op_gather, nb, kv_cache(kv, layer), praw(bt, RAD_I32, nb),
brows(b_all, nb * bs));
RAD_ISSUE_N(c, op_mem, N, brows(b_all, N), RAD_W(w_mem), brows(b_mem, N));
/* The question, option and global vectors. */
RAD_ISSUE_N(c, op_seg, N, brows(b_all, N), dev(L.seg_cu, S + 1), brows(b_seg, S));
RAD_ISSUE_N(c, op_g_q, Q, brows(b_seg, S), dev(L.q_seg, Q), brows(b_qv, Q));
RAD_ISSUE_N(c, op_g_o, O, brows(b_seg, S), dev(L.o_seg, O), brows(b_oc, O));
RAD_ISSUE_N(c, op_g_last, 1, brows(b_all, N), dev(L.last, 1), brows(b_g, 1));
RAD_ISSUE_N(c, op_lex, Lx, dev(L.lex_ids, Lx), RAD_W(w_lm_head), brows(b_lx, Lx));
RAD_ISSUE_N(c, op_lexmean, Lx, brows(b_lx, Lx), dev(L.lex_cu, O + 1), brows(b_lex, O));
/* Option queries, then the evidence layers over the memory. */
RAD_ISSUE_N(c, op_octx, O, brows(b_oc, O), RAD_W(w_octx), brows(b_x, O));
RAD_ISSUE_N(c, op_olex, O, brows(b_lex, O), RAD_W(w_olex), brows(b_t1, O));
RAD_ISSUE_N(c, op_add_x1, O, brows(b_x, O), brows(b_t1, O), brows(b_x, O));
RAD_ISSUE_N(c, op_oq, Q, brows(b_qv, Q), RAD_W(w_oq), brows(b_qq, Q));
RAD_ISSUE_N(c, op_g_oq, O, brows(b_qq, Q), dev(L.o_q, O), brows(b_t1, O));
RAD_ISSUE_N(c, op_add_x2, O, brows(b_x, O), brows(b_t1, O), brows(b_x, O));
for (const Ev& e : ev) {
RAD_ISSUE_N(c, e.ln_q, O, brows(b_x, O), RAD_W(e.qn_w), RAD_W(e.qn_b), brows(b_t1, O));
RAD_ISSUE_N(c, e.ln_m, N, brows(b_mem, N), RAD_W(e.mn_w), RAD_W(e.mn_b), brows(b_mn, N));
RAD_ISSUE_N(c, e.pq, O, brows(b_t1, O), RAD_W(e.wq), RAD_W(e.bq), RAD_NONE, brows(b_t2, O));
RAD_ISSUE_N(c, e.pk, N, brows(b_mn, N), RAD_W(e.wk), RAD_W(e.bk), RAD_NONE, brows(b_k, N));
RAD_ISSUE_N(c, e.pv, N, brows(b_mn, N), RAD_W(e.wv), RAD_W(e.bv), RAD_NONE, brows(b_v, N));
RAD_ISSUE_N(c, e.attn, O, brows(b_t2, O), brows(b_k, N), brows(b_v, N),
dev(L.cu_o, 2), dev(L.cu_k, 2), brows(b_t1, O));
RAD_ISSUE_N(c, e.po, O, brows(b_t1, O), RAD_W(e.wo), RAD_W(e.bo), brows(b_x, O), brows(b_x, O));
RAD_ISSUE_N(c, e.ln_f, O, brows(b_x, O), RAD_W(e.fn_w), RAD_W(e.fn_b), brows(b_t1, O));
RAD_ISSUE_N(c, e.f1, O, brows(b_t1, O), RAD_W(e.w1), RAD_W(e.b1), RAD_NONE, brows(b_ff, O));
RAD_ISSUE_N(c, e.f2, O, brows(b_ff, O), RAD_W(e.w2), RAD_W(e.b2), brows(b_x, O), brows(b_x, O));
}
/* Base fields, each question's routing over its options, and the field vectors. */
RAD_ISSUE_N(c, op_qproj, Q, brows(b_qv, Q), RAD_W(w_q), brows(b_bf, Q));
RAD_ISSUE_N(c, op_g_fr, O, brows(b_bf, Q), dev(L.o_q, O), brows(b_fr, O));
RAD_ISSUE_N(c, op_mul_sc, O, brows(b_x, O), brows(b_fr, O), brows(b_t1, O));
RAD_ISSUE_N(c, op_score, O, brows(b_t1, O), brows(b_sc, O));
RAD_ISSUE_N(c, op_route, O, brows(b_sc, O), brows(b_x, O), dev(L.opt_cu, Q + 1), brows(b_sum, Q));
RAD_ISSUE_N(c, op_ln_osn, Q, brows(b_sum, Q), RAD_W(osn_w), RAD_W(osn_b), brows(b_f1, Q));
RAD_ISSUE_N(c, op_add_f1, Q, brows(b_bf, Q), brows(b_f1, Q), brows(b_f, Q));
RAD_ISSUE_N(c, op_glob, 1, brows(b_g, 1), RAD_W(w_glob), brows(b_gw, 1));
RAD_ISSUE_N(c, op_add_fg, Q, brows(b_f, Q), brows(b_gw, 1), brows(b_f, Q));
RAD_ISSUE_N(c, op_type, Q, dev(L.type, Q), RAD_W(w_type), brows(b_f1, Q));
RAD_ISSUE_N(c, op_add_f2, Q, brows(b_f, Q), brows(b_f1, Q), brows(b_f, Q));
for (const Dec& d : dec) {
RAD_ISSUE_N(c, d.ln1, Q, brows(b_f, Q), RAD_W(d.n1w), RAD_W(d.n1b), brows(b_f1, Q));
RAD_ISSUE_N(c, d.qkv, Q, brows(b_f1, Q), RAD_W(d.sa_w), RAD_W(d.sa_b), RAD_NONE, brows(b_fq, Q));
RAD_ISSUE_N(c, d.sattn, Q, bcol(b_fq, 0, W, Q), bcol(b_fq, W, W, Q),
bcol(b_fq, 2 * W, W, Q), dev(L.cu_q, 2), brows(b_f1, Q));
RAD_ISSUE_N(c, d.so, Q, brows(b_f1, Q), RAD_W(d.so_w), RAD_W(d.so_b), brows(b_f, Q), brows(b_f, Q));
RAD_ISSUE_N(c, d.ln2, Q, brows(b_f, Q), RAD_W(d.n2w), RAD_W(d.n2b), brows(b_f1, Q));
RAD_ISSUE_N(c, d.pq, Q, brows(b_f1, Q), RAD_W(d.cq_w), RAD_W(d.cq_b), RAD_NONE, brows(b_f2, Q));
RAD_ISSUE_N(c, d.pk, N, brows(b_mem, N), RAD_W(d.ck_w), RAD_W(d.ck_b), RAD_NONE, brows(b_k, N));
RAD_ISSUE_N(c, d.pv, N, brows(b_mem, N), RAD_W(d.cv_w), RAD_W(d.cv_b), RAD_NONE, brows(b_v, N));
RAD_ISSUE_N(c, d.cattn, Q, brows(b_f2, Q), brows(b_k, N), brows(b_v, N),
dev(L.cu_q, 2), dev(L.cu_k, 2), brows(b_f1, Q));
RAD_ISSUE_N(c, d.co, Q, brows(b_f1, Q), RAD_W(d.co_w), RAD_W(d.co_b), brows(b_f, Q), brows(b_f, Q));
RAD_ISSUE_N(c, d.ln3, Q, brows(b_f, Q), RAD_W(d.n3w), RAD_W(d.n3b), brows(b_f1, Q));
RAD_ISSUE_N(c, d.f1, Q, brows(b_f1, Q), RAD_W(d.w1), RAD_W(d.b1), RAD_NONE, brows(b_ff, Q));
RAD_ISSUE_N(c, d.f2, Q, brows(b_ff, Q), RAD_W(d.w2), RAD_W(d.b2), brows(b_f, Q), brows(b_f, Q));
}
RAD_ISSUE_N(c, op_ln_fn, Q, brows(b_f, Q), RAD_W(fn_w), RAD_W(fn_b), brows(b_fn, Q));
/* The scorer: the cosine, the lexical prior and the residual, one value an option, into
* out3's three stretches (prior | cosine | residual). */
RAD_ISSUE_N(c, op_g_fr2, O, brows(b_fn, Q), dev(L.o_q, O), brows(b_fr, O));
RAD_ISSUE_N(c, op_ln_on, O, brows(b_x, O), RAD_W(on_w), RAD_W(on_b), brows(b_on, O));
RAD_ISSUE_N(c, op_rms_a, O, brows(b_fr, O), brows(b_na, O));
RAD_ISSUE_N(c, op_rms_b, O, brows(b_on, O), brows(b_nb, O));
RAD_ISSUE_N(c, op_mul_cos, O, brows(b_na, O), brows(b_nb, O), brows(b_t1, O));
RAD_ISSUE_N(c, op_mean_cos, O, brows(b_t1, O), out3(OM, O));
RAD_ISSUE_N(c, op_g_an, O, brows(b_qv, Q), dev(L.o_q, O), brows(b_an, O));
RAD_ISSUE_N(c, op_add_an, O, brows(b_an, O), brows(b_g, 1), brows(b_an, O));
RAD_ISSUE_N(c, op_rms_an, O, brows(b_an, O), brows(b_p, O));
RAD_ISSUE_N(c, op_rms_lex, O, brows(b_lex, O), brows(b_ln, O));
RAD_ISSUE_N(c, op_mul_pri, O, brows(b_p, O), brows(b_ln, O), brows(b_an, O));
RAD_ISSUE_N(c, op_mean_pri, O, brows(b_an, O), out3(0, O));
RAD_ISSUE_N(c, op_neg1, 1, brows(b_neg1, 1));
RAD_ISSUE_N(c, op_nd, O, brows(b_on, O), brows(b_neg1, 1), brows(b_nd, O));
RAD_ISSUE_N(c, op_d, O, brows(b_fr, O), brows(b_nd, O), brows(b_d, O));
RAD_ISSUE_N(c, op_relu_d, O, brows(b_d, O), brows(b_abs, O));
RAD_ISSUE_N(c, op_nd2, O, brows(b_d, O), brows(b_neg1, 1), brows(b_nd, O));
RAD_ISSUE_N(c, op_relu_nd, O, brows(b_nd, O), brows(b_nd, O));
RAD_ISSUE_N(c, op_abs, O, brows(b_abs, O), brows(b_nd, O), brows(b_abs, O));
RAD_ISSUE_N(c, op_prod, O, brows(b_fr, O), brows(b_on, O), brows(b_prod, O));
/* [field | option | field*option | |field-option|], then the scorer. The field rows go
* in again (a copy into the first block) so every block arrives the same way. */
RAD_ISSUE_N(c, op_cp_fr, O, brows(b_fr, O), bcol(b_feat, 0, W, O));
RAD_ISSUE_N(c, op_cp_on, O, brows(b_on, O), bcol(b_feat, W, W, O));
RAD_ISSUE_N(c, op_cp_prod, O, brows(b_prod, O), bcol(b_feat, 2 * W, W, O));
RAD_ISSUE_N(c, op_cp_abs, O, brows(b_abs, O), bcol(b_feat, 3 * W, W, O));
RAD_ISSUE_N(c, op_rs1, O, brows(b_feat, O), RAD_W(rs1_w), RAD_W(rs1_b), RAD_NONE, brows(b_r, O));
RAD_ISSUE_N(c, op_rs2, O, brows(b_r, O), RAD_W(rs2_w), RAD_W(rs2_b), RAD_NONE, out3(2 * OM, O));
/* The three stretches, as f32, into the request's logits row (one row of 3 OM). */
RAD_ISSUE_N(c, op_cast, 1, brows(b_out3, 3 * OM),
bcol_at(b_logits, row, n_vocab, 0, 3 * OM, 1));
}
}
/* The zero logits rows a trunk leaves when it skips its lm_head for rows a decision head answers
* (the qwen35 plugins' `op_logits_fill`): declared here, by the plugin that wants the skip, so a
* trunk serving a plain container declares the same graph as before. */
inline rad_op clef_logits_fill(RadBuilder* b, Names& nm, const Geom& g, rad_buf b_logits) {
return rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_vocab),
RAD_STR("dtype", "f32"), RAD_F64("value", 0.0)),
RAD_NOWEIGHTS),
{}, { b_logits });
}
} /* namespace arch */
} /* namespace rad */
File diff suppressed because it is too large. Load diff
+269 -379
View File
@@ -2,161 +2,119 @@
*
* ============================== WHAT IT IS ==============================
*
* The THIRD drafter this engine serves, and the second block-diffusion one. It is
* `openbmb/MiniCPM5-2B-DSpark`: five plain Qwen3 attention layers that propose a whole block of
* tokens in ONE forward pass, conditioned on the target trunk's residual stream at five
* tokens in one forward pass, conditioned on the target trunk's residual stream at five
* intermediate layers. Published acceptance length 5.52 at T = 0 (math 6.05 / code 6.11 /
* general 4.16) against MTP's 3.74-5.02.
* general 4.16) versus MTP's 3.74-5.02.
*
* IT IS NOT rad_block_dflash2.h, and the name is the trap. DSpark subclasses SpecForge's
* `DFlashDraftModel`, which is PLAIN QWEN3 ATTENTION LAYERS; this library's `Dflash2` is the
* conv-based drafter (`dflash_conv`, `attn_conv_base`, `sel_rank`/`sel_topk`) from a different
* checkpoint of the same family. Same lineage, same word in the name, different architecture --
* and the checkpoint settles it: 5 layers of q/k/v/o + q_norm/k_norm + gate/up/down and not one
* conv or selection tensor. What IS taken from that file is its shape (Config / Wire / declare /
* context / step), its two rules, and -- see THE MARKOV HEAD below -- its selector.
* Not rad_block_dflash2.h despite the name: DSpark subclasses SpecForge's `DFlashDraftModel`,
* which is plain Qwen3 attention (the checkpoint has q/k/v/o, q_norm/k_norm, gate/up/down and no
* conv or selection tensors), while `Dflash2` is the conv-based drafter. This block reuses
* Dflash2's structure (Config / Wire / declare / context / step) and its selector.
*
* ============================== THE FORWARD PASS, PINNED ==============================
* ============================== THE FORWARD PASS ==============================
*
* The reference is NOT in the published repo: `config.json` says `auto_map: dspark.DSparkDraftModel`
* and the repo holds only config / README / safetensors. `RadixArk/Qwen3.8-27B-DSpark` ships
* `dspark.py` and `dflash.py`, and that pair is the spec this block implements. The composition is
* not recoverable from the tensor list alone, so it is written out here:
* The published repo has no reference code (`auto_map: dspark.DSparkDraftModel`);
* `RadixArk/Qwen3.8-27B-DSpark` ships `dspark.py` and `dflash.py`, which this implements:
*
* target_hidden = hidden_norm(fc(concat of the trunk's residual stream after layers
* 1, 10, 20, 30, 39)) [n_taps * n_embd] -> [n_embd]
* h = target.embed_tokens([anchor, MASK, MASK, ...]) `block` noise rows
* per layer (x5):
* h_n = input_layernorm(h)
* q = q_norm(q_proj(h_n)) Q FROM THE NOISE ROWS ONLY
* q = q_norm(q_proj(h_n)) q from the noise rows only
* k = k_norm(concat(k_proj(target_hidden), k_proj(h_n))) context first, then noise
* v = concat(v_proj(target_hidden), v_proj(h_n))
* rope(q, k); attention is NON-CAUSAL, mask None at inference
* rope(q, k); attention is non-causal, mask None at inference
* h += o_proj(attn); h += mlp(post_attention_layernorm(h))
* logits = target.lm_head(norm(h)) + markov_w2 @ markov_w1[prev_token]
*
* `fc` THEN `hidden_norm`, in that order, and `target_hidden` is computed ONCE and fed to EVERY
* layer, which projects it with its OWN k_proj and v_proj. The drafter ships no embedding table
* and no lm_head; it reads the target's, which is why a vocabulary that disagrees is not a drafter
* for this target at all.
* `fc` then `hidden_norm`; `target_hidden` is computed once and each layer projects it with its
* own k_proj and v_proj. The drafter uses the target's embedding table and lm_head, so the
* vocabularies must agree.
*
* ============================== THE DUAL-SOURCE K/V IS AN ORDINARY KV CACHE ==============================
* ============================== DUAL-SOURCE K/V AS A PAGED CACHE ==============================
*
* `concat(proj(target_hidden), proj(noise))` needs no new kernel and no fused-operand games. The
* reference's own cache says why: `past_key_values.update` appends the context rows and the noise
* rows, the block attends over the whole thing, and then `crop(start)` throws the noise away. That
* is a paged KV group with the context written per COMMITTED TOKEN and the noise rows written into
* slots past `seqused` -- which the next context pass overwrites, so the crop is free.
* The reference appends context and noise rows to its cache, attends over both, then
* `crop(start)`s the noise. Here that is a paged KV group: context written per committed token,
* noise rows written past `seqused`, where the next context pass overwrites them. Two passes, as
* in Dflash2:
*
* So the split is the same two passes Dflash2 has, for the same reason:
* Context pass, one row per committed token: the five k/v projections over the projected trunk
* taps, stored. The drafter's layers never run over the context.
*
* THE CONTEXT PASS, one row a committed token. It runs the five k/v projections over the
* projected trunk taps and stores them. The drafter's own layers never run over the context.
* Query pass, `block` rows per sequence, through the five layers, attending to the context and
* to each other.
*
* THE QUERY PASS, `block` rows a sequence, over the drafter's five layers, attending to the
* context rows AND to each other.
* `k_norm` is per head over head_dim, so norming the two halves separately is bit-identical to
* norming the concatenation. `attn_paged` with `causal = 0` serves the non-causal block. The
* shape (16 heads, 2 KV heads, head_dim 128, GQA 8) matches the target, so the trunk's attention
* and norm/rope rows serve it.
*
* AND THE PER-HEAD NORM OVER THE CONCAT IS THE SAME NUMBER EITHER WAY. `k_norm` is an RMS norm
* over each head's own `head_dim` row, so norming the context half in one pass and the noise half
* in the other is bit-for-bit what norming the concatenation would have been. Nothing about the
* split is an approximation.
* ============================== ROW ALIGNMENT ==============================
*
* `attn_paged` ALREADY TAKES `causal`, so `causal = 0` serves the non-causal block: every noise
* row sees every other row of its own block as well as the whole context. This drafter is
* 16 head / 2 kv / head_dim 128 = GQA 8, the same shape as its target, so the attention and the
* norm/rope rows the trunk resolves serve it unchanged.
* `block` is both the number of noise rows and the number of drafts (seven in, seven out, verify
* width eight). Row j of [anchor, MASK x (block-1)] predicts position start + j + 1, the anchor
* row included, so `steps() == block` here and `block - 1` in Dflash2, whose anchor row predicts
* nothing. Getting this wrong only shifts proposals by one and drops acceptance to chance. The
* core stages the block against `RadDrafterDecl::block` and runs the head over the last `depth`
* rows, which covers both conventions (rad_builder.h).
*
* ============================== THE ROW ALIGNMENT, WHICH IS THE WHOLE GAME ==============================
*
* `block_size` IS THE NUMBER OF NOISE ROWS AND ALSO THE NUMBER OF DRAFTS. Seven rows in, seven
* tokens out, verify width eight. The noise stream is [anchor, MASK x (block-1)] and ROW j
* PREDICTS THE TOKEN AT POSITION start + j + 1 -- the ordinary next-token relation, anchor row
* included, which is why `steps() == block` here and `steps() == block - 1` in Dflash2.
*
* THAT IS THE OPPOSITE CONVENTION TO Dflash2 AND IT IS INVISIBLE IF YOU GET IT WRONG. Dflash2's
* anchor row predicts nothing and each MASK row predicts the token at ITS OWN position; DSpark's
* anchor row is a real prediction and no row is wasted. Both run, both produce `depth` tokens, and
* the model's own output stays exactly correct either way because every draft is verified against
* the trunk -- what happens instead is that the proposals are shifted one position and acceptance
* falls to roughly chance. The core stages the block against `RadDrafterDecl::block` and runs the
* head over the LAST `depth` rows, which is the one rule both conventions reduce to; rad_builder.h
* argues it, and this file is the reason that field exists.
*
* ============================== THE MARKOV HEAD IS Dflash2'S SELECTOR ==============================
* ============================== THE MARKOV HEAD USES Dflash2'S SELECTOR ==============================
*
* DSpark adds a rank-256 learned bigram bias to the draft logits:
*
* logits[l] += markov_w2 @ markov_w1[prev(l)] prev(0) = the anchor,
* prev(l) = the token chosen at l - 1
*
* which is SERIAL in l for exactly the reason a block-diffusion drafter needs a selector at all:
* the positions were computed together and the bias at l depends on the token chosen at l - 1.
* Written literally it is seven full-vocabulary [rank, n_vocab] GEMMs with an argmax between each
* -- 66 MiB of `markov_w2` read seven times a step to use seven of its rows.
*
* `dflash_select` ALREADY COMPUTES THIS. Its edge score is
* This is serial in l. Literally it is seven [rank, n_vocab] GEMMs with an argmax between each,
* reading 66 MiB of `markov_w2` seven times a step. `dflash_select` scores
*
* unary[l][c] + sum_r pred[prev][r] * hp[l][r] * succ[cand[l][c]][r]
*
* over the base head's top K candidates, with the predecessor read after the previous step's
* argmax inside one workgroup and no launch between steps. Set `hp` ABSENT -- it is optional, and
* absent it is ones -- and the trilinear form drops to the plain bigram
* `<pred[prev], succ[cand]>`; pass `markov_w1` as `pred` and `markov_w2` as `succ` and the walk IS
* the Markov head, greedily decoded. The codebook gather is K * rank * 2 bytes a position, 8 KiB
* at K = 16, against 466 MiB for the literal form.
* over the base head's top K, reading the predecessor after the previous step's argmax inside one
* workgroup. With `hp` absent (treated as ones) it is the bigram `<pred[prev], succ[cand]>`;
* passing `markov_w1` as `pred` and `markov_w2` as `succ` makes the walk the greedily decoded
* Markov head. The gather is K * rank * 2 bytes a position (8 KiB at K = 16).
*
* WHAT IS APPROXIMATED IS THE CANDIDATE SET AND NOTHING ELSE: the bias can only re-rank the base
* head's top K, where the reference could promote any of 130560. That is the same trade the 2-bit
* draft head makes and it is sound for the same reason -- a draft is a proposal, the target
* verifies every one of them with its own untouched head, and speculative decoding is
* distribution-preserving, so a coarser draft costs acceptance and CANNOT change an emitted token.
* `RADIANCE_DRAFT_RAW=dspark_cand` proposes column 0 of the candidate plane instead, which is the
* base head's own argmax with the Markov walk thrown away: it isolates what the walk contributes,
* and it needs no rebuild.
* Only the candidate set is approximated: the bias re-ranks the base head's top K, where the
* reference could promote any of 130560 tokens. Since every draft is verified, this costs only
* acceptance.
*
* THE CONFIDENCE HEAD IS NOT IMPLEMENTED AND THAT IS NOT A GAP. `AcceptRatePredictor` predicts a
* per-position acceptance probability so a serving loop can shorten the block adaptively; this
* engine's depth is fixed at declare time and only 1, 3 and 7 are legal. It changes nothing the
* drafter proposes, so ignoring it is exactly correct -- unlike the input/output scalars Dflash2
* refuses, which would silently move every logit.
* The confidence head (`AcceptRatePredictor`) is not implemented: it only lets a serving loop
* shorten the block adaptively, and this engine's depth is fixed at declare (1, 3 or 7). It does
* not change what the drafter proposes.
*
* ============================== THE NORMS ARE PLAIN ==============================
* ============================== PLAIN NORMS ==============================
*
* `w`, not `1 + w`: the reference norms with `Qwen3RMSNorm` and the config says `model_type:
* qwen3`. `Geom::wadd` and `wadd_qk` are therefore ZERO for this block, which happens to agree
* with its MiniCPM5 target -- but it is the drafter's own answer and not inherited, and the two
* geometries are separate structs partly for this.
* `w`, not `1 + w`: the reference uses `Qwen3RMSNorm` (`model_type: qwen3`), so this geometry's
* `wadd` and `wadd_qk` are zero. That matches the MiniCPM5 target but is the drafter's own
* setting.
*
* ============================== WHAT IS FP8 AND WHAT IS NOT ==============================
* ============================== PRECISION ==============================
*
* E4M3 + a bf16 [N/128][K/128] plane fc, q/k/v/o, gate_up, down -- every linear
* BF16, no plane every norm, and both Markov codebooks
* what the recipe made them fc, q/k/v/o, gate_up, down -- every linear
* bf16, no plane every norm, and both Markov codebooks
*
* The checkpoint is dense bf16 throughout, so the first row is rad_fp8.h's DenseFP8 over a weight
* the recipe quantises to block fp8. The reason is bytes -- the drafter is read WHOLE on every
* decode step, so 324M parameters at bf16 is 648 MB a step and at fp8 is 324 MB. Nothing it
* computes can change an emitted token; the only thing quantising it can move is acceptance.
* The checkpoint is dense bf16; the linears are rad_fp8.h's DenseFP8 over weights the recipe
* quantises, because the drafter is read whole every decode step (324M parameters: 648 MB at
* bf16, 324 MB at eight bits). DenseFP8 reads block fp8 or MXFP4 against E4M3 activations, or a
* rotated int8 form (IQ8R and the narrower grids under the same rotation) against int8 ones
* (Config::act_i8); one format for all of them, since they share the activation pairs. This can
* only change acceptance.
*
* The codebooks stay bf16 and REPLICATED because they are gathered by GLOBAL token id out of a
* merged candidate set: a vocabulary shard would let a rank score only the candidates that
* happened to land in its own slice. 66.8 MiB each, and the gather is K rows a position, so what
* costs is the residency and not the reads.
* The codebooks are bf16 and replicated: they are gathered by global token id from a merged
* candidate set. 66.8 MiB each; only K rows are read per position, so the cost is residency.
*
* ============================== WHAT IS LEFT ON THE TABLE ==============================
* ============================== NOT DONE ==============================
*
* Two things this block does not do, and what each would be worth:
* The q/k norms and ropes are four launches per layer where `qk_norm_rope` would be one. That
* op takes a fused [q|k] row; the query pass would need a [q_dim + kv_dim] buffer, a column-
* slice store and a contiguous q copy, as in rad_block_attn_fp8.h. Worth twenty launches a step.
*
* THE Q/K NORM AND ROPE ARE FOUR LAUNCHES A LAYER where `qk_norm_rope` would be one. That op
* takes a FUSED [q|k] row and this block keeps q, k and v in three buffers -- which the context
* pass forces for k and v (it computes them with no q at all, and a block-scaled weight's layout
* follows its op's N) but does not force for the query pass. Fusing would want a [q_dim + kv_dim]
* buffer, a column-slice store, and a contiguous q lift for the attention, which is the trunk's
* own arrangement (rad_block_attn_fp8.h). It is worth twenty launches a step.
*
* THE ALL-REDUCE IS NOT FOLDED INTO THE FOLLOWING NORM. NormQuantFP8 has the fused form and this
* block passes kArNone, so a tp2 query pass issues ten collectives of its own. At `block` rows a
* sequence the message is 28 KiB at one sequence -- under the lossy wire's floor and served
* exactly -- so what a fold saves is launches, not bytes.
* The all-reduce is not folded into the following norm (kArNone), so a TP2 query pass issues
* ten collectives. At 28 KiB per message for one sequence (under the lossy floor), a fold
* would save launches, not bytes.
*/
#ifndef RAD_BLOCK_DSPARK_H
#define RAD_BLOCK_DSPARK_H
@@ -169,78 +127,82 @@ namespace arch {
struct Dspark {
enum { MAX_LAYERS = 8 };
/* The 2-bit draft head's scale group, which is the w2a8 row's own and not a choice. */
/* The 2-bit draft head's scale group, fixed by the w2a8 row. */
enum { DS_W2_GROUP = 128 };
/* Everything the drafter's own config.json says that its geometry does not. Read by the plugin
* from `draft.*` metadata keys and handed in whole, so this file reads no environment and no
* container. */
/* The drafter config beyond its geometry, read by the plugin from `draft.*` metadata keys. */
struct Config {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* NOISE ROWS a sequence -- and drafts, one per row */
int64_t block = 0; /* noise rows per sequence, and drafts (one per row) */
int64_t rank = 0; /* markov_rank: the codebooks' width */
int64_t top_k = 0; /* candidates the Markov walk re-ranks */
int64_t window = 0; /* sliding attention width, 0 for none */
int causal = 0;
/* EVERY ROW PREDICTS, so this is `block` and not `block - 1`. See THE ROW ALIGNMENT. */
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
* by had_quant_act_i8g and the rotating norm. Every linear must agree. `fc_mapped`:
* probe_i8 made `dspark.fc.weight`'s name map. */
bool act_i8 = false;
int64_t act_g8 = RAD_FP8_BLOCK;
bool fc_mapped = false;
/* Every row predicts, so `block`, not `block - 1` (see ROW ALIGNMENT). */
int64_t steps() const { return block; }
};
struct Wire {
/* ---- the context pass, one row a COMMITTED TOKEN */
/* ---- the context pass, one row per committed token */
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
rad_buf c = 0; /* [max_tok, n_embd] fc's output, then normed in place */
/* K AND V ARE TWO BUFFERS, not one [max_tok, 2*kv_dim] with K in its left half. Both
* halves are written by one projection and read by one kv_store, so fusing them is the
* obvious thing -- and it is wrong, because of the PER-HEAD NORM in between. `rmsnorm`
* takes ONE row pitch. K inside a fused row is `head_dim` apart within a token and
* `2*kv_dim` apart between tokens, and no single pitch is both; answering with the
* between-tokens stride normalises every eighth head against the wrong numbers, which is
* a drafter that runs and barely proposes anything the trunk accepts. libr4d refuses that
* operand (libr4d/r4d_model.cpp, rows_pitch). */
rad_buf ck = 0; /* [max_tok, kv_dim] ONE layer's K, reused across layers */
rad_buf cv = 0; /* [max_tok, kv_dim] ONE layer's V, reused across layers */
rad_buf srcq = 0, srcs = 0; /* the fp8 twins: e4m3 | f32 [.., /128] */
/* K and V are separate buffers because of the per-head k norm: `rmsnorm` takes one row
* pitch, and K heads inside a fused [K|V] row are head_dim apart within a token but
* 2*kv_dim apart between tokens. libr4d refuses such an operand (libr4d/r4d_model.cpp,
* rows_pitch). */
rad_buf ck = 0; /* [max_tok, kv_dim] one layer's K, reused across layers */
rad_buf cv = 0; /* [max_tok, kv_dim] one layer's V, reused across layers */
/* The codes and scales the linears read: e4m3 | f32 [.., /128], or with Config::act_i8
* i8 | f32 [.., /act_g8]. The same holds for the three ActFP8 pairs below, whose `q` and
* `s` are then the int8 pair. */
rad_buf srcq = 0, srcs = 0;
rad_buf cq = 0, cs = 0;
/* ---- the query pass, `block` rows a sequence */
/* ---- the query pass, `block` rows per sequence */
rad_buf x = 0; /* [qrows, n_embd] the drafter's residual stream */
/* THE NORMED INPUT AND THE BLOCK'S DELTA ARE ONE ACTIVATION, which is the trunk's own
* arrangement (rad_block_attn_fp8.h): o_proj and down_proj write `h.x`, and the NEXT
* norm reads it as the delta to fold into the stream before norming. One buffer, and the
* op that reads it also writes it. */
/* Normed input and the block's delta share one activation, as in the trunk
* (rad_block_attn_fp8.h): o_proj and down_proj write `h.x`, and the next norm folds it
* into the stream before norming, writing `h` again. */
ActFP8 h{}; /* [qrows, n_embd] */
rad_buf q = 0; /* [qrows, q_dim] */
rad_buf k = 0; /* [qrows, kv_dim] -- two buffers, and `ck` above says why */
rad_buf k = 0; /* [qrows, kv_dim] separate from v, see `ck` */
rad_buf v = 0; /* [qrows, kv_dim] */
ActFP8 attn{}; /* [qrows, q_dim] */
rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
ActFP8 ffn{}; /* [qrows, n_ff] */
/* ---- the head and the Markov walk, one row a DRAFT POSITION */
/* ---- the head and the Markov walk, one row per draft position */
rad_buf sel_h = 0; /* [srows, n_embd] the gathered final hidden states */
rad_buf dq = 0; /* [srows, n_embd] i8 the 2-bit head's quantised activation */
rad_buf ds = 0; /* [srows, 1] f32 one scale a row */
rad_buf dsum = 0; /* [n_embd/128, pad] f32 GROUP-major, quant_act_i8's asum plane */
rad_buf dlog = 0; /* [srows, head_rows(g)] bf16 the coarse logits */
rad_buf cand = 0; /* [srows, top_k] i32 candidate token ids, GLOBAL */
rad_buf cand = 0; /* [srows, top_k] i32 candidate token ids, global */
rad_buf unary = 0; /* [srows, top_k] f32 and their logits */
/* The vocab-parallel pair, declared only when the head is sharded. Both are (int32 id,
* float value) pairs read as f32: this rank's top-R, and the all-gathered world * R. */
/* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
* pairs stored as f32, this rank's top-R and the all-gathered world * R. */
rad_buf dpair = 0; /* [srows, top_k, 2] f32 */
rad_buf dgath = 0; /* [srows, world * top_k, 2] f32 */
rad_buf tokens = 0;/* [max_seqs, steps] i32 THE DRAFT -- the engine reads this by name */
rad_buf tokens = 0;/* [max_seqs, steps] i32 the draft; the engine reads it by name */
};
/* rad_arch.h's, asked through the block so whoever sizes `dlog` and the pair planes does not
* re-derive the rule. */
/* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
* planes. */
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
static int64_t head_rows(const Geom& g) { return vocab_head_rows(g); }
Geom g{}; /* the DRAFTER's geometry, not the trunk's */
Geom g{}; /* the drafter's geometry, not the trunk's */
Config cfg{};
Wire w{};
int first_layer = 0; /* absolute, so the KV group's layer_slot lookup finds these five */
int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */
int64_t qrows = 0, crows = 0, srows = 0;
int64_t gated_rows = 0; /* the band op_gug was declared over; 0 when there is no fold */
rad_kvgroup kv = 0;
@@ -249,14 +211,12 @@ struct Dspark {
DenseFP8 w_fc{};
rad_weight w_hnorm = 0, w_norm = 0;
rad_weight w_mk1 = 0, w_mk2 = 0; /* markov_w1 (pred), markov_w2 (succ) */
rad_weight w_tok = 0; /* the TARGET's embedding table */
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit copy of the TARGET's lm_head */
rad_weight w_tok = 0; /* the target's embedding table */
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit copy of the target's lm_head */
/* ---- per-layer weights. Q, K AND V ARE THREE WEIGHTS and not the trunk's fused one: the
* context pass wants k and v over the projected taps and has no use for q at all, so a fusion
* would make it compute and discard a q_dim-wide GEMM per layer per context token. K and V are
* apart from each other because a block-scaled weight's layout is a function of its OP's N and
* both passes take one of them at a time. */
/* ---- per-layer weights. q, k and v are separate: the context pass needs only k and v, and a
* block-scaled weight's layout follows its op's N, so k and v cannot be one weight issued a
* half at a time. */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{};
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {};
@@ -266,17 +226,14 @@ struct Dspark {
rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0;
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
/* ---- query-pass ops. The weightless ones are declared once and issued per layer: an op's
* declared read and write sets are what the buffer planner reads, and they are the same every
* layer. The per-layer ones are per-layer because a weight's prefetch interval and residency
* class come from the op that declares it. */
/* ---- query-pass ops. Weightless ones are declared once and issued per layer; ops with weights
* are per layer because a weight's prefetch interval and residency class come from the op
* that declares it. */
rad_op op_embed = 0, op_embed_ar = 0;
/* THE FUSED NORM / RESIDUAL-ADD / QUANTISE, declared by hand rather than through rad_fp8.h's
* NormQuantFP8. The wrapper's extra machinery is its FUSED-COLLECTIVE forms, which this block
* does not take (see WHAT IS LEFT ON THE TABLE), so what is left of it is one op -- and an
* ARRAY of the wrapper is not compilable: it nests a Geom, and g++ 16.1 ICEs in build_vec_init
* value-initialising an array of that inside an enclosing aggregate assignment (`m = Model{}`
* in the plugin). Handles are what every other member here is anyway. */
/* The fused norm / residual add / quantise, declared directly rather than via rad_fp8.h's
* NormQuantFP8: this block uses none of its fused-collective forms, and an array of the wrapper
* (which nests a Geom) makes g++ 16.1 ICE in build_vec_init when the plugin assigns
* `m = Model{}`. */
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
rad_op op_qat = 0;
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
@@ -292,13 +249,25 @@ struct Dspark {
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
rad_op op_sel = 0;
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
* declared, since it decides their dtype and scale grid. */
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
const char* fwn = nm.f("dspark.fc.weight");
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
RadEncoding fe{};
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
return RAD_OK;
}
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
const char* ck_lm, const char* ck_lm_alt, const Wire& wire);
/* The context pass, one row a committed token. `batch` carries those rows and the draft KV
* group's slot mapping; nothing about the query block is read. */
/* The context pass, one row per committed token; `batch` carries those rows and the draft KV
* group's slot mapping. */
void context(RadCtx* c, const RadBatch* batch) const;
/* The query pass, the head and the Markov walk: one call, `block` rows a sequence. */
/* The query pass, the head and the Markov walk, `block` rows per sequence. */
void step(RadCtx* c, const RadBatch* batch) const;
private:
@@ -326,17 +295,22 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
crows = g.max_tok;
qrows = g.max_seqs * cfg.block;
if (qrows > g.max_tok) qrows = g.max_tok;
/* EVERY QUERY ROW PREDICTS, so the head runs over as many rows as the block has. They are the
* same number and they are kept apart anyway: one is a pass's rows and the other is what the
* head was declared over, and Dflash2 -- the same struct shape over the other convention --
* has them differ by one sequence's worth. */
/* Every query row predicts, so srows equals the block's rows; kept separate from qrows because
* Dflash2's convention makes them differ. */
srows = g.max_seqs * cfg.steps();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
w_fc.w8h_ok = cfg.act_i8;
for (int i = 0; i < MAX_LAYERS; ++i)
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
w_dn[i].w8h_ok = cfg.act_i8;
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dspark.fc"), g.n_embd, cfg.n_taps * g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
{ nm.ckpt("%s.fc.weight", ck) }));
{ nm.ckpt("%s.fc.weight", ck) }, {}, cfg.fc_mapped));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
@@ -346,11 +320,10 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
/* THE TWO MARKOV CODEBOOKS, replicated at the WHOLE vocabulary and bf16. `markov_w1` is an
* nn.Embedding and `markov_w2` an nn.Linear, and both store [vocab, rank] -- so the bigram
* bias `w2 @ w1[prev]` is `<w1[prev], w2[cand]>` and the two go straight into the selector's
* `pred` and `succ` slots in that order. RAD_ACCESS_VOCAB because the reads are a gather of K
* rows a position and not a pass over the plane. */
/* The Markov codebooks, bf16, replicated over the whole vocabulary. `markov_w1` (nn.Embedding)
* and `markov_w2` (nn.Linear) both store [vocab, rank], so `w2 @ w1[prev]` is
* `<w1[prev], w2[cand]>` and they map to the selector's `pred` and `succ`. RAD_ACCESS_VOCAB:
* reads gather K rows per position. */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"),
nm.ckpt("%s.markov_head.markov_w1.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
@@ -361,16 +334,12 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
/* THE 2-BIT DRAFT HEAD, over the TARGET's lm_head. `dspark.draft_head.weight` is that tensor
* under a name of its own, which the recipe quantises to the 2-bit grid (u2 codes, an f16
* scale and a u8 zero a group of 128): one checkpoint tensor, two logical weights. The
* argument is rad_block_mtp_fp8.h's and it is the same one the Markov walk's top-K rests on: a
* draft is verified, so a coarser head costs acceptance and cannot move an emitted token.
/* The 2-bit draft head over the target's lm_head (as in rad_block_mtp_fp8.h):
* `dspark.draft_head.weight` is that tensor under its own name, quantised by the recipe to u2
* codes with an f16 scale and u8 zero per group of 128. One checkpoint tensor, two views.
*
* A TIED HEAD IS THE ALTERNATIVE SOURCE. Small LLaMA derivatives ship no `lm_head.weight` and
* read the embedding table as both; the trunk's own head is declared that way and the
* drafter's copy has to agree with it or the two would disagree about what the model's
* vocabulary projection IS. */
* The alternative source covers a tied head (small LLaMA derivatives ship no `lm_head.weight`
* and reuse the embedding); it must match how the trunk declares its own head. */
const bool dh_shard = head_sharded(g);
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
const char* dhn = nm.f("dspark.draft_head.weight");
@@ -426,15 +395,11 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
{ nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
}
/* NON-CAUSAL. The block is denoised as a whole, so every query row sees every other row of its
* own block as well as the context -- `causal` 0 is the drafter's own `is_causal: false` and
* not a default.
/* Non-causal: each query row sees its whole block plus the context (`causal` comes from the
* config's `is_causal: false`).
*
* DECLARED FIRST, before either kv_store, even though it runs after both. `block_size` is
* RAD_DERIVED -- the KV block is a property of the resolved attention kernel and not a number
* anyone gets to choose -- so it is omitted here and READ BACK with rad_kv_block_size() for
* the two stores, which need it as a parameter. Ask before the attention op is declared and
* the answer is zero. */
* Declared before both kv_stores, which read the resolved `block_size` back with
* rad_kv_block_size(); before this declaration it returns zero. */
op_attn = rw(b, RAD_OP(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
@@ -447,52 +412,54 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
/* ---------------------------------------------------------------- the context pass
*
* EVERY LINEAR HERE IS `fp8a8` and every activation that feeds one gets a `quant_act_fp8` in
* front of it. There is no `fp8a16` band anywhere in this block: that kernel is M <= 1 and
* neither pass ever runs at one row -- a context pass is a committed chunk and a query pass is
* `block` rows by construction. */
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
* Every linear is a DenseFP8 GEMM over the pair its quantiser writes: `quant_act_fp8` codes
* for block fp8 or MXFP4, had_quant_act_i8g's at the weights' scale group for a rotated int8
* drafter (cfg.act_i8). The linears read one activation pair, so they are all i8a8h forms at
* one group or none is. There is no `fp8a16` band: that kernel is M <= 1, and neither pass
* runs at one row. */
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
{
auto fits = [&](const DenseFP8& d) {
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
};
bool same = fits(w_fc);
for (int64_t l = 0; l < g.n_layer; ++l)
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
fits(w_gu[l]) && fits(w_dn[l]);
if (!same) {
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
"group or all block fp8 / MXFP4; they read one activation pair, so the "
"recipe must give them one format\n");
return RAD_E_DTYPE;
}
}
op_qsrc = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
RAD_INT("K", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_fc.w, w_fc.s)),
{w.srcq, w.srcs}, {w.c});
/* IN PLACE. Safe for any implementation that computes a row's scale before writing the row,
* which none can avoid doing; the per-head q/k norms below run in place for the same reason. */
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
* written. */
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.c});
/* ONE QUANTISE FOR ALL FIVE LAYERS. `c` is the normed projection of the trunk's taps and every
* layer's k|v reads that same buffer, so this is one launch a context pass and not five. */
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
/* One quantise for all layers: every layer's k and v read the same `c`. */
op_qc = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.c}, {w.cq, w.cs});
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* TWO OPS OF THE SAME SHAPE, one per weight: an op's declared weight list is what gives a
* weight its prefetch interval and its residency class. */
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.cq, w.cs}, {w.ck});
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.cq, w.cs}, {w.cv});
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
* and residency class. */
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
@@ -500,14 +467,11 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_WEIGHTS(w_kn[i])),
{w.ck}, {w.ck});
}
/* K-ONLY ROPE. `rope` rotates the first n_head + n_head_kv heads of its operand and leaves the
* V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
* n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
* serves every layer.
/* K-only rope: `rope` rotates the first n_head + n_head_kv heads, so a K-only tensor is
* n_head = n_head_kv, n_head_kv = 0. Weightless, so one op serves every layer.
*
* THE POSITION IS THE COMMITTED TOKEN'S OWN, which is what makes the split passes equal the
* reference's one concatenated rope: it hands `k` the full position range and `q` only the
* last `q_len` of it, so a context row at absolute position p is rotated by p either way. */
* Each context row is rotated by its own absolute position, as in the reference's single
* concatenated rope (k gets the full position range, q the last q_len). */
op_crope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
@@ -530,9 +494,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
/* The target's embedding is vocab-sharded, so this gather is partial and takes the same EXACT
* reduction the trunk's does: each token's row comes from one rank and every other contributes
* a zero, so a lossy wire would be pure loss on a value that is already the answer. */
/* The target's embedding is vocab-sharded, so the lookup is partial. The all-reduce is exact:
* each row comes from one rank and the others add zero, so a lossy wire would only lose
* precision. */
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -541,29 +505,21 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_NOWEIGHTS),
{w.x}, {w.x});
/* THE NORM, THE RESIDUAL ADD AND THE QUANTISER ARE ONE OP -- `rmsnorm_quant_fp8`, which
* rad_fp8.h's NormQuantFP8 wraps. Layer 0 has no delta to fold (its input is the embedding
* itself), every layer after it folds the previous feed-forward's, and `nq_out` folds the last
* one into the FINAL norm. So there is no `add` op in this block at all and the final norm is
* not a separate launch either.
/* Norm, residual add and quantise are one op, `rmsnorm_quant_fp8` (what rad_fp8.h's
* NormQuantFP8 wraps), or its rotating int8 twin `rmsnorm_had_quant_i8g` for a rotated int8
* drafter, which takes the same operands. Layer 0 has no delta to fold, each later norm folds the previous
* block's delta, and op_outnorm folds the last into the final norm, so there is no `add` op.
* The final norm's fp8 output is unused (the head runs its own i8 quantiser), a few KiB of
* waste that saves a launch: libr4d has no plain `rmsnorm_add` row.
*
* `nq_out` QUANTISES SOMETHING NOTHING READS. The head after it wants bf16 (it runs its own
* i8 quantiser at a different group width), and this op writes the bf16 normed row as well as
* the fp8 twin -- so the twin is 14 KiB of waste at a seven-row block, against a launch. The
* alternative is `add` + `rmsnorm`, which is two, because libr4d has no plain `rmsnorm_add`
* row: `rmsnorm_quant_fp8` IS this library's fused norm-add. */
/* `x` IS THE DELTA AND `residual` IS THE STREAM, and the op adds the first into the second
* before norming: residual_out = x + residual, y = rmsnorm(residual_out) * w. So a FOLDED
* site passes the previous block's output buffer as `x` and the stream as `residual`, and the
* UNFOLDED one (layer 0, whose input is the embedding) passes the stream as `x` and no
* residual at all. An absent optional operand is a null tensor in a full-length list.
*
* `residual` is INOUT, so it is in both sets: the buffer planner reads these for liveness and
* an INOUT that claimed only one of them is a plan free to reorder a reader in front of it. */
* The op computes residual_out = x + residual, y = rmsnorm(residual_out) * w. A folded site
* passes the previous block's output as `x` and the stream as `residual`; layer 0 passes the
* stream as `x` and no residual. `residual` is INOUT, so it is in both the read and write sets;
* otherwise the planner could reorder a reader in front of it. */
auto decl_norm = [&](rad_weight gain, bool fold) -> rad_op {
rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
rad_op h = RAD_OP(b, cfg.act_i8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
RAD_F64("eps", g.eps), RAD_INT("group", qgr),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(gain));
if (!h) return 0;
@@ -573,48 +529,27 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
rad_op_writes(b, h, wr, fold ? 4 : 3);
return h;
};
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
op_qat = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn.x}, {w.attn.q, w.attn.s});
if (!op_qat) return RAD_E_INVAL;
/* THE NORMS ARE DECLARED WHERE step() ISSUES THEM, because declaration order is the buffer
* planner's liveness: a transient lives over the op indices that touch it, and two whose spans
* are disjoint may share bytes (core/build/rad_bufplan.cpp). The stream `x` and the norm
* outputs `h` are live across every layer, and the norms are the only ops that touch the
* stream after the embedding, so their positions are the stream's lifetime. Each layer's two
* norms sit inside the loop and the final one after every op the layers issue -- the shared
* rope, store, silu_mul and quantiser handles below included.
*
* Declared together ahead of the layers, the stream's lifetime ended before the first layer's
* temporaries began, and the packer put a feed-forward temporary on top of it. The fused gated
* GEMM never writes those, so the overlap stayed silent up to 64 rows a pass; past 64 the
* unfused pair writes `gate_up` and `ffn.x`, and every draft was rejected from the tenth
* sequence on. */
/* Invariant: the norms are declared where step() issues them. Declaration order is the buffer
* planner's liveness (a transient lives over the op indices that touch it, and disjoint spans
* may share bytes; core/build/rad_bufplan.cpp). The norms are the only ops touching the stream
* `x` after the embedding, so their positions define its lifetime: each layer's two norms sit
* in the loop, the final one after every op the layers issue, including the shared handles
* below. Declared up front, the stream's lifetime would end before the layers and the planner
* could overlay a feed-forward temporary on it. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = decl_norm(w_anorm[i], i != 0);
if (!op_anorm[i]) return RAD_E_INVAL;
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
{w.h.q, w.h.s}, {w.q});
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.h.q, w.h.s}, {w.k});
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.h.q, w.h.s}, {w.v});
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h.q, w.h.s}, {w.q});
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.k});
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.v});
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
@@ -627,44 +562,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.k});
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
{w.attn.q, w.attn.s}, {w.h.x});
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.attn.q, w.attn.s}, {w.h.x});
op_fnorm[i] = decl_norm(w_fnorm[i], true);
if (!op_fnorm[i]) return RAD_E_INVAL;
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
{w.h.q, w.h.s}, {w.gate_up});
/* THE GATED FOLD: gate_up, silu_mul and the quantiser in one GEMM epilogue, over the same
* weights and into the same activation. NOT RAD_ARCH_TRY -- a kernel set without the row
* is the ordinary case and the pair below still runs -- and `gated_rows` is the band it
* was declared over, checked at the issue site, because M past the band is a REFUSAL in
* the kernel and not a slower path. */
{
const int64_t hi = qrows < 64 ? qrows : 64;
if (hi > 0) {
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s});
if (op_gug[i]) gated_rows = hi;
}
}
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
{w.ffn.q, w.ffn.s}, {w.h.x});
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h.q, w.h.s}, {w.gate_up});
/* The fold is an fp8a8 tile, so any other gate_up takes the pair. */
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffn.q, w.ffn.s}, {w.h.x});
}
op_qrope = rw(b, decl_rotary(b, g, "rope",
@@ -693,16 +599,13 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ffn.x});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
op_qff = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.ffn.x}, {w.ffn.q, w.ffn.s});
/* ONE COLLECTIVE DECLARATION, issued after the out projection and after the down projection:
* the two have the same shape over the same buffer. It is EXACT or lossy by the deployment's
* own setting, exactly as the trunk's is -- the drafter's message is the same residual stream
* and there is no reason for it to be held to a different standard than the thing it drafts
* for. */
/* One collective, issued after both the out and the down projection (same shape, same buffer).
* Exact or lossy per the deployment, as for the trunk. */
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -716,12 +619,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
/* ---------------------------------------------------------------- the head and the walk
*
* EVERY ROW OF THE BLOCK PREDICTS, so the head runs over all `steps` of them and the anchor is
* not skipped -- THE OPPOSITE of Dflash2, and the paragraph at the top of this file is why.
* The gather is what makes those rows contiguous, and it is also what fixes the head's row
* numbering at s * steps + l, which is the numbering the walk reads. It is the identity map
* for this convention as the scheduler emits it; it is issued anyway, because `out_ids` is the
* contract and RADIANCE_DFLASH_ANCHOR is allowed to move it. */
* Every row predicts, so the head runs over all `steps` rows, anchor included (see ROW
* ALIGNMENT). The gather numbers rows s * steps + l as the walk reads them; for this
* convention it is the identity, but `out_ids` is the contract, so it is issued anyway. */
op_gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
@@ -738,10 +638,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_STR("dtype", "w2a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds, w.dsum}, {w.dlog});
/* Sharded, the top-R runs over THIS RANK'S plane and reports GLOBAL ids, and it also writes
* the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
* replicated: an optional parameter present with the value 0 is not the same declaration as
* an absent one. */
/* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair
* plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
* with value 0 is a different declaration from an absent one. */
op_dtopk = dh_shard
? rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
@@ -755,10 +654,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary});
if (dh_shard) {
/* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side --
* `row_topk_merge` reads one row at one row stride. The merge reduces them to the same
* global top-R an unsharded head would have found, exactly, ties included, which is what
* lets the codebooks stay replicated and indexed by global id. */
/* Row-interleaved, so one draft position's pairs from every rank are adjacent for
* `row_topk_merge`, which reduces them to exactly the unsharded global top-R, ties
* included; the replicated codebooks are then indexed by global id. */
op_dgather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * cfg.top_k * 2),
@@ -773,14 +671,12 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_NOWEIGHTS),
{w.dgath}, {w.cand, w.unary});
}
/* THE MARKOV WALK. `dflash_select` with the hidden projection ABSENT is the plain bigram
* `unary + <markov_w1[prev], markov_w2[cand]>`, decoded greedily with the predecessor read
* after the previous step's argmax -- which is the Markov head, and the top of this file
* argues both halves of that claim. Operands are POSITIONAL, so the absent `hp` is still
* passed, as RAD_NONE, at the issue site.
/* The Markov walk: `dflash_select` with `hp` absent is the bigram
* `unary + <markov_w1[prev], markov_w2[cand]>`, decoded greedily (see the file header). The
* absent `hp` is passed as RAD_NONE at the issue site.
*
* `anchor_stride` is `block`, because the operand is the step's own token_ids: a draft pass
* carries `block` ids a sequence and the anchor is the first of them. */
* `anchor_stride` is `block`: the operand is the step's token_ids, `block` per sequence with
* the anchor first. */
op_sel = rw(b, RAD_OP(b, "dflash_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
RAD_INT("top_k", cfg.top_k), RAD_INT("rank", cfg.rank),
@@ -802,16 +698,16 @@ inline void Dspark::context(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.c, T), RAD_NONE, RAD_NONE);
brows(w.c, T), RAD_NONE, w_fc.bref());
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
@@ -830,9 +726,8 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
/* The fused norm at its three sites. Folded, `x` is the delta the previous block left in
* `h.x` and the stream is added into; unfolded (layer 0), `x` IS the stream and there is no
* residual operand -- an absent optional operand is still passed, as RAD_NONE. */
/* The fused norm. Folded, `x` is the previous block's delta in `h.x` and the stream is the
* residual; unfolded (layer 0), `x` is the stream and the residual is RAD_NONE. */
auto issue_norm = [&](rad_op op, bool fold, rad_weight gain, int64_t rows) {
RAD_ISSUE_N(c, op, rows, brows(fold ? w.h.x : w.x, rows),
fold ? brows(w.x, rows) : RAD_NONE, RAD_W(gain),
@@ -847,23 +742,21 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* ---- attention. The norm folds the previous layer's feed-forward delta into the stream
* and quantises, all in one launch; at layer 0 there is no delta and it norms the
* embedding itself. */
/* ---- attention. The norm folds the previous feed-forward delta into the stream and
* quantises; at layer 0 it norms the embedding. */
issue_norm(op_anorm[i], i != 0, w_anorm[i], T);
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
/* THE NOISE ROWS GO INTO THE CACHE, past this sequence's `seqused`, and the next context
* pass overwrites them from the trunk's real hidden states. That is the reference's
* `crop(start)` and it is why nothing here has to undo anything. */
/* Noise rows go into the cache past `seqused`; the next context pass overwrites them,
* which is the reference's `crop(start)`. */
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
@@ -875,7 +768,7 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
brows(w.attn.x, T));
RAD_ISSUE_N(c, op_qat, T, brows(w.attn.x, T), brows(w.attn.q, T), brows(w.attn.s, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.attn.q, T), brows(w.attn.s, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, w_o[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
/* ---- the feed-forward, behind the same fused norm-add-quantise */
@@ -887,37 +780,34 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
} else {
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
RAD_NONE);
w_gu[i].bref());
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn.x, T));
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn.x, T), brows(w.ffn.q, T), brows(w.ffn.s, T));
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffn.q, T), brows(w.ffn.s, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, w_dn[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
}
/* The last layer's delta folds into the FINAL norm rather than into a norm of its own. */
/* The last layer's delta folds into the final norm. */
issue_norm(op_outnorm, true, w_norm, T);
/* The rows that predict something, which here is all of them. The scheduler names them
* through out_ids, the same field the trunk's own logits gather reads. */
/* The predicting rows (all of them), named by the scheduler through out_ids. */
const int64_t S = batch->n_out;
if (S <= 0) return;
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h.x), praw(batch->out_ids, RAD_I32, S),
brows(w.sel_h, S));
/* `dsum` is quant_act_i8's GROUP-major plane, [n_embd/group][ceil(M/16)*16], so it is passed
* whole: there is no row slice of it that means anything. */
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
* whole. */
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S),
RAD_B(w.dsum));
/* The trailing operand is mxfp4's optional reference and is absent here; an absent optional
* operand is a null tensor in a FULL-LENGTH list, not a shorter list. */
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
* so an absent optional one is RAD_NONE, not a shorter list. */
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
brows(w.dlog, S), RAD_B(w.dsum), RAD_NONE);
if (op_dmerge) {
/* Sharded, this rank's top-R is not the answer -- it is this rank's CANDIDATES, and
* `cand`/`unary` are overwritten by the merge two ops below. Writing them here anyway
* costs nothing and keeps one issue site for both paths. */
/* Sharded, this rank's top-R are only candidates; the merge overwrites `cand`/`unary`. */
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
brows(w.dpair, S));
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
@@ -926,7 +816,7 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
RAD_NONE);
}
/* RAD_NONE in the third slot is the ABSENT hidden projection -- the bigram form. */
/* RAD_NONE in the third slot is the absent hidden projection: the bigram form. */
RAD_ISSUE_N(c, op_sel, batch->n_seq, brows(w.cand, S), brows(w.unary, S), RAD_NONE,
praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2),
brows(w.tokens, batch->n_seq));
+958
View File
@@ -0,0 +1,958 @@
/* rad_block_dspark_bf16.h -- the DSpark drafter over bf16 weights, at the widths a Spark layer
* uses: a few plain attention layers that denoise a whole block of masked positions in one pass,
* conditioned on the trunk's residual stream at a handful of layers, with a rank-N Markov head
* over the target's own output table.
*
* ============================== WHY A SECOND DSPARK BLOCK ==============================
*
* rad_block_dspark.h is the same drafter shape for a block-fp8 release: its linears are DenseFP8
* behind `quant_act_fp8`, its feed-forward is `silu_mul`, its norms carry q/k gains, and its draft
* head is a 2-bit copy of the target's. The published Spark drafts (`dflash` GGUFs, and the HF
* Spark drafter releases behind them) ship the other way: bf16 linears, no q/k norms, one sigmoid
* gate a head on the attention output, exact-erf GELU, one RMS gain per tap, and a sliding window.
* Those are different ops, not different parameters, so this block declares its own graph and
* uses an explicit anchor-window attention op and a full-vocabulary Markov selector so neither
* semantic distinction is silently folded into the generic per-row window or candidate-lattice ops.
*
* Nothing here is quantised. The drafter is 624M parameters read whole a draft pass, so bf16 costs
* 1.2 GiB of residency and one extra weight pass a step; quantising it is a separate measurement
* (it can only move acceptance, since every draft is verified by the target).
*
* ============================== THE FORWARD PASS ==============================
*
* The reference is llama.cpp's `llama_model_dflash::graph<false>` (XHToken/llama.cpp
* 22c0ae1871b, the branch the Spark draft cards name), which mirrors the HF export:
*
* tap(l) = rmsnorm(residual after trunk layer l) * fc_norm[l] one gain row per tap
* ctx = rmsnorm(fc(concat_l tap(l))) hidden_norm
* per draft layer (x5):
* h_n = input_layernorm(h)
* q,k,v = q_proj/k_proj/v_proj(h_n); k_ctx, v_ctx = k_proj/v_proj(ctx)
* rope(q, k); attention over [the layer's context K/V, this block] non-causally,
* inside a `window` positions
* h += o_proj(sigmoid(g_proj(h)) * attn) one gate a head, no q/k norms
* h += mlp(post_attention_layernorm(h)) gelu(gate) * up, then down
* logits = target.lm_head(output_norm(h)) + markov_w2 @ markov_w1[prev]
*
* The two projections of `ctx` are the drafter's own k_proj and v_proj, one pair per layer, and
* they run over every committed token; the drafter's layers never see the context rows. That is
* the context pass below, and the block above is the query pass -- the same split
* rad_block_dspark.h makes, and the same `RAD_DRAFT_BLOCK` drive.
*
* ============================== THE TAPS ARE NORMED, NOT JUST READ ==================
*
* `fc_norm` is [n_taps, n_embd]: the residual entering each tap layer is normed with its own gain
* before the concatenation, so `fc` sees n_taps unit-scaled streams instead of one sum whose
* magnitudes the trunk happens to have. One `rmsnorm` per tap over that tap's column slice of the
* tap buffer, into the same slice layout of a normed copy; `fc` then reads one contiguous
* [n_taps * n_embd] row.
*
* ============================== THE SHARED ANCHOR WINDOW ==========================
*
* The pinned llama.cpp oracle increments the configured history from 512 to 513 and repeats the
* anchor row's mask for every row in the denoising block. `attn_paged_anchor_window` implements
* that exact predicate: every row sees keys through the end of the staged context whose absolute
* position is less than 513 behind the anchor. The query row does not move the lower cutoff. The
* same 513-token width is passed to the KV group and scheduler, so rollback, cache recycling and
* block staging all retain the exact history the drafter reads.
*
* ============================== ROW ALIGNMENT ==============================
*
* Every row predicts, the anchor included (`dflash.sample_from_anchor`, which the GGUF import
* refuses when false): row j of [anchor, MASK x (block-1)] proposes the token at the anchor's
* position plus j + 1, so `steps()` is `block` and the head runs over all the block's rows. The
* core stages the block against `RadDrafterDecl::block` and runs the head over the last `depth`
* rows, which covers this and Dflash2's shift-by-one convention (abi/rad_builder.h).
*
* ============================== THE MARKOV HEAD ==============================
*
* The draft logits get a learned bigram bias
*
* score[l, token] = logits[l, token] + markov_w2[token] . markov_w1[prev(l)]
* prev(0) = the anchor; prev(l) = the greedy token chosen at l - 1
*
* `dflash_markov_greedy` scans the full vocabulary at every position and greedily chooses the
* largest biased score, following the structure of the pinned reference's serial Markov walk.
* Base logits are F32; reduction order and tie behavior can still differ from the reference. It
* does not prune to the base head's top K, use a joint-path heap, or apply confidence to logits.
*
* The confidence head (`conf_proj`, one sigmoid a position predicting acceptance) is imported and
* ignored: it exists to let a serving loop cut the block short, this engine's depth is fixed at
* declare, and it changes nothing the drafter proposes.
*
* ============================== PRECISION ==============================
*
* bf16 for every weight and activation except the residual stream, which is f32 exactly as the
* Spark trunk keeps it (rad_block_dspark.h's fp8 graphs fold the residual into the norm; here the
* norms read the f32 stream and write bf16, and `add` keeps the sum in f32). The reference runs
* bf16 weights against an f32 residual, so rounding the drafter's stream to bf16 would be a third
* opinion on every layer's output for no saved bytes worth having at `block` rows.
*
* ============================== NOT DONE ==============================
*
* The head and full-vocabulary Markov scan are read replicated, so a vocab-sharded deployment
* cannot draft with them. The plugin refuses `world > 1` rather than scoring only one rank's
* slice of the vocabulary.
*
* The drafter's linears are four GEMMs and one attention a layer with no folding: the norms are
* plain `rmsnorm`, not a fused norm-add-quantise, because nothing here quantises. At seven rows
* a pass the launches, not the bytes, are the cost.
*/
#ifndef RAD_BLOCK_DSPARK_BF16_H
#define RAD_BLOCK_DSPARK_BF16_H
#include "rad_arch.h"
namespace rad {
namespace arch {
/* The builder refuses a declaration it cannot serve and says why in its own words; this names which
* handle did not come back, so that message reads against a line of this file. An op that resolves
* to no kernel is recorded and handed back null -- it is only an error if the block issues it -- so
* without this a missing kernel surfaces as a bare "invalid argument" at startup. */
#define DS_REFUSED(...) ::rad::arch::drafter_refused({ __VA_ARGS__ })
inline int drafter_refused(std::initializer_list<const char*> what) {
std::string list;
for (const char* w : what) { if (!list.empty()) list += ", "; list += w; }
std::fprintf(stderr, "DSpark drafter: the builder gave no handle for %s\n", list.c_str());
return RAD_E_INVAL;
}
struct DsparkBF16 {
enum { MAX_LAYERS = 8 };
/* The drafter's config beyond its geometry. Everything here comes from the container's
* `draft.` keys; nothing is defaulted quietly, because a silently ignored gate or window only
* moves acceptance, which is the one number the user cannot see. */
struct Config {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* noise rows a sequence, and drafts (one per row) */
int64_t rank = 0; /* markov_rank: the codebooks' width */
int64_t window = 0; /* reference's anchor-aligned n_swa (configured history + 1) */
int64_t rot = 0; /* rotary dimensions a head; 0 for all of head_dim */
int causal = 0;
int tap_norm = 0; /* `fc_norm`: one RMS gain a tap before the concatenation */
int qk_norm = 0; /* per-head q/k gains, and no output gate */
int gate = 0; /* one sigmoid gate a head on the attention output */
const char* act = "gelu"; /* the feed-forward's activation */
int64_t steps() const { return block; } /* every row predicts */
};
struct Wire {
/* ---- the context pass, one row per committed token */
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
rad_buf srcn = 0; /* [max_tok, n_taps * n_embd] each tap normed, same layout */
rad_buf c = 0, cn = 0; /* [max_tok, n_embd] fc output and separately normed context */
rad_buf ck = 0, ckn = 0; /* [max_tok, kv_dim] projected and optionally normed K */
rad_buf cv = 0; /* [max_tok, kv_dim] and its V */
/* ---- the query pass, `block` rows per sequence */
rad_buf x = 0; /* [qrows, n_embd] f32 the drafter's residual stream */
rad_buf delta = 0; /* [qrows, n_embd] f32 the block a projection just wrote */
rad_buf h = 0; /* [qrows, n_embd] bf16 the normed stream, and every linear's output */
rad_buf q = 0, k = 0, v = 0, qn = 0, kn = 0;
rad_buf gate = 0, gaten = 0; /* [qrows, n_head] projection and sigmoid */
rad_buf attn = 0, attng = 0; /* [qrows, q_dim] attention and gated attention */
rad_buf gate_up = 0; rad_buf ff = 0;
/* ---- the head and the walk, one row per draft position */
rad_buf dlog = 0; /* [srows, n_vocab] f32 full-vocabulary draft logits */
rad_buf best_score = 0; /* [max_seqs, ceil(n_vocab/64)] f32 partial argmax scores */
rad_buf best_token = 0; /* [max_seqs, ceil(n_vocab/64)] i32 partial argmax ids */
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
};
Geom g{}; /* the drafter's geometry, not the trunk's */
Config cfg{};
Wire w{};
int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */
int64_t qrows = 0, crows = 0, srows = 0;
rad_kvgroup kv = 0;
/* ---- model-scope weights */
rad_weight w_fc = 0, w_hnorm = 0, w_norm = 0;
rad_weight w_fcnorm[MAX_LAYERS] = {}; /* one row of `fc_norm` a tap */
rad_weight w_mk1 = 0, w_mk2 = 0; /* markov_w1 (pred), markov_w2 (succ) */
rad_weight w_tok = 0; /* the target's embedding table */
rad_weight w_head = 0; /* the target's output table */
/* ---- per-layer weights */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
rad_weight w_q[MAX_LAYERS] = {}, w_k[MAX_LAYERS] = {}, w_v[MAX_LAYERS] = {}, w_o[MAX_LAYERS] = {};
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}, w_gate[MAX_LAYERS] = {};
rad_weight w_gu[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
/* ---- the context pass */
rad_op op_tapn[MAX_LAYERS] = {}; /* one per tap, not per layer */
rad_op op_cfc = 0, op_cnorm = 0;
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
rad_op op_crope = 0, op_cstore = 0;
/* ---- the query pass. The weightless ops are declared once and issued per layer; the ones
* with weights are per layer, since a weight's prefetch interval and residency class come
* from the op that declares it. */
rad_op op_embed = 0, op_widen = 0, op_add = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}, op_gp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {}, op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_widen2 = 0, op_widen3 = 0;
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
rad_op op_sig = 0, op_gate_heads = 0, op_act = 0;
/* ---- the head and the walk */
rad_op op_dlogits = 0, op_markov = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck, const char* ck_head,
const Wire& wire);
/* The context pass, one row per committed token. */
void context(RadCtx* c, const RadBatch* batch) const;
/* The query pass, the head and the Markov walk, `block` rows per sequence. */
void step(RadCtx* c, const RadBatch* batch) const;
private:
int64_t q_dim() const { return g.n_head * g.head_dim; }
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
};
/* ------------------------------------------------------------------------------ declare */
inline int DsparkBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
int base_layer, rad_kvgroup group, rad_weight tok_embd,
const char* ck, const char* ck_head, const Wire& wire) {
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
if (!ck || !ck_head || !w_tok) return DS_REFUSED("ck", "ck_head", "w_tok");
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: the bf16 DSpark drafter has %lld layers; this block carries at "
"most %d\n", (long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.n_taps <= 0 || cfg.n_taps > MAX_LAYERS || cfg.block < 2 || cfg.rank <= 0)
return RAD_E_INVAL;
if (cfg.qk_norm && cfg.gate) {
fprintf(stderr, "radiance: the drafter declares both per-head q/k norms and a per-head "
"output gate; no published drafter ships both, and this block would have "
"to guess which one the checkpoint trained with\n");
return RAD_E_UNSUPPORTED;
}
/* The full-vocabulary head and Markov scan are read replicated; partial-vocabulary drafting
* would need an exact distributed argmax and replicated codebook access. */
if (g.world > 1) {
fprintf(stderr, "radiance: the bf16 DSpark drafter reads the target's whole output table "
"and cannot draft at tp %d; run it at tp 1\n", g.world);
return RAD_E_UNSUPPORTED;
}
const int64_t qd = q_dim(), kvd = kv_dim(), E = g.n_embd;
crows = g.max_tok;
qrows = g.max_seqs * cfg.block;
if (qrows > g.max_tok) qrows = g.max_tok;
srows = g.max_seqs * cfg.steps(); /* every row predicts */
if (qrows <= 0 || srows <= 0 || cfg.rot < 0 || cfg.rot > g.head_dim || cfg.rot % 2)
return RAD_E_INVAL;
const int64_t rot = cfg.rot ? cfg.rot : g.head_dim;
/* One op declaration per kernel shape, shared by the layers: `rmsnorm`'s and `gemm_nt`'s
* parameters are geometry, and only the weights differ per layer. */
auto gemm = [&](int64_t rows, int64_t n, int64_t k, rad_weight wt, rad_buf x, rad_buf y) {
return rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n),
RAD_INT("K", k), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(wt)),
{x}, {y});
};
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.fc.weight"), nm.ckpt("%s.fc.weight", ck)));
w_fc = decl_w(b, nm.f("dspark.fc.weight"), RAD_BF16, {E, cfg.n_taps * E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
nm.ckpt("%s.hidden_norm.weight", ck)));
w_hnorm = decl_w(b, nm.f("dspark.hidden_norm.weight"), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_fc || !w_hnorm || !w_norm) return DS_REFUSED("w_fc", "w_hnorm", "w_norm");
/* `fc_norm` is [n_taps, n_embd]: one gain row a tap, read as that tap's slice. */
if (cfg.tap_norm) {
const char* src = nm.ckpt("%s.fc_norm.weight", ck);
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
RAD_ARCH_TRY(map_rows(b, nm.f("dspark.fc_norm.%d.weight", i),
{ { src, (int)t, 1 } }));
w_fcnorm[i] = decl_w(b, nm.f("dspark.fc_norm.%d.weight", i), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_fcnorm[i]) return DS_REFUSED("w_fcnorm[i]");
}
}
/* The Markov codebooks, bf16, replicated over the whole vocabulary: both are [vocab, rank], so
* `w2 @ w1[prev]` is `<w1[prev], w2[token]>`. RAD_ACCESS_VOCAB: each walk position reads one
* predecessor row and scans every successor row. */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"),
nm.ckpt("%s.markov_head.markov_w1.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
nm.ckpt("%s.markov_head.markov_w2.weight", ck)));
w_mk1 = decl_w(b, nm.f("dspark.markov_w1"), RAD_BF16, {g.n_vocab_all, cfg.rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
if (!w_mk1 || !w_mk2) return DS_REFUSED("w_mk1", "w_mk2");
/* The target's output table under the drafter's own name: one stored tensor, two arch weights,
* as rad_block_dspark.h does for its 2-bit copy. bf16 and replicated here, since the drafter
* reads it as the head its full-vocabulary walk scores (see NOT DONE for sharding). */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.head.weight"), ck_head));
w_head = decl_w(b, nm.f("dspark.head.weight"), RAD_BF16, {g.n_vocab_all, E},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
if (!w_head) return DS_REFUSED("w_head");
/* ---------------------------------------------------------------- per-layer weights
*
* One name map and one declaration a weight, spelled out: the list is the readable form of
* which checkpoint tensor feeds which matmul, and a drafter has few enough of them that a
* table would only hide it. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const RadWeightGroup grp = grp_layer(first_layer + i);
/* A norm gain: f32, read whole, never sharded. */
auto norm_w = [&](rad_weight* out, const char* suffix, const char* from,
std::initializer_list<int64_t> shape) -> int {
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
RAD_ARCH_TRY(map_copy(b, name, nm.ckpt("%s.layers.%d.%s", ck, i, from)));
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
return *out ? RAD_OK : RAD_E_INVAL;
};
/* A linear: bf16. More than one source is a concatenation, whose row parts say where each
* piece begins (RadWeightDecl::row_parts), so `act_mul` can read [gate | up] as one
* weight. */
auto lin_w = [&](rad_weight* out, const char* suffix,
std::initializer_list<const char*> srcs,
std::initializer_list<int64_t> shape,
std::initializer_list<int64_t> parts = {}) -> int {
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
if (srcs.size() > 1) RAD_ARCH_TRY(map_concat(b, name, srcs));
else RAD_ARCH_TRY(map_copy(b, name, *srcs.begin()));
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp, 0,
parts);
return *out ? RAD_OK : RAD_E_INVAL;
};
#define SRC(path) nm.ckpt("%s.layers.%d." path, ck, i)
RAD_ARCH_TRY(norm_w(&w_anorm[i], "attn_norm.weight", "input_layernorm.weight", {E}));
RAD_ARCH_TRY(norm_w(&w_fnorm[i], "ffn_norm.weight", "post_attention_layernorm.weight", {E}));
RAD_ARCH_TRY(lin_w(&w_q[i], "attn_q", { SRC("self_attn.q_proj.weight") }, {qd, E}));
RAD_ARCH_TRY(lin_w(&w_k[i], "attn_k", { SRC("self_attn.k_proj.weight") }, {kvd, E}));
RAD_ARCH_TRY(lin_w(&w_v[i], "attn_v", { SRC("self_attn.v_proj.weight") }, {kvd, E}));
RAD_ARCH_TRY(lin_w(&w_o[i], "attn_output", { SRC("self_attn.o_proj.weight") }, {E, qd}));
RAD_ARCH_TRY(lin_w(&w_gu[i], "ffn_gate_up",
{ SRC("mlp.gate_proj.weight"), SRC("mlp.up_proj.weight") },
{2 * g.n_ff, E}, { g.n_ff, g.n_ff }));
RAD_ARCH_TRY(lin_w(&w_dn[i], "ffn_down", { SRC("mlp.down_proj.weight") },
{E, g.n_ff}));
if (cfg.gate)
RAD_ARCH_TRY(lin_w(&w_gate[i], "attn_gate", { SRC("self_attn.g_proj.weight") },
{g.n_head, E}));
if (cfg.qk_norm) {
RAD_ARCH_TRY(norm_w(&w_qn[i], "attn_q_norm.weight", "self_attn.q_norm.weight",
{g.head_dim}));
RAD_ARCH_TRY(norm_w(&w_kn[i], "attn_k_norm.weight", "self_attn.k_norm.weight",
{g.head_dim}));
}
#undef SRC
}
/* Non-causal: every query row sees its whole block and the context the trunk committed
* (`causal` comes from `draft.is_causal`). Declared before both kv_stores, which read the
* resolved `block_size` back with rad_kv_block_size(); before it, that returns zero. */
op_attn = rw(b, RAD_OP(b, cfg.window > 0 ? "attn_paged_anchor_window" : "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.qn : w.q}, {w.attn});
if (!op_attn) return DS_REFUSED("op_attn");
/* ---------------------------------------------------------------- the context pass
*
* One row per committed token, run once per trunk step: the taps become the drafter's own K
* and V. Nothing here is per query row, so its cost follows the trunk's token count, not the
* block's. */
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
op_tapn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_fcnorm[i])),
{w.src}, {w.srcn});
if (!op_tapn[i]) return DS_REFUSED("op_tapn[i]");
}
op_cfc = gemm(crows, E, cfg.n_taps * E, w_fc, w.srcn, w.c);
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.cn});
if (!op_cfc || !op_cnorm) return DS_REFUSED("op_cfc", "op_cnorm");
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
* and residency class. */
op_ck[i] = gemm(crows, kvd, E, w_k[i], w.cn, w.ck);
op_cv[i] = gemm(crows, kvd, E, w_v[i], w.cn, w.cv);
if (!op_ck[i] || !op_cv[i]) return DS_REFUSED("op_ck[i]", "op_cv[i]");
if (cfg.qk_norm) {
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_kn[i])),
{w.ck}, {w.ckn});
if (!op_cknorm[i]) return DS_REFUSED("op_cknorm[i]");
}
}
/* K-only rope: `rope` rotates the first n_head + n_head_kv heads, so a K-only tensor is
* n_head = n_head_kv, n_head_kv = 0. Weightless, so one op serves every layer. Each context
* row is rotated by its own absolute position, as the reference's single concatenated rope
* does. */
op_crope = rw(b, decl_rope(b, g, crows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
{cfg.qk_norm ? w.ckn : w.ck}, {cfg.qk_norm ? w.ckn : w.ck});
op_cstore = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.ckn : w.ck, w.cv}, {});
if (!op_crope || !op_cstore) return DS_REFUSED("op_crope", "op_cstore");
/* ---------------------------------------------------------------- the query pass
*
* `block` rows per sequence, through the drafter's layers. The residual stream is f32 and the
* linears read bf16, exactly as the trunk keeps them: `rmsnorm` reads the stream and writes the
* activations, `cast` widens a projection's output, and `add` keeps the sum in f32. */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{}, {w.h});
op_widen = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{w.h}, {w.x});
/* One widen and one add serve both residual sites a layer: same shapes, same buffers. */
op_widen2 = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{w.h}, {w.delta});
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{w.x, w.delta}, {w.x});
if (!op_embed || !op_widen || !op_widen2 || !op_add)
return DS_REFUSED("op_embed", "op_widen", "op_widen2", "op_add");
/* Invariant: the norms are declared where step() issues them. Declaration order is the buffer
* planner's liveness (core/build/rad_bufplan.cpp), and the stream `x` lives over the ops that
* touch it: each layer's two norms in the loop, the final one after everything the layers
* issue. Declared up front, the stream's lifetime would end before the layers and the planner
* could overlay a feed-forward temporary on it. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_anorm[i])),
{w.x}, {w.h});
op_qp[i] = gemm(qrows, qd, E, w_q[i], w.h, w.q);
op_kp[i] = gemm(qrows, kvd, E, w_k[i], w.h, w.k);
op_vp[i] = gemm(qrows, kvd, E, w_v[i], w.h, w.v);
op_op[i] = gemm(qrows, E, qd, w_o[i], cfg.gate ? w.attng : w.attn, w.h);
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_fnorm[i])),
{w.x}, {w.h});
op_gu[i] = gemm(qrows, 2 * g.n_ff, E, w_gu[i], w.h, w.gate_up);
op_dn[i] = gemm(qrows, E, g.n_ff, w_dn[i], w.ff, w.h);
if (!op_anorm[i] || !op_qp[i] || !op_kp[i] || !op_vp[i] || !op_op[i] || !op_fnorm[i] ||
!op_gu[i] || !op_dn[i])
return RAD_E_INVAL;
if (cfg.qk_norm) {
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_qn[i])),
{w.q}, {w.qn});
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.kn});
if (!op_qn[i] || !op_kn[i]) return DS_REFUSED("op_qn[i]", "op_kn[i]");
}
if (cfg.gate) {
op_gp[i] = gemm(qrows, g.n_head, E, w_gate[i], w.h, w.gate);
if (!op_gp[i]) return DS_REFUSED("op_gp[i]");
}
}
op_qrope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head, 0, rot, "neox"),
{cfg.qk_norm ? w.qn : w.q}, {cfg.qk_norm ? w.qn : w.q});
op_krope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
{cfg.qk_norm ? w.kn : w.k}, {cfg.qk_norm ? w.kn : w.k});
op_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.kn : w.k, w.v}, {});
/* The gate the trunk uses too: one sigmoid a head, then one scale a head's whole row. */
if (cfg.gate) {
op_sig = rw(b, RAD_OP(b, "sigmoid",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_head),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.gate}, {w.gaten});
op_gate_heads = rw(b, RAD_OP(b, "scale_rows",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
RAD_INT("n", g.head_dim), RAD_STR("act", "none"),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.attn, w.gaten}, {w.attng});
if (!op_sig || !op_gate_heads) return DS_REFUSED("op_sig", "op_gate_heads");
}
/* `act_mul` with the activation the drafter was trained with: exact-erf gelu for the Spark
* drafts (`hidden_activation: gelu`), silu for a Qwen3-shaped one. `gelu_mul` is the tanh
* approximation and is not what the reference runs. */
op_act = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("act", cfg.act), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ff});
op_outnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
if (!op_qrope || !op_krope || !op_store || !op_act || !op_outnorm)
return DS_REFUSED("op_qrope", "op_krope", "op_store", "op_act", "op_outnorm");
/* ---------------------------------------------------------------- the head and full-vocabulary walk
*
* Every row predicts, so the head scores all `steps` rows, anchor included. The row order is
* sequence-major, which is the selector's [sequence, position, vocabulary] contract. The
* greedy Markov op scans all vocabulary entries at every position and feeds each winning id
* into the next position's bigram bias.
*/
op_dlogits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_head)),
{w.h}, {w.dlog});
op_markov = rw(b, RAD_OP(b, "dflash_markov_greedy_f32",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
RAD_INT("steps", cfg.steps()), RAD_INT("rank", cfg.rank),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", cfg.block),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_mk1, w_mk2)),
{w.dlog}, {w.best_score, w.best_token, w.tokens});
if (!op_dlogits || !op_markov) return DS_REFUSED("op_dlogits", "op_markov");
return RAD_OK;
}
/* ------------------------------------------------------------------------------ the context pass */
inline void DsparkBF16::context(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int64_t E = g.n_embd;
/* Each tap's slice of the residual the trunk just tapped, normed with its own gain into the
* same slice layout of one row-per-token buffer. */
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
if (!cfg.tap_norm) continue;
RAD_ISSUE_N(c, op_tapn[i], T, bcol(w.src, t * E, E, T), RAD_W(w_fcnorm[i]),
bcol(w.srcn, t * E, E, T));
}
RAD_ISSUE_N(c, op_cfc, T, cfg.tap_norm ? brows(w.srcn, T) : brows(w.src, T), RAD_W(w_fc),
brows(w.c, T));
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.cn, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cn, T), RAD_W(w_k[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cn, T), RAD_W(w_v[i]), brows(w.cv, T));
if (cfg.qk_norm)
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
brows(w.ckn, T));
RAD_ISSUE_N(c, op_crope, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_cstore, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), brows(w.cv, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
}
}
/* ------------------------------------------------------------------------------ the query pass */
inline void DsparkBF16::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
/* The block the core staged: the token the sampler just chose, then the mask token in every
* unfilled slot. */
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.h, T));
RAD_ISSUE_N(c, op_widen, T, brows(w.h, T), brows(w.x, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h, T), RAD_W(w_q[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h, T), RAD_W(w_k[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h, T), RAD_W(w_v[i]), brows(w.v, T));
if (cfg.qk_norm) {
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.qn, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]),
brows(w.kn, T));
}
RAD_ISSUE_N(c, op_qrope, T, brows(cfg.qk_norm ? w.qn : w.q, T), pos);
RAD_ISSUE_N(c, op_krope, T, brows(cfg.qk_norm ? w.kn : w.k, T), pos);
/* The block's own K and V go into the cache past `seqused`, which is how every row of the
* block attends to every other; the next context pass overwrites them, which is the
* reference's `crop(start)`. */
RAD_ISSUE_N(c, op_store, T, brows(cfg.qk_norm ? w.kn : w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
kv_cache(kv, first_layer + i));
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(cfg.qk_norm ? w.qn : w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T));
if (cfg.gate) {
/* One gate a head, applied to that head's whole row of the attention output, before
* o_proj. View [rows, heads * dim] and [rows, heads] as one row a head. */
RAD_ISSUE_N(c, op_gp[i], T, brows(w.h, T), RAD_W(w_gate[i]), brows(w.gate, T));
RAD_ISSUE_N(c, op_sig, T, brows(w.gate, T), brows(w.gaten, T));
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, w.attn), RAD_BF16, T * g.n_head,
g.head_dim);
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, w.gaten), RAD_BF16, T * g.n_head, 1);
const RadOperand gated = RAD_P_T2(rad_buf_ptr(c, w.attng), RAD_BF16, T * g.n_head,
g.head_dim);
RAD_ISSUE_N(c, op_gate_heads, T * g.n_head, heads, gates, RAD_NONE, gated);
}
RAD_ISSUE_N(c, op_op[i], T, brows(cfg.gate ? w.attng : w.attn, T), RAD_W(w_o[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h, T), RAD_W(w_gu[i]), brows(w.gate_up, T));
RAD_ISSUE_N(c, op_act, T, bcol(w.gate_up, 0, g.n_ff, T),
bcol(w.gate_up, g.n_ff, g.n_ff, T), brows(w.ff, T));
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ff, T), RAD_W(w_dn[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
}
RAD_ISSUE_N(c, op_outnorm, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
/* The predicting rows, named by the scheduler through `out_ids`. */
const int64_t S = batch->n_out;
if (S <= 0) return;
RAD_ISSUE_N(c, op_dlogits, S, brows(w.h, S), RAD_W(w_head), brows(w.dlog, S));
RAD_ISSUE_N(c, op_markov, batch->n_seq, brows(w.dlog, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2),
brows(w.best_score, batch->n_seq), brows(w.best_token, batch->n_seq),
brows(w.tokens, batch->n_seq));
}
/* ================================================================== the trunk's side of it
*
* The taps, and one call a target plugin makes to put a drafter on. Both live here because both
* are the drafter's contract with the trunk: which residual streams it reads, where its blocks
* live, and how deep a proposal it makes. */
/* The residual streams a drafter reads, captured as the trunk passes them. */
struct DsparkTaps {
enum { MAX_TAPS = DsparkBF16::MAX_LAYERS };
int n = 0;
int layer[MAX_TAPS] = {}; /* the trunk layer whose OUTPUT is tapped */
rad_buf src = 0; /* [rows, n * n_embd] f32, one column slice a tap */
rad_op op = 0; /* the residual stream, copied into that slice */
/* Read `draft.target_layer_ids`, which names the layers whose output is tapped. Zero taps when
* the container carries no drafter, or one that reads no trunk stream. Out-of-range ids are
* dropped, not clamped: a drafter naming a layer this model lacks belongs to another target. */
int read(const RadModelMeta* meta, int64_t n_layer) {
n = 0;
const char* ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
if (!ids) ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
if (!ids) ids = rad_meta_gets(meta, "draft.gguf_target_layers", nullptr);
n = parse_layer_ids(ids, n_layer, layer, MAX_TAPS);
return n;
}
/* The copy that saves a tap. A drafter reads the trunk's own residual stream, which is f32
* here and stays f32: the widening the fp8 graphs do is theirs, not this one's. */
int declare(RadBuilder* b, Names& nm, const Geom& g, int64_t rows, rad_buf residual) {
if (n <= 0) return RAD_OK;
src = decl_b(b, nm.f("draft_src"), RAD_F32, {rows, (int64_t)n * g.n_embd});
if (!src) return DS_REFUSED("src");
/* Declared over the trunk's own residual buffer: the op's operand pair is the stream and a
* tap's slice, and every issue site passes the slice it is writing. */
op = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_STR("from", "f32"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{residual}, {src});
return op ? RAD_OK : RAD_E_INVAL;
}
/* The tap that follows trunk layer `l`, if any. Issued on prefill and decode alike: the
* drafter conditions on every committed token's residual stream. */
void step(RadCtx* c, rad_buf residual, int64_t rows, int64_t l, int64_t n_embd) const {
if (!op) return;
for (int t = 0; t < n; ++t)
if (layer[t] == l)
RAD_ISSUE(c, op, brows(residual, rows),
bcol(src, (int64_t)t * n_embd, n_embd, rows));
}
};
/* Put a DSpark drafter on a trunk: its config from the container's `draft.` keys, its own KV
* group, its graph, and the drafter declaration the core drives. `base_layer` is the absolute
* layer its first block takes, one past the trunk's last.
*
* Nothing is defaulted quietly. A `draft.` key that describes a drafter this file does not
* implement is refused by name, because a silently ignored gate, window or block length only moves
* acceptance -- the one number a user cannot see in the output.
*
* The plugin calls it last, after its own head and logits: a drafter's passes run after the whole
* trunk, and the buffer planner lays an op's lifetimes out in declaration order, so declaring it
* earlier would let a trunk temporary land on the stream the drafter is still reading. */
inline int declare_dspark(DsparkBF16* ds, DsparkBF16::Wire* w, rad_kvgroup* kv, RadBuilder* b,
Names& nm, const RadModelMeta* meta, const RadBuildCtx* ctx,
const Geom& target, const DsparkTaps& taps, int base_layer,
rad_weight tok_embd, const char* ck_head) {
Geom dg{};
RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DSpark"));
/* The width the drafter concatenates and projects is the trunk's, and `drafter_geom` keeps the
* target's -- so a draft that disagrees is a draft for another model, and its `fc` would be
* read at a shape it was not trained at. */
const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size",
rad_meta_geti(meta, "draft.dflash_config.hidden_size",
dg.n_embd));
if (want_embd != dg.n_embd) {
fprintf(stderr, "radiance: the drafter reads a %lld-wide trunk and this target is %lld "
"wide; they are not the same model\n", (long long)want_embd,
(long long)dg.n_embd);
return RAD_E_UNSUPPORTED;
}
DsparkBF16::Config c{};
c.n_taps = taps.n;
c.rank = rad_meta_geti(meta, "draft.markov_rank", 0);
c.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0;
c.tap_norm = rad_meta_geti(meta, "draft.fc_norm", 0) ? 1 : 0;
c.qk_norm = rad_meta_geti(meta, "draft.qk_norm", 0) ? 1 : 0;
c.gate = rad_meta_geti(meta, "draft.headwise_attn_output_gate", 0) ? 1 : 0;
const char* act = rad_meta_gets(meta, "draft.hidden_act", "silu");
c.act = (!std::strcmp(act, "gelu") || !std::strcmp(act, "none")) ? "gelu"
: (!std::strcmp(act, "silu")) ? "silu" : nullptr;
if (!c.act) {
fprintf(stderr, "radiance: the drafter's feed-forward is '%s'; this block runs exact-erf "
"gelu (what the Spark drafts train with) or silu, and the two are not the "
"same function\n", act);
return RAD_E_UNSUPPORTED;
}
const char* gate_mode = rad_meta_gets(meta, "draft.gate_attn_act_mode", "sigmoid");
if (c.gate && std::strcmp(gate_mode, "sigmoid")) {
fprintf(stderr, "radiance: the drafter gates its attention output with '%s'; this block "
"applies a sigmoid\n", gate_mode);
return RAD_E_UNSUPPORTED;
}
/* Every row predicts, the anchor included. Without it a block row's worth of proposals is
* missing and the head reads rows the drafter never filled. */
if (!rad_meta_geti(meta, "draft.sample_from_anchor", 1)) {
fprintf(stderr, "radiance: the drafter declares sample_from_anchor false, whose bonus "
"anchor slot this block has no rows for\n");
return RAD_E_UNSUPPORTED;
}
/* The reference applies the bigram bias to the full vocabulary before each greedy choice. */
if (c.rank <= 0 || c.rank % 32 || c.rank > 512) {
fprintf(stderr, "radiance: the drafter's Markov head has rank %lld; the walk that applies "
"the bigram bias takes a multiple of 32 up to 512\n", (long long)c.rank);
return RAD_E_UNSUPPORTED;
}
/* The block is both the number of noise rows and the number of drafts: every row, the anchor
* included, predicts the token after it, so the depth is `block_size` rather than the
* `block_size - 1` a DFlash2 container's is. A block-diffusion drafter is trained for one
* block length and has no partial block, so any other depth is refused. */
const int64_t trained = rad_meta_geti(meta, "draft.block_size", 0);
if (trained < 2) {
fprintf(stderr, "radiance: this drafter declares no draft.block_size; the number of masked "
"positions it denoises is not a number this engine may choose.\n");
return RAD_E_FORMAT;
}
if ((long long)ctx->max_spec != trained) {
fprintf(stderr, "radiance: the drafter was trained at block_size %lld, which is %lld draft "
"tokens, and this serve asks for %d. A block-diffusion drafter denoises a "
"fixed number of mask positions; run it at %lld.\n",
(long long)trained, (long long)trained, ctx->max_spec, (long long)trained);
return RAD_E_UNSUPPORTED;
}
c.block = trained;
/* The reference gives every row of the block the anchor's history. `window` is the configured
* number of preceding positions; llama.cpp sets n_swa to window + 1 and masks when
* anchor - key >= n_swa. Keep that exact width in attention, the KV group and scheduler. */
int64_t window = 0;
if (rad_meta_geti(meta, "draft.use_sliding_window", 0))
window = rad_meta_geti(meta, "draft.sliding_window", 0);
if (window < 0 || (window && window < c.block)) {
fprintf(stderr, "radiance: the drafter's %lld-token window does not cover the %lld-token "
"block it denoises\n", (long long)window, (long long)c.block);
return RAD_E_UNSUPPORTED;
}
if (window > 0 && window == INT64_MAX) return RAD_E_INVAL;
c.window = window > 0 ? window + 1 : 0; /* llama.cpp dflash: n_swa += 1 */
const double prf = rad_meta_getf(meta, "draft.partial_rotary_factor",
rad_meta_getf(meta,
"draft.rope_parameters.partial_rotary_factor", 1.0));
const double rot = (double)dg.head_dim * prf;
if (!(prf > 0.0) && prf != 0.0) {
fprintf(stderr, "radiance: the drafter's partial_rotary_factor is %g\n", prf);
return RAD_E_INVAL;
}
if (std::floor(rot) != rot || (int64_t)rot % 2 || rot > (double)dg.head_dim) {
fprintf(stderr, "radiance: the drafter rotates %g of %lld head dimensions\n", rot,
(long long)dg.head_dim);
return RAD_E_INVAL;
}
c.rot = (int64_t)rot ? (int64_t)rot : dg.head_dim;
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, c.window, base_layer, kv));
/* Activations: one row per committed token for the context pass, one row per block position
* for the query pass. Both are small; the drafter's cost is its weights. */
const int64_t qd = dg.n_head * dg.head_dim, kvd = dg.n_head_kv * dg.head_dim;
int64_t qr = dg.max_seqs * c.block;
if (qr > dg.max_tok) qr = dg.max_tok;
const int64_t sr = dg.max_seqs * c.steps();
DsparkBF16::Wire& dw = *w;
dw.src = taps.src;
dw.srcn = decl_b(b, nm.f("ds_srcn"), RAD_BF16, {dg.max_tok, c.n_taps * dg.n_embd});
dw.c = decl_b(b, nm.f("ds_c"), RAD_BF16, {dg.max_tok, dg.n_embd});
dw.cn = decl_b(b, nm.f("ds_cn"), RAD_BF16, {dg.max_tok, dg.n_embd});
dw.ck = decl_b(b, nm.f("ds_ck"), RAD_BF16, {dg.max_tok, kvd});
dw.cv = decl_b(b, nm.f("ds_cv"), RAD_BF16, {dg.max_tok, kvd});
if (c.qk_norm) dw.ckn = decl_b(b, nm.f("ds_ckn"), RAD_BF16, {dg.max_tok, kvd});
dw.x = decl_b(b, nm.f("ds_x"), RAD_F32, {qr, dg.n_embd});
dw.delta = decl_b(b, nm.f("ds_delta"), RAD_F32, {qr, dg.n_embd});
dw.h = decl_b(b, nm.f("ds_h"), RAD_BF16, {qr, dg.n_embd});
dw.q = decl_b(b, nm.f("ds_q"), RAD_BF16, {qr, qd});
dw.k = decl_b(b, nm.f("ds_k"), RAD_BF16, {qr, kvd});
dw.v = decl_b(b, nm.f("ds_v"), RAD_BF16, {qr, kvd});
if (c.qk_norm) {
dw.qn = decl_b(b, nm.f("ds_qn"), RAD_BF16, {qr, qd});
dw.kn = decl_b(b, nm.f("ds_kn"), RAD_BF16, {qr, kvd});
}
dw.gate = decl_b(b, nm.f("ds_gate"), RAD_BF16, {qr, dg.n_head});
dw.attn = decl_b(b, nm.f("ds_attn"), RAD_BF16, {qr, qd});
if (c.gate) {
dw.gaten = decl_b(b, nm.f("ds_gaten"), RAD_BF16, {qr, dg.n_head});
dw.attng = decl_b(b, nm.f("ds_attng"), RAD_BF16, {qr, qd});
}
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), RAD_BF16, {qr, 2 * dg.n_ff});
dw.ff = decl_b(b, nm.f("ds_ff"), RAD_BF16, {qr, dg.n_ff});
dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_F32, {sr, dg.n_vocab});
const int64_t n_markov_tiles = (dg.n_vocab_all + 63) / 64;
dw.best_score = decl_b(b, nm.f("ds_markov_score"), RAD_F32,
{dg.max_seqs, n_markov_tiles});
dw.best_token = decl_b(b, nm.f("ds_markov_token"), RAD_I32,
{dg.max_seqs, n_markov_tiles});
/* The proposal buffer (RadDrafterDecl::proposal): a block pass proposes through the drafter's
* own walk, never through the sampler's token buffer. */
dw.tokens = decl_b(b, nm.f("ds_tokens"), RAD_I32, {dg.max_seqs, c.steps()});
if (!dw.srcn || !dw.c || !dw.cn || !dw.ck || !dw.cv ||
(c.qk_norm && (!dw.ckn || !dw.qn || !dw.kn)) ||
(c.gate && (!dw.gaten || !dw.attng)) || !dw.x || !dw.delta || !dw.h || !dw.q || !dw.k ||
!dw.v || !dw.gate || !dw.attn || !dw.gate_up || !dw.ff || !dw.dlog ||
!dw.best_score || !dw.best_token || !dw.tokens)
return RAD_E_INVAL;
RAD_ARCH_TRY(ds->declare(b, nm, dg, c, base_layer, *kv, tok_embd, "draft", ck_head, dw));
RadDrafterDecl drf{};
drf.name = "dspark";
drf.kind = RAD_DRAFT_BLOCK;
drf.depth = ctx->max_spec;
drf.block = c.block;
drf.proposal = dw.tokens;
drf.proposal_pitch = c.steps();
drf.window = c.window;
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.mask_token_id", -1);
if (drf.mask_token < 0)
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1);
if (drf.mask_token < 0) {
fprintf(stderr, "radiance: this drafter declares no mask_token_id, which every unfilled "
"block position embeds\n");
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
rad_note(b, "DSpark drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
"ffn %lld, %s attention with a %lld-token anchor-aligned window (%lld configured "
"history + 1), %lld of %lld rotary dimensions, %s, %s a head, %d trunk tap(s); one "
"forward over %lld noise row(s), the anchor included, proposes %lld tokens",
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1,
(long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim,
(long long)dg.n_ff, c.causal ? "causal" : "non-causal", (long long)c.window,
(long long)window, (long long)c.rot, (long long)dg.head_dim, c.act,
c.gate ? "sigmoid gate" : "no gate", (int)c.n_taps, (long long)c.block,
(long long)c.steps());
rad_note(b, "the rank-%lld Markov bigram head greedily scans all %lld vocabulary tokens at "
"each draft position; confidence is not applied to logits%s",
(long long)c.rank, (long long)dg.n_vocab_all,
rad_meta_geti(meta, "draft.has_confidence_head", 0)
? " (its reference role is adaptive depth, which this fixed-depth graph does not use)"
: "");
return RAD_OK;
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_DSPARK_BF16_H */
+74 -113
View File
@@ -1,50 +1,42 @@
/* rad_block_gdn.h -- one gated-delta-net (linear attention) block, bf16 operands.
*
* Hybrid models are the normal case, not an extension (spec §7.2): Qwen3.5-27B is 48 GDN layers to
* 16 full-attention ones. This block is the GDN half, and it composes with AttnGatedBF16 and
* MlpBF16 in one plugin exactly as they compose with each other.
* Hybrid models are the normal case (spec §7.2): Qwen3.5-27B has 48 GDN layers to 16
* full-attention ones. This block composes with AttnGatedBF16 and MlpBF16 in one plugin.
*
* rmsnorm -> in gemm ([q|k|v|a|b]) -> z gemm
* prefill: gdn_conv_prep -> gdn_kkt_solve -> gdn_chunk_scan -> gdn_gated_rmsnorm
* decode: gdn_conv_update -> gdn_recurrent_update (which folds the gated norm)
* -> out gemm -> [all_reduce] -> residual add
*
* THE TWO PATHS ARE A BRANCH ON PHASE, WHICH IS NOT THE BRANCH SPEC §2.4 FORBIDS. A quant branch
* makes the graph unreadable because it hides which of two op sequences a model uses; this branch
* picks between two sequences that are both declared, both resolved, both in the graph dump, and
* both run by the same model on different steps. The chunked path amortises across a prefill chunk
* and the recurrent path is O(1) per token; there is no single kernel that is right for both.
* The two paths branch on phase, which spec §10 allows: both sequences are declared, resolved
* and in the graph dump. The chunked path amortises over a prefill chunk, the recurrent path is
* O(1) per token, and no single kernel suits both.
*
* Both paths take `num_accepted`, because a linear-attention kernel pair MUST support speculative
* rollback: the recurrent state and the conv window have already absorbed rejected tokens, and a
* rejection is a change of read offset rather than a recompute (spec §10, OPS.md).
* Both paths take `num_accepted`: the recurrent state and conv window have already absorbed
* rejected draft tokens, and rollback is a change of read offset, not a recompute (spec §10,
* OPS.md).
*
* ============================== TWO CONVENTIONS TO GET RIGHT ==============================
* ============================== TWO CONVENTIONS ==============================
*
* `A_log` IS A LOG AND THE EXPONENT HAS NOT BEEN TAKEN. The decay is
* `A_log` is a log. The decay is
*
* g = -exp(A_log) . softplus(a + dt_bias)
*
* and the kernels -- libr4d's and libref's alike -- take the exponent themselves. The
* safetensors checkpoint stores `linear_attn.A_log` in exactly that form, so this block declares
* the weight as `ssm_a_log` and maps it straight through. THE GGUF CONVERSION DOES NOT: llama.cpp
* writes `ssm_a = -exp(A_log)` at convert time, so a container built from a GGUF must undo that or
* the decay becomes -exp(-exp(A_log)), which is a number near -1 for every head and a model that
* forgets everything in four tokens. The name carries the convention so the mismatch is visible in
* the weight manifest rather than in the perplexity.
* and the kernels (libr4d and libref) take the exponent themselves. Safetensors stores
* `linear_attn.A_log` in that form, so the weight is declared `ssm_a_log` and copied through.
* llama.cpp's GGUF conversion writes `ssm_a = -exp(A_log)` instead, so a container built from a
* GGUF must undo it; otherwise the decay is -exp(-exp(A_log)), near -1 for every head. The name
* makes the convention visible in the weight manifest.
*
* q AND k ARE L2-NORMALISED, NOT RMS-NORMALISED. Different arithmetic -- no division by the head
* width and no gain vector -- and it lives inside gdn_conv_prep (prefill) and
* gdn_recurrent_update (decode) because both kernels already have the head in registers. There is
* no l2_norm op to declare and there should not be one.
* q and k are L2-normalised, not RMS-normalised (no division by the width, no gain), inside
* gdn_conv_prep (prefill) and gdn_recurrent_update (decode), which already hold the head in
* registers. There is no separate l2_norm op.
*
* ============================== THE FUSED IN-PROJECTION ==============================
*
* gdn_conv_prep's `x` is the whole projection row [q | k | v | a | b]: conv_dim convolved channels
* followed by one decay input and one beta input per value head. So the three checkpoint tensors
* in_proj_qkv, in_proj_a and in_proj_b are ONE declared weight and ONE GEMM, which is also one
* movement unit and one launch instead of three. The cost is the ability to place them
* separately, which nothing wants.
* gdn_conv_prep's `x` is the whole row [q | k | v | a | b]: conv_dim convolved channels, then
* one decay input and one beta input per value head. So in_proj_qkv, in_proj_a and in_proj_b are
* one declared weight and one GEMM.
*/
#ifndef RAD_BLOCK_GDN_H
#define RAD_BLOCK_GDN_H
@@ -93,7 +85,7 @@ struct GdnBF16 {
const char* in_b = nullptr; /* linear_attn.in_proj_b.weight */
const char* in_z = nullptr; /* linear_attn.in_proj_z.weight */
const char* conv1d = nullptr; /* linear_attn.conv1d.weight */
const char* a_log = nullptr; /* linear_attn.A_log -- a LOG, see the header comment */
const char* a_log = nullptr; /* linear_attn.A_log, a log (see the header) */
const char* dt_bias = nullptr; /* linear_attn.dt_bias */
const char* out_norm = nullptr; /* linear_attn.norm.weight */
const char* out = nullptr; /* linear_attn.out_proj.weight */
@@ -125,31 +117,22 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
if (cfg.n_head_k <= 0 || cfg.head_k <= 0 || cfg.n_head_v <= 0 || cfg.head_v <= 0 ||
cfg.conv_width <= 0 || cfg.chunk <= 0)
return RAD_E_INVAL;
/* q and k are shared across a group of value heads -- 16 key heads to 48 value heads on this
* model. The kernels take H and Hg separately for exactly that; a value head count that is not
* a multiple of the key head count is a geometry no GDN kernel serves. */
/* q and k are shared across a group of value heads (16 key to 48 value heads on Qwen3.5-27B);
* the kernels take H and Hg separately and need H to be a multiple of Hg. */
if (cfg.n_head_v % cfg.n_head_k != 0) {
fprintf(stderr, "radiance: %lld value heads is not a multiple of %lld key heads\n",
(long long)cfg.n_head_v, (long long)cfg.n_head_k);
return RAD_E_INVAL;
}
/* THE QUERY SCALE, AND IT IS NOT OPTIONAL. `gdn_chunk_scan` and `gdn_recurrent_update` both
* carry a `scale` that multiplies the output -- o = scale * e^g Q S^T + ... -- and it defaults to
* 1. FLA's chunk_gated_delta_rule defaults it to head_k^-0.5 and vllm-radiance passes exactly
* that; llama.cpp's fused GDN does the same.
/* The query scale is required. `gdn_chunk_scan` and `gdn_recurrent_update` multiply the output
* by `scale` (o = scale * e^g Q S^T + ...), which defaults to 1; FLA's chunk_gated_delta_rule,
* vLLM and llama.cpp use head_k^-0.5.
*
* IT LOOKS LIKE IT CANCELS AND IT DOES NOT. The scan's output goes straight into the gated RMS
* norm, and an RMS norm divides a constant factor back out -- so scaling `o` by c should change
* nothing. That argument is wrong here for one reason: the scan output of this model is around
* 1e-6, `mean(o^2)` is then around 1e-12, and the norm's eps is 1e-6. eps DOMINATES the variance,
* the norm degenerates into a fixed division by sqrt(eps), and the factor passes straight through
* to the residual stream.
*
* Leaving it at 1 is visible end to end: the scan output comes out larger than the reference
* implementations' by exactly sqrt(head_k), and with forty-eight of this model's sixty-four
* layers delta net the residual stream then carries a delta-net contribution that many times
* too large -- fluent grammar with no content. */
* The following gated RMS norm does not cancel it: the scan output is around 1e-6, so
* mean(o^2) ~ 1e-12 is dominated by eps = 1e-6 and the norm reduces to a fixed division by
* sqrt(eps). Without the scale every delta-net layer's contribution is sqrt(head_k) too
* large. */
const double q_scale = 1.0 / std::sqrt((double)cfg.head_k);
const int64_t v_dim = cfg.v_dim();
@@ -157,11 +140,10 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
const int64_t in_dim = cfg.in_dim();
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
/* The fusion: q, k, v, a and b in one row, because that is the row
* gdn_conv_prep reads. A row-sharded CONCAT shards each source before concatenating -- and
* `in_proj_qkv` is ITSELF three head groups, so the row split declared below is FIVE parts and
* not three: q, k and v out of the fused source, then a, then b. The maps come ahead of the
* weights they name, since a checkpoint is asked what a weight is through its map. */
/* q, k, v, a and b in one row, as gdn_conv_prep reads it. A row-sharded CONCAT shards each
* source before concatenating, and `in_proj_qkv` is itself three head groups, so the row split
* below has five parts. Maps are declared before the weights, since weight encodings are looked
* up through the map. */
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ssm_in.weight", l),
{ src.in_qkv, src.in_a, src.in_b }, 0));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_z.weight", l), src.in_z));
@@ -178,11 +160,9 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.n_head_v, cfg.n_head_v});
w_z = decl_w(b, nm.f("blk.%d.ssm_z.weight", l), RAD_BF16, {v_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
/* The depthwise convolution is per channel, so it shards with the channels it convolves. The
* checkpoint ships [conv_dim, 1, 4]; the middle extent is the depthwise group and is squeezed
* at convert. There is NO conv bias on this architecture -- Qwen3.5's conv1d has bias=False --
* so none is declared and the operand is passed absent rather than as a zero vector nobody
* loads. */
/* The depthwise convolution shards with its channels. The checkpoint ships [conv_dim, 1, 4];
* the depthwise group extent is squeezed at convert. Qwen3.5's conv1d has bias=False, so the
* bias operand is passed absent. */
w_conv = decl_w(b, nm.f("blk.%d.ssm_conv1d.weight", l), RAD_BF16,
{conv_dim, cfg.conv_width},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
@@ -191,8 +171,7 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
w_dt_bias = decl_w(b, nm.f("blk.%d.ssm_dt.bias", l), RAD_F32, {cfg.n_head_v},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
/* One gain vector over head_v, shared by every head: replicated, like the attention q/k
* gains. */
/* One gain vector over head_v shared by every head, so replicated. */
w_out_norm = decl_w(b, nm.f("blk.%d.ssm_norm.weight", l), RAD_F32, {cfg.head_v},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_out = decl_w(b, nm.f("blk.%d.ssm_out.weight", l), RAD_BF16, {g.n_embd, v_dim},
@@ -211,14 +190,10 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_z)), {w.h}, {w.z});
/* ---- the chunked path: a prefill chunk, where the scan amortises over `chunk` tokens.
* `chunk` is RAD_DERIVED on gdn_kkt_solve and gdn_chunk_scan for the same reason block_size is
* on attn_paged -- the tile length belongs to the kernel -- so it is omitted there and comes
* off the resolution. gdn_conv_prep still takes it, because the gate cumsum it writes is per
* chunk and has to be cut at the same boundary the scan tiles on. THAT THOSE TWO NUMBERS CAN
* DISAGREE IS A HOLE: one is supplied and one is derived, nothing compares them, and a
* mismatch is a decay applied over the wrong span rather than a diagnostic. Closing it needs
* either a readback for a resolved parameter or conv_prep's chunk made derived too. */
/* ---- the chunked path (prefill). `chunk` is RAD_DERIVED on gdn_kkt_solve and gdn_chunk_scan
* (the tile length belongs to the kernel), but gdn_conv_prep takes it explicitly because its
* gate cumsum must be cut at the scan's tile boundary. Known gap: nothing checks that the
* supplied and derived values agree; a mismatch applies the decay over the wrong span. */
op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v), RAD_INT("chunk", cfg.chunk),
@@ -240,10 +215,10 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_out_norm)),
{w.o, w.z}, {w.o});
/* ---- the recurrent path: decode and speculative verify, ranged on q_len because a verify
* step carries up to n_spec+1 query rows per sequence. `n_head_v` is stated rather than left
* to the value tensor's rank: 48 value heads against 16 key heads is the one geometry where
* guessing it from a flattened view gives a plausible wrong answer. */
/* ---- the recurrent path (decode and speculative verify), ranged on q_len because a verify
* step has up to n_spec+1 query rows per sequence. `n_head_v` is stated explicitly: with 48
* value heads to 16 key heads, inferring it from a flattened view gives a plausible wrong
* answer. */
op_conv_update = rw(b, RAD_OP(b, "gdn_conv_update",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
RAD_INT("head_k", cfg.head_k),
@@ -251,17 +226,12 @@ inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("conv_width", cfg.conv_width)),
RAD_WEIGHTS(w_conv)),
{w.in}, {w.q, w.k, w.v});
/* WHAT THE STATE CACHE MEANS, and it is not derivable from the operands. libr4d's recurrent
* update has two state contracts. PER-CANDIDATE writes one full state per candidate token and
* needs `1 + n_spec` distinct slots; ANCHOR keeps one committed state a sequence and replays
* the accepted prefix onto it out of a scratch slot, which is two slots whatever the depth.
* Same `o` either way, and a completely different `state` -- so a reference that implements one
* of them and is handed the other computes a correct answer to the other question.
*
* The engine already chooses: KVGroupPlan::state_copies is 2 when the deployment speculates
* and 1 when it does not, which is exactly this condition. Saying it here is what lets a
* reference DECLINE the form it does not implement instead of disagreeing with it, and what
* lets the kernel refuse a caller whose pool was sized for the other one. */
/* `state_form` states what the state cache holds, which the operands do not show. libr4d's
* recurrent update has two contracts: per_candidate writes one full state per candidate token
* (1 + n_spec slots); anchor keeps one committed state per sequence and replays the accepted
* prefix from a scratch slot (two slots at any depth). `o` is the same, `state` differs. It
* matches KVGroupPlan::state_copies (2 when speculating, else 1), and lets a reference decline
* the form it lacks and the kernel refuse a pool sized for the other. */
op_recur = rw(b, RAD_OP(b, "gdn_recurrent_update",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v),
@@ -298,9 +268,8 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
const RadKVGroupBatch* st = kv_batch(batch, kv_state);
const RadKVGroupBatch* cv = kv_batch(batch, kv_conv);
const int32_t* st_idx = st ? st->state_index : nullptr;
/* HOW MANY SLOTS THE ROW NAMES. One is the state; a linear kernel serving speculation
* asks for scratch beside it and the manager sizes the row to suit (RadKVGroupBatch).
* The block passes the row through and does not read it. */
/* Slots per state_index row: the state, plus scratch when a kernel serving speculation asks
* for it (RadKVGroupBatch). Passed through unread. */
const int64_t st_w = st && st->state_index_pitch > 0 ? st->state_index_pitch : 1;
const int32_t* cv_idx = cv ? cv->state_index : nullptr;
@@ -313,17 +282,15 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE(c, op_in, brows(w.h, T), RAD_W(w_in), brows(w.in, T));
RAD_ISSUE(c, op_z, brows(w.h, T), RAD_W(w_z), brows(w.z, T));
/* THE TWO PATHS, EACH OVER ITS OWN RUN OF SEQUENCES. rad_block_gdn_fp8.h's step() carries the
* long form of why; the short one is that the step is sorted decode-first, every kernel here
* derives both its grid and its rows from cu_seqlens, and cu holds ABSOLUTE offsets -- so the
* prefill half is addressed by handing it `cu + D` with the token operands left at their
* base, and the decode half by narrowing both to DT. The gated norm takes no cu and is per
* token, so it takes a row slice instead. */
/* Each path runs over its own run of sequences (details in rad_block_gdn_fp8.h's step()). The
* step is sorted decode-first and every kernel derives grid and rows from cu_seqlens, which
* holds absolute offsets: the prefill half gets `cu + D` with token operands at their base,
* the decode half has both narrowed to DT. The gated norm is per token, so it takes a row
* slice. */
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
/* And the band the decode half selects on. max_q_len over a mixed step is the prefill chunk;
* over a pure decode step it is already the right number, so a batch that leaves
* max_q_len_decode zero still selects correctly there. */
/* The decode half's band. In a mixed step max_q_len is the prefill chunk's; in a pure decode
* step it is already right, so a batch leaving max_q_len_decode zero still works there. */
const int32_t qd = batch->phase == RAD_PHASE_MIXED ? batch->max_q_len_decode : batch->max_q_len;
const int64_t P = S - D;
const int64_t PT = T - DT;
@@ -336,8 +303,7 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
praw(batch->cu_seqlens, RAD_I32, D + 1),
brows(w.q, DT), brows(w.k, DT), brows(w.v, DT));
/* a and b are the last 2*n_head_v columns of the projection row, read in place. The
* recurrent kernel folds the gated norm, which is why it takes z and the gain: at one
* token a head there is nothing to gain from a second pass over the state. */
* recurrent kernel folds the gated norm, so it takes z and the gain. */
RAD_ISSUE_N(c, op_recur, qd,
brows(w.q, DT), brows(w.k, DT), brows(w.v, DT),
bcol(w.in, conv_dim, H, DT), bcol(w.in, conv_dim + H, H, DT),
@@ -345,25 +311,20 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
praw(batch->cu_seqlens, RAD_I32, D + 1),
brows(w.z, DT), RAD_W(w_out_norm), brows(w.o, DT),
/* The folded out-projection quantiser, which this block does not want: the
* bf16 out projection reads `o` directly. Absent is TWO NULL OPERANDS, not a
* shorter list -- operands are positional and the runtime refuses a count
* that does not match the schema's sixteen (core/runtime/issue.cpp:111). */
/* The folded out-projection quantiser, unused: the bf16 out projection reads
* `o` directly. Operands are positional and the runtime checks the schema's
* count of sixteen (core/runtime/issue.cpp), so pass two RAD_NONE. */
RAD_NONE, RAD_NONE);
}
if (P > 0) {
/* Sixteen operands, inputs before outputs (docs/OPS.md). `a` and `b_gate` are the same
* strided views of the projection row the recurrent path builds above; they are optional
* in the schema -- ref falls back to the fused `x` tail -- but libr4d's conv_prep
* dereferences them and `cache_idx` unconditionally, so omitting them does not select a
* cheaper kernel, it silently drops the layer to the reference one.
/* Sixteen operands, inputs before outputs (docs/OPS.md). `a` and `b_gate` are optional in
* the schema (libref falls back to the fused `x` tail), but libr4d's conv_prep requires
* them and `cache_idx`; omitting them would silently fall back to the reference kernel.
*
* `has_init` is ctx_lens, and it is exactly the right array: a zero entry means the slot
* holds no history, and a sequence's context length before this step is zero precisely
* when it is starting fresh -- a new sequence, or one preempted and replaying, whose conv
* slot was recycled and holds another sequence's window. Without it the first chunk of
* every prefill convolves against whatever the slot last contained. */
* `has_init` is ctx_lens: zero exactly when a sequence starts fresh (new, or preempted and
* replaying, with a recycled conv slot), so the first chunk does not convolve against the
* slot's stale window. */
RAD_ISSUE(c, op_conv_prep,
brows(w.in, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log), RAD_W(w_dt_bias),
kv_cache(kv_conv, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
@@ -381,8 +342,8 @@ inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
kv_cache(kv_state, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
brows(w.o, T), kv_cache(kv_state, layer),
praw2(st_idx ? st_idx + D * st_w : nullptr, RAD_I32, P, st_w));
/* PER TOKEN, so a row slice and not a sequence sub-array: over the decode rows the
* recurrent kernel has already applied the gate in its own epilogue. */
/* Per token, so a row slice over the prefill rows only; the recurrent kernel already
* gated the decode rows. */
RAD_ISSUE_N(c, op_gnorm, PT,
brow_slice(w.o, DT, PT, v_dim), brow_slice(w.z, DT, PT, v_dim),
RAD_W(w_out_norm), brow_slice(w.o, DT, PT, v_dim));
+270 -212
View File
@@ -1,46 +1,35 @@
/* rad_block_gdn_fp8.h -- the gated-delta-net block with block-scaled FP8 projections.
*
* THE ARCHITECTURE IS rad_block_gdn.h's AND IS DOCUMENTED THERE: that `A_log` is a log and the
* kernels take the exponent themselves, that q and k are L2-normalised rather than RMS-normalised
* and that this happens inside the conv/recurrent kernels, why the prefill and decode paths are two
* declared sequences and why that is not the branch spec §2.4 forbids, and why both take
* `num_accepted`. None of it changes with the weight format.
* The architecture (A_log convention, in-kernel L2 norm of q and k, the two declared paths,
* `num_accepted`) is documented in rad_block_gdn.h and does not change with the weight format.
*
* ============================== a AND b SPLIT OUT; z DOES NOT ==============================
* ============================== a AND b SPLIT OUT; z FUSED ==============================
*
* rad_block_gdn.h fuses in_proj_qkv, in_proj_a and in_proj_b into ONE weight and one GEMM, because
* [q|k|v|a|b] is the row gdn_conv_prep reads. THAT FUSION IS NOT AVAILABLE HERE, and the reason is
* the checkpoint rather than a limitation:
* rad_block_gdn.h fuses in_proj_qkv, in_proj_a and in_proj_b into one weight. Here the
* checkpoint prevents it:
*
* in_proj_qkv.weight F8_E4M3 [10240, 5120] with weight_scale_inv [80, 40]
* in_proj_z.weight F8_E4M3 [ 6144, 5120] with weight_scale_inv [48, 40]
* in_proj_a.weight BF16 [48, 5120] -- no scale plane
* in_proj_b.weight BF16 [48, 5120] -- no scale plane
*
* a and b emit ONE COLUMN PER VALUE HEAD, 48 of them, and 48 is not a whole 128-row scale block --
* so the quantiser that produced this checkpoint left them in bf16, and no concatenation of an
* E4M3 tensor with a BF16 one is a tensor. They become a second, tiny bf16 `gemm_nt`: [96, 5120],
* 0.5% of the layer's projection bytes, and the price of it is one extra launch.
* a and b have one row per value head (48, not a whole 128-row block), so the quantiser left them
* bf16 and they cannot be concatenated with E4M3 tensors. They become a separate small bf16
* `gemm_nt` ([96, 5120], 0.5% of the layer's projection bytes). gdn_conv_prep and
* gdn_recurrent_update take a and b as separate operands in both blocks (column views of the
* fused row there, of their own buffer here); libref sizes its `x` read as
* `conv_dim + (a present ? 0 : 2*H)` for this case.
*
* a and b are separate operands of gdn_conv_prep and gdn_recurrent_update in both blocks -- the
* bf16 block passes them as column views of the fused row, this one as column views of their own
* buffer -- so nothing downstream changes shape. Ref sizes its `x` read as
* `conv_dim + (a present ? 0 : 2*H)` for precisely this case.
*
* THE OUTPUT GATE IS THE OPPOSITE CASE and it IS fused, into `ssm_inz`: in_proj_z is E4M3 with its
* own scale plane, its rows are a whole number of blocks, and it reads the same normed activation.
* So [q|k|v|z] is one weight, one launch and the same bytes -- see declare() for why one call is
* cheaper than two. What that costs is that `w.in.x` is conv_dim + v_dim wide, and the convolution
* and the gate are COLUMN VIEWS of it rather than buffers of their own: gdn_conv_prep,
* gdn_conv_update and gdn_recurrent_update all take a row pitch on the operand concerned.
* The output gate is fused instead, into `ssm_inz`: in_proj_z is E4M3 with whole scale blocks and
* reads the same normed activation, so [q|k|v|z] is one weight and one launch. `w.in.x` is then
* conv_dim + v_dim wide, and the convolution input and the gate are column views of it; the
* consuming kernels all take a row pitch.
*
* ============================== THE OUT-PROJECTION'S INPUT IS RANK 3 ==============================
*
* `o` is [tokens, value heads, head width] because libr4d's chunk-scan and recurrent kernels
* require rank 3 there, and it is the out-projection's activation -- so the quantiser has to accept
* it. It does: rows are dim 0 and everything after is the row, which is the reading r4d_row_pitch
* already takes and which the consuming GEMM's K forces. Reading it as one row per HEAD would put a
* scale on a grid the GEMM does not read.
* `o` is [tokens, value heads, head width] because libr4d's chunk-scan and recurrent kernels need
* rank 3. The quantiser reads dim 0 as rows and the rest as the row (as r4d_row_pitch does and
* the GEMM's K requires); one row per head would put scales on a grid the GEMM does not read.
*/
#ifndef RAD_BLOCK_GDN_FP8_H
#define RAD_BLOCK_GDN_FP8_H
@@ -48,15 +37,14 @@
#include "rad_fp8.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
namespace rad {
namespace arch {
struct GdnFP8 {
/* The same geometry the bf16 block takes, with one addition: `ab_dim` is what the split costs
* in declared width, and it is 2 * n_head_v. */
/* The bf16 block's geometry plus the gate activation, uneven head splits, and `ab_dim`
* (2 * n_head_v), the width of the separate a|b projection. */
struct Config {
int64_t n_head_k = 0;
int64_t head_k = 0;
@@ -64,19 +52,15 @@ struct GdnFP8 {
int64_t head_v = 0;
int64_t conv_width = 4;
int64_t chunk = 64;
/* THE OUTPUT GATE'S ACTIVATION, and it is a CHECKPOINT PROPERTY rather than a family
* one. `RMSNormGated` defaults to silu and every Qwen3.5/3.6 release leaves it there,
* but Qwen4-Exp states `output_gate_type: "sigmoid"` and means it -- a gate of
* sigmoid(z) where this said silu(z) scales every value head's output by roughly z
* again. libr4d has compiled both arms all along (r4d_gdn_gated_rmsnorm's `gn_act`) and
* `gdn_recurrent_update` composes the same parameter, so this is a string to pass and
* not a kernel to write. "silu" or "sigmoid"; anything else is refused below. */
/* The output gate's activation, a per-checkpoint property: `RMSNormGated` defaults to
* silu (every Qwen3.5/3.6 release), while Qwen4-Exp sets `output_gate_type: "sigmoid"`.
* libr4d's r4d_gdn_gated_rmsnorm (`gn_act`) and `gdn_recurrent_update` implement both.
* "silu" or "sigmoid"; anything else is refused. */
const char* act = "silu";
/* AN UNEVEN SPLIT OF THE HEADS (rad_weight_shard_span_parts). n_head_k / n_head_v are
* this rank's; k_first / v_first its first head of the container's n_head_k_all /
* n_head_v_all. k_first < 0 is the even split the plain row shard gives, as before.
* Three ranks over 16 K heads take 6, 5 and 5 (and 18, 15, 15 of the 48 V heads) --
* every rank real heads, nothing padded, every kernel at its own head count. */
/* Uneven head split (rad_weight_shard_span_parts). n_head_k / n_head_v are this rank's;
* k_first / v_first are its first heads within the container's n_head_k_all /
* n_head_v_all. k_first < 0 means the plain even row shard. Three ranks over 16 K heads
* take 6, 5 and 5 (18, 15, 15 of 48 V heads), with no padding. */
int64_t k_first = -1, v_first = -1;
int64_t n_head_k_all = 0, n_head_v_all = 0;
bool uneven() const { return k_first >= 0; }
@@ -90,10 +74,8 @@ struct GdnFP8 {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the out projection */
/* ONE BUFFER, TWO PROJECTIONS: [q|k|v] and the output gate come out of one GEMM (see
* ssm_inz in declare()), so the gate is this buffer's right-hand `v_dim` columns and the
* convolution reads the left-hand `conv_dim`. Both are `bcol` views, which is why every
* consumer of either takes a row pitch. */
/* [q|k|v] and the output gate from one GEMM (ssm_inz): the convolution reads the left
* `conv_dim` columns and the gate is the right `v_dim`, both as `bcol` views. */
ActFP8 in{}; /* [max_tok, conv_dim+v_dim] [q|k|v] then the output gate */
rad_buf ab = 0; /* [max_tok, 2*n_head_v] the decay and beta inputs, bf16 */
rad_buf q = 0; /* [max_tok, n_head_k, head_k] post-convolution, l2-normed */
@@ -102,7 +84,7 @@ struct GdnFP8 {
rad_buf gdec = 0; /* [max_tok, n_head_v] */
rad_buf beta = 0; /* [max_tok, n_head_v] */
rad_buf kkt = 0; /* [max_tok, n_head_v, chunk] */
ActFP8 o{}; /* [max_tok, n_head_v, head_v] -- RANK 3, see the header */
ActFP8 o{}; /* [max_tok, n_head_v, head_v] rank 3, see the header */
};
struct Src {
@@ -127,6 +109,11 @@ struct GdnFP8 {
rad_weight w_norm = 0, w_ab = 0, w_conv = 0;
/* The input was normed and quantised by the caller; this block declares no norm. */
bool ext_in = false;
/* Set by the architecture before declare: the a|b projection runs on the second lane beside the
* in-projection at decode and verify sizes. Not where lane 1 carries collectives, which the
* projection would queue behind. Its concurrent buffers cost memory (at Qwen3.8-27B TP2: +70
* MiB arena and +33 MiB queues a card) for about +1 % at one stream. */
bool ab_lane = false;
rad_weight w_a_log = 0, w_dt_bias = 0, w_out_norm = 0;
LinearFP8 in{}, out{};
NormQuantFP8 nq_h{};
@@ -135,33 +122,52 @@ struct GdnFP8 {
rad_op op_ab = 0;
rad_op op_conv_prep = 0, op_kkt = 0, op_scan = 0, op_gnorm = 0; /* prefill */
rad_op op_conv_update = 0, op_recur = 0; /* decode */
/* `gdn_conv_recurrent_update`, if it resolves: the pair above as one launch, the convolution
* computed in the recurrent update's prologue. 0 leaves the pair, which is declared either
* way; cr_rows is the widest decode window the fold serves. */
/* `gdn_conv_recurrent_update`, if it resolves: the pair above in one launch, with the
* convolution in the recurrent update's prologue. The pair is declared either way; cr_rows is
* the widest decode window the fold serves. */
rad_op op_cr = 0;
/* Whether op_cr writes the out projection's codes; otherwise q_o follows it. */
bool cr_codes = false;
int64_t cr_rows = 0;
/* Set by the architecture after declare: a `prefetch` of the out-projection's leading bytes
* (decl_prefetch, rad_arch.h), issued beside the decode recurrent update on steps of up to
* pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
rad_op op_pf_out = 0;
int64_t pf_out_rows = 0, pf_out_seqs = 0;
rad_op op_ar = 0, op_add = 0;
/* ...AND WHETHER THE COLLECTIVE AT THE END OF THIS BLOCK IS THE NEXT BLOCK'S FIRST PASS.
* `ar_in` says this block's own norm absorbs its PREDECESSOR's all-reduce; `ar_out` says the
* block after it absorbs THIS one's, so this one must not issue it. They are the residual
* fold's two flags again, one boundary later, and they are separate for the same reason: a
* block is declared without knowing what follows it. On EITHER wire -- the fused kernel
* carries both payloads -- and both sides ask ar_fused_ok(g, T), so the two cannot disagree
* about whether the collective has already been issued. */
/* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_fp8.h). */
bool ar_out = false;
/* ...and WHICH WIRES that consumer takes (ArOut, rad_fp8.h): the norm's by default, and a gated
* residual's write says its own (HyperConn::ar_take). Set before declare; both sides then ask
* ar_taken(g, T, ar_out, ar_out_take). */
/* Which wires that consumer takes (ArOut, rad_fp8.h); set before declare. */
int ar_out_take = kArOutNorm;
/* `fold` says the PREVIOUS block left its delta in `w.h.x` for this norm to add; `add_out`
* says the NEXT one will not, so this block issues the trailing add itself. See rad_fp8.h. */
/* `fold`: the previous block left its delta in `w.h.x` for this norm to add. `add_out`: the
* next block will not add, so this one issues the trailing add. See rad_fp8.h. */
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
rad_kvgroup state, rad_kvgroup conv, const Wire& wire, const Src& s,
bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* `own_ar` false: the caller issues this step's all-reduce itself, a row slice at a time
* (issue_ar), to overlap it with other work (a pipelined prefill). Only on a block without a
* trailing add, which would read the delta before the reduction. */
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
ArPieces* pieces = nullptr) const;
/* Whether step() with `own_ar` false runs the whole block a piece at a time over `pieces`
* (its piece path), asked by a caller that must know before it commits to a schedule. */
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
return pieces && pieces->cu && pieces->cuts(batch->n_tok) &&
batch->n_tok <= 2 * pieces->rows && (ext_in || pieces->in_ready) && !op_add &&
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL;
}
/* Whether a step of T rows issues the all-reduce itself, asked by a caller before taking it
* over; and that all-reduce over rows [r0, r0 + rows) of the output. */
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
}
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
int ar_overlap = 0;
rad_op op_ar_ov = 0;
};
inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
@@ -179,22 +185,8 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
return RAD_E_INVAL;
}
/* THE QUERY SCALE, AND IT IS NOT OPTIONAL. `gdn_chunk_scan` and `gdn_recurrent_update` both
* carry a `scale` that multiplies the output -- o = scale * e^g Q S^T + ... -- and it defaults to
* 1. FLA's chunk_gated_delta_rule defaults it to head_k^-0.5 and vllm-radiance passes exactly
* that; llama.cpp's fused GDN does the same.
*
* IT LOOKS LIKE IT CANCELS AND IT DOES NOT. The scan's output goes straight into the gated RMS
* norm, and an RMS norm divides a constant factor back out -- so scaling `o` by c should change
* nothing. That argument is wrong here for one reason: the scan output of this model is around
* 1e-6, `mean(o^2)` is then around 1e-12, and the norm's eps is 1e-6. eps DOMINATES the variance,
* the norm degenerates into a fixed division by sqrt(eps), and the factor passes straight through
* to the residual stream.
*
* Leaving it at 1 is visible end to end: the scan output comes out larger than the reference
* implementations' by exactly sqrt(head_k), and with forty-eight of this model's sixty-four
* layers delta net the residual stream then carries a delta-net contribution that many times
* too large -- fluent grammar with no content. */
/* The query scale is required; rad_block_gdn.h explains why the gated norm does not cancel
* it. */
const double q_scale = 1.0 / std::sqrt((double)cfg.head_k);
if (!cfg.act || (std::strcmp(cfg.act, "silu") != 0 && std::strcmp(cfg.act, "sigmoid") != 0)) {
@@ -206,18 +198,10 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
const int64_t conv_dim = cfg.conv_dim();
const int64_t ab_dim = cfg.ab_dim();
/* THE INPUT MAY BE PREPARED BY THE ARCHITECTURE, and `src.norm == nullptr` is how it says so.
*
* A pre-norm model's block owns its own norm: one op that adds the previous block's delta into
* the residual stream, normalises it and quantises it (rad_fp8.h's NormQuantFP8). A GATED
* RESIDUAL model's does not -- arch/common/rad_block_hc.h's `hc_read` produces the block input
* from a stream four times as wide, with a data-dependent mix the block has no way to compute,
* and there is nothing left for a norm here to do. So this block takes `wire.h` as ALREADY
* normed and quantised and declares no norm weight at all.
*
* `ar_in` is refused in that mode rather than ignored: the fused all-reduce lives INSIDE the
* norm, so with no norm there is nowhere to fold it and a caller that asked would silently get
* an unreduced input. It emits a standalone collective instead (`add_out`/`ar_out`). */
/* `s.norm == nullptr`: the architecture prepares the input (a gated-residual model's
* rad_block_hc.h `hc_read`), so `wire.h` is already normed and quantised and no norm weight is
* declared. `ar_in` is then refused, since the fused all-reduce lives inside the norm. See
* rad_block_attn_gated_fp8.h. */
ext_in = (s.norm == nullptr);
if (ext_in) {
if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
@@ -226,22 +210,19 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
}
/* The name maps ahead of the weights they name: a checkpoint is asked what a weight is
* through its map, at the declaration. */
/* Maps before weights: weight encodings are looked up through the map. */
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ssm_ab.weight", l), { s.in_a, s.in_b }, 0));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_conv1d.weight", l), s.conv1d));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_a_log", l), s.a_log));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_dt.bias", l), s.dt_bias));
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_norm.weight", l), s.out_norm));
/* The decay and beta projections, kept bf16 because the checkpoint kept them bf16 -- see the
* header. Row-sharded with the value heads they belong to: a and b are concatenated along dim 0
* so rank r owns rows [r*n_head_v, (r+1)*n_head_v) of EACH half, which is what the two-part
* row split says and what a contiguous slice of the concatenation would not give. */
/* The decay and beta projections, bf16 as in the checkpoint. Row-sharded with their value
* heads: the two-part split gives rank r rows [r*n_head_v, (r+1)*n_head_v) of each of a and
* b, which a contiguous slice of the concatenation would not. */
w_ab = decl_w(b, nm.f("blk.%d.ssm_ab.weight", l), RAD_BF16, {ab_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
{cfg.n_head_v, cfg.n_head_v});
/* The depthwise convolution is per channel, so it shards with the channels it convolves --
* and those channels are [q|k|v], three groups in one stored tensor, so the split is theirs. */
/* The depthwise convolution shards with its channels, [q|k|v] (three parts). */
w_conv = decl_w(b, nm.f("blk.%d.ssm_conv1d.weight", l), RAD_BF16,
{conv_dim, cfg.conv_width},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
@@ -253,32 +234,26 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
w_out_norm = decl_w(b, nm.f("blk.%d.ssm_norm.weight", l), RAD_F32, {cfg.head_v},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
/* One norm and one quantise of the normed hidden state, in one op; the qkv and z
* projections both read it. rad_fp8.h's NormQuantFP8 says why they are not two. */
/* Norm and quantise in one op (rad_fp8.h: NormQuantFP8); the qkv|z and a|b projections read
* it. */
if (!ext_in)
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
fold ? w.x : 0, 0, ar_in));
/* TWO CHECKPOINT TENSORS, FOUR PROJECTIONS, ONE GEMM. in_proj_qkv is [q|k|v] stacked along
* dim 0 and in_proj_z is the output gate; both read the SAME normed, quantised hidden state
* and differ only in their rows, so they are one weight here and one launch at step time.
/* Two checkpoint tensors (in_proj_qkv = [q|k|v], in_proj_z = the gate), four projections, one
* GEMM. At decode two calls at 5120 and 3072 rows cost more than one at 8192, since each pays
* its own ramp and tail. Bit-identical: row arithmetic is unchanged and both extents are past
* the split-K threshold.
*
* WHY ONE CALL AND NOT TWO. The decode GEMM is bandwidth-bound but not at small N: two calls
* at 5120 and 3072 rows cost more between them than one call at 8192, because each pays its
* own ramp and tail on top of its launch. Over this model's delta-net layers that adds up to a
* measurable share of a decode step. It is bit-identical: nothing about a row's arithmetic
* changes, and both extents are already past the split-K threshold so the summation order does
* not move either.
*
* THE ROW PARTS ARE THE WHOLE POINT. Rank r must own its slice of EACH of q, k, v and z, so
* the shard is declared as four parts and not as one contiguous cut -- which would give rank 0
* all of q, all of k and a third of v, a well-formed wrong model. */
* The four row parts are required so rank r owns its slice of each of q, k, v and z; one
* contiguous cut would give rank 0 all of q and k. */
RAD_ARCH_TRY(in.declare(b, nm, g, nm.f("blk.%d.ssm_inz", l), conv_dim + v_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), { s.in_qkv, s.in_z }, w.h, w.in.x, 0,
{ cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() }));
{ cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() }, 0, 0,
/* a rotated weight was rotated per checkpoint tensor: q|k|v, then z */
{ 2 * cfg.k_dim() + cfg.v_dim(), cfg.v_dim() }));
if (cfg.uneven()) {
/* THIS RANK'S HEADS OF EACH PART, in the container's rows: q and k by K head, v and z by
* V head. The scale plane of a row shard has the same rows (its blocks run along K). */
/* This rank's heads of each part, in container rows: q and k by K head, v and z by V head.
* The scale plane of a row shard has the same rows (its blocks run along K). */
const int64_t kl = cfg.k_first * cfg.head_k, vl = cfg.v_first * cfg.head_v;
const int64_t ka = cfg.n_head_k_all * cfg.head_k, va = cfg.n_head_v_all * cfg.head_v;
const int64_t lo[4] = { kl, kl, vl, vl };
@@ -295,31 +270,25 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_ARCH_TRY(rad_weight_shard_span(b, w_a_log, cfg.v_first, cfg.v_first + cfg.n_head_v));
RAD_ARCH_TRY(rad_weight_shard_span(b, w_dt_bias, cfg.v_first, cfg.v_first + cfg.n_head_v));
}
/* NOT SLICED, and why it could need to be is worth keeping. This is a 96-column bf16 GEMM --
* half a percent of the layer's projection bytes -- and a bf16 kernel for this shape that
* stopped at M = 64 would leave a hole in its bucket table above 64. Since every op in a step
* is issued at the same token count, that one hole would cap the prefill chunk of the entire
* 27B model at 64 tokens, and the workaround is a launch per 64 rows in every GDN layer. The
* cap was a launcher guard the kernel does not need: MT row tiles live in a block and grid.y
* covers the rest, so M is general, and with the guard raised this is one launch.
/* One launch over all rows: libr4d's bf16 kernel for this 96-column shape is general in M
* (MT row tiles per block, grid.y covers the rest). A kernel capped at M = 64 would cap every
* op in the step, and so the prefill chunk, at 64 tokens (see brow_slice in rad_arch.h).
*
* AT DECODE THE COST IS THE LAUNCH COUNT, not the arithmetic. `gemm_nt` is the most-dispatched
* kernel in a decode step and it is almost entirely fixed cost, spread over three separate
* small per-layer projections that all read the same activation: the MoE router (one a layer),
* the shared expert's gate (one a layer, RANK 0 ONLY, so on the rank the all-reduce is already
* waiting for) and this a|b (one a GDN layer).
*
* Fusing them is the lever and it is not a small one: they read the same activation but hold
* different weights, so a merge wants either contiguous weights -- a re-convert, which is
* ruled out -- or a GROUPED gemm_nt taking a table of weight pointers the way moe_gemm_q
* does. */
* At decode the cost is launch count: `gemm_nt` is the most-dispatched decode kernel, nearly
* all fixed cost, across three small per-layer projections of the same activation (the MoE
* router, the shared expert's gate on rank 0 only, and this a|b). Merging them would need
* contiguous weights (a re-convert) or a grouped gemm_nt over a weight-pointer table, as
* moe_gemm_q does. */
op_ab = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", ab_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_ab)), {w.h.x}, {w.ab});
if (ab_lane) {
RAD_ARCH_TRY(rad_buf_concurrent(b, w.h.x));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.ab));
}
/* ---- the chunked path. Unchanged from the bf16 block except that `a` and `b_gate` are views
* of `ab` rather than of the projection row's tail. */
/* ---- the chunked path. As in the bf16 block, except `a` and `b_gate` are views of `ab`. */
op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v), RAD_INT("chunk", cfg.chunk),
@@ -349,17 +318,7 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_INT("conv_width", cfg.conv_width)),
RAD_WEIGHTS(w_conv)),
{w.in.x}, {w.q, w.k, w.v});
/* WHAT THE STATE CACHE MEANS, and it is not derivable from the operands. libr4d's recurrent
* update has two state contracts. PER-CANDIDATE writes one full state per candidate token and
* needs `1 + n_spec` distinct slots; ANCHOR keeps one committed state a sequence and replays
* the accepted prefix onto it out of a scratch slot, which is two slots whatever the depth.
* Same `o` either way, and a completely different `state` -- so a reference that implements one
* of them and is handed the other computes a correct answer to the other question.
*
* The engine already chooses: KVGroupPlan::state_copies is 2 when the deployment speculates
* and 1 when it does not, which is exactly this condition. Saying it here is what lets a
* reference DECLINE the form it does not implement instead of disagreeing with it, and what
* lets the kernel refuse a caller whose pool was sized for the other one. */
/* `state_form`: anchor when speculating, else per_candidate (rad_block_gdn.h explains). */
op_recur = rw(b, RAD_OP(b, "gdn_recurrent_update",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v),
@@ -370,29 +329,37 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
g.max_spec > 0 ? "anchor" : "per_candidate")),
RAD_WEIGHTS(w_a_log, w_dt_bias, w_out_norm)),
{w.q, w.k, w.v, w.ab, w.in.x}, {w.o.x});
/* The epilogue's codes, for an fp8 or int8 out-projection -- the int8 pair when the model feeds
* it (ActFP8::q8_fed), whose dtype picks the kernel's quantiser; a bf16 one reads `o.x` and
* nothing else, and the operands are left absent. */
if (op_recur && w.o.cq()) {
/* The epilogue's codes for an fp8 or int8 out-projection (int8 when ActFP8::q8_fed; the codes
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent.
* Rotated int8 codes (ActFP8::q8_rot) only the conv fold writes (gdn_conv_recurrent_update_had);
* rows this update serves are quantised by q_o. */
if (op_recur && w.o.cq() && !w.o.q8_rot) {
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2));
}
/* THE FOLD, over the same weights and caches. Its window is a register preload, so the band
* stops at eight tokens a sequence; not RAD_ARCH_TRY, since a plugin without the row is the
* ordinary case and the pair runs. */
/* The conv + recurrent fold. Its window is a register preload, so the band stops at eight
* tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */
{
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
op_cr = rw(b, RAD_OP(b, "gdn_conv_recurrent_update",
RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v),
RAD_INT("conv_width", cfg.conv_width),
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
RAD_STR("state_form",
g.max_spec > 0 ? "anchor" : "per_candidate")),
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias, w_out_norm)),
/* The fold's rotated epilogue writes one scale per (row, 128), or per 256 for an IQ8R
* trunk's codes (ActFP8::g8; `group`, stated to that form alone: last, and cut off
* otherwise), where this rank's value heads pair up. */
const bool cr_wide = w.o.q8_rot && w.o.g8 == RAD_I8_GROUP_WIDE && cfg.n_head_v % 2 == 0;
cr_codes = w.o.cq() && (!w.o.q8_rot || w.o.g8 == RAD_FP8_BLOCK || cr_wide);
const RadParam cp[] = { RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v),
RAD_INT("conv_width", cfg.conv_width),
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate"),
RAD_INT("group", RAD_I8_GROUP_WIDE) };
const rad_weight cw[] = { w_conv, w_a_log, w_dt_bias, w_out_norm };
op_cr = rw(b, rad_decl_op(b, w.o.q8_rot && cr_codes ? "gdn_conv_recurrent_update_had"
: "gdn_conv_recurrent_update",
cp, (int)(sizeof cp / sizeof *cp) - (cr_wide && cr_codes ? 0 : 1),
cw, 4),
{w.in.x, w.ab}, {w.o.x});
if (op_cr && w.o.cq()) {
if (op_cr && cr_codes) {
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
RAD_ARCH_TRY(rad_op_writes(b, op_cr, oq, 2));
}
@@ -413,7 +380,18 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{w.h.x}, {w.h.x});
/* Only where the NEXT block's norm will not do it; see rad_fp8.h's NormQuantFP8. */
/* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
* prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
if (g.world > 1 && ar_overlap > 0)
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes),
RAD_INT("overlap", ar_overlap)),
RAD_NOWEIGHTS),
{w.h.x}, {w.h.x});
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
if (add_out)
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
@@ -423,58 +401,121 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
return RAD_OK;
}
inline void GdnFP8::step(RadCtx* c, const RadBatch* batch) const {
inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
ArPieces* pieces) const {
const RadKVGroupBatch* st = kv_batch(batch, kv_state);
const RadKVGroupBatch* cv = kv_batch(batch, kv_conv);
const int32_t* st_idx = st ? st->state_index : nullptr;
/* HOW MANY SLOTS THE ROW NAMES. One is the state; a linear kernel serving speculation
* asks for scratch beside it and the manager sizes the row to suit (RadKVGroupBatch).
* The block passes the row through and does not read it. */
/* Slots per state_index row: the state, plus scratch when a kernel serving speculation asks
* for it (RadKVGroupBatch). Passed through unread. */
const int64_t st_w = st && st->state_index_pitch > 0 ? st->state_index_pitch : 1;
const int32_t* cv_idx = cv ? cv->state_index : nullptr;
const int64_t T = batch->n_tok;
const int64_t S = batch->n_seq;
const int64_t H = cfg.n_head_v;
/* The two halves of `w.in.x`: the convolution's [q|k|v] and the output gate behind it. */
/* The two parts of `w.in.x`: the convolution's [q|k|v], then the output gate. */
const int64_t conv_dim = cfg.conv_dim();
const int64_t v_dim = cfg.v_dim();
if (!ext_in) nq_h.step(c, T);
in.step(c, w.h, w.in.x, T);
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
/* One prefill sequence in two pieces (ArPieces::cu): the whole block a piece at a time, each
* piece the chunk a span of 1 makes (the projection over its rows; the convolution, solve and
* scan over its bounds, with the state handed on through the cache; the gated norm, quantiser
* and out projection), so the first piece's reduction runs beside all of the second piece's
* work. The second piece reads the history the first left in the convolution slot, so each
* piece passes its own context length, its first row's position: the step's would tell the
* second piece of a prompt's first chunk that it has none. */
if (!own_ar && takes_pieces(batch, pieces)) {
const int64_t in_w = conv_dim + v_dim;
for (int64_t p = 0; p < 2; ++p) {
const int64_t r0 = p * pieces->rows;
const int64_t n = p == 0 ? pieces->rows : T - pieces->rows;
const int32_t* cu = pieces->cu + p;
in.step(c, w.h, w.in.x, T, r0, n);
RAD_ISSUE_N(c, op_ab, n, brow_slice(w.h.x, r0, n, g.n_embd), RAD_W(w_ab),
brow_slice(w.ab, r0, n, 2 * H));
RAD_ISSUE_N(c, op_conv_prep, n,
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log),
RAD_W(w_dt_bias), kv_cache(kv_conv, layer), praw(cu, RAD_I32, 2),
bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
praw(cv_idx, RAD_I32, 1), praw(batch->positions + r0, RAD_I32, 1),
brows(w.q, T), brows(w.k, T), brows(w.v, T),
brows(w.gdec, T), brows(w.beta, T));
RAD_ISSUE_N(c, op_kkt, n,
brows(w.k, T), brows(w.beta, T), brows(w.gdec, T),
praw(cu, RAD_I32, 2), brows(w.kkt, T));
RAD_ISSUE_N(c, op_scan, n,
brows(w.q, T), brows(w.k, T), brows(w.v, T), brows(w.kkt, T),
brows(w.gdec, T), brows(w.beta, T),
kv_cache(kv_state, layer), praw(cu, RAD_I32, 2),
brows(w.o.x, T), kv_cache(kv_state, layer),
praw2(st_idx, RAD_I32, 1, st_w));
RAD_ISSUE_N(c, op_gnorm, n,
brow_slice(w.o.x, r0, n, v_dim),
bcol_at(w.in.x, r0, in_w, conv_dim, v_dim, n),
RAD_W(w_out_norm), brow_slice(w.o.x, r0, n, v_dim));
q_o.step(c, T, r0, n);
out.step(c, w.o, w.h.x, T, r0, n);
if (p == 0) pieces->hand(r0, n);
}
return;
}
/* THE TWO PATHS, EACH OVER ITS OWN RUN OF SEQUENCES.
if (!ext_in) nq_h.step(c, T);
/* At decode and verify sizes the a|b projection is nearly all launch cost and reads only the
* norm's output, as the in-projection does, so it runs beside it on lane 1 and is joined before
* the convolution reads `ab`. A prefill chunk keeps one lane, where the two would share
* bandwidth. Where launches chain it stays on lane 0: its chained form starts beside the
* in-projection without the two lane joins, each of which holds a launch back until the host
* has seen the other lane finish (Qwen3.8-27B on two cards: the projection started 55 us late
* and the update behind it another 20 to 40 us). */
if (ab_lane && !rad_chain_on() && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK &&
rad_lane(c, 1) == RAD_OK) {
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
rad_lane(c, 0);
in.step(c, w.h, w.in.x, T);
rad_lane_join(c, 1, 0);
} else {
in.step(c, w.h, w.in.x, T);
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
}
/* Each path runs over its own run of sequences. The step is sorted decode-first: decode rows
* are sequences [0, D) with tokens [0, DT), prefill chunks are [D, S) with the rest. A pure
* step issues one path.
*
* The step is sorted decode-first, so the decode rows are sequences [0, D) holding tokens
* [0, DT) and the prefill chunks are sequences [D, S) holding the rest. Each path is issued
* over its own half and a pure step issues exactly one of them.
* Per-sequence arrays are offset, token operands are not. Every kernel here derives its grid
* and rows from cu_seqlens (N = len(cu) - 1, a sequence's first row is the absolute cu[n]), so
* the prefill half gets `cu + D` with q, k, v at their base; offsetting those too would count
* the displacement twice. The decode half is the prefix: cu ends at DT and its token operands
* are cut to DT rows. The gated norm and the standalone quantiser take no cu and are per
* token, so they take row slices at DT.
*
* THE PER-SEQUENCE ARRAYS MOVE AND THE TOKEN OPERANDS DO NOT. Every kernel here takes
* cu_seqlens and derives both its grid and its rows from it -- N is cu's own length minus one
* and row zero of a sequence is the ABSOLUTE cu[n] -- so the prefill half is addressed by
* handing it `cu + D` while leaving q, k, v and the rest at their base. Offsetting those too
* would count the displacement twice. The decode half is the prefix, so it narrows instead:
* its cu ends at DT and its token operands are cut to DT rows, which agree because they are
* the same number.
*
* The two ops that take no cu -- the gated norm and the standalone quantiser -- are per TOKEN,
* so they take a row slice and are the only place DT appears as an offset.
*
* What this buys is that a mixed step does not run the chunked path over a sequence that is
* only decoding. That path commits the state directly and has no num_accepted operand, so a
* draft verified on it could not be rolled back and the scheduler would have to refuse one in
* every mixed step -- on an agentic load, a large share of all decode rows. */
* This keeps decode-only sequences in a mixed step off the chunked path, which commits state
* directly and has no num_accepted, so drafts verified there could not be rolled back. */
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
/* And the band the decode half selects on. max_q_len over a mixed step is the prefill chunk;
* over a pure decode step it is already the right number, so a batch that leaves
* max_q_len_decode zero still selects correctly there. */
/* The decode half's band. In a mixed step max_q_len is the prefill chunk's; in a pure decode
* step it is already right, so a batch leaving max_q_len_decode zero still works there. */
const int32_t qd = batch->phase == RAD_PHASE_MIXED ? batch->max_q_len_decode : batch->max_q_len;
const int64_t P = S - D;
const int64_t PT = T - DT;
const int64_t in_w = conv_dim + v_dim; /* w.in.x's declared row width */
/* The recurrent update at decode heights runs one workgroup per (sequence, head) and leaves the
* card's memory mostly idle, so the out-projection's weight is read into the on-die cache
* beside it: in front of the update on lane 0 where launches chain (the read's chained form
* holds nothing behind it), else on the second lane behind a join from lane 0 (as
* prefetch_beside). */
if (op_pf_out && D > 0 && D <= pf_out_seqs && P == 0 && T <= pf_out_rows) {
if (prefetch_lane0()) {
RAD_ISSUE(c, op_pf_out, RAD_W(out.w));
} else {
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
RAD_ISSUE(c, op_pf_out, RAD_W(out.w));
rad_lane(c, 0);
}
}
if (D > 0 && op_cr && qd <= cr_rows) {
RAD_ISSUE_N(c, op_cr, qd,
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
@@ -484,8 +525,9 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch) const {
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
praw(batch->cu_seqlens, RAD_I32, D + 1),
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
w.o.cq() ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
cr_codes ? brows(w.o.cq(), DT) : RAD_NONE,
cr_codes ? brows(w.o.cs(), DT) : RAD_NONE);
if (w.o.cq() && !cr_codes) q_o.step(c, T, 0, DT);
} else if (D > 0) {
RAD_ISSUE_N(c, op_conv_update, qd,
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
@@ -499,10 +541,16 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch) const {
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
praw(batch->cu_seqlens, RAD_I32, D + 1),
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
w.o.cq() ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
w.o.cq() && !w.o.q8_rot ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() && !w.o.q8_rot ? brows(w.o.cs(), DT) : RAD_NONE);
/* Rotated codes come only from the fold; here the decode rows take the quantiser. */
if (w.o.q8_rot) q_o.step(c, T, 0, DT);
}
/* The output a piece at a time where the caller takes the all-reduce that way (ArPieces): the
* gated norm, quantiser and out projection are per row, so a pure prefill step can finish them
* a piece at a time and hand off each piece's reduction behind it. */
const bool cut = !own_ar && pieces && pieces->cuts(T) && D == 0 && P > 0 && !op_add;
if (P > 0) {
RAD_ISSUE(c, op_conv_prep,
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log), RAD_W(w_dt_bias),
@@ -521,23 +569,33 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch) const {
kv_cache(kv_state, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
brows(w.o.x, T), kv_cache(kv_state, layer),
praw2(st_idx ? st_idx + D * st_w : nullptr, RAD_I32, P, st_w));
/* PER TOKEN, so this one is a row slice and not a sequence sub-array. Over the decode
* rows the recurrent kernel has already applied the gate in its own epilogue. */
if (cut) {
for (int64_t r0 = 0; r0 < T; r0 += pieces->rows) {
const int64_t n = T - r0 < pieces->rows ? T - r0 : pieces->rows;
RAD_ISSUE_N(c, op_gnorm, n,
brow_slice(w.o.x, r0, n, v_dim),
bcol_at(w.in.x, r0, in_w, conv_dim, v_dim, n),
RAD_W(w_out_norm), brow_slice(w.o.x, r0, n, v_dim));
q_o.step(c, T, r0, n);
out.step(c, w.o, w.h.x, T, r0, n);
if (r0 + n < T) pieces->hand(r0, n);
}
return;
}
/* Per token, so a row slice over the prefill rows only; the recurrent kernel already
* gated the decode rows. */
RAD_ISSUE_N(c, op_gnorm, PT,
brow_slice(w.o.x, DT, PT, v_dim),
bcol_at(w.in.x, DT, in_w, conv_dim, v_dim, PT),
RAD_W(w_out_norm), brow_slice(w.o.x, DT, PT, v_dim));
/* PREFILL STILL QUANTISES SEPARATELY, and only prefill. The decode kernel folds the
* quantiser into its own epilogue -- see the operand list on gdn_recurrent_update -- so
* issuing this over those rows would overwrite the same bytes with the same values for a
* launch a layer, in every delta-net layer, for nothing. The chunked
* scan has no such epilogue: its workgroup is a chunk, not a row, and the group's amax is
* not a reduction it can do. */
/* Only the prefill rows are quantised here; the decode kernel quantises in its epilogue.
* The chunked scan cannot: its workgroup is a chunk, not a row, so it cannot reduce a
* row group's amax. */
q_o.step(c, T, DT, PT);
}
out.step(c, w.o, w.h.x, T);
if (op_ar && !ar_taken(g, T, ar_out, ar_out_take))
if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
}
+460
View File
@@ -0,0 +1,460 @@
/* rad_block_gemma4_audio.h -- Gemma 4's audio encoder (USM conformer), shared by the plugins whose
* checkpoints carry it: EmbeddingGemma 2 (embgemma2) and Gemma 4 E2B/E4B (gemma4_bf16).
*
* a frame is 128 log-mel bins (the processor's), four frames an output row
* subsampling: two 3x3 stride-2 convolutions over (time, frequency) -- 1 -> 128 -> 32 channels,
* each input masked to the clip's real frames first, each followed by a channel LayerNorm (no
* bias) and a ReLU -- then 32 x 32 features a row through a 1024 linear
* 12 conformer blocks: a feed-forward at half weight, local attention (11 frames back, a
* relative-position term, a softplus per-dimension query scale, a softcap of 50), a gated
* depthwise causal convolution, a second half-weight feed-forward, a norm; their linears are
* clipped: input and output clamped to bounds the checkpoint stores
* 1024 -> 1536 with a bias, then the multimodal embedder: an RMS norm with no gain, 1536 -> the
* text model's width.
*
* The blocks' clamps at +-1e10 ("gradient clipping") are omitted: they are ten orders of magnitude
* beyond the activations' range and change nothing. One clip is one segment; a pass carries up to
* RadBuildCtx::max_audio_frames frames. */
#ifndef RAD_BLOCK_GEMMA4_AUDIO_H
#define RAD_BLOCK_GEMMA4_AUDIO_H
#include "rad_arch.h"
#include <cstdio>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct Gemma4Audio {
/* A clipped linear: the weight and its four bounds. */
struct Clip {
rad_weight w = 0, in_lo = 0, in_hi = 0, out_lo = 0, out_hi = 0;
rad_op op_in = 0, op_mm = 0, op_out = 0;
};
struct FF {
rad_weight pre = 0, post = 0;
Clip l1, l2;
rad_op op_pre = 0, op_act = 0, op_post = 0, op_add = 0;
};
struct Layer {
FF ff1, ff2;
rad_weight n_pre_attn = 0, n_post_attn = 0, n_out = 0, w_rel = 0, pds = 0;
Clip q, k, v, post;
rad_weight lc_pre = 0, lc_dw = 0, lc_norm = 0;
Clip lc_start, lc_end;
rad_op op_npa = 0, op_rel = 0, op_attn = 0, op_npo = 0, op_add_attn = 0;
rad_op op_lc_pre = 0, op_glu = 0, op_dw = 0, op_lc_norm = 0, op_lc_act = 0, op_lc_add = 0;
rad_op op_out = 0;
};
bool on = false;
int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffw = 0, n_embd = 0, out_dims = 0;
int64_t c0 = 0, c1 = 0, nmel = 0, merge = 4, left = 0, chunk = 0, n_rel = 0;
double eps = 1e-6, softcap = 0;
rad_weight w_c0 = 0, w_c1 = 0, w_n0 = 0, w_n1 = 0, w_in = 0, w_out = 0, b_outw = 0, w_emb = 0;
rad_op op_c0 = 0, op_n0 = 0, op_r0 = 0, op_c1 = 0, op_n1 = 0, op_r1 = 0, op_in = 0;
rad_op op_relpos = 0, op_outp = 0, op_en = 0, op_emb = 0;
rad_buf b_s0 = 0, b_s1 = 0, b_x = 0, b_h = 0, b_hc = 0, b_f = 0, b_q = 0, b_k = 0, b_v = 0;
rad_buf b_att = 0, b_o = 0, b_g = 0, b_u = 0, b_relpos = 0, b_relk = 0, b_o2 = 0, b_on = 0;
rad_buf b_out = 0;
std::vector<Layer> L;
/* A feature-extractor key: preprocessor_config.json's (`preprocessor.`), else
* processor_config.json's `feature_extractor` object (`processor.feature_extractor.`). */
static int64_t fe_i(const RadModelMeta* m, const char* k, int64_t d) {
char a[96], b[128];
std::snprintf(a, sizeof a, "preprocessor.%s", k);
std::snprintf(b, sizeof b, "processor.feature_extractor.%s", k);
return rad_meta_geti(m, a, rad_meta_geti(m, b, d));
}
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
return t && !std::strcmp(t, "gemma4_audio");
}
/* The longest clip in frames: 30 s at the extractor's 10 ms hop, rounded up to whole rows. */
static int64_t frames_for(const RadModelMeta* m) {
const int64_t rate = fe_i(m, "sampling_rate", 16000);
const int64_t fl = fe_i(m, "frame_length", 320);
const int64_t hop = fe_i(m, "hop_length", 160);
if (rate <= 0 || hop <= 0) return 0;
const int64_t n = 30 * rate;
const int64_t real = (n + fl / 2 - fl - 1) / hop + 1;
return (real + 3) / 4 * 4;
}
/* `pre` is the checkpoint prefix of the encoder and its embedder ("model." for Gemma 4's
* conditional-generation checkpoints, "" for EmbeddingGemma 2); `who` names the plugin in
* refusals. The encoder's layers take weight groups from `first_group`. */
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group, const char* pre, const char* who) {
on = false;
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
const char* A = "audio_config";
auto gi = [&](const char* k, int64_t d) {
char key[96];
std::snprintf(key, sizeof key, "%s.%s", A, k);
return rad_meta_geti(m, key, d);
};
auto gf = [&](const char* k, double d) {
char key[96];
std::snprintf(key, sizeof key, "%s.%s", A, k);
return rad_meta_getf(m, key, d);
};
H = gi("hidden_size", 0);
heads = gi("num_attention_heads", 0);
out_dims = gi("output_proj_dims", 0);
chunk = gi("attention_chunk_size", 0);
/* transformers masks a key unless 0 <= q - k < attention_context_left - 1, so the
* furthest key back is context_left - 2 frames: 11 for this checkpoint, the query and
* eleven before it. */
left = gi("attention_context_left", 0) - 2;
softcap = gf("attention_logit_cap", 0.0);
eps = gf("rms_norm_eps", 1e-6);
const int64_t depth = gi("num_hidden_layers", 0);
const int64_t kconv = gi("conv_kernel_size", 0);
const int64_t right = gi("attention_context_right", 0);
const double resw = gf("residual_weight", 0.0);
const char* act = rad_meta_gets(m, "audio_config.hidden_act", "");
const char* chs = rad_meta_gets(m, "audio_config.subsampling_conv_channels", "");
nmel = fe_i(m, "feature_size", 0);
if (std::sscanf(chs ? chs : "", "%lld %lld", (long long*)&c0, (long long*)&c1) != 2)
c0 = c1 = 0;
hd = heads > 0 ? H / heads : 0;
ffw = 4 * H;
n_rel = left + 1;
if (H <= 0 || heads <= 0 || hd * heads != H || out_dims <= 0 || depth <= 0 || kconv <= 0 ||
chunk <= 0 || left < 0 || right != 0 || !(softcap > 0) || resw != 0.5 ||
std::strcmp(act ? act : "", "silu") || c0 <= 0 || c1 <= 0 || nmel != 128 ||
(nmel / 4) * c1 != H) {
fprintf(stderr, "radiance: %s: the container's audio_config is not the "
"conformer this plugin serves (hidden %lld, heads %lld, output %lld, "
"layers %lld, conv %lld, left %lld right %lld, residual %g, act %s, "
"subsampling %lld/%lld over %lld bins)\n", who, (long long)H,
(long long)heads, (long long)out_dims, (long long)depth, (long long)kconv,
(long long)left, (long long)right, resw, act ? act : "", (long long)c0,
(long long)c1, (long long)nmel);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
P = ctx->max_audio_frames;
if (P % merge) return RAD_E_SHAPE;
R = P / merge;
const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
char T[64];
std::snprintf(T, sizeof T, "%saudio_tower", pre);
/* ---- weights */
auto w = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
RadWeightGroup g) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
};
auto clip = [&](Clip& c, const char* dn, const char* src, int64_t out, int64_t in,
RadWeightGroup g) {
char d1[160], s1[200];
std::snprintf(d1, sizeof d1, "%s.w", dn); std::snprintf(s1, sizeof s1, "%s.linear.weight", src);
c.w = w(nm.f("%s", d1), nm.ckpt("%s", s1), {out, in}, g);
const char* bn[4] = { "input_min", "input_max", "output_min", "output_max" };
rad_weight* dst[4] = { &c.in_lo, &c.in_hi, &c.out_lo, &c.out_hi };
for (int i = 0; i < 4; ++i) {
std::snprintf(d1, sizeof d1, "%s.%s", dn, bn[i]);
std::snprintf(s1, sizeof s1, "%s.%s", src, bn[i]);
*dst[i] = w(nm.f("%s", d1), nm.ckpt("%s", s1), {1}, g);
}
};
w_c0 = w(nm.f("a.sscp.c0"), nm.ckpt("%s.subsample_conv_projection.layer0.conv.weight", T), {c0, 1, 3, 3}, grp_model());
w_n0 = w(nm.f("a.sscp.n0"), nm.ckpt("%s.subsample_conv_projection.layer0.norm.weight", T), {c0}, grp_model());
w_c1 = w(nm.f("a.sscp.c1"), nm.ckpt("%s.subsample_conv_projection.layer1.conv.weight", T), {c1, c0, 3, 3}, grp_model());
w_n1 = w(nm.f("a.sscp.n1"), nm.ckpt("%s.subsample_conv_projection.layer1.norm.weight", T), {c1}, grp_model());
w_in = w(nm.f("a.sscp.proj"), nm.ckpt("%s.subsample_conv_projection.input_proj_linear.weight", T), {H, H}, grp_model());
w_out = w(nm.f("a.out.w"), nm.ckpt("%s.output_proj.weight", T), {out_dims, H}, grp_model());
b_outw = w(nm.f("a.out.b"), nm.ckpt("%s.output_proj.bias", T), {out_dims}, grp_model());
w_emb = w(nm.f("a.embed"), nm.ckpt("%sembed_audio.embedding_projection.weight", pre), {n_embd, out_dims}, grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const long long li = (long long)i;
const RadWeightGroup g = grp_layer(first_group + (int)i);
char d[96], s[160];
auto D = [&](const char* x) { std::snprintf(d, sizeof d, "a.blk.%lld.%s", li, x); return nm.f("%s", d); };
auto S = [&](const char* x) { std::snprintf(s, sizeof s, "%s.layers.%lld.%s", T, li, x); return nm.ckpt("%s", s); };
for (int f = 0; f < 2; ++f) {
FF& ff = f ? l.ff2 : l.ff1;
const char* fn = f ? "feed_forward2" : "feed_forward1";
char px[64]; std::snprintf(px, sizeof px, "%s.pre_layer_norm.weight", fn);
ff.pre = w(D(px), S(px), {H}, g);
std::snprintf(px, sizeof px, "%s.post_layer_norm.weight", fn);
ff.post = w(D(px), S(px), {H}, g);
char dn[96], sn[160];
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l1", li, fn);
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_1", T, li, fn);
clip(ff.l1, dn, sn, ffw, H, g);
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l2", li, fn);
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_2", T, li, fn);
clip(ff.l2, dn, sn, H, ffw, g);
}
l.n_pre_attn = w(D("norm_pre_attn"), S("norm_pre_attn.weight"), {H}, g);
l.n_post_attn = w(D("norm_post_attn"), S("norm_post_attn.weight"), {H}, g);
l.n_out = w(D("norm_out"), S("norm_out.weight"), {H}, g);
l.w_rel = w(D("rel_k"), S("self_attn.relative_k_proj.weight"), {H, H}, g);
l.pds = w(D("per_dim_scale"), S("self_attn.per_dim_scale"), {hd}, g);
const char* qn[4] = { "q_proj", "k_proj", "v_proj", "post" };
Clip* qc[4] = { &l.q, &l.k, &l.v, &l.post };
for (int j = 0; j < 4; ++j) {
char dn[96], sn[160];
std::snprintf(dn, sizeof dn, "a.blk.%lld.attn.%s", li, qn[j]);
std::snprintf(sn, sizeof sn, "%s.layers.%lld.self_attn.%s", T, li, qn[j]);
clip(*qc[j], dn, sn, H, H, g);
}
l.lc_pre = w(D("lconv.pre"), S("lconv1d.pre_layer_norm.weight"), {H}, g);
l.lc_dw = w(D("lconv.dw"), S("lconv1d.depthwise_conv1d.weight"), {H, 1, kconv}, g);
l.lc_norm = w(D("lconv.norm"), S("lconv1d.conv_norm.weight"), {H}, g);
{
char dn[96], sn[160];
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.start", li);
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_start", T, li);
clip(l.lc_start, dn, sn, 2 * H, H, g);
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.end", li);
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_end", T, li);
clip(l.lc_end, dn, sn, H, H, g);
}
}
/* ---- activations: the subsampler's planes at their own widths, the blocks' at R rows */
b_s0 = decl_b(b, nm.f("a.s0"), RAD_BF16, {P / 2, (nmel / 2) * c0});
b_s1 = decl_b(b, nm.f("a.s1"), RAD_BF16, {R, (nmel / 4) * c1});
b_x = decl_b(b, nm.f("a.x"), RAD_BF16, {R, H});
b_h = decl_b(b, nm.f("a.h"), RAD_BF16, {R, H});
b_hc = decl_b(b, nm.f("a.hc"), RAD_BF16, {R, H});
b_f = decl_b(b, nm.f("a.f"), RAD_BF16, {R, ffw});
b_q = decl_b(b, nm.f("a.q"), RAD_BF16, {R, H});
b_k = decl_b(b, nm.f("a.k"), RAD_BF16, {R, H});
b_v = decl_b(b, nm.f("a.v"), RAD_BF16, {R, H});
b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H});
b_o = decl_b(b, nm.f("a.o"), RAD_BF16, {R, H});
b_g = decl_b(b, nm.f("a.g"), RAD_BF16, {R, 2 * H});
b_u = decl_b(b, nm.f("a.u"), RAD_BF16, {R, H});
b_relpos = decl_b(b, nm.f("a.relpos"), RAD_BF16, {n_rel, H});
b_relk = decl_b(b, nm.f("a.relk"), RAD_BF16, {n_rel, H});
b_o2 = decl_b(b, nm.f("a.o2"), RAD_BF16, {R, out_dims});
b_on = decl_b(b, nm.f("a.on"), RAD_BF16, {R, out_dims});
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd});
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight wt) {
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(wt));
};
auto rms = [&](int64_t rows, int64_t n, rad_weight wt, double mult) {
if (!wt)
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16"), RAD_F64("mult", mult)),
RAD_WEIGHTS(wt));
};
auto clamp = [&](int64_t rows, int64_t n, rad_weight lo, rad_weight hi) {
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(lo, hi));
};
auto unary = [&](const char* op, int64_t rows, int64_t n) {
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
auto add = [&](int64_t rows, int64_t n) { return unary("add", rows, n); };
auto lnorm = [&](int64_t rows, int64_t n, rad_weight g) {
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(g));
};
auto conv = [&](int64_t rows, int64_t width, int64_t ci, int64_t co, int64_t cu_div,
int64_t vstride, rad_weight wt) {
return RAD_OP(b, "conv2d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width),
RAD_INT("cin", ci), RAD_INT("cout", co),
RAD_INT("kh", 3), RAD_INT("kw", 3),
RAD_INT("stride", 2), RAD_INT("pad", 1),
RAD_INT("cu_div", cu_div),
RAD_INT("valid_stride", vstride),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(wt));
};
/* A clipped linear over rows of `in` into `out`: the input clamp writes a copy (the input
* feeds several projections, each with its own bounds), the output clamp is in place. The
* copy is a whole [R, n_in] buffer, since a GEMM's input must be contiguous. */
auto clipped = [&](Clip& c, int64_t n_out, int64_t n_in, rad_buf in, rad_buf tmp,
rad_buf out) {
c.op_in = rw(b, clamp(R, n_in, c.in_lo, c.in_hi), {in}, {tmp});
c.op_mm = rw(b, gemm(R, n_out, n_in, c.w), {tmp}, {out});
c.op_out = rw(b, clamp(R, n_out, c.out_lo, c.out_hi), {out}, {out});
};
op_c0 = rw(b, conv(P, nmel, 1, c0, 1, 1, w_c0), {}, {b_s0});
op_n0 = rw(b, lnorm(P / 2 * (nmel / 2), c0, w_n0), {b_s0}, {b_s0});
op_r0 = rw(b, unary("relu", P / 2 * (nmel / 2), c0), {b_s0}, {b_s0});
op_c1 = rw(b, conv(P / 2, nmel / 2, c0, c1, 2, 2, w_c1), {b_s0}, {b_s1});
op_n1 = rw(b, lnorm(R * (nmel / 4), c1, w_n1), {b_s1}, {b_s1});
op_r1 = rw(b, unary("relu", R * (nmel / 4), c1), {b_s1}, {b_s1});
op_in = rw(b, gemm(R, H, H, w_in), {b_s1}, {b_x});
op_relpos = rw(b, RAD_OP(b, "rel_sinusoid",
RAD_PARAMS(RAD_RANGE("M", 1, n_rel), RAD_INT("n", H),
RAD_F64("max_timescale", 10000.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{}, {b_relpos});
for (Layer& l : L) {
auto ffw_block = [&](FF& ff) {
ff.op_pre = rw(b, rms(R, H, ff.pre, 1.0), {b_x}, {b_h});
clipped(ff.l1, ffw, H, b_h, b_hc, b_f);
ff.op_act = rw(b, unary("silu", R, ffw), {b_f}, {b_f});
/* the activation's only reader is this linear, so its clamp is in place */
clipped(ff.l2, H, ffw, b_f, b_f, b_o);
ff.op_post = rw(b, rms(R, H, ff.post, 0.5), {b_o}, {b_o});
ff.op_add = rw(b, add(R, H), {b_x, b_o}, {b_x});
};
ffw_block(l.ff1);
l.op_npa = rw(b, rms(R, H, l.n_pre_attn, 1.0), {b_x}, {b_h});
clipped(l.q, H, H, b_h, b_hc, b_q);
clipped(l.k, H, H, b_h, b_hc, b_k);
clipped(l.v, H, H, b_h, b_hc, b_v);
l.op_rel = rw(b, gemm(n_rel, H, H, l.w_rel), {b_relpos}, {b_relk});
l.op_attn = rw(b, RAD_OP(b, "attn_local_rel",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd),
RAD_INT("n_head", heads), RAD_INT("left", left),
RAD_INT("right", 0), RAD_F64("softcap", softcap),
RAD_INT("cu_div", merge), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(l.pds)),
{b_q, b_k, b_v, b_relk}, {b_att});
clipped(l.post, H, H, b_att, b_hc, b_o);
l.op_npo = rw(b, rms(R, H, l.n_post_attn, 1.0), {b_o}, {b_o});
l.op_add_attn = rw(b, add(R, H), {b_x, b_o}, {b_x});
l.op_lc_pre = rw(b, rms(R, H, l.lc_pre, 1.0), {b_x}, {b_h});
clipped(l.lc_start, 2 * H, H, b_h, b_hc, b_g);
/* GLU: the first half times the sigmoid of the second. */
l.op_glu = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_g}, {b_u});
l.op_dw = rw(b, RAD_OP(b, "conv1d_dw",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
RAD_INT("k", kconv), RAD_INT("cu_div", merge),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(l.lc_dw)),
{b_u}, {b_o});
l.op_lc_norm = rw(b, rms(R, H, l.lc_norm, 1.0), {b_o}, {b_o});
l.op_lc_act = rw(b, unary("silu", R, H), {b_o}, {b_o});
clipped(l.lc_end, H, H, b_o, b_hc, b_u);
l.op_lc_add = rw(b, add(R, H), {b_x, b_u}, {b_x});
ffw_block(l.ff2);
l.op_out = rw(b, rms(R, H, l.n_out, 1.0), {b_x}, {b_x});
}
op_outp = rw(b, RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", out_dims),
RAD_INT("K", H), RAD_STR("dtype", "bf16"),
RAD_STR("act", "none")),
RAD_WEIGHTS(w_out, b_outw)),
{b_x}, {b_o2});
op_en = rw(b, rms(R, out_dims, 0, 1.0), {b_o2}, {b_on});
op_emb = rw(b, gemm(R, n_embd, out_dims, w_emb), {b_on}, {b_out});
RadEncoderDecl e{};
e.name = "audio";
e.modalities = RAD_MM_AUDIO;
e.patch_dim = nmel;
e.merge = merge;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "audio encoder: %lld conformer blocks of %lld (%lld heads x %lld), "
"subsampling %lld/%lld channels, local attention %lld back; %lld frames a "
"pass -> %lld rows of %lld", (long long)depth, (long long)H, (long long)heads,
(long long)hd, (long long)c0, (long long)c1, (long long)left, (long long)P,
(long long)R, (long long)n_embd);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
if (!on || Pn <= 0 || Pn > P || Pn % merge || S <= 0) {
rad_step_fail(c, "an audio pass this program's audio encoder cannot serve: none "
"declared, more frames than it was declared for, or not whole rows");
return;
}
const int64_t Rn = Pn / merge;
const int32_t* crd = batch->enc_coord;
const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel);
const RadOperand valid = praw(crd + Pn, RAD_I32, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
auto clipped = [&](const Clip& cl, rad_buf in, int64_t n_in, rad_buf tmp, rad_buf out,
int64_t n_out) {
RAD_ISSUE_N(c, cl.op_in, Rn, bcol(in, 0, n_in, Rn), RAD_W(cl.in_lo), RAD_W(cl.in_hi),
bcol(tmp, 0, n_in, Rn));
RAD_ISSUE_N(c, cl.op_mm, Rn, bcol(tmp, 0, n_in, Rn), RAD_W(cl.w), bcol(out, 0, n_out, Rn));
RAD_ISSUE_N(c, cl.op_out, Rn, bcol(out, 0, n_out, Rn), RAD_W(cl.out_lo), RAD_W(cl.out_hi),
bcol(out, 0, n_out, Rn));
};
RAD_ISSUE_N(c, op_c0, Pn, frames, RAD_W(w_c0), cu, valid, brows(b_s0, Pn / 2), RAD_NONE);
RAD_ISSUE_N(c, op_n0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), RAD_W(w_n0), RAD_NONE,
brows(b_s0, Pn / 2));
RAD_ISSUE_N(c, op_r0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), brows(b_s0, Pn / 2));
RAD_ISSUE_N(c, op_c1, Pn / 2, brows(b_s0, Pn / 2), RAD_W(w_c1), cu, valid, brows(b_s1, Rn),
RAD_NONE);
RAD_ISSUE_N(c, op_n1, Rn * (nmel / 4), brows(b_s1, Rn), RAD_W(w_n1), RAD_NONE,
brows(b_s1, Rn));
RAD_ISSUE_N(c, op_r1, Rn * (nmel / 4), brows(b_s1, Rn), brows(b_s1, Rn));
RAD_ISSUE_N(c, op_in, Rn, brows(b_s1, Rn), RAD_W(w_in), brows(b_x, Rn));
RAD_ISSUE_N(c, op_relpos, n_rel, brows(b_relpos, n_rel));
for (const Layer& l : L) {
auto ffw_block = [&](const FF& ff) {
RAD_ISSUE_N(c, ff.op_pre, Rn, brows(b_x, Rn), RAD_W(ff.pre), brows(b_h, Rn));
clipped(ff.l1, b_h, H, b_hc, b_f, ffw);
RAD_ISSUE_N(c, ff.op_act, Rn, brows(b_f, Rn), brows(b_f, Rn));
clipped(ff.l2, b_f, ffw, b_f, b_o, H);
RAD_ISSUE_N(c, ff.op_post, Rn, brows(b_o, Rn), RAD_W(ff.post), brows(b_o, Rn));
RAD_ISSUE_N(c, ff.op_add, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
};
ffw_block(l.ff1);
RAD_ISSUE_N(c, l.op_npa, Rn, brows(b_x, Rn), RAD_W(l.n_pre_attn), brows(b_h, Rn));
clipped(l.q, b_h, H, b_hc, b_q, H);
clipped(l.k, b_h, H, b_hc, b_k, H);
clipped(l.v, b_h, H, b_hc, b_v, H);
RAD_ISSUE_N(c, l.op_rel, n_rel, brows(b_relpos, n_rel), RAD_W(l.w_rel),
brows(b_relk, n_rel));
RAD_ISSUE_N(c, l.op_attn, Rn, brows(b_q, Rn), brows(b_k, Rn), brows(b_v, Rn),
brows(b_relk, n_rel), RAD_W(l.pds), cu, brows(b_att, Rn));
clipped(l.post, b_att, H, b_hc, b_o, H);
RAD_ISSUE_N(c, l.op_npo, Rn, brows(b_o, Rn), RAD_W(l.n_post_attn), brows(b_o, Rn));
RAD_ISSUE_N(c, l.op_add_attn, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
RAD_ISSUE_N(c, l.op_lc_pre, Rn, brows(b_x, Rn), RAD_W(l.lc_pre), brows(b_h, Rn));
clipped(l.lc_start, b_h, H, b_hc, b_g, 2 * H);
RAD_ISSUE_N(c, l.op_glu, Rn, bcol(b_g, H, H, Rn), bcol(b_g, 0, H, Rn), brows(b_u, Rn));
RAD_ISSUE_N(c, l.op_dw, Rn, brows(b_u, Rn), RAD_W(l.lc_dw), cu, brows(b_o, Rn),
RAD_NONE);
RAD_ISSUE_N(c, l.op_lc_norm, Rn, brows(b_o, Rn), RAD_W(l.lc_norm), brows(b_o, Rn));
RAD_ISSUE_N(c, l.op_lc_act, Rn, brows(b_o, Rn), brows(b_o, Rn));
clipped(l.lc_end, b_o, H, b_hc, b_u, H);
RAD_ISSUE_N(c, l.op_lc_add, Rn, brows(b_x, Rn), brows(b_u, Rn), brows(b_x, Rn));
ffw_block(l.ff2);
RAD_ISSUE_N(c, l.op_out, Rn, brows(b_x, Rn), RAD_W(l.n_out), brows(b_x, Rn));
}
RAD_ISSUE_N(c, op_outp, Rn, brows(b_x, Rn), RAD_W(w_out), RAD_W(b_outw), RAD_NONE,
brows(b_o2, Rn));
RAD_ISSUE_N(c, op_en, Rn, brows(b_o2, Rn), RAD_NONE, brows(b_on, Rn));
RAD_ISSUE_N(c, op_emb, Rn, brows(b_on, Rn), RAD_W(w_emb), brows(b_out, Rn));
}
};
} /* namespace arch */
} /* namespace rad */
#endif
+263
View File
@@ -0,0 +1,263 @@
/* rad_block_gemma4_unified.h -- the media embedders of Gemma 4 12B ("unified", transformers'
* Gemma4UnifiedVisionEmbedder and the audio Gemma4UnifiedMultimodalEmbedder), served by gemma4_bf16.
* Neither has an encoder: the language model sees each patch or audio frame after a few norms and
* linears.
*
* image: a patch is 48 x 48 x 3 (3 x 3 of the processor's 16-pixel patches), staged by the core's
* Gemma 4 processor as u / 255 in bf16, (y, x, channel); a LayerNorm over the patch, a linear with
* a bias, a LayerNorm, plus a learned row for the patch's column and one for its row (the
* checkpoint's [npos, 2, width] table, read as its two taps of dimension 1), a LayerNorm, then the
* multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. The LayerNorms are
* nn.LayerNorm's default eps 1e-5, which no config states. One patch is one row.
* audio: a frame is 640 samples at 16 kHz as they are, the last zero-padded, in bf16; an RMS norm
* with no gain and a 640 -> n_embd linear. One frame is one row.
*
* Their rows replace the placeholders' embeddings unscaled, as the vision tower's do. Every rank
* runs them whole (RAD_SHARD_NONE). */
#ifndef RAD_BLOCK_GEMMA4_UNIFIED_H
#define RAD_BLOCK_GEMMA4_UNIFIED_H
#include "rad_arch.h"
#include <cstdio>
#include <cstring>
namespace rad {
namespace arch {
struct Gemma4UnifiedVision {
bool on = false;
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
* plugin sets it before declare. */
bool bidirectional = false;
int64_t P = 0, width = 0, patch_dim = 0, npos = 0, n_embd = 0;
rad_weight w_ln1 = 0, w_ln1b = 0, w_in = 0, w_inb = 0, w_ln2 = 0, w_ln2b = 0, w_px = 0, w_py = 0;
rad_weight w_pn = 0, w_pnb = 0, w_proj = 0;
rad_op op_ln1 = 0, op_in = 0, op_ln2 = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0;
rad_op op_pn = 0, op_norm = 0, op_out = 0;
rad_buf b_n = 0, b_x = 0, b_h = 0, b_px = 0, b_py = 0, b_out = 0;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
return t && !std::strcmp(t, "gemma4_unified_vision");
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, const char* who) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
width = rad_meta_geti(m, "vision_config.mm_embed_dim", 0);
npos = rad_meta_geti(m, "vision_config.mm_posemb_size", 0);
const int64_t side = rad_meta_geti(m, "vision_config.model_patch_size", 0);
const int64_t outd = rad_meta_geti(m, "vision_config.output_proj_dims", width);
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
if (width <= 0 || npos <= 0 || side <= 0 || outd != width) {
fprintf(stderr, "radiance: %s: the container's vision_config is incomplete or not the "
"embedder this plugin serves (mm_embed_dim %lld, mm_posemb_size %lld, "
"model_patch_size %lld, output_proj_dims %lld)\n", who,
(long long)width, (long long)npos, (long long)side, (long long)outd);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
patch_dim = 3 * side * side;
P = ctx->max_enc_patches;
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
const char* V = "model.vision_embedder";
struct { const char* to; const char* from; } cp[] = {
{ "v.ln1.weight", "patch_ln1.weight" }, { "v.ln1.bias", "patch_ln1.bias" },
{ "v.in.weight", "patch_dense.weight" }, { "v.in.bias", "patch_dense.bias" },
{ "v.ln2.weight", "patch_ln2.weight" }, { "v.ln2.bias", "patch_ln2.bias" },
{ "v.pn.weight", "pos_norm.weight" }, { "v.pn.bias", "pos_norm.bias" } };
for (const auto& e : cp)
RAD_ARCH_TRY(map_copy(b, nm.f("%s", e.to), nm.ckpt("%s.%s", V, e.from)));
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_x.weight"), nm.ckpt("%s.pos_embedding", V), 1, 0));
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_y.weight"), nm.ckpt("%s.pos_embedding", V), 1, 1));
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight")));
w_ln1 = decl_w(b, nm.f("v.ln1.weight"), RAD_BF16, {patch_dim}, A, N, grp_model());
w_ln1b = decl_w(b, nm.f("v.ln1.bias"), RAD_BF16, {patch_dim}, A, N, grp_model());
w_in = decl_w(b, nm.f("v.in.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
w_inb = decl_w(b, nm.f("v.in.bias"), RAD_BF16, {width}, A, N, grp_model());
w_ln2 = decl_w(b, nm.f("v.ln2.weight"), RAD_BF16, {width}, A, N, grp_model());
w_ln2b = decl_w(b, nm.f("v.ln2.bias"), RAD_BF16, {width}, A, N, grp_model());
w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_pn = decl_w(b, nm.f("v.pn.weight"), RAD_BF16, {width}, A, N, grp_model());
w_pnb = decl_w(b, nm.f("v.pn.bias"), RAD_BF16, {width}, A, N, grp_model());
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
b_n = decl_b(b, nm.f("v.n"), RAD_BF16, {P, patch_dim});
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width});
b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width});
b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width});
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {P, n_embd});
auto ln = [&](int64_t n, rad_weight w, rad_weight bias) {
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
auto lookup = [&](rad_weight w) {
return RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
RAD_WEIGHTS(w));
};
auto add = [&]() {
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
op_ln1 = rw(b, ln(patch_dim, w_ln1, w_ln1b), {}, {b_n});
op_in = rw(b, RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16"),
RAD_STR("act", "none")),
RAD_WEIGHTS(w_in, w_inb)),
{b_n}, {b_x});
op_ln2 = rw(b, ln(width, w_ln2, w_ln2b), {b_x}, {b_h});
op_px = rw(b, lookup(w_px), {}, {b_px});
op_py = rw(b, lookup(w_py), {}, {b_py});
op_padd = rw(b, add(), {b_px, b_py}, {b_px});
op_add = rw(b, add(), {b_h, b_px}, {b_h});
op_pn = rw(b, ln(width, w_pn, w_pnb), {b_h}, {b_x});
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_x}, {b_h});
op_out = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
RAD_INT("K", width), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_proj)),
{b_h}, {b_out});
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = 1;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.bidirectional = bidirectional ? 1 : 0;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision embedder (no tower): %lldx%lld patches of %lld values -> %lld, "
"positions %lld a side; %lld patches a pass -> %lld rows of %lld",
(long long)side, (long long)side, (long long)patch_dim, (long long)width,
(long long)npos, (long long)P, (long long)P, (long long)n_embd);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch;
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
rad_step_fail(c, "an encoder pass this program's vision embedder cannot serve: none "
"declared, or more patches than it was declared for");
return;
}
const int32_t* crd = batch->enc_coord;
RAD_ISSUE_N(c, op_ln1, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim), RAD_W(w_ln1),
RAD_W(w_ln1b), brows(b_n, Pn));
RAD_ISSUE_N(c, op_in, Pn, brows(b_n, Pn), RAD_W(w_in), RAD_W(w_inb), RAD_NONE, brows(b_x, Pn));
RAD_ISSUE_N(c, op_ln2, Pn, brows(b_x, Pn), RAD_W(w_ln2), RAD_W(w_ln2b), brows(b_h, Pn));
RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
RAD_ISSUE_N(c, op_add, Pn, brows(b_h, Pn), brows(b_px, Pn), brows(b_h, Pn));
RAD_ISSUE_N(c, op_pn, Pn, brows(b_h, Pn), RAD_W(w_pn), RAD_W(w_pnb), brows(b_x, Pn));
RAD_ISSUE_N(c, op_norm, Pn, brows(b_x, Pn), RAD_NONE, brows(b_h, Pn));
RAD_ISSUE_N(c, op_out, Pn, brows(b_h, Pn), RAD_W(w_proj), brows(b_out, Pn));
}
};
struct Gemma4UnifiedAudio {
bool on = false;
int64_t P = 0, frame = 0, n_embd = 0;
rad_weight w_proj = 0;
rad_op op_norm = 0, op_out = 0;
rad_buf b_n = 0, b_out = 0;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
return t && !std::strcmp(t, "gemma4_unified_audio");
}
/* Samples a frame: the extractor's audio_samples_per_token, else the embedder's input width. */
static int64_t frame_for(const RadModelMeta* m) {
return rad_meta_geti(m, "processor.feature_extractor.audio_samples_per_token",
rad_meta_geti(m, "audio_config.audio_embed_dim", 0));
}
/* The longest clip in frames: processor_config.json's audio_seq_length, else 30 s. */
static int64_t frames_for(const RadModelMeta* m) {
const int64_t f = frame_for(m);
const int64_t rate = rad_meta_geti(m, "processor.feature_extractor.sampling_rate", 16000);
if (f <= 0 || rate <= 0) return 0;
return rad_meta_geti(m, "processor.audio_seq_length", (30 * rate + f - 1) / f);
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, const char* who) {
on = false;
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
frame = frame_for(m);
const int64_t width = rad_meta_geti(m, "audio_config.audio_embed_dim", 0);
const double eps = rad_meta_getf(m, "audio_config.rms_norm_eps", 1e-6);
if (frame <= 0 || width != frame) {
fprintf(stderr, "radiance: %s: the container's audio frame (%lld samples) is not the "
"embedder's input (audio_embed_dim %lld)\n", who, (long long)frame,
(long long)width);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
P = ctx->max_audio_frames;
RAD_ARCH_TRY(map_copy(b, nm.f("a.embed.weight"), nm.ckpt("model.embed_audio.embedding_projection.weight")));
w_proj = decl_w(b, nm.f("a.embed.weight"), RAD_BF16, {n_embd, frame}, RAD_ACCESS_PER_REQUEST,
RAD_SHARD_NONE, grp_model());
b_n = decl_b(b, nm.f("a.n"), RAD_BF16, {P, frame});
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {P, n_embd});
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", frame),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{}, {b_n});
op_out = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
RAD_INT("K", frame), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_proj)),
{b_n}, {b_out});
RadEncoderDecl e{};
e.name = "audio";
e.modalities = RAD_MM_AUDIO;
e.patch_dim = frame;
e.merge = 1;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "audio embedder (no encoder): frames of %lld samples -> %lld; %lld frames a pass",
(long long)frame, (long long)n_embd, (long long)P);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch;
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
rad_step_fail(c, "an audio pass this program's audio embedder cannot serve: none "
"declared, or more frames than it was declared for");
return;
}
RAD_ISSUE_N(c, op_norm, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, frame), RAD_NONE,
brows(b_n, Pn));
RAD_ISSUE_N(c, op_out, Pn, brows(b_n, Pn), RAD_W(w_proj), brows(b_out, Pn));
}
};
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_GEMMA4_UNIFIED_H */
+403
View File
@@ -0,0 +1,403 @@
/* rad_block_gemma4_vision.h -- Gemma 4's vision tower (transformers' Gemma4VisionModel), served by
* gemma4_bf16 (the 31B's tower: 27 layers of width 1152) and embgemma2 (16 layers of width 768).
*
* a patch is 16 x 16 x 3, staged by the core's Gemma 4 processor as 2 * (u / 255) - 1 in bf16,
* (y, x, channel); patch embedding a [width, 768] linear plus a learned row for the patch's
* column and one for its row (a [2, npos, width] table), the two summed first
* layers: sandwich norms (gain w, not 1 + w), q/k RMS-normed with a gain and v without one, a
* 2-D rotary over two neox blocks of a head -- x (the column) over the first, y over the second,
* each block at theta^(-j / (hd / 4)) (rope_type "default"; EmbeddingGemma 2 spells the same
* rotary "axial") -- bidirectional attention within an image at scale 1, a gated gelu-tanh MLP
* pooling: the mean of each pool x pool window times sqrt(width) (the processor lays a window's
* patches out consecutively, raster order of windows, as the reference's position pooling)
* standardisation (vision_config.standardize), when set: (z - std_bias) * std_scale per channel.
* The reference does it in f32 because a few channels carry ~5e4 with a bias that cancels them;
* here z is the pooler's bf16 row, so those channels keep bf16's spacing at that magnitude
* (about 1e-2 after the scale). The bias row is made on the card: fill(-1) times std_bias, added
* to z, then times std_scale.
* the multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. Its rows
* replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the
* image rows are not scaled).
*
* Clipped linears (vision_config.use_clipped_linears, Gemma 4 E2B/E4B): every projection clamps its
* input and its output to bounds the checkpoint stores (`<proj>.input_min/max`, `output_min/max`;
* transformers' Gemma4ClippableLinear). The tower keeps its fused q|k|v and gate|up GEMMs, so it
* takes the input bounds of q_proj (and of gate_proj) for the fused input, q_proj's output bounds for
* q's columns, k_proj's for k's and v's, and gate_proj's output bounds for gate|up. That is exact
* where the fused parts share their bounds, as NVIDIA's E4B does in all 16 layers (k and v share the
* input bounds of q and their output bounds, up shares gate's). The bound weights are one bf16
* element each, read by `clamp`.
*
* One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an
* image, or one frame of a video). Every rank runs the whole tower (engine_mm.cpp), so its weights
* are replicated (RAD_SHARD_NONE) and each rank writes the rows into its own copy of the embedding
* stream. */
#ifndef RAD_BLOCK_GEMMA4_VISION_H
#define RAD_BLOCK_GEMMA4_VISION_H
#include "rad_arch.h"
#include <cmath>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct Gemma4Vision {
struct Layer {
rad_weight in_norm = 0, qkv = 0, q_norm = 0, k_norm = 0, o = 0, post_attn = 0;
rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0;
rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0;
/* clipped linears: the bounds (lo, hi) of the nine clamps, and the clamps */
enum { C_QKV_IN, C_Q_OUT, C_KV_OUT, C_O_IN, C_O_OUT, C_GU_IN, C_GU_OUT, C_DN_IN, C_DN_OUT, C_N };
rad_weight lo[C_N] = {}, hi[C_N] = {};
rad_op op_c[C_N] = {};
};
bool on = false, standardize = false, clip = false;
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
* plugin sets it before declare. */
bool bidirectional = false;
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
int64_t npos = 0, n_embd = 0;
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
rad_op op_patch = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0, op_pool = 0, op_norm = 0;
rad_op op_out = 0, op_sfill = 0, op_sbias = 0, op_sadd = 0, op_sscale = 0;
rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_px = 0,
b_py = 0, b_pool = 0, b_sb = 0, b_pn = 0, b_out = 0;
std::vector<Layer> L;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
return t && !std::strcmp(t, "gemma4_vision");
}
/* `pre` is the checkpoint prefix of the tower and its embedder ("model." for Gemma 4's
* conditional-generation checkpoints, "" for EmbeddingGemma 2); `who` names the plugin in
* refusals. The tower's layers take weight groups from `first_group`. */
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group, const char* pre, const char* who) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
hd = rad_meta_geti(m, "vision_config.head_dim", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
pool = rad_meta_geti(m, "vision_config.pooling_kernel_size", 0);
npos = rad_meta_geti(m, "vision_config.position_embedding_size", 0);
const int64_t depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
const int64_t patch = rad_meta_geti(m, "vision_config.patch_size", 0);
const int64_t kvh = rad_meta_geti(m, "vision_config.num_key_value_heads", heads);
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
const double theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 0.0);
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "");
const char* act = rad_meta_gets(m, "vision_config.hidden_activation", "");
standardize = rad_meta_geti(m, "vision_config.standardize", 0) != 0;
if (width <= 0 || heads <= 0 || hd <= 0 || ff <= 0 || pool <= 0 || npos <= 0 ||
depth <= 0 || patch <= 0 || !(theta > 0) || heads * hd != width || kvh != heads ||
hd % 4) {
fprintf(stderr, "radiance: %s: the container's vision_config is incomplete or not the "
"shape this tower serves (hidden %lld, heads %lld x %lld, kv %lld, ff "
"%lld, pooling %lld, layers %lld)\n", who, (long long)width,
(long long)heads, (long long)hd, (long long)kvh, (long long)ff,
(long long)pool, (long long)depth);
return RAD_E_INVAL;
}
/* Any rotary or activation other than the 2-D one and gelu-tanh is refused by name. */
if ((std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
std::strcmp(act, "gelu_pytorch_tanh")) {
fprintf(stderr, "radiance: %s: this vision tower uses a '%s' rotary or a '%s' "
"activation, which it does not serve\n", who, rt, act);
return RAD_E_UNSUPPORTED;
}
clip = rad_meta_geti(m, "vision_config.use_clipped_linears", 0) != 0;
n_embd = model_embd;
patch_dim = 3 * patch * patch;
const int64_t kk = pool * pool;
P = ctx->max_enc_patches;
if (P % kk) P -= P % kk;
R = P / kk;
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
char V[64];
std::snprintf(V, sizeof V, "%svision_tower", pre);
RAD_ARCH_TRY(map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.patch_embedder.input_proj.weight", V)));
RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_x.weight"),
nm.ckpt("%s.patch_embedder.position_embedding_table", V), 0));
RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_y.weight"),
nm.ckpt("%s.patch_embedder.position_embedding_table", V), 1));
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("%sembed_vision.embedding_projection.weight", pre)));
w_in = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
if (standardize) {
RAD_ARCH_TRY(map_copy(b, nm.f("v.std_bias"), nm.ckpt("%s.std_bias", V)));
RAD_ARCH_TRY(map_copy(b, nm.f("v.std_scale"), nm.ckpt("%s.std_scale", V)));
w_sbias = decl_w(b, nm.f("v.std_bias"), RAD_BF16, {width}, A, N, grp_model());
w_sscale = decl_w(b, nm.f("v.std_scale"), RAD_BF16, {width}, A, N, grp_model());
}
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const long long li = (long long)i;
const RadWeightGroup g = grp_layer(first_group + (int)i);
auto src = [&](const char* s) { return nm.ckpt("%s.encoder.layers.%lld.%s", V, li, s); };
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.in_norm", li), src("input_layernorm.weight")));
RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.qkv", li),
{src("self_attn.q_proj.linear.weight"),
src("self_attn.k_proj.linear.weight"),
src("self_attn.v_proj.linear.weight")}));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.q_norm", li), src("self_attn.q_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.k_norm", li), src("self_attn.k_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.o", li), src("self_attn.o_proj.linear.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_attn", li), src("post_attention_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.pre_ff", li), src("pre_feedforward_layernorm.weight")));
RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.gate_up", li),
{src("mlp.gate_proj.linear.weight"),
src("mlp.up_proj.linear.weight")}));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.down", li), src("mlp.down_proj.linear.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_ff", li), src("post_feedforward_layernorm.weight")));
l.in_norm = decl_w(b, nm.f("v.blk.%lld.in_norm", li), RAD_BF16, {width}, A, N, g);
l.qkv = decl_w(b, nm.f("v.blk.%lld.qkv", li), RAD_BF16, {3 * width, width}, A, N, g);
l.q_norm = decl_w(b, nm.f("v.blk.%lld.q_norm", li), RAD_BF16, {hd}, A, N, g);
l.k_norm = decl_w(b, nm.f("v.blk.%lld.k_norm", li), RAD_BF16, {hd}, A, N, g);
l.o = decl_w(b, nm.f("v.blk.%lld.o", li), RAD_BF16, {width, width}, A, N, g);
l.post_attn = decl_w(b, nm.f("v.blk.%lld.post_attn", li), RAD_BF16, {width}, A, N, g);
l.pre_ff = decl_w(b, nm.f("v.blk.%lld.pre_ff", li), RAD_BF16, {width}, A, N, g);
l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g);
l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g);
l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g);
if (clip) {
/* clamp k -> the checkpoint projection whose bound it takes, and which bound */
static const char* const proj[Layer::C_N] = {
"self_attn.q_proj", "self_attn.q_proj", "self_attn.k_proj", "self_attn.o_proj",
"self_attn.o_proj", "mlp.gate_proj", "mlp.gate_proj", "mlp.down_proj",
"mlp.down_proj" };
static const bool in_side[Layer::C_N] = { true, false, false, true, false, true,
false, true, false };
for (int k = 0; k < Layer::C_N; ++k) {
const char* side = in_side[k] ? "input" : "output";
const char* lo_n = nm.f("v.blk.%lld.clip%d.lo", li, k);
const char* hi_n = nm.f("v.blk.%lld.clip%d.hi", li, k);
RAD_ARCH_TRY(map_copy(b, lo_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_min", V, li,
proj[k], side)));
RAD_ARCH_TRY(map_copy(b, hi_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_max", V, li,
proj[k], side)));
l.lo[k] = decl_w(b, lo_n, RAD_BF16, {1}, A, N, g);
l.hi[k] = decl_w(b, hi_n, RAD_BF16, {1}, A, N, g);
if (!l.lo[k] || !l.hi[k]) return RAD_E_INVAL;
}
}
}
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width});
b_o = decl_b(b, nm.f("v.o"), RAD_BF16, {P, width});
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, {P, 3 * width});
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, {P, width});
b_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, {P, 2 * ff});
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, {P, ff});
b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width});
b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width});
b_pool = decl_b(b, nm.f("v.pool"), RAD_BF16, {R, width});
b_sb = decl_b(b, nm.f("v.sb"), RAD_BF16, {R, width});
b_pn = decl_b(b, nm.f("v.pn"), RAD_BF16, {R, width});
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {R, n_embd});
auto rms = [&](int64_t rows, rad_weight w) {
if (!w)
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight w) {
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto add = [&](int64_t rows) {
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
auto lookup = [&](rad_weight w) {
return RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
RAD_WEIGHTS(w));
};
auto clamp = [&](int64_t n, rad_weight lo, rad_weight hi) {
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(lo, hi));
};
auto gain = [&](rad_weight w) {
return RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
RAD_STR("dtype", "bf16"), RAD_INT("scalar", 0)),
RAD_WEIGHTS(w));
};
op_patch = rw(b, gemm(P, width, patch_dim, w_in), {}, {b_x});
op_px = rw(b, lookup(w_px), {}, {b_px});
op_py = rw(b, lookup(w_py), {}, {b_py});
op_padd = rw(b, add(P), {b_px, b_py}, {b_px});
op_add = rw(b, add(P), {b_x, b_px}, {b_x});
/* Two neox blocks of hd / 4 pairs, x (staged plane 1, the column) then y (plane 0). */
char sec[48];
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
for (Layer& l : L) {
/* the clamps, each in place on the one buffer its linear reads or writes (each of those
* is read by that linear alone, or by what follows it) */
if (clip) {
using C = Layer;
const struct { int k; int64_t n; rad_buf buf; } cl[C::C_N] = {
{ C::C_QKV_IN, width, b_h }, { C::C_Q_OUT, width, b_qkv },
{ C::C_KV_OUT, 2 * width, b_qkv }, { C::C_O_IN, width, b_att },
{ C::C_O_OUT, width, b_o }, { C::C_GU_IN, width, b_h },
{ C::C_GU_OUT, 2 * ff, b_gu }, { C::C_DN_IN, ff, b_ff },
{ C::C_DN_OUT, width, b_o } };
for (const auto& e : cl)
l.op_c[e.k] = rw(b, clamp(e.n, l.lo[e.k], l.hi[e.k]), {e.buf}, {e.buf});
}
l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h});
l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv});
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
RAD_F64("theta", theta), RAD_F64("eps", eps),
RAD_STR("mode", "blocks"), RAD_INT("v_norm", 1),
RAD_STR("sections", sec), RAD_STR("comps", "1 0")),
RAD_WEIGHTS(l.q_norm, l.k_norm)),
{b_qkv}, {b_qkv});
l.op_attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"), RAD_F64("scale", 1.0),
RAD_INT("max_seqlen", P), RAD_INT("window", 0)),
RAD_NOWEIGHTS),
{b_qkv}, {b_att});
l.op_o = rw(b, gemm(P, width, width, l.o), {b_att}, {b_o});
l.op_pa = rw(b, rms(P, l.post_attn), {b_o}, {b_o});
l.op_add1 = rw(b, add(P), {b_x, b_o}, {b_x});
l.op_pf = rw(b, rms(P, l.pre_ff), {b_x}, {b_h});
l.op_gu = rw(b, gemm(P, 2 * ff, width, l.gate_up), {b_h}, {b_gu});
l.op_act = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff),
RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_gu}, {b_ff});
l.op_down = rw(b, gemm(P, width, ff, l.down), {b_ff}, {b_o});
l.op_pff = rw(b, rms(P, l.post_ff), {b_o}, {b_o});
l.op_add2 = rw(b, add(P), {b_x, b_o}, {b_x});
}
op_pool = rw(b, RAD_OP(b, "pool_rows",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("k", kk), RAD_F64("mult", std::sqrt((double)width)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_x}, {b_pool});
if (standardize) {
op_sfill = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
RAD_STR("dtype", "bf16"), RAD_F64("value", -1.0)),
RAD_NOWEIGHTS),
{}, {b_sb});
op_sbias = rw(b, gain(w_sbias), {b_sb}, {b_sb});
op_sadd = rw(b, add(R), {b_pool, b_sb}, {b_pool});
op_sscale = rw(b, gain(w_sscale), {b_pool}, {b_pool});
}
op_norm = rw(b, rms(R, 0), {b_pool}, {b_pn});
op_out = rw(b, gemm(R, n_embd, width, w_proj), {b_pn}, {b_out});
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = kk;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.bidirectional = bidirectional ? 1 : 0;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld",
(long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff,
(long long)patch, (long long)pool, (long long)pool,
standardize ? ", standardised" : "", clip ? ", clipped linears" : "",
(long long)P, (long long)R,
(long long)n_embd);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg, kk = pool * pool;
if (!on || Pn <= 0 || Pn > P || Pn % kk || S <= 0) {
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, "
"more patches than it was declared for, or not whole pooling windows");
return;
}
const int64_t Rn = Pn / kk;
const int32_t* crd = batch->enc_coord;
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand rc = praw2(crd, RAD_I32, 2, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_in), brows(b_x, Pn));
RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn));
/* a clamp of operand `x` in place, when the tower clips */
auto cl = [&](const Layer& l, int k, RadOperand x) {
if (clip) RAD_ISSUE_N(c, l.op_c[k], Pn, x, RAD_W(l.lo[k]), RAD_W(l.hi[k]), x);
};
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn));
cl(l, Layer::C_QKV_IN, brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn));
cl(l, Layer::C_Q_OUT, bcol(b_qkv, 0, width, Pn));
cl(l, Layer::C_KV_OUT, bcol(b_qkv, width, 2 * width, Pn));
RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
cl(l, Layer::C_O_IN, brows(b_att, Pn));
RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn));
cl(l, Layer::C_O_OUT, brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn));
cl(l, Layer::C_GU_IN, brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn));
cl(l, Layer::C_GU_OUT, brows(b_gu, Pn));
RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn),
brows(b_ff, Pn));
cl(l, Layer::C_DN_IN, brows(b_ff, Pn));
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn));
cl(l, Layer::C_DN_OUT, brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
}
RAD_ISSUE_N(c, op_pool, Pn, brows(b_x, Pn), brows(b_pool, Rn));
if (standardize) {
RAD_ISSUE_N(c, op_sfill, Rn, brows(b_sb, Rn));
RAD_ISSUE_N(c, op_sbias, Rn, brows(b_sb, Rn), RAD_W(w_sbias), brows(b_sb, Rn));
RAD_ISSUE_N(c, op_sadd, Rn, brows(b_pool, Rn), brows(b_sb, Rn), brows(b_pool, Rn));
RAD_ISSUE_N(c, op_sscale, Rn, brows(b_pool, Rn), RAD_W(w_sscale), brows(b_pool, Rn));
}
RAD_ISSUE_N(c, op_norm, Rn, brows(b_pool, Rn), RAD_NONE, brows(b_pn, Rn));
RAD_ISSUE_N(c, op_out, Rn, brows(b_pn, Rn), RAD_W(w_proj), brows(b_out, Rn));
}
};
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_GEMMA4_VISION_H */
+422
View File
@@ -0,0 +1,422 @@
/* GLM-5.3's DSA indexer: the stateful compressed-index core over its paged key cache (DsaCache),
* which scores every complete block of a sequence's history against each query and selects the
* 512 the MLA attends to, and the front end around it (GlmIndexer), whose casts bridge ordinary
* linear rows to the flattened per-head quantiser and join normalized keys with learned pool
* gates. No RoPE; the only rotation is the Hadamard inside dsa_query. Selected pages belong to
* the MLA.
*
* Under tensor parallelism the key side stays replicated (every rank pools into the whole index
* cache and scores against it), but from GlmTp::kSplitRows rows, or a smaller step whose rows x
* live blocks reach GlmTp::kSplitWork, each rank scores and selects for its own run of query rows
* (GlmTp::run_of) and two all_gathers join the runs' page tables and lengths: every row's
* selection is computed by the same kernels from the same operands as on one rank, so the joined
* table is the replicated one's bits. The query side (projection, head gates, quantiser) then runs
* on this rank's run of rows only, since no other rank reads them. */
#ifndef RAD_BLOCK_GLM_INDEXER_H
#define RAD_BLOCK_GLM_INDEXER_H
#include "rad_fp8.h"
#include "rad_glm_tp.h"
namespace rad {
namespace arch {
struct DsaCache {
struct Config {
int64_t blocks = 0, work = 0, ring = 0, topk = 512;
};
struct Wire {
rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0;
rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0;
rad_buf score = 0, selected = 0, nsel = 0, length = 0;
/* A taking-all step's zero scores, [max_tok, topk + 1]: such a step does not split, and
* the score plane holds only a run of rows when the step may. */
rad_buf unscored = 0;
/* TP only: a rank's rebased bounds, page tables and lengths before the gathers. */
rad_buf cu_part = 0, sel_part = 0, len_part = 0;
};
/* The narrower of the two gathered rows, one i32 length a query row (the page table's 513 a
* row is a multiple of it), so a run is whole 16-byte words of both: a multiple of four rows.
* The query and output planes hold world times this. */
static constexpr int64_t kGatherRowBytes = 4;
static int64_t part_rows(int64_t rows, int world) {
return GlmTp::run_rows(rows, world, kGatherRowBytes);
}
Geom g{};
Config c{};
Wire w{};
int layer = 0;
rad_kvgroup index = 0, tail = 0, attention = 0;
rad_weight ape = 0;
rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0;
rad_op op_unscored = 0, op_select_all = 0;
rad_op op_score_part = 0, op_select_part = 0, op_gather_sel = 0, op_gather_len = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
const Wire& wire, rad_kvgroup attn, rad_kvgroup tail_group,
rad_kvgroup* index_group, const char* ape_source) {
g = geom;
c = cfg;
w = wire;
layer = l;
attention = attn;
tail = tail_group;
if (!b || !index_group || !ape_source || !attention || !tail || c.blocks < 1 ||
c.work < (g.max_tok + 3) / 4 + g.max_seqs || c.ring < 4 + g.max_spec || c.topk != 512 ||
!w.query || !w.codes || !w.scales || !w.gate || !w.kg || !w.stage || !w.page ||
!w.bpos || !w.nc || !w.pooled || !w.pool_scale || !w.score || !w.selected || !w.nsel ||
!w.length)
return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, tail));
const char* name = nm.f("blk.%d.index_ape", l);
RAD_ARCH_TRY(map_copy(b, name, ape_source));
ape = decl_w(b, name, RAD_F32, { 4, 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
if (!ape) return RAD_E_INVAL;
// Query buffers are [tokens*32,128]; scoring uses their rank-three view.
op_query = rw(b,
RAD_OP(b, "dsa_query",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.query }, { w.codes, w.scales });
op_work = rw(
b,
RAD_OP(b, "qsa_work",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), RAD_INT("ratio", 4),
RAD_INT("ring", c.ring), RAD_INT("seqs", g.max_seqs),
RAD_INT("work", c.work), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.kg }, { w.stage, w.page, w.bpos, w.nc });
// Declare immediately before the cache consumer: page size comes from that op.
if (!*index_group) {
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = RAD_U8;
d.n_head_kv = 1;
d.head_dim = 17;
*index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d);
/* dsa_score reads this group over the whole history every step, so it stays resident and
* holds every sequence's context while a sibling streams (kvstream/carve.cpp). */
RAD_ARCH_TRY(rad_kv_group_dense_read(b, *index_group));
}
index = *index_group;
if (!index) return RAD_E_INVAL;
op_pool =
rw(b,
RAD_OP(b, "dsa_pool",
RAD_PARAMS(RAD_RANGE("M", 1, c.work), RAD_INT("n", 128), RAD_INT("ratio", 4),
RAD_INT("block_size", 4), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(ape)),
{ w.stage, w.page }, { w.pooled, w.pool_scale });
if (!op_pool || rad_kv_block_size(b, index) != 4) return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, index));
op_tail = rw(b,
RAD_OP(b, "qsa_tail_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256),
RAD_INT("ratio", 4), RAD_INT("ring", c.ring),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.kg }, {});
/* A step whose every row reaches topk or fewer blocks selects them all (takes_all), and
* qsa_select takes any finite scores in block order then: zeros serve as well as the
* scorer's. The fill spans topk + 1 columns, at least the live reach of such a step. */
op_unscored = rw(b,
RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("n", unscored_cols()), RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{}, { w.unscored });
op_score = rw(b,
RAD_OP(b, "dsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_INT("heads", 32), RAD_INT("blocks", c.blocks),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3")),
RAD_NOWEIGHTS),
{ w.codes, w.scales, w.gate, w.nc }, { w.score });
const bool split = g.world > 1;
const int64_t part = split ? part_rows(g.max_tok, g.world) : 0;
if (split && (!w.cu_part || !w.sel_part || !w.len_part)) return RAD_E_INVAL;
if (split)
op_score_part =
rw(b,
RAD_OP(b, "dsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, part), RAD_INT("n", 128),
RAD_INT("heads", 32), RAD_INT("blocks", c.blocks),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3"),
RAD_INT("row_part", g.rank)),
RAD_NOWEIGHTS),
{ w.codes, w.scales, w.gate, w.nc }, { w.score, w.cu_part });
op_select = rw(b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", c.blocks),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.score, w.nc }, { w.selected, w.nsel, w.length });
op_select_all = rw(b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("blocks", unscored_cols()),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.unscored, w.nc }, { w.selected, w.nsel, w.length });
if (split) {
op_select_part = rw(
b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, part), RAD_INT("blocks", c.blocks),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.score, w.nc, w.cu_part }, { w.sel_part, w.nsel, w.len_part });
op_gather_sel = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4 * 513, part * 513),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ w.sel_part }, { w.selected });
op_gather_len = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4, part),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ w.len_part }, { w.length });
if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len)
return RAD_E_INVAL;
}
return op_query && op_work && op_tail && op_unscored && op_score && op_select &&
op_select_all
? RAD_OK
: RAD_E_INVAL;
}
int64_t unscored_cols() const { return c.topk + 1 < c.blocks ? c.topk + 1 : c.blocks; }
/* The columns a step scores: the live reach the batch bounds on the host. */
int64_t live_blocks(const RadBatch* batch) const {
const auto* ib = kv_batch(batch, index);
int64_t live = ((int64_t)batch->max_ctx_len + batch->n_tok + batch->n_spec + 4) / 4 + 1;
if (live > c.blocks) live = c.blocks;
// T is the total across sequences, so the conservative bound can exceed the
// per-sequence page table. Columns without a table entry cannot be scored.
if (ib && live > ib->block_table_pitch) live = ib->block_table_pitch;
return live < 1 ? 1 : live;
}
/* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by
* the core), so every rank takes the same path and a recorded decode pass changes it only when
* that bound moves. A step that takes all its blocks never splits: with nothing to score, every
* rank selects the whole step itself, and the gathers have nothing to save. */
bool splits(const RadBatch* batch) const {
const int64_t T = batch->n_tok;
return op_score_part && live_blocks(batch) > c.topk &&
(GlmTp::splits(T, g.world) ||
(T >= GlmTp::kSplitWorkRows && T * live_blocks(batch) >= GlmTp::kSplitWork));
}
/* Every row's history fits the selection, so the query side (projection, head gates,
* quantiser, scorer) has nothing to decide: the selected table is every live block in order,
* bit for bit what scoring would select. Read from the same host bound as splits(), so every
* rank agrees. */
bool takes_all(const RadBatch* batch) const { return live_blocks(batch) <= c.topk; }
/* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of).
* A rank whose run lies wholly past a small step runs the step's first R rows instead: no
* sequence holds its run, so its scores are -inf, and its answers land past T. The caller's
* projections into `query` and `gate` cover the same rows. */
void query_rows(const RadBatch* batch, int64_t* r0, int64_t* rows) const {
const int64_t T = batch->n_tok;
*r0 = 0;
*rows = T;
if (!splits(batch)) return;
const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kGatherRowBytes);
*r0 = run.first;
*rows = run.rows;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const auto* ib = kv_batch(batch, index);
const auto* tb = kv_batch(batch, tail);
const auto* ab = kv_batch(batch, attention);
if (!ib || !tb || !ab || !ib->block_table || !ab->block_table || !tb->state_index) {
rad_step_fail(ctx, "DSA requires index/attention block tables and tail state indices");
return;
}
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t work = (T + 3) / 4 + S,
pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1;
const bool all = takes_all(batch);
int64_t q0 = 0, qn = T;
query_rows(batch, &q0, &qn);
if (!all)
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
brow_slice(w.codes, q0 * 32, qn * 32, 128),
brow_slice(w.scales, q0 * 32, qn * 32, 1));
RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch),
praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), RAD_NONE,
brows(w.stage, work * 4), brows(w.page, work), brows(w.bpos, work),
brows(w.nc, S));
RAD_ISSUE_N(ctx, op_pool, work, brows(w.stage, work * 4), RAD_W(ape), brows(w.pooled, work),
brows(w.pool_scale, work), brows(w.page, work), kv_cache(index, layer));
// Gather before overwriting the tail; the wider ring preserves rejected-token rollback.
RAD_ISSUE_N(ctx, op_tail, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch));
const int64_t live = live_blocks(batch);
if (splits(batch)) {
step_split(ctx, batch, live);
return;
}
if (all) {
const int64_t U = unscored_cols();
RAD_ISSUE_N(ctx, op_unscored, T, brows(w.unscored, T));
RAD_ISSUE_N(ctx, op_select_all, T, bcol_at(w.unscored, 0, U, 0, live, T),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch),
brows(w.nc, S), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.selected, T),
brows(w.nsel, T), brows(w.length, T));
return;
}
// dsa_score declares ten operands, cu_part the optional tenth; the engine counts them.
RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32),
brows(w.gate, T), kv_cache(index, layer), RAD_NONE,
praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S),
bcol_at(w.score, 0, c.blocks, 0, live, T), RAD_NONE);
RAD_ISSUE_N(ctx, op_select, T, bcol_at(w.score, 0, c.blocks, 0, live, T),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S),
praw(batch->positions, RAD_I32, T), praw(batch->cu_seqlens, RAD_I32, S + 1),
brows(w.selected, T), brows(w.nsel, T), brows(w.length, T));
}
/* Rank r scores rows [r R, r R + R) (rows past the step score -inf) and selects for those
* that exist (query_rows), against the bounds the scorer rebased to its first row. The
* gathers lay the runs end to end, so rows past the step land past T, where nothing reads
* them. */
void step_split(RadCtx* ctx, const RadBatch* batch, int64_t live) const {
const auto* ib = kv_batch(batch, index);
const auto* ab = kv_batch(batch, attention);
const int64_t T = batch->n_tok, S = batch->n_seq, W = g.world;
const int64_t R = part_rows(T, g.world);
int64_t p0 = 0, rows = 0;
query_rows(batch, &p0, &rows);
RAD_ISSUE_N(ctx, op_score_part, R, brows(w.codes, W * R * 32),
brows(w.scales, W * R * 32), brows(w.gate, W * R), kv_cache(index, layer),
RAD_NONE, praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S),
bcol_at(w.score, 0, c.blocks, 0, live, R), brows(w.cu_part, S + 1));
RAD_ISSUE_N(ctx, op_select_part, rows, bcol_at(w.score, 0, c.blocks, 0, live, rows),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S),
praw(batch->positions + p0, RAD_I32, rows), brows(w.cu_part, S + 1),
brows(w.sel_part, rows), brows(w.nsel, rows), brows(w.len_part, rows));
RAD_ISSUE_N(ctx, op_gather_sel, R * 513, brows(w.sel_part, R), brows(w.selected, W * R));
RAD_ISSUE_N(ctx, op_gather_len, R, brows(w.len_part, R), brows(w.length, W * R));
}
};
struct GlmIndexer {
struct Wire {
rad_buf input = 0, q_low = 0, q_wide = 0, kg_raw = 0;
DsaCache::Wire cache{};
};
Geom g{};
Wire w{};
LinearFP8 query{}, key_gate{};
DsaCache cache{};
rad_weight gain = 0, bias = 0, head_weight = 0;
rad_op op_norm = 0, op_query_copy = 0, op_gate_copy = 0, op_head = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const char* prefix, const DsaCache::Config& cfg, rad_kvgroup attention,
rad_kvgroup tail, rad_kvgroup* index) {
g = geom;
w = wire;
if (!b || !prefix || g.n_embd != 4096 || !w.input || !w.q_low || !w.q_wide || !w.kg_raw)
return RAD_E_INVAL;
Geom bg = g;
bg.w_bf16 = true;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
RAD_ARCH_TRY(query.declare(b, nm, bg, nm.f("blk.%d.index_query", l), 4096, 1536,
RAD_SHARD_NONE, grp_layer(l),
{ nm.ckpt("%s.wq_b.weight", prefix) }, act(w.q_low), w.q_wide));
RAD_ARCH_TRY(key_gate.declare(
b, nm, bg, nm.f("blk.%d.index_key_gate", l), 256, 4096, RAD_SHARD_NONE, grp_layer(l),
{ nm.ckpt("%s.wk.weight", prefix), nm.ckpt("%s.index_kpool_compress_gate", prefix) },
act(w.input), w.kg_raw, 0, { 128, 128 }));
const char *gn = nm.f("blk.%d.index_norm.weight", l),
*bn = nm.f("blk.%d.index_norm.bias", l),
*hn = nm.f("blk.%d.index_head.weight", l);
RAD_ARCH_TRY(map_copy(b, gn, nm.ckpt("%s.k_norm.weight", prefix)));
RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.k_norm.bias", prefix)));
RAD_ARCH_TRY(map_copy(b, hn, nm.ckpt("%s.weights_proj.weight", prefix)));
gain = decl_w(b, gn, RAD_F32, { 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
bias = decl_w(b, bn, RAD_F32, { 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
head_weight = decl_w(b, hn, RAD_F32, { 32, 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
if (!gain || !bias || !head_weight) return RAD_E_INVAL;
op_norm = rw(b,
RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain, bias)),
{ w.kg_raw }, { w.cache.kg });
op_query_copy = rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ w.q_wide }, { w.cache.query });
op_gate_copy = rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ w.kg_raw }, { w.cache.kg });
op_head = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 32),
RAD_INT("K", 4096), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(head_weight)),
{ w.input }, { w.cache.gate });
RAD_ARCH_TRY(cache.declare(b, nm, g, l, cfg, w.cache, attention, tail, index,
nm.ckpt("%s.index_kpool_compress_ape", prefix)));
return op_norm && op_query_copy && op_gate_copy && op_head ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
int64_t r0 = 0, rows = T;
cache.query_rows(batch, &r0, &rows);
/* The key side runs on every step, since the index cache must stay current; the query
* side only where the selection is a choice (DsaCache::takes_all). */
const bool all = cache.takes_all(batch);
/* Every output row of these ops is independent of the others and of how many there are,
* except the bf16 projection's at 64 rows and under, a band whose split count a tuned
* configuration may set: it stays on the step's rows unless every run is wider. */
const bool runs = cache.splits(batch);
if (!all) {
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
else
query.step(ctx, act(w.q_low), w.q_wide, T);
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
}
key_gate.step(ctx, act(w.input), w.kg_raw, T);
RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias),
bcol(w.cache.kg, 0, 128, T));
RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T),
bcol(w.cache.kg, 128, 128, T));
if (!all)
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096),
RAD_W(head_weight), brow_slice(w.cache.gate, r0, rows, 32));
cache.step(ctx, batch);
}
};
}
} // namespace rad::arch
#endif
+221
View File
@@ -0,0 +1,221 @@
/* GLM-5.3's KDA layer: the seven bf16 projections around the recurrent core (GlmKda), and the
* core itself over already projected inputs (KdaState), whose ple_conv supplies exactly causal
* depthwise convolution + SiLU, cold start and accepted-history rollback included. The two
* low-rank gate paths have no intervening activation. The caller supplies the normalized input
* and owns the mHC residual connection.
*
* Under tensor parallelism the heads split (GlmTp::heads), and with them the q/k/v rows, the
* convolution taps, the state and the output projection's columns; the two rank-128 projections
* into the gates are replicated. The block's all_reduce sums the output. */
#ifndef RAD_BLOCK_GLM_KDA_H
#define RAD_BLOCK_GLM_KDA_H
#include "rad_fp8.h"
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct KdaState {
struct Config {
int64_t heads = 16, dim = 128, width = 4;
double lower = -5;
};
struct Src {
const char *q_conv = nullptr, *k_conv = nullptr, *v_conv = nullptr, *alog = nullptr,
*bias = nullptr, *norm = nullptr;
};
struct Wire {
rad_buf qkv = 0, conv = 0, a = 0, beta = 0, gate = 0, out = 0;
};
Geom g{};
Config c{};
Wire w{};
int layer = 0;
rad_kvgroup state = 0, history = 0;
rad_weight taps = 0, alog = 0, bias = 0, norm = 0;
rad_op op_conv = 0, op_verify = 0, op_prefill = 0, op_norm = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup st, rad_kvgroup cv,
const Config& cfg, const Wire& wire, const Src& src) {
g = geom;
c = cfg;
w = wire;
layer = l;
state = st;
history = cv;
if (!b || !st || !cv || c.heads < 1 || c.dim != 128 || c.width != 4 || g.max_spec > 31 ||
!std::isfinite(c.lower) || c.lower >= 0 || !w.qkv || !w.conv || !w.a || !w.beta ||
!w.gate || !w.out || w.qkv == w.conv || !src.q_conv || !src.k_conv || !src.v_conv ||
!src.alog || !src.bias || !src.norm)
return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, st));
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, cv));
const int64_t width = c.heads * c.dim;
const char *tn = nm.f("blk.%d.ssm_conv.weight", l), *an = nm.f("blk.%d.ssm_a", l),
*bn = nm.f("blk.%d.ssm_dt_bias", l), *nn = nm.f("blk.%d.ssm_norm.weight", l);
RAD_ARCH_TRY(map_concat(b, tn, { src.q_conv, src.k_conv, src.v_conv }));
RAD_ARCH_TRY(map_copy(b, an, src.alog));
RAD_ARCH_TRY(map_copy(b, bn, src.bias));
RAD_ARCH_TRY(map_copy(b, nn, src.norm));
taps = decl_w(b, tn, RAD_BF16, { 3 * width, c.width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
grp_layer(l), 0, { width, width, width });
alog =
decl_w(b, an, RAD_F32, { c.heads }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
bias = decl_w(b, bn, RAD_F32, { width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
norm =
decl_w(b, nn, RAD_F32, { c.dim }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
if (!taps || !alog || !bias || !norm) return RAD_E_INVAL;
op_conv = rw(b,
RAD_OP(b, "ple_conv",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 3 * width),
RAD_INT("width", c.width), RAD_INT("dilation", 1),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(taps)),
{ w.qkv }, { w.conv });
for (int verify = 0; verify < 2; ++verify) {
const rad_op op = rw(
b,
RAD_OP(b, "kda_update",
RAD_PARAMS(
RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads),
RAD_INT("head_k", c.dim), RAD_INT("head_v", c.dim),
RAD_F64("lower_bound", c.lower),
RAD_F64("scale", 1.0 / std::sqrt((double)c.dim)),
RAD_F64("l2_eps", 1e-6), RAD_STR("mode", verify ? "verify" : "prefill"),
RAD_STR("dtype", "bf16"),
RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate")),
RAD_WEIGHTS(alog, bias)),
{ w.conv, w.a, w.beta }, { w.out });
if (verify)
op_verify = op;
else
op_prefill = op;
}
op_norm = rw(b,
RAD_OP(b, "gdn_gated_rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", c.dim),
RAD_F64("eps", g.eps), RAD_STR("act", "sigmoid")),
RAD_WEIGHTS(norm)),
{ w.out, w.gate }, { w.out });
return op_conv && op_verify && op_prefill && op_norm ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const auto *st = kv_batch(batch, state), *cv = kv_batch(batch, history);
if (!st || !cv || !st->state_index || !cv->state_index) {
rad_step_fail(ctx, "KDA requires recurrent and convolution state indices");
return;
}
const int64_t T = batch->n_tok, S = batch->n_seq, width = c.heads * c.dim;
const int64_t pitch = st->state_index_pitch > 0 ? st->state_index_pitch : 1;
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
for (int verify = 1; verify >= 0; --verify) {
const int64_t seq0 = verify ? 0 : D, seqs = verify ? D : S - D, rows = verify ? DT : T;
if (!seqs) continue;
const RadOperand cu = praw(batch->cu_seqlens + seq0, RAD_I32, seqs + 1);
const RadOperand init = praw(batch->ctx_lens + seq0, RAD_I32, seqs);
const RadOperand accepted =
verify ? praw(batch->num_accepted, RAD_I32, seqs) : RAD_NONE;
RAD_ISSUE_N(ctx, op_conv, rows, brows(w.qkv, rows), RAD_W(taps),
kv_cache(history, layer), cu, RAD_NONE,
praw(cv->state_index + seq0, RAD_I32, seqs), init, accepted,
brows(w.conv, rows));
RAD_ISSUE_N(ctx, verify ? op_verify : op_prefill, rows, bcol(w.conv, 0, width, rows),
bcol(w.conv, width, width, rows), bcol(w.conv, 2 * width, width, rows),
brows(w.a, rows), brows(w.beta, rows), RAD_W(alog), RAD_W(bias),
kv_cache(state, layer),
praw2(st->state_index + seq0 * pitch, RAD_I32, seqs, pitch), cu, accepted,
init, brows(w.out, rows));
}
RAD_ISSUE_N(ctx, op_norm, T, brows(w.out, T), brows(w.gate, T), RAD_W(norm),
brows(w.out, T));
}
};
struct GlmKda {
struct Wire {
rad_buf input = 0, forget_low = 0, gate_low = 0, out = 0;
KdaState::Wire core{};
};
Geom g{};
Wire w{};
KdaState core{};
LinearFP8 qkv{}, beta{}, forget_a{}, forget_b{}, gate_a{}, gate_b{}, output{};
rad_op op_ar = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const Wire& wire,
const char* prefix, const KdaState::Src& src, rad_kvgroup state,
rad_kvgroup history, bool reduce = true) {
g = geom;
w = wire;
if (!b || !prefix || g.n_embd != 4096 || g.world < 1 || GlmTp::kHeads % g.world ||
!w.input || !w.forget_low || !w.gate_low || !w.out || w.input == w.out ||
w.forget_low == w.gate_low)
return RAD_E_INVAL;
// All seven projections are plain bf16 in the pinned checkpoint; under w_bf16,
// LinearFP8::declare refuses a quantised one by name.
Geom bg = g;
bg.w_bf16 = true;
const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world);
const auto group = grp_layer(layer);
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
const auto input = act(w.input);
RAD_ARCH_TRY(qkv.declare(
b, nm, bg, nm.f("blk.%d.attn_qkv", layer), 3 * width, 4096, RAD_SHARD_ROW, group,
{ nm.ckpt("%s.q_proj.weight", prefix), nm.ckpt("%s.k_proj.weight", prefix),
nm.ckpt("%s.v_proj.weight", prefix) },
input, w.core.qkv, 0, { width, width, width }));
RAD_ARCH_TRY(beta.declare(b, nm, bg, nm.f("blk.%d.attn_beta", layer), heads, 4096,
RAD_SHARD_ROW, group, { nm.ckpt("%s.b_proj.weight", prefix) },
input, w.core.beta));
/* Both low-rank down-projections before either up-projection, in step() as here: the
* four reads of the input then share one ordered point of a recorded pass and the two
* up-projections the next, where forget_b between them cost a third. Declared in the
* issue order because the buffer plan takes lifetimes from this list, and forget_low and
* gate_low must not share bytes while both are live. */
RAD_ARCH_TRY(forget_a.declare(
b, nm, bg, nm.f("blk.%d.attn_forget_a", layer), 128, 4096, RAD_SHARD_NONE, group,
{ nm.ckpt("%s.f_a_proj.weight", prefix) }, input, w.forget_low));
RAD_ARCH_TRY(gate_a.declare(b, nm, bg, nm.f("blk.%d.attn_gate_a", layer), 128, 4096,
RAD_SHARD_NONE, group,
{ nm.ckpt("%s.g_a_proj.weight", prefix) }, input, w.gate_low));
RAD_ARCH_TRY(forget_b.declare(
b, nm, bg, nm.f("blk.%d.attn_forget_b", layer), width, 128, RAD_SHARD_ROW, group,
{ nm.ckpt("%s.f_b_proj.weight", prefix) }, act(w.forget_low), w.core.a));
RAD_ARCH_TRY(gate_b.declare(b, nm, bg, nm.f("blk.%d.attn_gate_b", layer), width, 128,
RAD_SHARD_ROW, group, { nm.ckpt("%s.g_b_proj.weight", prefix) },
act(w.gate_low), w.core.gate));
KdaState::Config cfg;
cfg.heads = heads;
RAD_ARCH_TRY(core.declare(b, nm, bg, layer, state, history, cfg, w.core, src));
RAD_ARCH_TRY(output.declare(b, nm, bg, nm.f("blk.%d.attn_output", layer), 4096, width,
RAD_SHARD_COL, group, { nm.ckpt("%s.o_proj.weight", prefix) },
act(w.core.out), w.out));
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
const auto input = act(w.input);
qkv.step(ctx, input, w.core.qkv, T);
beta.step(ctx, input, w.core.beta, T);
forget_a.step(ctx, input, w.forget_low, T);
gate_a.step(ctx, input, w.gate_low, T);
forget_b.step(ctx, act(w.forget_low), w.core.a, T);
gate_b.step(ctx, act(w.gate_low), w.core.gate, T);
core.step(ctx, batch);
output.step(ctx, act(w.core.out), w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
}
};
}
} // namespace rad::arch
#endif
+138
View File
@@ -0,0 +1,138 @@
/* GLM-5.3's manifold-constrained residual connections (mHC): four residual streams in one
* 16384-wide row. read() mixes them down to the block's 4096-wide input and saves the mixing
* coefficients; write() adds the block's output back into every stream. The mixed residual must
* have a separate destination: each output stream reads every original input stream. */
#ifndef RAD_BLOCK_GLM_MHC_H
#define RAD_BLOCK_GLM_MHC_H
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct ManifoldConn {
struct Config {
int64_t hc = 4, iterations = 20;
double eps = 1e-6, hc_eps = 1e-6;
};
struct Src {
const char *fn = nullptr, *scale = nullptr, *base = nullptr;
};
struct Wire {
rad_buf h = 0, x = 0, y = 0, out = 0;
// Saved by read(), consumed by write() after the block produces y.
rad_buf post = 0, comb = 0;
};
Geom g{};
Config c{};
Wire w{};
rad_weight w_fn = 0, w_scale = 0, w_base = 0;
rad_op op_pre = 0, op_post = 0;
/* Above the split threshold under TP, GLM's projection is split by residual chunks: each rank
* computes the partials of its chunks with mhc_pre's own kernels, an all_gather joins them,
* and mhc_pre_finish completes the read on every rank (rad_glm_tp.h). */
static constexpr int64_t kChunk = 2048, kPartStride = 28;
rad_buf part = 0, parts = 0;
rad_op op_partial = 0, op_gather = 0, op_finish = 0;
int64_t split_rows = 0, part_row = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name,
const Config& cfg, const Wire& wire, const Src& src, bool defer_post = false) {
g = geom;
c = cfg;
w = wire;
if (!b || !name || !src.fn || !src.scale || !src.base || g.n_embd < 1 || g.max_tok < 1 ||
c.hc < 2 || c.hc > 8 || c.iterations < 1 || c.iterations > 256 ||
!std::isfinite(c.eps) || !std::isfinite(c.hc_eps) || c.eps <= 0 || c.hc_eps < 0 ||
!w.h || !w.x || !w.y || !w.out || !w.post || !w.comb || w.h == w.out || w.h == w.x ||
w.h == w.y || w.x == w.out || w.y == w.out || w.post == w.comb)
return RAD_E_INVAL;
const int64_t width = c.hc * g.n_embd, mix = c.hc * (c.hc + 2);
const char *fn = nm.f("%s.fn", name), *scale = nm.f("%s.scale", name),
*base = nm.f("%s.base", name);
RAD_ARCH_TRY(map_copy(b, fn, src.fn));
RAD_ARCH_TRY(map_copy(b, scale, src.scale));
RAD_ARCH_TRY(map_copy(b, base, src.base));
// Mixing coefficients are F32 in the checkpoint; keep them replicated under TP.
const rad_weight wf = w_fn = decl_w(b, fn, RAD_F32, { mix, width }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
const rad_weight ws = w_scale = decl_w(b, scale, RAD_F32, { 3 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
const rad_weight wb = w_base = decl_w(b, base, RAD_F32, { mix }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
if (!wf || !ws || !wb) return RAD_E_INVAL;
op_pre = rw(b,
RAD_OP(b, "mhc_pre",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(wf, ws, wb)),
{ w.h }, { w.x, w.post, w.comb });
if (!op_pre) return RAD_E_INVAL;
RAD_ARCH_TRY(declare_split(b, nm, name));
return defer_post ? RAD_OK : declare_post(b);
}
int declare_split(RadBuilder* b, Names& nm, const char* name) {
const int64_t total = c.hc * g.n_embd / kChunk;
split_rows = GlmTp::kSplitRows;
if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || total % g.world) {
split_rows = 0;
return RAD_OK;
}
const int64_t mine = total / g.world, T = g.max_tok;
part_row = mine * kPartStride;
part = decl_b(b, nm.f("%s.part", name), RAD_F32, { T, part_row });
parts = decl_b(b, nm.f("%s.parts", name), RAD_F32, { T, total * kPartStride });
op_partial =
rw(b,
RAD_OP(b, "mhc_pre_partial",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), RAD_INT("hc", c.hc),
RAD_INT("chunk", kChunk), RAD_INT("first", g.rank * mine),
RAD_INT("chunks", mine), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fn)),
{ w.h }, { part });
op_gather = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", part_row, T * part_row),
RAD_STR("dtype", "f32"), RAD_INT("row", part_row)),
RAD_NOWEIGHTS),
{ part }, { parts });
op_finish = rw(b,
RAD_OP(b, "mhc_pre_finish",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
RAD_INT("chunk", kChunk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_scale, w_base)),
{ parts, w.h }, { w.x, w.post, w.comb });
return part && parts && op_partial && op_gather && op_finish ? RAD_OK : RAD_E_INVAL;
}
int declare_post(RadBuilder* b) {
op_post = rw(b,
RAD_OP(b, "mhc_post",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ w.y, w.h, w.post, w.comb }, { w.out });
return op_post ? RAD_OK : RAD_E_INVAL;
}
void read(RadCtx* ctx, int64_t rows) const {
if (split_rows && rows >= split_rows) {
RAD_ISSUE_N(ctx, op_partial, rows, brows(w.h, rows), RAD_W(w_fn), brows(part, rows));
RAD_ISSUE_N(ctx, op_gather, rows * part_row, brows(part, rows), brows(parts, rows));
RAD_ISSUE_N(ctx, op_finish, rows, brows(parts, rows), brows(w.h, rows), RAD_W(w_scale),
RAD_W(w_base), brows(w.x, rows), brows(w.post, rows), brows(w.comb, rows));
return;
}
RAD_ISSUE_N(ctx, op_pre, rows, brows(w.h, rows), RAD_W(w_fn), RAD_W(w_scale), RAD_W(w_base),
brows(w.x, rows), brows(w.post, rows), brows(w.comb, rows));
}
void write(RadCtx* ctx, int64_t rows) const {
RAD_ISSUE_N(ctx, op_post, rows, brows(w.y, rows), brows(w.h, rows), brows(w.post, rows),
brows(w.comb, rows), brows(w.out, rows));
}
};
}
} // namespace rad::arch
#endif
+368
View File
@@ -0,0 +1,368 @@
/* GLM-5.3's sparse latent attention (MLA, no RoPE): the projections and the latent cache store
* around the absorbed core (GlmMla), and the core itself over the latent cache (MlaLatent), whose
* complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent
* for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual.
*
* Under tensor parallelism the head form splits the 64 heads over the ranks (GlmTp::heads): the
* rows of q_b and kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent
* cache are replicated. From GlmTp::kSplitRows a prefill-sized step takes the row form instead
* (Wire::rows, Form::rows): each rank runs its run of the step's rows (GlmTp::run_of) through q_b,
* absorption, attention, expansion and the output projection with all 64 heads, then an
* all_gather lays the runs out as the whole step. The latent cache and the selection are whole on
* every rank already, so the split needs no other exchange. The gather moves half the bytes of
* the head form's all-reduce, and the attention loads each key once for all 64 heads of a row.
* The price is the three projections at full width on every rank (126 MB a layer); RowsWire::q
* unset declares neither them nor the form. */
#ifndef RAD_BLOCK_GLM_MLA_H
#define RAD_BLOCK_GLM_MLA_H
#include "rad_fp8.h"
#include "rad_glm_tp.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct MlaLatent {
struct Config {
int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513;
};
/* The attention over the latent cache, `rows` rows of `heads` heads. The cache is Geom::kv_dtype
* (bf16, or fp8_e4m3 under --kv-cache-dtype fp8); `kv_dtype` is stated only for a cache that is
* not bf16, so a bf16 build declares the op it always did. */
static rad_op attn_op(RadBuilder* b, const Geom& g, int64_t rows, int64_t heads,
int64_t blocks, double scale) {
if (g.kv_dtype && std::strcmp(g.kv_dtype, "bf16"))
return RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
RAD_INT("block_size", 4), RAD_F64("scale", scale),
RAD_STR("dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS);
return RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
RAD_INT("block_size", 4), RAD_F64("scale", scale),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
}
struct Wire {
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
/* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`.
* Never `length`, which is a token count. */
rad_buf nsel = 0;
};
Geom g{};
Config c{};
Wire w{};
int layer = 0;
rad_kvgroup kv = 0;
rad_weight projection = 0;
rad_op op_absorb = 0, op_attn = 0, op_expand = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
const Config& cfg, const Wire& wire, const char* source) {
g = geom;
c = cfg;
w = wire;
layer = l;
kv = group;
if (!b || !source || !group || c.heads < 1 || c.blocks < 1 || !w.q || !w.q_latent ||
!w.attn_latent || !w.out || !w.selected || !w.length || w.q == w.q_latent ||
w.q_latent == w.attn_latent || w.attn_latent == w.out || c.latent_dim != 512 ||
c.head_dim != 256)
return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, group));
const char* name = nm.f("blk.%d.attn_kv_b.weight", l);
RAD_ARCH_TRY(map_copy(b, name, source));
// The conversion recipe decodes this small projection only.
projection = decl_w(b, name, RAD_BF16, { c.heads * 2 * c.head_dim, c.latent_dim },
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
if (!projection) return RAD_E_INVAL;
op_absorb = rw(
b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads),
RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim),
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.q }, { w.q_latent });
op_attn = rw(b,
attn_op(b, g, g.max_tok, c.heads, c.blocks,
1.0 / std::sqrt((double)c.head_dim)),
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL;
op_expand = rw(
b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads),
RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim),
RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.attn_latent }, { w.out });
return op_absorb && op_attn && op_expand ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* ctx, int64_t rows) const {
RAD_ISSUE_N(ctx, op_absorb, rows, brows(w.q, rows), RAD_W(projection),
brows(w.q_latent, rows));
RAD_ISSUE_N(ctx, op_attn, rows, brows(w.q_latent, rows), kv_cache(kv, layer),
brows(w.selected, rows), brows(w.length, rows), brows(w.attn_latent, rows));
RAD_ISSUE_N(ctx, op_expand, rows, brows(w.attn_latent, rows), RAD_W(projection),
brows(w.out, rows));
}
};
struct GlmMla {
/* How a prefill-sized step under tensor parallelism runs: `heads` keeps the head form at every
* step size and spares the full-width weights' VRAM; `rows` is the row form. The plugin
* chooses (RadBuildCtx::tp_attn_rows); the block takes the choice through whether it is given
* RowsWire buffers. */
enum class Form { heads, rows };
/* The row form's buffers, `rows_for(max_tok)` rows each. `out` (Wire::out) must hold
* world * rows_for(T) rows, since every rank's run is gathered at full length. */
struct RowsWire {
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0;
ActFP8 attn{};
};
struct Wire {
ActFP8 input{}, q_low{}, attn{};
rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0;
MlaLatent::Wire core{};
RowsWire rows{};
};
/* The gathered row of the row form: 4096 bf16, so a run is ceil(T / world) rows. */
static constexpr int64_t kOutRowBytes = 4096 * 2;
static int64_t rows_for(int64_t T, int world) {
return GlmTp::run_rows(T, world, kOutRowBytes);
}
Geom g{};
Wire w{};
int layer = 0;
rad_kvgroup kv = 0;
LinearFP8 q_a{}, kv_a{}, q_b{}, output{};
NormQuantFP8 q_norm{};
QuantFP8 attn_quant{};
MlaLatent core{};
rad_weight q_gain = 0, kv_gain = 0;
rad_op op_kv_norm = 0, op_store = 0, op_store_stream = 0, op_resolve = 0, op_ar = 0;
LinearFP8 rows_q_b{}, rows_output{};
QuantFP8 rows_quant{};
rad_weight rows_kv_b = 0;
rad_op op_rows_absorb = 0, op_rows_attn = 0, op_rows_expand = 0, op_rows_gather = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const char* prefix, rad_kvgroup group, bool reduce = true,
bool defer_finish = false) {
g = geom;
w = wire;
layer = l;
kv = group;
if (!b || !prefix || !kv || g.n_embd != 4096 || g.world < 1 || GlmTp::kHeads % g.world ||
!w.input.x || !w.q_raw || !w.kv_raw || !w.latent || !w.out || !w.q_low.x || !w.attn.x ||
w.attn.x != w.core.out)
return RAD_E_INVAL;
const auto wg = grp_layer(l);
RAD_ARCH_TRY(q_a.declare(b, nm, g, nm.f("blk.%d.attn_q_a", l), 1536, 4096, RAD_SHARD_NONE,
wg, { nm.ckpt("%s.q_a_proj.weight", prefix) }, w.input, w.q_raw));
RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), 512, 4096, RAD_SHARD_NONE,
wg, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", prefix) }, w.input,
w.kv_raw));
const char* qn = nm.f("blk.%d.attn_q_a_norm.weight", l);
const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, qn, nm.ckpt("%s.q_a_layernorm.weight", prefix)));
RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", prefix)));
q_gain = decl_w(b, qn, RAD_F32, { 1536 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
kv_gain = decl_w(b, kn, RAD_F32, { 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
if (!q_gain || !kv_gain) return RAD_E_INVAL;
RAD_ARCH_TRY(q_norm.declare(b, g, q_gain, w.q_raw, w.q_low, 1536));
op_kv_norm = rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 512),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(kv_gain)),
{ w.kv_raw }, { w.latent });
if (!op_kv_norm) return RAD_E_INVAL;
RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world),
1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
w.q_low, w.core.q));
/* Cache stores contiguous halves of the normalized latent, with no duplicated K/V. An E4M3
* cache (Geom::kv_dtype) stores at kv_store's default descale of 1, which mla_attn reads. */
op_store = rw(b,
RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{ w.latent }, {});
if (!op_store) return RAD_E_INVAL;
return defer_finish ? RAD_OK : declare_finish(b, nm, prefix, reduce);
}
int declare_finish(RadBuilder* b, Names& nm, const char* prefix, bool reduce = true) {
MlaLatent::Config cfg;
cfg.heads = GlmTp::heads(g.world);
RAD_ARCH_TRY(
core.declare(b, nm, g, layer, kv, cfg, w.core, nm.ckpt("%s.kv_b_proj.weight", prefix)));
RAD_ARCH_TRY(attn_quant.declare(b, g, w.attn, GlmTp::mla_width(g.world)));
RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096,
GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer),
{ nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out));
/* The streamed store: kv_store's operands plus the residency map and the layer's mirror row,
* added at issue (prepare). */
if (rad_op_declared(b, "kv_store_streamed") && rad_kv_block_size(b, kv) == 4)
op_store_stream = rw(b,
RAD_OP(b, "kv_store_streamed",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("head_dim", 256), RAD_INT("n_head_kv", 1),
RAD_INT("block_size", 4),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{ w.latent }, {});
/* Issued in finish, after this layer's indexer selects and before the attention reads
* `selected`. `sel_pitch` is the row pitch MlaLatent declares its attention with. */
op_resolve = kv_resolve_declare(b, g, kv, w.core.selected, w.core.nsel, core.c.blocks);
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
if (!op_store || ((reduce && g.world > 1) && !op_ar)) return RAD_E_INVAL;
return reduce ? declare_rows(b, nm, prefix) : RAD_OK;
}
/* Declared whatever the step size, as every TP split here is: arena levels declare again at a
* smaller max_tok and must get the same graph. The gather's message bound is the all-reduce's,
* so both share one exchange instance and its scratch. */
int declare_rows(RadBuilder* b, Names& nm, const char* prefix) {
const auto& r = w.rows;
if (!r.q || g.world < 2) return RAD_OK;
if (!r.q_latent || !r.attn_latent || !r.out || !r.attn.x || r.attn.x == r.q) return RAD_E_INVAL;
const int64_t R = rows_for(g.max_tok, g.world);
const auto wg = grp_layer(layer);
/* Whole views of the head form's container entries: one stored weight each, whose
* encoding (block fp8 at f32 scales, the decoded bf16 kv_b) the views inherit. */
rows_q_b.stored = nm.f("blk.%d.attn_q_b.weight", layer);
RAD_ARCH_TRY(rows_q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b_rows", layer), 16384, 1536,
RAD_SHARD_NONE, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
w.q_low, r.q, R));
rows_kv_b = decl_view(b, nm.f("blk.%d.attn_kv_b_rows.weight", layer),
nm.f("blk.%d.attn_kv_b.weight", layer), nullptr, RAD_BF16,
{ 64 * 2 * 256, 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
if (!rows_kv_b) return RAD_E_INVAL;
auto project = [&](const char* mode, rad_buf in, rad_buf out) {
return rw(b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("heads", 64),
RAD_INT("head_dim", 256), RAD_INT("latent_dim", 512),
RAD_STR("mode", mode), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(rows_kv_b)),
{ in }, { out });
};
op_rows_absorb = project("absorb", r.q, r.q_latent);
op_rows_attn = rw(b, MlaLatent::attn_op(b, g, R, 64, core.c.blocks, 1.0 / std::sqrt(256.0)),
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
op_rows_expand = project("expand", r.attn_latent, r.attn.x);
RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384));
rows_output.stored = nm.f("blk.%d.attn_output.weight", layer);
RAD_ARCH_TRY(rows_output.declare(b, nm, g, nm.f("blk.%d.attn_output_rows", layer), 4096,
16384, RAD_SHARD_NONE, wg,
{ nm.ckpt("%s.o_proj.weight", prefix) }, r.attn, r.out,
R));
op_rows_gather = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4096, g.max_tok * 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ r.out }, { w.out });
return op_rows_absorb && op_rows_attn && op_rows_expand && op_rows_gather ? RAD_OK
: RAD_E_INVAL;
}
/* From the TP split threshold, and while the last rank's run is not empty (always at that
* threshold for up to 8 ranks); the same answer on every rank, as the gather needs. */
bool rows_take(int64_t T) const {
return op_rows_gather && GlmTp::splits(T, g.world) &&
(g.world - 1) * rows_for(T, g.world) < T;
}
void prepare(RadCtx* ctx, const RadBatch* batch) const {
const auto* kb = kv_batch(batch, kv);
if (!kb || !kb->slot_mapping) {
rad_step_fail(ctx, "GLM MLA requires latent cache slot mapping");
return;
}
const int64_t T = batch->n_tok;
q_a.step(ctx, w.input, w.q_raw, T);
kv_a.step(ctx, w.input, w.kv_raw, T);
q_norm.step(ctx, T);
RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T));
/* The row form splits the query projection into finish_rows (per rank), so q_b runs here
* only in the head form; the latent store below is full length either way. */
if (!rows_take(T)) q_b.step(ctx, w.q_low, w.core.q, T);
if (!kb->stream) {
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
return;
}
/* A streamed group writes its host mirror, and the ring slot only where the block is
* resident; the stage wait goes immediately before the store (core/kvstream/stage.h). A
* staged pass also stores at block-id identity, which is how the stage view is read. */
const bool staged = kv_stage_wait(ctx, kv, kb, layer);
const KVStreamLayer L = kv_stream_layer(ctx, kv, layer, kb);
if (!op_store_stream || !L.host || L.blocks <= 0) {
rad_step_fail(ctx, "GLM MLA: this layer's KV group streams but the build has no "
"kv_store_streamed row to write its host mirror with");
return;
}
RAD_ISSUE_N(ctx, op_store_stream, T, bcol(w.latent, 0, 256, T),
bcol(w.latent, 256, 256, T), praw(kb->slot_mapping, RAD_I32, T),
kv_cache(kv, layer), praw(L.res, RAD_I32, L.blocks),
praw2(L.host, RAD_U8, L.blocks, L.bbytes));
if (staged)
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
}
void finish(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const auto* kb = kv_batch(batch, kv);
/* A streamed group's selection is resolved here, after this layer's indexer wrote fresh
* block ids into the one `selected` buffer every layer shares and before either form of
* the attention reads it. A pass on the stage view reads block ids and never resolves. */
if (kb && kb->stream && !kv_stage_layer(ctx, kv, kb, layer) && T > 0) {
const KVStreamLayer L = kv_stream_layer(ctx, kv, layer, kb);
if (!op_resolve || !w.core.nsel || !L.host || L.blocks <= 0 || L.slots <= 0) {
rad_step_fail(ctx, "GLM MLA: this layer's KV group streams but the build has no "
"kv_resolve for its selection");
return;
}
/* The count is qsa_select's entry count, never `length` (a token count). */
kv_resolve_issue(ctx, op_resolve, L, brow_slice(w.core.selected, 0, T, core.c.blocks),
brow_slice(w.core.nsel, 0, T, 1), kv, layer, T);
}
if (rows_take(T)) {
finish_rows(ctx, T);
} else {
core.step(ctx, T);
attn_quant.step(ctx, T);
output.step(ctx, w.attn, w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
}
/* After every attention launch of this layer (core/kvstream/stage.h). */
if (kb && kb->stream) kv_stage_next(ctx, kv, layer);
}
/* This rank's rows [first, first + n) end to end; the last rank's run may be short, and the
* gather sends its unwritten tail rows, which land past T. */
void finish_rows(RadCtx* ctx, int64_t T) const {
const auto& r = w.rows;
const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kOutRowBytes);
const int64_t first = run.first, n = run.rows;
rows_q_b.step(ctx, w.q_low, r.q, T, first, n, 0);
RAD_ISSUE_N(ctx, op_rows_absorb, n, brows(r.q, n), RAD_W(rows_kv_b), brows(r.q_latent, n));
RAD_ISSUE_N(ctx, op_rows_attn, n, brows(r.q_latent, n), kv_cache(kv, layer),
brow_slice(w.core.selected, first, n, core.c.blocks),
brow_slice(w.core.length, first, n, 1), brows(r.attn_latent, n));
RAD_ISSUE_N(ctx, op_rows_expand, n, brows(r.attn_latent, n), RAD_W(rows_kv_b),
brows(r.attn.x, n));
rows_quant.step(ctx, n);
rows_output.step(ctx, r.attn, r.out, n);
RAD_ISSUE_N(ctx, op_rows_gather, run.run * 4096, brows(r.out, run.run),
brows(w.out, g.world * run.run));
}
};
}
} // namespace rad::arch
#endif
+203
View File
@@ -0,0 +1,203 @@
/* GLM-5.3's draft head: checkpoint layer 45 as a serial drafter (RAD_DRAFT_SERIAL), around the
* one MLA + indexer + MoE layer the plugin declares and steps itself.
*
* h = gather(the trunk's final hidden states, at the rows this pass continues from)
* e = embed(the token one position on), the encoder's rows over its placeholders
* x = eh_proj( concat( enorm(e), hnorm(h) ) ) the normalized embedding first
* x += attention(norm(x)); the proposal rows: x += moe(norm(x)) <- the plugin's layer
* h' = shared_head.norm(x); logits = the trunk's lm_head over h'
*
* h' is both the logits input and the next round's `h`. No mHC: the layer's residual is a plain
* add. By the sign of RadBatch::draft_pass a history pass (< 0) covers every row the trunk step
* had, fills the draft layer's latent, index and tail for all of them and runs the MoE and the
* head on the proposal rows only (draft_out_ids); a draft round (> 1) is one row a sequence.
*
* The block is declared and stepped in three parts around the layer, in this order: `inputs`
* before the layer's attention, `join` (the residual add and the proposal rows' selection) between
* its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's.
* Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass.
*
* The same head serves another DeepSeek-style drafter by its checkpoint layout, set before
* declare_inputs: the residual width, the layer's checkpoint prefix and index, and the name of the
* head's final norm (Ling-3.0: 2560, `model.layers.42`, 42, `final_layernorm.weight`). */
#ifndef RAD_BLOCK_GLM_MTP_H
#define RAD_BLOCK_GLM_MTP_H
#include "rad_glm_tp.h"
#include "rad_block_vit.h"
namespace rad {
namespace arch {
struct GlmMtp {
/* The trunk's: its final hidden states, its logits, its embedding and head. */
struct Wire {
rad_buf final_hidden = 0, logits = 0;
rad_weight token = 0, head = 0;
};
static constexpr int kDepth = 3; /* --num-speculative-tokens auto */
int64_t width = 4096;
const char* prefix = "model.language_model.layers.45";
int layer = 45;
const char* norm_src = "shared_head.norm.weight";
Names nm{ "mtp" };
Geom g{};
Wire w{};
rad_buf x = 0, hidden = 0, embedding = 0, concat = 0, out = 0;
rad_weight en = 0, hn = 0, eh = 0, norm = 0;
rad_op op_prev = 0, op_embed = 0, op_embed_ar = 0, op_en = 0, op_hn = 0, op_eh = 0;
rad_op op_residual = 0, op_select = 0, op_back = 0;
rad_op op_norm = 0, op_copy = 0, op_head = 0;
MediaRows mrows{};
/* The buffers, the weights, and the ops up to the layer's input. `media`: the encoder's rows
* replace the placeholders' embeddings, as the target's do (SGLang feeds its draft model the
* target's image rows); without them the drafts read the placeholder's embedding and
* acceptance falls on a prompt with a picture. */
int declare_inputs(RadBuilder* b, const Geom& geom, const Wire& wire, bool media) {
g = geom;
w = wire;
if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1)
return RAD_E_INVAL;
const int64_t E = width;
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, E });
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, E }, RAD_BUF_PERSIST);
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, E });
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 2 * E });
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, E });
const char* pre = prefix;
auto gain = [&](const char* n, const char* src) {
const char* name = nm.f("%s", n);
if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0;
return decl_w(b, name, RAD_F32, { E }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(layer));
};
en = gain("enorm.weight", "enorm.weight");
hn = gain("hnorm.weight", "hnorm.weight");
norm = gain("output_norm.weight", norm_src);
RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre)));
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { E, 2 * E }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh)
return RAD_E_INVAL;
op_prev = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", E),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.final_hidden }, { hidden });
op_embed = rw(b,
RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w.token)),
{}, { embedding });
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, E, embedding));
op_embed_ar = GlmTp::reduce(b, g, embedding, true);
op_en = rmsnorm(b, en, embedding, concat);
op_hn = rmsnorm(b, hn, hidden, concat);
op_eh = rw(b,
RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", E),
RAD_INT("K", 2 * E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(eh)),
{ concat }, { x });
return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar)
? RAD_OK
: RAD_E_INVAL;
}
/* Between the layer's attention and its feed-forward: the residual add of the attention's
* output `y`, and on a history pass the proposal rows gathered to the head of `x`. */
int declare_join(RadBuilder* b, rad_buf y) {
op_residual = rw(b,
RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x, y }, { x });
// All history rows fill the draft cache; only proposal rows need its FFN.
op_select = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x }, { hidden });
op_back = cast(b, hidden, x);
return op_residual && op_select && op_back ? RAD_OK : RAD_E_INVAL;
}
/* After the layer: the head's norm, its output kept as the next round's hidden, the logits,
* and the drafter's declaration. */
int declare_head(RadBuilder* b) {
op_norm = rmsnorm(b, norm, x, out);
op_copy = cast(b, out, hidden);
op_head = rw(b,
RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", width),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w.head)),
{ hidden }, { w.logits });
if (!op_norm || !op_copy || !op_head) return RAD_E_INVAL;
RadDrafterDecl dd{};
dd.name = "mtp";
dd.kind = RAD_DRAFT_SERIAL;
dd.depth = g.max_spec;
dd.mask_token = -1;
return rad_declare_drafter(b, &dd);
}
/* The rows a pass runs its feed-forward and head on: the proposal rows of a history pass,
* every row of a draft round. */
static int64_t head_rows(const RadBatch* batch) {
return batch->draft_pass < 0 ? batch->n_draft_out : batch->n_tok;
}
void step_inputs(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (batch->draft_pass < 0 && batch->n_out > 0)
RAD_ISSUE_N(c, op_prev, batch->n_out, RAD_B(w.final_hidden),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(hidden, batch->n_out));
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token),
brows(embedding, T));
mrows.step(c, batch, embedding, T);
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * width, brows(embedding, T), RAD_NONE);
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, width, T));
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, width, width, T));
RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T));
}
void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const {
const int64_t T = batch->n_tok, L = head_rows(batch);
RAD_ISSUE_N(c, op_residual, T, brows(x, T), brows(y, T), brows(x, T));
if (batch->draft_pass < 0) {
RAD_ISSUE_N(c, op_select, L, RAD_B(x), praw(batch->draft_out_ids, RAD_I32, L),
brows(hidden, L));
RAD_ISSUE_N(c, op_back, L, brows(hidden, L), brows(x, L));
}
}
void step_head(RadCtx* c, const RadBatch* batch) const {
const int64_t L = head_rows(batch);
RAD_ISSUE_N(c, op_norm, L, brows(x, L), RAD_W(norm), brows(out, L));
RAD_ISSUE_N(c, op_copy, L, brows(out, L), brows(hidden, L));
RAD_ISSUE_N(c, op_head, L, brows(hidden, L), RAD_W(w.head), brows(w.logits, L));
}
private:
rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const {
return rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain)),
{ in }, { out });
}
rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const {
return rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ in }, { out });
}
};
}
} // namespace rad::arch
#endif
+95
View File
@@ -0,0 +1,95 @@
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. With `groups`
* above 1 the selection is group-limited (router_sigmoid_group_topk, Ling-3.0's 8 groups, 4 kept). */
#ifndef RAD_BLOCK_GLM_ROUTER_H
#define RAD_BLOCK_GLM_ROUTER_H
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct GlmRouter {
struct Config {
int64_t experts = 288, top_k = 8, rows = 32, groups = 1, topk_groups = 1;
int norm = 1;
double route_scale = 2.5;
};
struct Src {
const char *weight = nullptr, *correction = nullptr;
};
struct Wire {
rad_buf input = 0, logits = 0, ids = 0, weights = 0;
};
Geom g{};
Config c{};
Wire w{};
rad_weight projection = 0, correction = 0;
rad_op op_project = 0, op_select = 0;
SplitF32Proj split{};
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name,
const Config& cfg, const Wire& wire, const Src& src) {
g = geom;
c = cfg;
w = wire;
if (!b || !name || !src.weight || !src.correction || g.n_embd < 1 || c.experts < 1 ||
c.experts > 512 || c.top_k < 1 || c.top_k > c.experts || c.rows < 1 ||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 ||
c.groups < 1 || c.experts % c.groups || c.topk_groups < 1 || c.topk_groups > c.groups ||
!w.input || !w.logits || !w.ids || !w.weights || w.logits == w.weights)
return RAD_E_INVAL;
const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name);
RAD_ARCH_TRY(map_copy(b, pn, src.weight));
RAD_ARCH_TRY(map_copy(b, cn, src.correction));
projection = decl_w(b, pn, RAD_F32, { c.experts, g.n_embd }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
correction = decl_w(b, cn, RAD_F32, { c.experts }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(layer));
if (!projection || !correction) return RAD_E_INVAL;
op_project = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.experts),
RAD_INT("K", g.n_embd), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.input }, { w.logits });
RAD_ARCH_TRY(split.declare(b, nm, g, name, c.rows, c.experts, g.n_embd, projection, w.input,
w.logits));
if (c.groups > 1)
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_group_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("n_group", c.groups),
RAD_INT("topk_group", c.topk_groups), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
else
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
return op_project && op_select ? RAD_OK : RAD_E_INVAL;
}
void project(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
if (split.takes(rows))
split.step(ctx, rows, brow_slice(w.input, first, rows, g.n_embd), projection,
brow_slice(w.logits, output_first, rows, c.experts));
else
RAD_ISSUE_N(ctx, op_project, rows, brow_slice(w.input, first, rows, g.n_embd),
RAD_W(projection), brow_slice(w.logits, output_first, rows, c.experts));
}
void step(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
project(ctx, first, rows, output_first);
RAD_ISSUE_N(ctx, op_select, rows, brow_slice(w.logits, output_first, rows, c.experts),
RAD_W(correction), brow_slice(w.ids, output_first, rows, c.top_k),
brow_slice(w.weights, output_first, rows, c.top_k));
}
};
}
} // namespace rad::arch
#endif
+379
View File
@@ -0,0 +1,379 @@
/* rad_block_glm_vision.h -- GLM-5.3's vision tower (transformers' Glm5NextVisionModel), served by
* glm5next.
*
* What it computes, per encoder pass (RadBatch::enc):
*
* x = patches @ Wp^T + bp the Conv3d patch embedding as a linear layer; a
* patch row is (channel, frame, y, x), no position
* table
* depth times:
* h = RMS(x) gain only
* q, k, v = qkv(h) with bias; q and k RMS-normed per head with a
* gain, then a 2-D rotary over (row, column):
* `axial` over NeoX pairs (i, i + head_dim / 2),
* the row on the first head_dim / 4 frequencies and
* the column on the next, each on its own ladder
* x += proj(attn(q, k, v)) full attention within a segment (one picture)
* x += down(silu(min(g, L)) * clamp(u, -L, L)), g | u = gate_up(RMS(x)) all with bias
* y = RMS(x) post_layernorm
* d = conv2d(y viewed [rows / 2, 2, 2, width], 2 x 2, stride 2) + bd the downsample: one row
* a merged block of merge x merge patches
* out = down'(silu(min(g', L)) * clamp(u', -L, L)), g' | u' = gate_up'(gelu(LN(proj'(d))))
* the merger: no biases but the LayerNorm's, exact
* GELU, the clip of the blocks
*
* which is the reference module for module. The processor stages patches in merge-block order (the
* merge x merge patches of one output row consecutive), so the downsample's input view is the
* reference's own: `conv2d_unfold` writes each merged block's receptive field as one row, its
* columns in the checkpoint weight's order (channel, kernel row, kernel column), and the weight is
* read as stored. Every linear with a bias is `gemm_nt_bias`, its residual in the epilogue.
*
* Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the
* weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx::
* max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's
* step and nothing is declared to the core. */
#ifndef RAD_BLOCK_GLM_VISION_H
#define RAD_BLOCK_GLM_VISION_H
#include "rad_arch.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct GlmVision {
/* Geometry, from the container's vision_config. */
int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0;
int64_t chans = 0, merge = 0, n_embd = 0, proj_ff = 0, patch_dim = 0, P = 0;
double eps = 1e-5, theta = 10000.0, limit = 0.0;
bool on = false;
struct Layer {
rad_weight n1 = 0, qkv_w = 0, qkv_b = 0, q_norm = 0, k_norm = 0, out_w = 0, out_b = 0;
rad_weight n2 = 0, gu_w = 0, gu_b = 0, down_w = 0, down_b = 0;
rad_op op_n1 = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_proj = 0, op_n2 = 0, op_gu = 0;
rad_op op_act = 0, op_down = 0;
};
std::vector<Layer> L;
rad_weight w_patch = 0, b_patch = 0, w_post = 0, w_ds = 0, b_ds = 0;
rad_weight w_mproj = 0, w_mln = 0, b_mln = 0, w_mgu = 0, w_mdown = 0;
rad_op op_patch = 0, op_post = 0, op_unfold = 0, op_ds = 0, op_mproj = 0, op_mln = 0;
rad_op op_gelu = 0, op_mgu = 0, op_mact = 0, op_mdown = 0;
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_post = 0, b_unf = 0;
rad_buf b_d = 0, b_m = 0, b_mgu = 0, b_mff = 0, b_out = 0;
char sec[48] = {};
/* Whether the container carries GLM-5.3's tower. */
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
return t && !std::strcmp(t, "glm5_next_vision");
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int GlmVision::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
Names& nm, int64_t model_embd, int first_group) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
depth = rad_meta_geti(m, "vision_config.depth", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_heads", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
temporal = rad_meta_geti(m, "vision_config.temporal_patch_size", 0);
chans = rad_meta_geti(m, "vision_config.in_channels", 3);
merge = rad_meta_geti(m, "vision_config.spatial_merge_size", 0);
n_embd = rad_meta_geti(m, "vision_config.out_hidden_size", 0);
proj_ff = rad_meta_geti(m, "vision_config.projection_intermediate_size", 0);
eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-5);
limit = rad_meta_getf(m, "vision_config.swiglu_limit", 0.0);
/* The checkpoint states no rotary; the reference's default is axial at 10000. */
theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0);
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial");
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "");
const bool bias = rad_meta_geti(m, "vision_config.attention_bias", 1) != 0;
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || temporal <= 0 ||
chans <= 0 || merge <= 0 || n_embd <= 0 || proj_ff <= 0 || width % heads ||
(width / heads) % 4 || !(eps > 0) || !(theta > 0)) {
fprintf(stderr, "radiance: glm5next: the container's vision_config is incomplete or "
"inconsistent (depth %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
"merge %lld, out %lld, projection %lld)\n", (long long)depth,
(long long)width, (long long)heads, (long long)ff, (long long)patch,
(long long)merge, (long long)n_embd, (long long)proj_ff);
return RAD_E_INVAL;
}
/* The clipped SwiGLU, the axial rotary and the biased linears are what this tower is; a
* checkpoint that turns one of them off is another tower. */
if (std::strcmp(act, "silu") || !(limit > 0) || !std::isfinite(limit) ||
std::strcmp(rt, "axial") || !bias) {
fprintf(stderr, "radiance: glm5next: this vision tower has a '%s' activation, swiglu_limit "
"%g, a '%s' rotary or no attention bias; it serves silu, a positive "
"limit, axial and biased linears\n", act, limit, rt);
return RAD_E_UNSUPPORTED;
}
/* The merger's rows replace token embeddings, so they must be the model's width. */
if (n_embd != model_embd) {
fprintf(stderr, "radiance: glm5next: the vision tower emits %lld-wide rows and the model "
"embeds %lld-wide tokens\n", (long long)n_embd, (long long)model_embd);
return RAD_E_INVAL;
}
head_dim = width / heads;
patch_dim = chans * temporal * patch * patch;
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4),
(long long)(head_dim / 4));
const int64_t mm = merge * merge;
P = ctx->max_enc_patches;
/* The longest segment attention may see: the real pass size, even in a sizing declare (see
* rad_block_vit.h). */
const int64_t max_seg = P;
if (ctx->shape_probe) {
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
P = std::max<int64_t>(mm, r / mm * mm);
}
if (P % mm) return RAD_E_SHAPE;
const int64_t R = P / mm;
const int ACC = RAD_ACCESS_PER_REQUEST;
/* ---- weights, replicated: model-level groups for the stem, downsample and merger, one group
* a block from `first_group` on. gate and up are joined into one GEMM, gate first, as
* swiglu_clamped splits its operand. */
auto copy = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
RadWeightGroup g) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
};
auto join = [&](const char* dn, const char* gate, const char* up,
std::initializer_list<int64_t> shp, RadWeightGroup g) -> rad_weight {
if (map_concat(b, dn, { gate, up }) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
};
const char* V = "model.visual";
w_patch = copy(nm.f("v.patch.weight"), nm.ckpt("%s.patch_embed.proj.weight", V),
{ width, patch_dim }, grp_model());
b_patch = copy(nm.f("v.patch.bias"), nm.ckpt("%s.patch_embed.proj.bias", V), { width },
grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const RadWeightGroup g = grp_layer(first_group + (int)i);
const int li = (int)i;
auto src = [&](const char* s) { return nm.ckpt("%s.blocks.%d.%s", V, li, s); };
auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); };
l.n1 = copy(dn("norm1.weight"), src("norm1.weight"), { width }, g);
l.qkv_w = copy(dn("qkv.weight"), src("attn.qkv.weight"), { 3 * width, width }, g);
l.qkv_b = copy(dn("qkv.bias"), src("attn.qkv.bias"), { 3 * width }, g);
l.q_norm = copy(dn("q_norm.weight"), src("attn.q_norm.weight"), { head_dim }, g);
l.k_norm = copy(dn("k_norm.weight"), src("attn.k_norm.weight"), { head_dim }, g);
l.out_w = copy(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g);
l.out_b = copy(dn("proj.bias"), src("attn.proj.bias"), { width }, g);
l.n2 = copy(dn("norm2.weight"), src("norm2.weight"), { width }, g);
l.gu_w = join(dn("gate_up.weight"), src("mlp.gate_proj.weight"), src("mlp.up_proj.weight"),
{ 2 * ff, width }, g);
l.gu_b = join(dn("gate_up.bias"), src("mlp.gate_proj.bias"), src("mlp.up_proj.bias"),
{ 2 * ff }, g);
l.down_w = copy(dn("down.weight"), src("mlp.down_proj.weight"), { width, ff }, g);
l.down_b = copy(dn("down.bias"), src("mlp.down_proj.bias"), { width }, g);
if (!l.n1 || !l.qkv_w || !l.qkv_b || !l.q_norm || !l.k_norm || !l.out_w || !l.out_b ||
!l.n2 || !l.gu_w || !l.gu_b || !l.down_w || !l.down_b)
return RAD_E_INVAL;
}
w_post = copy(nm.f("v.post_norm.weight"), nm.ckpt("%s.post_layernorm.weight", V), { width },
grp_model());
/* [out, width, merge, merge] read as [out, width * merge^2]: conv2d_unfold's column order. */
w_ds = copy(nm.f("v.downsample.weight"), nm.ckpt("%s.downsample.weight", V),
{ n_embd, mm * width }, grp_model());
b_ds = copy(nm.f("v.downsample.bias"), nm.ckpt("%s.downsample.bias", V), { n_embd },
grp_model());
w_mproj = copy(nm.f("v.merger.proj.weight"), nm.ckpt("%s.merger.proj.weight", V),
{ n_embd, n_embd }, grp_model());
w_mln = copy(nm.f("v.merger.norm.weight"),
nm.ckpt("%s.merger.post_projection_norm.weight", V), { n_embd }, grp_model());
b_mln = copy(nm.f("v.merger.norm.bias"), nm.ckpt("%s.merger.post_projection_norm.bias", V),
{ n_embd }, grp_model());
w_mgu = join(nm.f("v.merger.gate_up.weight"), nm.ckpt("%s.merger.gate_proj.weight", V),
nm.ckpt("%s.merger.up_proj.weight", V), { 2 * proj_ff, n_embd }, grp_model());
w_mdown = copy(nm.f("v.merger.down.weight"), nm.ckpt("%s.merger.down_proj.weight", V),
{ n_embd, proj_ff }, grp_model());
if (!w_patch || !b_patch || !w_post || !w_ds || !b_ds || !w_mproj || !w_mln || !b_mln ||
!w_mgu || !w_mdown)
return RAD_E_INVAL;
/* ---- activations. `post` is declared at merge x width: the norm writes P rows of `width`
* and conv2d_unfold reads the same bytes as P / merge rows of `merge` columns (dh rows of dw
* columns), the reference's view() with no copy. */
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
b_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, { P, 2 * ff });
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
b_post = decl_b(b, nm.f("v.post"), RAD_BF16, { P / merge, merge * width });
b_unf = decl_b(b, nm.f("v.unf"), RAD_BF16, { R, mm * width });
b_d = decl_b(b, nm.f("v.d"), RAD_BF16, { R, n_embd });
b_m = decl_b(b, nm.f("v.m"), RAD_BF16, { R, n_embd });
b_mgu = decl_b(b, nm.f("v.mgu"), RAD_BF16, { R, 2 * proj_ff });
b_mff = decl_b(b, nm.f("v.mff"), RAD_BF16, { R, proj_ff });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_qkv || !b_att || !b_gu || !b_ff || !b_post || !b_unf || !b_d || !b_m ||
!b_mgu || !b_mff || !b_out)
return RAD_E_INVAL;
auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, rad_weight w, rad_weight bw) -> rad_op {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", "none")),
RAD_WEIGHTS(w, bw));
};
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op {
return RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto rms = [&](int64_t rows, rad_weight w) -> rad_op {
return RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto swiglu = [&](int64_t rows, int64_t n) -> rad_op {
return RAD_OP(b, "swiglu_clamped",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("limit", limit), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
op_patch = rw(b, gemm_b(P, width, patch_dim, w_patch, b_patch), {}, { b_x });
for (Layer& l : L) {
l.op_n1 = rw(b, rms(P, l.n1), { b_x }, { b_h });
l.op_qkv = rw(b, gemm_b(P, 3 * width, width, l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
RAD_F64("theta", theta), RAD_F64("eps", eps),
RAD_STR("mode", "axial"),
RAD_INT("rotary_dim", head_dim),
RAD_STR("sections", sec)),
RAD_WEIGHTS(l.q_norm, l.k_norm)),
{ b_qkv }, { b_qkv });
l.op_attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
RAD_INT("max_seqlen", max_seg)),
RAD_NOWEIGHTS),
{ b_qkv }, { b_att });
l.op_proj = rw(b, gemm_b(P, width, width, l.out_w, l.out_b), { b_att, b_x }, { b_x });
l.op_n2 = rw(b, rms(P, l.n2), { b_x }, { b_h });
l.op_gu = rw(b, gemm_b(P, 2 * ff, width, l.gu_w, l.gu_b), { b_h }, { b_gu });
l.op_act = rw(b, swiglu(P, ff), { b_gu }, { b_ff });
l.op_down = rw(b, gemm_b(P, width, ff, l.down_w, l.down_b), { b_ff, b_x }, { b_x });
}
op_post = rw(b, rms(P, w_post), { b_x }, { b_post });
/* Input rows are P / merge (one kernel row of merge patches each) and a segment's rows are its
* patches over merge, so a picture of whole merged blocks starts on an even row. */
op_unfold = rw(b, RAD_OP(b, "conv2d_unfold",
RAD_PARAMS(RAD_RANGE("M", 1, P / merge), RAD_INT("width", merge),
RAD_INT("cin", width), RAD_INT("kh", merge),
RAD_INT("kw", merge), RAD_INT("stride", merge),
RAD_INT("pad", 0), RAD_INT("cu_div", merge),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_post }, { b_unf });
op_ds = rw(b, gemm_b(R, n_embd, mm * width, w_ds, b_ds), { b_unf }, { b_d });
op_mproj = rw(b, gemm(R, n_embd, n_embd, w_mproj), { b_d }, { b_m });
/* torch.nn.LayerNorm's default eps: the merger states none. */
op_mln = rw(b, RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_mln, b_mln)),
{ b_m }, { b_d });
op_gelu = rw(b, RAD_OP(b, "gelu",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_d }, { b_m });
op_mgu = rw(b, gemm(R, 2 * proj_ff, n_embd, w_mgu), { b_m }, { b_mgu });
op_mact = rw(b, swiglu(R, proj_ff), { b_mgu }, { b_mff });
op_mdown = rw(b, gemm(R, n_embd, proj_ff, w_mdown), { b_mff }, { b_out });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE;
e.patch_dim = patch_dim;
e.merge = mm;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld clipped at %g, "
"patch %lld x %lld x %lld, %lld x %lld downsample, merger %lld; %lld patches a "
"pass -> %lld rows of %lld", (long long)depth, (long long)width,
(long long)heads, (long long)head_dim, (long long)ff, limit, (long long)temporal,
(long long)patch, (long long)patch, (long long)merge, (long long)merge,
(long long)proj_ff, (long long)P, (long long)R, (long long)n_embd);
}
on = true;
return RAD_OK;
}
inline void GlmVision::step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
const int64_t mm = merge * merge, Rn = Pn / mm;
if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0) {
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or "
"more patches than it was declared for, or not whole merged rows");
return;
}
/* Patches, coordinates (planes 0-1 a dense [2, P] of (row, column)) and segment boundaries,
* staged by the core. */
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand rc = praw2(batch->enc_coord, RAD_I32, 2, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn));
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.op_n1, Pn, brows(b_x, Pn), RAD_W(l.n1), brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
brows(b_qkv, Pn));
RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
RAD_ISSUE_N(c, l.op_proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
brows(b_x, Pn), brows(b_x, Pn));
RAD_ISSUE_N(c, l.op_n2, Pn, brows(b_x, Pn), RAD_W(l.n2), brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gu_w), RAD_W(l.gu_b), RAD_NONE,
brows(b_gu, Pn));
RAD_ISSUE_N(c, l.op_act, Pn, brows(b_gu, Pn), brows(b_ff, Pn));
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
brows(b_x, Pn), brows(b_x, Pn));
}
/* The norm writes Pn rows of `width`; the unfold reads them as Pn / merge rows. */
RAD_ISSUE_N(c, op_post, Pn, brows(b_x, Pn), RAD_W(w_post), brows(b_post, Pn / merge));
RAD_ISSUE_N(c, op_unfold, Pn / merge, brows(b_post, Pn / merge), cu, RAD_NONE,
brows(b_unf, Rn));
RAD_ISSUE_N(c, op_ds, Rn, brows(b_unf, Rn), RAD_W(w_ds), RAD_W(b_ds), RAD_NONE,
brows(b_d, Rn));
RAD_ISSUE_N(c, op_mproj, Rn, brows(b_d, Rn), RAD_W(w_mproj), brows(b_m, Rn));
RAD_ISSUE_N(c, op_mln, Rn, brows(b_m, Rn), RAD_W(w_mln), RAD_W(b_mln), brows(b_d, Rn));
RAD_ISSUE_N(c, op_gelu, Rn, brows(b_d, Rn), brows(b_m, Rn));
RAD_ISSUE_N(c, op_mgu, Rn, brows(b_m, Rn), RAD_W(w_mgu), brows(b_mgu, Rn));
RAD_ISSUE_N(c, op_mact, Rn, brows(b_mgu, Rn), brows(b_mff, Rn));
RAD_ISSUE_N(c, op_mdown, Rn, brows(b_mff, Rn), RAD_W(w_mdown), brows(b_out, Rn));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_GLM_VISION_H */
+224 -129
View File
@@ -1,13 +1,12 @@
/* rad_block_hc.h -- the GATED RESIDUAL, which is what Qwen4-Exp has instead of a pre-norm and a
* residual add.
/* rad_block_hc.h -- the gated residual (hyper-connection) Qwen4-Exp uses instead of a pre-norm
* and a residual add.
*
* ============================== THE RESIDUAL STREAM IS `hc` TIMES AS WIDE ==============================
*
* hidden_size 2560 at hc_count 4 is a 10240-wide stream. It is entered as FOUR IDENTICAL COPIES of
* the embedding, carried through all 48 layers, and collapsed once at the end by a connection with
* no write half. Every block -- attention or delta net, then the feed-forward, so 96 of them --
* reads a 2560 mix of the four streams and writes its output back into all four, and both halves
* are data-dependent:
* hidden_size 2560 at hc_count 4 gives a 10240-wide stream, entered as four identical copies of
* the embedding, carried through all 48 layers, and collapsed at the end by a connection with no
* write half. Each of the 96 blocks (attention or delta net, then feed-forward) reads a 2560 mix
* of the four streams and writes its output back into all four; both halves are data-dependent:
*
* read N = grouped_rmsnorm(h) one rsqrt per 2560 stream, one 10240 gain, `1 + w`
* g = sigmoid(mix_up @ silu(mix_down @ N / hc))
@@ -15,37 +14,21 @@
* inj[s] = 2 * sigmoid(inject_w[s] . N / hc) -> four scalars in (0, 2)
* write h[s] += inj[s] * y for each stream s
*
* docs/OPS.md's `hc_read` / `hc_write` rows carry the same statement and name the three choices a
* second implementation has to match (the mix is a MEAN; each gate argument has its own `/ hc`;
* the write adds into the UNNORMED stream).
* docs/OPS.md's `hc_read` / `hc_write` rows state the same and name what a second implementation
* must match: the mix is a mean, each gate argument has its own `/ hc`, and the write adds into
* the unnormed stream.
*
* ============================== WHY IT IS A BLOCK AND NOT TWO CALLS ==============================
* One struct declares both halves because they share weights and buffers and must pair: each
* write consumes the `inj` of its own read.
*
* Because the two halves share a weight set and a buffer set, and because the pairing is the
* invariant: a read whose `inj` nothing consumes is a bug, and a write whose `inj` came from a
* different read is a worse one. One struct declares both, holds the four weights once, and gives
* the plugin a `read()` and a `write()` that cannot be mismatched.
* Cost: the arithmetic is small (2 x 10240 x 320 + 4 x 10240 = 6.6M MACs per token, about one
* expert pair); the cost is launches, 96 connections per step. So the read emits the fp8 form of
* `x` itself instead of a following `quant_act_fp8`, and the write could later be folded into the
* producing block's epilogue.
*
* ============================== WHAT IT COSTS, AND WHERE THAT GOES ==============================
*
* The arithmetic is nothing: 2 x 10240 x 320 plus 4 x 10240 is 6.6M MACs a token against the 5.9M
* of one expert pair. The LAUNCHES are the cost. A kernel costs a dispatch whatever it computes,
* and there are 96 connections a step, so every extra op in a connection is 96 more dispatches --
* a real share of a decode budget measured in tens of milliseconds.
*
* That is why the read emits the fp8 form of `x` itself rather than leaving a `quant_act_fp8`
* behind it, and it is why the write is a candidate to be FOLDED INTO THE PRODUCING BLOCK'S
* EPILOGUE later (this tree's own rule: fold the quantiser into the producer, and quantise the
* bf16 that was written). Neither the read's five ops nor the write's one are on the table as
* separate launches.
*
* ============================== WHAT IS NOT SHARDED ==============================
*
* Nothing here. The residual stream is replicated on every rank (spec §9) and so is every weight
* in this file: 6.7 MB a connection at bf16, 1.3 GB over the model, which is the price of not
* putting a collective inside the connection. A sharded low-rank gate would need an all-reduce
* between `mix_down` and `mix_up` -- 96 more collectives a step, on 1280 bytes each, and a decode
* all-reduce is mostly fixed cost whatever the message.
* Nothing is sharded: the residual stream is replicated (spec §9), and so are these weights
* (6.7 MB per connection at bf16, 1.3 GB over the model). Sharding the low-rank gate would add an
* all-reduce between `mix_down` and `mix_up`, 96 more small collectives per step.
*/
#ifndef RAD_BLOCK_HC_H
#define RAD_BLOCK_HC_H
@@ -55,12 +38,9 @@
namespace rad {
namespace arch {
/* THE WIDE STREAM'S FIRST VALUE: hc identical copies of the embedding.
*
* One launch for the whole step, and it is its own op rather than part of the embedding lookup
* because that op's weight is [vocab, n_embd] and its output width is n_embd -- a wide output
* would be a different weight shape. The copies are identical here and diverge at the first
* connection, since every block writes into all hc streams with a DIFFERENT per-branch gain. */
/* Initialises the wide stream with hc identical copies of the embedding, one launch per step.
* Separate from the embedding lookup, whose output width is n_embd. The copies diverge at the
* first write, which uses a different gain per stream. */
struct HcEnter {
Geom g{};
int64_t hc = 0;
@@ -87,31 +67,33 @@ struct HyperConn {
struct Config {
int64_t hc = 0; /* streams; the reference refuses hc <= 1 and so does this */
int64_t lowrank = 0; /* the read gate's waist */
/* Whether this connection has a WRITE half. The final mixer does not: it collapses the
* wide stream into the one hidden state the lm_head reads and nothing follows it. */
/* Whether the connection has a write half. The final mixer does not: it collapses the
* stream into the hidden state the lm_head reads. */
int inject = 1;
/* Whether the read also emits the block input's fp8 codes. The trunk connections all do;
* the mixer does not, because its consumer is the lm_head, which reads a bf16 input. */
/* Whether the read also emits the block input's fp8 codes. Not for the final mixer, whose
* consumer (the lm_head) reads bf16. */
int quant = 1;
/* Whether the WRITE also carries the all-reduce of the block's output, which the block in
* front then skips on every step takes_ar() answers yes to. The block's partial sum and the
* write's input are the same buffer, so the reduction moves into the write's kernel and
* the pair's second launch disappears. */
/* Whether the write also performs the all-reduce of the block's output; the block then
* skips its own on every step takes_ar() accepts. The block's partial sum is the write's
* input buffer, so this saves a launch. */
int reduce = 0;
/* Whether the read also emits the HADAMARD-ROTATED fp8 codes of the block input, for a
* consumer whose weight carries the rotation (MoeFP8's rotated expert plane). They ride in
* the plain codes' finisher, so this needs `quant`, and the consumer then declares no
* quantiser of its own -- one dependent launch fewer a connection. */
/* Whether the read also emits Hadamard-rotated codes of the block input, for a consumer
* whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in the
* plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
int rotate = 0;
/* Whether those codes are INT8 (the input's q8/s8 pair) rather than E4M3 (q/s): a model
* whose trunk linears are int8 (LinearFP8::i8) reads them there, so the read writing them
* is one quantiser launch fewer a consumer. The rotated twin stays E4M3 either way -- it
* is the routed experts' operand. */
/* Whether the plain codes are int8 (q8/s8) rather than E4M3 (q/s), for int8 trunk linears
* (LinearFP8::i8). The rotated codes take the same dtype (had_quant_act_i8g's beside int8,
* had_quant_act_fp8's beside E4M3), so `Wire::rq` is declared to match. */
int codes_i8 = 0;
/* The most rows one read is declared for, 0 for max_tok; a wider step reads in pieces
* (read_pieces). The read's scratch is sized for its band (some 22 KiB a row at
* Flash-Next's shape, on every lane with a scratch region), so a model that reads a wider
* step in pieces anyway declares the band no wider than a piece. */
int64_t read_rows = 0;
};
struct Wire {
rad_buf h = 0; /* [max_tok, hc * n_embd] THE WIDE STREAM, in place */
rad_buf h = 0; /* [max_tok, hc * n_embd] the wide stream, updated in place */
ActFP8 x{}; /* [max_tok, n_embd] the block input; q/s unused if !quant */
rad_buf inj = 0; /* [max_tok, hc] the per-branch write gains */
rad_buf rq = 0; /* [max_tok, n_embd] the rotated codes, when `rotate` */
@@ -130,21 +112,25 @@ struct HyperConn {
Wire w{};
rad_weight w_norm = 0, w_down = 0, w_up = 0, w_inj = 0;
/* Whether the two mixing matrices are E4M3 rows with a scale a group of each row rather than
* bf16 -- OPS.md's `mix` -- which is their encoding's to say, read at declare. */
/* Whether the mixing matrices are E4M3 rows with a per-group scale rather than bf16 (OPS.md's
* `mix`), read from their encoding at declare. */
bool mix_e4m3 = false;
rad_op op_read = 0, op_write = 0;
/* The write with the all-reduce folded in; 0 when not asked for or when no kernel serves it.
* `op_ar_write6` is the same write on the ROTATED 6-BIT wire, declared only where a step can
* reach that wire -- an install that accepts a lossy payload -- and issued on exactly the steps
* ar_wire_is_exact answers no to: at a prefill chunk that is every all-reduce the trunk makes,
* and the payload is 2.6x smaller than the exact one. */
/* The block input's own int8 pair is the rotated one (ActFP8::q8_rot, a trunk stored rotated):
* the read writes its rotated codes there and its plain ones into `pq` / `ps`, a pair of this
* connection's that nothing reads. */
bool xrot = false;
rad_buf pq = 0, ps = 0;
/* The write with the all-reduce folded in; 0 when not requested or not served.
* `op_ar_write6` is the same on the rotated 6-bit wire, declared only when a lossy payload is
* accepted and issued on the steps ar_wire_is_exact rejects (every trunk all-reduce at a
* prefill chunk); its payload is 2.6x smaller. */
rad_op op_ar_write = 0;
rad_op op_ar_write6 = 0;
/* AND WITH THE MoE GATHER FOLDED IN FRONT OF THAT: the block behind this write leaves its
* routed experts' rows unsummed, and the reduction's message is their sum. Declared by
* declare_gather() after the block, whose buffers it reads; `gather_rows` is the bound it serves
* and 0 when it was not declared or no kernel serves it (see gather_taken). */
/* The same with the MoE gather folded in front: the block leaves its routed experts' rows
* unsummed, and the reduction's message is their sum. Declared by declare_gather() after the
* block, whose buffers it reads; `gather_rows` is its bound, 0 when not declared or not
* served (see gather_taken). */
struct GatherSrc {
rad_buf ye = 0, ew = 0, sorted = 0, sh = 0, sg = 0; /* sh and sg: the shared arm, or 0 */
int64_t top_k = 0;
@@ -155,17 +141,17 @@ struct HyperConn {
int64_t gather_rows = 0, gather_rows6 = 0;
int64_t hn() const { return c.hc * g.n_embd; }
/* THE REDUCING WRITE THIS STEP ISSUES, on the wire its message goes out on; 0 where that wire
* has no fused form, and the block's own collective then runs in front of the plain write. At
* four ranks there is no rotated form, so a step ar_exact_write_takes declines gets 0. */
/* The reducing write for this step's wire, or 0 when that wire has no fused form (then the
* block's own collective runs before the plain write). At four ranks there is no rotated
* form, so steps ar_exact_write_takes declines get 0. */
rad_op ar_write(int64_t T) const {
return ar_exact_write_takes(g, T) ? op_ar_write : op_ar_write6;
}
/* WHETHER THIS STEP'S WRITE REDUCES THE BLOCK'S OUTPUT. The block in front asks the same
* question of the same T -- ar_taken with ar_take() -- before skipping its own collective. */
/* Whether this step's write reduces the block's output. The block asks the same of the same T
* (ar_taken with ar_take()) before skipping its own collective. */
bool takes_ar(int64_t T) const { return ar_write(T) != 0; }
/* What that block is told: which wires this write takes. The rotated form is declared only
* beside the exact one, so the two together take every message. */
/* Which wires this write takes, for the block. The rotated form exists only beside the exact
* one, so together they take every message. */
int ar_take() const { return op_ar_write6 ? kArOutBoth : kArOutExact; }
bool takes_gather(int64_t T) const {
return takes_ar(T) && gather_taken(g, T, gather_rows, gather_rows6);
@@ -179,6 +165,16 @@ struct HyperConn {
void read (RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const;
void write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const;
/* The read over rows [0, T), in pieces of Config::read_rows where it is set; one read
* otherwise. The read's down product splits K by how many row tiles it is handed
* (hc_down_kchunk in libr4d), so one read over twice the rows sums in a different order than
* two reads over half of them; reading a wide step in pieces computes what the narrower steps
* did. */
void read_pieces(RadCtx* c_, int64_t T) const {
const int64_t piece = c.read_rows;
if (piece <= 0 || T <= piece) { read(c_, T, 0, T); return; }
for (int64_t r0 = 0; r0 < T; r0 += piece) read(c_, T, r0, T - r0 < piece ? T - r0 : piece);
}
};
inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const char* name,
@@ -191,9 +187,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
return RAD_E_INVAL;
}
if (!src.norm || !src.mix_down || !src.mix_up) return RAD_E_INVAL;
/* An inject WEIGHT with no `inj` buffer, or the reverse, is a connection whose two halves
* disagree about whether there is a write. Refused here rather than discovered as an
* all-rejected draft three stages later. */
/* The inject weight and the `inj` buffer must both be present or both absent. */
if (c.inject && (!src.inject_w || !w.inj)) {
fprintf(stderr, "radiance: %s: inject is on but %s is missing\n", name,
src.inject_w ? "the inj buffer" : "block_inject_weight");
@@ -205,6 +199,17 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
return RAD_E_INVAL;
}
if (c.quant && (c.codes_i8 ? (!w.x.q8 || !w.x.s8) : (!w.x.q || !w.x.s))) return RAD_E_INVAL;
/* A trunk whose int8 linears are stored rotated reads the rotated codes alone: `x`'s int8 pair
* is then that pair (ActFP8::q8_rot), and every reader of the block input -- the trunk's
* projections and the rotated experts -- takes it. The read derives the rotated codes in its
* plain codes' finisher, so the plain ones still have somewhere to go: a pair of this
* connection's own that nothing reads. */
xrot = c.quant && c.codes_i8 && w.x.q8_rot;
if (xrot && c.rotate) {
fprintf(stderr, "radiance: %s: the block input's own codes are the rotated ones "
"(ActFP8::q8_rot), so there is no second rotated pair to ask for\n", name);
return RAD_E_INVAL;
}
if (c.rotate && (!c.quant || !w.rq || !w.rs)) {
fprintf(stderr, "radiance: %s: the rotated codes need the plain ones (quant) and the "
"rq/rs pair on the wire\n", name);
@@ -214,7 +219,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
const int64_t HN = hn();
/* The name maps first: they are how the model is asked what each weight is. */
/* Maps first: weight encodings are looked up through them. */
const char* nn = nm.f("%s_norm.weight", name);
const char* dn = nm.f("%s_down.weight", name);
const char* un = nm.f("%s_up.weight", name);
@@ -224,10 +229,9 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
RAD_ARCH_TRY(map_copy(b, un, src.mix_up));
if (c.inject) RAD_ARCH_TRY(map_copy(b, in, src.inject_w));
/* THE MIXING MATRICES ARE WHATEVER THEIR ENCODING IS: bf16, or E4M3 rows with a scale a
* group of each row -- lowrank 320 is 2.5 scale blocks, so a 128x128 tile cannot cover them.
* Each is declared over every plane it has, at the codes' dtype, and the read's kernel takes
* codes and scales together. The two are one format or the read has no kernel. */
/* The mixing matrices are bf16 or E4M3 rows with a per-group scale (lowrank 320 is 2.5 scale
* blocks, so 128x128 tiles do not fit). Each is declared over all its planes at the codes'
* dtype; both must share one format for the read kernel. */
const uint32_t mdt = weight_codes_dtype(b, dn, RAD_BF16);
if (weight_codes_dtype(b, un, RAD_BF16) != mdt || (mdt != RAD_BF16 && mdt != RAD_F8E4M3)) {
fprintf(stderr, "radiance: %s: the mixing matrices are %s and %s; a connection reads both "
@@ -237,8 +241,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
}
mix_e4m3 = mdt == RAD_F8E4M3;
/* F32 like every other norm gain in this tree: 10240 numbers read once a connection, and the
* norm's arithmetic is f32 regardless, so narrowing them buys nothing. */
/* F32 like every norm gain in this tree. */
w_norm = decl_w(b, nn, RAD_F32, {HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_down = decl_w(b, dn, mdt, {c.lowrank, HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_model());
@@ -249,34 +252,39 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
grp_model());
if (!w_norm || !w_down || !w_up || (c.inject && !w_inj)) return RAD_E_INVAL;
/* `inject` and `group` are declared even when off, with the value 0, because a kernel row
* bands on them: a fused read that writes four gates is a different kernel from one that does
* not, and the resolver needs to be able to say so. An ABSENT key fails a constraint, so
* leaving them out would make both rows unselectable rather than one. */
/* RAD_WEIGHTS expands to TWO arguments -- the array and its length -- so it cannot sit in a
* ternary, and the four-or-three choice is made by building the array. The absent inject
* weight is a SHORTER list and not a zero handle: rad_plugin.h's absent-operand rule is about
* the launch, but a declared weight of 0 is a declaration failure here. */
/* `inject` and `group` are declared as 0 when off, not omitted: kernel rows constrain them, and
* an absent key fails every constraint.
*
* RAD_WEIGHTS expands to two arguments, so the weight list is built as an array. A missing
* inject weight shortens the list; a zero weight handle would be a declaration failure. */
const rad_weight wts[4] = { w_norm, w_down, w_up, w_inj };
const int n_wts = c.inject ? 4 : 3;
/* The write set is positional and the optional OUTPUTS are the tail, so an absent one shortens
* the list exactly as an absent weight does. The read's outputs are x, inj?, q?, scale? and
* both switches drop a suffix, never a middle -- which is why the schema puts inj before the
* quantiser's pair rather than after. */
/* Outputs are x, inj?, codes?, scales?, rotated pair?. The write set is positional with
* optional outputs at the tail, so an absent one shortens the list. */
rad_buf wr[6] = { w.x.x, 0, 0, 0, 0, 0 };
int n_wr = 1;
if (c.inject) wr[n_wr++] = w.inj;
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
if (xrot) {
pq = decl_b(b, nm.f("%s.plain.q8", name), RAD_I8, { g.max_tok, g.n_embd });
ps = decl_b(b, nm.f("%s.plain.s8", name), RAD_F32, { g.max_tok, fp8_blocks(g.n_embd) });
if (!pq || !ps || w.x.g8 != RAD_FP8_BLOCK) return RAD_E_INVAL;
wr[n_wr++] = pq; wr[n_wr++] = ps;
wr[n_wr++] = w.x.q8; wr[n_wr++] = w.x.s8;
} else {
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
}
op_read = RAD_OP(b, "hc_read",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_PARAMS(RAD_RANGE("M", 1, c.read_rows > 0 && c.read_rows < g.max_tok
? c.read_rows : g.max_tok),
RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("lowrank", c.lowrank),
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
RAD_F64("wadd", g.wadd), RAD_INT("inject", c.inject ? 1 : 0),
RAD_INT("group", c.quant ? RAD_FP8_BLOCK : 0),
RAD_INT("rotate", c.rotate ? 1 : 0),
RAD_INT("rotate", (c.rotate || xrot) ? 1 : 0),
RAD_STR("mix", mix_e4m3 ? "e4m3" : "bf16")),
wts, n_wts);
if (!op_read) return RAD_E_INVAL;
@@ -293,12 +301,9 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
RAD_NOWEIGHTS),
{w.x.x, w.inj, w.h}, {w.h});
if (!op_write) return RAD_E_INVAL;
/* A handle that did not resolve is 0 and not an error: a backend without the fused kernel
* keeps the pair, and takes_ar() then answers no on every step. At four ranks only the
* exact form exists, declared over the decode and verify steps' rows and taken where
* ar_wide_write_exact says so. The exact form states `wire` 0 rather than leaving it out:
* a row that serves one wire only says so with a constraint on `wire`, and a constraint on
* an absent key does not hold. */
/* An unresolved handle is 0, not an error: without the fused kernel the pair runs and
* takes_ar() always answers no. At four ranks only the exact form exists, declared over the
* decode and verify rows. `wire` 0 is stated, not omitted, because rows constrain it. */
const int64_t ar_rows = ar_exact_write_rows(g);
if (c.reduce && ar_rows >= 1)
op_ar_write = rw(b, RAD_OP(b, "ar_hc_write",
@@ -307,9 +312,9 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
RAD_STR("dtype", g.dtype), RAD_INT("wire", 0)),
RAD_NOWEIGHTS),
{w.x.x, w.inj, w.h}, {w.x.x, w.h});
/* The rotated form at two ranks only: the op has no four-rank form on that wire
* (docs/OPS.md), and an op declared that nothing resolves is reported at startup as a
* band a request cannot run in. */
/* The rotated form at two ranks only: there is no four-rank form on that wire
* (docs/OPS.md), and an unresolvable op would be reported at startup as an unservable
* band. */
if (op_ar_write && !g.wire_exact && g.world == 2)
op_ar_write6 = rw(b, RAD_OP(b, "ar_hc_write",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
@@ -323,26 +328,22 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
inline int HyperConn::declare_gather(RadBuilder* b, const GatherSrc& src) {
if (!op_ar_write || src.top_k <= 0 || !src.ye || !src.ew || !src.sorted) return RAD_OK;
/* Two ranks, and four on the exact wire: there the fused write exists in its exact form only,
* so the gather does too -- op_ar_write6 is 0 at four and the rotated form below is never
* declared. Any other width keeps its gather and both bounds stay 0. */
/* Two or four ranks. At four only the exact form exists (op_ar_write6 is 0). Other widths keep
* the block's own gather and both bounds stay 0. */
if (g.world != 2 && g.world != 4) return RAD_OK;
const bool shared = src.sh && src.sg;
gsrc = src;
/* EVERY ROW COUNT ONE PASS CARRIES, up to the rows the write itself was declared for
* (ar_exact_write_rows): prefill chunks included at two ranks, the decode and verify steps at
* four. The kernel reads its slots from an LDS table at a decode step and from an inverse
* table at a chunk, where the gather's reads then run beside the reduction's push instead of
* in a launch of their own. */
/* Up to one pass's rows, capped at the write's own bound (ar_exact_write_rows): prefill chunks
* at two ranks, decode and verify steps at four. The kernel reads its slots from an LDS table
* at decode and from an inverse table at a chunk. */
int64_t rows = src.rows;
const int64_t ar_rows = ar_exact_write_rows(g);
if (rows > ar_rows) rows = ar_rows;
if (rows < 1) return RAD_OK;
const rad_buf rd[8] = { src.ye, src.ew, src.sorted, w.x.x, w.inj, w.h, src.sh, src.sg };
const rad_buf wr[2] = { w.x.x, w.h };
/* One op a wire, as the write itself: the rotated form beside the rotated write only. A handle
* that did not resolve is 0 and not an error: the block keeps its gather and this write keeps
* the reduction alone, and that wire's bound stays 0 so both say so. */
/* One op per wire, the rotated form only beside the rotated write. An unresolved handle is 0:
* the block keeps its gather and that wire's bound stays 0. */
op_ar_gather_write = RAD_OP(b, "ar_gather_hc_write",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("top_k", src.top_k),
@@ -382,16 +383,110 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
c.inject ? RAD_W(w_inj) : RAD_NONE,
brow_slice(w.x.x, r0, rows, g.n_embd),
c.inject ? brow_slice(w.inj, r0, rows, c.hc) : RAD_NONE,
c.quant ? brow_slice(c.codes_i8 ? w.x.q8 : w.x.q, r0, rows, g.n_embd) : RAD_NONE,
c.quant ? brow_slice(c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
c.quant ? brow_slice(xrot ? pq : c.codes_i8 ? w.x.q8 : w.x.q, r0, rows,
g.n_embd) : RAD_NONE,
c.quant ? brow_slice(xrot ? ps : c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
fp8_blocks(g.n_embd)) : RAD_NONE,
c.rotate ? brow_slice(w.rq, r0, rows, g.n_embd) : RAD_NONE,
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
(c.rotate || xrot) ? brow_slice(xrot ? w.x.q8 : w.rq, r0, rows, g.n_embd)
: RAD_NONE,
(c.rotate || xrot) ? brow_slice(xrot ? w.x.s8 : w.rs, r0, rows,
fp8_blocks(g.n_embd)) : RAD_NONE);
}
/* `y` is the block's output, and it is `w.x.x` -- the same buffer the read wrote the block's INPUT
* into. Every block in this tree leaves its delta in the activation its norm produced, so the
* write reads it there; the input is dead by then. */
/* ================================================================== the control-vector projection
*
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). For a
* request that takes it, a steered layer's wide stream loses its component along that layer's
* direction right after the feed-forward's write:
*
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
*
* This is llama.cpp's `--cvec-mode project`. The dot is per stream, not on the stream mean, as
* llama.cpp's `mul_mat(v, cur)` over the [n_embd, hc, tokens] view reduces dim 0 alone.
*
* The switch is per request: `on` is a derived buffer of one int32 per row
* (core/sched/derive.cpp, `projection_on_rows`), so a step that mixes a projected conversation
* with a stock one projects only the rows that asked. The kernel neither reads nor writes a zero
* row, and a pass with no row on issues nothing (RadBatch::control_vector). `scale` is the norm
* the file stored for the layer times the package's own scale.
*
* One instance per layer; `declare` emits an op only where the vector steers, so a deployment
* without a vector declares no op and no buffer. */
struct HcProject {
rad_op op = 0; /* 0: this layer is not steered (or there is no vector) */
const float* dir = nullptr; /* this layer's row of the device direction table */
rad_buf on = 0; /* [rows] int32: 1 = project this row */
rad_buf h = 0; /* the model's wide stream */
int64_t n = 0, hc = 0;
bool steered() const { return op != 0; }
/* The per-token switch, declared once per model as a derived buffer. 0 when the deployment has
* no vector (or one of another width), which leaves every layer unsteered. */
static rad_buf declare_mask(RadBuilder* b, const char* name, const Geom& g,
const RadControlVector* cv) {
if (!b || g.n_embd <= 0 || g.max_tok <= 0) return 0;
if (!cv || !cv->dir || cv->n_layers <= 0) return 0;
if (cv->n_embd != g.n_embd) {
fprintf(stderr, "radiance: %s: the control vector is %lld wide and this model's "
"residual streams are %lld; not steering it\n",
name, (long long) cv->n_embd, (long long) g.n_embd);
return 0;
}
RadBufDecl d{};
d.dtype = RAD_I32;
d.rank = 1;
d.shape[0] = g.max_tok;
d.kind = RAD_BUF_DERIVED;
d.domain = RAD_DOMAIN_DEVICE;
d.derive = "projection_on_rows";
return rad_decl_buffer(b, name, &d);
}
/* `layer`'s projection, when the vector steers it. Called for every layer; the unsteered ones
* (outside the file, outside the range, or no vector at all) declare nothing. */
int declare(RadBuilder* b, const char* name, const Geom& g, int64_t layer,
const RadControlVector* cv, rad_buf mask, rad_buf stream, int64_t hc_streams) {
if (!b || !mask || !stream || !cv || !cv->dir || hc_streams <= 1) return RAD_OK;
if (layer <= 0 || layer >= cv->n_layers || layer >= g.n_layer) return RAD_OK;
const float scale = cv->scales ? cv->scales[(size_t) layer] : 0.0f;
if (scale == 0.0f) return RAD_OK;
n = g.n_embd;
hc = hc_streams;
on = mask;
h = stream;
dir = cv->dir + (size_t) layer * (size_t) n;
op = rw(b, RAD_OP(b, "hc_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_INT("hc", hc),
RAD_F64("scale", (double) scale), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{h, mask}, {h});
if (!op) {
fprintf(stderr, "radiance: %s: hc_project resolves to no kernel at n %lld, hc %lld -- "
"this rank cannot serve the control vector\n",
name, (long long) n, (long long) hc);
return RAD_E_INVAL;
}
return RAD_OK;
}
/* Rows [r0, r0 + rows) of the stream. The whole step is r0 = 0; the pipelined step issues one
* call per piece, in the same place in the graph. Nothing is issued on a pass where no row
* takes the vector (RadBatch::control_vector): every row would be skipped. */
void step(RadCtx* c_, const RadBatch* batch, int64_t r0, int64_t rows) const {
if (!op || !batch || !batch->control_vector) return;
RAD_ISSUE_N(c_, op, rows,
brow_slice(h, r0, rows, hc * n),
praw(dir, RAD_F32, n),
praw((const int32_t*) rad_buf_ptr(c_, on) + r0, RAD_I32, rows));
}
};
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
* every block leaves its delta in the activation its norm produced, and the input is dead by
* then. */
inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
if (!op_write) return;
if (takes_gather(T)) {
+395
View File
@@ -0,0 +1,395 @@
/* rad_block_lilicorr.h -- LiLiCorr's head: the candidate correlator after a DFlash2 backbone.
*
* NVIDIA's drafter for Nemotron-3.5-Bolt (vLLM's model_executor/models/lilicorr.py). The backbone is
* rad_block_dflash2.h's, with attention sinks (Dflash2::Config::lili). Its final hidden states at
* the block's draft rows go here instead of to DFlash2's selector:
*
* candidates each draft position's top-k from the target's own lm_head (log-softmax values,
* vocab-parallel: each rank's shard, all-gathered, merged)
* lattice steps x k rows a sequence, row s * k + j:
* token_proj(embed(cand)) + pass_hidden_proj(h_s)
* + feature_mlp(layernorm(five rank features)) + slot[s] + rank[j]
* 2 layers rmsnorm, attention over the lattice with a learned slot bias (lili_attn), the
* in/out projections; rmsnorm, silu MLP with biases; residuals
* factor x = output_norm(lattice), a = anchor_norm(context_proj(the anchor's context row))
* f = silu(W [x | a | x * a] + b), [out | in] = edge heads of f
* walk normalised dot products, start from the anchor's own outgoing head, greedy
* (lili_walk)
*
* The anchor's context row is hidden_norm(fc(taps)) at the last committed position, which the
* context pass left in Dflash2's `c` (RadBatch::anchor_rows names the row). The head reads the
* target's embedding and lm_head, and its own 25 linears are bf16: ModelOpt ships them NVFP4,
* which no kernel serves, and the recipe decodes them (`cast dtype=bf16`).
*
* Every rank computes the whole lattice (vLLM: "candidate IDs and embeddings are replicated across
* TP ranks"); only the head's logits and the embedding lookup are per rank, with the merge in
* lili_cand and an exact all-reduce after the lookup.
*/
#ifndef RAD_BLOCK_LILICORR_H
#define RAD_BLOCK_LILICORR_H
#include "rad_arch.h"
namespace rad {
namespace arch {
struct LiliCorr {
enum { MAX_LAYERS = 4 };
struct Config {
int64_t steps = 0; /* draft positions a sequence: the block less the anchor */
int64_t k = 8; /* candidates a position (lilicorr_candidate_topk) */
int64_t hs = 1024; /* the lattice's width (lilicorr_hidden_size) */
int64_t n_head = 8;
int64_t mlp = 2048; /* hs * lilicorr_mlp_ratio */
int64_t fdim = 1024; /* lilicorr_factor_dim */
int64_t n_layer = 2;
double eps = 1e-6; /* rms_norm_eps, the lattice's RMS norms */
double vec_eps = 1e-4; /* lilicorr_vector_eps, F.normalize's floor */
double scale = 8.0; /* lilicorr_logit_scale */
};
/* row_k: the pairs a rank's logprob row carries, k rounded up so 2 + 2 row_k floats are whole
* 16-byte words (the all-gather's unit): 9 for k = 8. */
static int64_t row_k(int64_t k) { return (k % 2) ? k : k + 1; }
struct Wire {
/* Dflash2's */
rad_buf sel_h = 0; /* [srows, n_embd] the drafter's final hidden states, draft rows */
rad_buf c = 0; /* [max_tok, n_embd] hidden_norm(fc(taps)), the context pass's rows */
rad_buf tokens = 0; /* [max_seqs, steps] i32, the proposal */
/* the head's own */
rad_buf logits = 0; /* [srows, n_vocab] f32, this rank's shard */
rad_buf stats = 0; /* [srows, 2 + 2 row_k] f32 */
rad_buf sgath = 0; /* [srows, world * (2 + 2 row_k)] f32, world > 1 */
rad_buf pas = 0; /* [srows, hs] */
rad_buf cand = 0; /* [srows * k] i32 */
rad_buf feat = 0; /* [lrows, hs] */
rad_buf hh = 0; /* [lrows, hs] the lattice's residual stream; starts as lili_cand's base */
rad_buf emb = 0; /* [lrows, n_embd] the candidates' embeddings */
rad_buf y = 0; /* [lrows, hs] */
rad_buf qkv = 0; /* [lrows, 3 hs] */
rad_buf att = 0; /* [lrows, hs] */
rad_buf up = 0; /* [lrows, mlp] */
rad_buf ups = 0; /* [lrows, mlp] */
rad_buf cat = 0; /* [lrows, 3 hs] */
rad_buf fh = 0; /* [lrows, hs] */
rad_buf fhs = 0; /* [lrows, hs] */
rad_buf edges = 0; /* [lrows, 2 fdim] */
rad_buf anc = 0; /* [max_seqs, n_embd] */
rad_buf ast = 0; /* [max_seqs, hs] */
rad_buf an = 0; /* [max_seqs, hs] */
rad_buf aout = 0; /* [max_seqs, fdim] */
};
Geom g{};
Config cfg{};
Wire w{};
int64_t srows = 0, lrows = 0, rk = 0;
rad_weight w_lm = 0, w_tok = 0; /* the target's */
rad_weight w_tokp = 0, b_tokp = 0, w_pass = 0, b_pass = 0, w_ctx = 0, b_ctx = 0;
rad_weight w_fdn = 0, b_fdn = 0, ln_w = 0, ln_b = 0, up_w = 0, up_b = 0, w_slot = 0, w_rank = 0;
rad_weight w_anorm[MAX_LAYERS] = {}, w_in[MAX_LAYERS] = {}, b_in[MAX_LAYERS] = {};
rad_weight w_out[MAX_LAYERS] = {}, b_out[MAX_LAYERS] = {}, w_mnorm[MAX_LAYERS] = {};
rad_weight w_up[MAX_LAYERS] = {}, b_up[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
rad_weight b_dn[MAX_LAYERS] = {};
rad_weight w_rel = 0, w_same = 0, w_onorm = 0, w_annorm = 0;
rad_weight w_fac = 0, b_fac = 0, w_edge = 0, b_edge = 0, w_aout = 0, b_aout = 0;
rad_op op_logits = 0, op_stats = 0, op_sgath = 0, op_pas = 0, op_cand = 0;
rad_op op_emb = 0, op_emb_ar = 0, op_tokp = 0, op_fdn = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_in[MAX_LAYERS] = {}, op_attn = 0;
rad_op op_out[MAX_LAYERS] = {}, op_mnorm[MAX_LAYERS] = {}, op_up[MAX_LAYERS] = {};
rad_op op_dn[MAX_LAYERS] = {}, op_silu_up = 0;
rad_op op_onorm = 0, op_anc = 0, op_ctx = 0, op_annorm = 0, op_factor = 0, op_fac = 0;
rad_op op_silu_f = 0, op_edge = 0, op_aout = 0, op_walk = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, rad_weight lm_head,
rad_weight tok_embd, const char* ck, const Wire& wire);
/* After Dflash2::step, on the same query batch: `sel_h` holds the draft rows. */
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int LiliCorr::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
rad_weight lm_head, rad_weight tok_embd, const char* ck,
const Wire& wire) {
g = geom; cfg = c; w = wire; w_lm = lm_head; w_tok = tok_embd;
if (!w_lm || !w_tok || !ck || cfg.steps < 1 || cfg.k < 2 || cfg.n_layer < 1 ||
cfg.n_layer > MAX_LAYERS || cfg.hs % cfg.n_head)
return RAD_E_INVAL;
const int64_t K = cfg.k, S = cfg.steps, hs = cfg.hs, fd = cfg.fdim, E = g.n_embd;
srows = g.max_seqs * S;
lrows = srows * K;
rk = row_k(K);
const int ACC = RAD_ACCESS_PER_TOKEN;
const RadWeightGroup grp = grp_model();
/* The head's weights, all replicated. Linears and tables bf16, biases, norms and the
* feature layer f32. */
auto wt = [&](const char* dn, const char* src, uint32_t dt,
std::initializer_list<int64_t> shp) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, grp);
};
const char* L = nm.ckpt("%s.lilicorr", ck);
auto src = [&](const char* tail) { return nm.ckpt("%s.%s", L, tail); };
w_tokp = wt(nm.f("dflash.lili.token_proj.weight"), src("token_proj.weight"), RAD_BF16, { hs, E });
b_tokp = wt(nm.f("dflash.lili.token_proj.bias"), src("token_proj.bias"), RAD_F32, { hs });
w_pass = wt(nm.f("dflash.lili.pass_proj.weight"), src("pass_hidden_proj.weight"), RAD_BF16,
{ hs, E });
b_pass = wt(nm.f("dflash.lili.pass_proj.bias"), src("pass_hidden_proj.bias"), RAD_F32, { hs });
w_ctx = wt(nm.f("dflash.lili.context_proj.weight"), src("context_proj.weight"), RAD_BF16,
{ hs, E });
b_ctx = wt(nm.f("dflash.lili.context_proj.bias"), src("context_proj.bias"), RAD_F32, { hs });
ln_w = wt(nm.f("dflash.lili.feature_norm.weight"), src("feature_norm.weight"), RAD_F32, { 5 });
ln_b = wt(nm.f("dflash.lili.feature_norm.bias"), src("feature_norm.bias"), RAD_F32, { 5 });
up_w = wt(nm.f("dflash.lili.feature_up.weight"), src("feature_mlp.up_proj.weight"), RAD_F32,
{ hs, 5 });
up_b = wt(nm.f("dflash.lili.feature_up.bias"), src("feature_mlp.up_proj.bias"), RAD_F32,
{ hs });
w_fdn = wt(nm.f("dflash.lili.feature_down.weight"), src("feature_mlp.down_proj.weight"),
RAD_BF16, { hs, hs });
b_fdn = wt(nm.f("dflash.lili.feature_down.bias"), src("feature_mlp.down_proj.bias"), RAD_F32,
{ hs });
/* [1, 1, steps, 1, hs] and [1, 1, 1, k, hs], read as tables (a reshape of one whole plane). */
w_slot = wt(nm.f("dflash.lili.slot_embedding"), src("slot_embedding"), RAD_BF16, { S, hs });
w_rank = wt(nm.f("dflash.lili.rank_embedding"), src("rank_embedding"), RAD_BF16, { K, hs });
w_rel = wt(nm.f("dflash.lili.relative_slot_bias"), src("relative_slot_bias"), RAD_F32,
{ cfg.n_head, 2 * (S + 1) - 1 });
w_same = wt(nm.f("dflash.lili.same_slot_bias"), src("same_slot_bias"), RAD_F32, { cfg.n_head });
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
auto ls = [&](const char* tail) { return nm.ckpt("%s.layers.%d.%s", L, i, tail); };
w_anorm[i] = wt(nm.f("dflash.lili.blk.%d.attn_norm.weight", i), ls("attn_norm.weight"),
RAD_F32, { hs });
w_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.weight", i), ls("attn.in_proj_weight"),
RAD_BF16, { 3 * hs, hs });
b_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.bias", i), ls("attn.in_proj_bias"), RAD_F32,
{ 3 * hs });
w_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.weight", i), ls("attn.out_proj.weight"),
RAD_BF16, { hs, hs });
b_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.bias", i), ls("attn.out_proj.bias"),
RAD_F32, { hs });
w_mnorm[i] = wt(nm.f("dflash.lili.blk.%d.mlp_norm.weight", i), ls("mlp_norm.weight"),
RAD_F32, { hs });
w_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.weight", i), ls("mlp.up_proj.weight"),
RAD_BF16, { cfg.mlp, hs });
b_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.bias", i), ls("mlp.up_proj.bias"), RAD_F32,
{ cfg.mlp });
w_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.weight", i), ls("mlp.down_proj.weight"),
RAD_BF16, { hs, cfg.mlp });
b_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.bias", i), ls("mlp.down_proj.bias"),
RAD_F32, { hs });
if (!w_anorm[i] || !w_in[i] || !b_in[i] || !w_out[i] || !b_out[i] || !w_mnorm[i] ||
!w_up[i] || !b_up[i] || !w_dn[i] || !b_dn[i])
return RAD_E_INVAL;
}
w_onorm = wt(nm.f("dflash.lili.output_norm.weight"), src("output_norm.weight"), RAD_F32, { hs });
w_annorm = wt(nm.f("dflash.lili.anchor_norm.weight"), src("anchor_norm.weight"), RAD_F32, { hs });
w_fac = wt(nm.f("dflash.lili.factor_proj.weight"), src("factor_input_proj.weight"), RAD_BF16,
{ hs, 3 * hs });
b_fac = wt(nm.f("dflash.lili.factor_proj.bias"), src("factor_input_proj.bias"), RAD_F32,
{ hs });
/* [out_head | in_head] as one linear, as vLLM fuses them (`_fused_edge_weight`). */
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.weight"),
{ src("out_head.weight"), src("in_head.weight") }, 0));
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.bias"),
{ src("out_head.bias"), src("in_head.bias") }, 0));
w_edge = decl_w(b, nm.f("dflash.lili.edge.weight"), RAD_BF16, { 2 * fd, hs }, ACC,
RAD_SHARD_NONE, grp);
b_edge = decl_w(b, nm.f("dflash.lili.edge.bias"), RAD_F32, { 2 * fd }, ACC, RAD_SHARD_NONE,
grp);
w_aout = wt(nm.f("dflash.lili.anchor_out.weight"), src("anchor_out_head.weight"), RAD_BF16,
{ fd, hs });
b_aout = wt(nm.f("dflash.lili.anchor_out.bias"), src("anchor_out_head.bias"), RAD_F32, { fd });
if (!w_tokp || !b_tokp || !w_pass || !b_pass || !w_ctx || !b_ctx || !ln_w || !ln_b || !up_w ||
!up_b || !w_fdn || !b_fdn || !w_slot || !w_rank || !w_rel || !w_same || !w_onorm ||
!w_annorm || !w_fac || !b_fac || !w_edge || !b_edge || !w_aout || !b_aout)
return RAD_E_INVAL;
/* ---------------------------------------------------------------- ops */
auto gemm_b = [&](int64_t rows, int64_t N, int64_t Kd, rad_weight wgt, rad_weight bias)
-> rad_op {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", Kd),
RAD_STR("dtype", "bf16"), RAD_STR("act", "none")),
RAD_WEIGHTS(wgt, bias));
};
auto rms = [&](int64_t rows, int64_t n, rad_weight gain) -> rad_op {
return RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", cfg.eps),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain));
};
auto silu = [&](int64_t rows, int64_t n) -> rad_op {
return RAD_OP(b, "silu",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
const int64_t sw = 2 + 2 * rk;
/* The candidates: this rank's shard of the target's logits, its logprob row, the exchange. */
op_logits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_lm)),
{ w.sel_h }, { w.logits });
/* Replicated, `vocab_off` is omitted: an optional parameter present at 0 is a different
* declaration from an absent one. */
op_stats = g.world > 1
? rw(b, RAD_OP(b, "sample_logprobs",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("k", rk), RAD_INT("vocab_off", g.vocab_off)),
RAD_NOWEIGHTS),
{ w.logits }, { w.stats })
: rw(b, RAD_OP(b, "sample_logprobs",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("k", rk)),
RAD_NOWEIGHTS),
{ w.logits }, { w.stats });
if (g.world > 1)
op_sgath = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * sw), RAD_STR("dtype", "f32"),
RAD_INT("row", sw)),
RAD_NOWEIGHTS),
{ w.stats }, { w.sgath });
op_pas = rw(b, gemm_b(srows, hs, E, w_pass, b_pass), { w.sel_h }, { w.pas });
op_cand = rw(b, RAD_OP(b, "lili_cand",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("k", K),
RAD_INT("world", g.world), RAD_INT("steps", S),
RAD_INT("n", hs), RAD_STR("dtype", "bf16"),
RAD_F64("eps", 1e-5), RAD_INT("row_k", rk)),
RAD_WEIGHTS(ln_w, ln_b, up_w, up_b, w_slot, w_rank)),
{ g.world > 1 ? w.sgath : w.stats, w.pas }, { w.cand, w.feat, w.hh });
/* The lattice: candidates' embeddings (the trunk's vocab-sharded table, exact reduce), the
* token and feature projections added onto lili_cand's base in their GEMMs' residual. */
op_emb = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{ w.cand }, { w.emb });
if (g.world > 1)
op_emb_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", E, lrows * E),
RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{ w.emb }, { w.emb });
op_tokp = rw(b, gemm_b(lrows, hs, E, w_tokp, b_tokp), { w.emb, w.hh }, { w.hh });
op_fdn = rw(b, gemm_b(lrows, hs, hs, w_fdn, b_fdn), { w.feat, w.hh }, { w.hh });
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, rms(lrows, hs, w_anorm[i]), { w.hh }, { w.y });
op_in[i] = rw(b, gemm_b(lrows, 3 * hs, hs, w_in[i], b_in[i]), { w.y }, { w.qkv });
op_out[i] = rw(b, gemm_b(lrows, hs, hs, w_out[i], b_out[i]), { w.att, w.hh }, { w.hh });
op_mnorm[i] = rw(b, rms(lrows, hs, w_mnorm[i]), { w.hh }, { w.y });
op_up[i] = rw(b, gemm_b(lrows, cfg.mlp, hs, w_up[i], b_up[i]), { w.y }, { w.up });
op_dn[i] = rw(b, gemm_b(lrows, hs, cfg.mlp, w_dn[i], b_dn[i]), { w.ups, w.hh }, { w.hh });
}
op_attn = rw(b, RAD_OP(b, "lili_attn",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("steps", S), RAD_INT("k", K),
RAD_INT("n_head", cfg.n_head),
RAD_INT("head_dim", hs / cfg.n_head),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_rel, w_same)),
{ w.qkv }, { w.att });
op_silu_up = rw(b, silu(lrows, cfg.mlp), { w.up }, { w.ups });
op_onorm = rw(b, rms(lrows, hs, w_onorm), { w.hh }, { w.y });
/* The anchor: the context pass's row at each drafting sequence's last committed position. */
op_anc = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.c }, { w.anc });
op_ctx = rw(b, gemm_b(g.max_seqs, hs, E, w_ctx, b_ctx), { w.anc }, { w.ast });
op_annorm = rw(b, rms(g.max_seqs, hs, w_annorm), { w.ast }, { w.an });
op_factor = rw(b, RAD_OP(b, "lili_factor",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("L", S * K),
RAD_INT("n", hs), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.y, w.an }, { w.cat });
op_fac = rw(b, gemm_b(lrows, hs, 3 * hs, w_fac, b_fac), { w.cat }, { w.fh });
op_silu_f = rw(b, silu(lrows, hs), { w.fh }, { w.fhs });
op_edge = rw(b, gemm_b(lrows, 2 * fd, hs, w_edge, b_edge), { w.fhs }, { w.edges });
op_aout = rw(b, gemm_b(g.max_seqs, fd, hs, w_aout, b_aout), { w.an }, { w.aout });
op_walk = rw(b, RAD_OP(b, "lili_walk",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", S),
RAD_INT("k", K), RAD_INT("n", fd), RAD_STR("dtype", "bf16"),
RAD_F64("eps", cfg.vec_eps), RAD_F64("scale", cfg.scale)),
RAD_NOWEIGHTS),
{ w.edges, w.aout, w.cand }, { w.tokens });
if (!op_logits || !op_stats || (g.world > 1 && (!op_sgath || !op_emb_ar)) || !op_pas ||
!op_cand || !op_emb || !op_tokp || !op_fdn || !op_attn || !op_silu_up || !op_onorm ||
!op_anc || !op_ctx || !op_annorm || !op_factor || !op_fac || !op_silu_f || !op_edge ||
!op_aout || !op_walk)
return RAD_E_INVAL;
return RAD_OK;
}
inline void LiliCorr::step(RadCtx* c, const RadBatch* batch) const {
const int64_t n = batch->n_seq, S = n * cfg.steps, Lr = S * cfg.k;
if (n <= 0) return;
if (!batch->anchor_rows) {
rad_step_fail(c, "lilicorr: the query pass carries no anchor rows (RadBatch::anchor_rows): "
"this engine does not position a block drafter's anchor");
return;
}
const int64_t E = g.n_embd, hs = cfg.hs, fd = cfg.fdim;
const int64_t sw = 2 + 2 * rk;
RAD_ISSUE_N(c, op_logits, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.logits, S));
RAD_ISSUE_N(c, op_stats, S, brows(w.logits, S), RAD_NONE, brows(w.stats, S));
if (op_sgath) RAD_ISSUE(c, op_sgath, brows(w.stats, S), brows(w.sgath, S));
RAD_ISSUE_N(c, op_pas, S, brows(w.sel_h, S), RAD_W(w_pass), RAD_W(b_pass), RAD_NONE,
brows(w.pas, S));
RAD_ISSUE_N(c, op_cand, S, op_sgath ? brows(w.sgath, S) : brows(w.stats, S), brows(w.pas, S),
RAD_W(ln_w), RAD_W(ln_b), RAD_W(up_w), RAD_W(up_b), RAD_W(w_slot), RAD_W(w_rank),
brow_slice(w.cand, 0, Lr, 1), brows(w.feat, Lr), brows(w.hh, Lr));
(void)sw;
RAD_ISSUE_N(c, op_emb, Lr, brow_slice(w.cand, 0, Lr, 1), RAD_W(w_tok), brows(w.emb, Lr));
if (op_emb_ar) RAD_ISSUE_N(c, op_emb_ar, Lr * E, brows(w.emb, Lr), RAD_NONE);
RAD_ISSUE_N(c, op_tokp, Lr, brows(w.emb, Lr), RAD_W(w_tokp), RAD_W(b_tokp), brows(w.hh, Lr),
brows(w.hh, Lr));
RAD_ISSUE_N(c, op_fdn, Lr, brows(w.feat, Lr), RAD_W(w_fdn), RAD_W(b_fdn), brows(w.hh, Lr),
brows(w.hh, Lr));
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_anorm[i], Lr, brows(w.hh, Lr), RAD_W(w_anorm[i]), brows(w.y, Lr));
RAD_ISSUE_N(c, op_in[i], Lr, brows(w.y, Lr), RAD_W(w_in[i]), RAD_W(b_in[i]), RAD_NONE,
brows(w.qkv, Lr));
RAD_ISSUE_N(c, op_attn, Lr, brows(w.qkv, Lr), RAD_W(w_rel), RAD_W(w_same), brows(w.att, Lr));
RAD_ISSUE_N(c, op_out[i], Lr, brows(w.att, Lr), RAD_W(w_out[i]), RAD_W(b_out[i]),
brows(w.hh, Lr), brows(w.hh, Lr));
RAD_ISSUE_N(c, op_mnorm[i], Lr, brows(w.hh, Lr), RAD_W(w_mnorm[i]), brows(w.y, Lr));
RAD_ISSUE_N(c, op_up[i], Lr, brows(w.y, Lr), RAD_W(w_up[i]), RAD_W(b_up[i]), RAD_NONE,
brows(w.up, Lr));
RAD_ISSUE_N(c, op_silu_up, Lr, brows(w.up, Lr), brows(w.ups, Lr));
RAD_ISSUE_N(c, op_dn[i], Lr, brows(w.ups, Lr), RAD_W(w_dn[i]), RAD_W(b_dn[i]),
brows(w.hh, Lr), brows(w.hh, Lr));
}
RAD_ISSUE_N(c, op_onorm, Lr, brows(w.hh, Lr), RAD_W(w_onorm), brows(w.y, Lr));
RAD_ISSUE_N(c, op_anc, n, RAD_B(w.c), praw(batch->anchor_rows, RAD_I32, n), brows(w.anc, n));
RAD_ISSUE_N(c, op_ctx, n, brows(w.anc, n), RAD_W(w_ctx), RAD_W(b_ctx), RAD_NONE, brows(w.ast, n));
RAD_ISSUE_N(c, op_annorm, n, brows(w.ast, n), RAD_W(w_annorm), brows(w.an, n));
RAD_ISSUE_N(c, op_factor, Lr, brows(w.y, Lr), brows(w.an, n), brows(w.cat, Lr));
RAD_ISSUE_N(c, op_fac, Lr, brows(w.cat, Lr), RAD_W(w_fac), RAD_W(b_fac), RAD_NONE,
brows(w.fh, Lr));
RAD_ISSUE_N(c, op_silu_f, Lr, brows(w.fh, Lr), brows(w.fhs, Lr));
RAD_ISSUE_N(c, op_edge, Lr, brows(w.fhs, Lr), RAD_W(w_edge), RAD_W(b_edge), RAD_NONE,
brows(w.edges, Lr));
RAD_ISSUE_N(c, op_aout, n, brows(w.an, n), RAD_W(w_aout), RAD_W(b_aout), RAD_NONE,
brows(w.aout, n));
RAD_ISSUE_N(c, op_walk, n, brows(w.edges, Lr), brows(w.aout, n),
brow_slice(w.cand, 0, Lr, 1), brows(w.tokens, n), RAD_NONE);
(void)E; (void)hs; (void)fd;
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_LILICORR_H */
+10 -12
View File
@@ -2,10 +2,9 @@
*
* rmsnorm -> gate_up gemm -> silu_mul -> down gemm -> [all_reduce] -> residual add
*
* gate and up are one weight and one GEMM. That is a convert-time fusion the plugin owns (spec
* §2.4): the container ships ffn_gate.weight and ffn_up.weight, the map concatenates them along
* dim 0, and silu_mul splits [M, 2n] back into gate times up. It buys one GEMM launch instead of
* two and one movement unit instead of two.
* gate and up are fused into one weight at convert time (spec §2.4): the map concatenates the
* checkpoint's gate and up along dim 0 and silu_mul splits [M, 2n] back into gate * up. One GEMM
* launch and one movement unit instead of two.
*/
#ifndef RAD_BLOCK_MLP_H
#define RAD_BLOCK_MLP_H
@@ -23,9 +22,9 @@ struct MlpBF16 {
rad_buf ffn = 0; /* [max_tok, n_ff] */
};
/* Checkpoint-side names for one layer. The plugin owns the spelling because it is the only
* component that knows both sides of the map (spec §2.4), and one architecture arrives as
* `model.language_model.layers.N.mlp.*` and another as `blk.N.ffn_*`. */
/* Checkpoint-side names for one layer. The plugin supplies them because only it knows both
* sides of the map (spec §2.4); spellings differ per checkpoint (`...layers.N.mlp.*`,
* `blk.N.ffn_*`). */
struct Src {
const char* norm = nullptr; /* post_attention_layernorm.weight */
const char* gate = nullptr;
@@ -84,8 +83,8 @@ inline int MlpBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, c
RAD_WEIGHTS(w_down)),
{w.ffn}, {w.h});
/* Column-sharded down projection: every rank holds a partial sum. Emitted here, by the
* plugin, so the graph dump shows it here (spec §9). */
/* Column-sharded down projection leaves a partial sum on every rank. The plugin emits the
* reduction so the graph dump shows it (spec §9). */
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -105,9 +104,8 @@ inline int MlpBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, c
}
inline void MlpBF16::step(RadCtx* c, const RadBatch* batch) const {
/* Every operand carries the STEP's row count and not the buffer's: a kernel reads its extents
* off the operands, because a ranged parameter has been collapsed to a band by the time issue
* runs (arch/common/rad_arch.h, libref/ref_ops.h). */
/* Operands carry the step's row count, not the buffer's: kernels read extents from the
* operands because a ranged parameter is collapsed to a band before issue (rad_arch.h). */
const int64_t T = batch->n_tok;
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
RAD_ISSUE(c, op_gate_up, brows(w.h, T), RAD_W(w_gate_up), brows(w.gate_up, T));
+119 -83
View File
@@ -3,27 +3,18 @@
* rmsnorm -> quant_act_fp8 -> gate_up gemm_nt_q -> silu_mul -> quant_act_fp8 -> down gemm_nt_q
* -> [all_reduce] -> residual add
*
* THE ARCHITECTURE IS rad_block_mlp.h's AND IS DOCUMENTED THERE -- the gate/up fusion, why the
* all-reduce is emitted by the plugin, what the residual add is for. This file is that block with
* two ops added and two changed, and it repeats none of it: a second copy of the prose is a second
* thing to keep true.
* rad_block_mlp.h documents the architecture. Differences:
*
* What differs, and only this:
* - Both projections are LinearFP8 (rad_fp8.h): an E4M3 weight with a bf16 [N/128][K/128]
* scale plane, through `gemm_nt_q` at dtype fp8a8.
* - Each takes an E4M3 activation quantised every step (the checkpoint's `activation_scheme`
* is `dynamic`, so no activation scale is stored).
* - Activations between ops stay bf16, so `Geom::dtype` stays "bf16" and every other op
* resolves as in the bf16 block.
*
* - the two projections are LinearFP8 (rad_fp8.h): an E4M3 weight, a bf16 [N/128][K/128] scale
* plane declared as a weight of its own, and `gemm_nt_q` at dtype fp8a8 instead of `gemm_nt`.
* - each of them is preceded by a `quant_act_fp8` over its input, because an fp8a8 GEMM takes an
* E4M3 activation and the checkpoint's `activation_scheme` is `dynamic` -- there is no
* activation scale on disk and one is computed every step.
* - the norm, the activation and the collective are UNCHANGED. Activations between ops are still
* bf16; only the two GEMM operands are narrow. So `Geom::dtype` stays "bf16" for this block and
* every op in it but the two linears resolves exactly as it does in the bf16 plugin.
*
* The gate/up fusion survives the format, which is not obvious and is the reason it is kept: the
* two sources are [17408,5120] each and their scale planes [136,40] each, and concatenating both
* along dim 0 gives [34816,5120] against [272,40] -- which is the grid, because 34816/128 is 272.
* A fusion whose parts were not whole multiples of 128 rows would silently misalign every scale
* after the seam.
* The gate/up fusion survives the format because each part is a whole number of 128-row blocks:
* two [17408, 5120] sources with [136, 40] scale planes concatenate to [34816, 5120] and
* [272, 40]. Parts not on a 128-row boundary would misalign every scale after the seam.
*/
#ifndef RAD_BLOCK_MLP_FP8_H
#define RAD_BLOCK_MLP_FP8_H
@@ -41,9 +32,8 @@ struct MlpFP8 {
ActFP8 ffn{}; /* [max_tok, n_ff] */
};
/* The checkpoint side. `gate`, `up` and `down` name the `.weight` tensors; a block-fp8
* checkpoint's scale planes sit beside them and the checkpoint reader pairs them, so a caller
* cannot spell one of the pair and forget the other. */
/* Checkpoint names. `gate`, `up` and `down` name the `.weight` tensors; the checkpoint reader
* pairs each with its scale plane. */
struct Src {
const char* norm = nullptr;
const char* gate = nullptr;
@@ -60,43 +50,54 @@ struct MlpFP8 {
NormQuantFP8 nq_h{};
GateQuantFP8 gq_ffn{};
rad_op op_ar = 0, op_add = 0;
/* ...AND THE gate_up PROJECTION WITH THE GATE AND THE QUANTISER IN ITS EPILOGUE.
*
* `gq_ffn`'s only input is `gate_up`'s only output. Unfused it is one of the larger remaining
* items in a decode step, and roughly half of that is the launch and half the second pass over
* a [M, 2*n_ff] bf16 tensor the GEMM's transposing store had just scattered. Folded, that
* tensor is never written at all.
*
* DECLARED BESIDE THE PAIR AND NOT INSTEAD OF IT, exactly as LinearFP8's matvec is: the fold
* is the narrow tile's epilogue and serves M <= 64, so a prefill chunk takes the pair. The two
* are byte-identical -- r4d_selftest holds them to it, and ref_test holds the reference to
* the same claim -- so this is two spellings of one arithmetic and not two answers. */
/* gate_up with the gate and quantiser in its epilogue, so the [M, 2*n_ff] bf16 product is
* never written (unfused, the extra launch and second pass are a sizeable decode cost).
* Declared beside the pair, not instead of it: the narrow fold serves M <= 64, so prefill
* chunks take the pair -- unless the model asked for `wide_fold`, whose row serves every M.
* Byte-identical, as r4d_selftest and ref_test check. */
rad_op op_gated = 0;
int64_t gated_rows = 0;
/* ...AND WHETHER THE COLLECTIVE AT THE END OF THIS BLOCK IS THE NEXT BLOCK'S FIRST PASS.
* `ar_in` says this block's own norm absorbs its PREDECESSOR's all-reduce; `ar_out` says the
* block after it absorbs THIS one's, so this one must not issue it. They are the residual
* fold's two flags again, one boundary later, and they are separate for the same reason: a
* block is declared without knowing what follows it. On EITHER wire -- the fused kernel
* carries both payloads -- and both sides ask ar_fused_ok(g, T), so the two cannot disagree
* about whether the collective has already been issued. */
/* The next block absorbs this block's closing all-reduce, so this one must not issue it.
* Counterpart of `ar_in`; both sides ask ar_fused_ok(g, T), so they agree. */
bool ar_out = false;
/* Set before declare: a clamped product (`swiglu_limit`) and its quantiser as one launch
* (GateQuantFP8::fuse_clamped). */
bool swiglu_quant = false;
/* `fold` says this block has a PREDECESSOR whose delta is still in `w.h.x`, so its norm does
* the residual add that block would otherwise have issued. False for the first block of a
* chain, whose residual stream comes straight from the embedding. See rad_fp8.h. */
/* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add
* (false for the first block of a chain). `add_out`: issue the trailing add here. See
* rad_fp8.h. */
/* `wide_fold`: declare the gated fold over the whole prompt (gemm_nt_q_gated_wide, whose row
* serves every M) rather than the narrow row's 64-row band. Set by a model that runs whole
* prompts through the fold; every other caller keeps the band and the pair past it. */
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0,
bool wide_fold = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
/* One row slice of the whole block; `rows <= 0` means the rest of the step. */
void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
/* The slice in its parts, for a caller that runs the norm and the tail elsewhere (qwen35_fp8's
* pipelined prefill puts both on the second lane): the projections from the normed input to
* the delta in `w.h.x`, then the all-reduce and add this block issues itself. */
void body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
void tail(RadCtx* c, int64_t r0, int64_t rows) const;
/* The block's all-reduce over rows [r0, r0 + rows) of the output, at `overlap` where declared
* (a caller that runs it beside other work). */
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
}
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
int ar_overlap = 0;
rad_op op_ar_ov = 0;
};
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold, bool add_out,
int ar_in, bool ar_out_) {
int ar_in, bool ar_out_, double swiglu_limit, bool wide_fold) {
g = geom; w = wire; layer = l;
ar_out = ar_out_;
@@ -104,41 +105,53 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
/* THE NORM, THE QUANTISER AND THE RESIDUAL ADD ARE ONE OP, and rad_fp8.h's NormQuantFP8 says
* why: both were a launch and a second pass over a row this kernel already had in registers.
* Folded, the norm reads the PREVIOUS block's delta out of the shared `h` buffer and adds it
* into the stream; unfolded it reads the stream directly and the block ends with its own add. */
/* Norm, quantise and residual add in one op (rad_fp8.h: NormQuantFP8). Folded, it adds the
* previous block's delta from `h` into the stream; unfolded it reads the stream directly. */
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd, fold ? w.x : 0,
0, ar_in));
RAD_ARCH_TRY(gate_up.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l),
2 * g.n_ff, g.n_embd, RAD_SHARD_ROW, grp_layer(l),
{ src.gate, src.up }, w.h, w.gate_up, 0, { g.n_ff, g.n_ff }));
/* THE bf16 SILU PRODUCT IS WRITTEN ONLY FOR A READER: a down projection that reads the bf16
* plane (LinearFP8::reads_x). A block-fp8 down_proj takes the codes and their scale alone. */
/* The bf16 silu product is written only if the down projection reads the bf16 plane
* (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales, and so does an
* int8 one fed its codes (ActFP8::q8_fed). */
const char* down_base = nm.f("blk.%d.ffn_down", l);
RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down }));
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x));
gq_ffn.fuse_clamped = swiglu_quant;
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0,
down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false,
swiglu_limit));
/* The fold, over the same weights and into the same activation the pair writes. Not
* RAD_ARCH_TRY: a plugin without the row is the ordinary case and the pair still runs. It
* multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold -- and neither
* has an MXFP4 one: libr4d's gated fold is an fp8a8 tile, and the pair serves it. */
{
const int64_t hi = g.max_tok < 64 ? g.max_tok : 64;
if (hi > 0 && !gate_up.bf16 && !gate_up.mx) {
op_gated = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", gate_up.N),
RAD_INT("K", gate_up.K),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
RAD_WEIGHTS(gate_up.w, gate_up.ws)),
{ w.h.q, w.h.s },
gq_ffn.want_x ? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s });
if (op_gated) gated_rows = hi;
}
}
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain
* MXFP4 at one to 16 rows (eight where K is short), decl_gated_fold_iqr for an IQR weight
* whose input and output are the rotated int8 trunk's fed pairs, to 16 rows. Other gate_up
* encodings (M2XFP4 included), and a clamped (swiglu_limit) product, take the pair. */
const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale;
if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 &&
!gate_up.i8)
op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
{ w.h.q, w.h.s },
gq_ffn.want_x
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
&gated_rows, wide_fold);
else if (fold_ok && gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.ffn.q8_fed && w.ffn.q8_rot)
op_gated = decl_gated_fold_iqr(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
{ w.h.q8, w.h.s8 },
gq_ffn.want_x
? std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8,
w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8 },
&gated_rows);
else if (fold_ok && gate_up.mx && !gate_up.paro)
op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
gate_up.wref, { w.h.q, w.h.s },
gq_ffn.want_x
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s,
w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
&gated_rows);
RAD_ARCH_TRY(down.declare(b, nm, g, down_base,
g.n_embd, g.n_ff, RAD_SHARD_COL, grp_layer(l),
{ src.down }, w.ffn, w.h.x));
@@ -151,8 +164,19 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{w.h.x}, {w.h.x});
/* The same collective for a caller that runs it beside other work (issue_ar): at `overlap` 1
* it gets the rows that hold fewer CUs while waiting on the link. */
if (g.world > 1 && ar_overlap > 0)
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes),
RAD_INT("overlap", ar_overlap)),
RAD_NOWEIGHTS),
{w.h.x}, {w.h.x});
/* Only where the NEXT block's norm will not do it; see rad_fp8.h's NormQuantFP8. */
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
if (add_out)
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
@@ -163,28 +187,40 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
return RAD_OK;
}
/* ONE ROW SLICE OF THE BLOCK. `rows` defaults to the whole step, and at r0 = 0 with rows = T every
* operand is byte-for-byte the one the unsliced form built -- `brow_slice` at offset 0 is `brows`.
*
* Every op here is per row: the norm and the quantiser group along K within a row, the GEMMs give
* each output row its own accumulation, and the fused all-reduce closes every reduction over one
* row (r4d_ar.cpp says so where it caps the block count). So a slice computes exactly the rows it
* names and nothing about the arithmetic depends on how the chunk was cut -- PROVIDED the cut
* obeys the band rule in core/runtime/ctx.h. */
/* One row slice of the block; r0 = 0, rows = T is the whole step (`brow_slice` at offset 0 is
* `brows`). Every op is per row: the norm and quantiser group along K within a row, the GEMMs
* accumulate each output row independently, and the fused all-reduce reduces within a row
* (r4d_ar.cpp). So results do not depend on the cut, provided it obeys the band rule in
* core/runtime/ctx.h. */
inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
if (rows <= 0) rows = T - r0;
nq_h.step(c, T, r0, rows);
if (op_gated && rows <= gated_rows) {
body(c, T, r0, rows);
tail(c, r0, rows);
}
inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
if (op_gated && rows <= gated_rows && gate_up.mx) {
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff),
RAD_W(gate_up.ws), RAD_W(gate_up.wref), brow_slice(w.ffn.q, r0, rows, g.n_ff),
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
} else if (op_gated && rows <= gated_rows) {
/* The fp8a8 fold's E4M3 pairs, or the IQR fold's int8 ones (cq / cs: the fed pair). */
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.cq(), r0, rows, g.n_embd),
brow_slice(w.h.cs(), r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
RAD_W(gate_up.ws), brow_slice(w.ffn.cq(), r0, rows, g.n_ff),
brow_slice(w.ffn.cs(), r0, rows, g.n_ff / RAD_FP8_BLOCK),
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
} else {
gate_up.step(c, w.h, w.gate_up, T, r0, rows);
gq_ffn.step(c, w.gate_up, T, r0, rows);
}
down.step(c, w.ffn, w.h.x, T, r0, rows);
}
inline void MlpFP8::tail(RadCtx* c, int64_t r0, int64_t rows) const {
if (op_ar && !(ar_out && ar_fused_ok(g, rows)))
RAD_ISSUE_N(c, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
if (op_add)
File diff suppressed because it is too large. Load diff
+146 -202
View File
@@ -2,109 +2,89 @@
*
* ============================== WHAT IT IS ==============================
*
* Qwen3.5 / Qwen3-Next ship ONE extra transformer layer beside the trunk, under an `mtp.` prefix
* of its own, whose job is to predict token i+2 from the trunk's hidden state at i and the
* embedding of the token at i+1. It is the drafter for speculative decoding, and it is a drafter
* with no second checkpoint: the embedding table and the lm_head are the trunk's
* (`mtp_use_dedicated_embeddings: false`, and no `mtp.lm_head` in the file).
* Qwen3.5 / Qwen3-Next ship one extra transformer layer under an `mtp.` prefix that predicts
* token i+2 from the trunk's hidden state at i and the embedding of token i+1. It is the
* speculative-decoding drafter; the embedding table and lm_head are the trunk's
* (`mtp_use_dedicated_embeddings: false`, no `mtp.lm_head`).
*
* THE INDEXING IS THE WHOLE THING, so it is stated once here and everything else follows:
* Indexing:
*
* head index i reads hidden(i) and embed(token at i + 1)
* writes its K and V at KV position i, with rope position i
* predicts the token at i + 2
*
* That is DeepSeek-V3's MTP layout, which this family follows: the head's transformer block runs
* over the SAME position indices as the trunk, and the shift lives entirely in which token gets
* embedded. Getting it off by one costs nothing visible -- the drafts are simply wrong and the
* acceptance rate collapses, while the model's own output stays exactly correct.
* This is DeepSeek-V3's MTP layout: the head runs over the trunk's position indices and the shift
* is only in which token is embedded. An off-by-one shows only as collapsed acceptance.
*
* The forward is short and every piece of it already exists in this library:
* The forward:
*
* h = gather(the trunk's final hidden states, at the rows this pass continues from)
* e = embed(the token one position on)
* x = fc( concat( pre_fc_norm_embedding(e), pre_fc_norm_hidden(h) ) )
* x = one gated-GQA layer + one SwiGLU feed-forward, over x <- AttnGatedFP8, MlpFP8
* h'= mtp.norm(x)
* logits = the TRUNK's lm_head over h'
* logits = the trunk's lm_head over h'
*
* and h' is BOTH the logits input and the `h` of the next draft round. That is the reference's
* shape too: a Qwen3-Next MTP forward returns one tensor and the proposer feeds the same tensor
* back, unlike an EAGLE head which returns a (normed, unnormed) pair.
* h' is both the logits input and the next round's `h`, as in the reference (a Qwen3-Next MTP
* forward returns one tensor; an EAGLE head returns a (normed, unnormed) pair).
*
* ============================== THE TWO KINDS OF PASS ==============================
*
* RadBatch::draft_pass says which, and the sign is the whole distinction:
* By the sign of RadBatch::draft_pass:
*
* < 0 A HISTORY PASS, one row a token, gathering the trunk's hidden states. It exists
* because the head's attention reads its OWN K and V for every earlier position, and
* nothing else in the engine writes those: the trunk's prefill fills layers 0..n-1 and
* leaves the head's layer untouched. Without it the head attends to whatever the pool
* last held, which is not wrong output -- a bad draft is only a rejected draft -- but it
* is a drafter that proposes noise. The scheduler runs one over the positions the last
* step added, the verified ones included.
* < 0 History pass, one row per token, gathering the trunk's hidden states. The head's
* attention reads its own K and V for every earlier position, which the trunk's prefill
* does not write; without this pass the head attends to stale pool contents and proposes
* noise. The scheduler runs it over the positions the last step added, verified ones
* included.
*
* It is also DRAFT ROUND 1 for every sequence that drafts: that sequence's last history
* row is the committed position with the token the trunk chose after it -- round 1's
* whole input -- so the pass ends in the lm_head over those rows (RadBatch::draft_out_ids)
* and leaves the head's output at them where round 2 reads it.
* It is also draft round 1 for every drafting sequence: its last history row is the
* committed position plus the token the trunk chose after it, so the pass ends in the
* lm_head over those rows (RadBatch::draft_out_ids) and leaves the head's output there
* for round 2.
*
* > 1 A DRAFT ROUND, one row a sequence, reading the head's own output from the round before,
* which is already in the same buffer. Every round ends in the lm_head, because a draft is
* a token. There is no round-1 pass; the history pass is it.
* > 1 Draft round, one row per sequence, reading the previous round's output from the same
* buffer and ending in the lm_head. There is no separate round-1 pass.
*
* ============================== WHAT IS AND IS NOT FP8 ==============================
* ============================== PRECISION ==============================
*
* Read off mtp.safetensors rather than assumed, exactly as qwen35_fp8.cpp reads the trunk:
* As stored in mtp.safetensors:
*
* F8_E4M3 + scale layers.0.self_attn.{q,k,v,o}_proj, layers.0.mlp.{gate,up,down}_proj
* BF16, no scale fc, norm, pre_fc_norm_embedding, pre_fc_norm_hidden, and every norm inside
* the layer
*
* `fc` is [5120, 10240] and bf16, so it is a plain `gemm_nt`, issued ONCE over the whole chunk.
* libr4d's bf16 GEMM row for this shape is C_LE("M", 65536) and K here is 10240, a multiple of 16,
* so the wide row serves the whole chunk in one launch. That matters because the history pass runs
* one row a TOKEN over a whole prefill chunk: banding this at 64 and slicing it would be dozens of
* launches a chunk for a GEMM whose traffic is microseconds.
* `fc` ([5120, 10240], bf16) is a plain `gemm_nt` issued once over the whole chunk: libr4d's bf16
* row is C_LE("M", 65536) and K = 10240 is a multiple of 16. The history pass has one row per
* token of a prefill chunk, so slicing at 64 would cost dozens of launches.
*
* ============================== THE CONCAT ORDER ==============================
*
* `fc` reads 10240 columns and the two halves are the normed embedding and the normed hidden
* state. WHICH HALF IS FIRST IS NOT IN THE CHECKPOINT: both orders are one contiguous [5120,10240]
* matrix and no shape, name or dtype distinguishes them. DeepSeek-V3's MTP -- the design this one
* follows -- concatenates `enorm(embedding)` then `hnorm(hidden)`, and that is the order here.
*
* Both readings are self-consistent, libref shares whichever one the graph picks, and no per-op
* oracle can reach it -- but it has a CHEAP EMPIRICAL ANSWER, the draft acceptance rate. A head
* wired the right way round accepts most of what it proposes; wired the wrong way round it
* proposes noise and accepts nothing, while the model's own output stays perfectly correct
* because a rejected draft costs only time.
* `fc` reads the normed embedding and the normed hidden state concatenated. The order is not in
* the checkpoint (both are one [5120, 10240] matrix); this follows DeepSeek-V3's MTP:
* `enorm(embedding)` then `hnorm(hidden)`. Per-op checks cannot tell the orders apart; the draft
* acceptance rate does (the wrong order accepts almost nothing).
*
* ============================== THE NORM GAINS ==============================
*
* GemmaRMSNorm's `1 + w` (Geom::wadd) applies here and the checkpoint proves it rather than
* suggesting it: pre_fc_norm_hidden sits at -0.06 .. -0.24 and pre_fc_norm_embedding at
* -0.27 .. -0.61 -- NEGATIVE gains, which only `1 + w` explains. `mtp.norm` sits at 0.59 .. 1.31,
* which reads as either, so it takes the same `final_wadd` the trunk's output norm takes -- one
* question, asked once, answered in one place.
* GemmaRMSNorm's `1 + w` (Geom::wadd) applies: pre_fc_norm_hidden is -0.06 .. -0.24 and
* pre_fc_norm_embedding -0.27 .. -0.61, negative gains that only `1 + w` explains. `mtp.norm`
* (0.59 .. 1.31) is ambiguous, so it takes the trunk output norm's `final_wadd`.
*
* ============================== THE KV CACHE ==============================
*
* The head's attention layer is bound to the TRUNK'S full-attention group as one more layer, at
* absolute index n_main. Two reasons, and neither is thrift:
* The head's attention is bound to the trunk's full-attention group as one more layer, at
* absolute index n_main:
*
* - the slot mapping and the block table are the trunk's. The head writes its K and V at the
* slot the trunk's token for that position occupies, so a rejected draft's entry is
* overwritten by the next step's correct token AT THE SAME ADDRESS. Draft rounds run in
* position order and each writes its own position before attending to it, so there is no
* rollback to get wrong -- which is why vLLM's EAGLE/MTP proposer needs no second block
* manager either.
* - a second group would need its own page geometry, its own free list and its own eviction,
* for a cache one seventeenth the size of the one already there.
* - It shares the trunk's slot mapping and block table, writing K and V at the slot of the
* trunk's token for that position. A rejected draft's entry is overwritten by the next step's
* correct token at the same address, and each round writes its position before attending to
* it, so no rollback is needed (as in vLLM's EAGLE/MTP proposer).
* - A second group would need its own page geometry, free list and eviction for a cache one
* seventeenth the size.
*
* The cost is that the group's page grows from 16 layers to 17 -- 6% more attention KV -- and it
* is paid only when the deployment declares speculation, because that is when the head is
* declared at all.
* The group's page grows from 16 layers to 17 (6% more attention KV), only when speculation is
* declared.
*/
#ifndef RAD_BLOCK_MTP_FP8_H
#define RAD_BLOCK_MTP_FP8_H
@@ -113,20 +93,16 @@
#include "rad_block_mlp_fp8.h"
#include "rad_block_vit.h"
#include <cstdlib>
namespace rad {
namespace arch {
/* THE 2-BIT DRAFT HEAD IS A WEIGHT THE MODEL HOLDS OR DOES NOT. `head` is the lm_head under a name
* of its own, which a recipe quantises to the 2-bit grid -- u2 codes, an f16 scale and a u8 zero a
* group of 128 -- so one checkpoint tensor makes two logical weights. This declares its name map
* (to `lm`, the checkpoint's head) and answers whether the model holds it at two bits, which is
* when the draft rounds read it. A checkpoint served as it stands, or a container converted
* without the rule, holds the bf16 head alone, and the draft rounds read that.
/* Declares the name map of the 2-bit draft head `head` (the checkpoint lm_head `lm` under its own
* name, quantised by a recipe to u2 codes with an f16 scale and u8 zero per group of 128) and
* returns whether the model holds it at two bits. If not (no such recipe), draft rounds read the
* bf16 head.
*
* Called ONCE, by the plugin, before it declares the head's buffers -- a name map is declared once
* -- and the block reads the answer back from whether those buffers exist. */
* Called once by the plugin, before it declares the head's buffers; the block infers the answer
* from whether those buffers exist. */
inline bool mtp_draft_head_q2(RadBuilder* b, const char* head, const char* lm) {
if (!head || !lm) return false;
if (map_copy(b, head, lm) < 0) return false;
@@ -134,41 +110,34 @@ inline bool mtp_draft_head_q2(RadBuilder* b, const char* head, const char* lm) {
return weight_enc(b, head, &e) && e.n_planes > 0 && e.plane[0].dtype == RAD_U2;
}
/* TEMPLATED ON THE FEED-FORWARD, because the head is a TRUNK LAYER and a trunk layer's
* feed-forward is dense in one member of this family and routed in the next. Qwen3.6-35B-A3B's
* `mtp.layers.0` carries `mlp.experts.*`, `mlp.gate` and a shared expert, exactly as its trunk
* layers do; a head hard-wired to MlpFP8 could not declare it, and the model would have a
* container with a drafter in it and no way to run one.
*
* `Ffn` is MlpFP8 or MoeFP8. Both take the same declare() arity over their own Wire and Src -- the
* MoE block's Config travels inside its Src for exactly this reason -- so nothing below has to
* know which one it has. */
/* Templated on the feed-forward, since the head mirrors a trunk layer, which is dense or routed
* by model (Qwen3.6-35B-A3B's `mtp.layers.0` has `mlp.experts.*`, `mlp.gate` and a shared expert).
* `Ffn` is MlpFP8 or MoeFP8; both have the same declare() signature over their own Wire and Src
* (MoeFP8's Config travels inside its Src for this reason). */
template <class Ffn>
struct MtpBlockFP8 {
struct Wire {
/* [max_tok, n_embd] the TRUNK's final hidden states for the step just run -- the plugin's
* `h`, which gather_rows already reads for the trunk's own logits. A pass names the rows
* it wants through out_ids and never has to know how they were laid out. */
/* [max_tok, n_embd] the trunk's final hidden states for the step just run (the plugin's
* `h`). A pass names the rows it wants through out_ids. */
rad_buf src = 0;
/* [max_tok, n_embd] IN: the hidden state this pass predicts from. OUT: the head's own,
* which is the next draft round's input. Sized for a whole prefill chunk because a
* history pass is one row a token. */
/* [max_tok, n_embd] in: the hidden state this pass predicts from; out: the head's own,
* the next round's input. Sized for a prefill chunk (history passes are one row per
* token). */
rad_buf hout = 0;
rad_buf e = 0; /* [max_tok, n_embd] the input token's embedding */
rad_buf c = 0; /* [max_tok, 2 * n_embd] the two normed halves, fc's input */
rad_buf x = 0; /* [max_tok, n_embd] the head's own residual stream */
rad_buf logits = 0; /* [max_logit_rows, n_vocab] the trunk's, shared */
/* THE 2-BIT DRAFT HEAD's working set -- see the block comment at op_dlogits. Every one of
* these is a draft round's, so they are sized at max_logit_rows and not at max_tok: a
* history pass never reaches any of them. */
/* The 2-bit draft head's working set (see op_dlogits), sized at max_logit_rows: only
* drafting rows reach it. */
rad_buf dq = 0; /* [max_logit_rows, n_embd] int8 codes */
rad_buf ds = 0; /* [max_logit_rows, 1] f32, one scale a row */
rad_buf dsum = 0; /* [n_embd/group, mpad] f32, GROUP-major (quant_act_i8's asum) */
rad_buf dsum = 0; /* [n_embd/group, mpad] f32, group-major (quant_act_i8's asum) */
rad_buf dlog = 0; /* [max_logit_rows, n_vocab] bf16, the coarse logits */
rad_buf didx = 0; /* [max_logit_rows, 1] i32, the proposed token */
rad_buf dval = 0; /* [max_logit_rows, 1] f32, its logit */
/* The layer's working set is the TRUNK's -- those buffers are dead by the time any of
* this runs, and a second set would be 150 MiB of activation planes for one layer. */
/* The layer reuses the trunk's working set, which is dead by the time the head runs (a
* second set would be 150 MiB). */
AttnGatedFP8::Wire attn{};
typename Ffn::Wire mlp{};
};
@@ -178,9 +147,8 @@ struct MtpBlockFP8 {
const char* norm = nullptr;
const char* pre_norm_hidden = nullptr;
const char* pre_norm_embedding = nullptr;
/* The checkpoint's lm_head, again. The trunk maps it as `output.weight`; the draft head is
* a second logical weight over the SAME tensor, which the recipe quantises to 2-bit codes
* (mtp_draft_head_q2). One source, two weights, no second checkpoint tensor. */
/* The checkpoint's lm_head. The trunk maps it as `output.weight`; the draft head is a
* second logical weight over the same tensor, quantised to 2 bits (mtp_draft_head_q2). */
const char* lm = nullptr;
AttnGatedFP8::Src attn{};
typename Ffn::Src mlp{};
@@ -188,8 +156,8 @@ struct MtpBlockFP8 {
Geom g{};
Wire w{};
int layer = 0; /* ABSOLUTE, so the KV group's layer_slot lookup finds it */
int64_t rows = 0; /* the widest pass: one row a token of a prefill chunk */
int layer = 0; /* absolute, for the KV group's layer_slot lookup */
int64_t rows = 0; /* the widest pass: one row per token of a prefill chunk */
int64_t off_e = 0, off_h = 0; /* the two halves' column offsets inside `c` */
rad_weight w_tok = 0, w_lm = 0, w_fc = 0, w_norm = 0, w_pre_h = 0, w_pre_e = 0;
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit lm_head and its (scale, zero) plane */
@@ -197,9 +165,9 @@ struct MtpBlockFP8 {
AttnGatedFP8 attn{};
Ffn mlp{};
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_pre_h = 0, op_pre_e = 0, op_fc = 0;
/* THE PROMPT'S MEDIA ROWS over the head's own embedding: its history pass embeds the prompt
* too, one position on, and an image token's embedding is the encoder's there as well. Set
* `media` before declare when the program has an encoder. */
/* Media rows over the head's embedding: the history pass embeds the prompt too (one position
* on), and an image token's embedding comes from the encoder. Set `media` before declare when
* the program has an encoder. */
bool media = false;
MediaRows mrows{};
rad_op op_norm = 0, op_dsel = 0, op_dback = 0, op_logits = 0;
@@ -220,14 +188,12 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
rows = g.max_tok;
if (rows <= 0 || !w_tok || !w_lm) return RAD_E_INVAL;
/* The normed embedding first, then the normed hidden state; see THE CONCAT ORDER above. */
/* The normed embedding first, then the normed hidden state (see the header). */
off_e = 0;
off_h = g.n_embd;
/* The head's own weights. SHARD_NONE on all four: three are per-channel norms over the
* residual stream, which is replicated, and `fc` reads and writes that same stream -- a
* column-sharded fc would need an all-reduce to buy 52 MiB a rank back, which is the wrong
* side of the trade at one GEMM per draft round. */
/* The head's own weights, all replicated: three norms over the replicated stream, and `fc`,
* which column-sharded would save 52 MiB per rank at the cost of an all-reduce per round. */
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.pre_fc_norm_hidden.weight"), src.pre_norm_hidden));
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.pre_fc_norm_embedding.weight"), src.pre_norm_embedding));
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.norm.weight"), src.norm));
@@ -242,9 +208,8 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
w_fc = decl_w(b, nm.f("mtp.fc.weight"), RAD_BF16, {g.n_embd, 2 * g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
/* A SECOND gather_rows and a SECOND embed_lookup, over the trunk's own buffers and weights.
* They are separate ops rather than re-issues of the trunk's because an op's read and write
* sets are what the buffer planner reads for liveness, and these write somewhere else. */
/* Separate gather_rows and embed_lookup ops over the trunk's buffers and weights, because
* they write different buffers and liveness comes from each op's read/write sets. */
op_gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
@@ -257,9 +222,8 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
RAD_WEIGHTS(w_tok)),
{}, {w.e});
if (media) RAD_ARCH_TRY(mrows.declare(b, rows, g.n_embd, w.e));
/* The trunk's table is vocab-sharded, so this gather is a partial one and needs the same
* exact reduction the trunk does. Its own op rather than the trunk's because it writes a
* different buffer, which is the rule the gather above states. */
/* The trunk's table is vocab-sharded, so the lookup is partial and needs an exact
* all-reduce. */
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -288,6 +252,23 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
{w.c}, {w.x});
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn));
/* Moves round 1's rows of a history pass (RadBatch::draft_out_ids, one per drafting sequence)
* to the front of `x` before the feed-forward, which then runs on those rows only. Goes through
* `hout` (dead between fc's read and the norm's write), since an in-place gather could
* overwrite a row not yet read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
RAD_ARCH_TRY(mlp.declare(b, nm, g, l, w.mlp, src.mlp));
op_norm = rw(b, RAD_OP(b, "rmsnorm",
@@ -297,24 +278,8 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
RAD_WEIGHTS(w_norm)),
{w.x}, {w.hout});
/* DRAFT ROUND 1'S ROWS OUT OF A HISTORY PASS (RadBatch::draft_out_ids), one a drafting
* sequence in round order, to the front of `hout` -- where the lm_head reads a round's rows
* and round 2 reads its input. Through `x`, which is dead once the norm has read it, because a
* gather in place could overwrite a row another sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* The trunk's lm_head, over the head's hidden state. Banded at the logits buffer's own extent
* rather than at `rows`: it runs over one row a drafting sequence. */
/* The trunk's lm_head over the head's hidden state, banded at the logits buffer's extent: it
* runs over one row per drafting sequence. */
op_logits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab),
@@ -322,47 +287,31 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
RAD_WEIGHTS(w_lm)),
{w.hout}, {w.logits});
/* ---- THE 2-BIT DRAFT HEAD -------------------------------------------------------------
/* ---- The 2-bit draft head.
*
* `logits_gemm` IS ALREADY AT THE MEMORY ROOFLINE for the bf16 lm_head's 2.54 GB, so the only
* lever it has is FEWER BYTES. That matters here and not at the trunk, because a speculative
* step runs the projection THREE times: once to verify, and once per draft round.
* `logits_gemm` is at the memory roofline for the bf16 lm_head's 2.54 GB, and a speculative
* step runs the projection once to verify plus once per draft round. Drafts are verified by the
* exact head, so a coarser draft head costs only acceptance, never an emitted token.
*
* The two draft ones do not need the exact distribution. A draft is a PROPOSAL; the target
* verifies every one of them with its own untouched bf16 head, and speculative decoding is
* distribution-preserving -- so a worse draft costs ACCEPTANCE and cannot change a token the
* model emits. That is the one place in the step where precision buys throughput outright.
* The draft rounds read a 2-bit copy: 318 MB of codes and 40 MB of (scale, zero) dwords, an
* eighth of the traffic. libr4d's `gemm_w2a8_nt` takes codes and the scale/zero planes as two
* operands, laid out as `r4d.w2a8.frag.g128` at load (libr4d/r4d_layout.cpp). The grid is
* asymmetric (four levels are too few for a symmetric one), so the activation side uses
* `quant_act_i8`'s three-output form, whose per-group row sums subtract the stored zero.
*
* So the drafter reads a 2-bit copy: 318 MB of codes and 40 MB of (scale, zero) dwords against
* 2.54 GB, an eighth of the traffic. It is a logical weight of its own over the checkpoint's
* head (mtp_draft_head_q2), quantised by the recipe; libr4d's `gemm_w2a8_nt` takes its codes
* and its scale and zero planes as two operands and lays them out as `r4d.w2a8.frag.g128` at
* load (libr4d/r4d_layout.cpp). The grid is asymmetric -- four levels are not enough for a
* symmetric one -- which is why the activation side is `quant_act_i8`'s three-output form: the
* per-group row sums are what subtract the stored zero.
*
* AND IT DOES NOT GO THROUGH THE SAMPLER. The 2-bit GEMM writes bf16 and the sampler's chain
* reads the f32 logits plane, so a draft round would need a cast of a 248K-wide row to reach
* it -- for an argmax. `row_topk` at R=1 is that argmax, on the bf16 the GEMM already wrote,
* and the engine reads the proposed id straight out of `didx`. The trunk's logits plane is
* left alone, which is also what lets a draft round sample nothing at all.
* The draft head bypasses the sampler, which reads f32 logits: `row_topk` at R=1 takes the
* argmax on the GEMM's bf16 output and the engine reads the id from `didx`. The trunk's logits
* plane is untouched.
*/
enum { MTP_W2_GROUP = 128 }; /* libr4d's R4D_GEMM_W2A8_GROUP, and the layout's g128 tag */
/* The plugin declared the working set only where mtp_draft_head_q2 found the head at two
* bits, which declared its name map too. */
/* The plugin declares the working set only when mtp_draft_head_q2 found a 2-bit head (and
* declared its name map). */
q2 = src.lm && w.dq && w.ds && w.dsum && w.dlog && w.didx && w.dval;
if (q2) {
/* REPLICATED, AT THE WHOLE VOCABULARY, and that is a decision rather than an omission.
*
* The trunk's lm_head is row-sharded and its logits are merged across ranks by the
* sampler. This head does NOT go through the sampler -- the comment above op_dlogits says
* why -- so its argmax is a `row_topk` over one rank's plane, and a sharded plane would
* make every rank propose only tokens from its own half. Replicating it costs 341 MiB a
* card at 2 bits (against the 1.27 GiB a rank saves on the trunk head) and keeps the
* draft path a single-rank computation, which is what it is.
*
* The stored bytes are also tile-major (16 output rows a packed block), so the relayout
* would have to be handed a row share that is a whole number of tiles. */
/* Replicated over the whole vocabulary. Without the sampler's cross-rank merge, a sharded
* plane would let each rank propose only its own vocabulary slice. Replication costs 341
* MiB per card at 2 bits and keeps the draft path single-rank. (The stored bytes are also
* tile-major, 16 output rows per packed block, so a shard would have to be whole tiles.) */
const char* dhn = nm.f("mtp.draft_head.weight");
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {g.n_vocab_all, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
@@ -393,11 +342,9 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
{w.dlog}, {w.didx, w.dval});
}
/* THE HEAD'S OUTPUT STAYS LIVE THROUGH THE WHOLE HEAD. It is the next round's input, written
* before this pass's lm_head runs; declared as read by the lm_head's first op alone, the
* buffer planner would let the ops after it take its bytes, and the next round would continue
* from what they wrote. Nothing fails: acceptance falls. Read by the head's last op as well,
* it survives every pass of the step. */
/* Keep `hout` live through the head's last op: it is the next round's input, and if only the
* lm_head's first op read it, the planner could give its bytes to later ops (silently lowering
* acceptance). */
{
const rad_op last = q2 ? op_dtopk : op_logits;
if (rad_op_reads(b, last, &w.hout, 1) < 0) return RAD_E_INVAL;
@@ -405,17 +352,16 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
return RAD_OK;
}
/* One pass of the head. The batch is the one the scheduler built for it: n_tok rows, `token_ids`
* already shifted one position on (batch.cpp, token_at), `positions` the head's own indices, and
* the KV group batch carrying the slot each row writes at -- so every op below runs at n_tok rows
* and the attention layer needs no special case at all. */
/* One pass of the head over the scheduler's batch for it: n_tok rows, `token_ids` already shifted
* one position on (batch.cpp, token_at), `positions` the head's indices, and the KV group batch
* carrying each row's slot, so the attention layer needs no special case. */
template <class Ffn>
inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const int r = batch->draft_pass;
/* The history pass gathers; the rounds after it read the head's own output, which the pass
* before left in the same buffer. */
/* The history pass gathers; later rounds read the previous pass's output from the same
* buffer. */
if (r == 1) {
rad_step_fail(c, "the MTP head was handed a draft-round-1 pass: that round is carried by "
"the history pass (RadBatch::draft_out_ids) and has no pass of its own");
@@ -435,34 +381,34 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE(c, op_fc, brows(w.c, T), RAD_W(w_fc), brows(w.x, T));
/* A history pass with no drafting rows (every prefill chunk but a prompt's last) only needs
* K and V. `n_draft_out` is the same on every rank, so skipped collectives match. */
if (r < 0 && batch->n_draft_out <= 0) {
attn.store_kv(c, batch);
return;
}
attn.step(c, batch);
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave K and V behind, and the
* attention above has stored them. The feed-forward, the norm and the lm_head compute the
* head's output, which only a drafting row reads -- and every prefill chunk but a prompt's
* last drafts nothing. `n_draft_out` is the batch's and the same on every rank, so a
* collective the feed-forward would run is skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) return;
mlp.step(c, batch);
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.hout, T));
/* A history pass that drafts brings round 1's rows to the front first. */
int64_t L = T; /* the rows the lm_head runs over */
/* A history pass with drafting rows continues on those rows alone (round 1): they are moved
* to the front of `x` and the rest of the head runs over them. */
int64_t L = T; /* the rows the stream goes on with */
if (r < 0) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hout), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.x, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.x, L), brows(w.hout, L));
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.x), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hout, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.hout, L), brows(w.x, L));
}
mlp.step_rows(c, L);
RAD_ISSUE(c, op_norm, brows(w.x, L), RAD_W(w_norm), brows(w.hout, L));
if (q2) {
/* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
* whole: there is no row slice of it that means anything. */
/* `dsum` is group-major [n_embd/group][ceil(L/16)*16], so it has no row slice; pass it
* whole. */
RAD_ISSUE_N(c, op_dquant, L, brows(w.hout, L), brows(w.dq, L), brows(w.ds, L),
RAD_B(w.dsum));
/* The trailing `b_ref` is mxfp4's and absent here; an absent optional operand is a null
* tensor in a full-length list, not a shorter list (rad_fp8.h says why). */
/* The trailing `b_ref` is mxfp4's and absent; operands are positional, so pass RAD_NONE
* (rad_fp8.h). */
RAD_ISSUE_N(c, op_dlogits, L, brows(w.dq, L), brows(w.ds, L), RAD_W(w_dh), RAD_W(w_dhs),
brows(w.dlog, L), RAD_B(w.dsum), RAD_NONE);
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
@@ -472,10 +418,8 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
}
}
/* The dense head, which is the 27B's and every other member of this family whose feed-forward is
* one SwiGLU. The routed one is MtpBlockFP8<MoeFP8>, named by the plugin that wants it -- this
* header does not include rad_block_moe_fp8.h, because a dense plugin should not compile a routed
* block it will never declare. */
/* The dense head (SwiGLU feed-forward). The routed one is MtpBlockFP8<MoeFP8>, named by the
* plugin that needs it; this header does not include rad_block_moe_fp8.h. */
using MtpFP8 = MtpBlockFP8<MlpFP8>;
} /* namespace arch */
+215 -231
View File
@@ -1,30 +1,25 @@
/* rad_block_mtp_hc.h -- the multi-token-prediction head of a model whose residual stream is `hc`
* times the model width.
*
* ============================== WHY THIS IS NOT rad_block_mtp_fp8.h ==============================
* ============================== DIFFERENCES FROM rad_block_mtp_fp8.h ==============================
*
* That file serves Qwen3.5 / Qwen3-Next / Qwen3.6, where the head is a PRE-NORM transformer layer
* that reads the trunk's [n_embd] hidden state. It is the same idea, the same indexing and the
* same two kinds of pass -- and almost none of the same parts, because Qwen4-Exp's head lives in
* the WIDE stream:
* That file serves Qwen3.5 / Qwen3-Next / Qwen3.6, whose head is a pre-norm layer reading the
* trunk's [n_embd] hidden state. Qwen4-Exp's head has the same indexing and passes but lives in
* the wide stream:
*
* ITS INPUT IS 10240 WIDE `mtp.pre_fc_norm_hidden.weight` is [hc * n_embd], so the hidden
* state this head continues from is the trunk's wide stream BEFORE
* the output mixer collapses it, not `last_hidden_state`.
* THERE ARE TWO fc MATRICES `mtp.fc_hidden` and `mtp.fc_embedding`, both [n_embd, n_embd].
* So there is no concatenation and no concat-ORDER question: the
* hidden half is one square matrix applied to EACH sub-stream and
* the embedding half is one product broadcast into all of them.
* docs/OPS.md's `mtp_enter` row is that arithmetic.
* ITS LAYER HAS TWO GATED `mtp.layers.0.attn_hyper_connection` and `.mlp_hyper_connection`,
* RESIDUALS, NOT TWO NORMS exactly as a trunk layer does. There is no `input_layernorm` and
* no `post_attention_layernorm` in this checkpoint at all.
* AND A MIXER OF ITS OWN `mtp.hyper_connection_mixer` -- a connection with no write half,
* which is what collapses the head's wide stream for the lm_head.
* It is the 98th connection in the model and the trunk's 97th has
* the same shape and the same absent `block_inject_weight`.
*
* What is NOT different is the part that is easy to get wrong, so it is restated here in full.
* 10240-wide input `mtp.pre_fc_norm_hidden.weight` is [hc * n_embd]: the head
* continues from the trunk's wide stream before the output mixer,
* not `last_hidden_state`.
* two fc matrices `mtp.fc_hidden` and `mtp.fc_embedding`, both [n_embd, n_embd], so
* no concatenation: the hidden matrix is applied to each
* sub-stream and the embedding product broadcast into all of them
* (docs/OPS.md's `mtp_enter` row).
* gated residuals, no norms `mtp.layers.0.attn_hyper_connection` and `.mlp_hyper_connection`,
* as in a trunk layer; no `input_layernorm` or
* `post_attention_layernorm`.
* its own mixer `mtp.hyper_connection_mixer`, a connection with no write half
* that collapses the wide stream for the lm_head (the model's 98th
* connection, shaped like the trunk's final one).
*
* ============================== THE INDEXING ==============================
*
@@ -32,62 +27,44 @@
* writes its K and V at KV position i, with rope position i
* predicts the token at i + 2
*
* DeepSeek-V3's MTP layout, which this family follows: the head's transformer block runs over the
* SAME position indices as the trunk and the shift lives entirely in which token gets embedded.
* Getting it off by one costs nothing visible -- the drafts are simply wrong, acceptance collapses,
* and the model's own output stays exactly correct.
* DeepSeek-V3's layout: the head runs over the trunk's position indices and the shift is only in
* which token is embedded. An off-by-one shows only as collapsed acceptance.
*
* ============================== THE TWO KINDS OF PASS ==============================
*
* `RadBatch::draft_pass` says which and the SIGN is the whole distinction:
* By the sign of `RadBatch::draft_pass` (details in rad_block_mtp_fp8.h):
*
* < 0 A HISTORY PASS, one row a token, continuing from the trunk's own wide stream. The
* head's attention reads its OWN K and V for every earlier position and nothing else in
* the engine writes those -- the trunk's prefill fills layers 0..n-1 and leaves the head's
* untouched. Without it the head attends to whatever the pool last held, which is not
* wrong output (a bad draft is only a rejected draft) but is a drafter that proposes noise.
* It is also DRAFT ROUND 1 for the sequences that draft: each one's last history row is
* the committed position with the token the trunk chose after it, which is round 1's
* whole input, so the pass ends in the lm_head over those rows (RadBatch::draft_out_ids)
* and hands their wide state on as the carry.
* > 1 A DRAFT ROUND, one row a sequence, continuing from the head's own stream. There is no
* round-1 pass; the history pass is it.
* < 0 History pass, one row per token, continuing from the trunk's wide stream. It writes the
* head's own K and V, which nothing else writes. It is also draft round 1 for drafting
* sequences: it ends in the lm_head over their rows (RadBatch::draft_out_ids) and hands
* their wide state on as the carry.
* > 1 Draft round, one row per sequence, continuing from the head's own stream.
*
* ============================== THE CARRY, AND WHY IT IS A COPY ==============================
* ============================== THE CARRY ==============================
*
* `hin` is what a round continues FROM and `hw` is the head's own stream. They cannot be one
* buffer: `mtp_enter` reads the whole wide row to produce every channel of its output, so a
* workgroup writing channels 0..31 would clobber input another workgroup has not read yet. The
* pre-norm head has no such problem because its carry is written by a DIFFERENT op at the end of
* the round (`mtp.norm`), and here the end of the round is the mlp connection's write, in place.
*
* So one `cast` copies `hw` back to `hin` between rounds -- a 20 KB row copy at decode, whose cost
* is its launch -- and it is SKIPPED on the last round because nothing reads it there. A history
* pass that drafts takes its carry with a `gather_rows` instead, of the round-1 rows alone, and
* copies them back to the front of `hw`, where the mixer reads a round's rows.
* `hin` is what a round continues from and `hw` the head's own stream. They cannot share a buffer:
* `mtp_enter` reads the whole wide row for every output channel, so in-place writes would clobber
* unread input. (The pre-norm head's carry is written by a different op, `mtp.norm`; here the
* round ends with the mlp connection's in-place write.) A `cast` copies `hw` to `hin` between
* rounds (a 20 KB row at decode), skipped on the last round. A drafting history pass instead
* gathers its round-1 rows and copies them back to the front of `hw`, where the mixer reads them.
*
* ============================== THE KV CACHE ==============================
*
* The head's attention layer is bound to the TRUNK'S full-attention group as one more layer, at
* absolute index n_layer. The slot mapping and the block table are the trunk's, so the head writes
* its K and V at the slot the trunk's token for that position occupies and A REJECTED DRAFT'S
* ENTRY IS OVERWRITTEN BY THE NEXT STEP'S CORRECT TOKEN AT THE SAME ADDRESS. Draft rounds run in
* position order and each writes its own position before attending to it, so there is no rollback
* to get wrong. The cost is that the group's page grows from 12 layers to 13 -- 8% more attention
* KV -- and it is paid only when the deployment declares speculation.
* The head's attention is bound to the trunk's full-attention group as one more layer, at
* absolute index n_layer, sharing its slot mapping and block table; a rejected draft's entry is
* overwritten by the next step's token at the same address (see rad_block_mtp_fp8.h). The group's
* page grows from 12 layers to 13 (8% more attention KV), only when speculation is declared.
*
* ============================== WHAT IS AND IS NOT DECLARED ==============================
* ============================== BUFFERS ==============================
*
* The head reuses the TRUNK'S working buffers for its layer -- `attn_qg`, the expert planes, the
* narrow block input. Every one of them is dead by the time a draft round runs (the trunk step has
* been sampled and committed) and a second set would be 150 MiB of activation planes for one
* layer. Only the wide stream, the carry, the embedding and the head's own logits path are its
* own, because those must survive the round that produced them.
* The layer reuses the trunk's working buffers (`attn_qg`, the expert planes, the narrow block
* input), which are dead once the trunk step is committed; a second set would be 150 MiB. Only
* the wide stream, the carry, the embedding and the logits path are its own.
*
* THIS BLOCK MUST THEREFORE BE DECLARED AFTER THE TRUNK'S LAST OP. Declaration order IS the buffer
* planner's liveness (core/build/rad_bufplan.cpp) and a drafter declared mid-trunk shares bytes
* with buffers the trunk still has live. The signature of getting it wrong is fluent output with
* acceptance EXACTLY zero.
* Invariant: declare this block after the trunk's last op. Declaration order is the buffer
* planner's liveness (core/build/rad_bufplan.cpp); declared mid-trunk, the head would share bytes
* with live trunk buffers (symptom: correct output, zero acceptance).
*/
#ifndef RAD_BLOCK_MTP_HC_H
#define RAD_BLOCK_MTP_HC_H
@@ -96,35 +73,28 @@
#include "rad_block_hc.h"
#include "rad_block_moe_fp8.h"
#include "rad_block_mtp_fp8.h" /* mtp_draft_head_q2(): one reading of the 2-bit head */
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire */
#include "rad_qsa.h"
#include "rad_block_vit.h"
#include <cstdlib>
namespace rad {
namespace arch {
/* HOW MANY CANDIDATES THE COARSE HEAD PROPOSES, and it is 8 because they are RESCORED.
/* Candidates the coarse 2-bit head proposes for exact rescoring (`logit_rerank` against the
* full-precision head) before column 0 is read. The 2-bit head's top-1 differs from the exact one
* often enough to cost acceptance; 8 is the reference implementation's value, which recovered
* 99.63% agreement with the exact argmax, at R rows of the weight per draft row (40 KB against
* 318 MB).
*
* A draft needs one token. The 2-bit head picks a different top-1 than the exact head often enough
* to cost several points of acceptance, so the coarse head proposes R candidates and
* `logit_rerank` scores those R against the full-precision head before column 0 is read. 8 is the
* reference implementation's number, which recovered a coarse head to 99.63% agreement with the
* exact argmax; the cost is R rows of the weight a draft row, 40 KB against 318 MB. */
/* AND R HAS AN OPTIMUM, which is not the obvious thing. A wider candidate set can only raise the
* EXACT score the rescore selects, so more candidates ought to be free -- and both sixteen and
* four are reproducibly worse than eight on draft acceptance.
*
* Because acceptance is agreement with the TRUNK and the rescore maximises the MTP HEAD's own
* preference over the candidate set. Past some width, taking that preference more seriously walks
* away from the trunk's argmax -- so the coarse head's ranking is a useful restriction and not
* just noise to be corrected. */
* Both 4 and 16 give lower acceptance than 8: acceptance is agreement with the trunk, while the
* rescore maximises the head's own preference, so beyond some width the coarse ranking is a useful
* restriction. */
static constexpr int64_t kDraftTopR = 8;
struct MtpHcBlock {
struct Wire {
/* [max_tok, hc * n_embd] the TRUNK's wide stream for the step just run. A pass names the
* rows it wants through out_ids and never has to know how they were laid out. */
/* [max_tok, hc * n_embd] the trunk's wide stream for the step just run; a pass names the
* rows it wants through out_ids. */
rad_buf src = 0;
rad_buf hin = 0; /* [max_tok, hc * n_embd] what this round continues from */
rad_buf hw = 0; /* [max_tok, hc * n_embd] the head's own wide stream */
@@ -132,13 +102,16 @@ struct MtpHcBlock {
rad_buf inj = 0; /* [max_tok, hc] both connections' write gains */
rad_buf hout = 0; /* [max_logit_rows, n_embd] the mixer's output, the lm_head's input */
rad_buf logits = 0; /* [max_logit_rows, n_vocab] the trunk's, shared */
ActFP8 x{}; /* the narrow block input -- the TRUNK's */
/* THE 2-BIT DRAFT HEAD's working set. Every one of these is a draft round's, so they are
* sized at max_logit_rows: a history pass never reaches any of them. */
ActFP8 x{}; /* the narrow block input, the trunk's */
/* The 2-bit draft head's working set, sized at max_logit_rows (only drafting rows reach
* it). */
rad_buf dq = 0, ds = 0, dsum = 0, dlog = 0, didx = 0, dval = 0;
/* The vocab-parallel pair, declared only when the head is SHARDED. Both are (int32 id,
* float value) pairs read as f32: this rank's top-1, and the all-gathered world * 1. */
/* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
* pairs stored as f32, this rank's top-R and the all-gathered world * R. */
rad_buf dpair = 0, dgath = 0;
/* --draft-coupling: [max_seqs] draws and [depth, max_seqs] states, both PERSIST across
* the serial passes (round 1 resets the logical stream, not the plane). */
rad_buf couple_draws = 0, couple_state = 0;
AttnGatedFP8::Wire attn{};
MoeFP8::Wire mlp{};
QsaIndexer::Wire qsa{};
@@ -160,12 +133,11 @@ struct MtpHcBlock {
Wire w{};
int layer = 0;
int64_t rows = 0;
int depth = 0; /* rounds this deployment will run -- the carry's last-round test */
int64_t ngroup = 0; /* the pre-fc norm's groups: hc, one rsqrt a sub-stream */
int depth = 0; /* rounds this deployment runs; decides whether the carry is needed */
int64_t ngroup = 0; /* the pre-fc norm's groups: hc, one rsqrt per sub-stream */
bool q2 = false;
/* The 2-bit draft head's logical weight: the checkpoint's lm_head under a name of its own,
* which a recipe stores as 2-bit codes. The plugin asks mtp_draft_head_q2 about this name --
* which also declares its map -- and declares the head's buffers when the answer is yes. */
/* The 2-bit draft head's name. The plugin passes it to mtp_draft_head_q2 (which declares the
* map) and declares the head's buffers if that returns true. */
static const char* head_name(Names& nm) { return nm.f("mtp.draft_head.weight"); }
rad_weight w_tok = 0, w_lm = 0, w_fc_h = 0, w_fc_e = 0, w_pre_h = 0, w_pre_e = 0;
@@ -174,13 +146,15 @@ struct MtpHcBlock {
HyperConn hc_attn{}, hc_mlp{}, mixer{};
AttnGatedFP8 attn{};
QsaIndexer qsa{};
/* The indexer's window bounds for a pass wider than its score plane (QsaIndexer::step), set by
* the caller before step(); null where no pass is. */
const int32_t* qsa_win_cu = nullptr;
MoeFP8 mlp{};
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_enter = 0, op_carry = 0;
/* THE PROMPT'S MEDIA ROWS over the head's own embedding: its history pass embeds the prompt
* too, one position on, and an image token's embedding is the encoder's there as well. Set
* `media` before declare when the program has an encoder. */
/* Media rows over the head's embedding (see MtpBlockFP8::media). Set before declare when the
* program has an encoder. */
bool media = false;
@@ -188,9 +162,12 @@ struct MtpHcBlock {
rad_op op_dsel = 0, op_dback = 0;
rad_op op_logits = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0, op_drerank = 0;
rad_op op_dgather = 0, op_dmerge = 0;
/* --draft-coupling: one op a round. The ABI freezes `round` as a parameter, so a round
* cannot be an operand and each gets its own declared op. */
rad_op op_couple[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
/* rad_arch.h's, asked through the block so whoever sizes `dlog` and the pair planes does not
* re-derive the rule. */
/* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
* planes. */
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
static int64_t head_rows(const Geom& g) { return vocab_head_rows(g); }
@@ -206,19 +183,16 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
const Wire& wire, const Src& src) {
g = geom; w = wire; layer = l; w_tok = tok_embd; w_lm = lm_head;
rows = g.max_tok; depth = draft_depth;
/* The pre-fc norm over the wide stream is GROUPED, one rsqrt a sub-stream, which is what every
* gated residual in this architecture does. A flat norm fits the same [hc*n] gain and no
* per-op oracle can tell the two apart; the acceptance rate can -- docs/OPS.md's `mtp_enter`
* row. */
/* The pre-fc norm over the wide stream is grouped, one rsqrt per sub-stream, like every gated
* residual here. A flat norm fits the same [hc*n] gain and passes per-op checks; only the
* acceptance rate tells them apart (docs/OPS.md's `mtp_enter` row). */
ngroup = hc.hc;
if (rows <= 0 || !w_tok || !w_lm || hc.hc <= 1) return RAD_E_INVAL;
if (!w.src || !w.hin || !w.hw || !w.e || !w.hout) return RAD_E_INVAL;
const int64_t HN = hc.hc * g.n_embd;
/* ---- the entry's four weights. SHARD_NONE on all of them: two are per-channel gains over a
* replicated stream and the two fc matrices read and write that same stream, so a column shard
* would need an all-reduce to save 13 MB a rank -- the wrong side of the trade at one launch
* per draft round. */
/* ---- the entry's four weights, all replicated: two gains over the replicated stream, and two
* fc matrices whose column shard would save 13 MB per rank at an all-reduce per round. */
const char* nph = nm.f("mtp.pre_fc_norm_hidden.weight");
const char* npe = nm.f("mtp.pre_fc_norm_embedding.weight");
const char* nfh = nm.f("mtp.fc_hidden.weight");
@@ -227,9 +201,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_ARCH_TRY(map_copy(b, npe, src.pre_norm_embedding));
RAD_ARCH_TRY(map_copy(b, nfh, src.fc_hidden));
RAD_ARCH_TRY(map_copy(b, nfe, src.fc_embedding));
/* THE TWO ENTRY MATRICES ARE WHATEVER THEIR ENCODING IS -- bf16, or E4M3 rows with a scale a
* group of each row (OPS.md's `fc` on mtp_enter) -- declared over every plane at the codes'
* dtype. It only ever changes the DRAFTS: the head proposes and the trunk verifies. */
/* The entry matrices are bf16 or E4M3 rows with a per-group scale (OPS.md's `fc` on
* mtp_enter), declared over all planes at the codes' dtype; both must match. */
const uint32_t fdt = weight_codes_dtype(b, nfh, RAD_BF16);
if (weight_codes_dtype(b, nfe, RAD_BF16) != fdt || (fdt != RAD_BF16 && fdt != RAD_F8E4M3)) {
fprintf(stderr, "radiance: the MTP head's fc_hidden is %s and fc_embedding %s; the entry "
@@ -246,9 +219,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
grp_layer(l));
if (!w_pre_h || !w_pre_e || !w_fc_h || !w_fc_e) return RAD_E_INVAL;
/* A SECOND gather_rows and a SECOND embed_lookup over the trunk's own buffers and weights.
* They are separate ops rather than re-issues of the trunk's because an op's read and write
* sets are what the buffer planner reads for liveness, and these write somewhere else. */
/* Separate gather_rows and embed_lookup ops over the trunk's buffers and weights, because
* they write different buffers and liveness comes from each op's read/write sets. */
op_gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", HN),
RAD_STR("dtype", g.dtype)),
@@ -261,8 +233,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_WEIGHTS(w_tok)),
{}, {w.e});
if (media) RAD_ARCH_TRY(mrows.declare(b, rows, g.n_embd, w.e));
/* The trunk's table is vocab-sharded, so this gather is a partial one and needs the same exact
* reduction the trunk's does. Its own op because it writes a different buffer. */
/* The trunk's table is vocab-sharded, so the lookup is partial and needs an exact
* all-reduce. */
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -281,9 +253,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
{w.hin, w.e}, {w.hw});
if (!op_gather || !op_embed || !op_enter) return RAD_E_INVAL;
/* ---- the layer. One gated residual, a gated full-attention block with its indexer, a second
* gated residual and the routed feed-forward -- a trunk full-attention layer, at layer index
* n_layer, and declared in exactly the order step() issues it in. */
/* ---- the layer, as a trunk full-attention layer at index n_layer: gated residual, gated
* attention with its indexer, gated residual, routed feed-forward. Declared in step()'s issue
* order. */
RAD_ARCH_TRY(hc_attn.declare(b, nm, g, nm.f("mtp.attn_hc"), hc, HyperConn::Wire{w.hw, w.x, w.inj},
src.hc_attn));
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
@@ -292,16 +264,35 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
false, false, kArNone, hc_attn.op_ar_write != 0));
if (src.qsa.qk_proj)
RAD_ARCH_TRY(qsa.declare(b, nm, g, l, src.qsa, w.qsa, w.attn.h, qsa_bk));
/* The rotated expert input rides in this read, as it does on the trunk. */
/* ---- round 1's rows of a history pass (RadBatch::draft_out_ids), moved before the
* feed-forward, which then runs on them only: gathered into `hin` and copied back to the
* front of `hw` (an in-place gather could overwrite unread rows). */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hin}, {w.hw});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* The connection's read also writes the rotated expert input, as on the trunk. */
HyperConn::Config mcfg = hc;
HyperConn::Wire mwire{w.hw, w.x, w.inj};
if (src.mlp.cfg.expert_rot) { mcfg.rotate = 1; mwire.rq = w.mlp.hr.q; mwire.rs = w.mlp.hr.s; }
if (src.mlp.cfg.expert_rot && !w.x.q8_rot) {
mcfg.rotate = 1;
mwire.rq = w.mlp.hr.cq();
mwire.rs = w.mlp.hr.cs();
}
RAD_ARCH_TRY(hc_mlp.declare(b, nm, g, nm.f("mtp.ffn_hc"), mcfg, mwire, src.hc_mlp));
mlp.ar_out_take = hc_mlp.ar_take();
mlp.hr_in = mcfg.rotate != 0;
RAD_ARCH_TRY(mlp.declare(b, nm, g, l, w.mlp, src.mlp, false, false, kArNone,
hc_mlp.op_ar_write != 0));
/* The write behind the block takes its gather where it can, as on the trunk. */
/* The following write takes the MoE gather where it can, as on the trunk. */
{
HyperConn::GatherSrc gs{};
gs.ye = mlp.w.edn;
@@ -315,30 +306,15 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
mlp.gather_out_rows6 = hc_mlp.gather_rows6;
}
/* ---- the carry. See the header: `mtp_enter` cannot be issued in place. */
/* ---- the carry (see the header: `mtp_enter` cannot run in place). */
op_carry = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", HN),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
/* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids): gathered into the
* carry, one row a drafting sequence in round order, and copied back to the front of `hw` for
* the mixer. Two ops and not one because a gather in place could overwrite a row another
* sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hin}, {w.hw});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* ---- the head's own mixer: the connection with no write half, which collapses its wide
* stream to the one hidden state the lm_head reads. No fp8 twin -- that input is bf16. */
/* ---- the head's mixer: a connection with no write half that collapses the wide stream for
* the lm_head, which reads bf16, so no fp8 codes. */
{
HyperConn::Config mc = hc;
mc.inject = 0;
@@ -348,8 +324,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_ARCH_TRY(mixer.declare(b, nm, g, nm.f("mtp.output_hc"), mc, mixw, src.hc_mix));
}
/* The trunk's lm_head over the head's hidden state, banded at the logits buffer's own extent:
* only a DRAFT round reaches this and a draft round is one row a sequence. */
/* The trunk's lm_head over the head's hidden state, banded at the logits buffer's extent (one
* row per drafting sequence). */
op_logits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab),
@@ -358,33 +334,22 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
{w.hout}, {w.logits});
if (!op_carry || !op_logits) return RAD_E_INVAL;
/* ---- THE 2-BIT DRAFT HEAD. rad_block_mtp_fp8.h argues it in full; the short version is that
* `logits_gemm` is already at the memory roofline, so its only lever is FEWER BYTES -- and
* a speculative step runs the projection once to verify and once PER DRAFT ROUND. A draft is a
* proposal the target verifies with its own head, so a worse draft costs acceptance and
* cannot change a token the model emits. */
/* ---- The 2-bit draft head (rationale in rad_block_mtp_fp8.h): fewer bytes per draft round,
* at the cost of acceptance only. */
enum { MTP_W2_GROUP = 128 };
/* A DRAFT NEEDS ONE TOKEN AND THE TOP-R IS WIDER THAN THAT; kDraftTopR says why. There is also
* a HARD LOWER BOUND of 2 from the all-gather: `ar_gather_2rank` places rank r's contribution
* row-interleaved and requires the row to be a whole number of 16-byte words, and a pair is
* (int32 id, float value) -- so R = 1 is an 8-byte row and is refused, while R = 2 is 16. The
* engine reads column 0 through `proposal_pitch`, which is what that field is for. */
/* R is kDraftTopR. It must also be at least 2: `ar_gather_2rank` needs rows of whole 16-byte
* words and a pair is 8 bytes. The engine reads column 0 through `proposal_pitch`. */
q2 = w.dq && w.ds && w.dsum && w.dlog && w.didx && w.dval;
if (q2) {
/* AND IT IS VOCAB-PARALLEL, which is 159 MB a round rather than 318. The head does not go
* through the sampler, so its argmax is a `row_topk` over one rank's plane -- and a
* sharded plane alone would make every rank propose only tokens from its own half. That
* is what `row_topk`'s `vocab_off` and `row_topk_merge` are for, and they are the same
* three ops arch/common/rad_block_dspark.h already drives: a top-R reporting GLOBAL ids,
* an all_gather of (id, value) pairs, and a merge that finds exactly the top-R an
* unsharded head would have. */
/* Vocab-parallel when possible (159 MB a round instead of 318). Bypassing the sampler, it
* uses the same three ops as rad_block_dspark.h: a top-R reporting global ids, an
* all_gather of (id, value) pairs, and a merge giving exactly the unsharded top-R. */
const bool dh_shard = head_sharded(g) && w.dpair && w.dgath;
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
const int64_t hrows = dh_shard ? g.n_vocab : g.n_vocab_all;
/* ITS OWN STORED WEIGHT, MADE FROM THE TRUNK'S lm_head by the recipe: two-bit codes with
* an f16 scale and a u8 zero point a group of 128 (`u2*f16+u8[1x128]`), its name map
* declared by mtp_draft_head_q2. The GEMM takes the codes as one operand and the scale
* and zero planes as the other. */
/* Its own stored weight made from the trunk's lm_head by the recipe (`u2*f16+u8[1x128]`),
* name map declared by mtp_draft_head_q2. The GEMM takes codes as one operand and the
* scale/zero planes as the other. */
const char* dhn = head_name(nm);
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {hrows, g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_layer(l));
@@ -404,10 +369,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_INT("group", MTP_W2_GROUP), RAD_STR("dtype", "w2a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds, w.dsum}, {w.dlog});
/* Sharded, the top-R runs over THIS RANK'S plane and reports GLOBAL ids, and it also
* writes the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
* replicated: an optional parameter present with the value 0 is not the same declaration
* as an absent one. */
/* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the
* pair plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter
* present with value 0 is a different declaration from an absent one. */
op_dtopk = dh_shard
? rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("N", hrows),
@@ -420,29 +384,18 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_INT("R", kDraftTopR), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.didx, w.dval});
/* ---- THE COARSE HEAD'S CANDIDATES, RESCORED EXACTLY.
/* ---- Exact rescoring of the coarse candidates against `w_lm`, the trunk's lm_head
* (already resident; the fallback `op_logits` reads it). It reads R rows per draft row in
* the trunk's stored layout, which libr4d's rerank shares with its fp8 logits GEMM.
*
* `w_lm` is the trunk's lm_head: already declared, already resident, already this
* block's (it is what the fallback's `op_logits` reads), so the rerank costs no weight.
* It reads R rows of it a draft row, in the stored form the trunk's logits_gemm reads:
* libr4d's rerank takes the same layout as its fp8 logits GEMM, so one stored head serves
* both, and a kernel that reads neither form is not selected for either.
* No extra collective: sharded, every candidate is one this rank owns, and the existing
* gather and merge then rank exact values. It overwrites `didx`/`dval`/`dpair` in place.
*
* IT NEEDS NO COLLECTIVE OF ITS OWN. Sharded, `row_topk` picked from THIS RANK'S plane and
* reported global ids, so every candidate it hands over is one this rank owns and can
* score; the existing all_gather and merge then find the global winner over exact values
* instead of coarse ones. The op writes back over `didx`/`dval`/`dpair` in place, which is
* what keeps that chain unchanged.
* Skipped for a replicated draft head above one rank: the vocabulary did not shard cleanly
* (vocab_head_sharded) while the trunk's lm_head stays row-sharded, so candidates include
* ids this rank cannot score.
*
* AND THAT OWNERSHIP IS WHY A REPLICATED DRAFT HEAD ABOVE ONE RANK SKIPS IT. A vocabulary
* that does not shard cleanly (vocab_head_sharded) replicates the DRAFT head while the
* trunk's lm_head stays row-sharded, so `row_topk` then reports ids from the whole
* vocabulary and half of them are not this rank's to score. The coarse head's own answer
* stands, unreranked, and the rerank sits out.
*
* `vocab_off` is passed always and not only when sharded: unlike `row_topk`, this op has
* one form, and at world 1 the offset is 0 and `n_vocab` is the whole vocabulary, which is
* the same declaration either way. */
* `vocab_off` is always passed: this op has one form, and at world 1 it is 0. */
const bool rerank = dh_shard || g.world <= 1;
if (rerank) {
op_drerank = RAD_OP(b, "logit_rerank",
@@ -453,16 +406,16 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_lm));
if (!op_drerank) return RAD_E_INVAL;
/* Arrays and not rw()'s braced lists: the write set is conditional and a braced list
* inside a ternary is a temporary -- rad_fp8.h's NormQuantFP8 records the same. */
/* Arrays rather than rw(): the write set is conditional (see rad_fp8.h:
* NormQuantFP8). */
rad_buf rd[2] = { w.hout, w.didx };
rad_buf wr[3] = { w.didx, w.dval, w.dpair };
rad_op_reads (b, op_drerank, rd, 2);
rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
}
if (dh_shard) {
/* ROW-INTERLEAVED, so one draft row's pairs from every rank land side by side --
* `row_topk_merge` reads one row at one row stride. */
/* Row-interleaved, so one draft row's pairs from every rank are adjacent for
* `row_topk_merge`. */
op_dgather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", g.max_logit_rows * kDraftTopR * 2),
@@ -480,30 +433,47 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
if (!op_dgather || !op_dmerge) return RAD_E_INVAL;
}
if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL;
/* The coupled proposal: one op a round, after the final rerank/merge, over the shortlist
* whose column 0 is the proposal. Linear chains only: x is a token, while a tree reads
* column 0 as a parent index. The engine refuses other drafters; this check keeps a
* mismatched declaration from writing tokens into a tree plane. */
if (w.couple_draws || w.couple_state) {
if (!w.couple_draws || !w.couple_state || depth < 1 ||
depth > RAD_MTP_COUPLE_MAX_ROUNDS || !op_drerank || (g.world > 1 && !op_dmerge))
return RAD_E_UNSUPPORTED;
for (int round = 1; round <= depth; ++round) {
op_couple[round - 1] = rw(b, RAD_OP(b, "mtp_couple_propose",
/* The whole vocabulary: `row_topk` reports global ids and the merge keeps
* them, while `g.n_vocab` is this rank's shard. */
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("round", round), RAD_INT("max_rounds", depth)),
RAD_NOWEIGHTS),
{ w.didx, w.dval, w.couple_draws }, { w.didx, w.couple_state });
if (!op_couple[round - 1]) return RAD_E_INVAL;
}
}
}
/* THE CARRY STAYS LIVE THROUGH THE WHOLE HEAD. A pass writes `hin` for the round after it
* before its mixer and lm_head run; declared as used by the carry alone, the buffer planner
* would let the ops after it take its bytes, and the next round would continue from what they
* wrote. Nothing fails: acceptance falls. Read by the head's last op as well, it survives
* every pass of the step. */
/* Keep the carry `hin` live through the head's last op: it is written before the mixer and
* lm_head run, and the planner could otherwise give its bytes to them (silently lowering
* acceptance). */
{
rad_op last = op_logits;
if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
if (op_couple[0]) last = op_couple[depth - 1];
if (rad_op_reads(b, last, &w.hin, 1) < 0) return RAD_E_INVAL;
}
return RAD_OK;
}
/* One pass of the head. The batch is the one the scheduler built for it: n_tok rows, `token_ids`
* already shifted one position on (sched/batch.cpp, token_at), `positions` the head's own indices,
* and the KV group batch carrying the slot each row writes at -- so every op below runs at n_tok
* rows and the attention layer needs no special case at all. */
/* One pass of the head over the scheduler's batch for it: n_tok rows, `token_ids` already shifted
* one position on (sched/batch.cpp, token_at), `positions` the head's indices, and the KV group
* batch carrying each row's slot, so the attention layer needs no special case. */
inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const int r = batch->draft_pass;
/* The history pass continues from the TRUNK's wide stream; the rounds after it continue from
* the head's, which the carry left in the same buffer. */
/* The history pass continues from the trunk's wide stream; later rounds from the head's,
* which the carry left in the same buffer. */
if (r == 1) {
rad_step_fail(c, "the MTP head was handed a draft-round-1 pass: that round is carried by "
"the history pass (RadBatch::draft_out_ids) and has no pass of its own");
@@ -522,56 +492,57 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE(c, op_enter, brows(w.hin, T), brows(w.e, T), RAD_W(w_pre_h), RAD_W(w_pre_e),
RAD_W(w_fc_h), RAD_W(w_fc_e), brows(w.hw, T));
hc_attn.read(c, T, 0, T);
/* THE INDEXER RUNS FIRST, because the attention reads its selection. It can: this block's
* input is normed and quantised by the connection above, so `w.h` is already what it will be
* when the attention runs. */
qsa.step(c, attn.w.h, batch);
attn.step(c, batch);
hc_attn.read_pieces(c, T);
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave the head's state behind --
* the K and V the attention just stored and the indexer's block keys and tail -- and both are
* written above. Everything below computes the head's stream, which only a drafting row
* reads: the experts, the two connections around them and the lm_head. Every prefill chunk
* but a prompt's last is such a pass, so on those the head costs its attention alone.
* `n_draft_out` is the batch's and the same on every rank, so the collectives skipped here
* are skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) return;
/* A history pass with no drafting rows (every prefill chunk but a prompt's last) only stores
* the head's state: K and V, and the indexer's block keys and tail. `n_draft_out` is the same
* on every rank, so skipped collectives match. */
if (r < 0 && batch->n_draft_out <= 0) {
qsa.store(c, attn.w.h, batch);
attn.store_kv(c, batch);
return;
}
/* The indexer runs first because the attention reads its selection; `w.h` is already final,
* written by the connection above. */
qsa.step(c, attn.w.h, batch, qsa_win_cu);
attn.step(c, batch);
hc_attn.write(c, T, 0, T);
hc_mlp.read(c, T, 0, T);
mlp.step(c, batch);
hc_mlp.write(c, T, 0, T);
/* THE CARRY, and only where a round after this one will read it. The last round of a group
* is followed by a trunk step. A history pass that drafts takes round 1's rows out of its own
* -- into the carry, and back to the front of `hw` for the mixer below. */
int64_t L = T; /* the rows the lm_head runs over */
/* A history pass with drafting rows continues on those rows alone (round 1): they are moved
* to the front of `hw` and the rest of the head runs over them. */
int64_t L = T; /* the rows the stream goes on with */
if (r < 0) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hin, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
} else if (r < depth) {
RAD_ISSUE_N(c, op_carry, T, brows(w.hw, T), brows(w.hin, T));
}
hc_mlp.read_pieces(c, L);
mlp.step_rows(c, L);
hc_mlp.write(c, L, 0, L);
/* The carry, only if a later round reads it: a history pass is round 1, followed by round 2
* when depth > 1; the last round is followed by a trunk step. */
if (r < 0 ? depth > 1 : r < depth)
RAD_ISSUE_N(c, op_carry, L, brows(w.hw, L), brows(w.hin, L));
mixer.read(c, L, 0, L);
if (q2) {
/* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
* whole: there is no row slice of it that means anything. */
/* `dsum` is group-major [n_embd/group][ceil(L/16)*16], so it has no row slice; pass it
* whole. */
RAD_ISSUE_N(c, op_dquant, L, brows(w.hout, L), brows(w.dq, L), brows(w.ds, L),
RAD_B(w.dsum));
/* The trailing `b_ref` is mxfp4's and absent here; an absent optional operand is a null
* tensor in a full-length list, not a shorter list (rad_fp8.h says why). */
/* The trailing `b_ref` is mxfp4's and absent; operands are positional, so pass RAD_NONE
* (rad_fp8.h). */
RAD_ISSUE_N(c, op_dlogits, L, brows(w.dq, L), brows(w.ds, L), RAD_W(w_dh), RAD_W(w_dhs),
brows(w.dlog, L), RAD_B(w.dsum), RAD_NONE);
if (op_dmerge) {
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
brows(w.dpair, L));
/* In place over all three, so the gather and the merge below are unchanged and now
* carry EXACT values instead of the coarse head's. */
/* In place over all three, so the gather and merge carry exact values. */
if (op_drerank)
RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
brows(w.didx, L), brows(w.dval, L), brows(w.dpair, L));
@@ -584,6 +555,19 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
brows(w.didx, L), brows(w.dval, L), RAD_NONE);
}
/* After the final reranked shortlist: column 0 is what ADV_TAKE reads, and a sampled row
* replaces it with its x. Round 1 runs in the history pass (r < 0), later rounds in their
* own passes. */
if (op_couple[0]) {
const int round = r < 0 ? 1 : r;
if (round < 1 || round > depth) {
rad_step_fail(c, "MTP coupled round exceeds the declared draft depth");
return;
}
RAD_ISSUE_N(c, op_couple[round - 1], L, brows(w.didx, L), brows(w.dval, L),
praw(batch->seq_ids, RAD_I32, batch->n_seq),
brows(w.couple_draws, L), RAD_B(w.couple_state));
}
} else {
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
}
+253 -210
View File
@@ -2,10 +2,10 @@
*
* ============================== WHAT IT IS ==============================
*
* ONE layer of the model gets a second embedding table, addressed not by the token but by a HASH of
* the last three. Qwen3.8-Flash-Next's is 320,001,536 rows of 160 -- FOUR FIFTHS OF THE CHECKPOINT,
* 51 of its 125 billion parameters -- read sixteen rows a token and mixed into the residual stream
* by a dot product against the stream itself:
* One layer has a second embedding table addressed by a hash of the last three tokens.
* Qwen3.8-Flash-Next's is 320,001,536 rows of 160 (51 of the checkpoint's 125 billion
* parameters), read sixteen rows per token and mixed into the residual stream by a dot product
* against the stream:
*
* ids = ngram_ids(tokens) [T, 16] a hash of the last 3 ids, per head
* e = embed_lookup_q(ids, table, scale) [T, 2560] 16 x 160, flattened
@@ -15,44 +15,37 @@
* out = ple_conv(gvn, resid = gv, ...) dilated depthwise conv, silu, and the add
* h += out
*
* and it happens BEFORE the attention hyper-connection reads the stream, so `h` here is the wide
* un-normed residual.
* This runs before the attention hyper-connection reads the stream, so `h` is the wide, un-normed
* residual.
*
* ============================== THE TABLE DECIDES THE SHAPE OF ALL OF THIS ======================
* ============================== THE TABLE ==============================
*
* 51.2 GB cannot be staged onto a card, so `embed_lookup_q` reads it where --ngram-placement put
* it: the HOST gather over the container's own mmap or a locked copy in RAM (libavx/avx_ngram.cpp
* carries that argument in full), or a device kernel reading a pinned copy over the link -- or the
* card's own copy, on a card that holds it. Either way its result reaches the card through the
* host arena, 5 KB a token at decode. Three consequences reach this file:
* The 51.2 GB table cannot be staged onto a card, so `embed_lookup_q` reads it where
* --ngram-placement put it: a host gather over the container's mmap or a locked RAM copy
* (libavx/avx_ngram.cpp), a device kernel reading a pinned copy over the link, or a card's own
* copy. The result reaches the card through the host arena, 5 KB per token at decode. Hence:
*
* THE TABLE IS A WEIGHT OPERAND, because the planner puts an op on the host only when every
* weight operand of it is Site::Host, and decides that from the table's placement. A gather
* whose source were an activation could never be placed there.
* The table is a weight operand: the planner places an op on the host only when all its weight
* operands are Site::Host, judged from the table's placement.
*
* ITS BUFFERS ARE HOST DOMAIN. `ids` and `e` are read and written by the host gather when it
* runs, so they live in the host arena, which a device gather reads and writes over the link
* just as well; everything downstream of `e` is ordinary device work.
* `ids` and `e` are host-domain buffers, written and read by the host gather; a device gather
* accesses them over the link. Everything downstream of `e` is device work.
*
* IT IS 128 CHECKPOINT TENSORS. RadNameMap holds eight sources, so the map is declared in pieces
* by map_concat_shards() and the order IS the concatenation -- a permuted table is a model that
* loads, runs, and looks up the wrong embeddings.
* It is 128 checkpoint tensors, mapped in pieces by map_concat_shards(); the order is the
* concatenation, and a permuted table silently looks up wrong rows.
*
* ============================== TWO STATES, ONE CONTRACT ==============================
* ============================== THE TWO ROLLING WINDOWS ==============================
*
* The n-gram hash needs the two committed ids in front of the step, and the convolution needs nine
* timesteps of its input. Both are RAD_KV_CONV rolling windows read at `num_accepted - 1`. They
* differ in ONE thing: the token window's cold value is EOS and the convolution's is zero, because
* zero is a real token id. `has_init` says which slots are cold and both ops read it.
* The n-gram hash needs the two committed ids before the step, and the convolution nine timesteps
* of its input. Both are RAD_KV_CONV windows read at `num_accepted - 1`. The token window's cold
* value is EOS, the convolution's zero (zero is a real token id); `has_init` marks cold slots.
*
* WHAT A STEP LEAVES IN THE WINDOW DEPENDS ON WHAT KIND OF STEP IT WAS, and the op learns that
* from whether `num_accepted` is passed (libref/ref_ple.cpp). A decode row may have its drafts
* rejected, so its window is left in gdn_conv_update's shifted layout, where the next step's read
* offset picks out the history ending at the last token kept. A prefill chunk commits everything,
* so its window is its tail at offset zero, which the scheduler's `num_accepted` of 1 for the next
* step reads. One layout cannot serve both: at offset zero the first holds the history ending at
* the step's FIRST token and the second the history ending at its LAST. So step() issues both ops
* once per half of the batch, the way rad_block_gdn_fp8.h issues its two convolutions.
* What a step leaves in the window depends on the step, signalled by whether `num_accepted` is
* passed (libref/ref_ple.cpp). A decode row may have drafts rejected, so its window uses
* gdn_conv_update's shifted layout, where the next read offset selects the history ending at the
* last kept token. A prefill chunk commits everything and leaves its tail at offset zero, read by
* the next step's `num_accepted` of 1. One layout cannot serve both, so step() issues both ops
* once per half of the batch, as rad_block_gdn_fp8.h does.
*/
#ifndef RAD_BLOCK_PLE_H
#define RAD_BLOCK_PLE_H
@@ -79,7 +72,7 @@ struct PleLayer {
};
struct Wire {
rad_buf h = 0; /* [max_tok, hc * n_embd] THE WIDE STREAM, read and added into */
rad_buf h = 0; /* [max_tok, hc * n_embd] the wide stream, read and added into */
};
struct Src {
@@ -103,27 +96,53 @@ struct PleLayer {
int layer_ = 0;
rad_weight w_table = 0, w_scale = 0, w_mult = 0, w_vsz = 0, w_off = 0;
/* The table as the checkpoint ships it -- plain bf16, no scale weight -- rather than E4M3. */
/* The table is plain bf16 as shipped (no scale weight) rather than E4M3. */
bool table_bf16 = false;
rad_weight w_key = 0, w_value = 0, w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
rad_weight w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
/* The two projections of the gathered embedding, each in the encoding its container stores:
* plain bf16 as the checkpoint ships them, or rotated int8 (or a narrower rotated form), which
* halves the bytes a pass waits for once the rows are on the card. `a_embd` is their input and
* `a_fed` the same planes for the second projection, whose codes the first one's quantiser
* wrote. */
LinearFP8 key{}, value{};
ActFP8 a_embd{}, a_fed{};
rad_kvgroup kv_tok = 0, kv_conv = 0;
rad_buf b_ids = 0, b_emb = 0, b_embd = 0, b_k = 0, b_v = 0, b_gv = 0, b_gvn = 0, b_out = 0;
rad_op op_ids = 0, op_gather = 0, op_embd = 0, op_key = 0, op_value = 0;
rad_op op_ids = 0, op_gather = 0, op_embd = 0;
rad_op op_gate = 0, op_conv = 0, op_add = 0;
/* The draft passes' hint (hint_ids, hint_fetch), where a drafter and `ngram_hint` exist: the
* per-slot tails the hash continues from, the hinted ids (host domain, as `ple_ids`) and the
* rows fetched for them, which nothing reads. */
rad_buf b_tail = 0, b_hint_ids = 0, b_hint_emb = 0;
rad_op op_hint_hist = 0, op_hint_round = 0, op_hint_gather = 0;
int64_t hn() const { return c.hc * g.n_embd; }
/* The read-ahead queue's depth in steps: batch.cpp's k_ahead_chunks steps of the following
* prompt, whose rows the gather's reader thread prefetches. Clamped to what `b_ids` holds, so
* a larger offer only shortens the queue. */
static constexpr int64_t kAheadChunks = 2;
/* The prompt that follows the step, bounded by what `b_ids` holds after the step's rows. */
int64_t ahead_rows(const RadBatch* batch) const {
const int64_t a = batch->n_ahead;
return a <= 0 ? 0 : (a < g.max_tok ? a : g.max_tok);
if (a <= 0) return 0;
const int64_t cap = kAheadChunks * g.max_tok;
return a < cap ? a : cap;
}
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg, int layer,
const Wire& wire, const Src& src);
/* The hash, issued at the TOP of the step; the rest, at the layer. See step(). */
/* The hash, issued at the top of the step; the rest at the layer (see ids()). */
void ids(RadCtx* c_, const RadBatch* batch) const;
void step(RadCtx* c_, const RadBatch* batch) const;
/* On a draft head's pass: the ids of each sequence's newest token, first in the pass, and
* the fetch of their rows, last in it (see hint_ids()). */
void hint_ids(RadCtx* c_, const RadBatch* batch) const;
void hint_fetch(RadCtx* c_, const RadBatch* batch) const;
bool hints(const RadBatch* batch) const {
return op_hint_gather != 0 &&
(batch->draft_pass > 1 || (batch->draft_pass < 0 && batch->n_draft_out > 0));
}
};
inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg,
@@ -140,7 +159,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
return RAD_E_INVAL;
}
/* `heads` is `ngram - 1` equal blocks, one per n-gram order, and `embed_dim` splits evenly
* across them. Both are the reference's own constructor checks. */
* across heads (the reference's constructor checks). */
if (c.heads % (c.ngram - 1) || c.embed_dim % c.heads) {
fprintf(stderr, "radiance: ple: %lld heads over %lld n-gram orders, %lld embed dims -- "
"neither divides\n", (long long)c.heads, (long long)(c.ngram - 1),
@@ -151,69 +170,42 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
if (!src.shard_prefix || !src.shard_suffix || !src.mult || !src.vocab_sizes ||
!src.offsets || !src.key_proj || !src.value_proj || !src.norm_key || !src.norm_query ||
!src.norm_conv || !src.conv1d) return RAD_E_INVAL;
/* ============================== THE WHOLE LAYER IS REPLICATED UNDER TP ==============================
/* ============================== REPLICATED UNDER TP ==============================
*
* Replication is the RIGHT answer here, not a gap: sharding would be the mistake.
* The whole layer is replicated and has no collective. The table is addressed by a token hash
* every rank computes identically, so a vocabulary shard is useless; and it is Tier::Mapped,
* so all ranks gather through one shared row cache over the same file.
*
* THE TABLE IS ADDRESSED BY A HASH OF THE TOKENS, which every rank computes identically, so a
* vocabulary shard would give each rank rows it can never be asked for. And it costs NOTHING
* to replicate: it is Tier::Mapped, read from the container's own file, so both ranks point at
* the same table on the same machine and gather through one row cache they share.
* The rest is 63 MiB per rank (key_proj 50, value_proj 12.5, three norm gains, a conv weight).
* Column-sharding the projections would shard `gv` and `gvn` across the hyper-connection
* streams and need an all-gather per step to save 31 MiB per card. Every rank adds the same
* `out` into an identical copy of the stream, so the result stays bit-identical across ranks.
*
* WHAT IS LEFT IS 63 MiB A RANK -- key_proj 50, value_proj 12.5, three norm gains and a conv
* weight -- against the 112 GiB of experts TP exists to split here. Column-sharding the
* projections would shard `gv` and `gvn` across the hyper-connection streams, and then the
* convolution and the residual add would need the full width back: an all-gather a step, to
* save 31 MiB a card. Geom::n_embd is "the residual stream, replicated on every rank", and
* this layer reads and writes exactly that.
*
* SO EVERY RANK RUNS THE WHOLE LAYER AND THERE IS NO COLLECTIVE IN IT. Both ranks see the same
* token ids, hash them the same way, gather the same rows and add the same `out` into their
* own copy of a stream that was already identical -- bit for bit, because the all-reduce that
* produced it delivers the same sum to both. The duplicated work is two small GEMMs and one
* host gather per rank.
*
* ---- AND THAT LAST SENTENCE IS TRUE AT DECODE AND EXPENSIVE AT PREFILL ---------------------
*
* The duplicated gather is `heads` rows a TOKEN, so what is sixteen rows at a decode step is
* sixteen thousand at a 1024-token chunk and thirty-two thousand at a 2048 one. A gather that
* reads the table through the mapping costs each rank about 70 ms at a 2048-token chunk --
* about 7.6% of a prefill step each. The RANKS ARE THREADS IN ONE PROCESS, so the page faults
* are shared, but each rank still walks every row, and the step waits for both.
*
* THAT COST IS PAGE-TABLE POPULATION, NOT I/O. The distinct rows a prefill wants land on
* distinct 4 KiB pages -- about ONE USEFUL ROW A PAGE, where a page holds 25 of them -- so a
* gather through the mapping pays a fault per row. At decode, with varied text, it is the
* other way round: half of every step's rows are new, and the page cache makes the waiting
* thread start each of those reads itself. So the kernel keeps the rows in a cache of its own
* and reads a miss straight from the file (libavx/avx_ngram.cpp).
*
* AND THAT CACHE SPLITS THE COLD WORK WITHOUT A COLLECTIVE. Dividing the rows between ranks,
* or having one rank gather for both, would need a cross-rank HOST barrier inside a block that
* deliberately has no collective in it. The shared cache does not: each rank claims the misses
* it reaches first, reads only those, and waits only for rows the other rank has already
* claimed -- so a miss is read once, and a late rank finds the rows there. What each rank still
* does alone is decode the rows into its own output, which is a table lookup a byte. A
* vocabulary shard is still wrong for the reason given above.
* The duplicated gather is `heads` rows per token: 16 at decode, 32768 at a 2048-token chunk,
* about 70 ms per rank through the mapping (7.6% of a prefill step). That cost is page-table
* population, not I/O: a prefill's distinct rows land about one per 4 KiB page (of 25), so the
* mapping pays a fault per row. At decode half of each step's rows are new and the page cache
* makes the waiting thread start each read. So the kernel keeps its own row cache and reads
* misses straight from the file (libavx/avx_ngram.cpp). Ranks share that cache: each claims
* and reads the misses it reaches first and waits only for rows another rank has claimed, so
* each miss is read once without a cross-rank barrier.
*/
const int64_t HN = hn();
const int64_t HD = c.head_dim();
/* ---- the table, its scale, and the three hash constants -------------------------------- */
/* E4M3 with ONE scale for all 320 million rows -- Qwen3.8-Flash-Next-FP8's own choice, and the
* table's statistics say why that works: E4M3 carries its own exponent, a row's dynamic range
* is 2.3x, and the scale sits on a three-octave plateau. ONE STORED WEIGHT, `fp8_e4m3*bf16[*x*]`
* -- its codes and a one-element scale plane, made by the recipe from the dense checkpoint
* (data/recipes/qwen4exp-w4.recipe) -- and the gather takes the two planes as two operands.
* The shards are joined along rows by the name map, declared first because it is how the
* model is asked what the table is. RAD_ACCESS_VOCAB because it IS a vocabulary table, just
* not the token one. */
/* E4M3 with one scale for all 320 million rows (Qwen3.8-Flash-Next-FP8's choice; E4M3 has its
* own exponent, a row's dynamic range is 2.3x, and the scale sits on a three-octave plateau).
* One stored weight, `fp8_e4m3*bf16[*x*]`: codes plus a one-element scale plane, made by the
* recipe (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe) or read as that release ships it (its shards under
* one `weight_scale`); the gather takes them as two operands. The name map
* joins the shards along rows and is declared first, since the encoding is looked up through
* it. RAD_ACCESS_VOCAB: it is a vocabulary table, just not the token one. */
const char* tn = nm.f("blk.%d.ple_ngram.weight", layer);
RAD_ARCH_TRY(map_concat_shards(b, tn, src.shard_prefix, src.shard_suffix, (int)c.shards, 0));
/* OR THE CHECKPOINT'S OWN bf16 TABLE, 102 GB, when the container holds it as it ships: the
* same op with no scale (embed_lookup_q's absent scale is one), so it stays a host gather over
* the mapping like the E4M3 one -- the gather's row cache serves either row size. */
/* Or the checkpoint's own bf16 table (102 GB) when the container holds it as shipped: the same
* op with no scale (an absent scale means 1), still a host gather over the mapping. */
RadEncoding te{};
table_bf16 = weight_enc(b, tn, &te) && rad_enc_is(&te, "plain") && te.n_planes == 1 &&
te.plane[0].dtype == RAD_BF16;
@@ -227,8 +219,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
}
/* I64 AND NOT I32. The multipliers are ~2.4e13 -- the hash's whole point is that a token id
* times one of them fills sixty-three bits -- so narrowing them would change every id. */
/* I64: the multipliers are ~2.4e13 (a token id times one fills 63 bits), so narrowing them
* would change every id. */
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_mult", layer), src.mult));
w_mult = decl_w(b, nm.f("blk.%d.ple_mult", layer), RAD_I64, {c.ngram},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
@@ -240,14 +232,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
/* ---- the projections and the three gains ------------------------------------------------ */
/* BF16 AND NOT fp8: `modules_to_not_convert` in the FP8 checkpoint names both projections, so
* these arrive dense whichever checkpoint is the source. */
/* bf16 as shipped (the FP8 checkpoint's `modules_to_not_convert` names both projections); a
* recipe may store them rotated int8. The name maps come first: the encodings, looked up
* through them, say whether the input needs its int8 pair. They are declared below, with the
* buffers they read and write. */
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_key.weight", layer), src.key_proj));
w_key = decl_w(b, nm.f("blk.%d.ple_key.weight", layer), RAD_BF16, {HN, c.embed_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_value.weight", layer), src.value_proj));
w_value = decl_w(b, nm.f("blk.%d.ple_value.weight", layer), RAD_BF16,
{g.n_embd, c.embed_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_key.weight", layer), src.norm_key));
w_nk = decl_w(b, nm.f("blk.%d.ple_norm_key.weight", layer), RAD_F32, {HN},
@@ -265,19 +255,17 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
w_conv = decl_w(b, nm.f("blk.%d.ple_conv.weight", layer), RAD_BF16, {HN, c.conv_width},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off || !w_key || !w_value ||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off ||
!w_nk || !w_nq || !w_nc || !w_conv) return RAD_E_INVAL;
/* ---- the two rolling windows ------------------------------------------------------------ */
/* RAD_KV_CONV is "per-sequence, a rolling window of width-1 + num_spec entries", which is both
* of these. The token window's `conv_width` is ngram, so its window is ngram - 1 + n_spec.
/* RAD_KV_CONV is a per-sequence rolling window of width-1 + num_spec entries. The token
* window's `conv_width` is ngram, so its window is ngram - 1 + n_spec.
*
* THE CHANNEL COUNT IS n_head_kv * head_dim AND NOT state_dim, which is the one field pair a
* reader of RadKVGroupDecl gets wrong: `state_dim` is RAD_KV_LINEAR's per-head geometry and
* the CONV kind never looks at it. Declared into state_dim, both of these size to zero bytes a
* sequence and the KV manager refuses the model at bring-up -- which is the good outcome, but
* rad-kbench cannot find it: it synthesises the state operand from the op's own shape function
* and never asks the manager for one. */
* The channel count is n_head_kv * head_dim, not `state_dim` (RAD_KV_LINEAR's per-head
* geometry, ignored by the CONV kind). Set via state_dim, both groups would size to zero and
* the KV manager would refuse the model; rad-kbench would not catch it, since it synthesises
* the state operand from the op's shape function. */
{
RadKVGroupDecl td{};
td.kind = RAD_KV_CONV;
@@ -290,10 +278,9 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RadKVGroupDecl cd{};
cd.kind = RAD_KV_CONV;
cd.dtype = g.act_dtype;
/* The conv's history is (width-1)*dilation deep, so the GROUP's width -- which the manager
* reads as "window = conv_width - 1 + n_spec" -- is that plus one. Passing the raw
* conv_width here would size the window for an undilated convolution and the deepest tap
* would read a value that was never written. */
/* The conv's history is (width-1)*dilation deep, so the group's width (window =
* conv_width - 1 + n_spec) is that plus one; the raw conv_width would size an undilated
* window and the deepest tap would read unwritten data. */
cd.conv_width = c.hist() + 1;
cd.n_head_kv = 1;
cd.head_dim = HN; /* [n_states, hc*n_embd, hist + n_spec] */
@@ -304,49 +291,39 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_ARCH_TRY(rad_bind_layer_kv(b, layer, kv_conv));
/* ---- buffers ---------------------------------------------------------------------------- */
/* HOST DOMAIN for the two the gather touches. `ids` is written by ngram_ids and read by the
* gather; `e` is written by the gather and read by one device copy onto the card
* (`ple_emb_dev`, below). The host arena is mapped, so the device side of that hand-off is a
* link read (core/runtime/ctx.cpp) -- 5 KB a token at decode. Where a device kernel gathers
* (--ngram-placement ram or vram, with libr4d loaded) it reads `ids` and writes `e` over the
* link too, which costs a round trip of those 5 KB and leaves no host op in the step: the
* domain is declared here, before the placement that would say who gathers is decided.
/* The two buffers the gather touches are host domain. `ids` is written by ngram_ids and read by
* the gather; `e` is written by the gather and copied onto the card (`ple_emb_dev`). The host
* arena is mapped, so the device reads it over the link (core/runtime/ctx.cpp), 5 KB per token
* at decode. A device gather (--ngram-placement ram or vram, with libr4d) reads `ids` and
* writes `e` over the link too; the domain is fixed here, before placement decides who gathers.
*
* `ids` IS PERSIST because it is written at the top of the step and read at this layer: the
* buffer plan computes liveness in DECLARED order, where the two ops are neighbours, and a
* transient would lend its bytes to anything issued in between. */
* `ids` is PERSIST: it is written at the top of the step and read at this layer, but liveness
* follows declared order, where the two ops are adjacent, so a transient could be overwritten
* in between. */
{
/* TWICE THE STEP'S ROWS: the step's own ids, then the ids of the prompt that follows it
* (RadBatch::n_ahead), which the gather hands to its reader to fetch while the step runs. */
/* The step's rows, then kAheadChunks further steps of the following prompt
* (RadBatch::n_ahead) for the reader to prefetch. */
RadBufDecl d{};
d.dtype = RAD_I32; d.rank = 2; d.shape[0] = 2 * g.max_tok; d.shape[1] = c.heads;
d.dtype = RAD_I32; d.rank = 2;
d.shape[0] = (1 + kAheadChunks) * g.max_tok; d.shape[1] = c.heads;
d.kind = RAD_BUF_PERSIST; d.domain = RAD_DOMAIN_HOST;
b_ids = rad_decl_buffer(b, nm.f("ple_ids"), &d);
/* [max_tok, embed_dim] AND NOT [max_tok * heads, head_dim], because ONE declared shape has
* to serve two readings and only this one does. The gather writes `heads` rows a token and
* the projections read one row a token of `embed_dim` -- the same bytes either way -- and
* the direction that works is decided by HOW EACH KERNEL FINDS ITS ROW COUNT.
*
* The gather derives it: r4d_rows_pitch(x, n_embd) is numel / the width the kernel asks
* for, so [T, 2560] read at 160 IS T*16 rows of 160. The GEMM does not: gemm_ops takes
* M = a->shape[0] and K = a->shape[1] straight off the operand, because a strided rank-3
* activation has to be refused rather than folded. So the wide shape serves both and the
* tall one serves only the gather: declared tall, the key projection is handed M = T*16,
* K = 160 against a [T, 10240] output and refuses the step. */
/* [max_tok, embed_dim], not [max_tok * heads, head_dim]: one shape must serve the gather
* (`heads` rows per token) and the projections (one `embed_dim` row per token). The gather
* derives its row count as numel / width (r4d_rows_pitch), so [T, 2560] read at 160 is
* T*16 rows. The GEMM takes M and K from the operand's shape (gemm_ops), so the tall shape
* would give it M = T*16, K = 160 and the step would be refused. */
RadBufDecl e{};
e.dtype = g.act_dtype; e.rank = 2;
e.shape[0] = g.max_tok; e.shape[1] = c.embed_dim;
e.kind = RAD_BUF_TRANSIENT; e.domain = RAD_DOMAIN_HOST;
b_emb = rad_decl_buffer(b, nm.f("ple_emb"), &e);
}
/* AND ITS COPY ON THE CARD, which is what the two projections read. `e` in the mapped host
* arena is a link read, and a GEMM does not read its A operand once: the tiled kernel reads
* each row band once a column block, 80 times for the key projection, every one of them a PCIe
* round trip or a hit on the copy that round trip left in the card's cache. At a 2048-token
* chunk the two projections take about 3.0 and 0.9 ms reading the host arena against 1.4 and
* 0.3 ms reading VRAM. One pass of the link into VRAM is 10.5 MB at a chunk and 5 KB a token
* at decode. */
/* The device copy the projections read. A tiled GEMM reads each A row band once per column
* block (80 times for the key projection), so reading `e` from the host arena repeats link
* traffic: at a 2048-token chunk the projections take about 3.0 and 0.9 ms from the host arena
* versus 1.4 and 0.3 ms from VRAM. The copy is 10.5 MB per chunk, 5 KB per token at decode. */
b_embd = decl_b(b, nm.f("ple_emb_dev"), g.act_dtype, {g.max_tok, c.embed_dim});
b_k = decl_b(b, nm.f("ple_k"), g.act_dtype, {g.max_tok, HN});
b_v = decl_b(b, nm.f("ple_v"), g.act_dtype, {g.max_tok, g.n_embd});
@@ -356,12 +333,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
if (!b_ids || !b_emb || !b_embd || !b_k || !b_v || !b_gv || !b_gvn || !b_out)
return RAD_E_INVAL;
/* NO DERIVED BUFFER FOR THE STATE SLOTS, and that is worth saying because the obvious reading
* of the core says otherwise. `conv_state_index` exists, computes exactly the cursor these two
* states want, and is called by NO architecture plugin: rad_block_gdn_fp8.h takes
* `cv->state_index` straight off RadKVGroupBatch, which the step batch fills PER GROUP. This
* block does the same -- one fewer per-step computation, and the same number the working
* precedent uses.
/* State slots come from RadKVGroupBatch::state_index, filled per group by the step batch, as in
* rad_block_gdn_fp8.h; the core's `conv_state_index` is not used.
*
* ---- the ops, in the order step() issues them ------------------------------------------- */
layer_ = layer;
@@ -372,20 +345,58 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_WEIGHTS(w_mult, w_vsz, w_off)),
{}, {b_ids});
/* M IS T * heads HERE, not T: the gather fetches one table row per HEAD per token, and the
* band this op resolves on is that count. */
if (table_bf16)
/* M is T * heads: the gather fetches one table row per head per token, and the band resolves
* on that count. */
{
const rad_weight wt[2] = { w_table, w_scale }; /* a bf16 table has no scale plane */
op_gather = rw(b, RAD_OP(b, "embed_lookup_q",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * c.heads), RAD_INT("n_embd", HD),
RAD_INT("n_vocab", c.rows), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_table)),
wt, table_bf16 ? 1 : 2),
{b_ids}, {b_emb});
else
op_gather = rw(b, RAD_OP(b, "embed_lookup_q",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * c.heads), RAD_INT("n_embd", HD),
RAD_INT("n_vocab", c.rows), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_table, w_scale)),
{b_ids}, {b_emb});
}
/* ---- the draft passes' hint. A verify step's rows are the token the last verify chose and
* the drafter's proposals, each known a draft pass or more before the verify hashes it,
* except the last. Each draft pass hashes its sequences' newest token (`ngram_hint`) and
* gathers those rows through the same row source, which for a table on a drive reads them
* into its row cache; the verify step's gather then waits for the last proposal's rows
* only. All three ops or none: without a drafter, or where no library hashes the hint,
* nothing is declared and the verify step reads every row itself, as before. */
if (g.max_spec > 0 && rad_op_declared(b, "ngram_hint")) {
const int64_t ctx = c.ngram - 1;
b_tail = decl_b(b, nm.f("ple_hint_tail"), RAD_I32, {g.max_seqs, 2 * ctx}, RAD_BUF_PERSIST);
RadBufDecl hi{};
hi.dtype = RAD_I32; hi.rank = 2;
hi.shape[0] = g.max_seqs; hi.shape[1] = c.heads;
hi.kind = RAD_BUF_PERSIST; hi.domain = RAD_DOMAIN_HOST;
b_hint_ids = rad_decl_buffer(b, nm.f("ple_hint_ids"), &hi);
/* PERSIST although nothing reads it: a transient's bytes are shared by declared op
* order, and the fetch runs on the host while the draft pass's other buffers are live. */
RadBufDecl he{};
he.dtype = g.act_dtype; he.rank = 2;
he.shape[0] = g.max_seqs; he.shape[1] = c.embed_dim;
he.kind = RAD_BUF_PERSIST; he.domain = RAD_DOMAIN_HOST;
b_hint_emb = rad_decl_buffer(b, nm.f("ple_hint_emb"), &he);
if (!b_tail || !b_hint_ids || !b_hint_emb) return RAD_E_INVAL;
for (const int hist : { 1, 0 })
(hist ? op_hint_hist : op_hint_round) =
rw(b, RAD_OP(b, "ngram_hint",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("heads", c.heads),
RAD_INT("ngram", c.ngram), RAD_INT("eos", c.eos),
RAD_INT("hist", hist)),
RAD_WEIGHTS(w_mult, w_vsz, w_off)),
{b_tail}, {b_tail, b_hint_ids});
const rad_weight wt[2] = { w_table, w_scale };
op_hint_gather = rw(b, RAD_OP(b, "embed_lookup_q",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs * c.heads),
RAD_INT("n_embd", HD), RAD_INT("n_vocab", c.rows),
RAD_STR("dtype", g.dtype)),
wt, table_bf16 ? 1 : 2),
{b_hint_ids}, {b_hint_emb});
if (!op_hint_hist || !op_hint_round || !op_hint_gather)
op_hint_hist = op_hint_round = op_hint_gather = 0;
}
op_embd = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim),
@@ -393,19 +404,38 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_NOWEIGHTS),
{b_emb}, {b_embd});
op_key = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", HN),
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_key)),
{b_embd}, {b_k});
op_value = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_value)),
{b_embd}, {b_v});
/* The projections. An int8 one reads the embedding's int8 codes at its own scale group; the
* first such quantises the bf16 plane and a second reads those codes, so two int8 projections
* must agree in rotation and group (LinearFP8 refuses the pair otherwise). */
{
const char* kb = nm.f("blk.%d.ple_key", layer);
const char* vb = nm.f("blk.%d.ple_value", layer);
RadEncoding ke{}, ve{};
const bool kk = weight_enc(b, nm.f("%s.weight", kb), &ke);
const bool vk = weight_enc(b, nm.f("%s.weight", vb), &ve);
const bool k8 = !g.w_bf16 && kk && (linear_is_w8(ke) || linear_is_w8h(ke));
const bool v8 = !g.w_bf16 && vk && (linear_is_w8(ve) || linear_is_w8h(ve));
a_embd.x = b_embd;
if (k8 || v8)
RAD_ARCH_TRY(a_embd.declare_qs(b, nm, g, "ple_emb_dev", c.embed_dim, 0, true, false,
linear_w8h_group(k8 ? ke : ve)));
a_fed = a_embd;
if (k8 && v8) {
a_fed.q8_fed = true;
a_fed.q8_rot = linear_is_w8h(ke);
}
key.mapped = value.mapped = true;
/* Anything but an int8 form is the plain bf16 GEMM, in a quantised model too. */
Geom gb = g;
gb.w_bf16 = true;
RAD_ARCH_TRY(key.declare(b, nm, k8 ? g : gb, kb, HN, c.embed_dim, RAD_SHARD_NONE,
grp_model(), { src.key_proj }, a_embd, b_k));
RAD_ARCH_TRY(value.declare(b, nm, v8 ? g : gb, vb, g.n_embd, c.embed_dim, RAD_SHARD_NONE,
grp_model(), { src.value_proj }, a_fed, b_v));
}
/* `q` IS THE INCOMING STREAM ITSELF, un-normed: the op owns all three norms because the third
* is taken over bytes it wrote. */
/* `q` is the incoming stream, un-normed; the op applies all three norms because the third is
* over bytes it writes. */
op_gate = rw(b, RAD_OP(b, "ple_gate",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_F64("eps", g.eps),
@@ -420,41 +450,33 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_WEIGHTS(w_conv)),
{b_gvn, b_gv}, {b_out});
/* AND THE ADD INTO THE STREAM. The reference is `hidden_states = hidden_states + ple(...)`,
* and `ple(...)` is what ple_conv already produced -- the convolution's residual operand
* folded the layer's own `gv + silu(conv)`, so what is left is one add of the whole thing. */
/* The add into the stream: `hidden_states + ple(...)`, where ple_conv's residual operand
* already produced `gv + silu(conv)`. */
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", HN),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h, b_out}, {w.h});
if (!op_ids || !op_gather || !op_embd || !op_key || !op_value || !op_gate || !op_conv ||
if (!op_ids || !op_gather || !op_embd || !key.op || !value.op || !op_gate || !op_conv ||
!op_add)
return RAD_E_INVAL;
return RAD_OK;
}
/* THE SLOTS COME OFF THE GROUP BATCH, per group, exactly as the gated delta net reads them. And
* `has_init` is `ctx_lens`: a sequence with computed tokens behind it has a history, one without
* has none, which is the same test rad_block_gdn_fp8.h makes of the same field.
/* Slots come from the group batch, and `has_init` is `ctx_lens` (nonzero means a history), as in
* rad_block_gdn_fp8.h.
*
* THE TWO WINDOWED OPS ARE ISSUED ONCE PER HALF OF THE STEP. The step is sorted decode-first, so
* the decode rows are sequences [0, D) holding tokens [0, DT) and the prefill chunks are sequences
* [D, S) holding the rest (batch_split). The decode half passes `num_accepted`, which is what
* makes the op leave its window in the layout a partly rejected verify can be read back from; the
* prefill half passes none, so each chunk leaves its tail at offset zero. A pure step issues one
* half, so a pure decode step is one launch and only a mixed step pays a second.
* The two windowed ops are issued once per half of the step (batch_split: decode sequences
* [0, D) with tokens [0, DT) first, then prefill). The decode half passes `num_accepted`, so the
* op leaves its window readable after a partial rejection; the prefill half passes none and leaves
* each chunk's tail at offset zero. The prefill half gets per-sequence arrays at `+ D` with token
* operands at their base (kernels use the absolute offsets in `cu`); the decode half narrows to DT
* rows.
*
* The prefill half is addressed the way the GDN's is: the per-sequence arrays move to `+ D` and
* the token operands stay at their base, because each kernel takes a sequence's rows from the
* ABSOLUTE offsets in `cu`. The decode half is the prefix, so it narrows to DT rows instead. */
/* THE HASH GOES FIRST IN THE STEP, AHEAD OF EVERY LAYER. It reads the batch's token ids and its
* own rolling window and nothing the trunk computes, so it can run as soon as the batch has been
* uploaded. The gather that consumes it runs on the host and has to wait for it; issued here, that
* wait is for one small kernel, and the layers issued between the two keep the device busy while
* the host gathers. Issued at the layer, the wait would be for every layer in front of it, and the
* device would sit idle through the gather. */
* ids() runs first in the step, before every layer: it reads only the token ids and its own
* window. The host gather that consumes it then waits for one small kernel, and the layers issued
* in between keep the device busy during the gather. */
inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const int64_t S = batch->n_seq;
@@ -475,9 +497,9 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
praw(batch->ctx_lens, RAD_I32, D),
praw(batch->num_accepted, RAD_I32, D),
brows(b_ids, DT), RAD_NONE);
/* THE PROMPT THAT FOLLOWS the last prefill chunk is hashed in the same launch, into the rows
* after the step's: `tok` then reaches past the step by that many tokens, and the window the
* op leaves behind is the step's alone. */
/* The prompt following the last prefill chunk is hashed in the same launch into the rows
* after the step's (`tok` reaches A tokens past the step); the window left behind is the
* step's alone. */
const int64_t A = P > 0 ? ahead_rows(batch) : 0;
if (P > 0)
RAD_ISSUE_N(c_, op_ids, T,
@@ -491,10 +513,36 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
}
/* The hint of a draft head's pass. The history pass ends at the token the verify chose and each
* later round reads the proposal before it (RadBatch::draft_pass), so the pass's newest token per
* sequence is one the next verify step runs. hint_ids() hashes it first in the pass, so the ids
* are in host memory as the pass starts; hint_fetch() goes last, where the host has issued the
* whole pass and only waits for that one kernel, and the rows it reads arrive while the card
* drafts. A history pass that drafts nothing gets neither. */
inline void PleLayer::hint_ids(RadCtx* c_, const RadBatch* batch) const {
if (!hints(batch)) return;
const int64_t T = batch->n_tok, S = batch->n_seq;
const RadKVGroupBatch* tk = kv_batch(batch, kv_tok);
const int32_t* tk_idx = tk ? tk->state_index : nullptr;
RAD_ISSUE_N(c_, batch->draft_pass < 0 ? op_hint_hist : op_hint_round, S,
praw(batch->token_ids, RAD_I32, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
tk_idx ? praw(tk_idx, RAD_I32, S) : RAD_NONE,
RAD_B(b_tail), brows(b_hint_ids, S));
}
inline void PleLayer::hint_fetch(RadCtx* c_, const RadBatch* batch) const {
if (!hints(batch)) return;
const int64_t S = batch->n_seq;
RAD_ISSUE_N(c_, op_hint_gather, S * c.heads,
brows(b_hint_ids, S), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
brows(b_hint_emb, S), RAD_NONE);
}
inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const int64_t S = batch->n_seq;
const int64_t HD = c.head_dim();
const RadKVGroupBatch* cv = kv_batch(batch, kv_conv);
const int32_t* cv_idx = cv ? cv->state_index : nullptr;
@@ -503,21 +551,18 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
batch_split(batch, &D, &DT);
const int64_t P = S - D;
/* T ROWS, not T * heads: the buffer is [max_tok, embed_dim] and the gather derives its own
* 16-rows-a-token reading out of numel. The op's M band is still T * heads -- that is how many
* table rows it fetches -- but the OPERAND is the token count. */
/* The ids of the prompt that follows, which the gather's reader fetches while this step
* runs, so the next step finds its rows already read. */
/* Operands are T rows (the gather derives its per-head rows from numel); the op's M band is
* T * heads. The trailing operand is the following prompt's ids, which the gather's reader
* prefetches for the next step. */
const int64_t A = P > 0 ? ahead_rows(batch) : 0;
RAD_ISSUE_N(c_, op_gather, T * c.heads,
brows(b_ids, T), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
brows(b_emb, T),
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
(void)HD;
RAD_ISSUE_N(c_, op_embd, T, brows(b_emb, T), brows(b_embd, T));
RAD_ISSUE_N(c_, op_key, T, brows(b_embd, T), RAD_W(w_key), brows(b_k, T));
RAD_ISSUE_N(c_, op_value, T, brows(b_embd, T), RAD_W(w_value), brows(b_v, T));
key.step(c_, a_embd, b_k, T, 0, T);
value.step(c_, a_fed, b_v, T, 0, T);
RAD_ISSUE_N(c_, op_gate, T,
brows(b_k, T), brows(w.h, T), brows(b_v, T),
@@ -541,9 +586,7 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
RAD_NONE,
brows(b_out, T));
/* M IS T, not T * HN. `add` counts ROWS of `n` -- every other block in this tree issues it
* that way -- and the declared band is 1..max_tok. Passing the element count instead lands
* outside every band of the op's own bucket table and the run phase refuses the step. */
/* M is T rows of `n`, not the element count, matching the declared band 1..max_tok. */
RAD_ISSUE_N(c_, op_add, T, brows(w.h, T), brows(b_out, T), brows(w.h, T));
}
File diff suppressed because it is too large. Load diff
+122 -44
View File
@@ -14,19 +14,20 @@
* x += fc2(gelu_tanh(fc1(LN2(x))))
* out = fc2'(gelu(fc1'(LN(x) viewed [P/merge^2, merge^2 * width]))) the patch merger
*
* which is transformers' Qwen3_5VisionModel with no deepstack taps (the checkpoints this tree
* serves list none, and one that did would be refused at declare). Every linear layer is
* `gemm_nt_bias` with its activation and residual in the epilogue, each rounded where the
* reference's separate tensors are.
* which is transformers' Qwen3_5VisionModel. Qwen3-VL's deepstack taps (the residual stream after
* named blocks, each through its own merger whose norm is taken after the 2x2 view, over
* merge^2 * width, added to the language model's hidden state after its first layers) are declared
* only for a plugin that passes `deepstack`; otherwise a tower with taps is refused. Every linear
* is `gemm_nt_bias` with activation and residual in the epilogue, rounded where the reference's
* separate tensors are.
*
* EVERY RANK RUNS THE WHOLE TOWER. Its weights are replicated rather than sharded: the rows are
* needed on every rank (each rank embeds every token), and a tower split across ranks would pay a
* collective per layer to save compute that happens once per picture. The weights are
* Every rank runs the whole tower with replicated weights: every rank embeds every token, and
* sharding would cost a collective per layer for once-per-picture compute. Weights are
* RAD_ACCESS_PER_REQUEST, so placement may keep them off the card when VRAM is short.
*
* ITS ACTIVATIONS ARE SIZED BY THE PASS, not by a step: RadBuildCtx::max_enc_patches rows. A
* sizing declare (shape_probe) sizes them by the probe's step instead, which keeps the tower out
* of the smaller arena levels -- an encoder pass always runs at the full plan (Engine::arena_step).
* Activations are sized by the pass (RadBuildCtx::max_enc_patches rows), except in a sizing
* declare (shape_probe), which uses the probe's step to keep the tower out of the smaller arena
* levels; an encoder pass always runs at the full plan (Engine::arena_step).
*/
#ifndef RAD_BLOCK_VIT_H
#define RAD_BLOCK_VIT_H
@@ -35,6 +36,7 @@
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
@@ -61,22 +63,48 @@ struct VisionTower {
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_mh = 0, b_mf = 0, b_out = 0;
char sec[48] = {};
/* Is there a tower to declare: the container carries one and the deployment asked for media.
* `why` is set when the container carries one this block cannot serve. */
/* Deepstack: tap t is the residual stream after block `ds_layer[t]`, merged into `b_ds[t]`
* ([P / merge^2, n_embd], one row per merged token, in `b_out`'s order). */
enum { MAX_DS = 4 };
int n_ds = 0;
int ds_layer[MAX_DS] = {};
rad_weight ds_nw[MAX_DS] = {}, ds_nb[MAX_DS] = {}, ds_1w[MAX_DS] = {}, ds_1b[MAX_DS] = {};
rad_weight ds_2w[MAX_DS] = {}, ds_2b[MAX_DS] = {};
rad_op ds_ln[MAX_DS] = {}, ds_1[MAX_DS] = {}, ds_2[MAX_DS] = {};
rad_buf b_ds[MAX_DS] = {};
/* Whether the container carries a vision tower. */
static bool present(const RadModelMeta* m) {
return rad_meta_geti(m, "vision_config.depth", 0) > 0;
}
/* With `gate_weights`, a checkpoint or container without the tower's weights declares nothing
* and leaves `on` false, for a model whose config names a tower its weights may not have. */
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group);
int64_t model_embd, int first_group, bool deepstack = false,
bool gate_weights = false);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
Names& nm, int64_t model_embd, int first_group) {
Names& nm, int64_t model_embd, int first_group, bool deepstack,
bool gate_weights) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
/* Whether the stem is there: its map first, then its encoding, which convert answers from the
* checkpoint and load from the container alike. A map left behind is inert. */
if (gate_weights) {
if (map_copy(b, nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight")) < 0)
return RAD_E_INVAL;
RadEncoding enc;
if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) {
std::fprintf(stderr, "radiance: vision_config names a tower the checkpoint does not "
"ship; declaring without it\n");
return RAD_OK;
}
}
depth = rad_meta_geti(m, "vision_config.depth", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_heads", 0);
@@ -98,21 +126,33 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
(long long)ff, (long long)patch, (long long)merge, (long long)npos);
return RAD_E_INVAL;
}
/* THE MERGER WRITES ROWS OF THE MODEL'S OWN WIDTH, or its rows could not replace a token's. */
/* The merger's rows replace token embeddings, so they must be the model's width. */
if (n_embd != model_embd) {
fprintf(stderr, "radiance: the vision tower emits %lld-wide rows and the model embeds "
"%lld-wide tokens\n", (long long)n_embd, (long long)model_embd);
return RAD_E_INVAL;
}
/* DEEPSTACK -- tower layers feeding the language model's early layers directly -- is a second
* input path this block does not carry. Refused by name rather than dropped. */
/* Deepstack feeds tower layers into the language model's early layers; a plugin that does not
* consume it is refused the tower. */
const char* ds = rad_meta_gets(m, "vision_config.deepstack_visual_indexes", "");
for (const char* q = ds; q && *q; ++q)
if (*q >= '0' && *q <= '9') {
n_ds = 0;
for (const char* q = ds; q && *q;) {
if (*q < '0' || *q > '9') { ++q; continue; }
char* e = nullptr;
const long v = std::strtol(q, &e, 10);
q = e;
if (!deepstack) {
fprintf(stderr, "radiance: this vision tower has deepstack taps (%s), which this plugin "
"does not serve\n", ds);
return RAD_E_UNSUPPORTED;
}
if (n_ds >= MAX_DS || v < 0 || v >= depth) {
fprintf(stderr, "radiance: deepstack taps '%s' do not fit a %lld-block tower\n", ds,
(long long)depth);
return RAD_E_INVAL;
}
ds_layer[n_ds++] = (int)v;
}
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu_pytorch_tanh");
if (std::strcmp(act, "gelu_pytorch_tanh") && std::strcmp(act, "gelu")) {
fprintf(stderr, "radiance: vision_config.hidden_act '%s' is not served\n", act);
@@ -127,13 +167,13 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
const int64_t mm = merge * merge;
P = ctx->max_enc_patches;
/* The longest segment attention may see: the REAL pass size in a sizing declare too. It is a
* fixed parameter the kernel is chosen by, and the engine runs the real declare's kernel at
* every level; only the ranged row counts may follow the probe's step. */
/* The longest segment attention may see: the real pass size, even in a sizing declare. It
* selects the kernel, and the engine runs the real declare's kernel at every level; only the
* ranged row counts may follow the probe's step. */
const int64_t max_seg = P;
if (ctx->shape_probe) {
/* A sizing declare: the tower's rows follow the probe's step, which keeps its activations
* out of the levels a decode step runs at. Rounded to a whole merged row. */
/* A sizing declare: rows follow the probe's step (rounded to whole merged rows), keeping
* the activations out of the levels a decode step runs at. */
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
P = std::max<int64_t>(mm, r / mm * mm);
}
@@ -141,17 +181,21 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
const int64_t R = P / mm;
const int ACC = RAD_ACCESS_PER_REQUEST;
/* ---- weights. Replicated; model-level groups for the stem and the merger, and one group a
* block from `first_group` on, past every language layer, so a tower block is its own unit
* of movement and never shares one with a text layer. */
/* ---- weights, replicated. Model-level groups for the stem and merger; one group per block
* from `first_group` on (past every language layer), so a tower block is its own movement
* unit. */
auto bw = [&](const char* dn, const char* src, uint32_t dt, std::initializer_list<int64_t> shp,
RadWeightGroup g) -> rad_weight {
/* the map first: it is how the checkpoint is asked what the weight is */
/* map first: the weight's encoding is looked up through it */
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, g);
};
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
RAD_BF16, { width, patch_dim }, grp_model());
/* Mapped above with `gate_weights`. */
w_patch = gate_weights
? decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim },
RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_model())
: bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
RAD_BF16, { width, patch_dim }, grp_model());
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("model.visual.patch_embed.proj.bias"),
RAD_BF16, { width }, grp_model());
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("model.visual.pos_embed.weight"),
@@ -182,10 +226,21 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
m2_b = bw(nm.f("v.merger.fc2.bias"), nm.ckpt("model.visual.merger.linear_fc2.bias"), RAD_BF16, { n_embd }, grp_model());
if (!w_patch || !b_patch || !w_pos || !mn_w || !mn_b || !m1_w || !m1_b || !m2_w || !m2_b)
return RAD_E_INVAL;
for (int t = 0; t < n_ds; ++t) {
const char* pre = "model.visual.deepstack_merger_list";
ds_nw[t] = bw(nm.f("v.ds.%d.norm.weight", t), nm.ckpt("%s.%d.norm.weight", pre, t), RAD_BF16, { mm * width }, grp_model());
ds_nb[t] = bw(nm.f("v.ds.%d.norm.bias", t), nm.ckpt("%s.%d.norm.bias", pre, t), RAD_BF16, { mm * width }, grp_model());
ds_1w[t] = bw(nm.f("v.ds.%d.fc1.weight", t), nm.ckpt("%s.%d.linear_fc1.weight", pre, t), RAD_BF16, { mm * width, mm * width }, grp_model());
ds_1b[t] = bw(nm.f("v.ds.%d.fc1.bias", t), nm.ckpt("%s.%d.linear_fc1.bias", pre, t), RAD_BF16, { mm * width }, grp_model());
ds_2w[t] = bw(nm.f("v.ds.%d.fc2.weight", t), nm.ckpt("%s.%d.linear_fc2.weight", pre, t), RAD_BF16, { n_embd, mm * width }, grp_model());
ds_2b[t] = bw(nm.f("v.ds.%d.fc2.bias", t), nm.ckpt("%s.%d.linear_fc2.bias", pre, t), RAD_BF16, { n_embd }, grp_model());
if (!ds_nw[t] || !ds_nb[t] || !ds_1w[t] || !ds_1b[t] || !ds_2w[t] || !ds_2b[t])
return RAD_E_INVAL;
}
/* ---- activations. `mh` is the merger's input, declared at the MERGED width: the norm writes
* it as P rows of `width` and the first merger layer reads it as P/mm rows of mm * width,
* which is the same bytes -- the reference's view(), with no copy. */
/* ---- activations. `mh`, the merger's input, is declared at the merged width: the norm writes
* P rows of `width` and the first merger layer reads the same bytes as P/mm rows of
* mm * width (the reference's view(), no copy). */
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
@@ -244,6 +299,21 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
op_mln = rw(b, lnorm(P, mn_w, mn_b), { b_x }, { b_mh });
op_m1 = rw(b, gemm(R, mm * width, mm * width, "gelu", m1_w, m1_b), { b_mh }, { b_mf });
op_m2 = rw(b, gemm(R, n_embd, mm * width, "none", m2_w, m2_b), { b_mf }, { b_out });
/* A deepstack merger normalises after the view, over R rows of merge^2 * width. Its ops are
* declared after the tower and issued between blocks; their working planes are consumed before
* the next block. Each tap's output must survive until the language model reads it, so it is
* PERSIST. */
for (int t = 0; t < n_ds; ++t) {
b_ds[t] = decl_b(b, nm.f("v.ds.%d.out", t), RAD_BF16, { R, n_embd }, RAD_BUF_PERSIST);
if (!b_ds[t]) return RAD_E_INVAL;
ds_ln[t] = rw(b, RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", mm * width),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(ds_nw[t], ds_nb[t])),
{ b_x }, { b_mh });
ds_1[t] = rw(b, gemm(R, mm * width, mm * width, "gelu", ds_1w[t], ds_1b[t]), { b_mh }, { b_mf });
ds_2[t] = rw(b, gemm(R, n_embd, mm * width, "none", ds_2w[t], ds_2b[t]), { b_mf }, { b_ds[t] });
}
if (!ctx->shape_probe) {
RadEncoderDecl e{};
@@ -273,8 +343,8 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const {
"more patches than it was declared for, or not whole merged rows");
return;
}
/* The patches, their coordinates -- planes 0 and 1 are a dense [2, P] (row, column), all four
* a dense [4, P] -- and the segment boundaries, all staged by the core. */
/* Patches, coordinates (planes 0-1 a dense [2, P] of (row, column); all four a dense [4, P])
* and segment boundaries, staged by the core. */
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand rc = praw2(batch->enc_coord, RAD_I32, 2, Pn);
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
@@ -282,7 +352,8 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
for (const Layer& l : L) {
for (size_t li = 0; li < L.size(); ++li) {
const Layer& l = L[li];
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
brows(b_qkv, Pn));
@@ -297,9 +368,17 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const {
brows(b_ff, Pn));
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
brows(b_x, Pn), brows(b_x, Pn));
for (int t = 0; t < n_ds; ++t) {
if (ds_layer[t] != (int)li) continue;
RAD_ISSUE_N(c, ds_ln[t], Rn, brows(b_x, Pn), RAD_W(ds_nw[t]), RAD_W(ds_nb[t]),
brows(b_mh, Rn));
RAD_ISSUE_N(c, ds_1[t], Rn, brows(b_mh, Rn), RAD_W(ds_1w[t]), RAD_W(ds_1b[t]), RAD_NONE,
brows(b_mf, Rn));
RAD_ISSUE_N(c, ds_2[t], Rn, brows(b_mf, Rn), RAD_W(ds_2w[t]), RAD_W(ds_2b[t]), RAD_NONE,
brows(b_ds[t], Rn));
}
}
/* The merger norm writes P rows of `width` into a buffer declared at the merged width: the
* same bytes the next layer reads as P/mm rows. */
/* The merger norm writes P rows of `width`; the next layer reads them as P/mm merged rows. */
RAD_ISSUE_N(c, op_mln, Pn, brows(b_x, Pn), RAD_W(mn_w), RAD_W(mn_b), brows(b_mh, Rn));
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(m1_w), RAD_W(m1_b), RAD_NONE,
brows(b_mf, Rn));
@@ -309,13 +388,12 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const {
/* ================================================================== the encoder rows
*
* THE ROWS AN ENCODER PRODUCED, OVER THE TOKEN EMBEDDINGS THEY REPLACE (RadBatch::mm_rows). One
* `scatter_rows` over opaque bytes: a row is `n_embd` bf16, the destination the embedding buffer.
* Scatters encoder rows over the token embeddings they replace (RadBatch::mm_rows): one
* `scatter_rows` of `n_embd` bf16 rows into the embedding buffer.
*
* ISSUE IT BEFORE THE EMBEDDING'S REDUCTION. The lookup is vocab-sharded, so each rank's output is
* a partial sum, and the core hands rank 0 the encoder rows and every other rank zeros: overwritten
* there, the reduction that follows -- an all_reduce, or the first layer's fused norm -- counts
* each row once, as it counts a token's embedding once. */
* Issue it before the embedding's reduction. The lookup is vocab-sharded, so each rank holds a
* partial sum; the core gives rank 0 the encoder rows and other ranks zeros, so the following
* reduction (an all_reduce, or the first layer's fused norm) counts each row once. */
struct MediaRows {
rad_op op = 0;
int64_t n_embd = 0;
+374
View File
@@ -0,0 +1,374 @@
/* rad_calib_full.h -- the whole Hessian of each linear's input in a dense bf16 trunk, under tensor
* parallelism, recorded over a --calib-corpus run into --calib-dir (RadBuildCtx::calib_*).
*
* GPTQ needs H = sum over tokens of x x^T for the whole input x of a linear. A linear split by its
* input columns across ranks (o_proj, the delta net's out_proj, down_proj) sees only its rank's
* columns, and a Gram of those is one diagonal block of H: the products across ranks are never
* formed on any card. So each such input is gathered to its whole width first (`all_gather`,
* row-interleaved: rank r's columns land at r * width / world), and the Gram is taken of the whole
* row. An input every rank holds whole (a norm's output) is read where it is.
*
* One rank records each layer (layer % world), so the Gram work and the host memory split
* evenly. Its f32 scratch receives one step's sum for one input (`gram_accum` with `upper` 1: H is
* symmetric and only k2 >= k1 is kept), whose upper triangle is copied to a pinned square and which
* is zeroed for the next input, all in stream order. A worker thread waits on the copy's event and adds the square to a
* host accumulator holding the upper triangle packed row by row (k(k+1)/2 f32), while the rank goes
* on issuing the step: two squares alternate, so the rank waits only when the adds fall two Grams
* behind. Syncing and adding on the rank's own thread instead left the card idle for every add, 16
* of 1.2 GB a step on each rank of Qwen3.8-27B, and the ranks wait on each other at every
* all-reduce. The host holds every recorded input of the rank: 786 MB a layer at Qwen3.8-27B,
* which is what --calib-layers bounds. A step's sum is f32 over at most a step's
* rows, and the host adds a few thousand of them; the consumer damps H by a percent of its trace,
* far above that rounding.
*
* Files, written once the plugin has seen RadBuildCtx::calib_tokens rows (the whole corpus): one
* safetensors file per input, <dir>/<stem>.safetensors, holding `hessian_upper`, f32
* [k * (k + 1) / 2], row i's entries k2 = i .. k-1 after row i-1's, and metadata naming `k`, the
* rows summed and the checkpoint linears that read the input. H is the raw sum; divide by `rows`
* for the mean second moment.
*
* An int8 trunk (site_i8, one rank only) is recorded from the codes and scales its GEMMs actually
* read, so H includes what the model's own quantisation did to the input -- the input a quantised
* model feeds each layer, for GPTQ against the error it inherits. Codes a rotating producer wrote
* are in the rotated domain; the file's metadata then names it (`domain`: the Hadamard width), as
* RADGRAM2's header does, and the reader converts. */
#pragma once
#include <arch/rad_arch.h>
#include <algorithm>
#include <condition_variable>
#include <cstdio>
#include <cstring>
#include <deque>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
namespace rad::arch {
struct CalibFull {
struct Site {
std::string stem; /* the file's name, without .safetensors */
std::string linears; /* the checkpoint linears that read this input, comma-separated */
rad_buf local = 0; /* this rank's part of the input (the whole input when replicated) */
int64_t K = 0; /* the whole input's width */
int64_t k_local = 0; /* this rank's columns; K when replicated */
rad_op op_gather = 0; /* the columns of every rank into `gathered`; 0 when replicated */
rad_op op_gram = 0; /* declared on the owner only */
bool owner = false;
rad_buf q8 = 0, s8 = 0; /* site_i8: the int8 codes and their f32 (row, 128) scales */
uint32_t domain = 0; /* site_i8: the codes' rotation width, 0 for none */
std::vector<float> tri; /* the owner's accumulator, upper triangle packed */
};
bool on = false;
const char* dir = nullptr;
int rank = 0, world = 1;
int64_t lo = 0, hi = 0; /* layers recorded */
long long target = 0, seen = 0;
bool written = false;
rad_buf gathered = 0; /* [max_tok, widest split input] bf16 */
int64_t gather_w = 0;
rad_buf scratch = 0; /* [kmax, kmax] f32 on a rank that owns any input */
int64_t kmax = 0;
std::vector<Site> sites;
/* The host side of the taps (see the file comment). Created at the first tap and released once
* the files are written; a run that ends before then leaks it, since its worker may still wait
* on a card that is being torn down. */
struct Async {
std::mutex mu;
std::condition_variable cv;
std::thread worker;
float* square[2] = { nullptr, nullptr }; /* pinned, kmax * kmax f32 */
RadEvent copied[2] = { nullptr, nullptr };
int site[2] = { -1, -1 }; /* the site square s holds; -1 when free */
std::deque<int> queue; /* squares copied and not yet added */
int next = 0;
bool stop = false, failed = false;
};
Async* async = nullptr;
/* Whether this run records layer l. */
bool records(int64_t l) const { return on && l >= lo && l < hi; }
int owner_of(int64_t l) const { return (int)(l % world); }
/* From the build context: nothing unless --calib-dir is set. `widest_split` and `widest` are
* the largest split input and the largest input of any recorded site, which size the gather
* buffer and the scratch. */
int begin(RadBuilder* b, Names& nm, const Geom& g, const RadBuildCtx* ctx, int64_t n_layer,
int64_t widest_split, int64_t widest) {
if (!ctx->calib_dir || !*ctx->calib_dir) return RAD_OK;
on = true;
dir = ctx->calib_dir;
rank = g.rank;
world = g.world;
lo = ctx->calib_layer_hi ? ctx->calib_layer_lo : 0;
hi = ctx->calib_layer_hi ? std::min<int64_t>(ctx->calib_layer_hi, n_layer) : n_layer;
target = ctx->calib_tokens;
if (lo >= hi) {
std::fprintf(stderr, "radiance: --calib-layers %lld:%lld names no layer of %lld\n",
(long long)lo, (long long)hi, (long long)n_layer);
return RAD_E_INVAL;
}
if (target <= 0) {
std::fprintf(stderr, "radiance: --calib-dir records over a --calib-corpus run, which "
"states the corpus's size\n");
return RAD_E_INVAL;
}
if (world > 1) {
gather_w = widest_split;
gathered = decl_b(b, nm.f("calib.gathered"), RAD_BF16, { g.max_tok, gather_w });
if (!gathered) return RAD_E_INVAL;
}
kmax = widest;
scratch = decl_b(b, nm.f("calib.scratch"), RAD_F32, { kmax, kmax }, RAD_BUF_PERSIST);
return scratch ? RAD_OK : RAD_E_INVAL;
}
/* One input of layer `layer` (-1: the lm_head's, recorded by rank 0). `local` is the rank's
* part, `k_local` its width; the input is split across ranks when k_local * world == K. */
int site(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
rad_buf local, int64_t k_local, int64_t K) {
Site s;
s.stem = std::move(stem);
s.linears = std::move(linears);
s.local = local;
s.K = K;
s.k_local = k_local;
s.owner = (layer < 0 ? 0 : owner_of(layer)) == rank;
const bool split = k_local != K;
if (split) {
if (k_local * world != K || !gathered || K > gather_w) return RAD_E_INVAL;
s.op_gather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", world),
RAD_RANGE("numel", k_local, g.max_tok * k_local),
RAD_STR("dtype", "bf16"), RAD_INT("row", k_local)),
RAD_NOWEIGHTS),
{ local }, { gathered });
if (!s.op_gather) return RAD_E_INVAL;
}
if (s.owner) {
if (K > kmax) return RAD_E_INVAL;
s.op_gram = rw(b, RAD_OP(b, "gram_accum",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
RAD_INT("group", 128), RAD_STR("dtype", "bf16"), /* group: unread at bf16 */
RAD_INT("upper", 1)),
RAD_NOWEIGHTS),
{ split ? gathered : local, scratch }, { scratch });
if (!s.op_gram) return RAD_E_INVAL;
}
sites.push_back(std::move(s));
return RAD_OK;
}
/* One input of layer `layer` from an int8 trunk's codes `q8` and scales `s8` (see the file
* comment): the whole input on one rank, `domain` the Hadamard width the codes were rotated by
* (0 for none). */
int site_i8(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
rad_buf q8, rad_buf s8, int64_t K, uint32_t domain) {
if (world > 1 || !q8 || !s8 || K > kmax) return RAD_E_INVAL;
Site s;
s.stem = std::move(stem);
s.linears = std::move(linears);
s.K = s.k_local = K;
s.owner = true;
s.q8 = q8;
s.s8 = s8;
s.domain = domain;
(void)layer;
s.op_gram = rw(b, RAD_OP(b, "gram_accum",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
RAD_INT("group", 128), RAD_STR("dtype", "i8a8"),
RAD_INT("upper", 1)),
RAD_NOWEIGHTS),
{ q8, s8, scratch }, { scratch });
if (!s.op_gram) return RAD_E_INVAL;
sites.push_back(std::move(s));
return RAD_OK;
}
/* Site `i` over a step's T rows: gather (every rank), then on the owner the Gram into the
* scratch, copied to a free square, the scratch zeroed, and the square handed to the worker. */
void tap(RadCtx* c, size_t i, int64_t T) {
Site& s = sites[i];
RadOperand a = brows(s.local, T);
if (s.op_gather) {
RAD_ISSUE_N(c, s.op_gather, T * s.k_local, brows(s.local, T), bcol(gathered, 0, s.K, T));
a = bcol(gathered, 0, s.K, T);
}
if (!s.owner) return;
float* dev = static_cast<float*>(rad_buf_ptr(c, scratch));
if (!dev || (!async && !start())) {
rad_step_fail(c, "calibration: no scratch or pinned squares");
return;
}
/* Allocated at the first step, not at declare: the engine may declare more than once. */
if (s.tri.empty()) s.tri.assign((size_t)(s.K * (s.K + 1) / 2), 0.0f);
Async& q = *async;
const int k = q.next;
q.next ^= 1;
{
std::unique_lock<std::mutex> lk(q.mu);
q.cv.wait(lk, [&] { return q.site[k] < 0 || q.failed; });
if (q.failed) {
lk.unlock();
rad_step_fail(c, "calibration: waiting on a Gram's copy failed");
return;
}
}
const int64_t K = s.K;
if (s.q8)
RAD_ISSUE_N(c, s.op_gram, T, brows(s.q8, T), brows(s.s8, T), praw2(dev, RAD_F32, K, K));
else
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
/* `upper` 1 writes no entry below the diagonal, so only the upper triangle comes back:
* band by band of kBand rows, each from its first row's diagonal on, about half the
* square's bytes. The link is what a step's taps wait on, 25 GB a step on each rank of
* Qwen3.8-27B as whole squares. */
constexpr int64_t kBand = 512;
bool ok = true;
for (int64_t r = 0; r < K && ok; r += kBand)
ok = rad_memcpy_2d_async(q.square[k] + r * K + r, K * 4, dev + r * K + r, K * 4,
(K - r) * 4, std::min(kBand, K - r), rad_stream(c)) >= 0;
if (!ok || rad_memset_async(dev, 0, K * K * 4, rad_stream(c)) < 0 ||
rad_event_record(q.copied[k], rad_stream(c)) < 0) {
rad_step_fail(c, "calibration: copying a Gram back failed");
return;
}
{
std::lock_guard<std::mutex> lk(q.mu);
q.site[k] = (int)i;
q.queue.push_back(k);
}
q.cv.notify_all();
}
/* After a step: once the corpus is through, every owned input to its file. */
void after_step(RadCtx* c, int64_t T) {
if (!on || written) return;
seen += T;
if (seen < target) return;
written = true;
int n = 0, bad = finish() ? 0 : 1;
for (const Site& s : sites) {
if (!s.owner || s.tri.empty()) continue;
++n;
if (!write(s)) ++bad;
}
std::fprintf(stderr, "radiance: calibration: rank %d wrote %d Hessian(s) of layers %lld:%lld "
"after %lld rows to %s%s\n", rad_rank(c), n, (long long)lo, (long long)hi,
seen, dir, bad ? ", with errors" : "");
if (seen != target)
std::fprintf(stderr, "radiance: calibration: %lld rows seen and the corpus has %lld\n",
seen, target);
}
private:
bool start() {
Async* q = new Async;
bool ok = true;
for (int k = 0; k < 2; ++k) {
q->square[k] = static_cast<float*>(rad_dev_alloc(kmax * kmax * 4, RAD_MEM_HOST_PINNED));
ok = ok && q->square[k] && rad_event_create(&q->copied[k]) >= 0;
}
if (!ok) {
std::fprintf(stderr, "radiance: calibration could not pin 2 x %lld MiB of host squares "
"on rank %d\n", (long long)((kmax * kmax * 4) >> 20), rank);
release(q);
return false;
}
async = q;
q->worker = std::thread([this] { work(); });
return true;
}
/* The worker: each copied square, in the order the rank issued them, into its site. */
void work() {
Async& q = *async;
for (;;) {
int k;
{
std::unique_lock<std::mutex> lk(q.mu);
q.cv.wait(lk, [&] { return q.stop || !q.queue.empty(); });
if (q.queue.empty()) return;
k = q.queue.front();
q.queue.pop_front();
}
Site& s = sites[(size_t)q.site[k]];
const bool ok = rad_event_sync(q.copied[k]) >= 0;
if (ok) add_upper(s.tri.data(), q.square[k], s.K);
{
std::lock_guard<std::mutex> lk(q.mu);
q.site[k] = -1;
if (!ok) q.failed = true;
}
q.cv.notify_all();
}
}
/* Every square added and the worker gone; false if a copy failed. */
bool finish() {
if (!async) return true;
{
std::lock_guard<std::mutex> lk(async->mu);
async->stop = true;
}
async->cv.notify_all();
async->worker.join();
const bool ok = !async->failed;
if (!ok) std::fprintf(stderr, "radiance: calibration: a Gram's copy failed on rank %d\n", rank);
release(async);
async = nullptr;
return ok;
}
static void release(Async* q) {
for (int k = 0; k < 2; ++k) {
if (q->square[k]) rad_dev_free(q->square[k], RAD_MEM_HOST_PINNED);
if (q->copied[k]) rad_event_destroy(q->copied[k]);
}
delete q;
}
/* acc's upper triangle, packed row by row, += the upper triangle of the k x k row-major `full`. */
static void add_upper(float* acc, const float* full, int64_t k) {
const unsigned nt = std::max(1u, std::min(16u, std::thread::hardware_concurrency() / 2));
std::vector<std::thread> th;
for (unsigned t = 0; t < nt; ++t)
th.emplace_back([=] {
for (int64_t i = t; i < k; i += nt) {
float* d = acc + (i * k - i * (i - 1) / 2);
const float* s = full + i * k + i;
for (int64_t j = 0; j < k - i; ++j) d[j] += s[j];
}
});
for (std::thread& x : th) x.join();
}
bool write(const Site& s) const {
char path[1024];
std::snprintf(path, sizeof path, "%s/%s.safetensors", dir, s.stem.c_str());
const uint64_t bytes = (uint64_t)s.tri.size() * 4;
std::string hdr = "{\"__metadata__\":{\"k\":\"" + std::to_string(s.K) + "\",\"rows\":\"" +
std::to_string(seen) + "\",\"layout\":\"upper triangle, row-major, packed\","
"\"linears\":\"" + s.linears + "\"" +
(s.domain ? ",\"domain\":\"" + std::to_string(s.domain) + "\"" : std::string()) +
"},\"hessian_upper\":{\"dtype\":\"F32\","
"\"shape\":[" + std::to_string(s.tri.size()) + "],\"data_offsets\":[0," +
std::to_string(bytes) + "]}}";
while (hdr.size() % 8) hdr += ' ';
const uint64_t hl = hdr.size();
FILE* f = std::fopen(path, "wb");
if (!f) { std::fprintf(stderr, "radiance: calibration cannot write %s\n", path); return false; }
bool ok = std::fwrite(&hl, 8, 1, f) == 1 && std::fwrite(hdr.data(), 1, hl, f) == hl &&
std::fwrite(s.tri.data(), 4, s.tri.size(), f) == s.tri.size();
ok = std::fclose(f) == 0 && ok;
if (!ok) std::fprintf(stderr, "radiance: calibration write to %s was short\n", path);
return ok;
}
};
} /* namespace rad::arch */
+63
View File
@@ -0,0 +1,63 @@
/* rad_deepseek41_chat.h -- DeepSeek-V4.1's reply format (reasoning and DSML tool calls) as data.
*
* The model's own encoder (encoding/encoding.py in the checkpoint) writes an assistant turn as
*
* [reasoning</think>]content\n\n<|DSML| calls>
* <|DSML| invoke name="NAME">
* <|DSML| parameter name="ARG" string="true">raw text</|DSML| parameter>
* <|DSML| parameter name="ARG" string="false">JSON</|DSML| parameter>
* </|DSML| invoke>
* ...
* </|DSML| calls><|end▁of▁sentence|>
*
* Every call sits in one section, each argument's tag says whether its value is a string or JSON,
* and the tag names carry a leading space (V4 wrote `<|DSML|tool_calls>`, V3.2
* `<|DSML|function_calls>`). The generation prompt ends in `<think>` with thinking on and in a
* bare `</think>` with it off, so the reply starts inside the block only when the prompt opened
* it.
*
* The template analysis cannot state the typed argument tags, so the plugin declares the format;
* the reply-format tests read this same declaration. */
#pragma once
#include "rad_builder.h"
namespace rad {
namespace arch {
inline const RadChatFormat* deepseek41_chat_format() {
static const char* const kBreaks[] = { "<|DSML| calls>" };
static const char* const kTriggers[] = { "<|DSML| calls>" };
static const RadChatFormat f = [] {
RadChatFormat c{};
c.struct_size = (uint32_t)sizeof(RadChatFormat);
c.name = "plugin:deepseek41";
c.reasoning_open = "<think>";
c.reasoning_close = "</think>";
/* A section that starts inside an unclosed reasoning block ends it there. */
c.reasoning_breaks = kBreaks;
c.n_reasoning_breaks = 1;
c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
c.section_open = "<|DSML| calls>";
c.section_close = "</|DSML| calls>";
c.name_prefix = "<|DSML| invoke name=\"";
c.name_suffix = "\">\n";
c.call_end = "</|DSML| invoke>";
c.arg_prefix = "<|DSML| parameter name=\"";
c.arg_name_suffix = "\"";
c.arg_value_prefix = " string=\"true\">";
c.arg_json_value_prefix = " string=\"false\">";
c.arg_value_suffix = "</|DSML| parameter>";
c.string_value = RAD_CHAT_VALUE_RAW;
c.other_value = RAD_CHAT_VALUE_JSON;
c.value_newlines = 0;
c.triggers = kTriggers;
c.n_triggers = 1;
return c;
}();
return &f;
}
} /* namespace arch */
} /* namespace rad */
+1610 -654
View File
File diff suppressed because it is too large. Load diff
+61
View File
@@ -0,0 +1,61 @@
/* rad_gemma4_chat.h -- Gemma 4's reply format (reasoning and tool calls) as data.
*
* Template analysis finds nothing in Gemma 4's chat template (llama.cpp uses a hand-written
* handler), so without this the model would get no reasoning split and refuse tool requests.
* This restates the model's tokenizer_config.json `response_template` in the engine's terms:
*
* thinking <|channel>thought\n ... <channel|>
* tool calls <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3,flag:true}<tool_call|>, repeated
* the object unquoted keys, strings between <|"|> and <|"|> with their text verbatim, every
* other value as JSON writes it
* the turn ends at <turn|>; after its calls the model writes <|tool_response> and stops
* (generation_config.json names it beside <eos> and <turn|>)
*
* The model also emits an extra thought channel after the answer and a lone <channel|>.
* `reasoning_anywhere` reads the first as reasoning and drops the second.
*
* Shared because two plugins serve Gemma 4 (arch/gemma4 with bf16 and fp8 experts, arch/gemma4_bf16
* for the CT-INT4 dense release) and the format belongs to the model; the reply-format tests read
* this same declaration. */
#pragma once
#include "rad_builder.h"
namespace rad {
namespace arch {
inline const RadChatFormat* gemma4_chat_format() {
static const char* const kBreaks[] = { "<|tool_call>" };
static const char* const kTriggers[] = { "<|tool_call>" };
static const RadChatFormat f = [] {
RadChatFormat c{};
c.struct_size = (uint32_t)sizeof(RadChatFormat);
c.name = "plugin:gemma4";
c.reasoning_open = "<|channel>thought\n";
c.reasoning_close = "<channel|>";
/* A call that starts inside an unclosed thought ends it there. */
c.reasoning_breaks = kBreaks;
c.n_reasoning_breaks = 1;
/* Thinking off: the template closes an empty channel in the generation prompt. On: the
* model opens its own, or the prompt has opened it after a tool response. */
c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
c.reasoning_anywhere = 1;
c.call_open = "<|tool_call>";
c.call_close = "<tool_call|>";
c.name_prefix = "call:";
c.name_suffix = ""; /* the name ends at the object's `{` */
c.call_end = ""; /* and the object's `}` ends the call */
c.args_form = RAD_CHAT_ARGS_OBJECT;
c.object_string_open = "<|\"|>";
c.object_string_close = "<|\"|>";
c.object_bare_keys = 1;
c.triggers = kTriggers;
c.n_triggers = 1;
return c;
}();
return &f;
}
} /* namespace arch */
} /* namespace rad */
File diff suppressed because it is too large. Load diff
+146
View File
@@ -0,0 +1,146 @@
/* GLM-5.3's tensor parallelism in one place: what a rank's shard of the model is, from which step
* size a replicated or head-split piece of work splits over the ranks instead, how a step's rows
* fall into one run a rank, and the column split of a replicated F32 projection.
*
* The residual stream is replicated (spec.md §9). Three kinds of split share the ranks' work:
*
* heads the MLA and KDA heads, with them the rows of their projections, the KDA state and
* the convolution history; the experts' and the dense feed-forward's width
* (`heads`, `kda_width`, `expert_width`, `dense_width`); joined by an all_reduce
* rows a prefill-sized step's rows, one run a rank, each rank computing its run with the
* unsplit kernels (`run_rows`, `run_of`); joined by an all_gather of whole runs
* columns a replicated F32 projection's output columns (SplitF32Proj); joined by a
* row-interleaved all_gather, bit for bit the replicated projection
*
* The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered
* row, because an all_gather moves whole words. The MLA gathers 4096-wide bf16 rows, so its runs
* are ceil(T / world); the indexer gathers one i32 length a row beside its page tables, so its
* runs are multiples of four rows. The last rank's run may be short, or lie wholly past a small
* step (`run_of`). */
#ifndef RAD_GLM_TP_H
#define RAD_GLM_TP_H
#include "rad_arch.h"
#include <algorithm>
#include <numeric>
namespace rad {
namespace arch {
struct GlmTp {
/* The model's widths a rank's shard divides: 64 heads of 128 (KDA) and 256 (MLA), experts of
* 2048 and a dense feed-forward of 12288. */
static constexpr int64_t kHeads = 64, kKdaDim = 128, kMlaDim = 256, kExpertFF = 2048,
kDenseFF = 12288;
static bool world_ok(int world) { return world == 1 || world == 2 || world == 4 || world == 8; }
static int64_t heads(int world) { return kHeads / world; }
static int64_t kda_width(int world) { return heads(world) * kKdaDim; }
static int64_t mla_width(int world) { return heads(world) * kMlaDim; }
static int64_t expert_width(int world) { return kExpertFF / world; }
static int64_t dense_width(int world) { return kDenseFF / world; }
/* Rows from which a step splits by rows or columns over the ranks. Below it, as in decode, the
* collective's latency outweighs the saved arithmetic and every rank runs the replicated or
* head-split form. */
static constexpr int64_t kSplitRows = 256;
/* Rows x live blocks from which the indexer splits a smaller step as well: a decode step at
* long context, where scoring every query row against every block of its sequence outweighs
* the two gathers. On one R9700 48 rows over 8000 blocks (32k of context) score and select in
* about 250 us and a run of 8 in 50, against roughly 50 us for the two eight-rank gathers;
* over 4000 blocks the saving is about the gathers' cost, and six rows never pay. From 16
* rows, so that at least four ranks share the work and every run fits in the step. */
static constexpr int64_t kSplitWork = 1 << 18, kSplitWorkRows = 16;
static bool splits(int64_t rows, int world) { return world > 1 && rows >= kSplitRows; }
/* A rank's run of a step of `rows`, gathered as rows of `row_bytes`: ceil(rows / world) rounded
* up to whole 16-byte words of the gathered row. Every rank but possibly the last takes a whole
* run; the planes a split writes hold world runs, which can reach past the step. */
static int64_t run_rows(int64_t rows, int world, int64_t row_bytes) {
const int64_t word = 16 / std::gcd<int64_t>(16, row_bytes);
return word * ((rows + word * world - 1) / (word * world));
}
struct Run {
int64_t run = 0, first = 0, rows = 0;
};
/* Rank `rank`'s rows [first, first + rows) of a step of `rows`. A rank whose run lies wholly
* past a small step takes the step's first run instead, so every plane it computes from and
* gathers is written; what it computes there is dead rows past the step, and the gather lays
* them past T, where nothing reads them. */
static Run run_of(int64_t rows, int world, int rank, int64_t row_bytes) {
Run r;
r.run = run_rows(rows, world, row_bytes);
r.first = rank * r.run;
r.rows = std::min(r.run, rows - r.first);
if (r.rows <= 0) {
r.first = 0;
r.rows = r.run;
}
return r;
}
/* The all_reduce of a replicated 4096-wide bf16 row over the ranks: the embedding's (exact)
* and each head-split block's (the deployment's wire). */
static rad_op reduce(RadBuilder* b, const Geom& g, rad_buf x, bool exact = false) {
if (g.world == 1) return 0;
return rw(b,
RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4096, g.max_tok * 4096),
RAD_STR("dtype", "bf16"),
RAD_INT("exact", exact ? 1 : g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{ x }, { x });
}
};
/* The split's ops are declared whatever the step size, and each gather's message as a range of
* rows: the engine's arena levels declare again at a smaller max_tok and must get the same graph
* with the same fixed parameters.
*
* A replicated [n, k] F32 projection computed column-split: rank r runs the same gemm_nt_f32 on
* rows [r*n/world, (r+1)*n/world) of the weight and a row-interleaved all_gather lays the slices
* out as the full [M, n]. The kernel computes every output column independently of n and the
* gather moves bytes, so each value is bit-identical to the replicated projection's. */
struct SplitF32Proj {
rad_buf part = 0;
rad_op op_part = 0, op_gather = 0;
int64_t cols = 0, k = 0, min_rows = 0, first_col = 0;
int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, int64_t n,
int64_t width, rad_weight weight, rad_buf input, rad_buf output) {
min_rows = GlmTp::kSplitRows;
if (g.world < 2 || n % g.world || (n / g.world * 4) % 16) {
min_rows = 0;
return RAD_OK;
}
cols = n / g.world;
k = width;
first_col = g.rank * cols;
part = decl_b(b, nm.f("%s.part", name), RAD_F32, { rows, cols });
op_part = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", cols), RAD_INT("K", k),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(weight)),
{ input }, { part });
op_gather = rw(
b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", cols, rows * cols),
RAD_STR("dtype", "f32"), RAD_INT("row", cols)),
RAD_NOWEIGHTS),
{ part }, { output });
return part && op_part && op_gather ? RAD_OK : RAD_E_INVAL;
}
bool takes(int64_t rows) const { return min_rows && rows >= min_rows; }
void step(RadCtx* ctx, int64_t rows, RadOperand input, rad_weight weight,
RadOperand output) const {
RadOperand slice = RAD_W(weight);
slice.offset = first_col * k;
slice.rows = cols;
RAD_ISSUE_N(ctx, op_part, rows, input, slice, brows(part, rows));
RAD_ISSUE_N(ctx, op_gather, rows * cols, brows(part, rows), output);
}
};
}
} // namespace rad::arch
#endif
+210 -225
View File
@@ -1,16 +1,15 @@
/* rad_qsa.h -- Qwen4-Exp's QSA indexer: the part of a full-attention layer that decides WHICH
* blocks of key history that layer's attention reads.
/* rad_qsa.h -- Qwen4-Exp's QSA indexer: decides which blocks of key history a full-attention
* layer's attention reads.
*
* docs/QSA.md is the decomposition and the argument; this is the declaration side of it. The
* kernels are libr4d's `qsa_block_key`, `qsa_score` and `qsa_select`, and the sparse attention is
* the ORDINARY `attn_paged` issued with the selection in place of the sequence's own block table
* -- both of those are plain operands, so nothing in core/ learns what QSA is.
* docs/QSA.md has the design; this is the declaration side. The kernels are libr4d's
* `qsa_block_key`, `qsa_score` and `qsa_select`; the sparse attention is the ordinary `attn_paged`
* issued with the selection in place of the sequence's block table (both plain operands, so core/
* knows nothing of QSA).
*
* WHAT IS HERE is the whole indexer: the projection and the query path, the block-key path with
* its two states, and the score and selection the sparse attention is issued with. Below
* `budget + ratio - 1` tokens of context the selection is EVERY visible block, so the sparse path
* must reproduce the dense path's text byte for byte -- which is the oracle any change to this
* file is checked against.
* Contents: the projection and query path, the block-key path with its two states, and the score
* and selection. Below `budget + ratio - 1` tokens of context every visible block is selected, so
* the sparse path must reproduce the dense path's text byte for byte; that is the test for any
* change here.
*/
#ifndef RAD_QSA_H
#define RAD_QSA_H
@@ -18,6 +17,8 @@
#include "rad_arch.h"
#include "rad_fp8.h"
#include <atomic>
namespace rad {
namespace arch {
@@ -27,105 +28,75 @@ struct QsaIndexer {
int64_t head_dim = 0; /* indexer_head_dim -- 128 */
int64_t ratio = 0; /* indexer_compress_ratio -- 4 tokens a block */
int64_t budget = 0; /* indexer_budget -- 2048 tokens, so 512 blocks */
int64_t rot = 0; /* the LAYER's rotary width, which the indexer shares */
int64_t rot = 0; /* the layer's rotary width, shared by the indexer */
const char* mode = "neox";
/* Checkpoint names. Absent means this layer has no indexer and declare() is a no-op. */
const char* qk_proj = nullptr;
const char* q_norm = nullptr;
const char* k_norm = nullptr;
/* Derived, and all four are the caller's because they size things it declares. */
/* Derived; set by the caller because they size buffers it declares. */
int64_t topk = 0; /* budget / ratio -- blocks the selection keeps */
int64_t max_blocks = 0; /* max_ctx / ratio -- the widest block table */
int64_t max_work = 0; /* ceil(max_tok / ratio) + max_seqs */
/* THE TAIL'S RING LENGTH, `ratio + max_spec`, and the `max_spec` is the whole of it.
*
* A tail of exactly `ratio` rows indexed by `pos % ratio` is right when a step's tokens
* are the tokens that happened. Under speculation they are not: a verify step runs
* 1 + n_spec positions and the next step RESTARTS at the first rejected one, so positions
* the tail has already overwritten are needed again. Concretely at ratio 4, depth 3,
* positions 9..12 -- the store writes slots 1,2,3,0 and position 12 lands on the slot
* position 8 is still owed to. Accept one and the next step rebuilds block 2 (tokens
* 8..11) out of a slot holding token 12. That block key is then wrong in the cache for
* the rest of the sequence, and it happens on any step that straddles a block boundary
* and does not accept everything -- which is most of them.
*
* The deepest rollback is to the first draft, so the widest window a step can still owe
* is [p0 - ratio + 1, p0 + n_spec]: ratio + n_spec positions, each needing its own
* residue. Under `ratio + max_spec` a slot is only ever overwritten by a position that
* far ahead, which is past the end of the step that could ask for it. */
/* The tail's ring length, `ratio + max_spec`. A ring of `ratio` indexed by `pos % ratio`
* fails under speculation: the next step restarts at the first rejected position, so
* overwritten slots are needed again (at ratio 4, depth 3, positions 9..12 write slots
* 1,2,3,0 and 12 overwrites the slot of 8; accepting one then rebuilds block 2 from token
* 12, corrupting that block key permanently). A step can still owe positions
* [p0 - ratio + 1, p0 + n_spec], so `ratio + max_spec` slots keep every owed position. */
int64_t ring = 0; /* ratio + max_spec */
/* THE ATTENTION GROUP, because the SELECTION's output is what the attention reads and so
* it is that group's page ids that come out. The block-key group is this block's own and
* is declared on first use -- see declare(). */
/* The attention group, whose page ids the selection outputs. The block-key group is
* declared on first use (see declare()). */
rad_kvgroup kv_attn = 0;
/* THE TAIL'S GROUP: one RAD_KV_LINEAR state a sequence a layer, `ring` rows of
* `head_dim`. It is a KV group and not a buffer because a buffer has no way to name a
* SEQUENCE -- see the note on Wire. */
/* The tail's group: one RAD_KV_LINEAR state per sequence per layer, `ring` rows of
* `head_dim` (a KV group because it is per-sequence state; see Wire). */
rad_kvgroup kv_tail = 0;
/* DOES ANYTHING READ THE SELECTION? False on the DENSE path, where the attention is
* issued with the sequence's own block table and `sel` is written for nobody. The block-key
* half still runs -- it is STATEFUL, and a history built without it is a history the sparse
* path could not later read -- but the score and the selection are then dead work, and on
* this model they are the largest op in the indexer. Declared either way, so the graph and
* the buffer plan do not depend on it. */
/* Whether anything reads the selection. False on the dense path; the stateful block-key
* half still runs so the sparse path can later read the history, but score and select (the
* indexer's largest ops) are skipped. Declared either way, so the graph and buffer plan do
* not depend on it. */
bool emit_sel = true;
/* The rows the score plane was declared with, 0 for max_tok. Fewer only where a step
* wider than them is one sequence (RadBuildCtx::max_mixed_tok); such a step scores and
* selects in windows of this many rows (step()). */
int64_t plane_rows = 0;
};
/* The two planes the front half produces. `qk` is the projection whole -- `heads` query heads
* then ONE raw key head -- and `q` is the query heads normed and rotated, contiguous.
/* `qk` is the whole projection (`heads` query heads, then one raw key head); `q` is the query
* heads normed and rotated, contiguous.
*
* THE RAW KEY IS NEVER NORMED OR ROTATED HERE. It is pooled over `ratio` tokens FIRST and the
* norm and the rotation happen to the pooled result, at the position of the block's first
* token (`qsa_block_key`). Reading the reference quickly gives the opposite impression,
* because the q path right above it does both. */
* The raw key is not normed or rotated here: it is pooled over `ratio` tokens first, and the
* pooled result is normed and rotated at the block's first token's position (`qsa_block_key`),
* unlike the q path. */
struct Wire {
rad_buf qk = 0; /* [max_tok, (heads + 1) * head_dim] */
rad_buf q = 0; /* [max_tok, heads * head_dim] */
/* THE TAIL IS NOT IN THIS WIRE AND CANNOT BE. Every other buffer here is within-step
* scratch, which is why one set serves the whole model; the tail carries an unfinished
* block's RAW INDEX KEYS ACROSS STEPS, and that makes it state with two axes a buffer
* cannot express.
*
* THE LAYER. The keys are `index_qk_proj`'s output and that weight is PER LAYER, so a
* shared tail has layer L pooling layer L-1's keys -- at decode three of every four
* keys in a completing block come from the wrong layer. Every layer needs its own,
* including the MTP head's.
*
* THE SEQUENCE. A per-layer buffer indexed by the BATCH ROW is no better across
* requests: the row is step-local -- the scheduler builds the step from `running_` in
* priority order and then stable-sorts decode first -- so a sequence that outlives an
* earlier one shifts down a row and inherits its keys. A buffer has no per-sequence
* axis to index instead; a KV group does, and that is the one the engine keeps stable
* for the life of a sequence, zeroes when it hands a slot out, and checkpoints with
* the rest of the linear state when the prefix cache saves one.
*
* So the tail is `Config::kv_tail`, a RAD_KV_LINEAR group, and declare() binds this
* layer to it. Nothing about it belongs to a wire shared by every layer. */
/* These buffers are within-step scratch shared by every layer. The tail is not here: it
* carries an unfinished block's raw index keys across steps, per layer (each layer has its
* own `index_qk_proj`, the MTP head included) and per sequence (batch rows are step-local
* and shift between steps). A KV group has a stable per-sequence slot, zeroed on hand-out
* and checkpointed with the linear state by the prefix cache, so the tail is
* `Config::kv_tail` (RAD_KV_LINEAR), bound to this layer in declare(). */
rad_buf stage = 0; /* [max_work * ratio, head_dim] */
rad_buf page = 0; /* [max_work] i32 */
rad_buf bpos = 0; /* [max_work] i32, or [max_work, 3] under M-RoPE */
rad_buf nc = 0; /* [max_seqs] i32 */
/* The selection, ONE ROW A QUERY and not one a sequence. At decode the two are the same
* thing; at prefill a chunk's queries share one history and each picks its own set out of
* it, which is the whole of Stage B (docs/QSA.md). `sel` and `seqused` are what the sparse
* attention is issued with in place of the sequence's own block table and length.
/* The selection, one row per query, not per sequence (the same at decode; at prefill each
* query of a chunk selects from the shared history, docs/QSA.md, "Per-query selection"). `sel` and
* `seqused` replace the sequence's block table and length for the sparse attention.
*
* `score` IS THE BIG ONE: max_tok * max_ctx/ratio floats, 134 MB at a 2048-token chunk and
* 64K of context. It is one buffer for the whole model rather than one a layer, and
* declare() refuses a geometry whose product is unreasonable rather than discovering it as
* an allocation failure. Tiling the query axis would cap it, and the reason it is not done
* is that `cu` is absolute over the batch: a tile would need its rows rebased, which means
* a per-token sequence id operand -- qsa_work is where it would come from. */
* `score` is the largest: max_tok * max_ctx/ratio floats, 134 MB at a 2048-token chunk
* and 64K context, one buffer for the whole model. A step of one sequence is tiled on the
* query axis when it is wider than the plane (Config::plane_rows): a window of it is a
* sequence of its own rows. A step of several is not: that would need a per-token
* sequence id operand (from qsa_work), since `cu` is absolute over the batch. */
rad_buf score = 0; /* [max_tok, max_blocks] f32 */
rad_buf sel = 0; /* [max_tok, topk + 1] i32 */
rad_buf nsel = 0; /* [max_tok] i32 */
rad_buf sequ = 0; /* [max_tok] i32 */
/* THE MODEL'S cos/sin PLANE, [rope_table_rows, rot], or 0 if it builds none. It is the
* attention block's -- `rope_table` fills it once a step for every layer -- and the
* indexer's own rotation is at the same `rot`, `theta` and `scale`, so the rows are
* already there. A block handed no table asks for no fusion and runs the per-head norms
* below, which is what keeps a plugin that does not build the table on the unfused
* path. */
/* The model's cos/sin plane, [rope_table_rows, rot], or 0 if it builds none. Filled once a
* step by `rope_table` for the attention block; the indexer rotates at the same `rot`,
* `theta` and `scale`. Without it the unfused per-head norms run. */
rad_buf cos_sin = 0;
};
@@ -137,23 +108,26 @@ struct QsaIndexer {
LinearFP8 proj{};
rad_kvgroup kv_bk = 0;
rad_op op_norm = 0, op_rope = 0, op_qprep = 0;
/* The most rows `op_qprep` may be issued over, 0 when it is not declared. It is the model's
* own `qk_fuse_rows` and it is NOT a tuning: the cos/sin table is filled only for steps at or
* under it, so above it the rows this op would read were never written. */
/* Most rows `op_qprep` may be issued over (0 when not declared): `qk_fuse_rows`, a correctness
* bound, since the cos/sin table is filled only for steps at or under it. */
int64_t qprep_rows = 0;
rad_op op_work = 0, op_bkey = 0, op_tail = 0, op_score = 0, op_select = 0;
bool on() const { return op_rope != 0; }
/* `bk` is the block-key KV group, created on FIRST USE and shared by every QSA layer after
* that -- which is why it is an in/out parameter rather than a member. It cannot be declared
* with the model's other groups: `Builder::find_kv_consumer` binds a group to the first op
* declared AFTER it that carries a `block_size`, and between a model-level declaration and
* this block's `qsa_block_key` there is a whole layer of other ops. Declared immediately
* before its own consumer, the binding cannot be anything else. */
/* `bk` is the block-key KV group, created on first use and shared by all QSA layers (hence
* in/out). It must be declared immediately before `qsa_block_key`: `Builder::find_kv_consumer`
* binds a group to the first later-declared op with a `block_size`. */
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
const Wire& wire, const ActFP8& in, rad_kvgroup* bk);
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
/* `win_cu`, device: {0, plane_rows}, the one sequence of a window of a step wider than the
* score plane (Config::plane_rows); null where no step is. */
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch,
const int32_t* win_cu = nullptr) const;
/* Stores the pass's block keys and tail exactly as step() does, with no query, score or
* selection (see AttnGatedFP8::store_kv). */
void store(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
bool store_keys(RadCtx* c, const RadBatch* batch) const;
};
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -163,9 +137,8 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
if (!c.qk_proj || !c.q_norm) return RAD_OK; /* no indexer on this layer */
if (c.heads <= 0 || c.head_dim <= 0 || c.ratio <= 0 || c.budget <= 0) return RAD_E_INVAL;
if (!w.qk || !w.q) return RAD_E_INVAL;
/* The rotation is the LAYER's and it has to fit inside the index head, which the checkpoint's
* own validator also requires -- so a container that violated it is refused here by name
* rather than rotating past the end of a head. */
/* The layer's rotary width must fit inside the index head (as the checkpoint's validator also
* requires). */
if (c.rot < 0 || c.rot > c.head_dim || (c.rot & 1)) return RAD_E_SHAPE;
const int64_t nw = (c.heads + 1) * c.head_dim; /* the projection width */
@@ -177,41 +150,23 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
if (!w_qn) return RAD_E_INVAL;
/* ONE DECLARED NORM, ISSUED ONCE A HEAD, and the reason is the projection's layout rather
* than a preference. `qk` is `heads + 1` heads wide, so the query heads are 128 apart WITHIN
* a token and 640 apart ACROSS tokens -- which is not a stride any rank-2 view can express,
* and the ABI narrows dim 0 or the last dimension and nothing between. A column slice of ONE
* head is expressible, so the norm runs `heads` times and writes into a contiguous `q` that
* the rotation can then take whole.
/* Unfused, one norm op is issued once per head: in `qk` (`heads + 1` heads wide) the query
* heads are 128 apart within a token and 640 apart across tokens, which no rank-2 view can
* express, but a one-head column slice can. It writes a contiguous `q` that the rope takes
* whole. For 128-wide rows these launches are nearly all overhead.
*
* Four extra launches a layer, and for a 128-wide row the launch IS the cost: the norms and
* the ropes across the model's indexer layers are a real slice of a decode step against
* microseconds of arithmetic. `op_qprep` is the fused form that replaces them.
*
* THE FUSED FORM IS `qk_norm_rope_gate`'S K SIDE, not a new op. That kernel already reads a
* plain [tokens, heads, head_dim] input at the operand's OWN row pitch and writes the heads
* contiguously -- which is exactly this projection's query half inside its `heads + 1` width
* -- and it already rounds the norm to bf16 before rotating, because that is what a norm that
* stores a tensor and a rope that reads it back do. The only thing its q side adds is the
* [q|gate] split, and there is no gate here, so `n_head` 0 asks for the half that fits and
* passes no q operands at all. Five launches a layer become one.
*
* IT NEEDS THE MODEL'S cos/sin TABLE and asks for nothing if it has none. The rotation is at
* the same `rot`, `theta` and `scale` as the attention block's, so `rope_table` has already
* written the rows this step's positions name -- and a plugin that builds no table leaves
* `w.cos_sin` at 0 and runs the per-head norms below unchanged.
*
* AND ONLY UP TO `qk_fuse_rows`, WHICH IS A CORRECTNESS BOUND AND NOT A TUNING. The model
* issues `rope_table` only for steps at or under that row count -- the fusion pays where the
* launch is the cost, and a prefill chunk's kernels already fill the card -- so ABOVE it the
* table rows this op would read were never written THIS step. It would rotate by another
* step's angles: fluent text with a subtly wrong sense of position, which is the failure
* `rope_table`'s own note calls out and which nothing downstream would flag. The bound is the
* attention block's, off the same function, so the two cannot drift apart. */
* `op_qprep` fuses them (five launches to one) using `qk_norm_rope_gate`'s k side: it reads
* [tokens, heads, head_dim] at the operand's row pitch, writes heads contiguously, and rounds
* the norm to bf16 before rotating. With no gate, `n_head` 0 selects that half and passes no
* q operands. It needs the model's cos/sin table (same `rot`, `theta`, `scale` as the
* attention block) and is used only up to `qk_fuse_rows`, a correctness bound: the table is
* filled only for steps that small, so a larger step would rotate by stale angles. The bound
* comes from the same function as the attention block's. */
const bool qprep_neox = !std::strcmp(c.mode, "neox") || !std::strcmp(c.mode, "mrope") ||
g.rope_mc;
qprep_rows = qk_fuse_rows(g);
if (w.cos_sin && qprep_neox && qprep_rows > 0 && (c.head_dim % 32) == 0)
if (w.cos_sin && qprep_neox && qprep_rows > 0 && (c.head_dim % 32) == 0 &&
rad_op_declared(b, "qk_norm_rope_gate"))
op_qprep = rw(b, RAD_OP(b, "qk_norm_rope_gate",
RAD_PARAMS(RAD_RANGE("M", 1, qprep_rows),
RAD_INT("head_dim", c.head_dim), RAD_INT("n_head", 0),
@@ -234,9 +189,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
if (!c.k_norm || !w.stage || !c.topk || !c.max_blocks || !c.max_work)
return RAD_E_INVAL;
if (!c.kv_tail || c.ring < c.ratio) return RAD_E_INVAL;
/* THIS LAYER'S TAIL STATE. The group is the caller's -- it holds one state per sequence per
* BOUND LAYER, so binding is how this layer gets its own, and it is the same call the
* block-key group needs for the same reason. */
/* This layer's tail state: the caller's group holds one state per sequence per bound layer. */
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, c.kv_tail));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.qsa_k_norm.weight", l), c.k_norm));
w_kn = decl_w(b, nm.f("blk.%d.qsa_k_norm.weight", l), RAD_F32, { c.head_dim },
@@ -251,10 +204,9 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_NOWEIGHTS),
{w.qk}, {w.stage, w.page, w.bpos, w.nc});
/* THE GROUP IS DECLARED HERE, immediately before the op that sizes it -- see declare()'s
* note. `kv_heads` 1, `block_size` the compress ratio and `head_dim` n/(2*ratio) make a page
* hold exactly `n` contiguous values, which is one block key, and make the manager allocate
* exactly one page per `ratio` tokens. The geometry is a container, not an attention shape. */
/* The block-key group, declared immediately before its consumer (see the declaration). One KV
* head, `block_size` = ratio and `head_dim` = n / (2 * ratio) make a page hold exactly one
* block key of `n` values, one page per `ratio` tokens. */
if (*bk == 0) {
if ((c.head_dim % (2 * c.ratio)) != 0) return RAD_E_SHAPE;
RadKVGroupDecl d{};
@@ -264,29 +216,25 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
d.head_dim = c.head_dim / (2 * c.ratio);
*bk = rad_decl_kv_group(b, nm.f("kv_qsa_bkey"), &d);
if (!*bk) return RAD_E_INVAL;
/* qsa_score reads every complete block of the history each step, so this group stays resident
* and holds every sequence's context while a sibling streams (kvstream/carve.h). */
RAD_ARCH_TRY(rad_kv_group_dense_read(b, *bk));
}
kv_bk = *bk;
/* UNDER M-RoPE a block key rotates at its first token's three components, which qsa_work
* writes into a [work, 3] `bpos` when it is handed the step's rotary planes. */
op_bkey = g.rope_mc
? decl_rotary(b, g, "qsa_block_key",
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
RAD_INT("block_size", c.ratio),
RAD_F64("eps", g.eps), RAD_F64("theta", g.theta),
RAD_F64("scale", g.rope_scale), RAD_F64("wadd", g.wadd_qk),
RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
RAD_STR("sections", g.rope_sections)),
RAD_WEIGHTS(w_kn))
: decl_rotary(b, g, "qsa_block_key",
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
RAD_INT("block_size", c.ratio),
RAD_F64("eps", g.eps), RAD_F64("theta", g.theta),
RAD_F64("scale", g.rope_scale), RAD_F64("wadd", g.wadd_qk),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_kn));
op_bkey = rw(b, op_bkey, {w.stage, w.page, w.bpos}, {});
/* Under M-RoPE a block key rotates at its first token's three components, which qsa_work
* writes into a [work, 3] `bpos` when given the step's rotary planes. */
{
const RadParam ps[] = { RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
RAD_INT("block_size", c.ratio),
RAD_F64("eps", g.eps), RAD_F64("theta", g.theta),
RAD_F64("scale", g.rope_scale), RAD_F64("wadd", g.wadd_qk),
RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
RAD_STR("sections", g.rope_sections) };
const int n_ps = (int)(sizeof ps / sizeof ps[0]) - (g.rope_mc ? 0 : 2);
op_bkey = rw(b, decl_rotary(b, g, "qsa_block_key", ps, n_ps, &w_kn, 1),
{w.stage, w.page, w.bpos}, {});
}
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv_bk));
op_tail = rw(b, RAD_OP(b, "qsa_tail_store",
@@ -297,8 +245,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_NOWEIGHTS),
{w.qk}, {});
/* M IS QUERIES ON BOTH, up to a whole prefill chunk. A band stopping at max_seqs would be
* right only for a per-SEQUENCE selection; this one selects per QUERY. */
/* M is queries for both, up to a whole prefill chunk: the selection is per query. */
op_score = rw(b, RAD_OP(b, "qsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.head_dim),
RAD_INT("heads", c.heads), RAD_INT("blocks", c.max_blocks),
@@ -311,61 +258,34 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_INT("ratio", c.ratio), RAD_INT("seqs", g.max_seqs)),
RAD_NOWEIGHTS),
{w.score, w.nc}, {w.sel, w.nsel, w.sequ});
/* When the attention group streams, the attention block resolves `sel` to ring slots after its
* layer's store (AttnGatedFP8::step); prefill runs on the stage and never resolves. */
return RAD_OK;
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
/* Stores the block keys of the blocks the pass completes and the tail of raw keys after them,
* from the projection's raw-key head. False when the step has no batch for the indexer's
* groups. */
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t qw = c.heads * c.head_dim;
const int64_t nw = (c.heads + 1) * c.head_dim;
const int64_t koff = qw; /* the raw-key head, after the query heads */
proj.step(c_, in, w.qk, T);
/* ONE LAUNCH OR `heads` + 1. The fused form takes the projection WHOLE -- the kernel picks
* head `h` out of it at the operand's own row pitch, so the strided view the unfused norm
* needs is not taken at all -- and it writes the query heads contiguous and rotated, which is
* what the pair below leaves behind. `n_head` 0 is the k-only form: no q_gate, no q_w, no
* q_out, and the ninth operand (`gate_out`) is absent as it is everywhere else.
*
* `T <= qprep_rows` IS THE TABLE'S BOUND and declare() says why it is correctness. */
if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
RAD_ISSUE_N(c_, op_qprep, T,
RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_NONE, RAD_W(w_qn),
RAD_NONE, brows(w.q, T), RAD_NONE);
} else {
for (int64_t h = 0; h < c.heads; ++h)
RAD_ISSUE_N(c_, op_norm, T,
bcol_at(w.qk, 0, nw, h * c.head_dim, c.head_dim, T), RAD_W(w_qn),
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
}
const int64_t koff = c.heads * c.head_dim; /* the raw-key head, after the query heads */
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
const RadKVGroupBatch* tlb = kv_batch(batch, c.kv_tail);
if (!bkb || !atb || !tlb) return;
/* COLUMN 0 OF THE STATE ROW IS THE COMMITTED SLOT. The row is wider than one whenever the
* deployment speculates -- the manager gives every linear group a second copy then, because
* the kernel that needed one asked for it -- and this op wants the committed slot in every
* case. The pitch is the batch's, not a constant. */
if (!bkb || !tlb) return false;
/* Column 0 of the state row is the committed slot; the row is wider when speculating (linear
* groups get a second copy), so use the batch's pitch. */
const int64_t tw = tlb->state_index_pitch > 0 ? tlb->state_index_pitch : 1;
/* THE WORK LIST BEFORE THE TAIL STORE, and the order is load-bearing rather than tidy: the
* gather reads the raw keys of the block that is completing, and up to `ratio - 1` of them
* are in the tail from earlier steps -- which the store is about to overwrite with this
* step's. Reversed, every block completing at decode would pool three of this step's keys.
*
* The ring makes the store's overwrite land `ring` positions later rather than `ratio`, so
* the two do not collide within a step either -- but the order still decides what a
* straddling block reads, and it is the cheaper of the two guarantees to keep. */
/* Invariant: the work list runs before the tail store. The gather reads a completing block's
* raw keys, up to `ratio - 1` of which are in the tail from earlier steps and are about to be
* overwritten. The ring also spaces overwrites by `ring` positions, but the order still decides
* what a straddling block reads. */
const int64_t work = (T + c.ratio - 1) / c.ratio + S;
/* THE BLOCK POSITIONS: one component a block, or -- under M-RoPE with the planes -- three.
* Under M-RoPE `bpos` is declared [max_work, 3], a block a row, so a smaller step is fewer
* rows and the arena's sizing declare can shrink it; this step hands [work, 3], or its first
* column alone when the pass has no planes -- qsa_work then writes component 0 and the block
* key reads the one-component form. */
/* Block positions: one component per block, or three under M-RoPE with planes. Under M-RoPE
* `bpos` is [max_work, 3]; this step passes [work, 3], or only column 0 when the pass has no
* planes (qsa_work then writes component 0 and the block key reads the one-component form). */
const bool mc = g.rope_mc && batch->rope_pos;
RadOperand bpos = g.rope_mc ? RAD_B_COL(w.bpos, 0, mc ? 3 : 1) : brows(w.bpos, work);
if (g.rope_mc) bpos.rows = work;
@@ -389,30 +309,96 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw));
return true;
}
/* SCORE AND SELECT OVER EVERY QUERY IN THE STEP. A selection does not have to be per-SEQUENCE
* even though a block table is: both ops take `cu`, the block table stays the sequence's, and
* `m` is a query row. So a prefill chunk's queries each get their own selection out of the one
* history they share, which is what the checkpoint does, and there is no cap on the context a
* step may index. */
inline void QsaIndexer::store(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
proj.step(c_, in, w.qk, batch->n_tok);
(void)store_keys(c_, batch);
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch,
const int32_t* win_cu) const {
if (!on()) return;
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t qw = c.heads * c.head_dim;
const int64_t nw = (c.heads + 1) * c.head_dim;
proj.step(c_, in, w.qk, T);
/* One fused launch or `heads` + 1 unfused. The fused form takes the whole projection at its
* row pitch and writes the query heads contiguous and rotated. `n_head` 0 is the k-only form:
* no q_gate, q_w or q_out, and `gate_out` absent. `T <= qprep_rows` is a correctness bound
* (see declare()). */
if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
RAD_ISSUE_N(c_, op_qprep, T,
RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_NONE, RAD_W(w_qn),
RAD_NONE, brows(w.q, T), RAD_NONE);
} else {
for (int64_t h = 0; h < c.heads; ++h)
RAD_ISSUE_N(c_, op_norm, T,
bcol_at(w.qk, 0, nw, h * c.head_dim, c.head_dim, T), RAD_W(w_qn),
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
}
/* The keys first: the selection below reads the blocks they complete. */
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
if (!atb || !store_keys(c_, batch)) return;
/* Score and select per query: both ops take `cu`, the block table stays per sequence, and `m`
* is a query row, so each query of a prefill chunk selects from the shared history, as the
* checkpoint does. */
if (!c.emit_sel) return;
/* HOW MUCH HISTORY THERE ACTUALLY IS. The score plane is declared for `max_ctx`, so scoring
* and selecting to its width means a 2000-token prompt walks 50000 block slots -- and both
* kernels size their GRID from the declared width, because the live count is device data.
* Narrowing the operand is how the host tells them: the pitch stays the declaration's, only
* the column count moves, which is the same trick the attention block plays with `reach`.
/* Narrow the score columns to the live history. Both kernels size their grid from the
* operand's width (the live count is device data), so the full `max_ctx` width would make a
* 2000-token prompt walk 50000 block slots; the pitch stays declared, only the column count
* moves.
*
* IT IS A CEILING AND EVERY TERM IS SLACK, because an UNDER-estimate silently drops blocks
* from the selection and nothing would say so. A query's complete-block count is at most
* (position + 1) / ratio; the highest position this step can reach is bounded by the
* host-side context bound plus every token in the step plus the draft window; and the +1
* keeps `n < nb`, which is what makes the partial page -- `bt[n]` -- readable at all. */
* This must be an upper bound: an underestimate silently drops blocks. A query has at most
* (position + 1) / ratio complete blocks; positions are bounded by the host context bound plus
* the step's tokens plus the draft window; the +1 keeps `n < nb` so the partial page `bt[n]`
* is readable. */
const int64_t reach = (int64_t)batch->max_ctx_len + batch->n_tok + batch->n_spec + c.ratio;
int64_t live = reach / c.ratio + 1;
if (live > c.max_blocks) live = c.max_blocks;
if (live < 1) live = 1;
/* A step wider than the score plane is one sequence (Config::plane_rows), scored and selected
* in windows of the plane's rows from the front, the last one ending at the step's end and
* overlapping the one before. A window is handed as a sequence of its own rows (`win_cu` =
* {0, rows}). Every operand a query row reads is its own (query, position, selection) and the
* block table and complete-block count are the step's, so each row is scored and selected as
* in one pass over the step, and a row two windows share is written twice with the same
* bytes. */
const int64_t PR = c.plane_rows > 0 ? c.plane_rows : T;
if (T > PR) {
if (S != 1 || !win_cu) {
rad_step_fail(c_, "qsa: a step wider than the score plane must be one sequence with "
"its window bounds (RadBuildCtx::max_mixed_tok)");
return;
}
for (int64_t w0 = 0;;) {
RAD_ISSUE_N(c_, op_score, PR,
brow_slice(w.q, w0, PR, qw), kv_cache(kv_bk, layer),
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
praw(win_cu, RAD_I32, 2), brows(w.nc, S),
bcol_at(w.score, 0, c.max_blocks, 0, live, PR));
RAD_ISSUE_N(c_, op_select, PR,
bcol_at(w.score, 0, c.max_blocks, 0, live, PR),
praw2(atb->block_table, RAD_I32, S, atb->block_table_pitch),
brows(w.nc, S), praw(batch->positions + w0, RAD_I32, PR),
praw(win_cu, RAD_I32, 2),
brow_slice(w.sel, w0, PR, c.topk + 1), brow_slice(w.nsel, w0, PR, 1),
brow_slice(w.sequ, w0, PR, 1));
if (w0 + PR >= T) break;
w0 = w0 + PR + PR <= T ? w0 + PR : T - PR;
}
return;
}
RAD_ISSUE_N(c_, op_score, T,
brows(w.q, T), kv_cache(kv_bk, layer),
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
@@ -425,14 +411,13 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
praw(batch->cu_seqlens, RAD_I32, S + 1),
brows(w.sel, T), brows(w.nsel, T), brows(w.sequ, T));
/* RADIANCE_DEBUG_QSA: the only window into a selection. Nothing else in the tree reports one,
* and the numbers it prints are what tell a divergence from the dense path apart from QSA
* doing its job -- `nc` above `topk` is blocks being dropped ON PURPOSE. It SYNCHRONISES THE
* STREAM, so it is an environment variable, off, and costs nothing when it is not set; the
* first few decode steps are enough to see the shape. */
if (getenv("RADIANCE_DEBUG_QSA")) {
static int seen = 0;
if (seen++ < 6) {
/* RADIANCE_DEBUG_QSA: prints the first few selections (nc, nsel, sequ, leading sel and score
* entries) to tell a divergence from intended dropping (`nc` above `topk`). Synchronises the
* stream; off unless set. */
static const bool dbg = std::getenv("RADIANCE_DEBUG_QSA") != nullptr;
if (dbg) {
static std::atomic<int> seen{0};
if (seen.fetch_add(1) < 6) {
rad_stream_sync(rad_stream(c_));
std::vector<int32_t> hnc(1), hns(1), hsu(1), hsel(8);
std::vector<float> hsc(8);
+167
View File
@@ -0,0 +1,167 @@
/* rad_resample.h -- fp32 bicubic resampling reproducing torch's
* F.interpolate(x, size=(n, m), mode="bicubic", antialias=True) on the CPU float32 kernel,
* operation for operation, for the Unlimited-OCR DeepEncoder's position tables.
*
* The reference resamples two fixed tables (deepencoder.py):
* get_abs_pos_sam() permutes SAM's pos_embed [1,64,64,768] to (0,3,1,2), casts fp32 and
* interpolates to 40x40; get_abs_pos() takes CLIP position_embedding rows 1: as a 16x16 grid,
* interpolates to 10x10, and cats row 0 (cls) in front. Here the table is row-major [h, w, C]
* with C innermost and each of the C channels is interpolated over the (h, w) grid
* independently; the cls split/catenation is the caller's job.
*
* The float32 antialias path (upsample_bicubic2d_aa_kernel_impl ->
* upsample_separable_Nd_kernel_impl -> _compute_index_ranges_weights with antialias=true,
* aten/src/ATen/native/cpu/UpSampleKernel.cpp, torch v2.14.0) is mirrored operation for
* operation, scalar_t = float:
* per axis scale = (float)(in / out); support = scale >= 1 ? (interp_size/2) * scale =
* 2 * scale : 2; invscale = scale >= 1 ? 1 / scale : 1;
* the output-pixel centre center = scale * (i + 0.5f);
* the taps run over xmin = max((int64)(center - support + 0.5), 0) ..
* min((int64)(center + support + 0.5), in) - 1 -- truncating casts, so a negative
* start truncates toward zero before the clamp to 0; border taps are simply absent,
* the row normalization below absorbs the lost mass;
* each tap weight is aa_filter((j + xmin - center + 0.5) * invscale), the Keys cubic
* with a = -0.5 (torch's antialias filter is the Pillow-compatible -0.5 kernel; the
* -0.75 OpenCV-compatible one belongs to the non-antialias path);
* the axis weights are normalized by their float running sum total_w, exactly as
* _compute_indices_min_size_weights_aa divides wt_ptr[j] /= total_w;
* the resize is separable: the width pass over every input row first, then the height
* pass (the order upsample_separable_Nd_kernel_impl walks the dims), each tap
* accumulating acc = (float)(acc + w * v) in float.
* Golden-checked by tests/resample_golden.py (geometries 64->40, 24->20, 8->5, 16->10,
* 16x20->10x13, and both checkpoint tables).
*/
#pragma once
#ifndef RAD_RESAMPLE_H
#define RAD_RESAMPLE_H
#include <cmath>
#include <cstdint>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
namespace resample_detail {
/* aa_filter, the Keys cubic with a = -0.5 that torch's antialias path uses (the -0.75
* OpenCV-compatible kernel belongs to the non-antialias path), in float. */
inline float cubic_aa(float x) {
const float ax = std::fabs(x);
if (ax < 1.0f) return ((1.5f * ax - 2.5f) * ax) * ax + 1.0f;
if (ax < 2.0f) return (((-0.5f * ax + 2.5f) * ax - 4.0f) * ax) + 2.0f;
return 0.0f;
}
struct Axis {
int n = 0; /* tap slots per output pixel (max_interp_size) */
std::vector<int32_t> size; /* [out] taps this output pixel reads */
std::vector<int32_t> idx; /* [out*n] input index per tap (xmin + j) */
std::vector<float> w; /* [out*n] weights, normalized by the tap sum */
};
/* One axis of _compute_indices_min_size_weights_aa, float32 expression for expression. */
inline Axis make_axis(int in, int out) {
Axis a;
const float scale = (float)((double)in / (double)out);
const float support = scale >= 1.0f ? (float)(2.0 * (double)scale) : 2.0f;
const float invscale = scale >= 1.0f ? (float)(1.0 / (double)scale) : 1.0f;
a.n = (int)std::ceil((double)support) * 2 + 1; /* max_interp_size */
a.size.resize((size_t)out, 0);
a.idx.assign((size_t)out * (size_t)a.n, 0);
a.w.assign((size_t)out * (size_t)a.n, 0.0f);
for (int i = 0; i < out; ++i) {
const float c = ((float)i + 0.5f) * scale;
int xmin = (int)(c - support + 0.5f);
if (xmin < 0) xmin = 0;
int xsize = (int)(c + support + 0.5f);
if (xsize > in) xsize = in;
xsize -= xmin;
if (xsize < 0) xsize = 0;
/* ATen's own `xsize = min(xsize, n)`, kept for parity. It cannot bind here: with
* xmin > 0 the window spans 2*support + 1 taps, at most a.n = 2*ceil(support) + 1
* (the bound ATen sized the slots from), and with xmin == 0 it spans fewer. So the
* clamp is a no-op safety net, never a silent tap truncation. */
if (xsize > a.n) xsize = a.n;
int* idx = &a.idx[(size_t)i * (size_t)a.n];
float* w = &a.w[(size_t)i * (size_t)a.n];
float total = 0.0f;
for (int j = 0; j < xsize; ++j) {
w[j] = cubic_aa(((float)(xmin + j) - c + 0.5f) * invscale);
idx[j] = xmin + j;
total = (float)(total + w[j]);
}
a.size[i] = xsize;
if (total != 0.0f)
for (int j = 0; j < xsize; ++j) w[j] = (float)(w[j] / total);
}
return a;
}
/* One 1D resize pass. `rows` scans travel `src_row_stride` floats apart, taps step
* `tap_stride` floats along the resized axis, and outputs land at
* dst + r * dst_row_stride + i * out_stride + channel; tap order and float accumulation
* follow ATen's separable 1D resize. */
inline void resize_axis(const float* src, int64_t src_row_stride, int64_t tap_stride,
float* dst, int64_t dst_row_stride, int64_t out_stride, int rows,
const Axis& ax, int out_n, int channels) {
for (int r = 0; r < rows; ++r) {
const float* srow = src + (size_t)r * (size_t)src_row_stride;
float* drow = dst + (size_t)r * (size_t)dst_row_stride;
for (int i = 0; i < out_n; ++i) {
const int n = ax.size[i];
const int32_t* idx = &ax.idx[(size_t)i * (size_t)ax.n];
const float* w = &ax.w[(size_t)i * (size_t)ax.n];
for (int c = 0; c < channels; ++c) {
if (n == 0) { drow[(size_t)i * (size_t)out_stride + (size_t)c] = 0.0f; continue; }
float acc = (float)(srow[(size_t)idx[0] * (size_t)tap_stride + (size_t)c] * w[0]);
for (int j = 1; j < n; ++j)
acc = (float)(acc +
srow[(size_t)idx[j] * (size_t)tap_stride + (size_t)c] * w[j]);
drow[(size_t)i * (size_t)out_stride + (size_t)c] = acc;
}
}
}
}
} // namespace resample_detail
/* Resample an [in_h, in_w, channels] fp32 table (channels innermost) to
* [out_h, out_w, channels] with torch's bicubic + antialias interpolation: the width pass
* over every input row, then the height pass. Runs once at load. */
inline void resample_bicubic_aa(const float* src, int in_h, int in_w, int out_h, int out_w,
int channels, float* dst) {
if (!src || !dst || in_h <= 0 || in_w <= 0 || out_h <= 0 || out_w <= 0 || channels <= 0)
return;
if (in_h == out_h && in_w == out_w) {
std::memcpy(dst, src, (size_t)in_h * (size_t)in_w * (size_t)channels * sizeof(float));
return;
}
const resample_detail::Axis ay = resample_detail::make_axis(in_h, out_h);
const resample_detail::Axis ax = resample_detail::make_axis(in_w, out_w);
const float* work = src;
int work_w = in_w;
std::vector<float> wide;
if (in_w != out_w) { /* width pass first, the order upsample_separable_Nd walks the dims */
wide.assign((size_t)in_h * (size_t)out_w * (size_t)channels, 0.0f);
resample_detail::resize_axis(src, (int64_t)in_w * channels, channels, wide.data(),
(int64_t)out_w * channels, channels, in_h, ax, out_w,
channels);
work = wide.data();
work_w = out_w;
}
if (in_h == out_h) {
if (work != dst)
std::memcpy(dst, work, (size_t)out_h * (size_t)out_w * (size_t)channels * sizeof(float));
return;
}
/* height pass over the widened rows: one scan per output-width column */
resample_detail::resize_axis(work, channels, (int64_t)work_w * channels, dst, channels,
(int64_t)out_w * channels, work_w, ay, out_h, channels);
}
} // namespace arch
} // namespace rad
#endif // RAD_RESAMPLE_H
+430
View File
@@ -0,0 +1,430 @@
/* rad_vae2d.h -- an image VAE (encoder or decoder) as a recorded list of ops over NHWC images.
*
* Image size varies per request, so a VAE's ops are declared once for the largest image and issued
* with each pass's extents (`Vae::issue`). Qwen-Image 2.1's residual Wan-2.2 VAE, Qwen-Image's
* and Krea 2's Wan-2.1 one and FLUX's GroupNorm one are each a few lines of `conv`, `norm`,
* `resblock` and `attention` calls in their plugin.
*/
#pragma once
#include <arch/rad_arch.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <utility>
#include <vector>
namespace rad {
namespace arch {
/* ================================================================== the VAE as a recorded graph
*
* Image size varies per request, so the VAE's ops are declared once for the largest image and
* issued with the actual extents: every image operand is a raw [height, width * channels] view of
* its buffer (docs/OPS.md, "Image generation"), with extents from the pass's picture size and the
* stage's scale. `Vae` records each op with what it needs to rebuild its operands, so declare()
* and step() walk the same list.
*
* Every output is its own buffer, sized for its stage; the planner shares storage between those
* whose lives do not overlap, and no buffer is reused by hand. This is sound because ops are issued
* in declaration order. */
struct VImg {
rad_buf buf = 0;
int64_t ch = 0;
int lvl = 0; /* the side is the pass's base side times 2^lvl (decoder) or / 2^lvl (encoder) */
};
struct VOp {
enum Kind { CONV, NORM, ADD, D2S, S2D, ATTN, GNORM, LIN } kind = CONV;
rad_op op = 0;
VImg x{}, y{}, z{}; /* inputs x (and z for ADD), output y */
rad_weight w = 0, b = 0;
int k = 1, up = 1, stride = 1;
int64_t qkv_ch = 0; /* ATTN: x is the [*, 3C] qkv rows, y the [*, C] output */
};
/* What a checkpoint stores a VAE's convolutions as. */
enum VaeConvForm {
VAE_CONV_2D, /* [cout, cin, k, k] */
VAE_CONV_CAUSAL, /* a causal 3-D convolution [cout, cin, kt, k, k], run on one frame: its
* last temporal tap (RAD_MAP_TAP) */
};
struct Vae {
std::vector<VOp> ops;
Names* nm = nullptr;
RadBuilder* b = nullptr;
const char* scope = ""; /* "dec" or "enc" */
bool down = false; /* an encoder: a level halves the side */
int64_t base_px = 0; /* pixels at level 0, the largest any pass hands it */
int n_buf = 0;
int first_group = 0;
/* The banded tail. From op `band_from` on, every output pixel reads a bounded window of rows
* (3x3 convolutions, nearest upsampling, per-pixel norms and adds, depth-to-space shortcuts),
* so a rank can run the tail on its band of level-0 rows plus `halo` rows per side and get its
* band's pixels bit for bit: rows spoiled by a conv's zero padding at the band edge never reach
* the band. The ops before it include the mid-block's attention, which reads every pixel, and
* run whole; `whole` holds their outputs, read by the tail at the band's row offset. -1: no
* tail. */
int band_from = -1;
int64_t halo = 0;
std::vector<rad_buf> whole;
VaeConvForm form = VAE_CONV_2D;
/* group_norm's statistics scratch, one for every GroupNorm op (they run one after another). */
rad_buf gn_stats = 0;
int64_t px_at(int lvl) const {
int64_t p = base_px;
for (int i = 0; i < lvl; ++i) p = down ? (p + 3) / 4 : p * 4;
return p;
}
VImg img(int64_t ch, int lvl) {
VImg v;
v.ch = ch;
v.lvl = lvl;
v.buf = decl_b(b, nm->f("%s.t%d", scope, n_buf++), RAD_BF16, { px_at(lvl), ch });
return v;
}
rad_weight wt(const char* name, const char* src, std::initializer_list<int64_t> shape,
bool tap = false) {
if ((tap ? map_tap(b, name, src, 2, -1) : map_copy(b, name, src)) < 0) return 0;
return decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE,
grp_layer(first_group));
}
/* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */
VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad,
const char* ckpt) {
VOp o;
o.kind = VOp::CONV;
o.x = x;
o.up = up;
o.stride = stride;
int lvl = x.lvl;
if (up == 2) lvl = down ? lvl - 1 : lvl + 1;
if (stride == 2) lvl = down ? lvl + 1 : lvl - 1;
o.y = img(cout, lvl);
o.k = k;
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k },
form == VAE_CONV_CAUSAL);
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
o.op = RAD_OP(b, "conv2d_nhwc",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch),
RAD_INT("cout", cout), RAD_INT("k", k),
RAD_INT("stride", stride), RAD_STR("pad", pad),
RAD_INT("up", up), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b));
/* An input with no buffer is the picture the pass staged, read where it lies. */
if (x.buf) rw(b, o.op, { x.buf }, { o.y.buf });
else rw(b, o.op, {}, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* The channel norm, `silu` or not. `gamma` is [C, 1, 1(, 1)] in the checkpoint. */
VImg norm(const VImg& x, bool silu, const char* ckpt, int gamma_rank) {
VOp o;
o.kind = VOp::NORM;
o.x = x;
o.y = img(x.ch, x.lvl);
const char* dn = nm->f("%s.gamma", ckpt);
if (map_copy(b, dn, nm->ckpt("%s.gamma", ckpt)) < 0) return VImg{};
o.w = gamma_rank == 4
? decl_w(b, dn, RAD_BF16, { x.ch, 1, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group))
: decl_w(b, dn, RAD_BF16, { x.ch, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group));
o.op = rw(b, RAD_OP(b, "l2norm_chan",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_STR("act", silu ? "silu" : "none"),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w)),
{ x.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
VImg add(const VImg& x, const VImg& z) {
VOp o;
o.kind = VOp::ADD;
o.x = x;
o.z = z;
o.y = img(x.ch, x.lvl);
o.op = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x.buf, z.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* y += the resampling shortcut of x (in place on y). */
void shortcut(const VImg& x, const VImg& y, int ft) {
VOp o;
o.kind = down ? VOp::S2D : VOp::D2S;
o.x = x;
o.y = y;
o.up = ft;
o.op = rw(b, RAD_OP(b, down ? "s2d_avg_add" : "d2s_add",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(y.lvl)), RAD_INT("cin", x.ch),
RAD_INT("cout", y.ch), RAD_INT("ft", ft),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x.buf, y.buf }, { y.buf });
ops.push_back(o);
}
/* A residual block, in -> out channels. */
VImg resblock(const VImg& x, int64_t out, const char* ckpt) {
VImg h = x;
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
t = norm(t, true, nm->f("%s.norm2", ckpt), 4);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
return add(t, h);
}
/* The mid-block's single-head attention over every pixel. */
VImg attention(const VImg& x, const char* ckpt) {
const int64_t C = x.ch;
VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3);
VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt));
VOp o;
o.kind = VOp::ATTN;
o.x = qkv;
o.y = img(C, x.lvl);
o.qkv_ch = 3 * C;
o.op = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
RAD_NOWEIGHTS),
{ qkv.buf }, { o.y.buf });
ops.push_back(o);
VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt));
return add(p, x);
}
/* PyTorch's GroupNorm over the whole picture, `silu` or not (FLUX's VAE). Not row-local, so a
* VAE that has one runs whole (no banded tail). */
VImg gnorm(const VImg& x, bool silu, const char* ckpt, int64_t groups, double eps) {
VOp o;
o.kind = VOp::GNORM;
o.x = x;
o.y = img(x.ch, x.lvl);
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { x.ch });
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { x.ch });
if (!gn_stats)
gn_stats = decl_b(b, nm->f("%s.gn_stats", scope), RAD_F32, { 64 * (2 + 3 * 1024) });
o.k = (int)groups;
o.op = RAD_OP(b, "group_norm",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_INT("groups", groups), RAD_F64("eps", eps),
RAD_STR("act", silu ? "silu" : "none"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b));
rw(b, o.op, { x.buf, gn_stats }, { o.y.buf, gn_stats });
ops.push_back(o);
return o.y;
}
/* A per-pixel linear with a bias (a 1x1 convolution kept as a Linear): `cout` from x's
* channels. */
VImg lin(const VImg& x, int64_t cout, const char* ckpt) {
VOp o;
o.kind = VOp::LIN;
o.x = x;
o.y = img(cout, x.lvl);
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch });
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
o.op = rw(b, RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("N", cout),
RAD_INT("K", x.ch), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b)),
{ x.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* A GroupNorm residual block (FLUX's VAE, diffusers' ResnetBlock2D): norm1, silu, conv1,
* norm2, silu, conv2, plus the input or its 1x1 `conv_shortcut`. */
VImg resblock_gn(const VImg& x, int64_t out, const char* ckpt, int64_t groups, double eps) {
VImg h = x;
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
VImg t = gnorm(x, true, nm->f("%s.norm1", ckpt), groups, eps);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
t = gnorm(t, true, nm->f("%s.norm2", ckpt), groups, eps);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
return add(t, h);
}
/* diffusers' single-head VAE attention: GroupNorm, to_q / to_k / to_v linears with biases,
* attention over every pixel, to_out.0, plus the input. */
VImg attention_gn(const VImg& x, const char* ckpt, int64_t groups, double eps) {
const int64_t C = x.ch;
VImg t = gnorm(x, false, nm->f("%s.group_norm", ckpt), groups, eps);
VImg q = lin(t, C, nm->f("%s.to_q", ckpt));
VImg k = lin(t, C, nm->f("%s.to_k", ckpt));
VImg v = lin(t, C, nm->f("%s.to_v", ckpt));
VOp o;
o.kind = VOp::ATTN;
o.x = q;
o.y = img(C, x.lvl);
o.z = k;
o.w = 0;
o.qkv_ch = 0;
o.k = 0;
o.op = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
RAD_NOWEIGHTS),
{ q.buf, k.buf, v.buf }, { o.y.buf });
attn_v.push_back({ ops.size(), v });
ops.push_back(o);
VImg p = lin(o.y, C, nm->f("%s.to_out.0", ckpt));
return add(p, x);
}
/* The value image of each separate-projection attention, by op index. */
std::vector<std::pair<size_t, VImg>> attn_v;
const VImg* value_of(size_t i) const {
for (const auto& e : attn_v) if (e.first == i) return &e.second;
return nullptr;
}
/* The operands of op `o` for a pass whose level-0 picture is H0 x W0 pixels (or latent tokens,
* for the decoder), in the op's schema order, and its ranged value. */
static int64_t side(int64_t s0, int lvl, bool dn) {
int64_t s = s0;
for (int i = 0; i < lvl; ++i) s = dn ? s / 2 : s * 2;
return s;
}
/* Declares `cu`, a buffer of the plugin's, as read by every attention: issue() hands it to
* them. */
int attn_reads(rad_buf cu) const {
for (const VOp& o : ops)
if (o.kind == VOp::ATTN) RAD_ARCH_TRY(rad_op_reads(b, o.op, &cu, 1));
return RAD_OK;
}
/* `cu` is {0, pixels} at the attention's level -- the pass's latent tokens -- and `input` the
* level-0 picture when the first op reads one the pass staged. Ops [from, to) are issued; with
* `row0`, H0 is a band's rows and a `whole` buffer is read from its level-0 row `row0`. */
void issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, const void* input,
size_t from = 0, size_t to = (size_t)-1, int64_t row0 = 0) const;
bool is_whole(rad_buf v) const {
for (rad_buf w : whole) if (w == v) return true;
return false;
}
/* The tail's halo in level-0 rows: walked back from the last op, a buffer's margin is the most
* any reader of it needs, in its own rows -- a k x k conv adds k/2, reading through a 2x
* upsample halves it rounding up, and the depth-to-space shortcut halves it. -1 when the tail
* holds an op that is not row-local, or reads a whole buffer above level 0. */
int64_t band_halo() const {
if (band_from < 0 || ops.empty()) return -1;
std::vector<std::pair<rad_buf, int64_t>> need{ { ops.back().y.buf, 0 } };
auto get = [&](rad_buf v) -> int64_t {
for (const auto& e : need) if (e.first == v) return e.second;
return 0;
};
auto want = [&](rad_buf v, int64_t m) {
for (auto& e : need) if (e.first == v) { e.second = std::max(e.second, m); return; }
need.push_back({ v, m });
};
for (size_t i = ops.size(); i-- > (size_t)band_from;) {
const VOp& o = ops[i];
const int64_t my = get(o.y.buf);
switch (o.kind) {
case VOp::CONV: {
if (o.stride != 1) return -1;
const int64_t m = my + o.k / 2;
want(o.x.buf, o.up == 2 ? (m + 1) / 2 : m);
break;
}
case VOp::NORM: want(o.x.buf, my); break;
case VOp::LIN: want(o.x.buf, my); break;
case VOp::ADD: want(o.x.buf, my); want(o.z.buf, my); break;
case VOp::D2S: want(o.x.buf, (my + 1) / 2); break;
default: return -1;
}
}
int64_t h = 0;
for (size_t i = (size_t)band_from; i < ops.size(); ++i) {
const VOp& o = ops[i];
for (const VImg* v : { &o.x, &o.z })
if (v->buf && is_whole(v->buf)) {
if (v->lvl != 0) return -1;
h = std::max(h, get(v->buf));
}
}
return h;
}
};
inline void Vae::issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu,
const void* input, size_t from, size_t to, int64_t row0) const {
auto ptr = [&](const VImg& v) -> const void* {
if (!v.buf) return input;
const char* p = (const char*)rad_buf_ptr(c, v.buf);
return row0 && is_whole(v.buf) ? p + row0 * W0 * v.ch * (int64_t)sizeof(uint16_t) : p;
};
auto view = [&](const VImg& v, int64_t* H, int64_t* W) {
*H = side(H0, v.lvl, down);
*W = side(W0, v.lvl, down);
return RAD_P_T2(ptr(v), RAD_BF16, *H, *W * v.ch);
};
auto rows = [&](const VImg& v, int64_t cols) {
const int64_t H = side(H0, v.lvl, down), W = side(W0, v.lvl, down);
return RAD_P_T2(ptr(v), RAD_BF16, H * W * v.ch / cols, cols);
};
for (size_t i = from; i < to && i < ops.size(); ++i) {
const VOp& o = ops[i];
int64_t Hx, Wx, Hy, Wy;
switch (o.kind) {
case VOp::CONV: {
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
RAD_ISSUE_N(c, o.op, Hy * Wy, x, RAD_W(o.w), RAD_W(o.b), y);
break;
}
case VOp::NORM: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), rows(o.y, o.y.ch));
break;
}
case VOp::ADD: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), rows(o.z, o.z.ch), rows(o.y, o.y.ch));
break;
}
case VOp::D2S:
case VOp::S2D: {
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
RAD_ISSUE_N(c, o.op, Hy * Wy, x, y);
break;
}
case VOp::ATTN: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
const int64_t C = o.y.ch, n = H * W;
if (const VImg* v = value_of(i)) {
/* Separate q, k and v images. */
RAD_ISSUE_N(c, o.op, n, rows(o.x, C), rows(o.z, C), rows(*v, C), cu,
brows(o.y.buf, n));
} else {
/* q, k and v are column slices of the qkv rows, at its 3C pitch. */
RAD_ISSUE_N(c, o.op, n, bcol(o.x.buf, 0, C, n), bcol(o.x.buf, C, C, n),
bcol(o.x.buf, 2 * C, C, n), cu, brows(o.y.buf, n));
}
break;
}
case VOp::GNORM: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), RAD_W(o.b), RAD_NONE,
RAD_P_T2(rad_buf_ptr(c, gn_stats), RAD_F32, 1, 64 * (2 + 3 * 1024)),
rows(o.y, o.y.ch));
break;
}
case VOp::LIN: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), RAD_W(o.b), RAD_NONE,
rows(o.y, o.y.ch));
break;
}
}
}
}
} /* namespace arch */
} /* namespace rad */
+2 -3
View File
@@ -1,6 +1,5 @@
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
# radiance (`cmake -S arch/embgemma2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/embgemma2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(embgemma2 LANGUAGES CXX)
+54 -770
View File
@@ -1,11 +1,10 @@
/* embgemma2 -- EmbeddingGemma 2, a bidirectional Gemma encoder that pools a whole input into one
* vector. bf16 weights and bf16 activations.
*
* AN EMBEDDING MODEL, NOT A GENERATIVE ONE. It declares a pooled output (rad_declare_pooled) and
* no logits, so the engine runs it with no sampler and no KV cache, carries every input whole in
* one step and hands each sequence's pooled row back as its answer. Attention is BIDIRECTIONAL on
* every layer, which is why nothing is paged: a token attends to the tokens after it, so there is
* nothing a cache could carry from one step to the next.
* An embedding model: it declares a pooled output (rad_declare_pooled) and no logits, so the
* engine runs it with no sampler and no KV cache, carries every input whole in one step, and
* returns each sequence's pooled row. Attention is bidirectional on every layer, so nothing is
* paged: a token attends to later tokens, and there is nothing to carry between steps.
*
* ============================== THE SHAPE ==============================
*
@@ -13,27 +12,27 @@
* layer_types: five `sliding_attention` then one `full_attention`, four times over
* sliding: 4 heads / 2 kv heads / head_dim 256, rope theta 1e4, |i - j| <= 512
* full: 4 heads / 1 kv head / head_dim 512, rope theta 1e6, the whole input
* attention scale 1.0 (the q/k norms carry the temperature); q, k AND v are RMS-normed per head,
* attention scale 1.0 (the q/k norms carry the temperature); q, k and v are RMS-normed per head,
* v with no gain
* Gemma's sandwich norms: a norm before AND after attention and the feed-forward, all plain
* Gemma's sandwich norms: a norm before and after attention and the feed-forward, all plain
* RMSNorm gains (x_hat * w, not 1 + w)
* a gated gelu-tanh feed-forward
* PER-LAYER EMBEDDINGS, projection-only: the token embedding projected to 24 x 512, normed, and
* per-layer embeddings, projection-only: the token embedding projected to 24 x 512, normed, and
* each layer's slice gating that layer's residual through a 512 -> 512 -> 512 bottleneck
* a learned scalar per layer, multiplying the residual stream at the layer's end
* final norm, then the mean over every token of the input, then 512 -> 768
*
* The reference is transformers' modeling_embedding_gemma2 (model_type embedding_gemma2, which
* rad-convert spells `embeddinggemma2`). Its mean pooling and normalisation are
* sentence-transformers' modules on top; the normalisation is the server's (it truncates to
* sentence-transformers' modules on top; normalisation is the server's (it truncates to
* `dimensions` first), so the pooled row here is the unnormalised mean.
*
* ============================== WHAT THIS PLUGIN DOES NOT YET DECLARE ==============================
*
* Nothing the checkpoint carries: the text model, the vision tower and the audio encoder are all
* below.
* Everything the checkpoint carries is declared: the text model, the vision tower
* (rad_block_gemma4_vision.h) and the audio encoder (rad_block_gemma4_audio.h).
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_gemma4_audio.h>
#include <arch/rad_block_gemma4_vision.h>
#include <cmath>
#include <cstdint>
@@ -67,713 +66,6 @@ struct Layer {
rad_op op_post_ple = 0, op_add_ple = 0, op_scale = 0;
};
/* ============================== THE VISION TOWER (Gemma 4's) ==============================
*
* a patch is 16 x 16 x 3, staged by the processor as 2 * (u / 255) - 1 in bf16, (y, x, channel)
* patch embedding: a 768 x 768 linear, plus a learned row for the patch's column and one for its
* row (a [2, 10240, 768] table), the two summed first
* 16 layers: Gemma's sandwich norms, q/k RMS-normed with a gain and v without one, a 2-D rotary
* (theta 100) with x over the first half of each 64-wide head and y over the second, each half a
* rotary of its own; bidirectional attention within an image at scale 1; a gated gelu-tanh MLP
* pooling: the mean of each 3 x 3 window -- the processor lays a window's nine patches out
* consecutively -- times sqrt(768), then the multimodal embedder: an RMS norm with no gain and a
* 768 -> 512 linear. Its rows take the place of the image's placeholder tokens BEFORE the
* per-layer inputs are projected, so the per-layer inputs of an image token are its image row's.
*
* One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an
* image, or one frame of a video). */
struct Vision {
struct Layer {
rad_weight in_norm = 0, qkv = 0, q_norm = 0, k_norm = 0, o = 0, post_attn = 0;
rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0;
rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0;
};
bool on = false;
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
int64_t npos = 0, n_embd = 0;
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0;
rad_op op_patch = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0, op_pool = 0, op_norm = 0;
rad_op op_out = 0;
rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_px = 0,
b_py = 0, b_pool = 0, b_pn = 0, b_out = 0;
std::vector<Layer> L;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
return t && !std::strcmp(t, "gemma4_vision");
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
hd = rad_meta_geti(m, "vision_config.head_dim", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
pool = rad_meta_geti(m, "vision_config.pooling_kernel_size", 0);
npos = rad_meta_geti(m, "vision_config.position_embedding_size", 0);
const int64_t depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
const int64_t patch = rad_meta_geti(m, "vision_config.patch_size", 0);
const int64_t kvh = rad_meta_geti(m, "vision_config.num_key_value_heads", heads);
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
const double theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 0.0);
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "");
const char* act = rad_meta_gets(m, "vision_config.hidden_activation", "");
if (width <= 0 || heads <= 0 || hd <= 0 || ff <= 0 || pool <= 0 || npos <= 0 ||
depth <= 0 || patch <= 0 || !(theta > 0) || heads * hd != width || kvh != heads ||
hd % 4) {
fprintf(stderr, "radiance: embgemma2: the container's vision_config is incomplete or "
"not the shape this plugin serves (hidden %lld, heads %lld x %lld, kv "
"%lld, ff %lld, pooling %lld, layers %lld)\n", (long long)width,
(long long)heads, (long long)hd, (long long)kvh, (long long)ff,
(long long)pool, (long long)depth);
return RAD_E_INVAL;
}
/* What this tower does not carry is refused by name: clipped linears (their bounds are
* buffers the vision checkpoint states as infinite), feature standardisation, and any
* rotary or activation other than the axial one and gelu-tanh. */
if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
rad_meta_geti(m, "vision_config.standardize", 0) || std::strcmp(rt, "axial") ||
std::strcmp(act, "gelu_pytorch_tanh")) {
fprintf(stderr, "radiance: embgemma2: this vision tower uses clipped linears, "
"standardisation, a '%s' rotary or a '%s' activation, which this "
"plugin does not serve\n", rt, act);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
patch_dim = 3 * patch * patch;
const int64_t kk = pool * pool;
P = ctx->max_enc_patches;
if (P % kk) P -= P % kk;
R = P / kk;
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
const char* V = "vision_tower";
/* ---- weights: the stem, the position tables and the embedder are model-level; each
* tower layer is its own group, past every text layer. */
RAD_ARCH_TRY(map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.patch_embedder.input_proj.weight", V)));
RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_x.weight"),
nm.ckpt("%s.patch_embedder.position_embedding_table", V), 0));
RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_y.weight"),
nm.ckpt("%s.patch_embedder.position_embedding_table", V), 1));
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("embed_vision.embedding_projection.weight")));
w_in = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const long long li = (long long)i;
const RadWeightGroup g = grp_layer(first_group + (int)i);
auto src = [&](const char* s) { return nm.ckpt("%s.encoder.layers.%lld.%s", V, li, s); };
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.in_norm", li), src("input_layernorm.weight")));
RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.qkv", li),
{src("self_attn.q_proj.linear.weight"),
src("self_attn.k_proj.linear.weight"),
src("self_attn.v_proj.linear.weight")}));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.q_norm", li), src("self_attn.q_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.k_norm", li), src("self_attn.k_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.o", li), src("self_attn.o_proj.linear.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_attn", li), src("post_attention_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.pre_ff", li), src("pre_feedforward_layernorm.weight")));
RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.gate_up", li),
{src("mlp.gate_proj.linear.weight"),
src("mlp.up_proj.linear.weight")}));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.down", li), src("mlp.down_proj.linear.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_ff", li), src("post_feedforward_layernorm.weight")));
l.in_norm = decl_w(b, nm.f("v.blk.%lld.in_norm", li), RAD_BF16, {width}, A, N, g);
l.qkv = decl_w(b, nm.f("v.blk.%lld.qkv", li), RAD_BF16, {3 * width, width}, A, N, g);
l.q_norm = decl_w(b, nm.f("v.blk.%lld.q_norm", li), RAD_BF16, {hd}, A, N, g);
l.k_norm = decl_w(b, nm.f("v.blk.%lld.k_norm", li), RAD_BF16, {hd}, A, N, g);
l.o = decl_w(b, nm.f("v.blk.%lld.o", li), RAD_BF16, {width, width}, A, N, g);
l.post_attn = decl_w(b, nm.f("v.blk.%lld.post_attn", li), RAD_BF16, {width}, A, N, g);
l.pre_ff = decl_w(b, nm.f("v.blk.%lld.pre_ff", li), RAD_BF16, {width}, A, N, g);
l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g);
l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g);
l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g);
}
/* ---- activations, sized by the pass. */
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width});
b_o = decl_b(b, nm.f("v.o"), RAD_BF16, {P, width});
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, {P, 3 * width});
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, {P, width});
b_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, {P, 2 * ff});
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, {P, ff});
b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width});
b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width});
b_pool = decl_b(b, nm.f("v.pool"), RAD_BF16, {R, width});
b_pn = decl_b(b, nm.f("v.pn"), RAD_BF16, {R, width});
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {R, n_embd});
auto rms = [&](int64_t rows, rad_weight w) {
if (!w)
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight w) {
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto add = [&](int64_t rows) {
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
auto lookup = [&](rad_weight w) {
return RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
RAD_WEIGHTS(w));
};
op_patch = rw(b, gemm(P, width, patch_dim, w_in), {}, {b_x});
op_px = rw(b, lookup(w_px), {}, {b_px});
op_py = rw(b, lookup(w_py), {}, {b_py});
op_padd = rw(b, add(P), {b_px, b_py}, {b_px});
op_add = rw(b, add(P), {b_x, b_px}, {b_x});
char sec[48];
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
for (Layer& l : L) {
l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h});
l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv});
/* x is the column (plane 1 of the staged coordinates), y the row (plane 0). */
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
RAD_F64("theta", theta), RAD_F64("eps", eps),
RAD_STR("mode", "blocks"), RAD_INT("v_norm", 1),
RAD_STR("sections", sec), RAD_STR("comps", "1 0")),
RAD_WEIGHTS(l.q_norm, l.k_norm)),
{b_qkv}, {b_qkv});
l.op_attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"), RAD_F64("scale", 1.0),
RAD_INT("max_seqlen", P), RAD_INT("window", 0)),
RAD_NOWEIGHTS),
{b_qkv}, {b_att});
l.op_o = rw(b, gemm(P, width, width, l.o), {b_att}, {b_o});
l.op_pa = rw(b, rms(P, l.post_attn), {b_o}, {b_o});
l.op_add1 = rw(b, add(P), {b_x, b_o}, {b_x});
l.op_pf = rw(b, rms(P, l.pre_ff), {b_x}, {b_h});
l.op_gu = rw(b, gemm(P, 2 * ff, width, l.gate_up), {b_h}, {b_gu});
l.op_act = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff),
RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_gu}, {b_ff});
l.op_down = rw(b, gemm(P, width, ff, l.down), {b_ff}, {b_o});
l.op_pff = rw(b, rms(P, l.post_ff), {b_o}, {b_o});
l.op_add2 = rw(b, add(P), {b_x, b_o}, {b_x});
}
op_pool = rw(b, RAD_OP(b, "pool_rows",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("k", kk), RAD_F64("mult", std::sqrt((double)width)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_x}, {b_pool});
op_norm = rw(b, rms(R, 0), {b_pool}, {b_pn});
op_out = rw(b, gemm(R, n_embd, width, w_proj), {b_pn}, {b_out});
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = kk;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"pooled %lldx%lld; %lld patches a pass -> %lld rows of %lld",
(long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff,
(long long)patch, (long long)pool, (long long)pool, (long long)P, (long long)R,
(long long)n_embd);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg, kk = pool * pool;
if (!on || Pn <= 0 || Pn > P || Pn % kk || S <= 0) {
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, "
"more patches than it was declared for, or not whole pooling windows");
return;
}
const int64_t Rn = Pn / kk;
const int32_t* crd = batch->enc_coord;
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand rc = praw2(crd, RAD_I32, 2, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_in), brows(b_x, Pn));
RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn));
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn));
RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn));
RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn),
brows(b_ff, Pn));
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
}
RAD_ISSUE_N(c, op_pool, Pn, brows(b_x, Pn), brows(b_pool, Rn));
RAD_ISSUE_N(c, op_norm, Rn, brows(b_pool, Rn), RAD_NONE, brows(b_pn, Rn));
RAD_ISSUE_N(c, op_out, Rn, brows(b_pn, Rn), RAD_W(w_proj), brows(b_out, Rn));
}
};
/* ============================== THE AUDIO ENCODER (Gemma 4's USM conformer) ==============================
*
* a frame is 128 log-mel bins (the processor's), four frames an output row
* subsampling: two 3x3 stride-2 convolutions over (time, frequency) -- 1 -> 128 -> 32 channels,
* each input masked to the clip's real frames first, each followed by a channel LayerNorm (no
* bias) and a ReLU -- then 32 x 32 features a row through a 1024 linear
* 12 conformer blocks: a feed-forward at half weight, local attention (11 frames back, a
* relative-position term, a softplus per-dimension query scale, a softcap of 50), a gated
* depthwise causal convolution, a second half-weight feed-forward, a norm; their linears are
* CLIPPED, input and output clamped to bounds the checkpoint stores
* 1024 -> 1536 with a bias, then the multimodal embedder: an RMS norm with no gain, 1536 -> 512.
*
* The blocks' clamps at +-1e10 ("gradient clipping") are left out: they bound activations ten
* orders of magnitude past anything bf16 holds near them, so they change nothing a pass computes.
* One clip is one segment; a pass carries up to RadBuildCtx::max_audio_frames frames. */
struct Audio {
/* A clipped linear: the weight and its four bounds. */
struct Clip {
rad_weight w = 0, in_lo = 0, in_hi = 0, out_lo = 0, out_hi = 0;
rad_op op_in = 0, op_mm = 0, op_out = 0;
};
struct FF {
rad_weight pre = 0, post = 0;
Clip l1, l2;
rad_op op_pre = 0, op_act = 0, op_post = 0, op_add = 0;
};
struct Layer {
FF ff1, ff2;
rad_weight n_pre_attn = 0, n_post_attn = 0, n_out = 0, w_rel = 0, pds = 0;
Clip q, k, v, post;
rad_weight lc_pre = 0, lc_dw = 0, lc_norm = 0;
Clip lc_start, lc_end;
rad_op op_npa = 0, op_rel = 0, op_attn = 0, op_npo = 0, op_add_attn = 0;
rad_op op_lc_pre = 0, op_glu = 0, op_dw = 0, op_lc_norm = 0, op_lc_act = 0, op_lc_add = 0;
rad_op op_out = 0;
};
bool on = false;
int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffw = 0, n_embd = 0, out_dims = 0;
int64_t c0 = 0, c1 = 0, nmel = 0, merge = 4, left = 0, chunk = 0, n_rel = 0;
double eps = 1e-6, softcap = 0;
rad_weight w_c0 = 0, w_c1 = 0, w_n0 = 0, w_n1 = 0, w_in = 0, w_out = 0, b_outw = 0, w_emb = 0;
rad_op op_c0 = 0, op_n0 = 0, op_r0 = 0, op_c1 = 0, op_n1 = 0, op_r1 = 0, op_in = 0;
rad_op op_relpos = 0, op_outp = 0, op_en = 0, op_emb = 0;
rad_buf b_s0 = 0, b_s1 = 0, b_x = 0, b_h = 0, b_hc = 0, b_f = 0, b_q = 0, b_k = 0, b_v = 0;
rad_buf b_att = 0, b_o = 0, b_g = 0, b_u = 0, b_relpos = 0, b_relk = 0, b_o2 = 0, b_on = 0;
rad_buf b_out = 0;
std::vector<Layer> L;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
return t && !std::strcmp(t, "gemma4_audio");
}
/* The longest clip in frames: 30 s at the extractor's 10 ms hop, rounded up to whole rows. */
static int64_t frames_for(const RadModelMeta* m) {
const int64_t rate = rad_meta_geti(m, "preprocessor.sampling_rate", 16000);
const int64_t fl = rad_meta_geti(m, "preprocessor.frame_length", 320);
const int64_t hop = rad_meta_geti(m, "preprocessor.hop_length", 160);
if (rate <= 0 || hop <= 0) return 0;
const int64_t n = 30 * rate;
const int64_t real = (n + fl / 2 - fl - 1) / hop + 1;
return (real + 3) / 4 * 4;
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group) {
on = false;
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
const char* A = "audio_config";
auto gi = [&](const char* k, int64_t d) {
char key[96];
std::snprintf(key, sizeof key, "%s.%s", A, k);
return rad_meta_geti(m, key, d);
};
auto gf = [&](const char* k, double d) {
char key[96];
std::snprintf(key, sizeof key, "%s.%s", A, k);
return rad_meta_getf(m, key, d);
};
H = gi("hidden_size", 0);
heads = gi("num_attention_heads", 0);
out_dims = gi("output_proj_dims", 0);
chunk = gi("attention_chunk_size", 0);
/* transformers masks a key unless 0 <= q - k < attention_context_left - 1, so the
* furthest key back is context_left - 2 frames: 11 for this checkpoint, the query and
* eleven before it. */
left = gi("attention_context_left", 0) - 2;
softcap = gf("attention_logit_cap", 0.0);
eps = gf("rms_norm_eps", 1e-6);
const int64_t depth = gi("num_hidden_layers", 0);
const int64_t kconv = gi("conv_kernel_size", 0);
const int64_t right = gi("attention_context_right", 0);
const double resw = gf("residual_weight", 0.0);
const char* act = rad_meta_gets(m, "audio_config.hidden_act", "");
const char* chs = rad_meta_gets(m, "audio_config.subsampling_conv_channels", "");
nmel = rad_meta_geti(m, "preprocessor.feature_size", 0);
if (std::sscanf(chs ? chs : "", "%lld %lld", (long long*)&c0, (long long*)&c1) != 2)
c0 = c1 = 0;
hd = heads > 0 ? H / heads : 0;
ffw = 4 * H;
n_rel = left + 1;
if (H <= 0 || heads <= 0 || hd * heads != H || out_dims <= 0 || depth <= 0 || kconv <= 0 ||
chunk <= 0 || left < 0 || right != 0 || !(softcap > 0) || resw != 0.5 ||
std::strcmp(act ? act : "", "silu") || c0 <= 0 || c1 <= 0 || nmel != 128 ||
(nmel / 4) * c1 != H) {
fprintf(stderr, "radiance: embgemma2: the container's audio_config is not the "
"conformer this plugin serves (hidden %lld, heads %lld, output %lld, "
"layers %lld, conv %lld, left %lld right %lld, residual %g, act %s, "
"subsampling %lld/%lld over %lld bins)\n", (long long)H,
(long long)heads, (long long)out_dims, (long long)depth, (long long)kconv,
(long long)left, (long long)right, resw, act ? act : "", (long long)c0,
(long long)c1, (long long)nmel);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
P = ctx->max_audio_frames;
if (P % merge) return RAD_E_SHAPE;
R = P / merge;
const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
const char* T = "audio_tower";
/* ---- weights */
auto w = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
RadWeightGroup g) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
};
auto clip = [&](Clip& c, const char* dn, const char* src, int64_t out, int64_t in,
RadWeightGroup g) {
char d1[160], s1[200];
std::snprintf(d1, sizeof d1, "%s.w", dn); std::snprintf(s1, sizeof s1, "%s.linear.weight", src);
c.w = w(nm.f("%s", d1), nm.ckpt("%s", s1), {out, in}, g);
const char* bn[4] = { "input_min", "input_max", "output_min", "output_max" };
rad_weight* dst[4] = { &c.in_lo, &c.in_hi, &c.out_lo, &c.out_hi };
for (int i = 0; i < 4; ++i) {
std::snprintf(d1, sizeof d1, "%s.%s", dn, bn[i]);
std::snprintf(s1, sizeof s1, "%s.%s", src, bn[i]);
*dst[i] = w(nm.f("%s", d1), nm.ckpt("%s", s1), {1}, g);
}
};
w_c0 = w(nm.f("a.sscp.c0"), nm.ckpt("%s.subsample_conv_projection.layer0.conv.weight", T), {c0, 1, 3, 3}, grp_model());
w_n0 = w(nm.f("a.sscp.n0"), nm.ckpt("%s.subsample_conv_projection.layer0.norm.weight", T), {c0}, grp_model());
w_c1 = w(nm.f("a.sscp.c1"), nm.ckpt("%s.subsample_conv_projection.layer1.conv.weight", T), {c1, c0, 3, 3}, grp_model());
w_n1 = w(nm.f("a.sscp.n1"), nm.ckpt("%s.subsample_conv_projection.layer1.norm.weight", T), {c1}, grp_model());
w_in = w(nm.f("a.sscp.proj"), nm.ckpt("%s.subsample_conv_projection.input_proj_linear.weight", T), {H, H}, grp_model());
w_out = w(nm.f("a.out.w"), nm.ckpt("%s.output_proj.weight", T), {out_dims, H}, grp_model());
b_outw = w(nm.f("a.out.b"), nm.ckpt("%s.output_proj.bias", T), {out_dims}, grp_model());
w_emb = w(nm.f("a.embed"), nm.ckpt("embed_audio.embedding_projection.weight"), {n_embd, out_dims}, grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const long long li = (long long)i;
const RadWeightGroup g = grp_layer(first_group + (int)i);
char d[96], s[160];
auto D = [&](const char* x) { std::snprintf(d, sizeof d, "a.blk.%lld.%s", li, x); return nm.f("%s", d); };
auto S = [&](const char* x) { std::snprintf(s, sizeof s, "%s.layers.%lld.%s", T, li, x); return nm.ckpt("%s", s); };
for (int f = 0; f < 2; ++f) {
FF& ff = f ? l.ff2 : l.ff1;
const char* fn = f ? "feed_forward2" : "feed_forward1";
char px[64]; std::snprintf(px, sizeof px, "%s.pre_layer_norm.weight", fn);
ff.pre = w(D(px), S(px), {H}, g);
std::snprintf(px, sizeof px, "%s.post_layer_norm.weight", fn);
ff.post = w(D(px), S(px), {H}, g);
char dn[96], sn[160];
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l1", li, fn);
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_1", T, li, fn);
clip(ff.l1, dn, sn, ffw, H, g);
std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l2", li, fn);
std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_2", T, li, fn);
clip(ff.l2, dn, sn, H, ffw, g);
}
l.n_pre_attn = w(D("norm_pre_attn"), S("norm_pre_attn.weight"), {H}, g);
l.n_post_attn = w(D("norm_post_attn"), S("norm_post_attn.weight"), {H}, g);
l.n_out = w(D("norm_out"), S("norm_out.weight"), {H}, g);
l.w_rel = w(D("rel_k"), S("self_attn.relative_k_proj.weight"), {H, H}, g);
l.pds = w(D("per_dim_scale"), S("self_attn.per_dim_scale"), {hd}, g);
const char* qn[4] = { "q_proj", "k_proj", "v_proj", "post" };
Clip* qc[4] = { &l.q, &l.k, &l.v, &l.post };
for (int j = 0; j < 4; ++j) {
char dn[96], sn[160];
std::snprintf(dn, sizeof dn, "a.blk.%lld.attn.%s", li, qn[j]);
std::snprintf(sn, sizeof sn, "%s.layers.%lld.self_attn.%s", T, li, qn[j]);
clip(*qc[j], dn, sn, H, H, g);
}
l.lc_pre = w(D("lconv.pre"), S("lconv1d.pre_layer_norm.weight"), {H}, g);
l.lc_dw = w(D("lconv.dw"), S("lconv1d.depthwise_conv1d.weight"), {H, 1, kconv}, g);
l.lc_norm = w(D("lconv.norm"), S("lconv1d.conv_norm.weight"), {H}, g);
{
char dn[96], sn[160];
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.start", li);
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_start", T, li);
clip(l.lc_start, dn, sn, 2 * H, H, g);
std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.end", li);
std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_end", T, li);
clip(l.lc_end, dn, sn, H, H, g);
}
}
/* ---- activations: the subsampler's planes at their own widths, the blocks' at R rows */
b_s0 = decl_b(b, nm.f("a.s0"), RAD_BF16, {P / 2, (nmel / 2) * c0});
b_s1 = decl_b(b, nm.f("a.s1"), RAD_BF16, {R, (nmel / 4) * c1});
b_x = decl_b(b, nm.f("a.x"), RAD_BF16, {R, H});
b_h = decl_b(b, nm.f("a.h"), RAD_BF16, {R, H});
b_hc = decl_b(b, nm.f("a.hc"), RAD_BF16, {R, H});
b_f = decl_b(b, nm.f("a.f"), RAD_BF16, {R, ffw});
b_q = decl_b(b, nm.f("a.q"), RAD_BF16, {R, H});
b_k = decl_b(b, nm.f("a.k"), RAD_BF16, {R, H});
b_v = decl_b(b, nm.f("a.v"), RAD_BF16, {R, H});
b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H});
b_o = decl_b(b, nm.f("a.o"), RAD_BF16, {R, H});
b_g = decl_b(b, nm.f("a.g"), RAD_BF16, {R, 2 * H});
b_u = decl_b(b, nm.f("a.u"), RAD_BF16, {R, H});
b_relpos = decl_b(b, nm.f("a.relpos"), RAD_BF16, {n_rel, H});
b_relk = decl_b(b, nm.f("a.relk"), RAD_BF16, {n_rel, H});
b_o2 = decl_b(b, nm.f("a.o2"), RAD_BF16, {R, out_dims});
b_on = decl_b(b, nm.f("a.on"), RAD_BF16, {R, out_dims});
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd});
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight wt) {
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(wt));
};
auto rms = [&](int64_t rows, int64_t n, rad_weight wt, double mult) {
if (!wt)
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16"), RAD_F64("mult", mult)),
RAD_WEIGHTS(wt));
};
auto clamp = [&](int64_t rows, int64_t n, rad_weight lo, rad_weight hi) {
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(lo, hi));
};
auto unary = [&](const char* op, int64_t rows, int64_t n) {
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
auto add = [&](int64_t rows, int64_t n) { return unary("add", rows, n); };
auto lnorm = [&](int64_t rows, int64_t n, rad_weight g) {
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(g));
};
auto conv = [&](int64_t rows, int64_t width, int64_t ci, int64_t co, int64_t cu_div,
int64_t vstride, rad_weight wt) {
return RAD_OP(b, "conv2d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width),
RAD_INT("cin", ci), RAD_INT("cout", co),
RAD_INT("kh", 3), RAD_INT("kw", 3),
RAD_INT("stride", 2), RAD_INT("pad", 1),
RAD_INT("cu_div", cu_div),
RAD_INT("valid_stride", vstride),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(wt));
};
/* A clipped linear over rows of `in` into `out`: the input clamp writes a copy (the input
* is shared by the projections it feeds, each with its own bounds), the output clamp is in
* place. The copy is a whole [R, n_in] buffer: a GEMM's input must be contiguous, and a
* column slice of a wider one is not. */
auto clipped = [&](Clip& c, int64_t n_out, int64_t n_in, rad_buf in, rad_buf tmp,
rad_buf out) {
c.op_in = rw(b, clamp(R, n_in, c.in_lo, c.in_hi), {in}, {tmp});
c.op_mm = rw(b, gemm(R, n_out, n_in, c.w), {tmp}, {out});
c.op_out = rw(b, clamp(R, n_out, c.out_lo, c.out_hi), {out}, {out});
};
op_c0 = rw(b, conv(P, nmel, 1, c0, 1, 1, w_c0), {}, {b_s0});
op_n0 = rw(b, lnorm(P / 2 * (nmel / 2), c0, w_n0), {b_s0}, {b_s0});
op_r0 = rw(b, unary("relu", P / 2 * (nmel / 2), c0), {b_s0}, {b_s0});
op_c1 = rw(b, conv(P / 2, nmel / 2, c0, c1, 2, 2, w_c1), {b_s0}, {b_s1});
op_n1 = rw(b, lnorm(R * (nmel / 4), c1, w_n1), {b_s1}, {b_s1});
op_r1 = rw(b, unary("relu", R * (nmel / 4), c1), {b_s1}, {b_s1});
op_in = rw(b, gemm(R, H, H, w_in), {b_s1}, {b_x});
op_relpos = rw(b, RAD_OP(b, "rel_sinusoid",
RAD_PARAMS(RAD_RANGE("M", 1, n_rel), RAD_INT("n", H),
RAD_F64("max_timescale", 10000.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{}, {b_relpos});
for (Layer& l : L) {
auto ffw_block = [&](FF& ff) {
ff.op_pre = rw(b, rms(R, H, ff.pre, 1.0), {b_x}, {b_h});
clipped(ff.l1, ffw, H, b_h, b_hc, b_f);
ff.op_act = rw(b, unary("silu", R, ffw), {b_f}, {b_f});
/* the activation's only reader is this linear, so its clamp is in place */
clipped(ff.l2, H, ffw, b_f, b_f, b_o);
ff.op_post = rw(b, rms(R, H, ff.post, 0.5), {b_o}, {b_o});
ff.op_add = rw(b, add(R, H), {b_x, b_o}, {b_x});
};
ffw_block(l.ff1);
l.op_npa = rw(b, rms(R, H, l.n_pre_attn, 1.0), {b_x}, {b_h});
clipped(l.q, H, H, b_h, b_hc, b_q);
clipped(l.k, H, H, b_h, b_hc, b_k);
clipped(l.v, H, H, b_h, b_hc, b_v);
l.op_rel = rw(b, gemm(n_rel, H, H, l.w_rel), {b_relpos}, {b_relk});
l.op_attn = rw(b, RAD_OP(b, "attn_local_rel",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd),
RAD_INT("n_head", heads), RAD_INT("left", left),
RAD_INT("right", 0), RAD_F64("softcap", softcap),
RAD_INT("cu_div", merge), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(l.pds)),
{b_q, b_k, b_v, b_relk}, {b_att});
clipped(l.post, H, H, b_att, b_hc, b_o);
l.op_npo = rw(b, rms(R, H, l.n_post_attn, 1.0), {b_o}, {b_o});
l.op_add_attn = rw(b, add(R, H), {b_x, b_o}, {b_x});
l.op_lc_pre = rw(b, rms(R, H, l.lc_pre, 1.0), {b_x}, {b_h});
clipped(l.lc_start, 2 * H, H, b_h, b_hc, b_g);
/* GLU: the first half times the sigmoid of the second. */
l.op_glu = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_g}, {b_u});
l.op_dw = rw(b, RAD_OP(b, "conv1d_dw",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
RAD_INT("k", kconv), RAD_INT("cu_div", merge),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(l.lc_dw)),
{b_u}, {b_o});
l.op_lc_norm = rw(b, rms(R, H, l.lc_norm, 1.0), {b_o}, {b_o});
l.op_lc_act = rw(b, unary("silu", R, H), {b_o}, {b_o});
clipped(l.lc_end, H, H, b_o, b_hc, b_u);
l.op_lc_add = rw(b, add(R, H), {b_x, b_u}, {b_x});
ffw_block(l.ff2);
l.op_out = rw(b, rms(R, H, l.n_out, 1.0), {b_x}, {b_x});
}
op_outp = rw(b, RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", out_dims),
RAD_INT("K", H), RAD_STR("dtype", "bf16"),
RAD_STR("act", "none")),
RAD_WEIGHTS(w_out, b_outw)),
{b_x}, {b_o2});
op_en = rw(b, rms(R, out_dims, 0, 1.0), {b_o2}, {b_on});
op_emb = rw(b, gemm(R, n_embd, out_dims, w_emb), {b_on}, {b_out});
RadEncoderDecl e{};
e.name = "audio";
e.modalities = RAD_MM_AUDIO;
e.patch_dim = nmel;
e.merge = merge;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "audio encoder: %lld conformer blocks of %lld (%lld heads x %lld), "
"subsampling %lld/%lld channels, local attention %lld back; %lld frames a "
"pass -> %lld rows of %lld", (long long)depth, (long long)H, (long long)heads,
(long long)hd, (long long)c0, (long long)c1, (long long)left, (long long)P,
(long long)R, (long long)n_embd);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
if (!on || Pn <= 0 || Pn > P || Pn % merge || S <= 0) {
rad_step_fail(c, "an audio pass this program's audio encoder cannot serve: none "
"declared, more frames than it was declared for, or not whole rows");
return;
}
const int64_t Rn = Pn / merge;
const int32_t* crd = batch->enc_coord;
const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel);
const RadOperand valid = praw(crd + Pn, RAD_I32, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
auto clipped = [&](const Clip& cl, rad_buf in, int64_t n_in, rad_buf tmp, rad_buf out,
int64_t n_out) {
RAD_ISSUE_N(c, cl.op_in, Rn, bcol(in, 0, n_in, Rn), RAD_W(cl.in_lo), RAD_W(cl.in_hi),
bcol(tmp, 0, n_in, Rn));
RAD_ISSUE_N(c, cl.op_mm, Rn, bcol(tmp, 0, n_in, Rn), RAD_W(cl.w), bcol(out, 0, n_out, Rn));
RAD_ISSUE_N(c, cl.op_out, Rn, bcol(out, 0, n_out, Rn), RAD_W(cl.out_lo), RAD_W(cl.out_hi),
bcol(out, 0, n_out, Rn));
};
RAD_ISSUE_N(c, op_c0, Pn, frames, RAD_W(w_c0), cu, valid, brows(b_s0, Pn / 2));
RAD_ISSUE_N(c, op_n0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), RAD_W(w_n0), RAD_NONE,
brows(b_s0, Pn / 2));
RAD_ISSUE_N(c, op_r0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), brows(b_s0, Pn / 2));
RAD_ISSUE_N(c, op_c1, Pn / 2, brows(b_s0, Pn / 2), RAD_W(w_c1), cu, valid, brows(b_s1, Rn));
RAD_ISSUE_N(c, op_n1, Rn * (nmel / 4), brows(b_s1, Rn), RAD_W(w_n1), RAD_NONE,
brows(b_s1, Rn));
RAD_ISSUE_N(c, op_r1, Rn * (nmel / 4), brows(b_s1, Rn), brows(b_s1, Rn));
RAD_ISSUE_N(c, op_in, Rn, brows(b_s1, Rn), RAD_W(w_in), brows(b_x, Rn));
RAD_ISSUE_N(c, op_relpos, n_rel, brows(b_relpos, n_rel));
for (const Layer& l : L) {
auto ffw_block = [&](const FF& ff) {
RAD_ISSUE_N(c, ff.op_pre, Rn, brows(b_x, Rn), RAD_W(ff.pre), brows(b_h, Rn));
clipped(ff.l1, b_h, H, b_hc, b_f, ffw);
RAD_ISSUE_N(c, ff.op_act, Rn, brows(b_f, Rn), brows(b_f, Rn));
clipped(ff.l2, b_f, ffw, b_f, b_o, H);
RAD_ISSUE_N(c, ff.op_post, Rn, brows(b_o, Rn), RAD_W(ff.post), brows(b_o, Rn));
RAD_ISSUE_N(c, ff.op_add, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
};
ffw_block(l.ff1);
RAD_ISSUE_N(c, l.op_npa, Rn, brows(b_x, Rn), RAD_W(l.n_pre_attn), brows(b_h, Rn));
clipped(l.q, b_h, H, b_hc, b_q, H);
clipped(l.k, b_h, H, b_hc, b_k, H);
clipped(l.v, b_h, H, b_hc, b_v, H);
RAD_ISSUE_N(c, l.op_rel, n_rel, brows(b_relpos, n_rel), RAD_W(l.w_rel),
brows(b_relk, n_rel));
RAD_ISSUE_N(c, l.op_attn, Rn, brows(b_q, Rn), brows(b_k, Rn), brows(b_v, Rn),
brows(b_relk, n_rel), RAD_W(l.pds), cu, brows(b_att, Rn));
clipped(l.post, b_att, H, b_hc, b_o, H);
RAD_ISSUE_N(c, l.op_npo, Rn, brows(b_o, Rn), RAD_W(l.n_post_attn), brows(b_o, Rn));
RAD_ISSUE_N(c, l.op_add_attn, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn));
RAD_ISSUE_N(c, l.op_lc_pre, Rn, brows(b_x, Rn), RAD_W(l.lc_pre), brows(b_h, Rn));
clipped(l.lc_start, b_h, H, b_hc, b_g, 2 * H);
RAD_ISSUE_N(c, l.op_glu, Rn, bcol(b_g, H, H, Rn), bcol(b_g, 0, H, Rn), brows(b_u, Rn));
RAD_ISSUE_N(c, l.op_dw, Rn, brows(b_u, Rn), RAD_W(l.lc_dw), cu, brows(b_o, Rn));
RAD_ISSUE_N(c, l.op_lc_norm, Rn, brows(b_o, Rn), RAD_W(l.lc_norm), brows(b_o, Rn));
RAD_ISSUE_N(c, l.op_lc_act, Rn, brows(b_o, Rn), brows(b_o, Rn));
clipped(l.lc_end, b_o, H, b_hc, b_u, H);
RAD_ISSUE_N(c, l.op_lc_add, Rn, brows(b_x, Rn), brows(b_u, Rn), brows(b_x, Rn));
ffw_block(l.ff2);
RAD_ISSUE_N(c, l.op_out, Rn, brows(b_x, Rn), RAD_W(l.n_out), brows(b_x, Rn));
}
RAD_ISSUE_N(c, op_outp, Rn, brows(b_x, Rn), RAD_W(w_out), RAD_W(b_outw), RAD_NONE,
brows(b_o2, Rn));
RAD_ISSUE_N(c, op_en, Rn, brows(b_o2, Rn), RAD_NONE, brows(b_on, Rn));
RAD_ISSUE_N(c, op_emb, Rn, brows(b_on, Rn), RAD_W(w_emb), brows(b_out, Rn));
}
};
struct Model {
Names nm{""};
Geom g{};
@@ -790,25 +82,15 @@ struct Model {
rad_op op_mm = 0; /* the media rows over their placeholders' embeddings */
std::vector<Layer> layers;
Vision vis;
Audio aud;
Gemma4Vision vis;
Gemma4Audio aud;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* A value as a bf16 tensor holds it: round to nearest even on the top 16 bits of the f32. */
static double bf16_round(double v) {
float f = (float)v;
uint32_t u;
std::memcpy(&u, &f, 4);
u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u;
std::memcpy(&f, &u, 4);
return (double)f;
}
/* The layer schedule, read and not derived: layer_types is the checkpoint's statement of which
* layers attend to the whole input, and a pattern assumed from the model card would build a model
* that runs and pools the wrong function if a sibling checkpoint moved one. */
/* The layer schedule, read rather than derived: layer_types states which layers attend to the
* whole input, and an assumed pattern would silently be wrong for a sibling checkpoint that
* differs. */
static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector<int>* full) {
const char* s = rad_meta_gets(meta, "layer_types", nullptr);
if (!s || !*s) {
@@ -841,16 +123,17 @@ static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector<
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
/* A 270M encoder is a fraction of one card; splitting it would cost an all-reduce a layer to
* save nothing, so it is not offered. */
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
/* A 270M encoder fits easily on one card; tensor parallelism would only add an all-reduce per
* layer, so it is not offered. */
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: embgemma2 runs on one card (--tp 1); the text model is 270M "
"parameters\n");
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
@@ -862,14 +145,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &full));
/* The two attention kinds. The sliding one is the config's top-level geometry; the full one
* overrides head width and KV heads per layer (per_layer_config), and every full layer of
* this checkpoint states the same override -- checked below, layer by layer. */
* overrides head width and KV heads per layer (per_layer_config), and every full layer must
* state the same override (checked below). */
m.ks.head_dim = g.head_dim;
m.ks.n_head = g.n_head;
m.ks.n_head_kv = g.n_head_kv;
m.ks.theta = rad_meta_getf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0);
/* A RADIUS in the reference (|i - j| <= sliding_window), and attn_dense's window is the
* strict bound, so one more. */
/* The reference's window is a radius (|i - j| <= sliding_window) and attn_dense's is a strict
* bound, so one more. */
const int64_t radius = meta_int2(meta, "", "sliding_window", 0);
m.ks.window = radius + 1;
m.kf.n_head = g.n_head;
@@ -901,12 +184,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_INVAL;
}
const int64_t P = m.n_ple * g.n_layer;
/* ONE INPUT IS AT MOST ONE STEP (Request::embed), so the longest attention segment is the
/* One input is at most one step (Request::embed), so the longest attention segment is the
* step's token budget. */
const int64_t max_seg = T;
/* ---- activations. ple holds every layer's per-layer input for the whole step, read a
* column slice a layer. */
/* ---- activations. ple holds every layer's per-layer input for the whole step, read as one
* column slice per layer. */
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {T, E});
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
m.b_o = decl_b(b, nm.f("o"), RAD_BF16, {T, E});
@@ -923,9 +206,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.b_pooled= decl_b(b, nm.f("pooled"), RAD_F32, {g.max_seqs, m.n_out}, RAD_BUF_PERSIST);
RAD_ARCH_TRY(rad_declare_pooled(b, m.b_pooled));
/* ---- the model-level weights. Every one at the checkpoint's own bf16, the norm gains
* included: the reference widens a gain to f32 at use, which is exact, so storing it wider
* buys nothing and costs reading it in place on the host backend. */
/* ---- the model-level weights, all at the checkpoint's bf16, norm gains included: the
* reference widens a gain to f32 at use, which is exact, and a wider stored copy could not be
* read in place on the host backend. */
const char* L = "language_model";
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", L)));
RAD_ARCH_TRY(map_copy(b, nm.f("ple_proj.weight"),
@@ -974,24 +257,23 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_NOWEIGHTS);
};
/* The embedding, scaled by sqrt(hidden) AS THE REFERENCE ROUNDS IT: the scale is a bf16
* buffer, so sqrt(512) = 22.6274 multiplies as 22.625. */
const double escale = bf16_round(std::sqrt((double)E));
/* The embedding, scaled by sqrt(hidden) rounded as the reference rounds it (a bf16 buffer):
* sqrt(512) = 22.6274 multiplies as 22.625. */
const double escale = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)E)));
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", 0), RAD_F64("mult", escale)),
RAD_WEIGHTS(m.w_tok)),
{}, {m.b_x});
/* THE PER-LAYER INPUTS: the embedding projected to n_layer x n_ple and RMS-normed per layer.
* The reference scales the projection by hidden^-0.5 before the norm; an RMS norm of s*x with
* eps is exactly the norm of x with eps / s^2, which is what this declares, so the scale is
* applied without the extra bf16 rounding of s*x the reference pays. */
/* A media part's rows over its placeholders' embeddings, before anything reads them: the
* per-layer inputs are projected from what the model embeds, and for an image token that is
* its image row (declared only when a tower is). */
if ((Vision::present(meta) && ctx->max_enc_patches > 0) ||
(Audio::present(meta) && ctx->max_audio_frames > 0))
/* The per-layer inputs: the embedding projected to n_layer x n_ple and RMS-normed per layer.
* The reference scales the projection by hidden^-0.5 before the norm; the RMS norm of s*x with
* eps equals the norm of x with eps / s^2, which is what is declared, avoiding the bf16
* rounding of s*x. */
/* A media part's rows overwrite its placeholders' embeddings before anything reads them, so an
* image token's per-layer inputs come from its image row (declared only with a tower). */
if ((Gemma4Vision::present(meta) && ctx->max_enc_patches > 0) ||
(Gemma4Audio::present(meta) && ctx->max_audio_frames > 0))
m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_STR("dtype", "bf16")),
@@ -1106,9 +388,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_NOWEIGHTS),
{m.b_proj}, {m.b_pooled});
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, E, (int)g.n_layer));
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, E,
(int)g.n_layer + (int)m.vis.L.size()));
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, E, (int)g.n_layer, "", "embgemma2"));
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, E, (int)g.n_layer + (int)m.vis.L.size(), "",
"embgemma2"));
int n_full = 0;
for (int f : full) n_full += f;
@@ -1123,20 +405,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_OK;
}
/* Before declare: the vision tower's pooling window, so a pass size the core picks itself is a
* whole number of them. */
/* Before declare: the vision tower's pooling window, so a pass size the core picks is a whole
* number of windows. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
if (Vision::present(meta)) {
if (Gemma4Vision::present(meta)) {
const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0);
if (k > 0) out->enc_merge = k * k;
}
if (Audio::present(meta)) out->audio_frames = Audio::frames_for(meta);
if (Gemma4Audio::present(meta)) out->audio_frames = Gemma4Audio::frames_for(meta);
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
const Geom& g = m.g;
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
if (batch->enc) {
@@ -1199,6 +481,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
} /* namespace embgemma2 */
#ifndef RAD_ARCH_NO_EXPORTS
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(embgemma2, "embeddinggemma2", "", "0.1.0",
"EmbeddingGemma 2: a bidirectional Gemma encoder with per-layer embeddings, "
"mean-pooled to one vector an input; bf16")
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/fishomni -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(fishomni LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(fishomni architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/fishomni.cpp)
File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/flux3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(flux3 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(flux3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flux3.cpp)
+1325
View File
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/flux3distilled -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see
# cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(flux3distilled LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(flux3distilled architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flux3distilled.cpp)
+13
View File
@@ -0,0 +1,13 @@
/* flux3distilled -- arch/flux3 under the architecture name of FLUX.3 [klein]'s step-distilled
* release.
*
* The released pipeline is a `Flux3DistilledModularPipeline` and its base a
* `Flux3ModularPipeline`, so rad-convert names them `flux3distilled` and `flux3`. Both hold the same
* networks; the transformer's `flow_map` flag is what tells them apart inside the plugin. A
* separate .so because a plugin answers to one architecture name (spec §2.4). Everything else is
* arch/flux3/flux3.cpp.
*/
#define FLUX3_NS flux3distilled
#define FLUX3_ID "flux3distilled"
#include "../flux3/flux3.cpp"
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/gemma3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(gemma3 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(gemma3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma3.cpp)
File diff suppressed because it is too large. Load diff
+14
View File
@@ -0,0 +1,14 @@
# gemma4 -- architecture plugin for Gemma 4's text model (Gemma4ForConditionalGeneration /
# Gemma4ForCausalLM: the 26B-A4B MoE and the dense sizes without per-layer embeddings), with a
# z-lab DFlash drafter merged at convert time.
#
# Built in radiance's tree (arch/ discovers it) or standalone against an installed radiance:
# cmake -S arch/gemma4 -B build-gemma4 -DCMAKE_PREFIX_PATH=/opt/radiance && cmake --build build-gemma4
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(gemma4 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(gemma4 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma4.cpp)
File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/gemma4_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(gemma4_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(gemma4_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma4_bf16.cpp)
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(glm5next LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(glm5next architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/glm5next.cpp)
+690
View File
@@ -0,0 +1,690 @@
/* glm5next -- GLM-5.3-Flash (`model_type: glm5_next`) from AMD's Quark MXFP4 export: four mHC
* residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers behind a DSA indexer,
* 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32
* scales, each weight served as the container stores it; its MTP layer is a serial drafter, and
* its vision tower is declared when the container carries it and the deployment asks for an
* encoder. docs/ARCHITECTURES.md describes the model and its traps.
*
* The blocks live in arch/common (installed as <arch/...>), one a file:
*
* rad_block_glm_mhc.h ManifoldConn the four-stream residual read and write
* rad_block_glm_kda.h GlmKda the 34 linear layers, KdaState their recurrence
* rad_block_glm_mla.h GlmMla the 11 sparse MLA layers, MlaLatent their core
* rad_block_glm_indexer.h GlmIndexer the DSA indexer, DsaCache its key cache and selection
* rad_block_glm_router.h GlmRouter the correction-bias router (through MoeFP8)
* rad_block_glm_mtp.h GlmMtp the draft head around the plugin's layer 45
* rad_block_glm_vision.h GlmVision the tower, MediaRows its rows over the embeddings
* rad_glm_tp.h GlmTp the shards, the row runs and the split thresholds
*
* This file declares the buffers the blocks share, places the blocks and issues the step's
* order. Declaration order is liveness (the buffer plan takes lifetimes from it) and the issue
* order is the recorded pass, so both are kept as they read here. This plugin uses only the
* public ABI and the installed common headers. */
#include <arch/rad_block_glm_mhc.h>
#include <arch/rad_block_glm_kda.h>
#include <arch/rad_block_glm_mla.h>
#include <arch/rad_block_glm_indexer.h>
#include <arch/rad_block_glm_mtp.h>
#include <arch/rad_block_glm_vision.h>
#include <arch/rad_block_mlp_fp8.h>
#include <arch/rad_block_moe_fp8.h>
#include <memory>
namespace glm5next {
using namespace rad::arch;
struct Layer {
bool full = false, draft = false;
ManifoldConn attn_hc{}, ffn_hc{};
NormQuantFP8 norm{};
GlmKda kda{};
GlmMla mla{};
GlmIndexer index{};
MlpFP8 dense{};
MoeFP8 moe{};
};
struct Model {
Names nm{};
Geom g{};
/* The MLA's split of a prefill-sized step under TP (RadBuildCtx::tp_attn_rows). The head
* form declares none of the row form's full-width weights (1.29 GiB a card at eight ranks);
* the row form is opt-in because it is not bit-identical to it (docs/ARCHITECTURES.md). */
GlmMla::Form form = GlmMla::Form::heads;
/* Routed experts whole on their rank (288/world of them) instead of split by width across
* every rank. Whole experts can be read from the drive, which two cards need; at four and
* eight the width split is the shape the MXFP4 kernels are tuned for (prefill runs about three
* times faster), so all-MXFP4 experts take it unless --weights-disk-tier asks for the drive.
* Anything else stays whole: a plain bf16 expert cannot be sliced at all. */
bool whole_experts = false;
std::vector<Layer> layers;
rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0;
/* The streams and the step's stream-wide buffers. */
rad_buf h0 = 0, h1 = 0, x = 0, y = 0, post = 0, comb = 0, final_hidden = 0, logit_input = 0,
logits = 0;
ActFP8 act{};
/* The blocks' wires: one set of activations, shared by every layer of a kind. */
GlmKda::Wire kw{};
GlmMla::Wire aw{};
GlmIndexer::Wire iw{};
MlpFP8::Wire dw{};
MoeFP8::Wire mw{};
rad_weight token = 0, head = 0, final_gain = 0;
rad_op embed = 0, embed_ar = 0, expand = 0, contract = 0, norm = 0, gather = 0, head_op = 0;
/* The draft head and its layer, declared only when the deployment speculates. */
bool have_mtp = false;
GlmMtp mtp{};
Layer draft{};
/* Media: the tower, and its rows over the trunk's embedding (the draft head scatters its own). */
bool media = false;
GlmVision vit{};
MediaRows mrows{};
};
static std::unique_ptr<Model> models[MAX_SLOTS];
static thread_local std::unique_ptr<Model> probe_model;
/* Whether every routed expert is MXFP4, asked before any buffer is sized and of the same experts on
* every rank, so all ranks reach the same layout. It reads the container's entries and declares no
* name map, so it leaves the graph as it was. One expert in another format settles it: a protected
* bf16 expert is served only whole. No answer means no container entry, and what is not known to
* be MXFP4 stays whole. */
static bool experts_are_mxfp4(RadBuilder* b, Names& nm) {
for (int l = 3; l < 45; ++l)
for (int ge = 0; ge < 288; ++ge)
for (const char* fmt : { "blk.%d.ffn_gate_up_exps.%d.weight",
"blk.%d.ffn_down_exps.%d.weight" }) {
RadEncoding e{};
if (!weight_enc(b, nm.f(fmt, l, ge), &e) || MoeFP8::format_of(e) != 8)
return false;
}
return true;
}
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
char nested[160];
std::snprintf(nested, sizeof nested, "text_config.%s", key);
return rad_meta_geti(m, key, rad_meta_geti(m, nested, fallback));
}
static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y) {
return rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ x }, { y });
}
static rad_op norm(RadBuilder* b, const Geom& g, rad_weight w, rad_buf x, rad_buf y) {
return rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w)),
{ x }, { y });
}
/* ------------------------------------------------------------------ the shared activations */
static int stream_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok;
m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, 16384 });
m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, 16384 });
m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, 4096 });
/* The MLA row form gathers every rank's run at full length, so its output is rounded up to
* whole runs; the head form keeps the step's rows. */
const bool rows = g.world > 1 && m.form == GlmMla::Form::rows;
m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16,
{ rows ? g.world * GlmMla::rows_for(T, g.world) : T, 4096 });
m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 });
m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 });
m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 });
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normalized", 4096));
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, 4096 }, RAD_BUF_PERSIST);
m.logit_input = decl_b(b, nm.f("logit_input"), RAD_BF16, { g.max_logit_rows, 4096 });
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
return rad_declare_logits(b, m.logits);
}
static int kda_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, W = GlmTp::kda_width(g.world);
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& kw = m.kw;
kw.input = m.act.x;
kw.out = m.y;
kw.forget_low = bf("forget_low", 128);
kw.gate_low = bf("gate_low", 128);
kw.core.qkv = bf("qkv", 3 * W);
kw.core.conv = bf("convolved", 3 * W);
kw.core.a = bf("forget", W);
kw.core.beta = bf("beta", GlmTp::heads(g.world));
kw.core.gate = bf("gate", W);
kw.core.out = bf("recurrent_out", W);
return RAD_OK;
}
/* The head form's buffers, then the selection planes the indexer writes and the MLA reads, then
* the row form's (Model::form). Under TP the selection planes hold every rank's run of rows,
* which can reach past the step (DsaCache::part_rows). */
static int mla_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, H = GlmTp::heads(g.world), Q = GlmTp::mla_width(g.world);
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& aw = m.aw;
aw.input = m.act;
aw.q_raw = bf("q_raw", 1536);
aw.kv_raw = bf("kv_raw", 512);
aw.q_low.x = bf("q_low", 1536);
RAD_ARCH_TRY(aw.q_low.declare_qs(b, nm, g, "q_low", 1536));
aw.latent = bf("latent", 512);
aw.out = m.y;
aw.core.q = bf("query", Q);
aw.core.q_latent = decl_b(b, nm.f("q_latent"), RAD_BF16, { T, H, 512 });
aw.core.attn_latent = decl_b(b, nm.f("attn_latent"), RAD_BF16, { T, H, 512 });
aw.attn.x = bf("expanded", Q);
RAD_ARCH_TRY(aw.attn.declare_qs(b, nm, g, "expanded", Q));
aw.core.out = aw.attn.x;
const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0;
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { TQ, 513 });
aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { TQ });
if (g.world > 1 && m.form == GlmMla::Form::rows) {
auto& rows = aw.rows;
const int64_t R = GlmMla::rows_for(T, g.world);
rows.q = decl_b(b, nm.f("rows_query"), RAD_BF16, { R, 16384 });
rows.q_latent = decl_b(b, nm.f("rows_q_latent"), RAD_BF16, { R, 64, 512 });
rows.attn_latent = decl_b(b, nm.f("rows_attn_latent"), RAD_BF16, { R, 64, 512 });
rows.attn.x = decl_b(b, nm.f("rows_expanded"), RAD_BF16, { R, 16384 });
RAD_ARCH_TRY(rows.attn.declare_qs(b, nm, g, "rows_expanded", 16384, R));
rows.out = decl_b(b, nm.f("rows_out"), RAD_BF16, { R, 4096 });
}
return RAD_OK;
}
static int indexer_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok;
const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0;
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
const int64_t work = (T + 3) / 4 + g.max_seqs, blocks = (g.max_ctx + 3) / 4 + 1;
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& iw = m.iw;
iw.input = m.act.x;
iw.q_low = m.aw.q_low.x;
iw.q_wide = bf("index_query", 4096);
iw.kg_raw = bf("index_key_gate", 256);
auto& c = iw.cache;
c.query = decl_b(b, nm.f("index_heads"), RAD_BF16, { T * 32, 128 });
c.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { TQ * 32, 128 });
c.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { TQ * 32, 1 });
c.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { TQ, 32 });
c.kg = bf("index_normalized_key_gate", 256);
c.stage = decl_b(b, nm.f("pool_stage"), RAD_BF16, { work * 4, 256 });
c.page = decl_b(b, nm.f("pool_page"), RAD_I32, { work });
c.bpos = decl_b(b, nm.f("pool_pos"), RAD_I32, { work });
c.nc = decl_b(b, nm.f("pool_count"), RAD_I32, { g.max_seqs });
c.pooled = decl_b(b, nm.f("pool_codes"), RAD_F8E4M3, { work, 128 });
c.pool_scale = decl_b(b, nm.f("pool_scales"), RAD_F32, { work, 1 });
/* A split step scores one run of rows a rank and an unsplit one is under GlmTp::kSplitRows:
* at 64k of context the whole step's plane would be 256 MiB. */
const int64_t scored = g.world > 1 ? std::min(T, std::max(part, GlmTp::kSplitRows)) : T;
c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { scored, blocks });
c.unscored = decl_b(b, nm.f("index_unscored"), RAD_F32, { T, std::min<int64_t>(513, blocks) });
c.selected = m.aw.core.selected;
c.length = m.aw.core.length;
c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
/* The MLA block's resolve count: qsa_select's second output, never `length`. */
m.aw.core.nsel = c.nsel;
if (g.world > 1) {
c.cu_part = decl_b(b, nm.f("index_part_bounds"), RAD_I32, { g.max_seqs + 1 });
c.sel_part = decl_b(b, nm.f("selected_part"), RAD_I32, { part, 513 });
c.len_part = decl_b(b, nm.f("length_part"), RAD_I32, { part });
}
return RAD_OK;
}
static int ffn_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, F = GlmTp::expert_width(g.world);
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& dw = m.dw;
dw.x = m.x;
dw.h = m.act;
dw.gate_up = bf("dense_gate_up", 2 * g.n_ff);
dw.ffn.x = bf("dense_ff", g.n_ff);
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
auto& mw = m.mw;
mw.x = m.x;
mw.h = m.act;
mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, 288 });
mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 });
mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 });
mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 });
/* PERSIST, as every other MoE here declares it: the router writes the counts and no declared
* op reads them (rad_route_report is a handoff), so as a transient a later buffer could share
* their bytes and an arena level would move them, while the core copies them at the block's
* end and the file stager reads them, through the address the last pass reported, at the
* layer's first expert op. */
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }, RAD_BUF_PERSIST);
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * 8 });
mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { T * 8 });
// FE: the routed experts' intermediate. Under expert parallelism a rank owns whole experts,
// so the routed arm's buffers are full-width (2048); split by width they are F. The SHARED
// expert stays width-sharded (F) either way. The two coincide at world 1.
const int64_t FE = m.whole_experts ? 2048 : F;
mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * FE });
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, FE });
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", FE, T * 8));
mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { T * 8, 4096 });
mw.sgu = bf("shared_gate_up", 2 * F);
mw.sff.x = bf("shared_ff", F);
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", F));
mw.sout = bf("shared_out", 4096);
mw.sgate = bf("shared_one", 1);
return RAD_OK;
}
static int kv_groups(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
// bf16, or E4M3 under --kv-cache-dtype fp8 (geometry); the other groups keep their own.
d.dtype = rad_dtype_parse(g.kv_dtype);
d.n_head_kv = 1;
d.head_dim = 256;
m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d);
d = {};
d.kind = RAD_KV_LINEAR;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.state_dim[0] = 4 + g.max_spec;
d.state_dim[1] = 256;
m.tail = rad_decl_kv_group(b, nm.f("kv_index_tail"), &d);
d = {};
d.kind = RAD_KV_LINEAR;
d.dtype = RAD_F32;
d.n_head_kv = GlmTp::heads(g.world);
d.state_dim[0] = d.state_dim[1] = 128;
m.state = rad_decl_kv_group(b, nm.f("kv_kda"), &d);
d = {};
d.kind = RAD_KV_CONV;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.head_dim = 3 * GlmTp::kda_width(g.world);
d.conv_width = 4;
m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d);
// The index group is declared by the first indexer, right before its cache consumer.
return m.latent && m.tail && m.state && m.conv ? RAD_OK : RAD_E_INVAL;
}
/* ------------------------------------------------------------------ one layer */
static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool draft) {
const auto& g = m.g;
lay.draft = draft;
lay.full = draft || l % 4 == 3;
const char* pre = nm.ckpt("model.language_model.layers.%d", l);
const char* ap = nm.ckpt("%s.self_attn", pre);
rad_buf input = draft ? m.mtp.x : m.x;
ManifoldConn::Config hc;
hc.eps = g.eps;
if (!draft) {
ManifoldConn::Wire a{ m.h0, m.x, m.y, m.h1, m.post, m.comb };
ManifoldConn::Src as{ nm.ckpt("%s.hc_attn_fn", pre), nm.ckpt("%s.hc_attn_scale", pre),
nm.ckpt("%s.hc_attn_base", pre) };
RAD_ARCH_TRY(lay.attn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_attn", l), hc, a, as, true));
}
const char* nn = nm.f("blk.%d.attn_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre)));
const auto gain =
decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096));
if (lay.full) {
// The MTP layer keeps the head form: its row form would cost another 126 MB a card.
auto aw = m.aw;
if (draft) aw.rows = {};
RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, aw, ap, m.latent, true, true));
DsaCache::Config c;
c.blocks = (g.max_ctx + 3) / 4 + 1;
c.work = (g.max_tok + 3) / 4 + g.max_seqs;
c.ring = 4 + g.max_spec;
RAD_ARCH_TRY(lay.index.declare(b, nm, g, l, m.iw, nm.ckpt("%s.indexer", ap), c, m.latent,
m.tail, &m.index));
RAD_ARCH_TRY(lay.mla.declare_finish(b, nm, ap));
} else {
KdaState::Src s{ nm.ckpt("%s.q_conv1d.weight", ap), nm.ckpt("%s.k_conv1d.weight", ap),
nm.ckpt("%s.v_conv1d.weight", ap), nm.ckpt("%s.A_log", ap),
nm.ckpt("%s.dt_bias", ap), nm.ckpt("%s.o_norm.weight", ap) };
RAD_ARCH_TRY(lay.kda.declare(b, nm, g, l, m.kw, ap, s, m.state, m.conv));
}
// The ffn connection is declared after the attention's post: declaration order is liveness.
if (!draft) {
RAD_ARCH_TRY(lay.attn_hc.declare_post(b));
ManifoldConn::Wire f{ m.h1, m.x, m.act.x, m.h0, m.post, m.comb };
ManifoldConn::Src fs{ nm.ckpt("%s.hc_ffn_fn", pre), nm.ckpt("%s.hc_ffn_scale", pre),
nm.ckpt("%s.hc_ffn_base", pre) };
RAD_ARCH_TRY(lay.ffn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_ffn", l), hc, f, fs, true));
} else {
RAD_ARCH_TRY(m.mtp.declare_join(b, m.y));
}
if (l < 3) {
auto w = m.dw;
w.x = input;
MlpFP8::Src s{ nm.ckpt("%s.post_attention_layernorm.weight", pre),
nm.ckpt("%s.mlp.gate_proj.weight", pre),
nm.ckpt("%s.mlp.up_proj.weight", pre),
nm.ckpt("%s.mlp.down_proj.weight", pre) };
lay.dense.swiglu_quant = true;
RAD_ARCH_TRY(lay.dense.declare(b, nm, g, l, w, s, false, draft, kArNone, false, 10));
} else {
auto w = m.mw;
w.x = input;
MoeFP8::Src s;
s.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
s.router = nm.ckpt("%s.mlp.gate.weight", pre);
s.router_bias = nm.ckpt("%s.mlp.gate.e_score_correction_bias", pre);
s.experts = nm.ckpt("%s.mlp.experts", pre);
s.shared = nm.ckpt("%s.mlp.shared_experts", pre);
// EXPERT PARALLELISM AT TP: each rank owns 288/world WHOLE experts (the contiguous
// window [expert_base, expert_base+n_expert) of the checkpoint's numbering), which the
// helper declares RAD_SHARD_NONE -- unsharded, so an expert unit is file-direct and can
// live in the container's mapping or the file tier
// instead of needing VRAM+pinned-pool residency for all 151 GiB of them. The router
// stays replicated over n_expert_all; moe_scatter/router_topk_scatter drop slots
// outside the window (moe_scatter schema: "which is how EXPERT PARALLELISM is
// expressed"); the shared expert stays width-sharded on its own declaration path; the
// block's all-reduce sums the partials exactly as width TP did. At world 1 this
// degenerates to the old whole-model declaration (n_expert == n_expert_all, no spans).
s.cfg.n_expert_all = 288;
s.cfg.top_k = 8;
s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
if (m.whole_experts) {
s.cfg.n_expert = 288 / g.world;
// A shape probe may pass rank >= world (arch_test's parallel declares reuse i % 4);
// old code tolerated that because expert_base stayed 0, so clamp to rank 0's window.
const int ep_rank = g.rank < g.world ? g.rank : 0;
s.cfg.expert_base = ep_rank * (288 / g.world);
s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate
} else {
s.cfg.n_expert = 288;
s.cfg.n_ff_exp = GlmTp::expert_width(g.world);
}
s.cfg.rows = g.max_tok;
s.cfg.sigmoid_router = 1;
s.cfg.route_scale = 2.5;
s.cfg.swiglu_limit = 10;
s.cfg.shared_ungated = 1;
s.cfg.router_fuse = 1;
s.cfg.swiglu_quant = 1;
// At world 1 the width-slice declaration IS the whole model: keep the spans so the
// graph stays the pinned one. Whole experts need no width spans (split && ep is refused
// by the helper).
if (!m.whole_experts) {
for (int q = 0; q < 2; ++q) {
s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
}
}
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg));
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, w, s, false, draft));
}
if (!draft) RAD_ARCH_TRY(lay.ffn_hc.declare_post(b));
return RAD_OK;
}
/* ------------------------------------------------------------------ declare */
static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, int world) {
g.n_layer = 45;
g.n_embd = 4096;
g.head_dim = GlmTp::kMlaDim;
g.n_head_all = g.n_head_kv_all = GlmTp::kHeads;
g.n_head = g.n_head_kv = GlmTp::heads(world);
g.n_ff_all = GlmTp::kDenseFF;
g.n_ff = GlmTp::dense_width(world);
g.n_vocab_all = 154880;
g.n_vocab = shard_extent(154880, world, ctx->rank);
g.vocab_off = shard_begin(154880, world, ctx->rank);
g.rank = ctx->rank;
g.world = world;
g.attn_world = world;
g.attn_rank = ctx->rank;
g.max_tok = ctx->max_tok;
g.max_ctx = ctx->max_ctx;
g.max_seqs = ctx->max_seqs;
g.max_spec = ctx->max_spec;
/* Filled by hand here, not by geom_from: without it kv_resolve would declare the whole context as
* the ring. */
g.kv_resident = ctx->kv_resident_blocks;
g.max_logit_rows = std::min<int64_t>(g.max_tok, g.max_seqs * (g.max_spec + 1));
if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows;
g.eps = meta->rms_eps;
/* --kv-cache-dtype names the latent cache's dtype only (kv_groups); declare refuses all but
* bf16 and fp8. */
g.kv_dtype = rad_dtype_name(rad_kv_cache_dtype(ctx, RAD_BF16));
g.wire_exact = !ctx->tp_wire_lossy;
g.wire_min_bytes = ctx->tp_wire_min_bytes;
return g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0 ? RAD_E_INVAL : RAD_OK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
const int world = ctx->world_size ? ctx->world_size : 1;
if (!GlmTp::world_ok(world)) {
fprintf(stderr, "radiance: glm5next: --tp %d; the head, KDA channel and expert splits of "
"this plugin are built for 1, 2, 4 or 8 ranks\n", world);
return RAD_E_UNSUPPORTED;
}
/* The graph is written for the released GLM-5.3-Flash and reads none of these from the
* checkpoint, so a checkpoint that differs in any of them is refused by name. */
const struct {
const char* what;
int64_t got, want;
} shape[] = { { "hidden_size", meta->n_embd, 4096 },
{ "num_hidden_layers", meta->n_layers, 45 },
{ "vocab_size", meta->n_vocab, 154880 },
{ "num_nextn_predict_layers", cfg(meta, "num_nextn_predict_layers", 0), 1 },
{ "hc_mult", cfg(meta, "hc_mult", 0), 4 },
{ "n_routed_experts", cfg(meta, "n_routed_experts", 0), 288 },
{ "index_topk", cfg(meta, "index_topk", 0), 2048 } };
for (const auto& s : shape)
if (s.got != s.want) {
fprintf(stderr, "radiance: glm5next: the checkpoint's %s is %lld; this plugin serves "
"the GLM-5.3-Flash geometry, where it is %lld\n",
s.what, (long long)s.got, (long long)s.want);
return RAD_E_UNSUPPORTED;
}
if (ctx->max_spec > 31) {
fprintf(stderr, "radiance: glm5next: --num-speculative-tokens %d; the KDA verify pass "
"takes at most 32 rows a sequence, so the MTP depth is at most 31\n",
ctx->max_spec);
return RAD_E_UNSUPPORTED;
}
/* fp8 narrows the latent attention cache to E4M3 at a descale of 1 (kv_groups); the index
* tail, the DSA index and the KDA caches keep their dtypes. */
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_F8E4M3) {
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin serves its latent "
"attention cache in bf16 or fp8 only\n",
rad_dtype_name(ctx->kv_dtype));
return RAD_E_UNSUPPORTED;
}
auto& slot = ctx->shape_probe ? probe_model : models[rad_build_slot(ctx)];
slot = std::make_unique<Model>();
auto& m = *slot;
auto& g = m.g;
m.nm = Names(ctx->scope);
auto& nm = m.nm;
m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads;
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
m.whole_experts = world == 2 || (world > 2 && (ctx->expert_file_tier ||
!experts_are_mxfp4(b, nm)));
RAD_ARCH_TRY(stream_buffers(b, m));
RAD_ARCH_TRY(kda_buffers(b, m));
RAD_ARCH_TRY(mla_buffers(b, m));
RAD_ARCH_TRY(indexer_buffers(b, m));
RAD_ARCH_TRY(ffn_buffers(b, m));
RAD_ARCH_TRY(kv_groups(b, m));
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"),
nm.ckpt("model.language_model.embed_tokens.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight")));
RAD_ARCH_TRY(
map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.language_model.norm.weight")));
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, { g.n_vocab, 4096 }, RAD_ACCESS_VOCAB,
RAD_SHARD_ROW, grp_model());
m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, 4096 }, RAD_ACCESS_VOCAB,
RAD_SHARD_ROW, grp_model());
m.final_gain = decl_w(b, nm.f("output_norm.weight"), RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_model());
m.embed = rw(b,
RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(m.token)),
{}, { m.x });
// The encoder's rows overwrite the lookup before its reduction (MediaRows).
m.media = GlmVision::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, 4096, m.x));
m.embed_ar = GlmTp::reduce(b, g, m.x, true);
m.expand = copy(b, g, m.x, m.h0);
m.layers.resize(45);
for (int l = 0; l < 45; ++l) RAD_ARCH_TRY(layer(b, m, m.layers[l], nm, l, false));
// Every rank computes the whole normed latent and pools into the whole index cache
// (rad_block_glm_mla.h, rad_block_glm_indexer.h), so the host tier keeps each once a slot.
RAD_ARCH_TRY(rad_kv_group_replicated(b, m.latent));
if (m.index) RAD_ARCH_TRY(rad_kv_group_replicated(b, m.index));
m.contract = rw(b,
RAD_OP(b, "mhc_contract",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_INT("hc", 4), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.h0 }, { m.x });
m.norm = norm(b, g, m.final_gain, m.x, m.final_hidden);
m.gather = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.final_hidden }, { m.logit_input });
m.head_op =
rw(b,
RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", 4096), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(m.head)),
{ m.logit_input }, { m.logits });
if (g.max_spec > 0) {
GlmMtp::Wire tw{ m.final_hidden, m.logits, m.token, m.head };
RAD_ARCH_TRY(m.mtp.declare_inputs(b, g, tw, m.media));
RAD_ARCH_TRY(layer(b, m, m.draft, m.mtp.nm, 45, true));
RAD_ARCH_TRY(m.mtp.declare_head(b));
m.have_mtp = true;
}
// The tower, last: an encoder pass issues nothing else, so its activations share the arena
// with every buffer above. Its weight groups follow the 45 layers and the MTP layer's.
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, 4096, 46));
rad_note(b,
"GLM-5.3: TP%d, 45 mHC layers, 34 KDA + 11 sparse MLA, mixed MXFP4/FP8, native MTP "
"%s, vision %s",
world, m.have_mtp ? "enabled" : "disabled", m.media ? "enabled" : "disabled");
return RAD_OK;
}
/* ------------------------------------------------------------------ step */
static void attention(RadCtx* c, Layer& l, const RadBatch* batch) {
l.norm.step(c, batch->n_tok);
if (l.full) {
l.mla.prepare(c, batch);
l.index.step(c, batch);
l.mla.finish(c, batch);
} else
l.kda.step(c, batch);
}
static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
if (!m.have_mtp || batch->draft_pass == 1) {
rad_step_fail(c, "GLM MTP pass is not declared or has invalid round 1");
return;
}
const int64_t T = batch->n_tok;
m.mtp.step_inputs(c, batch);
auto& l = m.draft;
l.norm.step(c, T);
l.mla.prepare(c, batch);
l.index.step(c, batch);
// A history pass with no proposal row fills the draft caches and ends there.
if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return;
l.mla.finish(c, batch);
m.mtp.step_join(c, batch, m.y);
l.moe.step_rows(c, GlmMtp::head_rows(batch));
m.mtp.step_head(c, batch);
}
static void step(RadCtx* c, const RadBatch* batch) {
auto& m = *models[rad_slot(c)];
const int64_t T = batch->n_tok;
// An encoder pass runs only the vision tower (RadBatch::enc).
if (batch->enc) {
m.vit.step(c, batch);
return;
}
if (batch->draft_pass) {
draft_pass(c, m, batch);
return;
}
RAD_ISSUE_N(c, m.embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), brows(m.x, T));
m.mrows.step(c, batch, m.x, T);
if (m.embed_ar) RAD_ISSUE_N(c, m.embed_ar, T * 4096, brows(m.x, T), RAD_NONE);
for (int i = 0; i < 4; ++i)
RAD_ISSUE_N(c, m.expand, T, brows(m.x, T), bcol(m.h0, i * 4096, 4096, T));
for (int i = 0; i < 45; ++i) {
auto& l = m.layers[i];
l.attn_hc.read(c, T);
attention(c, l, batch);
l.attn_hc.write(c, T);
l.ffn_hc.read(c, T);
if (i < 3)
l.dense.step(c, batch);
else
l.moe.step(c, batch);
l.ffn_hc.write(c, T);
}
RAD_ISSUE_N(c, m.contract, T, brows(m.h0, T), brows(m.x, T));
RAD_ISSUE_N(c, m.norm, T, brows(m.x, T), RAD_W(m.final_gain), brows(m.final_hidden, T));
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.final_hidden, T),
praw(batch->out_ids, RAD_I32, batch->n_out),
brows(m.logit_input, batch->n_out));
RAD_ISSUE_N(c, m.head_op, batch->n_out, brows(m.logit_input, batch->n_out), RAD_W(m.head),
brows(m.logits, batch->n_out));
}
}
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
/* The MLA block declares the streamed store and the resolve (rad_block_glm_mla.h). */
out->kv_stream_ok = 1;
if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth;
// The tower's merged block, so a pass size the core picks itself is whole output rows.
if (GlmVision::present(meta)) {
const int64_t k = rad_meta_geti(meta, "vision_config.spatial_merge_size", 0);
if (k > 0) out->enc_merge = k * k;
}
out->shape_probe_ok = 1;
out->tp_attn_rows_ok = 1;
/* --kv-cache-dtype fp8: the latent attention cache as E4M3 (declare, kv_groups). */
out->kv_fp8_ok = 1;
return RAD_OK;
}
} // namespace glm5next
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(glm5next)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(glm5next, "glm5next", "", "0.1.0",
"GLM-5.3-Flash mixed MXFP4/FP8, mHC/KDA/MLA and native serial MTP")
#endif
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/hunyuan3d2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(hunyuan3d2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(hunyuan3d2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hunyuan3d2.cpp)
File diff suppressed because it is too large. Load diff
+9
View File
@@ -0,0 +1,9 @@
# Built in radiance's tree, or standalone against an installed radiance.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(hyv3_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(hyv3_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_bf16.cpp)
+5
View File
@@ -0,0 +1,5 @@
#define HYV3_NS hyv3_bf16
#define HYV3_QUANT ""
#define HYV3_FP8_SOURCE 0
#define HYV3_PLUGIN_NAME "hyv3_bf16"
#include "../hyv3_common/hyv3_impl.cpp"
+208
View File
@@ -0,0 +1,208 @@
/* HYV3 full GQA attention with block-scaled FP8 projections and per-head
* Q/K RMSNorm before NeoX RoPE (the HYV3 attention path).
*
* rmsnorm -> q/k/v gemm_nt_q -> per-head q/k RMSNorm -> rope -> kv_store -> attn_paged
* -> quant_act_fp8 -> o gemm_nt_q -> [all_reduce] -> residual add
*
* Unlike AttnFP8, the projections stay separate so Q and K can be normalized independently before
* rotation. The weights and all non-attention activations use the same contracts as the other FP8
* blocks in rad_fp8.h.
*/
#ifndef HYV3_ATTENTION_H
#define HYV3_ATTENTION_H
#include <arch/rad_fp8.h>
#include <cmath>
#include <cstdio>
#include <cstring>
namespace rad {
namespace arch {
struct AttnQKFP8 {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] residual stream */
ActFP8 h{}; /* [max_tok, n_embd] normed input, then o output */
rad_buf q = 0; /* [max_tok, q_dim], projected, normed and rotated */
rad_buf k = 0; /* [max_tok, kv_dim], projected, normed and rotated */
rad_buf v = 0; /* [max_tok, kv_dim], projected */
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
};
struct Src {
const char* norm = nullptr;
const char* q = nullptr;
const char* k = nullptr;
const char* v = nullptr;
const char* q_norm = nullptr;
const char* k_norm = nullptr;
const char* o = nullptr;
};
Geom g{};
Wire w{};
int layer = 0;
rad_kvgroup kv = 0;
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
LinearFP8 q{}, k{}, v{}, o{};
NormQuantFP8 nq_h{};
QuantFP8 q_attn{};
rad_op op_q_norm = 0, op_k_norm = 0;
rad_op op_rope_q = 0, op_rope_k = 0, op_attn = 0, op_kv_store = 0;
rad_op op_qkr_store = 0; /* Q/K norms, NeoX rotary and BF16 cache store, decode band */
int64_t qkr_rows = 0;
rad_op op_ar = 0, op_add = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
const Wire& wire, const Src& src, bool fold = false, bool add_out = true);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rad_kvgroup group, const Wire& wire, const Src& src,
bool fold, bool add_out) {
g = geom;
w = wire;
layer = l;
kv = group;
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
if (g.world > g.n_head_kv_all) {
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
"with n_head_kv = %lld\n", __func__, g.world,
(long long)g.n_head_kv_all);
return RAD_E_UNSUPPORTED;
}
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
if (!w_norm || !w_q_norm || !w_k_norm) return RAD_E_INVAL;
// As in the other pre-norm blocks, absorb a preceding delta into the residual stream.
// The fused kernel normalises the BF16-rounded sum, not an unrounded FP32 substitute.
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
fold ? w.x : 0));
RAD_ARCH_TRY(q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), q_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), {src.q}, w.h, w.q));
RAD_ARCH_TRY(k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), {src.k}, w.h, w.k));
RAD_ARCH_TRY(v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), {src.v}, w.h, w.v));
auto head_norm = [&](int64_t heads, rad_weight wt) {
return RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(wt));
};
op_q_norm = rw(b, head_norm(g.n_head, w_q_norm), {w.q}, {w.q});
op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k});
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"),
{w.q}, {w.q});
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim, "neox"),
{w.k}, {w.k});
const rad_op attn = rad_decl_op(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS);
op_attn = rw(b, attn, {w.q}, {w.attn.x});
op_kv_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.k, w.v}, {});
/* The standalone chain stays available for prefill, scaled/multicomponent rotary, the int8
* cache and libraries without the fold. A 128-channel BF16 decode prologue is otherwise five tiny
* launches; the fused kernel preserves the BF16 norm rounding before the rotary. */
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
!std::strcmp(g.kv_dtype, "bf16") &&
!g.rope_mc && g.yarn.factor == 0.0f &&
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
qkr_rows = qk_fuse_rows(g);
op_qkr_store = RAD_OP(b, "qkv_norm_rope_kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, qkr_rows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps),
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
RAD_INT("v_norm", 0), RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_WEIGHTS(w_q_norm, w_k_norm));
if (!op_qkr_store || !rad_op_resolved(b, op_qkr_store)) op_qkr_store = 0;
if (op_qkr_store)
op_qkr_store = rw(b, op_qkr_store, {w.q, w.k, w.v}, {w.q, w.k, w.v});
}
RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
RAD_SHARD_COL, grp_layer(l), {src.o}, w.attn, w.h.x));
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{w.h.x}, {w.h.x});
if (add_out) op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h.x}, {w.x});
return op_attn && op_kv_store && (!add_out || op_add) ? RAD_OK : RAD_E_INVAL;
}
inline void AttnQKFP8::step(RadCtx* c, const RadBatch* batch) const {
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
const int64_t T = batch->n_tok;
nq_h.step(c, T);
q.step(c, w.h, w.q, T);
k.step(c, w.h, w.k, T);
v.step(c, w.h, w.v, T);
if (op_qkr_store && T <= qkr_rows) {
RAD_ISSUE_N(c, op_qkr_store, T, brows(w.q, T), brows(w.k, T), brows(w.v, T),
rope_posmc(g, batch, T), RAD_W(w_q_norm), RAD_W(w_k_norm),
praw(slot, RAD_I32, T), kv_cache(kv, layer));
} else {
RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_kv_store, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
kv_cache(kv, layer));
}
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T));
q_attn.step(c, T);
o.step(c, w.attn, w.h.x, T);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
}
} // namespace arch
} // namespace rad
#endif /* HYV3_ATTENTION_H */
+535
View File
@@ -0,0 +1,535 @@
/* Shared HYV3 graph. Thin architecture wrappers select the source descriptor and source format. */
#ifndef HYV3_NS
#define HYV3_NS hyv3_fp8
#endif
#ifndef HYV3_QUANT
#define HYV3_QUANT "fp8"
#endif
#ifndef HYV3_FP8_SOURCE
#define HYV3_FP8_SOURCE 1
#endif
#ifndef HYV3_PLUGIN_NAME
#define HYV3_PLUGIN_NAME "hyv3_fp8"
#endif
#ifndef HYV3_GGUF_SOURCE
#define HYV3_GGUF_SOURCE 0
#endif
#include <arch/rad_arch.h>
#include "hyv3_attention.h"
#include "rad_abi_layout.h"
#include <arch/rad_block_mlp_fp8.h>
#include <arch/rad_block_moe_fp8.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
namespace HYV3_NS {
using namespace rad::arch;
struct Layer {
bool dense = false;
AttnQKFP8 attn{};
MlpFP8 dense_mlp{};
MoeFP8 moe{};
};
struct Model {
Names nm{};
Geom g{};
int64_t n_ff_expert = 0, n_ff_shared = 0;
rad_kvgroup kv_full = 0;
rad_buf x = 0, h_out = 0, logits = 0;
ActFP8 h{};
rad_buf q = 0, k = 0, v = 0;
ActFP8 attn{};
rad_buf dense_gate_up = 0;
ActFP8 dense_ffn{};
MoeFP8::Wire mw{};
rad_weight token = 0, final_norm = 0, lm_head = 0;
rad_op embed = 0, embed_ar = 0, shared_one = 0, final_rms = 0, gather = 0, logits_op = 0;
std::vector<Layer> layers;
};
static Model models[MAX_SLOTS];
static int check_format(const RadModelMeta* meta) {
const char* q = meta && meta->quant ? meta->quant : "";
#if HYV3_GGUF_SOURCE
if (std::strcmp(q, "gguf_ftype_15") != 0) {
fprintf(stderr, "radiance: HYV3 GGUF adapter expects quant descriptor 'gguf_ftype_15'; "
"got '%s'\n", *q ? q : "(none)");
return RAD_E_UNSUPPORTED;
}
#elif HYV3_FP8_SOURCE
if (std::strcmp(q, "fp8") != 0) {
fprintf(stderr, "radiance: HYV3 FP8 expects quant descriptor 'fp8'; got '%s'\n",
*q ? q : "(none)");
return RAD_E_UNSUPPORTED;
}
const char* fmt = rad_meta_gets(meta, "quantization_config.fmt", nullptr);
if (fmt && std::strcmp(fmt, "e4m3") != 0) return RAD_E_UNSUPPORTED;
const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr);
if (method && std::strcmp(method, "fp8") != 0) return RAD_E_UNSUPPORTED;
#else
if (*q) {
fprintf(stderr, "radiance: HYV3 BF16 expects an unquantized checkpoint; got '%s'\n", q);
return RAD_E_UNSUPPORTED;
}
#endif
return RAD_OK;
}
static int check_model_config(const RadModelMeta* meta, const Geom& g, Model& model) {
if (meta_text_geti(meta, "qk_norm", 0) != 1 ||
meta_text_geti(meta, "moe_router_use_sigmoid", 0) != 1 ||
meta_text_geti(meta, "moe_router_enable_expert_bias", 0) != 1 ||
meta_text_geti(meta, "route_norm", 0) != 1 ||
meta_text_geti(meta, "enable_moe_fp32_combine", 0) != 1 ||
meta_text_geti(meta, "attention_bias", 0) != 0 ||
meta_text_geti(meta, "mlp_bias", 0) != 0) {
fprintf(stderr, "radiance: hyv3 requires QK norm, sigmoid routing with correction bias, "
"route normalization, FP32 MoE combine, and bias-free projections\n");
return RAD_E_UNSUPPORTED;
}
const int64_t first_dense = meta_text_geti(meta, "first_k_dense_replace", -1);
const int64_t n_expert = meta_text_geti(meta, "num_experts", 0);
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", 0);
const int64_t n_shared = meta_text_geti(meta, "num_shared_experts", 0);
const int64_t moe_intermediate = meta_text_geti(meta, "moe_intermediate_size", 0);
const int64_t n_ff_shared = meta_text_geti(meta, "expert_hidden_dim", 0);
model.n_ff_expert = meta_text_geti(meta, "expert_hidden_dim", 0);
const int64_t route_norm = meta_text_geti(meta, "route_norm", 0);
const double route_scale = meta_text_getf(meta, "router_scaling_factor", 1.0);
const char* schedule = meta_text_gets(meta, "mlp_layer_types", nullptr);
std::vector<int> kinds;
if (first_dense != 1 || n_expert != meta->n_expert || top_k != meta->n_expert_used ||
n_expert != 128 || top_k != 8 || n_shared != 1 || model.n_ff_expert != 768 ||
n_ff_shared != 768 || moe_intermediate != 1536 || route_norm != 1 ||
!std::isfinite(route_scale) || route_scale <= 0 ||
std::fabs(route_scale - 2.826) > 1e-6 || model.n_ff_expert % RAD_FP8_BLOCK != 0) {
fprintf(stderr, "radiance: hyv3: unsupported MoE geometry/config; expected 128 experts, "
"top-8, 768-wide routed and shared experts, normalized "
"sigmoid routing scaled by 2.826, and one dense first layer\n");
return RAD_E_UNSUPPORTED;
}
if (schedule && *schedule) {
RAD_ARCH_TRY(parse_layer_kinds("hyv3", schedule, {"sparse"}, "dense", &kinds));
if ((int64_t)kinds.size() != g.n_layer) {
fprintf(stderr, "radiance: hyv3: mlp_layer_types names %zu layers; the model has %lld\n",
kinds.size(), (long long)g.n_layer);
return RAD_E_UNSUPPORTED;
}
for (int64_t l = 0; l < g.n_layer; ++l) {
const int want = l == 0 ? 0 : 1;
if (kinds[(size_t)l] != want) {
fprintf(stderr, "radiance: hyv3: layer %lld has an unsupported MLP kind; expected "
"dense at layer 0 and sparse afterwards\n", (long long)l);
return RAD_E_UNSUPPORTED;
}
}
}
const int64_t shared_width = n_ff_shared * n_shared;
if (shared_width <= 0 || shared_width % RAD_FP8_BLOCK != 0) return RAD_E_SHAPE;
model.n_ff_shared = shared_width;
return RAD_OK;
}
static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) {
const int64_t blocks = width / RAD_FP8_BLOCK;
const int64_t base = blocks / world, rem = blocks % world;
const int64_t first = rank * base + std::min<int64_t>(rank, rem);
const int64_t count = base + (rank < rem ? 1 : 0);
*lo = first * RAD_FP8_BLOCK;
*hi = (first + count) * RAD_FP8_BLOCK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = models[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
int status = check_format(meta);
if (status < 0) return status;
status = geom_from(m.g, meta, ctx, "bf16", RAD_BF16);
if (status < 0) return status;
Geom& g = m.g;
Names& nm = m.nm;
if (g.n_layer < 2 || g.n_embd != 2048 || g.n_head_all != 32 || g.n_head_kv_all != 4 ||
g.head_dim != 128 || g.n_vocab_all != 120832 ||
(g.world != 1 && g.world != 2)) {
fprintf(stderr, "radiance: hyv3 supports Hy-Memory's 2048-wide, 32/4-head, "
"head_dim=128 geometry at tensor-parallel world sizes 1 or 2\n");
return RAD_E_UNSUPPORTED;
}
status = check_model_config(meta, g, m);
if (status < 0) return status;
if (ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_I8) {
fprintf(stderr, "radiance: HYV3 serves a bf16 or an int8 KV cache, not %s\n",
rad_dtype_name(ctx->kv_dtype));
return RAD_E_UNSUPPORTED;
}
status = yarn_from(g, meta, "", g.head_dim);
if (status < 0) return status;
const int64_t n_expert_all = meta_text_geti(meta, "num_experts", meta->n_expert);
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
if (n_expert_all % g.world != 0) return RAD_E_SHAPE;
const int64_t n_expert_local = n_expert_all / g.world;
/* ---- Full-attention KV cache. All layers share one group. */
RadKVGroupDecl kd{};
kd.kind = RAD_KV_FULL;
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
kd.n_head_kv = g.n_head_kv;
kd.head_dim = g.head_dim;
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &kd);
if (!m.kv_full) return RAD_E_INVAL;
g.kv_dtype = rad_dtype_name(kd.dtype);
const int64_t T = g.max_tok, qd = g.q_dim(), kvd = g.kv_dim();
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, g.n_embd});
m.h.x = decl_b(b, nm.f("h"), RAD_BF16, {T, g.n_embd});
RAD_ARCH_TRY(m.h.declare_qs(b, nm, g, "h", g.n_embd, 0, !HYV3_FP8_SOURCE));
m.q = decl_b(b, nm.f("attn_q"), RAD_BF16, {T, qd});
m.k = decl_b(b, nm.f("attn_k"), RAD_BF16, {T, kvd});
m.v = decl_b(b, nm.f("attn_v"), RAD_BF16, {T, kvd});
m.attn.x = decl_b(b, nm.f("attn_out"), RAD_BF16, {T, qd});
RAD_ARCH_TRY(m.attn.declare_qs(b, nm, g, "attn_out", qd, 0, !HYV3_FP8_SOURCE));
m.dense_gate_up = decl_b(b, nm.f("dense_gate_up"), RAD_BF16, {T, 2 * g.n_ff});
m.dense_ffn.x = decl_b(b, nm.f("dense_ffn"), RAD_BF16, {T, g.n_ff});
RAD_ARCH_TRY(m.dense_ffn.declare_qs(b, nm, g, "dense_ffn", g.n_ff, 0, !HYV3_FP8_SOURCE));
m.h_out = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
/* The router is replicated, while the routed experts are expert-parallel. The shared expert
* is split only on whole FP8 scale blocks; the final block remainder is assigned to early
* ranks. At TP2, routed and shared BF16 outputs are all-reduced separately before FP32 combine. */
MoeFP8::Config mc{};
mc.n_expert_all = n_expert_all;
mc.n_expert = n_expert_local;
mc.expert_base = n_expert_local * g.rank;
mc.probed_expert = mc.expert_base;
mc.top_k = top_k;
mc.n_ff_exp = m.n_ff_expert;
mc.norm_topk = 1;
mc.sigmoid_router = 1;
mc.route_scale = meta_text_getf(meta, "router_scaling_factor", 2.826);
mc.shared_ungated = 1;
mc.shared_fp32_combine = 1;
mc.shared_one_external = g.world == 1;
mc.router_fuse = 1;
mc.rows = T < 2048 ? T : 2048;
block_slice_128(m.n_ff_shared, g.world, g.rank, &mc.shared_lo, &mc.shared_hi);
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
#if HYV3_FP8_SOURCE
/* The source's per-tensor scales are imported by the recipe to format 9 (block FP8 with F32
* 128x128 scales). The model probes the source before recipe planning, so state that encoding
* explicitly here. */
mc.expert_f32_scale = 1;
#endif
const int64_t R = T, S = mc.rows * top_k;
m.mw.x = m.x;
m.mw.h = m.h;
m.mw.logits = decl_b(b, nm.f("moe_logits"), RAD_F32, {R, n_expert_all});
m.mw.ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, top_k});
m.mw.ew = decl_b(b, nm.f("moe_weights"), RAD_F32, {R, top_k});
m.mw.eoff = decl_b(b, nm.f("moe_offsets"), RAD_I32, {n_expert_local + 1});
m.mw.ecnt = decl_b(b, nm.f("moe_counts"), RAD_I32, {n_expert_local}, RAD_BUF_PERSIST);
m.mw.sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {S});
m.mw.egu = decl_b(b, nm.f("moe_gate_up"), RAD_BF16, {S, 2 * mc.n_ff_exp});
m.mw.eff.x = decl_b(b, nm.f("moe_ffn"), RAD_BF16, {S, mc.n_ff_exp});
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, !HYV3_FP8_SOURCE));
m.mw.edn = decl_b(b, nm.f("moe_down"), RAD_BF16, {S, g.n_embd});
m.mw.moe = decl_b(b, nm.f("moe_routed"), RAD_BF16, {T, g.n_embd});
m.mw.sgu = decl_b(b, nm.f("shared_gate_up"), RAD_BF16, {T, 2 * mc.n_ff_shared});
m.mw.sff.x = decl_b(b, nm.f("shared_ffn"), RAD_BF16, {T, mc.n_ff_shared});
RAD_ARCH_TRY(m.mw.sff.declare_qs(b, nm, g, "shared_ffn", mc.n_ff_shared, 0,
!HYV3_FP8_SOURCE));
m.mw.sout = decl_b(b, nm.f("shared_out"), RAD_BF16, {T, g.n_embd});
m.mw.sgate = decl_b(b, nm.f("shared_one"), RAD_BF16, {T, 1});
if (mc.shared_one_external) {
m.shared_one = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 1),
RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)),
RAD_NOWEIGHTS), {}, {m.mw.sgate});
if (!m.shared_one) return RAD_E_INVAL;
}
/* ---- Token embedding and head. */
#if HYV3_GGUF_SOURCE
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("token_embd.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("output_norm.weight")));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("output.weight"),
nm.ckpt("token_embd.weight")));
#else
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("model.embed_tokens.weight")));
#endif
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.final_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.lm_head = decl_w(b, nm.f("output.weight"),
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(m.token)),
{}, {m.x});
if (g.world > 1)
m.embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{m.x}, {m.x});
AttnQKFP8::Wire aw{};
aw.x = m.x; aw.h = m.h; aw.q = m.q; aw.k = m.k; aw.v = m.v; aw.attn = m.attn;
MlpFP8::Wire dw{};
dw.x = m.x; dw.h = m.h; dw.gate_up = m.dense_gate_up; dw.ffn = m.dense_ffn;
m.layers.resize((size_t)g.n_layer);
for (int64_t l = 0; l < g.n_layer; ++l) {
Layer& lay = m.layers[(size_t)l];
lay.dense = (l == 0);
#if HYV3_GGUF_SOURCE
const char* pre = nm.ckpt("blk.%lld", (long long)l);
#else
const char* pre = nm.ckpt("model.layers.%lld", (long long)l);
#endif
AttnQKFP8::Src as{};
#if HYV3_GGUF_SOURCE
as.norm = nm.ckpt("%s.attn_norm.weight", pre);
as.q = nm.ckpt("%s.attn_q.weight", pre);
as.k = nm.ckpt("%s.attn_k.weight", pre);
as.v = nm.ckpt("%s.attn_v.weight", pre);
as.q_norm = nm.ckpt("%s.attn_q_norm.weight", pre);
as.k_norm = nm.ckpt("%s.attn_k_norm.weight", pre);
as.o = nm.ckpt("%s.attn_output.weight", pre);
#else
as.norm = nm.ckpt("%s.input_layernorm.weight", pre);
as.q = nm.ckpt("%s.self_attn.q_proj.weight", pre);
as.k = nm.ckpt("%s.self_attn.k_proj.weight", pre);
as.v = nm.ckpt("%s.self_attn.v_proj.weight", pre);
as.q_norm = nm.ckpt("%s.self_attn.q_norm.weight", pre);
as.k_norm = nm.ckpt("%s.self_attn.k_norm.weight", pre);
as.o = nm.ckpt("%s.self_attn.o_proj.weight", pre);
#endif
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
// Each norm folds its predecessor's residual add. The first attention reads the
// embedding directly; the final feed-forward keeps its add for the plain output norm.
// Keep collective placement and both routed/shared BF16 rounding points.
status = lay.attn.declare(b, nm, g, (int)l, m.kv_full, aw, as, l > 0, false);
if (status < 0) {
fprintf(stderr, "radiance: hyv3: attention layer %lld declaration failed (%d)\n",
(long long)l, status);
return status;
}
if (lay.dense) {
MlpFP8::Src ds{};
#if HYV3_GGUF_SOURCE
ds.norm = nm.ckpt("%s.ffn_norm.weight", pre);
ds.gate = nm.ckpt("%s.ffn_gate.weight", pre);
ds.up = nm.ckpt("%s.ffn_up.weight", pre);
ds.down = nm.ckpt("%s.ffn_down.weight", pre);
#else
const char* mlp = nm.ckpt("%s.mlp", pre);
ds.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
ds.gate = nm.ckpt("%s.gate_proj.weight", mlp);
ds.up = nm.ckpt("%s.up_proj.weight", mlp);
ds.down = nm.ckpt("%s.down_proj.weight", mlp);
#endif
status = lay.dense_mlp.declare(b, nm, g, (int)l, dw, ds, true,
l + 1 == g.n_layer);
if (status < 0) {
fprintf(stderr, "radiance: hyv3: dense MLP declaration failed (%d)\n", status);
return status;
}
} else {
MoeFP8::Src ms{};
ms.cfg = mc;
#if HYV3_GGUF_SOURCE
ms.norm = nm.ckpt("%s.ffn_norm.weight", pre);
ms.router = nm.ckpt("%s.ffn_gate_inp.weight", pre);
ms.router_bias = nm.ckpt("%s.exp_probs_b", pre);
ms.experts_gate = nm.ckpt("%s.ffn_gate_exps.weight", pre);
ms.experts_up = nm.ckpt("%s.ffn_up_exps.weight", pre);
ms.experts_down = nm.ckpt("%s.ffn_down_exps.weight", pre);
ms.shared_mlp_gate = nm.ckpt("%s.ffn_gate_shexp.weight", pre);
ms.shared_mlp_up = nm.ckpt("%s.ffn_up_shexp.weight", pre);
ms.shared_mlp_down = nm.ckpt("%s.ffn_down_shexp.weight", pre);
#else
const char* mlp = nm.ckpt("%s.mlp", pre);
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
ms.router = nm.ckpt("%s.router.gate.weight", mlp);
ms.router_bias = nm.ckpt("%s.expert_bias", mlp);
ms.experts = nm.ckpt("%s.experts", mlp);
ms.shared = nm.ckpt("%s.shared_mlp", mlp);
#endif
#if !HYV3_FP8_SOURCE
status = MoeFP8::probe(b, nm, (int)l, ms, &ms.cfg);
if (status < 0) {
fprintf(stderr, "radiance: HYV3: expert format probe failed at layer %lld (%d)\n",
(long long)l, status);
return status;
}
#endif
status = lay.moe.declare(b, nm, g, (int)l, m.mw, ms, true, l + 1 == g.n_layer);
if (status < 0) {
fprintf(stderr, "radiance: hyv3: MoE layer %lld declaration failed (%d)\n",
(long long)l, status);
return status;
}
}
}
m.final_rms = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.final_norm)),
{m.x}, {m.h.x});
m.gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.h.x}, {m.h_out});
m.logits_op = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.lm_head)),
{m.h_out}, {m.logits});
rad_note(b, "HYV3: %lld layers (dense first, then top-%lld/%lld sigmoid MoE), %lld/%lld "
"attention/KV heads x %lld; expert width %lld, shared width %lld, router scale %.3f",
(long long)g.n_layer, (long long)top_k, (long long)n_expert_all,
(long long)g.n_head_all, (long long)g.n_head_kv_all, (long long)g.head_dim,
(long long)m.n_ff_expert, (long long)m.n_ff_shared, mc.route_scale);
#if HYV3_FP8_SOURCE
rad_note(b, "E4M3 per-tensor scales are imported to 128x128 F32 planes; Q/K RMSNorm precedes "
"NeoX RoPE and shared/routed outputs combine in FP32");
#elif HYV3_GGUF_SOURCE
rad_note(b, "GGUF-source HYV3; Q4_K/Q6_K tensors are decoded and recipe-converted to native "
"Radiance weights, adding quantization loss to an already-lossy source");
#else
rad_note(b, "BF16-source HYV3; per-weight recipes may quantize linears or routed experts; "
"Q/K RMSNorm precedes NeoX RoPE and shared/routed outputs combine in FP32");
#endif
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = models[rad_slot(c)];
RAD_ISSUE(c, m.embed,
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.token),
brows(m.x, batch->n_tok));
if (m.embed_ar)
RAD_ISSUE_N(c, m.embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
brows(m.x, batch->n_tok), RAD_NONE);
// All TP1 ungated gathers read this same ones plane; no per-layer fill or combine launch.
if (m.shared_one)
RAD_ISSUE_N(c, m.shared_one, batch->n_tok, brows(m.mw.sgate, batch->n_tok));
for (Layer& layer : m.layers) {
layer.attn.step(c, batch);
if (layer.dense) layer.dense_mlp.step(c, batch);
else layer.moe.step(c, batch);
}
RAD_ISSUE(c, m.final_rms, brows(m.x, batch->n_tok), RAD_W(m.final_norm),
brows(m.h.x, batch->n_tok));
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.gather, batch->n_out,
brows(m.h.x, batch->n_tok), praw(batch->out_ids, RAD_I32, batch->n_out),
brows(m.h_out, batch->n_out));
RAD_ISSUE_N(c, m.logits_op, batch->n_out,
brows(m.h_out, batch->n_out), RAD_W(m.lm_head),
brows(m.logits, batch->n_out));
}
}
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
return RAD_OK;
}
} // namespace HYV3_NS
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(HYV3_NS)
static const char* const kHyv3ToolTriggers[] = { "<tool_calls>" };
static const RadChatFormat kHyv3ChatFormat = {
.struct_size = sizeof(RadChatFormat),
.name = "hyv3",
.reasoning_open = "<think>",
.reasoning_close = "</think>",
.reasoning_breaks = kHyv3ToolTriggers,
.n_reasoning_breaks = 1,
.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT,
.section_open = "<tool_calls>",
.section_close = "</tool_calls>",
.name_prefix = "<tool_call>",
.name_suffix = "<tool_sep>",
.call_end = "</tool_call>",
.arg_prefix = "<arg_key>",
.arg_name_suffix = "</arg_key>\n",
.arg_value_prefix = "<arg_value>",
.arg_value_suffix = "</arg_value>",
.string_value = RAD_CHAT_VALUE_RAW,
.other_value = RAD_CHAT_VALUE_JSON,
.triggers = kHyv3ToolTriggers,
.n_triggers = 1,
.args_form = RAD_CHAT_ARGS_TAGGED,
};
extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
return &kHyv3ChatFormat;
}
extern "C" const char* rad_arch_id(void) { return "hyv3"; }
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
extern "C" const char* rad_arch_quant(void) { return HYV3_QUANT; }
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
return HYV3_NS::declare(b, m, c);
}
extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
HYV3_NS::step(c, batch);
}
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
RAD_PLUGIN_ABI_LAYOUT_EXPORT
extern "C" const RadPluginInfo* rad_plugin_info(void) {
static const RadPluginInfo info = {
RAD_PLUGIN_ARCH, HYV3_PLUGIN_NAME, "0.2.0",
"Tencent Hy-Memory HYV3: Q/K-normalized full attention and sigmoid MoE", ""
};
return &info;
}
#endif
#undef HYV3_NS
#undef HYV3_QUANT
#undef HYV3_FP8_SOURCE
#undef HYV3_PLUGIN_NAME
#undef HYV3_GGUF_SOURCE
+9
View File
@@ -0,0 +1,9 @@
# Built in radiance's tree, or standalone against an installed radiance.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(hyv3_fp8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(hyv3_fp8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hyv3_fp8.cpp)
Loaded 100 of 1733 files, more files were not shown because too many files have changed in this diff. Show more