Compare commits

...
184 Commits
Author SHA1 Message Date
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
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
Deadcode 89cee7ce41 radiance 1.3.0
- #47: llama-server's request fields, routes and sampler order, and /props (with baKon's model
  entry: max_model_len, root and capabilities on /v1/models, and /v1/models/:id)
- new APIs: Anthropic's Messages API (/v1/messages), OpenAI's Responses API (/v1/responses),
  llama-server's /completion and /infill, logprobs (OpenAI's logprobs and top_logprobs, up to
  20; llama-server's n_probs), OpenAI's legacy `functions`, and X-Api-Key beside the bearer key
- #4: --model takes a Hugging Face repo id (owner/name), fetched before startup into
  ~/.cache/radiance/hf or --download-dir and checked for changes at every start (redxherring)
- #46: --tp 3 --tp-wire wht6 serves -- a three-rank two-shot all-reduce with uneven shards and
  the tiered-int8 wire over it (baKon); scripts/cardclock.py names what holds each card's clock
  under load (baKon)
- CPU-only serving works again; --kernels names the kernel libraries to load; a model the
  loaded libraries cannot fully serve refuses at startup instead of failing its first request;
  --vram-kv-mib and --vram-weights-mib are gone (the split is automatic)
- --embedding-placement ram is the default, and `auto` is gone
- #40: Swift 1.5 recipes; rad-convert reads which shard holds a tensor from the index
- #53: the pinned host pool gets huge pages where shmem THP is off; #57: a crash on video with
  an odd frame width is fixed
2026-10-08 18:22:08 +02:00
redxherring 6a2ee986d6 serve: --help notes --model also takes an HF repo id 2026-10-08 17:47:27 +02:00
redxherring 7e796642e6 serve: --model takes an HF repo id, fetched to $RADIANCE_HOME/hf via hfget.sh
A non-path owner/name is downloaded before bring-up and the model path
rewritten to the cached dir, so a new user points --model at a repo link
instead of a pre-fetched checkpoint. hfget.sh now keys its re-run skip on
lfs.oid (sha256) for LFS files and size for the rest, recorded in a
.hfget-manifest, so a same-size weight update is caught and re-fetched
while a warm cache stays a no-rehash no-op.
2026-10-08 17:47:27 +02:00
baKon 9238b1f23d libr4d: --tp-wire wht6 at three ranks, the tiered-int8 wire over the uneven two-shot
--tp 3 --tp-wire wht6 had no kernel: the lossy rows were world_size 2 (rotated 6-bit) and 4
(tiered int8 over the two-shot). The tiered-int8 two-shot is already written over the world size,
and what kept it at four was the even split it shards by -- numel % (32 x ws) -- which a 2048-wide
row (64 groups) meets at three ranks one step in three.

The kernel now splits ng = numel/32 groups as evenly as they divide, the first ng % ws shards one
group longer, and lays every slot out for the longest shard, so writer and reader agree on one
number. At four ranks the entry still requires numel % 128 and the split is the even one it was.
ar_twoshot_3rank_ti8 is the only lossy row at three, so as at four it resolves at every size; a
message under min_bytes, or not whole groups, goes to the exact one-shot.

r4d_selftest holds it to what a lossy wire can be held to: every rank the same bytes, the declined
messages the exact fold bit for bit, and the rest within the int8 wire's error of the fp32 sum
(relative RMS < 1%), over groups % 3 of 0, 1 and 2 with outliers, to the 20971520 ceiling. The
--tp-wire help, the startup LOSSY warning, README, GUIDE and TP3.md say three ranks.
2026-10-08 17:16:10 +02:00
baKon 6b4a67f52e libr4d: a three-rank two-shot all-reduce, with shards one word uneven
At three ranks the exact all-reduce was the one-shot at every size: the two-shot required the
message to shard evenly, and a 2048-wide bf16 row is 256 16-byte words, a multiple of 3 only one
step in three. Every prefill chunk therefore sent twice its message per rank where the two-shot
sends 4/3.

The two-shot kernel now splits n16 words into shards of n16/ws, the first n16 % ws one word longer,
with region B at the longest shard. At 4 and 8 ranks every message the entries accept divides, so
nothing there changes. ar_twoshot_3rank_exact takes the band above R4D_AR_WIDE_ONESHOT_MAX_ELEMS the
way the 4- and 8-rank rows do. Its fold is the one-shot's -- fp32, ascending rank order -- so the
band edge between the two rows changes no bits.

r4d_selftest runs both three-rank rows through a per-element oracle (bf16 and fp32, words % 3 of 0,
1 and 2, 16 words to the 20971520-element ceiling, in and out of place, back to back on one
instance).
2026-10-08 17:16:10 +02:00
baKon a97985e7c2 scripts/cardclock.py: what holds each card's clock under a sustained load, and which card the step waits for
A tensor-parallel step ends when its slowest rank does, and under a sustained load the firmware picks
each card's clock: the power limit, a temperature or current limit, or the top of the card's
voltage/frequency curve. The same image then reads several percent apart from one boot to the next,
depending on which card heats first and how hard its limit bites.

cardclock.py reads every AMD card's gpu_metrics table ten times a second (read-only, no root) and
counts a throttler bit only when the clock is lower while it is set -- some firmware keeps a bit on at
idle -- then names the card the step waits for, what holds it, and the setting that addresses it. The
engine's own step counters sit beside it per window, so a slow window is attributed (slower steps,
fewer tokens per step, host time between steps) before anyone tunes a card. It drives its own greedy
load, or with --watch only samples a server that real traffic is driving; --compare puts two saved
runs side by side.
2026-10-08 17:16:06 +02:00
baKon 7c0bd03841 serve: the model entry carries the capabilities /server_info reports
OpenAI's model object has no field for what a model can be asked for, so a client learned it
by sending a request and reading the refusal. The entry it already fetches now carries the same
capabilities object /server_info does (tools, reasoning, grammar, media, logprobs, the reasoning
efforts the template takes), built by one Server::capabilities() so the two cannot disagree.
2026-10-08 15:57:51 +02:00
baKon d5b584a4c1 serve: the model entry names the file behind the served name as root
A served name is chosen for clients and says nothing about which container is behind it.
Report what --model named as `root`, the field vLLM fills with the path it loaded; left out
when the server has none.
2026-10-08 15:57:51 +02:00
baKon 3a3345951f serve: /v1/models/:id answers the model object, not a list of one
OpenAI's retrieve returns the entry itself, and its SDK reads `id` off the top level, where
the list of one this route answered before has none. /v1/models still answers the list.
2026-10-08 15:57:51 +02:00
baKon 86128c2e75 serve: /v1/models reports max_model_len, the context the server runs with
The model list carried only the id, so a client had no way to read the context the server
was started with and guessed it from the model's name. Carry the field vLLM's model card does:
the server's max_ctx (--max-model-len, else the container's trained length), on both
/v1/models and /v1/models/:id, and leave it out when the length is unknown.
2026-10-08 15:57:51 +02:00
baKon 7fd2cd7fa6 serve: /props answers what llama-server clients read
Front-ends built against llama-server size their context from /props'
default_generation_settings.n_ctx, decide whether to offer images from modalities, and read the
defaults a request inherits; on Radiance that route was a 404. Answer it with what this server
can fill honestly, under llama-server's names: n_ctx (the context one request may use, left out
when unknown), total_slots, modalities, the sampler defaults and build_info. No chat template
text or GGUF metadata -- the server has neither.
2026-10-07 17:27:29 -05:00
Deadcode 7d840861af radiance 1.2.4
- EmbeddingGemma 2 (google/embeddinggemma-2): text, image, video and audio embeddings on the
  card (libr4d) and on the CPU (libavx); prompt_name, Matryoshka dimensions, image budgets,
  mixed content parts and the messages form on /v1/embeddings
- #43: on serves that lend the activation arena to the experts (Qwen3.8-Flash-Next with
  expert_tiered), every image after the first read its rows from the wrong place -- garbage
  replies, or an earlier request's image. Fixed
- the Qwen vision towers' attention resolves on the card again (broken on main after 1.2.3,
  never released)
- #42: a warning at startup when amdgpu cwsr_enable is 0, and a stalled queue is reported as
  slow or stuck; the guide covers the GPU-hang-and-reset chain
2026-10-07 22:42:45 +02:00
927 changed files with 270005 additions and 81500 deletions

No files matched your search

+1
View File
@@ -5,3 +5,4 @@ compile_commands.json
*.rad
/sync-jarvis.sh
__pycache__/
.cache/
+122 -217
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.2.3 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 1.9.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -13,31 +12,30 @@ 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 and video parts with libavformat/libavcodec/libswscale")
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_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 +48,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 +63,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 +79,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 +159,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
# container:
#
# 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 +172,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 is routed (moe_gemm_q,
# router_topk, moe_scatter, 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,79 +184,41 @@ 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()
# 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.
# The downloader behind `radiance --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-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")
@@ -316,32 +243,29 @@ endif()
find_package(Threads REQUIRED)
# ---------------------------------------------------------------- media decoding
# An image or video part of a chat request is decoded by libavformat/libavcodec and converted by
# libswscale (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)
if(PkgConfig_FOUND)
pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale)
pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale
libswresample)
endif()
if(RAD_FFMPEG_FOUND)
message(STATUS "radiance: media decoding via libavformat ${RAD_FFMPEG_libavformat_VERSION}")
elseif(RAD_WITH_FFMPEG STREQUAL "ON")
message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale were not found.")
message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale/libswresample were not found.")
else()
message(STATUS "radiance: no libavformat -- image and video input will be refused")
message(STATUS "radiance: no libavformat -- image, video and audio input will be refused")
endif()
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.
@@ -349,13 +273,10 @@ 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.
# 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()
@@ -367,55 +288,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(
@@ -431,14 +336,12 @@ 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)
@@ -446,3 +349,5 @@ install(FILES vendor/nlohmann/LICENSE.MIT
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME nlohmann-json.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)
+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"
}
]
}
+183 -68
View File
@@ -1,39 +1,44 @@
# 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; 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; libr4d serves RDNA4 only and
# drops every architecture outside gfx12. 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,24 +51,29 @@ 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 - \
&& tar -xJf ffmpeg.tar.xz && cd "ffmpeg-${FFMPEG_VERSION}" \
&& ./configure --prefix=/opt/ffmpeg --enable-shared --disable-static --disable-debug \
--disable-programs --disable-doc --disable-network --disable-autodetect --disable-everything \
--disable-avdevice --disable-avfilter --disable-swresample \
--enable-zlib --enable-libdav1d \
--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 \
--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 \
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl \
--disable-avdevice --disable-avfilter --enable-swresample \
--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 \
&& mkdir -p /opt/ffmpeg/share/doc/ffmpeg \
@@ -73,41 +83,117 @@ 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
# ------------------------------------------------------------------------------------------- llvm
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS llvm
ARG JOBS=
# 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 \
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
# 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.
# 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 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.
# 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.
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 \
cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \
&& 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,52 +201,81 @@ 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).
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' ${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
@@ -178,8 +293,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
+65 -13
View File
@@ -1,19 +1,65 @@
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, and --rope-scaling) and hazyumps (static YaRN for the Qwen rotary
paths).
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, and the
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files
- 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, 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
- 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
- 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
- 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, and Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime
- 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, and added tokens decoded as HuggingFace
decodes them
- 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
- 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
- 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
This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each.
@@ -24,3 +70,9 @@ license text is in the file named beside each.
libquant/lq_ggml_*
nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
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.
+185 -51
View File
@@ -1,15 +1,19 @@
# radiance
An LLM inference server for AMD GPUs, in C++ and HIP, with an OpenAI-compatible HTTP API. 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 (`libr4d`) target AMD RDNA4 (`gfx1200`, `gfx1201`). The serve flags
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
@@ -19,10 +23,30 @@ If you wish to support the developement of the radiance engine you can do so [he
| 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` |
| Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-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` |
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` |
| 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) | `gemma4-31b-heretic-ara-w4a8.yaml` |
| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` |
| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` |
| Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` |
| Krea 2 Raw FP8: the same, undistilled | `krea-2-raw-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-fp8) | `krea-2-raw.yaml` |
| FLUX.3 [klein] FP8: text to image and edits from up to ten pictures, one card | `flux-3-klein-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-fp8) | `flux-3-klein.yaml` |
| FLUX.3 [klein] base FP8 | `flux-3-klein-base-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-fp8) | `flux-3-klein.yaml` |
| LTX-2.5 distilled FP8: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-fp8) | `ltx-2.5.yaml` |
| LTX-2.5 base FP8 | `ltx-2.5-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-fp8) | `ltx-2.5.yaml` |
| MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` |
| FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` |
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` |
| 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) | `breeze-tts2.yaml` |
| Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` |
| TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` |
| GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, eight cards | `glm53-flash-mxfp4.rad` (171 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.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-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) | — |
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
@@ -33,25 +57,79 @@ 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
```
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 in three steps: an int8 container to
calibrate in, its Gram matrices over translation prompts, then MXFP4 with GPTQ
(`data/recipes/translategemma-27b-*.recipe`, the steps in docs/ARCHITECTURES.md). On two R9700s it
decodes 56 tok/s a stream (205 at four) and scores mean KL 0.042 against the bf16 model on held-out
translations; with a DFlash2 drafter, 152 a stream. Its chat template takes structured turns
naming the two languages and refuses the plain turn the server renders at startup, so
`translategemma-27b.yaml` serves a plain Gemma 3 template (`deploy/compose/gemma3.jinja`) and a
client sends on `/v1/completions` the prompt the checkpoint's template renders.
GLM-5.3-Flash is converted from AMD's Quark export (`amd/GLM-5.3-Flash-Quark-MXFP4`) with
`data/recipes/glm53-mxfp4.recipe`, which keeps every weight as stored except the latent
attention's small kv_b, decoded to bf16. At 171 GiB it takes eight R9700s (`--tp 8`), every expert
resident, and its own MTP layer drafts. On eight R9700s it prefills 3958 tok/s at 6k tokens,
decodes 166 tok/s on one stream and 426 over eight, and 506 under eight streams of agent turns.
It serves text only, with a bf16 KV cache. Its template knows the reasoning efforts `low` and
`high` and renders any other as its maximum, so `glm53-flash.yaml` maps `medium` and `xhigh`
to `high`.
The ParoQuant containers keep the trunk exactly as the ParoQuant releases ship it, with the learned
Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, int5 from
`Launch80/Qwen3.8-27B-PARO-int5` and MXFP4 from `MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2`, each with
`data/recipes/q38-27b-paro-mxfp4-df2.recipe` and the DFlash2 drafter. A ParoQuant container made
before 1.5.0 is refused at startup; convert it again with the old one as `--reuse`, which copies
every tensor that did not change.
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.
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). 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.
## 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 needs Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). 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:
```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
cp .env.example .env # set RADIANCE_MODELS, 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
```
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).
Every model listens on the same port and most use both cards, 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
@@ -60,67 +138,103 @@ 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 the fp8 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
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an install 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>
```
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` (`--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,
`--download-dir` must name a writable mount, since the compose files mount `/models` read-only.
These rows match the compose files, minus Flash-Next's `--prefix-cache-mib`; the three- and
four-rank rows have no compose file. The other models' flags are in their compose files.
| model | flags |
|---|---|
| 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 FP8 and MXFP4, 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` |
| 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` |
| Breeze-TTS-2 | `--tp 1` |
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
Every model here runs at up to 32 sequences a step. The Flash-Next rows (except the bf16 reference)
and the 27B in bf16 keep 8: 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 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
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 --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 flags 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 pinned on every card, so the four-rank row pins 4 × 12 GiB = 48 GiB of RAM
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 `flashnext-tp1.yaml` with 49 GiB pinned
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
Add `--api-key KEY` to require `Authorization: Bearer KEY`. Add `--debug-graph` to print every op
and the kernel it resolved to, then exit without serving. Then:
Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `--debug-graph`
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}'
```
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
budgets, long context, speculative decoding and operating a server.
@@ -130,23 +244,43 @@ 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 \
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/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \
--recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \
--draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2
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
```
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: `radiance --model /srv/models/hf/Qwen/Qwen3.8-27B-FP8`. A release
someone else quantised is read as it ships when the engine serves its form (block-scaled FP8,
Quark's MXFP4), written at its own numbers when the kernels read them in another spelling (an int4
W4A16 release, compressed-tensors' AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with
`data/recipes/q38-27b-w4a16.recipe`), and converted from its exact dequantisation when no kernel
reads it: NVFP4 (compressed-tensors' and NVIDIA ModelOpt's) to the MXFP4 kernels, an AutoRound
Flash-Next's int4 block projections to int8. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
with their `rad-convert` commands.
## 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
| | |
+256 -338
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,27 +12,26 @@
extern "C" {
#endif
/* Bumped whenever anything a plugin compiles against changes shape -- this header, rad_types.h,
/* 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
* kind of plugin reports it, and a plugin that does not report exactly this version is refused at
* load with both versions printed. 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 24u
/* ================================================================== 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;
@@ -43,8 +41,8 @@ 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 */
@@ -60,9 +58,8 @@ typedef struct RadArgs {
int world_size;
} 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 +79,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 +124,103 @@ 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. */
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. */
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 +229,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 +245,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 +323,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 +348,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 +386,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 +398,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 +430,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 +446,30 @@ 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". */
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.
/* 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.
*
* 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. */
RadFuseFn replaces;
} RadKernelInfo;
/* ================================================================== 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,38 +478,54 @@ 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 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 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);
* 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`. */
typedef int (*RadPluginReferenceFn)(void);
#ifdef __cplusplus
+954 -314
View File
File diff suppressed because it is too large. Load diff
+9 -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
+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;
}
+16 -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
@@ -74,7 +74,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 +84,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 +105,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,8 +116,8 @@ 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. */
@@ -152,9 +152,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 };
+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;
}
+33 -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,10 +100,9 @@ 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);
+530 -187
View File
@@ -1,7 +1,7 @@
/* rad_runtime.h -- the run phase. Ordinary C++ with one rule: it may only issue handles obtained
* during declare. Nothing else is constrained; in particular there is no capture discipline on
* this code, because a graph is built out of the kernels' own launch DESCRIPTIONS (RadDescribeFn
* in rad_abi.h) rather than by capturing the step. See spec.md §3.2.
* during declare. There is no capture discipline: the device backend records a pass's dispatch
* packets at the queue as they are issued and replays them (core/device/aql.cpp,
* core/runtime/ctx.h), so the step function needs no graph-safe form. See spec.md §3.2.
*/
#ifndef RAD_RUNTIME_H
#define RAD_RUNTIME_H
@@ -15,12 +15,11 @@ extern "C" {
typedef struct RadCtx RadCtx;
/* ================================================================== the step batch */
/* Built ONCE PER STEP BY THE CORE and shared by every layer and every KV group. Rebuilding it per
* KV-cache group and per layer instead turns a substantial share of a decode step into host work
* with the device idle, which is the cost spec §8 exists to avoid.
/* Built once per step by the core and shared by every layer and KV group; rebuilding it per group
* and per layer would make a large share of a decode step host work with the device idle (spec §8).
*
* Every pointer here is device memory unless the field name says _h. The host mirrors exist
* because the scheduler and the run phase both need the bounds without a device read. */
* Every pointer is device memory unless the field name says _h. The host mirrors give the
* scheduler and the run phase the bounds without a device read. */
enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 };
typedef struct RadKVGroupBatch {
@@ -30,11 +29,10 @@ typedef struct RadKVGroupBatch {
int64_t block_table_pitch;
int32_t* seqused; /* [n_seq] context length in this group, device */
int32_t* state_index; /* [n_seq, state_index_pitch] state slots per sequence, device */
/* HOW MANY SLOTS A SEQUENCE NAMES, and it is 1 unless the group's kernel asked for scratch
* beside the state. A linear kernel serving speculation does: it cannot commit the state
* until acceptance is known, so it keeps the committed one in column 0 and its own replay
* scratch in the columns after it. The engine zeroes every one of them when the sequence is
* admitted and otherwise does not look inside. Zero means 1, for a caller that predates it. */
/* State slots per sequence: 1 unless the group's kernel asked for scratch beside the state.
* A linear kernel serving speculation cannot commit the state until acceptance is known, so it
* keeps the committed state in column 0 and replay scratch in the later columns. The engine
* zeroes all of them at admission and otherwise does not look inside. Zero means 1. */
int64_t state_index_pitch;
int64_t block_size;
int64_t max_blocks;
@@ -51,22 +49,33 @@ typedef struct RadBatch {
const int32_t* positions; /* [n_tok] device */
const int32_t* cu_seqlens; /* [n_seq+1] device: sequence boundaries within this step */
const int32_t* seq_ids; /* [n_seq] device: engine-side sequence identity */
/* [n_tok] device: the runtime LoRA adapter each token's row runs with, as a slot of the
* adapter pools the core declared (docs/OPS.md, lora_shrink / lora_expand). A row whose slot is
* < 0 or >= the pools' slot count S is a base row, which an adapter op leaves untouched. Every
* row of a sequence carries its request's slot, fixed when the request was admitted, so a step
* that mixes adapters and the base needs nothing else.
*
* Null on a step with no adapter row, so always when the engine serves no adapters (no --lora
* and no --max-loras). The core issues the adapter ops itself, only when this is set; a block
* with an adapter epilogue of its own reads it too. Like every array above it sits at one
* address per rank for the engine's life and is rewritten every step, so a recorded pass
* replays it. */
const int32_t* lora_slot;
/* WHICH TOKENS THE SAMPLER WANTS LOGITS FOR: indices into THIS STEP's tokens, [n_out].
/* The tokens the sampler wants logits for: indices into this step's tokens, [n_out].
*
* A prefill chunk computes hidden states for every token in it and the sampler wants one row
* per sequence -- the last. Without this array the architecture plugin has to run the lm_head
* GEMM over all n_tok rows, which is n_tok/n_seq times the work and, at max_tok 8192 against
* a 248K vocab, an 8 GiB logits buffer instead of a 63 MiB one. The plugin issues gather_rows
* against it and then multiplies only what came back (docs/OPS.md, "Vocabulary edges").
* A prefill chunk computes hidden states for every token, but the sampler wants only each
* sequence's last. The plugin issues gather_rows over these and runs the lm_head only on the
* result (docs/OPS.md, "Vocabulary edges"); over all n_tok rows at max_tok 8192 and a 248K
* vocab the logits buffer would be 8 GiB instead of 63 MiB.
*
* n_out is 0 for a chunk that finishes no sequence, which is the ordinary middle of a long
* prefill: no logits are produced at all and the lm_head is not touched. */
* n_out is 0 for a chunk that finishes no sequence (the middle of a long prefill): no logits
* are produced and the lm_head is not run. */
int64_t n_out;
const int32_t* out_ids; /* [n_out] device */
const int32_t* q_lens; /* [n_seq] device: query length this step */
const int32_t* ctx_lens; /* [n_seq] device: context length BEFORE this step */
const int32_t* ctx_lens; /* [n_seq] device: context length before this step */
int32_t max_q_len; /* host-side bounds -- these select kernel bands */
int32_t max_ctx_len;
@@ -75,28 +84,27 @@ typedef struct RadBatch {
/* Speculative window (spec §10). n_spec == 0 for an ordinary decode step. */
int n_spec; /* draft tokens per sequence this step */
const int32_t* num_accepted; /* [n_seq] device, from the PREVIOUS verify */
const int32_t* num_accepted; /* [n_seq] device, from the previous verify */
const int32_t* spec_parent; /* [n_tok] device, tree layout; null for a linear chain */
/* THE DRAFT PASS. 0 is an ordinary step and the plugin runs the trunk; a non-zero value runs
* ONLY the draft head, and the SIGN says which kind of pass:
/* The draft pass. 0 is an ordinary step that runs the trunk; non-zero runs only the draft
* head, and the sign gives the kind:
*
* r < 0 a HISTORY pass: one row a token, gathered from the trunk step's rows
* (out_ids). The head attends to its own K and V, and nothing else in the engine
* writes those -- a prefill fills the trunk's layers and leaves the head's
* untouched. This fills them for the positions the step just committed. When
* `n_draft_out` is non-zero the pass is ALSO draft round 1: it ends in the lm_head
* over the rows `draft_out_ids` names, one a drafting sequence (see there).
* r > 1 draft round r, ONE-BASED. One row a sequence, reading the head's own output
* from the round before, ending in the lm_head; the token it samples is the r-th
* draft. There is no pass with r == 1: the history pass carries that round.
* r < 0 a history pass: one row per token, gathered from the trunk step's rows
* (out_ids). The head attends to its own K and V, which nothing else writes (a
* prefill fills only the trunk's layers); this fills them for the positions the
* step just committed. When `n_draft_out` is non-zero the pass is also draft round
* 1 and ends in the lm_head over the rows `draft_out_ids` names.
* r > 1 draft round r, one-based. One row per sequence, reading the head's output from
* the round before and ending in the lm_head; it samples the r-th draft. There is
* no pass with r == 1: the history pass carries that round.
*
* Zero is the ordinary step so that a zeroed RadBatch runs the model, the same reason
* `num_accepted` is one-based (docs/OPS.md).
*
* On any such pass `token_ids` is already shifted: the head at index i reads the token at
* i + 1, and the batch builder applies that shift so no kernel and no plugin has to know it.
* Everything else in this struct means what it means on any other step. */
* On any draft pass `token_ids` is already shifted (the head at index i reads the token at
* i + 1) by the batch builder, so no kernel or plugin applies the shift. Every other field
* keeps its usual meaning. */
int32_t draft_pass;
/* Linear-state checkpointing (spec §7.3): tokens at which the scheduler wants a checkpoint
@@ -105,157 +113,466 @@ typedef struct RadBatch {
const int32_t* checkpoint_tok; /* [n_checkpoints] device: index into this step's tokens */
const int32_t* checkpoint_slot; /* [n_checkpoints] device: destination snapshot slot */
/* THE DECODE / PREFILL SPLIT WITHIN A MIXED STEP.
/* The decode / prefill split within a mixed step.
*
* Sequences [0, n_seq_decode) carry decode rows and the rest carry prefill chunks. The
* scheduler orders every step that way, so a block that has to treat the two differently can
* issue over each as a CONTIGUOUS sub-range of the per-sequence arrays -- `cu_seqlens +
* n_seq_decode`, `state_index + n_seq_decode * pitch`, and so on -- while leaving the token
* operands at their base. That works because cu_seqlens holds ABSOLUTE row offsets: a kernel
* whose workgroup n reads cu[n] and cu[n+1] finds the right rows whichever sub-array it was
* handed, and no kernel changes to allow it.
* Sequences [0, n_seq_decode) carry decode rows and the rest prefill chunks; the scheduler
* orders every step that way. A block that treats the two differently issues over each as a
* contiguous sub-range of the per-sequence arrays (`cu_seqlens + n_seq_decode`,
* `state_index + n_seq_decode * pitch`, ...) with the token operands left at their base. This
* works because cu_seqlens holds absolute row offsets, so a kernel reading cu[n] and cu[n+1]
* finds the right rows in either sub-array.
*
* It exists because without the split a mixed step is prefill-shaped for every sequence in it,
* so the decode rows travelling with a prefill chunk cannot verify a draft and produce one
* token where they could have produced several. On an interactive load a large fraction of
* steps are mixed, so that is a large fraction of all decode rows.
* Without the split a mixed step is prefill-shaped for every sequence, so its decode rows
* cannot verify a draft and produce one token instead of several; under interactive load many
* steps are mixed.
*
* n_seq_decode == n_seq on a pure decode step and 0 on a pure prefill one, so a block that
* does not care can ignore all three fields, and one that does needs no phase test. */
* n_seq_decode == n_seq on a pure decode step and 0 on a pure prefill, so a block that does
* not care can ignore these fields, and one that does needs no phase test. */
int64_t n_seq_decode;
/* AND WHERE THEIR TOKENS END. The decode rows are tokens [0, n_tok_decode) and the prefill
* chunks are the rest, which a per-TOKEN op needs and cannot derive: each decode row is
* 1 + its own draft count, and those differ between sequences. */
/* The decode rows are tokens [0, n_tok_decode) and the prefill chunks the rest. A per-token
* op cannot derive this, since each decode row is 1 + its own draft count. */
int64_t n_tok_decode;
/* The longest query in each half, because max_q_len over a mixed step is the prefill chunk and
* banding the decode half with it would hand a thousand-row GEMM's band to eight rows.
/* The longest query in each half. max_q_len over a mixed step is the prefill chunk's, and
* banding the decode half with it would give eight rows a thousand-row GEMM's band.
*
* ONLY THE DECODE ONE IS READ TODAY, by the GDN blocks. The prefill one is here because the
* pair is what makes the split legible, and because a block whose prefill path bands on a
* per-sequence query length will want it -- the GDN prefill ops band on the step's TOTAL
* tokens instead, which they take from their operands, so they never ask. Said plainly rather
* than left to be discovered: an unread field that looks consumed is worse than one that
* says it is not. */
* Only the decode value is currently read (by the GDN blocks). The prefill value is for a
* block whose prefill path bands on a per-sequence query length; the GDN prefill ops band on
* the step's total tokens, taken from their operands. */
int32_t max_q_len_decode;
int32_t max_q_len_prefill;
/* DRAFT ROUND 1, CARRIED BY THE HISTORY PASS: [n_draft_out] device, indices into THIS pass's
* rows, one a sequence that drafts, in the order the later rounds' rows take.
/* Draft round 1, carried by the history pass: [n_draft_out] device, indices into this pass's
* rows, one per drafting sequence, in the order the later rounds' rows take.
*
* Round 1 continues from the last position the verify step committed, with the token the
* trunk chose after it -- and the history pass already has a row with exactly those inputs,
* because it covers every position the verify step could have committed and repeats the last
* committed one in the rows past it (core/sched/advance.h, ADV_HIST). A separate round-1 pass
* would run the head's whole layer again over a row that pass has just computed. So each
* drafting sequence's LAST history row is its round-1 row, and the pass ends in the lm_head
* over those rows; the head's wide state at them is what round 2 continues from.
* Round 1 continues from the last committed position with the token the trunk chose after it.
* The history pass already has a row with exactly those inputs: it covers every position the
* verify step could have committed and repeats the last committed one past it
* (core/sched/advance.h, ADV_HIST). So each drafting sequence's last history row is its
* round-1 row, saving a separate pass; the pass ends in the lm_head over those rows, and the
* head's wide state there is what round 2 continues from.
*
* 0 on a history pass that drafts nothing, and on every other pass. */
int64_t n_draft_out;
const int32_t* draft_out_ids;
/* THE PROMPT THAT FOLLOWS THIS STEP: `n_ahead` more tokens of the LAST sequence, stored in
* `token_ids` right after its n_tok -- the next chunk of a prefill with more prompt to run, and
* 0 on every other step (a decode step, a draft pass, a prefill's last chunk).
/* The prompt after this step: `n_ahead` more tokens of the last sequence, stored in
* `token_ids` right after its n_tok (the next prefill chunk); 0 on every other step (decode,
* draft pass, a prefill's last chunk).
*
* Nothing is computed on them and no output depends on them. They exist so an op that fetches
* per-token data from a slow tier can start the NEXT step's reads while this step runs: the
* PLE gather reads its rows from the container file, a few tens of thousands of random reads
* a chunk, and the chunk after this one is already known (docs/OPS.md, ngram_ids' `ahead_ids`
* and embed_lookup_q's `ahead`). */
* Nothing is computed on them. They let an op that fetches per-token data from a slow tier
* start the next step's reads during this one: the PLE gather reads its rows from the
* container file, tens of thousands of random reads per chunk (docs/OPS.md, ngram_ids'
* `ahead_ids` and embed_lookup_q's `ahead`). */
int64_t n_ahead;
/* ================================================ multimodal (spec §11) */
/* THE ROTARY POSITION OF EVERY TOKEN, AND IT IS NOT `positions`. `positions` is a token's
* index in its sequence -- the KV slot, the QSA block and every other piece of bookkeeping
* count in it -- and a rotary embedding over several position components does not. Qwen-VL
* style M-RoPE gives each token three components (temporal, height, width): a text token has
* all three equal, an image token has the image's start in the first and its row and column
* offsets in the other two, and the text after an image continues from the image's largest
* component, so from the first image on the rotary position runs BEHIND the index.
/* The rotary position of every token, which differs from `positions`. `positions` is a
* token's index in its sequence (the KV slot, the QSA block and other bookkeeping count in
* it). Qwen-VL style M-RoPE gives each token three components (temporal, height, width): a
* text token has all three equal, an image token has the image's start in the first and its
* row and column offsets in the others, and text after an image continues from the image's
* largest component, so from the first image on the rotary position runs behind the index.
*
* [3, n_tok] device, COMPONENT-MAJOR: plane c is rope_pos + c * n_tok, each n_tok long. Plane
* 0 alone is a valid one-component position for every token whose three components agree,
* which is every token on a pass where `rope_mixed` is 0 -- so a kernel that reads a position
* per token (a cos/sin table row, say) takes plane 0 on such a pass and needs no change.
* [3, n_tok] device, component-major: plane c is rope_pos + c * n_tok. Plane 0 alone is a
* valid one-component position for every token whose components agree, i.e. every token when
* `rope_mixed` is 0, so a kernel reading one position per token can use plane 0 then.
*
* Null when the program declares no encoder: nothing can move a rotary position away from
* the index then, and `positions` is the rotary position. */
* Null when the program declares no encoder; `positions` is then the rotary position. */
const int32_t* rope_pos;
/* Host-side: non-zero when some token on this pass has components that differ -- an image or
* video span is in the rows. A block whose fast path reads one component a token takes the
* multi-component path on such a pass. */
/* Host-side: non-zero when some token on this pass has differing components (an image or
* video span is present); a block with a one-component fast path must take the
* multi-component path. */
int32_t rope_mixed;
/* ROWS THAT TAKE AN ENCODER'S OUTPUT IN PLACE OF A TOKEN EMBEDDING. The placeholder ids a
* media span holds in `token_ids` are real ids -- a hashed n-gram embedding reads them -- but
* the embedding the model sees at those rows is the encoder's, and this is it: row i of
* `mm_embd` replaces the embedding of this pass's token `mm_rows[i]`.
/* Rows that take an encoder's output in place of a token embedding: row i of `mm_embd`
* replaces the embedding of this pass's token `mm_rows[i]`. The placeholder ids a media span
* holds in `token_ids` are still real ids (a hashed n-gram embedding reads them).
*
* RANK 0 HOLDS THE ROWS AND EVERY OTHER RANK HOLDS ZEROS, which is the split a vocabulary-
* sharded embedding lookup produces: a token's embedding comes from the one rank that owns
* its id and the rest contribute zero to the reduction that follows. So a plugin overwrites
* its lookup's output with these rows BEFORE that reduction, and every row arrives once --
* whether the reduction is its own all-reduce or folded into the first layer's norm. At one
* rank there is no difference.
* Rank 0 holds the rows and every other rank zeros, matching a vocabulary-sharded embedding
* lookup where non-owning ranks contribute zero to the following reduction. So a plugin
* overwrites its lookup output with these rows before that reduction, whether it is an
* all-reduce or folded into the first layer's norm.
*
* On a pass that shifts its tokens (a draft head's history pass) the rows are shifted with
* them. 0 rows on every pass with no media in it. */
* On a pass that shifts its tokens (a draft history pass) the rows are shifted with them. 0
* rows on every pass without media. */
int64_t n_mm_rows;
const int32_t* mm_rows; /* [n_mm_rows] device: index into this pass's tokens */
const void* mm_embd; /* [n_mm_rows, n_embd] bf16 device */
/* THE ENCODER PASS. Non-zero `enc` runs the plugin's declared encoder (rad_declare_encoder)
* and nothing else: no token rows, no KV, no logits. Its input is a list of patches, already
* resized, normalised and cut by the processor, and its output is the encoder's declared
* `out` buffer, one row per `merge` patches, which the core reads back after the pass.
/* The encoder pass. Non-zero `enc` runs a declared encoder (rad_declare_encoder) and nothing
* else: no token rows, no KV, no logits. Its value is that encoder's `modalities`
* (RAD_MM_AUDIO, or the image/video mask), selecting between two declared encoders. Input is a
* list of patches already resized, normalised and cut by the processor; output is the
* encoder's declared `out` buffer, one row per `merge` patches, read back after the pass.
*
* Patches are grouped into SEGMENTS -- one per image, and one per temporal group of a video
* -- and attention runs within a segment. `enc_coord` gives each patch its place in its
* segment, which is everything a learned position table and a 2-D rotary embedding need. */
* An audio pass's patches are feature frames with 1-D coordinates: plane 0 the frame's index
* in its clip, plane 1 whether it takes part in the convolution (1) or is staging the encoder
* reads as zero (0), plane 2 the clip's real frames and plane 3 its staged ones. The zero
* frames pad a clip staged whole to whole output rows, or, for a clip staged a second at a
* time (Qwen3-ASR), align each second to whole rows.
*
* Patches are grouped into segments (one per image, one per temporal group of a video), and
* attention runs within a segment. `enc_coord` gives each patch's place in its segment, which
* is all a learned position table or a 2-D rotary embedding needs. */
int32_t enc;
int64_t enc_n_patch;
const void* enc_pixels; /* [enc_n_patch, patch_dim] bf16 device */
/* [4, enc_n_patch] device, COMPONENT-MAJOR like rope_pos: row, column, the segment's height
/* [4, enc_n_patch] device, component-major like rope_pos: row, column, the segment's height
* and its width, all in patches. Planes 0 and 1 together are a [2, enc_n_patch] position. */
const int32_t* enc_coord;
int64_t enc_n_seg;
const int32_t* enc_cu; /* [enc_n_seg + 1] device: segment boundaries in patches */
int32_t enc_max_seg; /* host: the longest segment, which bands the attention */
/* ================================================ image generation */
/* A generator pass (rad_declare_generator): RAD_GEN_PASS_*, with `gen_b` its payload. 0 on
* every step of a program that declared no generator. */
int32_t gen;
const struct RadGenBatch* gen_b;
/* ================================================ audio generation */
/* An audio generator's pass (rad_declare_audio_generator; `gen` is one of its
* RAD_GEN_PASS_*): its payload. Null on every other step. */
const struct RadAudioGenBatch* agen_b;
/* ================================================ video generation */
/* A video generator's pass (rad_declare_video_generator; `gen` is one of its
* RAD_GEN_PASS_*): its payload. Null on every other step. */
const struct RadVideoGenBatch* vgen_b;
} RadBatch;
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
*
* COND one sequence. `token_ids`, `positions` and `rope_pos` are its conditioning prompt, the
* encoder's input (`enc_*`) is the prompt's reference pictures and `mm_rows` the prompt
* rows the encoder's output rows replace, as on any media step. What is here lays out
* the generator's sequence over those rows and writes it into the KV group.
* DENOISE one entry per (image, conditioning): `cu_seqlens` bounds each entry's latent rows,
* and the KV group's `block_table` and `seqused` name its conditioning's sequence.
* DECODE one image.
*
* Every pointer is device memory unless the name ends in _h. */
typedef struct RadGenBatch {
/* ---- COND */
int64_t rows; /* the generator's rows for this sequence */
/* Where each row comes from: >= 0 the prompt row of that index (the conditioning network's
* output there), < 0 the reference latent row -(1 + src). [rows] */
const int32_t* src;
/* Rotary positions, three components a row. On a COND pass they are laid out segment by
* segment: segment s's [3, length] component-major block starts at element 3 * seg_h[s], so a
* segment's positions are one dense operand. On a DENOISE pass, [3, n_tok] component-major,
* the latent rows'. */
const int32_t* rope;
/* The sequence in segments: rows [seg_h[s], seg_h[s+1]), each a picture (`seg_bidi_h` 1, its
* rows attend to each other both ways) or a run of text (0, causal). A segment is never split
* and attends to every segment before it. `seg` is the same offsets on the device; `seg_cu`
* is [n_seg, 2], segment s's own cu_seqlens {0, length}, and `seg_start` [n_seg] its first
* row -- the keys before it, which is its `seqused` when it is run on its own. */
int64_t n_seg;
const int32_t* seg;
const int32_t* seg_h;
const int32_t* seg_bidi_h;
const int32_t* seg_cu;
const int32_t* seg_start;
/* [rows] the KV slot each row is stored at. */
const int32_t* slot_mapping;
/* Pixels for the decoder's encoder: `n_px` blocks of `px` [*, pixel_channels] bf16 in
* [-1, 1], block b at pixel px_h[3b], px_h[3b+1] high and px_h[3b+2] wide. These are the
* reference pictures in prompt order and, with `inpaint`, a last block holding the picture
* being repainted at the output size, whose latents go to the lanes below. */
int64_t n_px;
const void* px;
const int32_t* px_h;
/* [n_px, 2] each block's own cu_seqlens over its latent tokens: {0, (h / scale) (w / scale)}. */
const int32_t* px_cu;
int32_t inpaint;
/* [image tokens] f32: 1 where the image is repainted, 0 where the picture is kept. */
const float* inp_mask;
/* The lanes this conditioning's images run in, which take the repainted picture's latents. */
int64_t n_lane;
const int32_t* lane_h;
/* ---- DENOISE, one value per entry ([n_seq]); on a COND pass `sigma` is one 0, the time
* the conditioning is modulated at */
const float* sigma; /* where the entry's latent is */
const float* sigma_next; /* where this step takes it */
const float* cfg; /* guidance: v = neg + cfg * (pos - neg); 1 without a pair */
/* The entry holding this image's negative conditioning, or -1 for none; -2 marks an entry
* that is one, whose rows serve another entry's step and which does not move its lane. */
const int32_t* pair;
const int32_t* lane; /* the plugin's lane the image's latent lives in */
const int32_t* lane_dh; /* ... the same, host */
/* RAD_GEN_F_*. */
const int32_t* flags;
/* [n_seq, 2] the image's noise seed, low word first. */
const uint32_t* seed;
/* ---- DECODE */
int32_t dec_lane;
int32_t dec_height, dec_width; /* pixels */
int32_t dec_preview; /* the lane's preview latent, not its state */
/* ---- the joint layout (RAD_GEN_LAYOUT_JOINT_STEP)
* COND: `branch` is 0 for the prompt and 1 for the negative prompt, and `n_lane` / `lane_h` /
* `lane` name every lane the conditioning's images run in; the plugin keeps the
* conditioning's row r for lane l at its own row (2 l + branch) cond_rows + r. The prompt's
* last `n_pad` tokens are the padding, and `valid_cu` is {0, the tokens before it}. `rope_f`
* is the conditioning's positions, [4, rows] f32 component-major.
* DENOISE: each entry's rows are its conditioning and then its image's latent tokens, so
* `cu_seqlens` bounds both together. `src` [n_tok] names a row's source: >= 0 the plugin's
* conditioning row (as above), < 0 the image row -(1 + k) of the compact image order, in
* which `img_cu` [n_seq + 1] bounds each entry's image and `img_rows` [n_img] is each image
* row's place in the pass. `mode_cu` [3 n_seq + 1] cuts each entry into its text (padding
* included), its reference pictures and its image: entry e's text is rows [mode_cu[3e],
* mode_cu[3e + 1]), its pictures [mode_cu[3e + 1], mode_cu[3e + 2]), its image up to
* mode_cu[3e + 3]. `rope_f` is [4, n_tok]. Everything sigma, cfg, pair, lane, flags and seed
* say is per entry as for JOINT_GRID, and the lane ops read `img_cu`. */
int32_t branch;
int32_t n_pad;
const int32_t* valid_cu;
int64_t n_img;
const int32_t* img_cu;
const int32_t* img_rows;
const int32_t* mode_cu;
const float* rope_f;
/* DENOISE: the rows again in mode-major order -- every entry's text, then every entry's
* pictures, then every entry's image (the compact image order) -- for a model whose early
* blocks run each mode on its own. `mode_rows` [n_tok] is each one's place in the pass,
* `mode_src` [n_tok] its source as `src` names it, and `mode_rope_f` holds the positions mode
* by mode, mode m's a dense [4, n_m] block at 4 times its start;
* `n_mode_h` [3] counts each mode's rows, so mode m starts at the sum of the counts before
* it, and `mode_ccu` [3, n_seq + 1] bounds each entry's rows of each mode from that start
* (mode m's cu_seqlens at mode_ccu + m (n_seq + 1), each beginning at 0). */
const int32_t* mode_rows;
const int32_t* mode_src;
const int32_t* mode_ccu;
const int64_t* n_mode_h;
const float* mode_rope_f;
} RadGenBatch;
/* An entry's flags on a DENOISE pass. */
enum {
RAD_GEN_F_FIRST = 1, /* the image's first step: its latent is the noise its seed draws */
RAD_GEN_F_INPAINT = 2, /* repaint: after the step, the kept region goes back to the picture,
* noised to sigma_next with the image's own noise */
RAD_GEN_F_PREVIEW = 4 /* write the step's estimate of the clean latent to the lane's preview */
};
/* What an audio generator's pass carries beside the step batch's own fields (rad_builder.h,
* RadAudioGenDecl, describes the passes):
*
* PROMPT an ordinary causal prefill: `token_ids`, `positions`, `cu_seqlens` and the KV group's
* slot mapping, block table and seqused, two sequences a lane (2i conditional, 2i + 1
* unconditional). A chunk of a longer prompt is the same with positions that start
* past zero.
* FRAME one row a sequence, two sequences a lane, ordered as PROMPT's: the frame's embedding
* is the plugin's (it samples the frame first), so `token_ids` are zero; `positions`,
* the slot mapping and seqused place the row after its sequence's earlier ones.
* WINDOW one entry per (window, branch): `cu_seqlens` bounds each entry's rows, `win_lead`
* rows of the plugin's own (RadAudioGenDecl::win_lead) and then the window's latent
* rows; positions count from 0 in each entry.
* VOCODE one window, no rows.
*
* Every pointer is device memory unless the name ends in _h. */
typedef struct RadAudioGenBatch {
/* ---- PROMPT and FRAME: the lanes of the pass's requests, in entry order */
int64_t n_lane;
const int32_t* lane; /* [n_lane] */
const int32_t* lane_h;
/* PROMPT: 1 where this pass holds the end of the lane's prompt, so the last rows' hidden
* states are the ones the first frame is sampled from. [n_lane] */
const int32_t* last;
const int32_t* last_h;
/* FRAME: the frame each lane makes, from 0; frames before RadAudioGenDecl::first_frame only
* move the model past the prompt. [n_lane] */
const int32_t* frame;
const int32_t* frame_h;
/* PROMPT, FRAME and WINDOW: each lane's (WINDOW: each entry's) request seed, [n, 2] low word
* first. */
const uint32_t* seed;
/* PROMPT and FRAME, one value per entry ([n_seq]): the entry's row in a state of two rows a
* lane, 2 lane + branch, and the entry's last row in the pass (a prompt chunk's, or a frame's
* one row). */
const int32_t* slot;
const int32_t* last_row;
/* PROMPT: each entry's rows already in the KV before this pass ([n_seq]), the prefix a chunk's
* rows attend to beside their own. */
const int32_t* prefix;
/* ---- WINDOW, one value per entry ([n_seq]) */
const float* t; /* where the entry's latent is, in [0, 1) */
const float* t_next; /* where this step takes it */
const float* cfg; /* v = u + cfg (c - u); 1 without a pair. FRAME: each lane's
* guidance, [n_lane] */
/* The entry holding this window's unconditional branch, or -1 for none; -2 marks an entry
* that is one, whose rows serve another entry's step and which does not move its lane. */
const int32_t* pair;
const int32_t* win_lane; /* the lane the window's request runs in */
const int32_t* win_lane_h;
/* RAD_AGEN_F_*, device and host. */
const int32_t* flags;
const int32_t* flags_h;
/* The window: its index in the request, its first frame and its frames, host and device. */
const int32_t* win_index;
const int32_t* win_index_h;
const int32_t* win_frame0;
const int32_t* win_frame0_h;
const int32_t* win_frames;
const int32_t* win_frames_h;
/* The latent rows apart from the lead rows: [n_seq + 1] offsets over them, and for each the
* row of the pass it is (`lat_rows` of them). */
int64_t lat_rows;
const int32_t* lat_cu;
const int32_t* lat_cu_h;
const int32_t* lat_src;
/* ---- VOCODE */
int32_t voc_lane;
int32_t voc_window;
int32_t voc_latents; /* the window's latents */
int32_t voc_left; /* latents at its start not played */
int32_t voc_right; /* latents at its end not played */
/* VOCODE with RadAudioGenDecl::voc_chunk: the lane's first frame the pass reads, counted
* from the first kept frame. 64 bits so that it starts past the struct's ABI 18 end. */
int64_t voc_frame0;
} RadAudioGenBatch;
/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear
* of RAD_GEN_F_*'s, so one flags array serves the image generator's sampler ops as well. */
enum {
RAD_AGEN_F_FIRST = 1, /* the window's first step: its latent is the noise its seed draws and
* its conditioning is built from the request's frames */
RAD_AGEN_F_LAST = 8, /* the window's last step: after it the latent is final */
RAD_AGEN_F_JOIN = 16 /* the window has a predecessor whose end it overlaps */
};
/* What a video generator's pass carries beside the step batch's own fields (rad_builder.h,
* RadVideoGenDecl, describes the passes). Every pass is one request's, in lane `lane`:
*
* VCOND `token_ids`, `positions` and `cu_seqlens` are the prompt, one sequence of `n_tok`
* rows, attended causally, nothing paged.
* VSTEP `n_tok` rows: the packed sequence, n_text + audio_channels n_audio + the video's
* patches. No token ids.
* ADECODE no rows of the pass's own.
* VDECODE `dec_rows` rows of the decoder's own (rad_arch_video_positions, RAD_VPOS_DECODE).
* VUPSCALE no rows of the pass's own: the lane's video latent from `geom_from` to `geom`.
*
* Every pointer is device memory unless the name ends in _h. */
typedef struct RadVideoGenBatch {
int32_t lane;
RadVideoGeom geom; /* the request's geometry */
/* The geometry again for ops that read it from an operand, i32 [RAD_VGEOM_N] (below). */
const int32_t* geom_d;
/* The same lane, i32 [1], and 1 on a request's first step (0 otherwise), i32 [1]. */
const int32_t* lane_d;
const int32_t* first_d;
/* i32 [4]: the packed sequence's segments, {0, n_text, n_text + audio rows, n_tok} -- text,
* soundtrack, video -- and i32 [4] {0, video rows, 0, audio rows}, the bounds of the lane's two
* latents counted from each one's first row. */
const int32_t* seg_cu;
const int32_t* lat_cu;
/* ---- VCOND: every step the request takes, the video's timestep and the soundtrack's */
int32_t n_steps;
const float* t_video; /* [n_steps] */
const float* t_audio; /* [n_steps] */
/* ---- VSTEP */
int32_t step; /* from 0; the first draws the lane's noise */
/* f32 [6]: the video's timestep, sigma and next sigma, then the soundtrack's. */
const float* sched;
const float* pos; /* f32 [3, n_tok]: RAD_VPOS_STEP */
/* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first (VSTEP, VUPSCALE and
* VDECODE passes; a decoder that denoises draws from it). */
const uint32_t* seed;
/* ---- VDECODE */
int32_t chunk; /* from 0, of n_chunks */
int32_t n_chunks;
int64_t dec_rows; /* RAD_VPOS_DECODE */
int32_t n_frames_out; /* frames the pass writes to frames_out */
/* ---- ADECODE */
int64_t n_samples; /* samples a channel the pass writes to audio_out */
/* ---- VUPSCALE (rad_builder.h, "Latent upscaling"). `geom` is the geometry the video latent
* is enlarged to and `geom_from` the one it has; `geom_d` carries both (RAD_VGEOM_UP_*).
* `sched` is the first full-size step's, whose sigmas (sched[1] the video's, sched[4] the
* soundtrack's) the latents are re-noised to; `seed` is a step's. */
RadVideoGeom geom_from;
const float* upscale; /* f32 [1]: the factor the network is told */
/* ---- appended in ABI 24 */
/* VCOND with a negative prompt: `n_neg` of the pass's tokens, after the prompt's. */
int32_t n_neg;
/* The request's guidance, f32 [8] host: the video's scale, its spatio-temporal scale, its
* modality scale and its rescale, then the soundtrack's four; a model's own defaults where
* the request named none. */
const float* guidance_h;
/* VCOND with a first frame (RadVideoGenDecl::image_cond): `image` [height, width, 3] bf16 in
* [-1, 1], device; null without one. Every later pass carries `has_image` 1 for such a
* request. */
const uint16_t* image;
int32_t has_image;
/* guidance_h on the device, f32 [8], for ops that read the terms. */
const float* guidance;
/* VDECODE: the decoder the request named (RadVideoGenDecl::decoders), its index; 0 the
* default. */
int32_t decoder;
} RadVideoGenBatch;
/* RadVideoGenBatch::geom_d. The request's latent geometry, then a VDECODE pass's chunk: the latent
* frames it reads (from latent frame `chunk_lat0`), its latent grid again so that (frames, h, w,
* first, last) is one run, and the same chunk in patches. */
enum {
RAD_VGEOM_LAT_FRAMES = 0, RAD_VGEOM_LAT_H = 1, RAD_VGEOM_LAT_W = 2, RAD_VGEOM_N_TEXT = 3,
RAD_VGEOM_N_AUDIO = 4, RAD_VGEOM_CHUNK_LAT0 = 5,
RAD_VGEOM_CHUNK_FRAMES = 6, RAD_VGEOM_CHUNK_H = 7, RAD_VGEOM_CHUNK_W = 8,
RAD_VGEOM_CHUNK_FIRST = 9, RAD_VGEOM_CHUNK_LAST = 10,
RAD_VGEOM_PATCH_FRAMES = 11, RAD_VGEOM_PATCH_H = 12, RAD_VGEOM_PATCH_W = 13,
/* A VUPSCALE pass's: (frames, h, w, H, W), the latent's grid before and after, of which the
* first three are also the source volume; (frames, H, W) the target volume; then both in
* patches, (frames, h / patch, w / patch) and (frames, H / patch, W / patch). */
RAD_VGEOM_UP_SRC = 16, RAD_VGEOM_UP_DST = 21, RAD_VGEOM_UP_PSRC = 24, RAD_VGEOM_UP_PDST = 27,
/* The soundtrack's latents as a volume of single latents, (n_audio, 1, 1); and the video's
* rows cut at its first latent frame, {0, that frame's patches, every patch} (a first frame
* a model conditions on at its own timestep). */
RAD_VGEOM_AUDIO_VOL = 32, RAD_VGEOM_FIRST_CU = 35,
RAD_VGEOM_N = 40
};
/* ================================================================== operands */
/* RAD_OPK_KV names a KV group's pool rather than a buffer: attention and kv_store take the cache
* as an operand, and RadKVGroupBatch carries the slot mapping and the block table but not the
* pool base -- the pool belongs to the block manager, not to the batch. handle is the
* rad_kvgroup and offset is the LAYER, because a group's pool holds one cache per bound layer. */
/* RAD_OPK_WTAB names a RUN of consecutively declared weights rather than one weight, and it
* exists because a routed mixture of experts has no single base to stride from. A layer's experts
* are separate movement units (spec §4.1) -- after placement one of them is in VRAM, the next is
* streamed over the link and the third is still on disk -- so "expert e is base + e*stride" is
* true only of the all-in-VRAM case and silently wrong of every other. The core therefore
* resolves each handle in the run the way it resolves any weight (residency table, mover event,
* use note) and hands the kernel a DEVICE ARRAY OF POINTERS, one per expert, in declaration
* order. See the RadTensor shape rule at RAD_WTAB below. */
* as an operand, and RadKVGroupBatch carries the slot mapping and block table but not the pool
* base, which belongs to the block manager. handle is the rad_kvgroup and offset is the layer,
* since a group's pool holds one cache per bound layer. */
/* RAD_OPK_WTAB names a run of consecutively declared weights. A routed MoE layer has no single
* base to stride from: its experts are separate movement units (spec §4.2), and after placement
* one may be in VRAM, the next streamed over the link and a third on disk. The core resolves each
* handle like any weight (residency table, mover event, use note) and hands the kernel a device
* array of pointers, one per expert, in declaration order. See RAD_WTAB below for the RadTensor
* shape rule. */
enum { RAD_OPK_BUF = 0, RAD_OPK_WEIGHT = 1, RAD_OPK_RAW = 2, RAD_OPK_NONE = 3, RAD_OPK_KV = 4,
RAD_OPK_WTAB = 5 };
typedef struct RadOperand {
uint8_t kind;
uint32_t dtype; /* RAD_OPK_RAW only: what the pointer points at. A buffer and a weight
* carry their dtype in the declaration; a raw pointer is a batch field
* the core did not allocate and has nowhere else to say. RAD_DT_INVALID
* means "the kernel knows from the op schema position", which is true
* for a specialised kernel and false for libref. */
uint32_t dtype; /* RAD_OPK_RAW only: what the pointer points at (buffers and weights
* carry their dtype in the declaration). RAD_DT_INVALID means the
* kernel knows it from the schema position, which a specialised
* kernel does and libref does not. */
uint32_t handle; /* rad_buf or rad_weight */
void* raw; /* RAD_OPK_RAW: a pointer the core did not allocate (a batch field) */
int64_t offset; /* element offset into the buffer or weight */
int64_t rows; /* 0 = the declared extent; >0 = only this many rows of dim 0 */
int64_t cols; /* 0 = the declared extent; >0 = a COLUMN SLICE of that width, with the
* declared width kept as the stride. This is what makes a fused qkv
* projection usable: q, k and v are views of one buffer, and without it
* the architecture plugin has to declare three buffers and copy. */
int64_t cols; /* 0 = the declared extent; >0 = a column slice of that width, with the
* declared width kept as the stride. Lets q, k and v be views of one
* fused qkv buffer instead of three buffers and a copy. */
} RadOperand;
#define RAD_B(h) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, 0, 0, 0 })
@@ -265,28 +582,24 @@ typedef struct RadOperand {
* stride. RAD_B_COL(qkv, 0, n_q) is the q view of a fused projection. */
#define RAD_B_COL(h, c, w) ((RadOperand){ RAD_OPK_BUF, RAD_DT_INVALID, (h), 0, (c), 0, (w) })
#define RAD_W(h) ((RadOperand){ RAD_OPK_WEIGHT, RAD_DT_INVALID, (h), 0, 0, 0, 0 })
/* A WEIGHT TABLE: the `n` weights declared at handles h, h+1, ... h+n-1 -- which is what a
* declaration loop over experts produces, because rad_decl_weight hands out consecutive indices.
/* A weight table: the `n` weights declared at handles h, h+1, ... h+n-1, as a declaration loop
* over experts produces (rad_decl_weight hands out consecutive indices).
*
* WHAT THE KERNEL RECEIVES. `RadTensor::data` is a device array of `n` `void*`, entry e being
* expert e's first byte. `shape[0]` is n and `stride[0]` is 0, which is the marker: a zero
* leading stride says the axis is not addressable by arithmetic and the table must be indexed.
* `dtype` and `shape[1..]` / `stride[1..]` are ONE entry's -- every weight in a run must agree
* about those, and the core refuses the issue by name if they do not, because a table whose
* entries have different shapes is a table the kernel cannot walk.
* The kernel receives `RadTensor::data` as a device array of `n` `void*`, entry e pointing at
* expert e's first byte. `shape[0]` is n and `stride[0]` is 0; the zero leading stride marks an
* axis that must be indexed through the table, not by arithmetic. `dtype` and `shape[1..]` /
* `stride[1..]` are one entry's; every weight in the run must agree on them, or the core refuses
* the issue by name.
*
* The table is rebuilt only when a pointer in it actually changes, so a resident model pays one
* comparison per expert per issue and no copy at all. */
* The table is rebuilt only when a pointer changes, so a resident model pays one comparison per
* expert per issue and no copy. */
#define RAD_WTAB(h, n) ((RadOperand){ RAD_OPK_WTAB, RAD_DT_INVALID, (h), 0, 0, (n), 0 })
#define RAD_KV(g, layer) ((RadOperand){ RAD_OPK_KV, RAD_DT_INVALID, (g), 0, (layer), 0, 0 })
#define RAD_P(ptr) ((RadOperand){ RAD_OPK_RAW, RAD_DT_INVALID, 0, (void*)(ptr), 0, 0, 0 })
#define RAD_P_T(ptr, dt) ((RadOperand){ RAD_OPK_RAW, (dt), 0, (void*)(ptr), 0, 0, 0 })
/* A raw pointer to a DENSE 2-D array: [rows, cols], packed. `cols` on a raw operand is not the
* column SLICE it is on a buffer -- there is no declared width to slice out of -- it is the second
* extent, and giving it is the only way a batch field that is genuinely two-dimensional can say so.
* The block table is the case that forced it: [n_seq, max_blocks], and passed as a rank-1 array of
* n_seq the width is simply gone. Every kernel that reads it then has to guess, and the only two
* guesses available are to refuse the operand for not being rank 2 or to read a width of one. */
/* A raw pointer to a dense 2-D array, [rows, cols], packed. On a raw operand `cols` is the second
* extent, not a column slice (there is no declared width to slice). This is how a two-dimensional
* batch field such as the block table, [n_seq, max_blocks], keeps its width. */
#define RAD_P_T2(ptr, dt, r, c) \
((RadOperand){ RAD_OPK_RAW, (dt), 0, (void*)(ptr), 0, (r), (c) })
#define RAD_NONE ((RadOperand){ RAD_OPK_NONE, RAD_DT_INVALID, 0, 0, 0, 0, 0 })
@@ -297,31 +610,29 @@ typedef struct RadOperand {
/* ================================================================== issue */
/* The core resolves each weight handle to a pointer, waits on the mover's event if the weight is
* in flight, indexes the op's bucket table with `n`, and dispatches to the device or host
* implementation according to the current execution site.
* implementation for the current execution site.
*
* `n` is the value of the op's ranged parameter -- at most one per op, which is what keeps this
* a single integer on the hot path. RAD_N_BATCH means "the batch's token count", which is what
* almost every op wants. An op with no ranged parameter ignores it.
* `n` is the value of the op's ranged parameter (at most one per op, so this is a single integer
* on the hot path). RAD_N_BATCH means the batch's token count, which almost every op wants. An op
* with no ranged parameter ignores it.
*
* If an op received a void*, the weight's location would be fixed at declare and placement could
* not be a core feature at all. This is the single ABI decision the whole placement design rests
* on (spec §3.2). */
* Ops take handles, not pointers, so a weight's location is not fixed at declare; placement
* depends on this (spec §3.2). */
#define RAD_N_BATCH ((int64_t)-1)
int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n);
/* THE SECOND LANE, for overlapping a collective -- or an arm no shard divides -- with compute.
* `rad_lane` selects which stream subsequent issues launch on (0 or 1); `rad_lane_join(c, from,
* to)` orders `to` behind everything already issued on `from` without blocking the host or
* draining either. The runtime joins lane 1 back into lane 0 at the end of every step, so a
* missing join costs speed and not correctness.
/* The second lane, for overlapping a collective (or an arm no shard divides) with compute.
* `rad_lane` selects the stream later issues launch on (0 or 1); `rad_lane_join(c, from, to)`
* orders `to` behind everything already issued on `from` without blocking the host. The runtime
* joins lane 1 into lane 0 at the end of every step, so a missing join costs speed, not
* correctness.
*
* THREE RULES, and Ctx::lane1_ in core carries the reasons: every collective must ride the SAME
* lane (the all-reduce numbers its scratch slots per launch and the two ranks must agree); a
* kernel that carries a device-wide arrival counter must key it on the STREAM, which libr4d's
* split-K GEMM does and a plugin that does not may not run here; and the buffer planner packs
* transients from a SINGLE LINEAR ORDER, so every buffer the second lane touches has to be named
* to rad_buf_concurrent, which gives up a few buffers' worth of the arena's sharing. */
* Three rules (reasons at Ctx::lane1_ in core): every collective must use the same lane, since
* the all-reduce numbers its scratch slots per launch and the ranks must agree; a kernel with a
* device-wide arrival counter must key it on the stream (libr4d's split-K GEMM does), or it may
* not run here; and every buffer the second lane touches must be named to rad_buf_concurrent,
* because the planner packs transients from one linear order. */
int rad_lane(RadCtx* c, int lane);
int rad_lane_join(RadCtx* c, int from, int to);
@@ -329,12 +640,9 @@ int rad_lane_join(RadCtx* c, int from, int to);
#define RAD_ISSUE(c, op, ...) rad_issue((c), (op), RAD_OPD(__VA_ARGS__), RAD_N_BATCH)
#define RAD_ISSUE_N(c, op, n, ...) rad_issue((c), (op), RAD_OPD(__VA_ARGS__), (n))
/* FAIL THE STEP WITH A REASON. An architecture block's step() returns void, so without this the
* only way to refuse a batch it cannot serve is to issue something invalid and let the operand
* check reject it -- which reports the wrong cause. A block that knows it does not serve
* a batch shape says so here, and the engine stops with `what` in the message rather than
* producing numbers nobody should trust. Returns the status it set, so `return rad_step_fail(...)`
* reads naturally in a helper. */
/* Fail the step with a reason. An architecture block's step() returns void, so this is how it
* refuses a batch shape it does not serve; the engine stops with `what` in the message. Returns
* the status it set, so a helper can `return rad_step_fail(...)`. */
int rad_step_fail(RadCtx* c, const char* what);
/* ================================================================== run-phase queries */
@@ -344,9 +652,9 @@ int rad_world_size(RadCtx* c);
RadStream rad_stream(RadCtx* c);
/* The routing result for a MoE layer, resolved on device against the current residency table.
* Routing NEVER blocks the compute stream: the histogram is copied back asynchronously and the
* heat engine consumes it on the next step (spec §5.5). This returns the device-side buffers,
* not host-visible expert ids -- the plugin issues its expert ops against them. */
* Routing never blocks the compute stream: the histogram is copied back asynchronously and the
* heat engine consumes it on the next step (spec §5.5). These are device-side buffers the plugin
* issues its expert ops against, not host-visible expert ids. */
typedef struct RadRouting {
const int32_t* expert_ids; /* [n_tok, top_k] device */
const float* expert_w; /* [n_tok, top_k] device */
@@ -362,17 +670,52 @@ typedef struct RadRouting {
* ordinary declared ops; this is the handoff, not a computation. */
int rad_route_report(RadCtx* c, int layer, const RadRouting* r);
/* WHERE A LAYER'S EXPERT COUNTS CAN BE WRITTEN IN PLACE: a device row of at least `n_expert` int32
* that the core owns and carries to the host itself, once, at the end of the pass. A router that
* writes its counts here and reports this pointer as `expert_count` hands them over for nothing;
* any other pointer is copied into this row, which is a dispatch a routed layer on the compute
* stream. Null when the core keeps no histogram for `layer` or its row is narrower than
* `n_expert` -- the router then writes its own buffer and reports that. */
/* A core-owned device row of at least `n_expert` int32 where a layer's expert counts can be
* written in place; the core copies it to the host once at the end of the pass. A router that
* writes here and reports this pointer as `expert_count` hands the counts over for free; any other
* pointer costs one copy dispatch per routed layer on the compute stream. Null when the core keeps
* no histogram for `layer` or its row is narrower than `n_expert`; the router then writes its own
* buffer and reports that. */
int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert);
/* A weight's pointer, for the rare op that genuinely needs one (a plugin-private kernel invoked
* outside the op vocabulary). Waits on the mover. Using this forfeits nothing except the ability
* to move that weight while the pointer is live, so it is legal only within one issue. */
/* Next-layer expert prefetch, at decode. At its router input a routed layer names the next routed
* layer; the core applies that layer's router to this layer's input rows, picks the experts it is
* likeliest to route that sit in the pinned host pool, and copies them to the card while the rest
* of this layer runs. Just before the next layer's routed GEMMs it points their weight-table
* entries at the copies that have landed, where the entries still name the pool slots copied from.
* Results are unchanged: a copy holds its slot's bytes. Active only when placement keeps experts
* in a pinned pool and the device backend can spare a DMA engine; a pass of more than 16 rows
* makes no prediction. The three calls are no-ops otherwise.
*
* `parts` names, for each of the next layer's experts, the weights its unit is made of (at most four,
* e.g. the gate-up matrix and its scales and the down matrix and its scales), as the routed GEMMs
* read them through weight tables; 0 where an expert has fewer or none. An expert is prefetched only
* where each of its weights is in exactly one table and all of them sit in one pool slot. The arrays
* must outlive the context; the core reads the routing counts only to rank and count, never to choose
* an expert's bytes. `layer` is the next layer's index as rad_route_report and
* rad_expert_prefetch_step name it; `router` is its router, [n_expert, n_embd] bf16. */
typedef struct RadPrefetchNext {
int layer;
rad_weight router;
int64_t n_expert, top_k;
int64_t n_parts;
const rad_weight* parts; /* [n_expert * n_parts] */
const int32_t* count_at; /* [n_expert]: where the expert's count is in the layer's routing
counts (rad_route_counts), -1 for nowhere; null when at its index */
} RadPrefetchNext;
/* At this layer's router input: `h` rows [r0, r0 + rows) of n_embd bf16, read in place on another
* stream -- the block must not overwrite them before this layer's routed GEMMs. */
int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows,
int64_t n_embd);
/* After this layer's routed down GEMM: the copies cross the link from here, overlapping the next
* layer's attention rather than this layer's own streamed experts. */
int rad_expert_prefetch_mark(RadCtx* c);
/* Ahead of `layer`'s routed GEMMs, on every routed layer of every pass. */
int rad_expert_prefetch_step(RadCtx* c, int layer);
/* A weight's pointer, for the rare plugin-private kernel invoked outside the op vocabulary. Waits
* on the mover. The weight may move afterwards, so the pointer is valid only within one issue. */
void* rad_weight_ptr(RadCtx* c, rad_weight w);
void* rad_buf_ptr(RadCtx* c, rad_buf b);
+33 -39
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,35 +24,35 @@
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 */
RAD_SP_MASK = 1 << 2, /* a grammar is constraining this sequence this step */
RAD_SP_XTC = 1 << 3,
RAD_SP_DRY = 1 << 4
RAD_SP_DRY = 1 << 4,
RAD_SP_LOGPROBS = 1 << 5 /* `sample_logprobs` summarises this row's raw logits */
};
/* 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
@@ -103,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
+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/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
+553 -448
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_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 */
+36 -63
View File
@@ -1,42 +1,31 @@
/* 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.
* 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.
*
* 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.
* `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.
*
* 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.
* 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 +38,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 +53,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;
@@ -99,10 +87,9 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
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. */
/* No KV-head replication: the fused [q|k|v] uses the plain even row shard, so above the KV head
* count a rank would read the wrong rows. rad_block_attn_gated_fp8.h is the block that uses
* geom_from's `kv_off`. */
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,
@@ -114,43 +101,29 @@ 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 }));
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),
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. */
/* 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_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),
@@ -169,8 +142,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 +177,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. */
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));
+99 -170
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. */
* 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_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));
+267 -244
View File
@@ -1,37 +1,26 @@
/* rad_block_attn_gated_fp8.h -- the gated GQA block with block-scaled FP8 projections.
/* rad_block_attn_gated_fp8.h -- gated GQA attention with block-scaled FP8 projections.
*
* THE ARCHITECTURE IS rad_block_attn_gated.h's AND IS DOCUMENTED THERE: the interleaved query/gate
* projection and why it is declared rank 3, the partial mrope and what is not expressible about it,
* why k and v are not fused, why the fused qk_norm_rope_gate probe is withdrawn, and why the gate
* is a sigmoid. None of that changes with the weight format and none of it is repeated here.
* The architecture (interleaved q|gate projection, partial M-RoPE, separate k and v, sigmoid
* gate) is documented in rad_block_attn_gated.h. What differs here:
*
* What differs:
* - q|gate, k, v and o are LinearFP8: an E4M3 weight with a bf16 [N/128][K/128] scale plane,
* through `gemm_nt_q` at dtype fp8a8.
* - One input quantise feeds the three input projections (they all read the post-norm hidden
* state); the gate pass quantises the out-projection's input.
* - Per-head norms, rope, kv_store and attn_paged stay bf16.
* - The KV cache dtype is `g.kv_dtype`, not `g.dtype`: it is a deployment choice that selects
* libr4d's fp8kv attention family. The attention op and kv_store both take it, so they agree.
* - Optional fused prologue, QSA sparse attention and an attention-zero mode (see declare).
*
* - q|gate, k, v and o are LinearFP8 -- an E4M3 weight with a bf16 [N/128][K/128] scale plane
* declared as a weight of its own, through `gemm_nt_q` at dtype fp8a8.
* - two `quant_act_fp8` launches a layer, not four: the three input projections all read the
* post-norm hidden state, so one quantise feeds all three, and the output projection gets its
* own because it reads the gated attention output.
* - everything between the GEMMs -- the per-head norms, rope, kv_store, attn_paged, the sigmoid
* and the gate multiply -- is UNCHANGED and still bf16.
* - THE KV CACHE'S WIDTH IS `g.kv_dtype` AND NOT `g.dtype`. `dtype` follows the WEIGHTS;
* "the cache is bf16 because the weights are fp8" is true of this checkpoint and is not a
* rule. `kv_dtype` follows the CACHE, which is a deployment choice: the fp8kv attention family
* and its descale operands are in libr4d, and the cache dtype is what selects them.
* Both the attention op and kv_store take it, so the two cannot disagree about the width of
* the thing one writes and the other reads.
*
* The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, and its scale plane
* is [96, 40]. Row-sharding by head keeps whole 128-row scale blocks together only because
* 2*head_dim is 512, a multiple of 128 -- so a rank's slice of the head range is a whole number of
* scale rows. LinearFP8 checks that rather than trusting it.
* The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, scale plane
* [96, 40]. Row-sharding by head keeps whole 128-row scale blocks only because 2*head_dim = 512 is
* a multiple of 128; LinearFP8 checks this.
*/
#ifndef RAD_BLOCK_ATTN_GATED_FP8_H
#define RAD_BLOCK_ATTN_GATED_FP8_H
#include "rad_fp8.h"
#include <cstdlib>
#include <cstring>
namespace rad {
@@ -45,14 +34,13 @@ struct AttnGatedFP8 {
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 */
/* [rope_table_rows, rot] f32, the model's, shared by every layer and filled once a step.
* Zero means the plugin has not been taught to build one, and then the fused prologue is
* not asked for at all. */
/* [rope_table_rows, rot] f32 cos/sin table, shared by every layer, filled once a step. Zero
* if the plugin builds none; the fused prologue is then not requested. */
rad_buf cos_sin = 0;
ActFP8 attn{}; /* [max_tok, q_dim] attention output, then gated in place */
/* [max_tok, q_dim] the de-interleaved sigmoid gate, in a model whose linears are bf16
* (Geom::w_bf16) only: there the gate is `sigmoid` then `mul`, rad_block_attn_gated.h's
* pair, and the fp8 path's fused gate-and-quantiser has no form that skips its codes. */
/* [max_tok, q_dim] de-interleaved sigmoid gate, used only with bf16 linears
* (Geom::w_bf16), where the gate is `sigmoid` then `mul`; the fused gate quantiser always
* writes codes. */
rad_buf gate = 0;
};
@@ -71,66 +59,47 @@ struct AttnGatedFP8 {
int layer = 0;
rad_kvgroup kv = 0;
int64_t n_rot = 0;
/* THE KV PAGE, IN TOKENS. 0 means RAD_KV_BLOCK, which is 16 and is what every geometry in
* this tree has wanted. It is a field rather than that constant because Qwen4-Exp's QSA
* selects 4-TOKEN BLOCKS, and a page of 4 makes the selected set a paged block table instead
* of a new attention kernel -- see docs/QSA.md. The attention kernel's own rows must carry a
* matching C_EQ("block_size", ...) or nothing resolves, which is the check that keeps this
* from being a number anyone can set. */
/* The KV page in tokens; 0 means RAD_KV_BLOCK (16). Qwen4-Exp's QSA selects 4-token blocks,
* and a page of 4 turns the selected set into a paged block table, so no new attention kernel
* is needed (docs/QSA.md). The attention kernel's rows must carry a matching
* C_EQ("block_size", ...) or nothing resolves. */
int64_t kv_block = 0;
/* THE QSA SELECTION, when this layer has an indexer. Set, and on a step where one query a
* sequence makes the selection per-SEQUENCE, the attention is issued with these in place of
* the sequence's own block table and context length -- which is the whole of what makes it
* sparse. Both are ordinary operands (the block table has always been one), so this is the
* SAME op and the SAME kernel reading a different list.
*
* `sel` is `topk + 1` wide and the kernel takes its block-table pitch from the operand, so
* nothing else has to be told. See docs/QSA.md; arch/common/rad_qsa.h produces them. */
/* The QSA selection, when this layer has an indexer (produced by arch/common/rad_qsa.h; see
* docs/QSA.md). On a sparse step the attention is issued with these in place of each row's
* block table and context length: same op, same kernel, different list. `sel` is `topk + 1`
* wide and the kernel takes its block-table pitch from the operand. */
rad_buf qsa_sel = 0;
rad_buf qsa_sequ = 0;
/* THE CONTEXT UP TO WHICH THE DENSE PATH IS THE SAME ANSWER, `budget + ratio - 1`. Below it
* every complete block is selected and the two paths agree to the bit, and the dense one is
* cheaper at prefill -- it reads each key once a query TILE where the sparse one reads a
* table a query. Above it the dense path is a different model. Zero means "always sparse",
* which is what a caller that has not been told the bound should get. */
/* Context length up to which dense attention gives the same result, `budget + ratio - 1`.
* Below it every complete block is selected, the paths agree to the bit, and dense is cheaper
* at prefill (it reads each key once per query tile, sparse reads a table per query). Zero
* means always sparse. */
int64_t qsa_exact_to = 0;
/* `sel`'s row pitch, `topk + 1`. The extra slot is the partial page and is not spare --
* r4d_qsa_select_bf16.hip says why. */
/* `sel`'s row pitch is `topk + 1`; the extra slot is the partial page
* (r4d_qsa_select_bf16.hip). */
int64_t qsa_topk = 0;
/* HOW MANY QUERY ROWS ONE SPARSE ATTENTION LAUNCH CARRIES, and it is a scratch budget rather
* than a preference. The decode kernel's split-KV partials are sized AT DECLARE from the
* `max_seqs` and `q_len` parameters, so the only way to issue more rows than `max_seqs` is to
* declare a larger one -- which grows the scratch arena by `rows * q_len_band * n_head *
* (head_dim + 2) * 4`, about 32 MiB at 256 rows on this model, ONCE for the whole program
* because the arena is the maximum over ops.
*
* It matters because the alternative is `max_seqs` itself. At `--max-num-seqs 4` a 2048-token
* prefill chunk would be 512 launches a layer, and the dispatch cost of that dominates what
* the sparse path saves. 256 makes it 8.
*
* Raising it further is pure scratch: 512 rows is 63 MiB, 2048 is 253. 256 is the point at
* which the launch cost has stopped mattering. */
/* Query rows per sparse attention launch, a scratch budget. The decode kernel's split-KV
* partials are sized at declare from `max_seqs` and `q_len`, so issuing more rows than
* `max_seqs` means declaring a larger value, which grows the scratch arena (the maximum over
* ops) by `rows * q_len_band * n_head * (head_dim + 2) * 4` bytes: about 32 MiB at 256 rows on
* this model, 63 MiB at 512, 253 MiB at 2048. With max_seqs alone, `--max-num-seqs 4` would
* split a 2048-token prefill chunk into 512 launches per layer; 256 makes it 8, past which
* launch cost no longer matters. */
static constexpr int64_t kQsaRows = 256;
int64_t qsa_rows() const { return g.max_seqs > kQsaRows ? g.max_seqs : kQsaRows; }
/* THE GATED FORM TAKES THE WHOLE STEP IN ONE LAUNCH, because its band is q_len 1 and so its
* partials are only `rows * n_head * (2 * head_dim + 8)` bytes -- 12.8 MiB at a 2048-row step
* on this model, where the ungated op's q_len band makes the same rows cost the figures
* above. Fewer launches still pay here: one 2048-row launch takes about 2.16 ms a layer
* against about 3.0 ms for eight 256-row ones, each of which is 256 one-wave workgroups -- two
* waves a SIMD -- with its own tail. */
/* The gated form takes the whole step in one launch: its band is q_len 1, so partials are only
* `rows * n_head * (2 * head_dim + 8)` bytes (12.8 MiB for 2048 rows on this model). One
* 2048-row launch is about 2.16 ms per layer versus 3.0 ms for eight 256-row launches, each
* with its own tail. */
int64_t qsa_gq_rows() const { return g.max_tok > qsa_rows() ? g.max_tok : qsa_rows(); }
/* THE ROTATION'S PAIRING, a question the checkpoint cannot answer by inspection and that no
* per-op check can reach, because both readings -- halves (NeoX, what HF's rotate_half does
* over the partial rotary width) and adjacent pairs (GPT-J) -- are self-consistent and libref
* shares whichever one the graph picks. Either answer is a DIFFERENT MODEL. "mrope" is what the
* model does, and over one position component a token it is NeoX (rad_block_attn_gated.h).
/* The rotation's pairing. Halves (NeoX, HF's rotate_half over the partial rotary width) and
* adjacent pairs (GPT-J) are both self-consistent and pass every per-op check, so it must be
* stated. "mrope" over one position component per token is NeoX (rad_block_attn_gated.h).
*
* THE q|gate ORDER IS FIXED TOO. q is the FIRST half of each head's pair and the gate the
* second, which is how vLLM chunks q_gate, and every consumer of the projection has to agree
* on it: the unfused q norm reads column 0 of each head, the gate quantiser column head_dim,
* and the fused prologue splits the pair the same way inside its kernel. A swap would be
* arithmetically silent -- q_norm renormalises either half and the sigmoid accepts either --
* so an order that only some of them followed would be fluent and wrong. */
* The q|gate order is fixed as well: q is the first half of each head's pair, the gate the
* second (as vLLM chunks q_gate). The unfused q norm reads column 0 of each head, the gate
* quantiser column head_dim, and the fused prologue splits the same way. A swap would pass
* silently, since q_norm and the sigmoid accept either half. */
const char* mode = "mrope";
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
@@ -140,34 +109,54 @@ struct AttnGatedFP8 {
NormQuantFP8 nq_h{};
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
rad_op op_fused_kv = 0; /* ...with kv_store folded on, likewise */
int64_t fused_rows = 0; /* ...and the widest T it is issued at */
rad_op op_fused_kv = 0; /* the same with kv_store folded in */
int64_t fused_rows = 0; /* widest T the fused ops take */
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_gq = 0;
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */
rad_op op_sig = 0, op_mul = 0; /* the bf16 gate, Geom::w_bf16 */
/* The output gate as `sigmoid` then `mul`: the bf16-linear form (Geom::w_bf16), and with fp8
* linears the chain gate_quant_fp8 fuses, where it is not served. `gate` is the sigmoid's
* output (the wire's with bf16 linears, the block's own otherwise) and `q_gate` the chain's
* quantiser (no op with bf16 linears). */
rad_op op_sig = 0, op_mul = 0;
rad_buf gate = 0;
QuantFP8 q_gate{};
rad_op op_ar = 0, op_add = 0;
rad_op op_fill = 0; /* the attention-zero rank: see declare */
/* ...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` (this block's norm absorbs the predecessor's); separate because a
* block is declared without knowing what follows. Both sides ask ar_fused_ok(g, T), so they
* agree on whether the collective was issued. */
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
/* Which wires that consumer takes (ArOut, rad_fp8.h): the norm's by default, or a gated
* residual's own (HyperConn::ar_take). Set before declare; both sides then ask
* ar_taken(g, T, ar_out, ar_out_take). */
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, int l, rad_kvgroup group,
int64_t rotary_dim, const Wire& wire, const Src& src,
bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* Stores the pass's K and V exactly as step() does, with no query, attention or output. Used
* by passes that only leave layer state behind, such as the MTP head's history pass over a
* prompt chunk with no drafting row. */
void store_kv(RadCtx* c, const RadBatch* batch) const;
/* The block's tail, declared last by every rank: the all-reduce and the trailing add. */
int declare_out(RadBuilder* b, bool add_out);
/* `own_ar` false: the caller issues the all-reduce itself (GdnFP8::step says when). */
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
ArPieces* pieces = nullptr) const;
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 AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -181,23 +170,17 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
const int64_t kv_dim = g.kv_dim();
const int64_t qg_dim = 2 * q_dim;
/* THE KV ROW SPAN, AND IT ONLY EXISTS ABOVE THE KV HEAD COUNT.
* A world size larger than `n_head_kv_all` cannot divide the KV heads, so rad_arch.h's
* `geom_from` replicates them in PAIRS: two ranks serve the same head, `g.n_head_kv` is 1 on
* each, and the checkpoint entry they both read is still `n_head_kv_all * head_dim` rows -- 512
* for 2 KV heads at head_dim 256. This rank wants ONE head's row-span of that entry, which the
* even shard would cut up instead (at 4 ranks it would hand rank 2 rows [256, 384), half of one
* head), so the span `[g.kv_off, g.kv_off + kv_dim)` is declared in the CONTAINER's unsharded
* units -- [0, 256) on ranks 0 and 1, [256, 512) on ranks 2 and 3 -- and the scale plane takes
* the same span in 128-blocks. `kv_off` is a multiple of head_dim, so it is whole blocks and
* never cuts one, and share.cpp's `shard_hi <= cpart` holds with cpart = 512 / 1 part.
* AT WORLD <= n_head_kv_all the ordinary even shard already selects exactly these rows, so the
* span stays 0/0 and the default path runs as before -- TP2 declares identically. */
/* AND UNDER A SMALLER ATTENTION WORLD (rad_arch.h Geom::attn_world: three ranks over two KV
* heads) the even shard over `world` is the wrong cut for every projection: q|gate and the
* output take this rank's heads [attn_rank * n_head, +n_head) as a span too, and k/v the
* kv_off span. An attention-zero rank declares none of them: its block is one `fill` of the
* output wire (the branch below), so the spans here are only ever cut for a rank with heads. */
/* Row spans, in the container's unsharded rows, used where the even shard is the wrong cut.
*
* Above the KV head count geom_from replicates KV heads (rad_arch.h): with 2 KV heads at
* head_dim 256 and 4 ranks, the k/v entry is 512 rows and ranks 0-1 take [0, 256), ranks 2-3
* [256, 512), where the even shard would hand rank 2 half a head. The scale plane takes the
* same span in 128-blocks; kv_off is a multiple of head_dim, so it never cuts a block. At
* world <= n_head_kv_all the span stays 0/0 and the even shard applies.
*
* Under a smaller attention world (Geom::attn_world) q|gate and the output also take this
* rank's heads [attn_rank * n_head, +n_head) as a span. An attention-zero rank declares none
* of them (see the `fill` below). */
const bool a_spanned = g.attn_world != g.world;
const bool kv_spanned = g.world > g.n_head_kv_all || a_spanned;
const int64_t kv_span_lo = kv_spanned ? g.kv_off : 0;
@@ -213,18 +196,13 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
return RAD_E_INVAL;
}
/* THE INPUT MAY BE PREPARED BY THE ARCHITECTURE, and `src.norm == nullptr` is how it says so.
/* `src.norm == nullptr`: the architecture prepares the input. A pre-norm block owns its norm
* (rad_fp8.h's NormQuantFP8: add the previous delta, normalise, quantise). In a gated-residual
* model, rad_block_hc.h's `hc_read` produces the block input from a 4x wider stream, so this
* block takes `wire.h` as already normed and quantised and declares no norm weight.
*
* 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`). */
* `ar_in` is refused in that mode: the fused all-reduce lives inside the norm, so it would be
* silently dropped. The caller emits a standalone collective instead (`add_out`/`ar_out`). */
ext_in = (src.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;
@@ -241,27 +219,23 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
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));
/* One norm, one quantise, three consumers -- and one op, see rad_fp8.h's NormQuantFP8. */
/* One norm+quantise op feeds all three input projections (rad_fp8.h: NormQuantFP8). */
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));
/* AN ATTENTION-ZERO RANK COMPUTES NO ATTENTION AT ALL. Its share of every projection is zero,
* so its q, k and v are zero, its attention is zero and its output projection adds exactly
* nothing to the reduce -- which is what the ranks that DO hold heads need from it and all
* they need. Declaring the projections and running them on zero weights spent the same
* dispatches and bytes as a real rank and a slot for every zero (and a KV pool nothing read,
* see rad_kv_group_zero). Here the block's output wire is written to zero by one `fill`, and
* the all-reduce and the residual below see what they always saw. The norm above stays: a
* pre-norm block's `fold` and `ar_in` live in it. Nothing in this branch runs for a rank with
* heads, so a world the heads divide (every TP2 and TP4 deployment) declares as it always did. */
/* An attention-zero rank holds no heads, so its output projection contributes zero to the
* reduce. Its output wire is zeroed by one `fill` instead of running projections on zero
* weights (and it keeps no KV pool, rad_kv_group_zero). The all-reduce and residual add run as
* usual, and the norm above stays because a pre-norm block's `fold` and `ar_in` live in it. */
if (g.attn_zero) {
op_fill = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{}, {w.h.x});
} else {
return declare_out(b, add_out);
}
RAD_ARCH_TRY(qg.declare(b, nm, g, nm.f("blk.%d.attn_qg", l), qg_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), { src.qg }, w.h, w.qg,
0, {}, qg_span_lo, qg_span_hi));
@@ -272,33 +246,25 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
RAD_SHARD_ROW, grp_layer(l), { src.v }, w.h, w.v,
0, {}, kv_span_lo, kv_span_hi));
/* THE FUSED PROLOGUE, AND IT IS A PROBE: the four ops below are declared either way and are
* what runs when nothing serves this one. rad_block_attn_gated.h does not make the probe,
* because the schema takes a PRECOMPUTED cos/sin table rather than `theta` and that block has
* none; `rope_table` builds one here, once a step for every layer, and `w.cos_sin` is where
* the model puts it. A block handed no table cannot ask for the fusion, which is what keeps a
* plugin that does not build the table on the unfused path.
/* The fused prologue (qk norms + rope + q|gate split) is a probe; the four unfused ops below
* are declared either way and run when it does not resolve. Its schema takes a precomputed
* cos/sin table instead of `theta`: `rope_table` fills `w.cos_sin` once a step for every
* layer, and without a table the fusion is not requested.
*
* NEOX ONLY. The fused kernel rotates NeoX pairs and has no `mode`, so the probe is made only
* where mrope reduces to neox -- one position component a token, which is every text batch and
* is argued in rad_block_attn_gated.h. A vision span would need the sections first.
* The kernel rotates NeoX pairs and has no `mode`. M-RoPE qualifies because the table is
* filled at one component per token, which is exact when the components agree; step() takes
* the fused path only then.
*
* NO `gate_out`. `gate_quant_fp8` below already reads the gate at its column offset inside the
* interleaved projection, so a contiguous copy would be q_dim of bf16 a layer written for
* nothing. The operand is optional and this passes none.
* No `gate_out` is passed: `gate_quant_fp8` reads the gate in place in the interleaved
* projection.
*
* IT IS BIT-IDENTICAL TO THE FOUR, checked in r4d_selftest (`qk_norm_rope_gate ... matches the
* unfused pair`) rather than argued: the kernel rounds its norm output to bf16 before rotating
* because that is what a norm that stores a tensor and a rope that reads it back do. It
* reproduces `r4d_rmsnorm_bf16`'s sum-of-squares fold element by element rather than folding
* eight elements a lane, and r4d_selftest asserts byte equality. A merely RELATIVE bound is
* not enough here: a fold order that agrees to a ULP and not to the last bit moves the
* engine's transcript within a few dozen steps. */
/* M-RoPE qualifies too: the table is filled at one component a token, which is exact on every
* pass whose tokens' components agree, and the step takes the fused path only then. */
* Bit-identical to the unfused ops, asserted in r4d_selftest: the kernel rounds the norm output
* to bf16 before rotating and reproduces `r4d_rmsnorm_bf16`'s sum-of-squares order element by
* element. A ULP-level difference would shift the engine's transcript within a few dozen
* steps. */
const bool rope_neox = !std::strcmp(mode, "neox") || !std::strcmp(mode, "mrope") || g.rope_mc;
fused_rows = qk_fuse_rows(g);
if (w.cos_sin && rope_neox && fused_rows > 0)
if (w.cos_sin && rope_neox && fused_rows > 0 && rad_op_declared(b, "qk_norm_rope_gate"))
op_fused = rw(b, RAD_OP(b, "qk_norm_rope_gate",
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head),
@@ -325,33 +291,25 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
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});
/* Declared before kv_store because block_size is RAD_DERIVED and kv_store reads it back --
* rad_block_attn_gated.h explains why the declared order differs from the issue order. */
/* Declared before kv_store, which reads back the resolved `block_size`
* (rad_block_attn_gated.h). */
op_attn = RAD_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", kv_block > 0 ? kv_block : (int64_t)RAD_KV_BLOCK),
/* The sparse path issues one row a QUERY, so the bound the split-KV
* scratch is sized from is the widest such launch and not the
* sequence count -- see kQsaRows. */
/* The sparse path issues one row per query, so the split-KV
* scratch is sized for the widest launch (kQsaRows). */
RAD_INT("max_seqs", (qsa_sel && qsa_sequ) ? qsa_rows()
: 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);
/* THE QSA SELECTION IS A READ OF THIS OP AND HAS TO BE DECLARED AS ONE. The block table has
* always been a raw batch pointer, so `attn_paged`'s read set was just the query -- and
* `sel`/`seqused` are BUFFERS, whose lifetimes the Builder plans from exactly these lists. Left
* out, their last use is `qsa_select` and the arena is free to lay another buffer over them;
* anything written between the selection and the attention then arrives as a page id, and a
* garbage page id is an address far outside the cache -- an aperture violation at the first
* step whose plan happens to overlap them, which need not be a step that ran before. Spelled
* with rad_op_reads rather than rw() because the list is conditional -- a layer with no
* indexer has no such read.
*
* THE DECLARATION ORDER IS THE BUFFER PLAN, and this is one of the shapes that rule takes. */
/* The QSA selection buffers must be declared as reads of this op. Otherwise their last use is
* `qsa_select`, the arena may overlay another buffer, and the attention reads garbage page
* ids: an aperture violation outside the cache. rad_op_reads rather than rw() because the list
* depends on whether the layer has an indexer. */
if (op_attn) {
const rad_buf rd[3] = { w.q, qsa_sel, qsa_sequ };
rad_op_reads(b, op_attn, rd, (qsa_sel && qsa_sequ) ? 3 : 1);
@@ -366,12 +324,11 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
RAD_NOWEIGHTS),
{w.k, w.v}, {});
/* THE PROLOGUE AND THE CACHE STORE AS ONE LAUNCH, wherever the fused prologue is taken: a k
* head's block already holds its token's rotated k, one element a lane, so it writes that and
* the head's v into the cache too, byte-for-byte what kv_store would (the fold's row says why).
* Declared here and not beside op_fused because the cache's block size is read back from the
* attention op above. It resolves for an E4M3 and a bf16 cache alike. */
if (op_fused)
/* The fused prologue with the cache store folded in: a k head's block already holds its
* token's rotated k, so it also writes k and v into the cache, byte-identical to kv_store.
* Declared here because the cache block size is read back from the attention op above.
* Resolves for E4M3 and bf16 caches. */
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store"))
op_fused_kv = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
@@ -383,48 +340,62 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
RAD_WEIGHTS(w_q_norm, w_k_norm)),
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
/* THE OUTPUT GATE, THE MULTIPLY AND THE QUANTISER ARE ONE PASS. Unfused they are three --
* sigmoid into a de-interleaved buffer, a multiply in place, then quant_act_fp8 -- and at
* decode each is small enough that the dispatch gap between them is comparable to the work
* itself, once per layer. THE ROW IS A (token, head) PAIR, which is what makes the fusion
* expressible: at that shape the gate is a fixed stride inside the [q|gate] projection, the
* attention output is contiguous, and the fp8 scale plane of [T * n_head, head_dim / 128] is
* byte-for-byte the [T, q_dim / 128] the out projection reads. No separate gate buffer is
* declared, because nothing reads one.
/* Output gate, multiply and quantiser in one pass (`gate_quant_fp8`); at decode the dispatch
* gaps between three small ops are comparable to the work. Each row is a (token, head) pair:
* the gate is a fixed stride inside [q|gate], the attention output is contiguous, and the
* [T * n_head, head_dim / 128] scale plane is byte-identical to the [T, q_dim / 128] the out
* projection reads.
*
* The bf16 product is still written, because that is what the unfused pair left in `w.attn.x`
* and the codes are taken over it -- see r4d_fused_quant_fp8.hip on why that is a requirement.
* The codes are the int8 pair when the model feeds the out projection int8 (ActFP8::q8_fed),
* and the same op writes them: the codes operand's dtype picks the quantiser.
* PREFILL AND DECODE BOTH TAKE IT: unlike the gdn fold this one has no reduction across the
* row, so there is no shape it cannot serve. */
if (g.w_bf16) {
* The bf16 product is still written to `w.attn.x` and the codes are taken over it
* (r4d_fused_quant_fp8.hip says why). The codes operand's dtype picks the quantiser, int8 when
* the out projection is fed int8 (ActFP8::q8_fed). Serves prefill and decode: there is no
* cross-row reduction.
*
* With bf16 linears (Geom::w_bf16) the gate is the plain `sigmoid` + `mul` pair instead.
*
* Where no loaded library declares gate_quant_fp8, or it does not resolve, the fp8 block runs
* the chain it fuses: the gate into a buffer of its own, the multiply, then the activation
* quantiser, which write what the fused op writes. A head of whole 128-column blocks makes
* the quantiser's [T, q_dim / 128] scale plane the fused op's [T * n_head, head_dim / 128]. */
auto gate_pair = [&](rad_buf out) {
gate = out;
op_sig = 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.qg}, {gate});
op_mul = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn.x, w.gate}, {w.attn.x});
if (!op_sig || !op_mul) return RAD_E_INVAL;
} else
op_gq = rw(b, RAD_OP(b, "gate_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
RAD_NOWEIGHTS),
{w.qg, w.attn.x}, {w.attn.cq(), w.attn.cs(), w.attn.x});
{w.attn.x, gate}, {w.attn.x});
return op_sig && op_mul ? RAD_OK : RAD_E_INVAL;
};
if (g.w_bf16) {
RAD_ARCH_TRY(gate_pair(w.gate));
} else {
if (rad_op_declared(b, "gate_quant_fp8"))
op_gq = rw(b, RAD_OP(b, "gate_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
RAD_NOWEIGHTS),
{w.qg, w.attn.x}, {w.attn.cq(), w.attn.cs(), w.attn.x});
if (!op_gq && g.head_dim % RAD_FP8_BLOCK == 0) {
RAD_ARCH_TRY(gate_pair(decl_b(b, nm.f("blk.%d.attn_gate", l), g.act_dtype,
{g.max_tok, q_dim})));
RAD_ARCH_TRY(q_gate.declare(b, g, w.attn, q_dim));
if (!q_gate.op) return RAD_E_INVAL;
}
}
/* AND ON THE SPARSE PATH THE GATE RIDES IN THE ATTENTION'S OWN MERGE. There every launch is
* one query row a (token, head) pair at q_len 1, and the split-KV merge that closes each row
* holds exactly the 256 values the gate and the quantiser read next -- so the fused op merges,
* gates, rounds and quantises the row where it is, byte-for-byte the pair (its row says how),
* and the launch between them is gone. Declared only beside a selection: the dense path's
* query rows are the band the prefill kernel serves as well, and that kernel has no merge. */
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16) {
/* On the sparse path the gate is applied inside the attention's split-KV merge: each launch
* row is one (token, head) at q_len 1, and the merge already holds the head_dim values the gate
* and quantiser read, so one op merges, gates, rounds and quantises (byte-identical to the
* pair). Declared only with a selection: the dense path also uses the prefill kernel, which
* has no merge. */
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 &&
rad_op_declared(b, "attn_paged_gate_quant")) {
op_attn_gq = RAD_OP(b, "attn_paged_gate_quant",
RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
@@ -448,8 +419,10 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
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,
0, {}, o_span_lo, o_span_hi));
} /* !g.attn_zero */
return declare_out(b, add_out);
}
inline int AttnGatedFP8::declare_out(RadBuilder* b, bool add_out) {
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -458,8 +431,19 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
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, 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 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),
@@ -470,7 +454,22 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
return RAD_OK;
}
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (!ext_in) nq_h.step(c, T);
if (op_fill) return; /* the attention-zero rank holds no heads to store */
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, 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_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));
}
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
ArPieces* pieces) 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;
@@ -480,9 +479,9 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
if (!ext_in) nq_h.step(c, T);
if (op_fill) {
/* The attention-zero rank: the output wire is zero, then the reduce and the residual. */
/* Attention-zero rank: zero output, then the reduce and the residual. */
RAD_ISSUE_N(c, op_fill, T, brows(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));
return;
@@ -491,11 +490,10 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
/* Four launches or one. The fused kernel takes the [q|gate] projection WHOLE and splits it
* itself -- so `w.qg` goes in as it stands and not as the column slice the unfused norm needs
* -- and it rotates k in place, which is what the unfused pair does too. */
/* THE FUSED PATH READS ONE COMPONENT A TOKEN, so a pass carrying media tokens -- whose
* components differ -- takes the unfused pair with the whole [3, T] instead. */
/* Fused or unfused prologue. The fused kernel takes the whole [q|gate] projection and splits it
* itself, and rotates k in place like the unfused ops. It reads one rotary component per
* token, so a pass with media tokens (differing components) takes the unfused path with the
* full [3, T] positions. */
const bool fuse_ok = T <= fused_rows && !rope_mixed(batch);
const bool fused_kv = op_fused_kv && fuse_ok;
if (fused_kv) {
@@ -522,26 +520,49 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE(c, op_kv_store,
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
/* ONE ROW A QUERY IS WHAT MAKES THE SPARSE PATH WORK AT PREFILL, and it needs no new kernel
* for the same reason the decode path needed none: `attn_paged` indexes its block table and
* its length by the ROW, and nothing says a row has to be a sequence. A chunk of T queries
* issued as T rows of q_len 1, each with its own selection and its own `seqused`, is exactly
* per-query sparse attention -- and at decode, where T is the sequence count, it is the same
* issue it has always been.
/* Sparse attention issues one row per query. `attn_paged` indexes its block table and length
* by row, and a row need not be a sequence, so T queries issued as T rows of q_len 1, each with
* its own selection and `seqused`, is per-query sparse attention; at decode T is the sequence
* count.
*
* DENSE BELOW THE BOUND, because there the two are the same answer and dense is cheaper: it
* reads each key once a query TILE where this reads a table a query. `max_ctx_len` is the
* host-side bound the batch already carries, so the test costs nothing.
* Below `qsa_exact_to` the dense path gives the same result more cheaply (see the field);
* `max_ctx_len` is a host-side bound the batch already carries.
*
* CHUNKED AT max_seqs, and that is not tidiness. The decode kernel's split-KV scratch is
* sized AT DECLARE from the `max_seqs` and `q_len` parameters -- max_seqs * q_len_max * heads
* rows -- and handing it T rows past that is refused as RAD_E_SCRATCH at issue. max_seqs rows
* of q_len 1 is strictly inside what q_len_max >= 1 already bought, so the bound holds
* whatever the kernel's band turns out to be. */
* Launches are chunked because the split-KV scratch is sized at declare from `max_seqs` and
* `q_len` (rows = max_seqs * q_len_max * heads); more rows are refused as RAD_E_SCRATCH at
* issue. Rows of q_len 1 up to the declared max_seqs always fit. */
const int64_t reach = (int64_t)batch->max_ctx_len + batch->max_q_len;
const bool sparse = qsa_sel && qsa_sequ &&
(T == batch->n_seq || qsa_exact_to <= 0 || reach > qsa_exact_to);
const bool gated = sparse && op_attn_gq;
/* A piece at a time where the caller takes the all-reduce that way (ArPieces). On the gated
* sparse path every query row is its own (q_len 1) and the gate rides in the merge, so the
* attention and out projection can finish a piece's rows and hand off its reduction while the
* next piece's attention runs. Each piece is launched as a step of the piece's width would
* launch it. */
if (gated && !own_ar && pieces && pieces->cuts(T) && !op_add) {
const int64_t chunk = qsa_gq_rows();
const int64_t qw = g.q_dim(), hd = g.head_dim;
for (int64_t p0 = 0; p0 < T; p0 += pieces->rows) {
const int64_t pn = T - p0 < pieces->rows ? T - p0 : pieces->rows;
for (int64_t off = p0; off < p0 + pn; off += chunk) {
const int64_t rows = (p0 + pn - off) < chunk ? (p0 + pn - off) : chunk;
RAD_ISSUE_N(c, op_attn_gq, 1,
brow_slice(w.q, off, rows, qw),
kv_cache(kv, layer),
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
brow_slice(qsa_sequ, off, rows, 1),
RAD_NONE, RAD_NONE, RAD_NONE,
brow_slice(w.attn.x, off, rows, qw),
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
brow_slice(w.attn.cq(), off, rows, qw),
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
}
o.step(c, w.attn, w.h.x, T, p0, pn);
if (p0 + pn < T) pieces->hand(p0, pn);
}
return;
}
if (gated) {
const int64_t chunk = qsa_gq_rows();
const int64_t qw = g.q_dim(), hd = g.head_dim;
@@ -578,25 +599,27 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
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.x, T));
}
if (op_sig) {
if (gated) {
/* the sparse attention gated and quantised in its merge */
} else if (op_sig) {
/* The gate is the strided second half of each head's [q|gate] pair. */
RAD_ISSUE_N(c, op_sig, T * g.n_head,
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.gate, T));
RAD_ISSUE(c, op_mul, brows(w.attn.x, T), brows(w.gate, T), brows(w.attn.x, T));
} else if (!gated)
bcol(w.qg, g.head_dim, g.head_dim, T), brows(gate, T));
RAD_ISSUE(c, op_mul, brows(w.attn.x, T), brows(gate, T), brows(w.attn.x, T));
q_gate.step(c, T);
} else {
RAD_ISSUE_N(c, op_gq, T * g.n_head,
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.attn.x, T),
brows(w.attn.cq(), T), brows(w.attn.cs(), T), brows(w.attn.x, T));
}
o.step(c, w.attn, 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));
}
+196 -317
View File
@@ -1,39 +1,32 @@
/* rad_block_dflash2.h -- the DFlash2 block-diffusion drafter, bf16.
*
* ============================== WHAT IT IS ==============================
* A small transformer that proposes a whole block of tokens in one forward pass. Compared with
* the MTP head (rad_block_mtp_fp8.h):
*
* A SECOND, SMALLER TRANSFORMER that proposes a whole block of tokens in ONE forward pass. It is
* the other drafter this engine serves, and it is a different shape of thing from the MTP head
* beside it (rad_block_mtp_fp8.h):
* MTP depth d costs d chained forwards; round i+1 embeds round i's token.
* DFlash2 depth d costs one forward over d+1 positions: the anchor token plus d mask
* tokens are denoised together.
*
* MTP depth d costs d CHAINED forwards. Round i+1 cannot start until round i has
* produced a token, because the token is what it embeds.
* DFlash2 depth d costs ONE forward over d+1 positions. The block is denoised together --
* the anchor token plus d mask tokens go in, d+1 hidden states come out.
* So depth is nearly free here, and there is no `draft_pass`. Published acceptance is 4.10-5.46
* versus MTP's 3.74-5.02 at 7 drafts.
*
* That is why depth is nearly free here and expensive there, and it is why this file has no
* `draft_pass`: there are no rounds. Published acceptance for this drafter is 4.10-5.46 against
* MTP's 3.74-5.02 at 7 drafts.
*
* The price of proposing the positions together is that position l+1 was computed WITHOUT KNOWING
* what position l would choose. The candidate selector is what puts that dependence back: each
* position keeps the draft head's top K, a low-rank bilinear form scores the edge between
* consecutive positions, and a greedy walk picks one path. `dflash_select` is that kernel.
* Since positions are proposed together, position l+1 does not know what position l chose. The
* candidate selector (`dflash_select`) restores that dependence: each position keeps the draft
* head's top K, a low-rank bilinear form scores edges between consecutive positions, and a greedy
* walk picks one path.
*
* ============================== THE TWO PASSES ==============================
*
* THE CONTEXT PASS, one row a committed token. The drafter never runs its layers over the context
* -- it reads the TARGET's hidden states instead, at five intermediate layers, and turns them
* straight into its own K and V:
* Context pass, one row per committed token. The drafter does not run its layers over the
* context; it turns the target's hidden states at five intermediate layers into its own K and V:
*
* c = fc(concat of the trunk's residual stream at layers 5, 19, 33, 47, 61) [n_taps*n_embd]
* c = hidden_norm(c)
* for each draft layer: k|v = kv_proj(c); k = k_norm(k) then rope; kv_store(k, v)
*
* The trunk's side of that -- the taps, and the `dflash_src` buffer they land in -- is in
* qwen35_fp8.cpp. This file reads the buffer and never asks where the rows came from.
* The taps and the `dflash_src` buffer they land in are the trunk's (qwen35_fp8.cpp).
*
* THE QUERY PASS, one row a draft position, `block` = 1 + n_spec of them a sequence:
* Query pass, one row per draft position, `block` = 1 + n_spec rows per sequence:
*
* x = embed(anchor, mask, mask, ...)
* for each layer:
@@ -47,9 +40,8 @@
* h = dflash_conv(h, coef[taps*NG:], ffn_conv_base[1]); x += h
* x = norm(x)
*
* and then, over the MASK rows of each sequence's block -- offsets 1..block-1, NOT 0..steps-1.
* The anchor at offset 0 is a token the target has already chosen, so its row predicts nothing and
* is there to condition the rest; each mask row predicts the token AT ITS OWN POSITION:
* then, over the mask rows of each block (offsets 1..block-1; the anchor at offset 0 is already
* chosen and only conditions the rest), each predicting the token at its own position:
*
* cand, unary = top_k(draft_head(x)) the candidates and their logits
* hp = hidden_projection(x) the selector's query, rank 256
@@ -57,61 +49,38 @@
*
* ============================== WHAT IS SHARED WITH THE TARGET ==============================
*
* The embedding table and the lm_head, both. The checkpoint ships neither -- 81 tensors, no
* `embed_tokens` and no `lm_head` -- so a drafter without a target is not a model. `mask_token_id`
* is an ordinary id in the target's vocabulary (248070 here), which is why there is no separate
* mask embedding to load.
* The embedding table and lm_head. The checkpoint (81 tensors) ships neither, and
* `mask_token_id` is an ordinary id in the target's vocabulary (248070 here), so there is no
* separate mask embedding.
*
* The head reads the 2-BIT copy of the lm_head, exactly as the MTP head does and for exactly the
* reason rad_block_mtp_fp8.h gives at op_dlogits: 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 a token the model emits. Its candidates
* are then rescored against the target's own head where that head is fp8 or int8 (op_drerank), so
* the coarseness costs only which candidates are proposed, not how they are ranked. The 2-bit head
* also buys something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
* global without an all-gather and the selector's codebooks can be indexed directly.
* The head reads the 2-bit copy of the lm_head, as the MTP head does (rad_block_mtp_fp8.h,
* op_dlogits): the target verifies every draft with its own head, so a coarser draft costs only
* acceptance, never an emitted token. Candidates are rescored against the target's head when it
* is fp8 or int8 (op_drerank), so coarseness affects only which candidates are proposed.
*
* ============================== THE NORMS ARE PLAIN ==============================
* ============================== PLAIN NORMS ==============================
*
* `w`, not `1 + w`, unlike every norm in the trunk this drafter is bolted to. vLLM says so by
* using the ordinary RMSNorm rather than the family's GemmaRMSNorm, and the checkpoint agrees:
* hidden_norm sits at 0.11..1.24 (mean 0.82), input_layernorm at 0.05..1.70, k_norm at 0.32..2.53
* and the final norm at 2.45..5.25. All positive, all centred near one -- which is a plain gain
* and is not what a `1 + w` tensor looks like. So `Geom::wadd` and `wadd_qk` are ZERO here while
* the trunk's are one, and the two geometries are separate structs for this reason among others.
* The norms use `w`, not the trunk's `1 + w`: vLLM uses plain RMSNorm here, and the gains are all
* positive and centred near one (hidden_norm 0.11..1.24, input_layernorm 0.05..1.70, k_norm
* 0.32..2.53, final norm 2.45..5.25). So this geometry's `wadd` and `wadd_qk` are zero.
*
* ============================== SHARDING ==============================
*
* The layers shard the way any transformer's do: q/kv and gate_up by row, o and down by column
* with an all-reduce. Ten collectives a draft pass, each 5120 * block * 2 bytes -- 80 KiB at the
* shipped block of 8 -- which is below the lossy wire's floor and is served exactly.
* q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per
* draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor.
*
* THREE THINGS ARE REPLICATED AND EACH IS A DECISION:
* Replicated:
*
* fc [n_embd, n_taps*n_embd], 262 MiB. It could be COLUMN-sharded, since its input
* is the replicated residual stream and its output would then be a partial sum:
* 131 MiB a rank and half the read bytes on the context pass's widest GEMM. Not
* done, because it puts an all-reduce on the PREFILL path to save a small
* fraction of it, and the real fix for the context pass's cost is not to run it
* over the whole prompt at all (see below).
* conv weights the projection and the base kernel, 26 MiB a layer. The convolution is over
* the whole replicated hidden row and every rank needs every coefficient; a row
* shard would give each rank a fraction of the groups.
* the codebooks [n_vocab, 256] each, 127 MiB each. They are gathered by GLOBAL token id and
* the ids come out of a whole-vocabulary draft head, so a vocabulary shard would
* let a rank score only the candidates that happened to land in its own slice.
* The gather is 128 rows a pass, so the bytes READ are nothing; it is the
* residency that costs.
* fc [n_embd, n_taps*n_embd], 262 MiB. Column-sharding would halve it but add an
* all-reduce to the prefill path.
* conv weights projection and base kernel, 26 MiB a layer. The convolution spans the whole
* replicated hidden row, so every rank needs every coefficient.
* codebooks [n_vocab, 256], 127 MiB each, gathered by global token id. Only 128 rows are
* read per pass; the cost is residency.
*
* ============================== THE CONTEXT PASS IS THE EXPENSIVE HALF ==============================
*
* In bytes: `fc` is 262 MiB and the five KV projections read 3.4 GB over a 2048-token prefill
* chunk, which is a real fraction of what the chunk costs.
*
* THE FIX IS NOT A FASTER GEMM. The drafter's attention has a 2048-token window, so a context
* position more than 2048 before the query is never read: for a prompt of any real length, all but
* the last 2048 rows of the context pass are computed and thrown away. The scheduler can simply
* not run it over them. That is scheduler work and it is noted here rather than done here.
* Cost: the context pass is the expensive half (`fc` plus five KV projections read 3.4 GB over a
* 2048-token prefill chunk). The attention window is 2048 tokens, so context rows further back
* are never read and the scheduler need not compute them.
*/
#ifndef RAD_BLOCK_DFLASH2_H
#define RAD_BLOCK_DFLASH2_H
@@ -122,9 +91,8 @@
namespace rad {
namespace arch {
/* A row slice of a WEIGHT, the same thing brow_slice() is for a buffer. The conv's base kernel is
* [2, taps, n_embd] and the two sides are the prepare tap set and the finish tap set; there is one
* checkpoint tensor and the op takes one side at a time. */
/* brow_slice() for a weight. The conv base kernel is one [2, taps, n_embd] tensor holding the
* prepare and finish tap sets; the op takes one side at a time. */
inline RadOperand wrow_slice(rad_weight h, int64_t first, int64_t n, int64_t pitch) {
RadOperand o = RAD_W(h);
o.offset = first * pitch;
@@ -135,9 +103,7 @@ inline RadOperand wrow_slice(rad_weight h, int64_t first, int64_t n, int64_t pit
struct Dflash2 {
enum { MAX_LAYERS = 8 };
/* 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; /* query rows a sequence: the anchor plus n_spec mask tokens */
@@ -147,10 +113,13 @@ struct Dflash2 {
int64_t sel_topk = 16; /* candidates kept per position */
int64_t window = 0; /* sliding attention width, 0 for none */
int causal = 0;
/* The target's embedding scale, applied to the query block as the drafter was trained
* (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */
double escale = 1.0;
int64_t steps() const { return block - 1; }
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
/* The kernel projection emits [2, taps, NG] per token -- one coefficient set for `prepare`
* and one for `finish` -- and `dflash_conv` reads a slice of it at the FULL row pitch. */
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
* `dflash_conv` reads a slice of it at the full row pitch. */
int64_t coef_dim(int64_t n_embd) const { return 2 * taps * ng(n_embd); }
};
@@ -158,43 +127,33 @@ struct Dflash2 {
/* the context pass */
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. libr4d
* refuses that operand (libr4d/r4d_model.cpp, rows_pitch), and the drafter gives it rows
* that are what they claim to be. The trunk's attention block splits
* k and v for the same reason -- see rad_block_attn_gated.h. */
/* 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). Same reason as in rad_block_attn_gated.h. */
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 query pass */
rad_buf x = 0; /* [qrows, n_embd] the drafter's residual stream */
rad_buf h = 0; /* [qrows, n_embd] normed input, o/down output, and the final norm */
rad_buf h2 = 0; /* [qrows, n_embd] the convolution's output -- it may not alias x */
rad_buf h2 = 0; /* [qrows, n_embd] the convolution's output; must not alias x */
rad_buf coef = 0; /* [qrows, coef_dim] */
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] */
rad_buf attn = 0; /* [qrows, q_dim] */
rad_buf gate_up = 0;/* [qrows, 2 * n_ff] */
rad_buf ffn = 0; /* [qrows, n_ff] */
/* THE FP8 TWINS OF THE FOUR ACTIVATIONS A LINEAR READS. `quant_act_fp8` writes them and
* the six `gemm_nt_q` linears read them; nothing else touches them, and the bf16 buffer
* beside each stays the thing the rest of the graph reads and writes.
*
* ONE PAIR PER ACTIVATION, NOT PER LINEAR. q and k|v both read h2, so quantising it once
* is the difference between two launches a layer and three -- the same argument rad_fp8.h
* makes for keeping QuantFP8 a separate struct from LinearFP8. h2 is quantised twice a
* layer all the same, because the convolution rewrites it between the attention half and
* the feed-forward half. */
/* FP8 codes and scales of the activations the linears read, written by `quant_act_fp8`
* and read only by the `gemm_nt_q` linears. One pair per activation, not per linear: q, k
* and v all read h2. h2 is still quantised twice a layer, because the convolution
* rewrites it between the attention and feed-forward halves. */
rad_buf srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] e4m3 | [.., /128] f32 */
rad_buf cq = 0, cs = 0; /* [max_tok, n_embd] */
rad_buf h2q = 0, h2s = 0; /* [qrows, n_embd] */
rad_buf atq = 0, ats = 0; /* [qrows, q_dim] */
rad_buf ffq = 0, ffs = 0; /* [qrows, n_ff] */
/* the head and the selector, at one row per DRAFT POSITION (block - 1 a sequence) */
/* the head and the selector, one row per draft position (block - 1 per sequence) */
rad_buf sel_h = 0; /* [srows, n_embd] the gathered final hidden states */
rad_buf hp = 0; /* [srows, sel_rank] hidden_projection of them */
rad_buf dq = 0; /* [srows, n_embd] i8 the 2-bit head's quantised activation */
@@ -203,57 +162,45 @@ struct Dflash2 {
rad_buf dlog = 0; /* [srows, head_rows(g)] bf16 the coarse logits */
rad_buf cand = 0; /* [srows, sel_topk] i32 candidate token ids, global */
rad_buf unary = 0; /* [srows, sel_topk] f32 and their logits */
/* The vocab-parallel pair, declared only when head_sharded(g). Both are f32 (int32 id,
* float value) pairs: this rank's top-R, and the all-gathered world_size * R of them. */
/* Vocab-parallel pairs, declared only when head_sharded(g): (int32 id, f32 value) pairs
* stored as f32, this rank's top-R and the all-gathered world_size * R. */
rad_buf dpair = 0; /* [srows, sel_topk, 2] f32 */
rad_buf dgath = 0; /* [srows, world * sel_topk, 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 */
};
/* WHETHER THE 2-BIT DRAFT HEAD IS VOCAB-SHARDED. The test itself is rad_arch.h's
* `vocab_head_sharded` -- shared, because the second block-diffusion drafter in this library
* asks it too and both the op and the buffer under it have to agree. These two names stay so
* that whoever declares Dflash2's buffers can ask the BLOCK rather than re-derive the rule.
*
* Sharding halves the widest read on the draft path -- 341 MiB of codes and scales at 248320
* rows when it is replicated -- at the price of one all_gather of R pairs a row. At 248320
* over two ranks the shard is 124160, which is 7760 whole 16-row blocks. */
/* Whether the 2-bit draft head is vocab-sharded (rad_arch.h: vocab_head_sharded), so whoever
* declares the buffers can ask the block. Sharding halves the draft path's widest read (341 MiB
* of codes and scales at 248320 rows) for one all_gather of R pairs a row. */
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
/* Rows of the draft head, and therefore the width of `dlog`, on THIS rank. */
/* Rows of the draft head on this rank, and so the width of `dlog`. */
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;
/* model-scope weights.
*
* THE SIX LINEARS ARE FP8 OR MXFP4 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares
* each as block fp8 or OCP-MXFP4, whichever the recipe made it -- and the reason is bytes: the
* drafter is read WHOLE on every decode step, which makes it one of the largest single items in
* the decode budget after the trunk's own GEMMs. On Qwen3.8-27B at depth 7, MXFP4 rounded to
* nearest accepts ~1% fewer tokens a step than fp8 and takes ~1.5 ms off a ~34 ms step.
* Nothing it computes can change an emitted token, because every draft is verified against the
* trunk exactly; the only thing quantising it can move is acceptance. */
* The linears are block fp8 or OCP-MXFP4 (rad_fp8.h: DenseFP8, per the recipe) although the
* checkpoint is bf16: the drafter is read whole every decode step. On Qwen3.8-27B at depth 7,
* MXFP4 accepts ~1% fewer tokens per step than fp8 and saves ~1.5 ms of a ~34 ms step.
* Quantisation can only change acceptance, since every draft is verified. */
DenseFP8 w_fc{};
rad_weight w_hnorm = 0, w_norm = 0;
rad_weight w_selp = 0, w_pred = 0, w_succ = 0;
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 */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
/* K AND V ARE TWO WEIGHTS, and the fp8 layout hook is why. One fused [2*kv_dim, n_embd]
* tensor issued a half at a time through wrow_slice would cost a launch and no bytes -- and a
* block-scaled weight cannot be used that way. The layout of an operand is a function of the
* OP's N, and this op's N is kv_dim because it computes one half; the hook would be handed a
* [2*kv_dim/128][K/128] plane for a [kv_dim, K] op and refuse it. Two weights make the op's N
* and the planes' rows the same number again, shard independently at kv_dim, and issue the
* same two launches. */
/* K and V are separate weights: a block-scaled operand's layout follows the op's N, so a fused
* [2*kv_dim, n_embd] weight issued one half at a time would hand the layout hook a
* [2*kv_dim/128][K/128] plane for a [kv_dim, K] op, which it refuses. */
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] = {};
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
@@ -264,14 +211,14 @@ struct Dflash2 {
rad_op op_cfc = 0, op_cnorm = 0, op_crope = 0, op_cstore = 0;
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
/* THE ACTIVATION QUANTISERS, one per activation that feeds a linear. Weightless and shape-only,
* so one declaration each serves every layer -- the per-layer ops above are per-layer only
* because a weight's prefetch interval comes from the op that declares it. */
rad_op op_qsrc = 0, op_qc = 0; /* the context pass's two */
rad_op op_qh2 = 0, op_qat = 0, op_qff = 0; /* the query pass's three */
/* Activation quantisers, one per activation that feeds a linear. Weightless, so one declaration
* serves every layer; ops with weights are per layer because a weight's prefetch interval
* comes from the op that declares it. */
rad_op op_qsrc = 0, op_qc = 0; /* context pass */
rad_op op_qh2 = 0, op_qat = 0, op_qff = 0; /* query pass */
/* 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. */
/* query-pass ops. Weightless ones are declared once and issued per layer; their read and write
* sets are the same every layer. */
rad_op op_embed = 0, op_embed_ar = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
rad_op op_acoef[MAX_LAYERS] = {}, op_fcoef[MAX_LAYERS] = {};
@@ -288,11 +235,11 @@ struct Dflash2 {
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
rad_op op_drerank = 0; /* the candidates rescored against the target's head */
/* THE TARGET'S lm_head, set by the plugin before declare when its plane is one logit_rerank
* reads (fp8 or int8 rows); 0 leaves the coarse head's own scores as the candidates'. */
/* The target's lm_head, set by the plugin before declare when logit_rerank can read it (fp8 or
* int8 rows); 0 keeps the coarse head's scores. */
rad_weight w_lm = 0;
/* How many candidates the coarse head proposes for the rerank: logit_rerank's and row_topk's
* ceiling. Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
/* Candidates the coarse head proposes for the rerank (logit_rerank's and row_topk's ceiling).
* Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
static constexpr int64_t kRerankR = 32;
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
rad_op op_hp = 0, op_sel = 0;
@@ -300,10 +247,10 @@ struct Dflash2 {
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 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 and the selector, one call, `block` rows a sequence. */
/* The query pass and the selector, `block` rows per sequence. */
void step(RadCtx* c, const RadBatch* batch) const;
private:
@@ -360,26 +307,15 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
/* THE 2-BIT DRAFT HEAD. The same declaration the MTP head makes, for the same reasons, argued
* at length in rad_block_mtp_fp8.h: `dflash.draft_head.weight` is the target's lm_head 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 GEMM takes the
* codes as one operand and the scale and zero planes, interleaved by its relayout, as the
* other.
/* The 2-bit draft head, declared as the MTP head's is (rad_block_mtp_fp8.h):
* `dflash.draft_head.weight` is the target's lm_head 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: codes, and the scale|zero planes the GEMM's relayout interleaves.
*
* IT IS SHARDED, AND THE MERGE IS WHAT MAKES THAT SAFE. The draft path never goes through the
* sampler, so its argmax is a `row_topk` over one rank's plane -- and a sharded plane on its
* own would let each rank propose only from its own half, while the selector's codebooks are
* gathered by GLOBAL token id and would then see only the candidates that landed locally. The
* merge runs BEFORE the selector: each rank's top-R comes back as global ids, an all_gather
* moves R pairs a row, and `row_topk_merge` reduces them to the same global top-R an unsharded
* head would have found -- exactly, ties included (docs/OPS.md). Both ranks then hold the same
* candidate set and the codebooks are replicated, so everything downstream is unchanged.
*
* What it buys is the widest read on the draft path halved -- 341 MiB of codes and scales at
* the whole vocabulary -- and that much device memory given back per rank. What it costs is
* one all_gather of `world * R` pairs a row, which at R = 16 is 2 KiB: the link's latency and
* essentially no bytes. */
* When sharded, each rank's `row_topk` reports global ids, an all_gather moves R pairs a row,
* and `row_topk_merge` reduces them to exactly the unsharded global top-R, ties included
* (docs/OPS.md). This runs before the selector, so every rank holds the same candidates for
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16). */
enum { DF_W2_GROUP = 128 };
const bool dh_shard = head_sharded(g);
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
@@ -418,12 +354,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
/* K, V AND Q ARE THREE WEIGHTS, which is not the fusion every other attention block in
* this library makes. Q is separate because of the context pass: it needs k and v over the
* trunk's projected hidden state and has no use for q at all, so a fused qkv would make it
* compute and discard a q_dim-wide GEMM per layer per context token. K and V are separate
* because a block-scaled weight's layout follows its op's N, and both passes take one of
* them at a time -- see the note beside the declarations. */
/* q, k and v are separate weights. The context pass needs only k and v, so a fused qkv
* would compute and discard q for every context token. k and v: see w_q's declaration. */
RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
@@ -461,16 +393,12 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
}
/* NON-CAUSAL, WINDOWED. 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 config
* (`is_causal: false`) and not a default. The window is the checkpoint's `sliding_window`, and
* it is the reason the context pass has a bounded amount of real work in it.
/* Non-causal and windowed: the block is denoised as a whole, so each query row sees its whole
* block plus the context (`causal` comes from the config's `is_causal: false`). The window is
* the checkpoint's `sliding_window`.
*
* DECLARED FIRST, before either kv_store, even though it runs long 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),
@@ -482,37 +410,28 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.q}, {w.attn});
/* ---------------------------------------------------------------- the context pass */
/* EVERY LINEAR HERE IS `fp8a8` -- or `mxfp4a8` where the recipe made the drafter 4-bit; DenseFP8
* reads which off the container and declares the GEMM (`gemm()`), and either one reads the
* same E4M3 pair -- and every activation that feeds one gets a `quant_act_fp8` in
* front of it. The fp8 weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
* why), and there is no `fp8a16` band anywhere in this block: that kernel is M <= 1, and
* neither pass here ever runs at one row -- a context pass is a committed chunk and a query
* pass is `block` rows by construction.
/* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the
* container and declares the GEMM), reading an E4M3 activation pair from a `quant_act_fp8`.
* There is no `fp8a16` band: that kernel is M <= 1, and neither pass runs at one row.
*
* AND NOTHING HERE IS ROW-SLICED. The fp8a8 pair covers every M (narrow to 16, tiled above),
* so a context pass over a 2048-token prefill chunk is one launch a layer rather than one per
* 64 rows.
*
* The convolutions' coefficient projections and the selector's hidden projection are still
* bf16, and they are not sliced either: libr4d's bf16 GEMM row is C_LE("M", 65536), and all
* three of these carry K = n_embd, a multiple of 16, so the wide row serves them whole. */
* Nothing is row-sliced: the fp8a8 pair covers every M, and libr4d's bf16 GEMM row (used by
* the conv coefficient projections and the selector's hidden projection, K = n_embd) is
* C_LE("M", 65536). */
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
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_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {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. */
/* 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. */
/* One quantise for all layers: every layer's k and v read the same `c`. */
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
@@ -520,9 +439,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{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, so two weights want two ops even
* where one would issue both. */
/* 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",
@@ -532,17 +450,18 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
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. */
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),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.ck}, {w.ck});
/* A whole-head NeoX rope over a q-only or k-only tensor of `heads` heads: `rope` rotates the
* first n_head + n_head_kv heads, so n_head_kv is 0. Weightless, so one op serves every layer. */
auto rope = [&](int64_t rows, int64_t heads, rad_buf x) {
return rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{x}, {x});
};
op_crope = rope(crows, g.n_head_kv, 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),
@@ -552,15 +471,24 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.ck, w.cv}, {});
/* ---------------------------------------------------------------- the query pass */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), 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(w_tok)),
{}, {w.x});
/* The trunk's embedding is vocab-sharded, so this gather is partial and takes the same exact
* reduction. It is on the DRAFT path, which runs once a step ahead of the trunk: a second
* small collective. */
/* An unscaled lookup is declared exactly as before the scale existed, so a Qwen container
* resolves the same op. */
if (cfg.escale != 1.0)
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), 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_F64("mult", cfg.escale)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
else
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), 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(w_tok)),
{}, {w.x});
/* The trunk's embedding 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),
@@ -568,10 +496,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{w.x}, {w.x});
/* The query pass's three quantisers, declared once and issued per layer -- weightless ops with
* the same shape every layer, exactly like the ropes and the residual add below. h2 is
* quantised TWICE a layer because the convolution rewrites it between the two halves; attn and
* ffn once each. */
/* The query pass's quantisers, issued per layer: h2 twice (the convolution rewrites it between
* the halves), attn and ffn once each. */
op_qh2 = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
@@ -629,40 +555,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_fcp[i])),
{w.h}, {w.coef});
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
/* THE SAME FOLD THE TRUNK'S MLP HAS, over the same weights and into the same activation;
* rad_block_mlp_fp8.h declares it beside the pair for the same reason. Unfused, a layer
* runs gate_up -> silu_mul -> quant, which is two extra launches and two extra passes over
* the [T, n_ff] product. The gated kernel is also the faster of the two on the SAME shape,
* because the fold saves the bf16 round trip.
*
* NOT RAD_ARCH_TRY: a kernel set without the row is the ordinary case and the pair below
* still runs. `gated_rows` is the band it was declared over and the issue site checks it,
* because M > 64 is a refusal in the kernel and not a slower path. */
{
const int64_t hi = qrows < 64 ? qrows : 64;
if (hi > 0 && !w_gu[i].mx) { /* the fold is an fp8a8 tile; an MXFP4 gate_up takes the pair */
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.h2q, w.h2s}, {w.ffq, w.ffs});
if (op_gug[i]) gated_rows = hi;
}
}
/* The fold saves two launches and the bf16 round trip of the [T, n_ff] product; it is an
* fp8a8 tile, so an MXFP4 gate_up takes the pair. */
if (!w_gu[i].mx)
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
{w.h2q, w.h2s}, {w.ffq, w.ffs}, &gated_rows);
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
}
/* The convolutions. `block_size` is the QUERY BLOCK -- the mask that kills the shifted tap at
* the first row of each block is what keeps one sequence's block from convolving with the
* previous sequence's, so it is the batch's per-sequence row count and not a tuning number.
/* The convolutions. `block_size` is the query block: the shifted tap is masked at each block's
* first row so one sequence's block does not convolve with the previous one's.
*
* ONE OP PER (LAYER, CONVOLUTION) even though every one of them is the same shape, because the
* base kernel is a WEIGHT and an op's declared weight list is what gives a weight its prefetch
* interval and its residency class. A single shared declaration would leave ten weights that
* no op admits to using. Each is issued twice -- `prepare` and `finish` -- against the two
* halves of one [2, taps, n_embd] tensor. */
* One op per (layer, convolution) because the base kernel is a weight (see op_ck). Each op is
* issued twice, prepare and finish, against the two halves of its [2, taps, n_embd] tensor. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_aconv[i] = rw(b, RAD_OP(b, "dflash_conv",
@@ -680,20 +585,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_fcb[i])),
{w.h, w.coef}, {w.h2});
}
op_qrope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.q}, {w.q});
op_krope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.k}, {w.k});
/* The attention output is written and read inside every layer, between the two halves of the
* attention convolution, but its two ops (op_attn, op_qat) are declared once ahead of the
* layers. Planned from those alone, its range would end before the coefficients' begins and
* the plan could lay one over the other. Read by the last convolution as well, it is live
* wherever the coefficients are. */
if (rad_op_reads(b, op_fconv[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
op_qrope = rope(qrows, g.n_head, w.q);
op_krope = rope(qrows, g.n_head_kv, 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),
@@ -728,15 +627,12 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
/* ---------------------------------------------------------------- the head and the selector
*
* THE MASK ROWS, offsets 1..block-1 of each sequence's block. Offset 0 is the ANCHOR -- the
* token the target has already chosen -- and its row predicts nothing: it is there so the mask
* rows have something to attend to. Each mask row predicts the token at ITS OWN position, so
* the head runs over `steps` rows a sequence and not `block`. Getting this off by one is the
* kind of mistake that costs nothing visible: the drafts are simply wrong, acceptance
* collapses, and the model's own output stays exactly correct.
* The head runs over the mask rows, offsets 1..block-1 of each block: `steps` rows per
* sequence, each predicting the token at its own position. The anchor row predicts nothing.
* An off-by-one here only shows as collapsed acceptance; the output stays correct.
*
* 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 `dflash_select` reads. */
* The gather makes those rows contiguous, numbered s * steps + l as `dflash_select` reads
* them. */
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)),
@@ -753,10 +649,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
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, so that graph is the one it always was -- 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. */
const bool rerank = w_lm && (dh_shard || g.world <= 1); /* see op_drerank below */
if (!rerank) top_w = cfg.sel_topk;
op_dtopk = dh_shard
@@ -771,17 +666,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("R", top_w), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary});
/* THE CANDIDATES ARE RESCORED EXACTLY when the target's head can be read row by row. The
* coarse head proposes its top kRerankR, `logit_rerank` scores those against the target's own
* fp8 head and re-sorts them, and the selector reads the best sel_topk of that order -- the
* candidate set and the unary logits the drafter was trained against, at kRerankR rows of the
* weight a draft row instead of a second, finer copy of the head. On Qwen3.8-27B the 2-bit
* head's own top-1 matches the exact head's on 76% of draft rows and the rescored one on all of
* them; served at depth 7 that is the 4-bit head's speed at half its bytes (330 MiB).
/* Exact rescoring when the target's head can be read row by row: the coarse head proposes its
* top kRerankR, `logit_rerank` scores them against the target's head and re-sorts, and the
* selector reads the best sel_topk, giving the candidates and unary logits the drafter was
* trained against. On Qwen3.8-27B the 2-bit head's top-1 matches the exact head on 76% of
* draft rows, the rescored one on all; this matches the 4-bit head's speed at half its bytes.
*
* Sharded, each rank rescores only ids it owns (row_topk reports this rank's slice), and the
* gather and merge below then rank exact values. A replicated draft head above one rank
* proposes ids another rank owns, so it keeps its own scores. */
* Sharded, each rank rescores only ids it owns and the merge below ranks exact values. A
* replicated head above one rank proposes ids other ranks own, so it keeps its own scores. */
if (rerank) {
op_drerank = RAD_OP(b, "logit_rerank",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
@@ -795,9 +687,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
}
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 same reason the sampler's own
* candidate gather carries `row`. */
/* Row-interleaved, so one draft position's pairs from every rank are adjacent, as
* `row_topk_merge` reads them. */
op_dgather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * top_w * 2),
@@ -817,8 +708,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_selp)),
{w.sel_h}, {w.hp});
/* `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.sel_topk), RAD_INT("rank", cfg.sel_rank),
@@ -838,10 +729,7 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
/* NOT SLICED. A context pass is one row a committed token, so it is as wide as the prefill
* chunk; the fp8a8 pair covers every M, so each op here is one launch and not one per 64
* rows. */
/* As wide as the prefill chunk, one launch per op (the fp8a8 pair covers every M). */
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, w_fc.bref());
@@ -872,7 +760,6 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
const int64_t NG = cfg.ng(g.n_embd);
const int64_t half = cfg.taps * NG; /* prepare's coefficients, then finish's */
@@ -913,10 +800,9 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
/* BEFORE the closing convolution, not after. The convolution is linear in its input and
* its coefficients come from the replicated pre-attention norm, so either order is the
* same arithmetic -- and reducing first keeps the residual stream's contract ("what the
* ranks add to x has already been agreed") in one place. */
/* Reduce before the closing convolution. It is linear with coefficients from the
* replicated norm, so either order gives the same result; reducing first keeps x's
* update agreed across ranks. */
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
@@ -948,27 +834,20 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
/* The rows that predict something: `steps` of every sequence's `block`. The scheduler names
* them through out_ids, the same field the trunk's own logits gather reads. */
/* The predicting rows, `steps` per sequence, 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), 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);
/* RAD_NONE is the `pairs` slot: operands are POSITIONAL, so an optional one that the graph
* does not use is still passed, absent. Omitting it is a miscount and the engine refuses the
* op rather than guessing which of the four was left out.
*
* SHARDED, the top-R over this rank's plane 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 (they are the same R entries the pairs plane holds) and keeps one issue site
* for both paths. */
/* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and
* the merge overwrites `cand`/`unary`. */
if (op_dmerge) {
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
brows(w.dpair, S));
+150
View File
@@ -0,0 +1,150 @@
/* GLM's stateful compressed-index core. The caller supplies projected queries,
* signed F32 head gates, and [LayerNorm(key), pool_gate] BF16 rows. No RoPE.
* Query projections are replicated across TP ranks; selected pages belong to MLA. */
#ifndef RAD_BLOCK_DSA_CACHE_H
#define RAD_BLOCK_DSA_CACHE_H
#include "rad_arch.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;
};
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;
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);
}
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 }, {});
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 });
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 });
return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL;
}
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;
RAD_ISSUE_N(ctx, op_query, T * 32, brows(w.query, T * 32), brows(w.codes, T * 32),
brows(w.scales, T * 32));
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));
int64_t live = ((int64_t)batch->max_ctx_len + T + 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 (live > ib->block_table_pitch) live = ib->block_table_pitch;
if (live < 1) live = 1;
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_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));
}
};
}
} // namespace rad::arch
#endif
+183 -304
View File
@@ -2,161 +2,116 @@
*
* ============================== 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
* 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 fp8). 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 +124,71 @@ 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. */
/* 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 */
rad_buf srcq = 0, srcs = 0; /* fp8 codes and scales: e4m3 | f32 [.., /128] */
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 +197,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 +212,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] = {};
@@ -295,10 +238,10 @@ struct Dspark {
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,10 +269,8 @@ 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;
@@ -346,11 +287,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 +301,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 +362,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,10 +379,8 @@ 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. */
* Every linear is `fp8a8`, fed by a `quant_act_fp8`. There is no `fp8a16` band: that kernel is
* M <= 1, and neither pass runs at one row. */
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
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)),
@@ -462,16 +392,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
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. */
/* 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. */
/* One quantise for all layers: every layer's k and v read the same `c`. */
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
@@ -479,8 +408,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
{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. */
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
* and 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),
@@ -500,14 +429,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 +456,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,25 +467,16 @@ 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). 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_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
@@ -580,19 +497,13 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
{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);
@@ -641,24 +552,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
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_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] = 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),
@@ -698,11 +593,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_INT("group", RAD_FP8_BLOCK), 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 +608,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 +627,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 +643,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 +660,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),
@@ -830,9 +715,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,9 +731,8 @@ 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);
@@ -861,9 +744,8 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
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,
@@ -896,28 +778,25 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
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 +805,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));
+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));
+187 -194
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 {
@@ -135,33 +117,38 @@ 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;
int64_t cr_rows = 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 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 +166,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 +179,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 +191,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 +215,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 +251,21 @@ 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});
/* ---- 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 +295,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,16 +306,14 @@ 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. */
/* 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. */
if (op_recur && w.o.cq()) {
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",
@@ -413,7 +347,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,53 +368,87 @@ 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();
/* 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: a spanned
* step is past the prompt's first interval, so its context length is never zero. */
if (!own_ar && pieces && pieces->cu && pieces->cuts(T) && T <= 2 * pieces->rows && ext_in &&
!op_add && S == 1 && batch->phase == RAD_PHASE_PREFILL) {
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->ctx_lens, 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;
}
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));
/* THE TWO PATHS, EACH OVER ITS OWN RUN OF SEQUENCES.
/* 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;
@@ -503,6 +482,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch) const {
w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
}
/* 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 +504,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));
}
+334
View File
@@ -0,0 +1,334 @@
/* 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).
*
* 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;
};
bool on = false, standardize = 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;
}
/* Clipped linears (their bounds are buffers the vision checkpoint states as infinite) and
* any rotary or activation other than the 2-D one and gelu-tanh are refused by name. */
if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
(std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
std::strcmp(act, "gelu_pytorch_tanh")) {
fprintf(stderr, "radiance: %s: this vision tower uses clipped linears, a '%s' rotary or "
"a '%s' activation, which it does not serve\n", who, 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;
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);
}
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 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) {
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;
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; %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" : "", (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));
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 */
+109
View File
@@ -0,0 +1,109 @@
/* Replicated GLM indexer front end. Casts bridge ordinary linear rows to the
* flattened per-head quantizer and join normalized keys with learned pool gates. */
#ifndef RAD_BLOCK_GLM_INDEXER_H
#define RAD_BLOCK_GLM_INDEXER_H
#include "rad_fp8.h"
#include "rad_block_dsa_cache.h"
#include "rad_tp_split.h"
namespace rad {
namespace arch {
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;
SplitF32Proj head_split{};
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(head_split.declare(b, nm, g, nm.f("blk.%d.index_head", l), g.max_tok, 32, 4096,
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;
};
query.step(ctx, act(w.q_low), w.q_wide, T);
RAD_ISSUE_N(ctx, op_query_copy, T * 32, brows(w.q_wide, T), brows(w.cache.query, T * 32));
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 (head_split.takes(T))
head_split.step(ctx, T, brows(w.input, T), head_weight, brows(w.cache.gate, T));
else
RAD_ISSUE_N(ctx, op_head, T, brows(w.input, T), RAD_W(head_weight),
brows(w.cache.gate, T));
cache.step(ctx, batch);
}
};
}
} // namespace rad::arch
#endif
+102
View File
@@ -0,0 +1,102 @@
/* GLM KDA projections around the recurrent/cache core. These checkpoint weights
* are BF16. The two low-rank gate paths have no intervening activation. The
* caller supplies normalized input and owns the mHC residual connection. */
#ifndef RAD_BLOCK_GLM_KDA_H
#define RAD_BLOCK_GLM_KDA_H
#include "rad_fp8.h"
#include "rad_block_kda_state.h"
namespace rad {
namespace arch {
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 || 64 % 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.
Geom bg = g;
bg.w_bf16 = true;
const int64_t width = 8192 / g.world, heads = 64 / 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));
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(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_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(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 (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 ||
!gate_b.bf16 || !output.bf16)
return RAD_E_UNSUPPORTED;
if (reduce && g.world > 1)
op_ar = 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", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{ w.out }, { 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);
forget_b.step(ctx, act(w.forget_low), w.core.a, T);
gate_a.step(ctx, input, w.gate_low, 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
+118
View File
@@ -0,0 +1,118 @@
/* No-RoPE GLM MLA. prepare() exposes normalized Q-lora for the replicated
* indexer; finish() consumes its selection. The caller owns the mHC residual. */
#ifndef RAD_BLOCK_GLM_MLA_H
#define RAD_BLOCK_GLM_MLA_H
#include "rad_fp8.h"
#include "rad_block_mla_latent.h"
namespace rad {
namespace arch {
struct GlmMla {
struct Wire {
ActFP8 input{}, q_low{}, attn{};
rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0;
MlaLatent::Wire core{};
};
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_ar = 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 || 64 % 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), 16384 / 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.
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", "bf16")),
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 = 64 / 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, 16384 / g.world));
RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096,
16384 / g.world, RAD_SHARD_COL, grp_layer(layer),
{ nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out));
if (reduce && g.world > 1)
op_ar = 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", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{ w.out }, { w.out });
return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL;
}
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));
q_b.step(ctx, w.q_low, w.core.q, T);
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;
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);
}
};
}
} // namespace rad::arch
#endif
+82
View File
@@ -0,0 +1,82 @@
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */
#ifndef RAD_BLOCK_GLM_ROUTER_H
#define RAD_BLOCK_GLM_ROUTER_H
#include "rad_tp_split.h"
#include <cmath>
namespace rad {
namespace arch {
struct GlmRouter {
struct Config {
int64_t experts = 288, top_k = 8, rows = 32;
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 || !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));
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
+98 -122
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,32 @@ 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 fp8 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 stay E4M3, the routed experts' operand. */
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 +111,20 @@ 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 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 +135,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 +159,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 +181,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");
@@ -214,7 +202,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 +212,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 +224,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,21 +235,16 @@ 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;
@@ -271,7 +252,9 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
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),
@@ -293,12 +276,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 +287,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 +303,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),
@@ -389,9 +365,9 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
c.rotate ? brow_slice(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 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)) {
+128
View File
@@ -0,0 +1,128 @@
/* GLM's recurrent core over already projected inputs. ple_conv supplies exactly
* causal depthwise convolution + SiLU, including cold start and accepted-history rollback. */
#ifndef RAD_BLOCK_KDA_STATE_H
#define RAD_BLOCK_KDA_STATE_H
#include "rad_arch.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));
}
};
}
} // namespace rad::arch
#endif
+136
View File
@@ -0,0 +1,136 @@
/* GLM manifold-constrained residual connections. The mixed residual must have a
* separate destination: each output stream reads every original input stream. */
#ifndef RAD_BLOCK_MHC_H
#define RAD_BLOCK_MHC_H
#include "rad_tp_split.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_tp_split.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 = kGlmTpSplitRows;
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
+84
View File
@@ -0,0 +1,84 @@
/* Absorbed GLM MLA core. The caller projects/norms q and stores the current
* latent before step(). Complete heads shard as rows of the shared K/V weight. */
#ifndef RAD_BLOCK_MLA_LATENT_H
#define RAD_BLOCK_MLA_LATENT_H
#include "rad_arch.h"
#include <cmath>
namespace rad {
namespace arch {
struct MlaLatent {
struct Config {
int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513;
};
struct Wire {
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 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,
RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim),
RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks),
RAD_INT("block_size", 4),
RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ 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));
}
};
}
} // namespace rad::arch
#endif
+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));
+54 -81
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,36 @@ 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 fold is the narrow tile's epilogue and
* serves M <= 64, so prefill chunks take the pair. 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. */
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);
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;
};
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) {
g = geom; w = wire; layer = l;
ar_out = ar_out_;
@@ -104,41 +87,34 @@ 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. */
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,
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, so bf16, f32-scaled, MXFP4, rotated 5-bit, 4-bit
* and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product.
* Declared over int8 codes, only a host kernel would take it, and that would pin the layer's
* weights to the host. */
if (swiglu_limit <= 0 && !gate_up.bf16 && !gate_up.f32_scale && !gate_up.mx &&
!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);
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));
@@ -152,7 +128,7 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
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,14 +139,11 @@ 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);
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 */
+170 -230
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
@@ -99,32 +76,24 @@
#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,12 +101,12 @@ 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;
AttnGatedFP8::Wire attn{};
MoeFP8::Wire mlp{};
@@ -160,12 +129,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 +142,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;
@@ -189,8 +159,8 @@ struct MtpHcBlock {
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;
/* 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 +176,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 +194,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 +212,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 +226,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 +246,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,7 +257,22 @@ 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; }
@@ -301,7 +281,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
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 +295,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 +313,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 +323,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 +358,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 +373,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 +395,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),
@@ -481,11 +423,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
}
if (!op_dquant || !op_dlogits || !op_dtopk) 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;
@@ -494,16 +434,15 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
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 +461,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));
+116 -188
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,7 +96,7 @@ 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;
@@ -121,7 +114,7 @@ struct PleLayer {
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;
};
@@ -140,7 +133,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 +144,41 @@ 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-w4.recipe); 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 +192,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,8 +205,7 @@ 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: the FP8 checkpoint's `modules_to_not_convert` names both projections. */
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());
@@ -269,15 +233,13 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
!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 +252,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 +265,38 @@ 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. */
/* Twice the step's rows: the step's ids, then those of the prompt that follows
* (RadBatch::n_ahead), which the gather's reader prefetches while the step runs. */
RadBufDecl d{};
d.dtype = RAD_I32; d.rank = 2; d.shape[0] = 2 * 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 +306,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 +318,16 @@ 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});
}
op_embd = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim),
@@ -404,8 +346,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_WEIGHTS(w_value)),
{b_embd}, {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,9 +362,8 @@ 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)),
@@ -435,26 +376,19 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
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 +409,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,
@@ -494,7 +428,6 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
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,17 +436,14 @@ 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));
@@ -541,9 +471,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));
}
+99 -42
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,19 +63,28 @@ 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;
}
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);
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) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
@@ -98,21 +109,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 +150,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,12 +164,12 @@ 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);
};
@@ -182,10 +205,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 +278,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 +322,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 +331,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 +347,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 +367,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;
+951 -587
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 */
+204 -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{};
@@ -266,27 +218,20 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
if (!*bk) return RAD_E_INVAL;
}
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 +242,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),
@@ -314,58 +258,28 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
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 +303,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 +405,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);
+65
View File
@@ -0,0 +1,65 @@
/* GLM's replicated F32 work split over the tensor-parallel ranks: each rank computes a disjoint
* part with the replicated kernel's own arithmetic and an all_gather moves the parts to every rank,
* so every value is bit-identical to the replicated computation's. */
#ifndef RAD_TP_SPLIT_H
#define RAD_TP_SPLIT_H
#include "rad_arch.h"
namespace rad {
namespace arch {
/* Rows from which a replicated F32 projection splits its columns over the ranks. Below it the
* collective's latency outweighs the saved arithmetic, so decode keeps the replicated form. */
constexpr int64_t kGlmTpSplitRows = 256;
/* 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 = kGlmTpSplitRows;
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
+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 */
+10
View File
@@ -0,0 +1,10 @@
# 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)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(embgemma2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/embgemma2.cpp)
+915
View File
@@ -0,0 +1,915 @@
/* embgemma2 -- EmbeddingGemma 2, a bidirectional Gemma encoder that pools a whole input into one
* vector. bf16 weights and bf16 activations.
*
* 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 ==============================
*
* 24 layers, hidden 512, ffn 2048, vocab 262144, embedding scale sqrt(512) rounded to bf16
* 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,
* v with no gain
* 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
* 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; normalisation is the server's (it truncates to
* `dimensions` first), so the pooled row here is the unnormalised mean.
*
* Everything the checkpoint carries is declared: the text model, the vision tower
* (rad_block_gemma4_vision.h) and the audio encoder.
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_gemma4_vision.h>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <vector>
namespace embgemma2 {
using namespace rad::arch;
/* What a layer's attention is: the two kinds differ in head width, KV head count, rotary base and
* window, and nothing else. */
struct Kind {
int64_t head_dim = 0;
int64_t n_head = 0;
int64_t n_head_kv = 0;
double theta = 0.0;
int64_t window = 0; /* attn_dense's `window`: |i - j| < window, 0 the whole input */
int64_t qkv() const { return (n_head + 2 * n_head_kv) * head_dim; }
int64_t q() const { return n_head * head_dim; }
};
struct Layer {
int full = 0;
rad_weight w_in_norm = 0, w_qkv = 0, w_q_norm = 0, w_k_norm = 0, w_o = 0, w_post_attn = 0;
rad_weight w_pre_ff = 0, w_gate_up = 0, w_down = 0, w_post_ff = 0;
rad_weight w_ple_gate = 0, w_ple_proj = 0, w_post_ple = 0, w_scalar = 0;
rad_op op_in_norm = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_post_attn = 0;
rad_op op_add_attn = 0, op_pre_ff = 0, op_gate_up = 0, op_act = 0, op_down = 0;
rad_op op_post_ff = 0, op_add_ff = 0, op_ple_gate = 0, op_ple_act = 0, op_ple_proj = 0;
rad_op op_post_ple = 0, op_add_ple = 0, op_scale = 0;
};
/* ============================== 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 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. */
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
* 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));
}
};
struct Model {
Names nm{""};
Geom g{};
Kind ks{}, kf{}; /* sliding, full */
int64_t n_ple = 0; /* hidden_size_per_layer_input */
int64_t n_out = 0; /* embedding_dim */
rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv_s = 0, b_qkv_f = 0, b_att_s = 0, b_att_f = 0;
rad_buf b_gu = 0, b_ff = 0, b_p = 0, b_ple = 0, b_mean = 0, b_proj = 0, b_pooled = 0;
rad_weight w_tok = 0, w_ple_proj = 0, w_ple_norm = 0, w_norm = 0, w_out = 0;
rad_op op_embed = 0, op_ple = 0, op_ple_norm = 0, op_norm = 0, op_mean = 0, op_out = 0;
rad_op op_cast = 0;
rad_op op_mm = 0; /* the media rows over their placeholders' embeddings */
std::vector<Layer> layers;
Gemma4Vision vis;
Audio aud;
};
static Model g_model[MAX_RANKS];
/* 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) {
fprintf(stderr, "radiance: embgemma2: the container has no layer_types; it says which "
"layers are sliding and which see the whole input, and is not guessed\n");
return RAD_E_INVAL;
}
full->clear();
for (const char* p = s; *p; ) {
while (*p == ' ') ++p;
if (!*p) break;
const char* t = p;
while (*p && *p != ' ') ++p;
const size_t len = (size_t)(p - t);
if (len == 14 && !std::strncmp(t, "full_attention", 14)) full->push_back(1);
else if (len == 17 && !std::strncmp(t, "sliding_attention", 17)) full->push_back(0);
else {
fprintf(stderr, "radiance: embgemma2: layer_types names '%.*s'; this plugin knows "
"full_attention and sliding_attention\n", (int)len, t);
return RAD_E_UNSUPPORTED;
}
}
if ((int64_t)full->size() != n_layer) {
fprintf(stderr, "radiance: embgemma2: layer_types names %zu layers and the model has "
"%lld\n", full->size(), (long long)n_layer);
return RAD_E_INVAL;
}
return RAD_OK;
}
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 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];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
Geom& g = m.g;
Names& nm = m.nm;
const int64_t T = g.max_tok, E = g.n_embd;
std::vector<int> full;
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 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);
/* 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;
m.kf.theta = rad_meta_getf(meta, "rope_parameters.full_attention.rope_theta", 0.0);
m.kf.window = 0;
for (int64_t l = 0; l < g.n_layer; ++l) {
if (!full[(size_t)l]) continue;
char k1[96], k2[96];
std::snprintf(k1, sizeof k1, "per_layer_config.%02lld.head_dim", (long long)l);
std::snprintf(k2, sizeof k2, "per_layer_config.%02lld.num_key_value_heads", (long long)l);
const int64_t hd = meta_int2(meta, "", k1, 0), kv = meta_int2(meta, "", k2, 0);
if (!m.kf.head_dim) { m.kf.head_dim = hd; m.kf.n_head_kv = kv; }
if (hd <= 0 || kv <= 0 || hd != m.kf.head_dim || kv != m.kf.n_head_kv) {
fprintf(stderr, "radiance: embgemma2: full-attention layer %lld states head_dim %lld "
"and %lld KV heads; this plugin serves one full geometry\n",
(long long)l, (long long)hd, (long long)kv);
return RAD_E_INVAL;
}
}
m.n_ple = meta_int2(meta, "", "hidden_size_per_layer_input", 0);
m.n_out = meta_int2(meta, "", "embedding_dim", 0);
if (!(m.ks.theta > 0) || !(m.kf.theta > 0) || radius <= 0 || m.kf.head_dim <= 0 ||
m.n_ple <= 0 || m.n_out <= 0 || m.ks.n_head % m.ks.n_head_kv || m.kf.n_head % m.kf.n_head_kv) {
fprintf(stderr, "radiance: embgemma2: the container does not describe the model (rope "
"thetas %g / %g, sliding_window %lld, full head_dim %lld, "
"hidden_size_per_layer_input %lld, embedding_dim %lld)\n",
m.ks.theta, m.kf.theta, (long long)radius, (long long)m.kf.head_dim,
(long long)m.n_ple, (long long)m.n_out);
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
* step's token budget. */
const int64_t max_seg = T;
/* ---- 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});
m.b_qkv_s = decl_b(b, nm.f("qkv_s"), RAD_BF16, {T, m.ks.qkv()});
m.b_qkv_f = decl_b(b, nm.f("qkv_f"), RAD_BF16, {T, m.kf.qkv()});
m.b_att_s = decl_b(b, nm.f("att_s"), RAD_BF16, {T, m.ks.q()});
m.b_att_f = decl_b(b, nm.f("att_f"), RAD_BF16, {T, m.kf.q()});
m.b_gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * g.n_ff});
m.b_ff = decl_b(b, nm.f("ffn"), RAD_BF16, {T, g.n_ff});
m.b_p = decl_b(b, nm.f("ple_p"), RAD_BF16, {T, m.n_ple});
m.b_ple = decl_b(b, nm.f("ple"), RAD_BF16, {T, P});
m.b_mean = decl_b(b, nm.f("mean"), RAD_BF16, {g.max_seqs, E});
m.b_proj = decl_b(b, nm.f("proj"), RAD_BF16, {g.max_seqs, m.n_out});
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, 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"),
nm.ckpt("%s.ple.per_layer_model_projection.weight", L)));
RAD_ARCH_TRY(map_copy(b, nm.f("ple_norm.weight"),
nm.ckpt("%s.ple.per_layer_projection_norm.weight", L)));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.norm.weight", L)));
RAD_ARCH_TRY(map_copy(b, nm.f("embd_proj.weight"),
nm.ckpt("%s.embedding_projection.weight", L)));
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, E},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
m.w_ple_proj = decl_w(b, nm.f("ple_proj.weight"), RAD_BF16, {P, E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.w_ple_norm = decl_w(b, nm.f("ple_norm.weight"), RAD_BF16, {m.n_ple},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.w_norm = decl_w(b, nm.f("output_norm.weight"), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.w_out = decl_w(b, nm.f("embd_proj.weight"), RAD_BF16, {m.n_out, E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
auto rmsnorm = [&](int64_t rows, int64_t n, double eps, rad_weight w) {
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_WEIGHTS(w));
};
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 elem = [&](const char* op, int64_t n, rad_weight w) {
if (w)
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
auto act_mul = [&](int64_t n) {
return RAD_OP(b, "act_mul", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n),
RAD_STR("act", "gelu_tanh"),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
/* 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; 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) ||
(Audio::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")),
RAD_NOWEIGHTS),
{m.b_x}, {m.b_x});
m.op_ple = rw(b, gemm(T, P, E, m.w_ple_proj), {m.b_x}, {m.b_ple});
m.op_ple_norm = rw(b, rmsnorm(T * g.n_layer, m.n_ple, (double)g.eps * (double)E, m.w_ple_norm),
{m.b_ple}, {m.b_ple});
m.layers.resize((size_t)g.n_layer);
for (int64_t l = 0; l < g.n_layer; ++l) {
Layer& y = m.layers[(size_t)l];
y.full = full[(size_t)l];
const Kind& k = y.full ? m.kf : m.ks;
const rad_buf qkv = y.full ? m.b_qkv_f : m.b_qkv_s;
const rad_buf att = y.full ? m.b_att_f : m.b_att_s;
const long long ll = (long long)l;
const RadWeightGroup gl = grp_layer((int)l);
auto src = [&](const char* s) { return nm.ckpt("%s.layers.%lld.%s", L, ll, s); };
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.in_norm", ll), src("input_layernorm.weight")));
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.qkv", ll),
{src("self_attn.q_proj.weight"), src("self_attn.k_proj.weight"),
src("self_attn.v_proj.weight")}));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.q_norm", ll), src("self_attn.q_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.k_norm", ll), src("self_attn.k_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.o", ll), src("self_attn.o_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.post_attn", ll),
src("post_attention_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.pre_ff", ll),
src("pre_feedforward_layernorm.weight")));
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.gate_up", ll),
{src("mlp.gate_proj.weight"), src("mlp.up_proj.weight")}));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.down", ll), src("mlp.down_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.post_ff", ll),
src("post_feedforward_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ple_gate", ll),
src("ple_block.per_layer_input_gate.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ple_proj", ll),
src("ple_block.per_layer_projection.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.post_ple", ll),
src("ple_block.post_per_layer_input_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.scalar", ll), src("layer_scalar")));
const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE;
y.w_in_norm = decl_w(b, nm.f("blk.%lld.in_norm", ll), RAD_BF16, {E}, A, N, gl);
y.w_qkv = decl_w(b, nm.f("blk.%lld.qkv", ll), RAD_BF16, {k.qkv(), E}, A, N, gl);
y.w_q_norm = decl_w(b, nm.f("blk.%lld.q_norm", ll), RAD_BF16, {k.head_dim}, A, N, gl);
y.w_k_norm = decl_w(b, nm.f("blk.%lld.k_norm", ll), RAD_BF16, {k.head_dim}, A, N, gl);
y.w_o = decl_w(b, nm.f("blk.%lld.o", ll), RAD_BF16, {E, k.q()}, A, N, gl);
y.w_post_attn = decl_w(b, nm.f("blk.%lld.post_attn", ll), RAD_BF16, {E}, A, N, gl);
y.w_pre_ff = decl_w(b, nm.f("blk.%lld.pre_ff", ll), RAD_BF16, {E}, A, N, gl);
y.w_gate_up = decl_w(b, nm.f("blk.%lld.gate_up", ll), RAD_BF16, {2 * g.n_ff, E}, A, N, gl);
y.w_down = decl_w(b, nm.f("blk.%lld.down", ll), RAD_BF16, {E, g.n_ff}, A, N, gl);
y.w_post_ff = decl_w(b, nm.f("blk.%lld.post_ff", ll), RAD_BF16, {E}, A, N, gl);
y.w_ple_gate = decl_w(b, nm.f("blk.%lld.ple_gate", ll), RAD_BF16, {m.n_ple, E}, A, N, gl);
y.w_ple_proj = decl_w(b, nm.f("blk.%lld.ple_proj", ll), RAD_BF16, {E, m.n_ple}, A, N, gl);
y.w_post_ple = decl_w(b, nm.f("blk.%lld.post_ple", ll), RAD_BF16, {E}, A, N, gl);
/* bf16 and one element: the reference multiplies the bf16 residual by it in bf16. */
y.w_scalar = decl_w(b, nm.f("blk.%lld.scalar", ll), RAD_BF16, {1}, A, N, gl);
y.op_in_norm = rw(b, rmsnorm(T, E, g.eps, y.w_in_norm), {m.b_x}, {m.b_h});
y.op_qkv = rw(b, gemm(T, k.qkv(), E, y.w_qkv), {m.b_h}, {qkv});
y.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", k.head_dim),
RAD_INT("n_head", k.n_head),
RAD_INT("n_head_kv", k.n_head_kv),
RAD_F64("theta", k.theta), RAD_F64("eps", g.eps),
RAD_STR("mode", "neox"), RAD_INT("v_norm", 1)),
RAD_WEIGHTS(y.w_q_norm, y.w_k_norm)),
{qkv}, {qkv});
y.op_attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", k.head_dim),
RAD_INT("gqa", k.n_head / k.n_head_kv),
RAD_INT("causal", 0), RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0),
RAD_INT("max_seqlen", max_seg),
RAD_INT("window", k.window)),
RAD_NOWEIGHTS),
{qkv}, {att});
y.op_o = rw(b, gemm(T, E, k.q(), y.w_o), {att}, {m.b_o});
y.op_post_attn= rw(b, rmsnorm(T, E, g.eps, y.w_post_attn), {m.b_o}, {m.b_o});
y.op_add_attn = rw(b, elem("add", E, 0), {m.b_x, m.b_o}, {m.b_x});
y.op_pre_ff = rw(b, rmsnorm(T, E, g.eps, y.w_pre_ff), {m.b_x}, {m.b_h});
y.op_gate_up = rw(b, gemm(T, 2 * g.n_ff, E, y.w_gate_up), {m.b_h}, {m.b_gu});
y.op_act = rw(b, act_mul(g.n_ff), {m.b_gu}, {m.b_ff});
y.op_down = rw(b, gemm(T, E, g.n_ff, y.w_down), {m.b_ff}, {m.b_o});
y.op_post_ff = rw(b, rmsnorm(T, E, g.eps, y.w_post_ff), {m.b_o}, {m.b_o});
y.op_add_ff = rw(b, elem("add", E, 0), {m.b_x, m.b_o}, {m.b_x});
y.op_ple_gate = rw(b, gemm(T, m.n_ple, E, y.w_ple_gate), {m.b_x}, {m.b_p});
y.op_ple_act = rw(b, act_mul(m.n_ple), {m.b_p, m.b_ple}, {m.b_p});
y.op_ple_proj = rw(b, gemm(T, E, m.n_ple, y.w_ple_proj), {m.b_p}, {m.b_o});
y.op_post_ple = rw(b, rmsnorm(T, E, g.eps, y.w_post_ple), {m.b_o}, {m.b_o});
y.op_add_ple = rw(b, elem("add", E, 0), {m.b_x, m.b_o}, {m.b_x});
y.op_scale = rw(b, RAD_OP(b, "mul_weight",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_STR("dtype", "bf16"), RAD_INT("scalar", 1)),
RAD_WEIGHTS(y.w_scalar)),
{m.b_x}, {m.b_x});
}
m.op_norm = rw(b, rmsnorm(T, E, g.eps, m.w_norm), {m.b_x}, {m.b_h});
m.op_mean = rw(b, RAD_OP(b, "seg_mean",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{m.b_h}, {m.b_mean});
m.op_out = rw(b, gemm(g.max_seqs, m.n_out, E, m.w_out), {m.b_mean}, {m.b_proj});
m.op_cast = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", m.n_out),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{m.b_proj}, {m.b_pooled});
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()));
int n_full = 0;
for (int f : full) n_full += f;
rad_note(b, "embedding model: %lld layers (%d whole-input, %lld sliding |i-j|<=%lld), hidden "
"%lld, ffn %lld; sliding %lldx%lld (kv %lld) theta %g, full %lldx%lld (kv %lld) "
"theta %g; per-layer inputs %lld; mean-pooled to %lld",
(long long)g.n_layer, n_full, (long long)(g.n_layer - n_full), (long long)radius,
(long long)E, (long long)g.n_ff, (long long)m.ks.n_head, (long long)m.ks.head_dim,
(long long)m.ks.n_head_kv, m.ks.theta, (long long)m.kf.n_head,
(long long)m.kf.head_dim, (long long)m.kf.n_head_kv, m.kf.theta,
(long long)m.n_ple, (long long)m.n_out);
return RAD_OK;
}
/* 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 (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);
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Geom& g = m.g;
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
if (batch->enc) {
if (batch->enc == RAD_MM_AUDIO) m.aud.step(c, batch);
else m.vis.step(c, batch);
return;
}
if (T <= 0 || S <= 0) return;
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
const RadOperand pos = praw(batch->positions, RAD_I32, T);
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
if (m.op_mm && batch->n_mm_rows > 0)
RAD_ISSUE_N(c, m.op_mm, batch->n_mm_rows,
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, E),
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, T));
RAD_ISSUE(c, m.op_ple, brows(m.b_x, T), RAD_W(m.w_ple_proj), brows(m.b_ple, T));
/* [T, n_layer * n_ple] read as [T * n_layer, n_ple]: one norm row per (token, layer). */
RAD_ISSUE_N(c, m.op_ple_norm, T * g.n_layer, brows(m.b_ple, T), RAD_W(m.w_ple_norm),
brows(m.b_ple, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const Layer& y = m.layers[(size_t)l];
const Kind& k = y.full ? m.kf : m.ks;
const rad_buf qkv = y.full ? m.b_qkv_f : m.b_qkv_s;
const rad_buf att = y.full ? m.b_att_f : m.b_att_s;
const int64_t q = k.q(), kv = k.n_head_kv * k.head_dim;
RAD_ISSUE(c, y.op_in_norm, brows(m.b_x, T), RAD_W(y.w_in_norm), brows(m.b_h, T));
RAD_ISSUE(c, y.op_qkv, brows(m.b_h, T), RAD_W(y.w_qkv), brows(qkv, T));
RAD_ISSUE(c, y.op_qk, brows(qkv, T), pos, RAD_W(y.w_q_norm), RAD_W(y.w_k_norm));
RAD_ISSUE(c, y.op_attn, bcol(qkv, 0, q, T), bcol(qkv, q, kv, T), bcol(qkv, q + kv, kv, T),
cu, brows(att, T));
RAD_ISSUE(c, y.op_o, brows(att, T), RAD_W(y.w_o), brows(m.b_o, T));
RAD_ISSUE(c, y.op_post_attn, brows(m.b_o, T), RAD_W(y.w_post_attn), brows(m.b_o, T));
RAD_ISSUE(c, y.op_add_attn, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
RAD_ISSUE(c, y.op_pre_ff, brows(m.b_x, T), RAD_W(y.w_pre_ff), brows(m.b_h, T));
RAD_ISSUE(c, y.op_gate_up, brows(m.b_h, T), RAD_W(y.w_gate_up), brows(m.b_gu, T));
RAD_ISSUE(c, y.op_act, bcol(m.b_gu, 0, g.n_ff, T), bcol(m.b_gu, g.n_ff, g.n_ff, T),
brows(m.b_ff, T));
RAD_ISSUE(c, y.op_down, brows(m.b_ff, T), RAD_W(y.w_down), brows(m.b_o, T));
RAD_ISSUE(c, y.op_post_ff, brows(m.b_o, T), RAD_W(y.w_post_ff), brows(m.b_o, T));
RAD_ISSUE(c, y.op_add_ff, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
RAD_ISSUE(c, y.op_ple_gate, brows(m.b_x, T), RAD_W(y.w_ple_gate), brows(m.b_p, T));
RAD_ISSUE(c, y.op_ple_act, brows(m.b_p, T), bcol(m.b_ple, l * m.n_ple, m.n_ple, T),
brows(m.b_p, T));
RAD_ISSUE(c, y.op_ple_proj, brows(m.b_p, T), RAD_W(y.w_ple_proj), brows(m.b_o, T));
RAD_ISSUE(c, y.op_post_ple, brows(m.b_o, T), RAD_W(y.w_post_ple), brows(m.b_o, T));
RAD_ISSUE(c, y.op_add_ple, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T));
RAD_ISSUE(c, y.op_scale, brows(m.b_x, T), RAD_W(y.w_scalar), brows(m.b_x, T));
}
RAD_ISSUE(c, m.op_norm, brows(m.b_x, T), RAD_W(m.w_norm), brows(m.b_h, T));
RAD_ISSUE(c, m.op_mean, brows(m.b_h, T), cu, brows(m.b_mean, S));
RAD_ISSUE_N(c, m.op_out, S, brows(m.b_mean, S), RAD_W(m.w_out), brows(m.b_proj, S));
RAD_ISSUE_N(c, m.op_cast, S, brows(m.b_proj, S), brows(m.b_pooled, S));
(void)E;
}
} /* namespace embgemma2 */
#ifndef RAD_ARCH_NO_EXPORTS
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")
RAD_ARCH_PROBE(embgemma2)
#endif
+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)
+1247
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
+682
View File
@@ -0,0 +1,682 @@
/* gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4.
*
* ============================== WHAT IT IS ==============================
*
* rad_block_dflash2.h without DFlash2's additions (the per-layer dynamic convolutions around
* attention and the feed-forward, and the candidate selector). The original DFlash is a small
* Qwen3-shaped transformer that denoises one anchor token plus `block - 1` mask tokens in one
* forward and takes every position's argmax from the target's lm_head.
*
* context pass, one row a committed token:
* c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids)))
* for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v)
*
* query pass, `block` rows a sequence:
* x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below
* for each layer:
* h = input_layernorm(x)
* q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store
* x += o_proj(attention(q, cache)) sliding layers causal over a 2048 window,
* the full layer non-causal over everything
* x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x)
* x = norm(x)
* over the mask rows: logits = lm_head(x) [the target's]; draft = argmax
*
* ============================== THE THREE GEMMA-SPECIFIC FACTS ==============================
*
* From vLLM PR #41703. Getting any of them wrong costs only acceptance, since every draft is
* verified against the trunk.
*
* The embedding is scaled. Gemma multiplies its token embedding by sqrt(hidden_size), stored as
* bf16 (53.0 at 2816), and the drafter was trained through the target's embedding module, which
* applies it. `embed_lookup`'s `mult` carries it.
*
* The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names
* four sliding layers and one full one, and the PR's test pins `causal True` on the sliding
* layers and `False` on the full one, so this block declares two attention ops and issues the one
* each layer's type names.
*
* The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
* cap * tanh(x / cap) is strictly increasing.
*
* ============================== THE HEAD ==============================
*
* The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma
* ties it to the embedding, so it is the weight the trunk's `embed_lookup` and `logits_gemm` read
* and costs no extra bytes. It is vocab-sharded with the trunk: the top-1 runs over this rank's
* slice and the ranks' candidates merge exactly (`row_topk` at R = 2 -> `all_gather` ->
* `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR).
*
* The bf16 head (262144 x 2816 x 2 bytes) is the widest read on the draft path, about 566 us of a
* 26B-A4B decode step at tp 4 on 4x R9700. So where the container holds a block-fp8 copy of the
* table under its own name, `dflash.draft_head.weight` (one checkpoint tensor, two logical
* weights, as in rad_block_dflash2.h), made by the recipe line
*
* dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
*
* the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, with the argmax over its
* coarser logits. Drafts are still verified, so the copy can change proposals but never accepted
* text. Without the copy, or in another encoding, the bf16 table is read. The copy costs half the
* table's bytes again (176 MiB per rank at tp 4). There is no rerank against the bf16 table:
* DFlash2's rerank needs the target's head in fp8 or int8, which a tied Gemma head is not.
*
* ============================== THE LINEARS ARE FP8 ==============================
*
* As in DFlash2, since the drafter is read whole on every decode step: the container must be
* converted with a recipe that makes the six linears block fp8 (or MXFP4). declare() refuses a bf16
* one by name rather than letting the loader fail on a view.
*/
#ifndef GEMMA4_DFLASH_H
#define GEMMA4_DFLASH_H
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <cstdio>
#include <cstring>
namespace gemma4 {
using namespace rad::arch;
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
* transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */
inline bool block_fp8_128(const RadEncoding& e) {
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 &&
sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK;
}
struct Dflash1 {
enum { MAX_LAYERS = 8 };
struct Config {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */
int64_t window = 0; /* the sliding layers' window; 0 for none */
int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */
double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */
int64_t steps() const { return block - 1; }
};
struct Wire {
/* the context pass */
rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | e4m3 | f32 */
rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */
rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */
/* the query pass */
rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */
rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */
rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */
rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */
/* the head, one row per draft position */
rad_buf sel_h = 0; /* [srows, n_embd] */
rad_buf selq = 0, sels = 0; /* [srows, n_embd] e4m3 | f32, the fp8 head's */
rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */
rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */
rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */
rad_buf tokens = 0; /* [srows, 1] i32: the draft, pitch `steps` */
};
Geom g{}; /* the drafter's geometry */
Config cfg{};
Wire w{};
int first_layer = 0;
int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0;
rad_kvgroup kv = 0;
bool sharded = false;
DenseFP8 w_fc{};
rad_weight w_hnorm = 0, w_norm = 0;
rad_weight w_tok = 0; /* the target's table: embedding and head */
DenseFP8 w_dh{}; /* its block-fp8 copy, the head where it is stored */
bool fp8_head = false;
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] = {};
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
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] = {};
rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
/* The residual add, norm and quantiser in one launch where `rmsnorm_quant_fp8` is served
* (libr4d): op_anq[i] for the attention input (layer 0's without the add) and op_fnq[i] for
* the feed-forward input. Zero where not served; the `add` / `rmsnorm` / `quant_act_fp8` chain
* is issued instead. */
rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {};
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0;
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0;
/* Candidates each rank contributes under a sharded head. The draft needs one, but the gather
* moves whole 16-byte words per row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is
* refused at launch (as rad_block_mtp_hc.h states). Two pairs make one word; `pair_argmax`
* reduces the world * 2 of them to the global top-1. */
static constexpr int64_t kTopR = 2;
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
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 Wire& wire,
const char* tok_src);
void context(RadCtx* c, const RadBatch* batch) const;
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; }
/* The six linears must be quantised by the recipe. DenseFP8 declares E4M3 (or MXFP4) views
* whatever the container holds, and the loader's error for a bf16 weight read through an fp8
* view would name the view, not the missing recipe. */
static int need_quantised(RadBuilder* b, const char* wn) {
RadEncoding e{};
if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */
const uint32_t dt = e.plane[0].dtype;
if (dt == RAD_F8E4M3 || dt == RAD_FP4E2M1) return RAD_OK;
fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its six linears "
"are served block fp8 (or MXFP4): convert with a recipe that names them, "
"e.g. `dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 "
"scale=bf16` and the same for fc, attn_k/v/output, ffn_gate_up and "
"ffn_down.\n", wn, rad_dtype_name(dt));
return RAD_E_DTYPE;
}
};
/* ------------------------------------------------------------------------------ declare */
inline int Dflash1::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 Wire& wire, const char* tok_src) {
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
if (!ck || !w_tok || !tok_src) return RAD_E_INVAL;
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most "
"%d\n", (long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL;
const int64_t qd = q_dim(), kvd = kv_dim();
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();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
sharded = head_sharded(g);
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.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) }));
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
/* ---------------------------------------------------------------- per-layer weights */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const RadWeightGroup gl = grp_layer(first_layer + i);
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i),
nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i),
nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i)));
w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
/* The declared names match rad_block_dflash2.h's, so one recipe quantises both
* drafters. */
RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl,
{ nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff,
g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i),
nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) },
{ g.n_ff, g.n_ff }));
RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl,
{ nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
for (const char* s : { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up",
"ffn_down" })
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, s)));
}
/* ---------------------------------------------------------------- attention: two kinds
* Declared before either kv_store, which reads `block_size` back from the resolved kernel.
* Both read the one KV group, so whichever resolves first answers for it. */
auto attn = [&](int causal, int64_t window) {
return 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", causal),
RAD_INT("window", 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", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
};
bool any_full = false, any_swa = false;
for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true;
if (any_swa) op_attn_swa = attn(1, cfg.window);
if (any_full) op_attn_full = attn(0, 0);
/* ---------------------------------------------------------------- the context pass */
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
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_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
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", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.c});
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
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_NOWEIGHTS),
{w.c}, {w.cq, w.cs});
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
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),
RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.ck}, {w.ck});
}
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),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.ck}, {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),
{w.ck, w.cv}, {});
/* ---------------------------------------------------------------- the query pass */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), 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_F64("mult", cfg.escale)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{w.x}, {w.x});
op_qh = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h}, {w.hq, w.hs});
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn}, {w.atq, w.ats});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
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_NOWEIGHTS),
{w.ffn}, {w.ffq, w.ffs});
/* x's norm under `gain`, quantised into hq|hs, in one launch; with `add`, the
* fused_add_rms_norm form (x += h first). It computes exactly the chain's result: the norm of
* the bf16-rounded sum and the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp). */
auto norm_quant = [&](rad_weight gain, bool add) -> rad_op {
const rad_op h = RAD_OP(b, "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_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)),
RAD_WEIGHTS(gain));
return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs});
};
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", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_anorm[i])),
{w.x}, {w.h});
op_anq[i] = norm_quant(w_anorm[i], l > 0);
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q});
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k});
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {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", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_qn[i])),
{w.q}, {w.q});
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", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.k});
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h});
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fnorm[i])),
{w.x}, {w.h});
op_fnq[i] = norm_quant(w_fnorm[i], true);
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up});
/* The gate_up|silu|quant fold where it resolves, else the pair (rad_block_dflash2.h's
* rule, band included). */
{
const int64_t hi = qrows < 64 ? qrows : 64;
if (hi > 0 && !w_gu[i].mx) {
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.hq, w.hs}, {w.ffq, w.ffs});
if (op_gug[i]) gated_rows = hi;
}
}
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
}
op_qrope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.q}, {w.q});
op_krope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.k}, {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),
{w.k, w.v}, {});
op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ffn});
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, qrows * 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, qrows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h}, {w.x});
op_final = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
/* ---------------------------------------------------------------- the head
* The mask rows (offsets 1..block-1 of each block, named by out_ids) are gathered contiguous,
* projected onto this rank's slice of the target's vocabulary, and the argmax taken. Sharded,
* each rank reports its best kTopR as global ids with logits; these are all-gathered and
* reduced to the global top-1 by `pair_argmax` (ties to the lower id), which is exact since the
* global winner is its own shard's first. */
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)),
RAD_NOWEIGHTS),
{w.h}, {w.sel_h});
/* The fp8 copy, where the container holds one (see the file header). The name map comes first
* since it is how the encoding is looked up; rad-convert writes only declared weights. The
* copy is row-sharded like the table, so this rank's rows are the same vocabulary slice and
* `vocab_off` holds. */
const char* dhn = nm.f("dflash.draft_head.weight");
RAD_ARCH_TRY(map_copy(b, dhn, tok_src));
RadEncoding he{};
fp8_head = weight_enc(b, dhn, &he) && block_fp8_128(he);
if (fp8_head) {
if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: gemma4: the fp8 draft head is %lldx%lld a rank, which "
"is not whole %d-row scale blocks\n",
(long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE;
w_dh.w = decl_view(b, dhn, nullptr, "codes", RAD_F8E4M3, { g.n_vocab, g.n_embd },
RAD_ACCESS_PER_TOKEN, shard, grp_model());
w_dh.s = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16,
{ fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN,
shard, grp_model());
if (!w_dh.w || !w_dh.s) return RAD_E_INVAL;
w.selq = decl_b(b, nm.f("df_selq"), RAD_F8E4M3, {srows, g.n_embd});
w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, {srows, fp8_blocks(g.n_embd)});
op_qsel = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.selq, w.sels});
op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog});
} else {
op_head = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_tok)),
{w.sel_h}, {w.dlog});
}
if (sharded) {
op_topk = rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary, w.dpair});
/* Row-interleaved, so one draft position's pairs from every rank land side by side. */
op_dgather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"),
RAD_INT("row", kTopR * 2)),
RAD_NOWEIGHTS),
{w.dpair}, {w.dgath});
op_pick = rw(b, RAD_OP(b, "pair_argmax",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{w.dgath}, {w.tokens});
if (!op_pick) {
fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the "
"device, and no loaded kernel library serves it there\n");
return RAD_E_UNSUPPORTED;
}
} else {
op_topk = rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("R", 1), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.tokens, w.unary});
}
return RAD_OK;
}
/* ------------------------------------------------------------------------------ the context pass */
inline void Dflash1::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;
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, 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, 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, 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));
RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T), praw(slot, RAD_I32, T),
kv_cache(kv, first_layer + i));
}
}
/* ------------------------------------------------------------------------------ the query pass */
inline void Dflash1::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;
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T));
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa;
/* The attention input, with the last layer's residual add where one launch takes both. */
if (op_anq[i]) {
RAD_ISSUE_N(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T),
l > 0 ? brows(w.x, T) : RAD_NONE, RAD_W(w_anorm[i]), brows(w.hq, T),
brows(w.hs, T), RAD_NONE);
} else {
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_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
}
RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T),
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.hq, T), brows(w.hs, T),
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.hq, T), brows(w.hs, T),
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));
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,
brows(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));
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
if (op_fnq[i]) {
RAD_ISSUE_N(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), RAD_W(w_fnorm[i]),
brows(w.hq, T), brows(w.hs, T), RAD_NONE);
} else {
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, 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_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
}
if (op_gug[i] && T <= gated_rows) {
RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T),
RAD_NONE);
} else {
RAD_ISSUE_N(c, op_gu[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
w_gu[i].bref());
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
/* the residual add, unless the next layer's input norm takes it */
if (l + 1 == g.n_layer || !op_anq[i + 1])
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T));
}
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
const int64_t S = batch->n_out;
if (S <= 0) return;
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
if (fp8_head) {
RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S));
RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w),
RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref());
} else {
RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S));
}
if (sharded) {
RAD_ISSUE_N(c, op_topk, 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));
RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE);
} else {
RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S),
RAD_NONE);
}
}
} /* namespace gemma4 */
#endif /* GEMMA4_DFLASH_H */
+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)
+535
View File
@@ -0,0 +1,535 @@
/* GLM-5.3-Flash: four mHC streams, KDA/latent MLA, mixed Quark weights,
* width-sharded routed experts and a native serial next-token decoder.
* This plugin uses only the public ABI and the installed common headers. */
#include <arch/rad_block_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_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{};
rad_op residual = 0;
};
struct Model {
Names nm{}, dnm{ "mtp" };
Geom g{};
std::vector<Layer> layers;
Layer draft{};
rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0;
rad_buf h0 = 0, h1 = 0, x = 0, y = 0, post = 0, comb = 0, final_hidden = 0, logit_input = 0,
logits = 0;
ActFP8 act{}, ff{};
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;
rad_buf mtp_x = 0, mtp_h = 0, mtp_e = 0, mtp_concat = 0, mtp_final = 0;
rad_weight en = 0, hn = 0, eh = 0, mnorm = 0;
rad_op mprev = 0, membed = 0, membed_ar = 0, men = 0, mhn = 0, meh = 0, mnorm_op = 0,
mselect = 0, mback = 0, mcopy = 0, mhead = 0;
bool have_mtp = false;
};
static std::unique_ptr<Model> models[MAX_RANKS];
static thread_local std::unique_ptr<Model> probe_model;
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 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 });
}
static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y, int64_t n = 4096) {
return rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
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 });
}
static int buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, W = 8192 / g.world, F = 2048 / g.world;
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto a = [&](ActFP8& v, const char* n, int64_t width) {
v.x = bf(n, width);
return v.declare_qs(b, nm, g, n, width);
};
m.h0 = bf("manifold", 16384);
m.h1 = bf("manifold_mid", 16384);
m.x = bf("collapsed", 4096);
m.y = bf("attn_delta", 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 });
RAD_ARCH_TRY(a(m.act, "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 });
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
m.kw.input = m.act.x;
m.kw.out = m.y;
m.kw.forget_low = bf("forget_low", 128);
m.kw.gate_low = bf("gate_low", 128);
m.kw.core.qkv = bf("qkv", 3 * W);
m.kw.core.conv = bf("convolved", 3 * W);
m.kw.core.a = bf("forget", W);
m.kw.core.beta = bf("beta", 64 / g.world);
m.kw.core.gate = bf("gate", W);
m.kw.core.out = bf("recurrent_out", W);
m.aw.input = m.act;
m.aw.q_raw = bf("q_raw", 1536);
m.aw.kv_raw = bf("kv_raw", 512);
RAD_ARCH_TRY(a(m.aw.q_low, "q_low", 1536));
m.aw.latent = bf("latent", 512);
m.aw.out = m.y;
m.aw.core.q = bf("query", 16384 / g.world);
m.aw.core.q_latent = decl_b(b, nm.f("q_latent"), RAD_BF16, { T, 64 / g.world, 512 });
m.aw.core.attn_latent = decl_b(b, nm.f("attn_latent"), RAD_BF16, { T, 64 / g.world, 512 });
RAD_ARCH_TRY(a(m.aw.attn, "expanded", 16384 / g.world));
m.aw.core.out = m.aw.attn.x;
m.aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { T, 513 });
m.aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { T });
const int64_t work = (T + 3) / 4 + g.max_seqs, blocks = (g.max_ctx + 3) / 4 + 1;
m.iw.input = m.act.x;
m.iw.q_low = m.aw.q_low.x;
m.iw.q_wide = bf("index_query", 4096);
m.iw.kg_raw = bf("index_key_gate", 256);
auto& iw = m.iw.cache;
iw.query = decl_b(b, nm.f("index_heads"), RAD_BF16, { T * 32, 128 });
iw.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { T * 32, 128 });
iw.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { T * 32, 1 });
iw.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { T, 32 });
iw.kg = bf("index_normalized_key_gate", 256);
iw.stage = decl_b(b, nm.f("pool_stage"), RAD_BF16, { work * 4, 256 });
iw.page = decl_b(b, nm.f("pool_page"), RAD_I32, { work });
iw.bpos = decl_b(b, nm.f("pool_pos"), RAD_I32, { work });
iw.nc = decl_b(b, nm.f("pool_count"), RAD_I32, { g.max_seqs });
iw.pooled = decl_b(b, nm.f("pool_codes"), RAD_F8E4M3, { work, 128 });
iw.pool_scale = decl_b(b, nm.f("pool_scales"), RAD_F32, { work, 1 });
iw.score = decl_b(b, nm.f("index_scores"), RAD_F32, { T, blocks });
iw.selected = m.aw.core.selected;
iw.length = m.aw.core.length;
iw.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
m.dw.x = m.x;
m.dw.h = m.act;
m.dw.gate_up = bf("dense_gate_up", 2 * g.n_ff);
RAD_ARCH_TRY(a(m.dw.ffn, "dense_ff", g.n_ff));
const int64_t R = T;
m.mw.x = m.x;
m.mw.h = m.act;
m.mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, 288 });
m.mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 });
m.mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 });
m.mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 });
m.mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 });
m.mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { R * 8 });
m.mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { R * 8 });
m.mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { R * 8, 2 * F });
m.mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { R * 8, F });
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "expert_ff", F, R * 8));
m.mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { R * 8, 4096 });
m.mw.sgu = bf("shared_gate_up", 2 * F);
RAD_ARCH_TRY(a(m.mw.sff, "shared_ff", F));
m.mw.sout = bf("shared_out", 4096);
m.mw.sgate = bf("shared_one", 1);
return RAD_OK;
}
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;
if (!draft) {
ManifoldConn::Config hc;
hc.eps = g.eps;
ManifoldConn::Wire a{ m.h0, m.x, m.y, m.h1, m.post, m.comb };
ManifoldConn::Wire f{ m.h1, m.x, m.act.x, m.h0, 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) };
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.attn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_attn", l), hc, a, as, true));
// Declare ffn mHC after the attention below: declaration order is liveness.
(void)f;
(void)fs;
}
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) {
RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.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));
}
if (!draft) {
RAD_ARCH_TRY(lay.attn_hc.declare_post(b));
ManifoldConn::Config hc;
hc.eps = g.eps;
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 {
lay.residual = rw(b,
RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.mtp_x, m.y }, { m.mtp_x });
// All history rows fill the draft cache; only proposal rows need its FFN.
m.mselect = 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.mtp_x }, { m.mtp_h });
m.mback = copy(b, g, m.mtp_h, m.mtp_x);
}
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);
s.cfg.n_expert = s.cfg.n_expert_all = 288;
s.cfg.top_k = 8;
s.cfg.n_ff_exp = s.cfg.n_ff_shared = 2048 / 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;
for (int q = 0; q < 2; ++q) {
s.cfg.ff_lo[q] = g.rank * (2048 / g.world);
s.cfg.ff_hi[q] = (g.rank + 1) * (2048 / 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;
}
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)
return RAD_E_INVAL;
const int world = ctx->world_size ? ctx->world_size : 1;
if ((world != 1 && world != 2 && world != 4 && world != 8) || meta->n_embd != 4096 ||
meta->n_layers != 45 || meta->n_vocab != 154880 ||
cfg(meta, "num_nextn_predict_layers", 0) != 1 || cfg(meta, "hc_mult", 0) != 4 ||
cfg(meta, "n_routed_experts", 0) != 288 || cfg(meta, "index_topk", 0) != 2048 ||
ctx->max_spec > 31 || (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16))
return RAD_E_UNSUPPORTED;
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
slot = std::make_unique<Model>();
auto& m = *slot;
auto& g = m.g;
m.nm = Names(ctx->scope);
auto& nm = m.nm;
g.n_layer = 45;
g.n_embd = 4096;
g.head_dim = 256;
g.n_head_all = g.n_head_kv_all = 64;
g.n_head = g.n_head_kv = 64 / world;
g.n_ff_all = 12288;
g.n_ff = 12288 / 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;
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;
g.wire_exact = !ctx->tp_wire_lossy;
g.wire_min_bytes = ctx->tp_wire_min_bytes;
if (g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0) return RAD_E_INVAL;
RAD_ARCH_TRY(buffers(b, m));
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = RAD_BF16;
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 = 64 / 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 * 8192 / world;
d.conv_width = 4;
m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d);
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 });
m.embed_ar = 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));
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) {
auto& dn = m.dnm;
m.mtp_x = decl_b(b, dn.f("x"), RAD_BF16, { g.max_tok, 4096 });
m.mtp_h = decl_b(b, dn.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST);
m.mtp_e = decl_b(b, dn.f("embedding"), RAD_BF16, { g.max_tok, 4096 });
m.mtp_concat = decl_b(b, dn.f("concat"), RAD_BF16, { g.max_tok, 8192 });
m.mtp_final = decl_b(b, dn.f("final"), RAD_BF16, { g.max_tok, 4096 });
const char* pre = "model.language_model.layers.45";
auto weight = [&](const char* n, const char* src) {
const char* name = dn.f("%s", n);
if (map_copy(b, name, dn.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0;
return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(45));
};
m.en = weight("enorm.weight", "enorm.weight");
m.hn = weight("hnorm.weight", "hnorm.weight");
m.mnorm = weight("output_norm.weight", "shared_head.norm.weight");
RAD_ARCH_TRY(map_copy(b, dn.f("eh_proj.weight"), dn.ckpt("%s.eh_proj.weight", pre)));
m.eh = decl_w(b, dn.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(45));
m.mprev = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.final_hidden }, { m.mtp_h });
m.membed = 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.mtp_e });
m.membed_ar = reduce(b, g, m.mtp_e, true);
m.men = norm(b, g, m.en, m.mtp_e, m.mtp_concat);
m.mhn = norm(b, g, m.hn, m.mtp_h, m.mtp_concat);
m.meh = rw(b,
RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096),
RAD_INT("K", 8192), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(m.eh)),
{ m.mtp_concat }, { m.mtp_x });
RAD_ARCH_TRY(layer(b, m, m.draft, dn, 45, true));
m.mnorm_op = norm(b, g, m.mnorm, m.mtp_x, m.mtp_final);
m.mcopy = copy(b, g, m.mtp_final, m.mtp_h);
m.mhead =
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.mtp_h }, { m.logits });
RadDrafterDecl dd{};
dd.name = "mtp";
dd.kind = RAD_DRAFT_SERIAL;
dd.depth = g.max_spec;
dd.mask_token = -1;
RAD_ARCH_TRY(rad_declare_drafter(b, &dd));
m.have_mtp = true;
}
rad_note(b,
"GLM-5.3: TP%d, 45 mHC layers, 34 KDA + 11 sparse MLA, mixed MXFP4/FP8, native MTP %s",
world, m.have_mtp ? "enabled" : "disabled");
return RAD_OK;
}
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 step(RadCtx* c, const RadBatch* batch) {
auto& m = *models[rad_rank(c)];
const int64_t T = batch->n_tok;
if (batch->enc) {
rad_step_fail(c, "GLM vision is not implemented by this text plugin");
return;
}
if (batch->draft_pass) {
if (!m.have_mtp || batch->draft_pass == 1) {
rad_step_fail(c, "GLM MTP pass is not declared or has invalid round 1");
return;
}
if (batch->draft_pass < 0 && batch->n_out > 0)
RAD_ISSUE_N(c, m.mprev, batch->n_out, RAD_B(m.final_hidden),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.mtp_h, batch->n_out));
RAD_ISSUE_N(c, m.membed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token),
brows(m.mtp_e, T));
if (m.membed_ar) RAD_ISSUE_N(c, m.membed_ar, T * 4096, brows(m.mtp_e, T), RAD_NONE);
RAD_ISSUE_N(c, m.men, T, brows(m.mtp_e, T), RAD_W(m.en), bcol(m.mtp_concat, 0, 4096, T));
RAD_ISSUE_N(c, m.mhn, T, brows(m.mtp_h, T), RAD_W(m.hn), bcol(m.mtp_concat, 4096, 4096, T));
RAD_ISSUE_N(c, m.meh, T, brows(m.mtp_concat, T), RAD_W(m.eh), brows(m.mtp_x, T));
auto& l = m.draft;
l.norm.step(c, T);
l.mla.prepare(c, batch);
l.index.step(c, batch);
if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return;
l.mla.finish(c, batch);
RAD_ISSUE_N(c, l.residual, T, brows(m.mtp_x, T), brows(m.y, T), brows(m.mtp_x, T));
const int64_t L = batch->draft_pass < 0 ? batch->n_draft_out : T;
if (batch->draft_pass < 0) {
RAD_ISSUE_N(c, m.mselect, L, RAD_B(m.mtp_x), praw(batch->draft_out_ids, RAD_I32, L),
brows(m.mtp_h, L));
RAD_ISSUE_N(c, m.mback, L, brows(m.mtp_h, L), brows(m.mtp_x, L));
}
l.moe.step_rows(c, L);
RAD_ISSUE_N(c, m.mnorm_op, L, brows(m.mtp_x, L), RAD_W(m.mnorm), brows(m.mtp_final, L));
RAD_ISSUE_N(c, m.mcopy, L, brows(m.mtp_final, L), brows(m.mtp_h, L));
RAD_ISSUE_N(c, m.mhead, L, brows(m.mtp_h, L), RAD_W(m.head), brows(m.logits, L));
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 * 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;
if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = 3;
out->shape_probe_ok = 1;
return RAD_OK;
}
} // namespace glm5next
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(glm5next)
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/krea2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(krea2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(krea2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/krea2.cpp)
+1389
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/lfm2_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(lfm2_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(lfm2_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/lfm2_bf16.cpp)
+488
View File
@@ -0,0 +1,488 @@
/* lfm2_bf16 -- LiquidAI's LFM2 and LFM2-VL, bf16 weights and activations, one rank.
*
* ============================== THE SHAPE ==============================
*
* A hybrid of two layer kinds, in the order the checkpoint's `layer_types` lists them (read, not
* derived: d1-3B's schedule is irregular, attention at 2, 5, 9, 13, ...):
*
* conv in_proj -> [B | C | x], y = out_proj(C * conv(B * x)), where conv is a
* depthwise causal convolution of width `conv_L_cache` with no activation
* full_attention GQA with per-head RMS norms on q and k, NeoX rotary over the whole head
*
* each followed by a SwiGLU feed-forward (w1 the gate, w3 the up, w2 the down). Every norm is a
* plain RMSNorm (`x_hat * w`, not Gemma's `1 + w`), and the final one is `embedding_norm`. At
* d1-3B: 30 layers (10 attention), hidden 2048, 32 heads over 8 at head_dim 64, ffn 10752,
* vocabulary 128000 with the lm_head tied to the embedding, conv width 3.
*
* LFM2-VL nests the same text model under `model.language_model` and adds a SigLIP2 tower and a
* projector (siglip2.h), declared when the container carries their weights and the deployment
* asked for media; the projector's rows replace the image placeholders' embeddings, which rotate
* at their token positions like any other token. A text-only LFM2 checkpoint keeps the text model
* under `model`. Which one this is comes from the config (a VL checkpoint has a `text_config`),
* not the model's name.
*
* ============================== WHAT IT DOES NOT SERVE ==============================
*
* Tensor parallelism (a 3B model needs one card). A drafter, MoE (LFM2-8B-A1B), conv bias, or a
* checkpoint without the rotary: each is refused by name.
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_mlp.h>
#include <arch/rad_block_vit.h>
#include "siglip2.h"
#include <sstream>
#include <string>
#include <vector>
namespace lfm2_bf16 {
using namespace rad::arch;
struct Layer {
bool attention = false;
MlpBF16 mlp;
rad_weight w_norm = 0, w_in = 0, w_out = 0;
/* conv */
rad_weight w_conv = 0;
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
/* attention: w_in is q, these are k, v and the two head norms */
rad_weight w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0;
rad_op op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
rad_op op_store = 0, op_attn = 0;
/* both */
rad_op op_norm = 0, op_in = 0, op_out = 0, op_add = 0;
};
struct Model {
Names nm{""};
Geom g{};
int64_t width = 0; /* conv_L_cache: the convolution's taps */
rad_kvgroup kv_attn = 0, kv_conv = 0;
rad_buf b_x = 0, b_h = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0;
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate_up = 0, b_ffn = 0;
rad_buf b_hout = 0, b_logits = 0;
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
std::vector<Layer> layers;
/* LFM2-VL's images: the tower and the scatter of its rows over the embeddings. */
bool media = false;
Siglip2 vit{};
MediaRows mrows{};
};
static Model g_model[MAX_RANKS];
/* A text_config key first, then the top level: a VL checkpoint nests the text model's settings
* and a text checkpoint does not. */
static const char* text_key(const RadModelMeta* m, const char* key) {
const std::string nested = std::string("text_config.") + key;
const char* v = rad_meta_gets(m, nested.c_str(), nullptr);
return v ? v : rad_meta_gets(m, key, nullptr);
}
static int64_t text_int(const RadModelMeta* m, const char* key, int64_t dflt) {
const char* v = text_key(m, key);
return v ? std::strtoll(v, nullptr, 10) : dflt;
}
static bool text_bool(const RadModelMeta* m, const char* key, bool dflt) {
const char* v = text_key(m, key);
if (!v) return dflt;
return std::strcmp(v, "true") == 0 || std::strcmp(v, "1") == 0;
}
/* `layer_types`, one word per layer, space-separated in the container. */
static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Layer>* out) {
const char* s = text_key(m, "layer_types");
if (!s || !*s) {
fprintf(stderr, "radiance: lfm2: the container has no layer_types; this family's schedule "
"is irregular and is not derived\n");
return RAD_E_FORMAT;
}
std::istringstream in(s);
std::string kind;
while (in >> kind) {
if (kind != "conv" && kind != "full_attention") {
fprintf(stderr, "radiance: lfm2: layer_types[%zu] is '%s'; this plugin knows 'conv' "
"and 'full_attention'\n", out->size(), kind.c_str());
return RAD_E_UNSUPPORTED;
}
Layer l;
l.attention = kind == "full_attention";
out->push_back(l);
}
if ((int64_t)out->size() != n_layer) {
fprintf(stderr, "radiance: lfm2: layer_types names %zu layers and the model has %lld\n",
out->size(), (long long)n_layer);
return RAD_E_FORMAT;
}
return RAD_OK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: lfm2_bf16 serves one rank; run it with --tp 1\n");
return RAD_E_UNSUPPORTED;
}
if (meta->n_expert > 0 || text_bool(meta, "conv_bias", false) ||
!text_bool(meta, "block_use_swiglu", true) || !text_bool(meta, "use_pos_enc", true)) {
fprintf(stderr, "radiance: lfm2_bf16 serves the dense SwiGLU model with rotary "
"attention and bias-free convolutions; this checkpoint is not that\n");
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
Names& nm = m.nm;
/* The FFN width as stated, unless the config asks for LFM2's sizing rule (1.2B and smaller
* releases): two thirds of it, times the multiplier, rounded up to `multiple_of`. */
RadModelMeta dims = *meta;
if (text_bool(meta, "block_auto_adjust_ff_dim", false)) {
int64_t ff = 2 * dims.n_ff / 3;
if (const char* mult = text_key(meta, "block_ffn_dim_multiplier")) {
const int64_t of = text_int(meta, "block_multiple_of", 256);
const double f = std::strtod(mult, nullptr);
if (!(f > 0.0) || of <= 0) return RAD_E_FORMAT;
ff = (int64_t)(f * (double)ff);
ff = of * ((ff + of - 1) / of);
}
dims.n_ff = ff;
}
RAD_ARCH_TRY(geom_from(m.g, &dims, ctx, "bf16", RAD_BF16));
Geom& g = m.g;
RAD_ARCH_TRY(yarn_from(g, meta, "", g.head_dim));
RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &m.layers));
m.width = text_int(meta, "conv_L_cache", 0);
if (m.width < 2 || m.width > 8) {
fprintf(stderr, "radiance: lfm2: conv_L_cache %lld is outside the 2..8 the convolution "
"kernels serve\n", (long long)m.width);
return RAD_E_UNSUPPORTED;
}
const char* pre = rad_meta_gets(meta, "text_config.num_hidden_layers", nullptr)
? "model.language_model" : "model";
/* ---- the two state groups: paged KV for the attention layers, and a rolling window of the
* convolution's last width-1 inputs (plus the speculative slack the manager adds) for the
* conv layers. The conv group's channels are n_head_kv * head_dim: one "head" of n_embd. */
RadKVGroupDecl fd{};
fd.kind = RAD_KV_FULL;
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
fd.n_head_kv = g.n_head_kv;
fd.head_dim = g.head_dim;
m.kv_attn = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
g.kv_dtype = rad_dtype_name(fd.dtype);
RadKVGroupDecl cd{};
cd.kind = RAD_KV_CONV;
cd.dtype = RAD_BF16;
cd.n_head_kv = 1;
cd.head_dim = g.n_embd;
cd.conv_width = m.width;
m.kv_conv = rad_decl_kv_group(b, nm.f("kv_conv"), &cd);
if (!m.kv_attn || !m.kv_conv) return RAD_E_INVAL;
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_bcx = decl_b(b, nm.f("conv_bcx"), RAD_BF16, {g.max_tok, 3 * g.n_embd});
m.b_conv_in = decl_b(b, nm.f("conv_in"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_conv_out = decl_b(b, nm.f("conv_out"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_q = decl_b(b, nm.f("attn_q"), RAD_BF16, {g.max_tok, g.q_dim()});
m.b_k = decl_b(b, nm.f("attn_k"), RAD_BF16, {g.max_tok, g.kv_dim()});
m.b_v = decl_b(b, nm.f("attn_v"), RAD_BF16, {g.max_tok, g.kv_dim()});
m.b_attn = decl_b(b, nm.f("attn_out"), RAD_BF16, {g.max_tok, g.q_dim()});
m.b_gate_up = decl_b(b, nm.f("gate_up"), RAD_BF16, {g.max_tok, 2 * g.n_ff});
m.b_ffn = decl_b(b, nm.f("ffn"), RAD_BF16, {g.max_tok, g.n_ff});
m.b_hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
/* ---- the vocabulary edges. The lm_head is tied but declared as its own weight: the
* embedding may live in host memory (--embedding-placement) and the head on the card, and a
* kernel may want a head layout the lookup does not read. */
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.embedding_norm.weight", pre)));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("%s.embed_tokens.weight", pre)));
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.w_lm_head = decl_w(b, nm.f("output.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
m.op_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_WEIGHTS(m.w_tok)),
{}, {m.b_x});
/* The encoder's rows overwrite the lookup; with one rank there is no reduction after it. */
m.media = Siglip2::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
MlpBF16::Wire mw{};
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
auto gemm = [&](int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) {
return rw(b, 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(w)),
{in}, {out});
};
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out) {
return rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w)),
{in}, {out});
};
auto layer_w = [&](const char* name, int l, std::initializer_list<int64_t> shape,
uint32_t dtype) {
return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
};
for (int l = 0; l < (int)m.layers.size(); ++l) {
Layer& L = m.layers[(size_t)l];
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),
nm.ckpt("%s.layers.%d.operator_norm.weight", pre, l)));
L.w_norm = layer_w("blk.%d.attn_norm.weight", l, {g.n_embd}, RAD_F32);
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
if (L.attention) {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_attn));
const char* a = "%s.layers.%d.self_attn.%s";
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), nm.ckpt(a, pre, l, "q_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), nm.ckpt(a, pre, l, "k_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), nm.ckpt(a, pre, l, "v_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l),
nm.ckpt(a, pre, l, "q_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l),
nm.ckpt(a, pre, l, "k_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l),
nm.ckpt(a, pre, l, "out_proj.weight")));
L.w_in = layer_w("blk.%d.attn_q.weight", l, {g.q_dim(), g.n_embd}, RAD_BF16);
L.w_k = layer_w("blk.%d.attn_k.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
L.w_v = layer_w("blk.%d.attn_v.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
L.w_q_norm = layer_w("blk.%d.attn_q_norm.weight", l, {g.head_dim}, RAD_F32);
L.w_k_norm = layer_w("blk.%d.attn_k_norm.weight", l, {g.head_dim}, RAD_F32);
L.w_out = layer_w("blk.%d.attn_output.weight", l, {g.n_embd, g.q_dim()}, RAD_BF16);
L.op_in = gemm(g.q_dim(), g.n_embd, L.w_in, m.b_h, m.b_q);
L.op_k = gemm(g.kv_dim(), g.n_embd, L.w_k, m.b_h, m.b_k);
L.op_v = gemm(g.kv_dim(), g.n_embd, L.w_v, m.b_h, m.b_v);
/* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
* T * heads rows. */
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q);
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k);
L.op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim,
"neox"), {m.b_q}, {m.b_q});
L.op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
"neox"), {m.b_k}, {m.b_k});
/* attn_paged before kv_store: the cache's block size is read from the resolved
* attention kernel. */
L.op_attn = rw(b, RAD_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),
{m.b_q}, {m.b_attn});
L.op_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, m.kv_attn)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{m.b_k, m.b_v}, {});
L.op_out = gemm(g.n_embd, g.q_dim(), L.w_out, m.b_attn, m.b_h);
} else {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv));
const char* c = "%s.layers.%d.conv.%s";
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_in.weight", l), nm.ckpt(c, pre, l, "in_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_out.weight", l), nm.ckpt(c, pre, l, "out_proj.weight")));
L.w_in = layer_w("blk.%d.conv_in.weight", l, {3 * g.n_embd, g.n_embd}, RAD_BF16);
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
* convert, as the gated delta net's conv1d is. */
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
L.w_out = layer_w("blk.%d.conv_out.weight", l, {g.n_embd, g.n_embd}, RAD_BF16);
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
L.op_in = gemm(3 * g.n_embd, g.n_embd, L.w_in, m.b_h, m.b_bcx);
L.op_gate_in = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_bcx}, {m.b_conv_in});
L.op_conv = rw(b, RAD_OP(b, "causal_conv1d",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(L.w_conv)),
{m.b_conv_in}, {m.b_conv_out});
L.op_gate_out = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_bcx, m.b_conv_out}, {m.b_conv_out});
L.op_out = gemm(g.n_embd, g.n_embd, L.w_out, m.b_conv_out, m.b_h);
}
L.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),
{m.b_x, m.b_h}, {m.b_x});
MlpBF16::Src ms{};
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
ms.gate = nm.ckpt("%s.layers.%d.feed_forward.w1.weight", pre, l);
ms.up = nm.ckpt("%s.layers.%d.feed_forward.w3.weight", pre, l);
ms.down = nm.ckpt("%s.layers.%d.feed_forward.w2.weight", pre, l);
RAD_ARCH_TRY(L.mlp.declare(b, nm, g, l, mw, ms));
}
/* The final norm runs on the gathered rows only: it is per token, and those are the rows the
* lm_head reads. */
m.op_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.b_x}, {m.b_hout});
m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, m.b_hout);
m.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), RAD_INT("n_embd", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.w_lm_head)),
{m.b_hout}, {m.b_logits});
/* The vision tower, last, so its activations share the arena with every buffer above. */
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
int64_t n_attn = 0;
for (const Layer& L : m.layers) n_attn += L.attention ? 1 : 0;
rad_note(b, "lfm2: %lld layers, %lld attention + %lld short convolution of width %lld; "
"%lld heads over %lld at head_dim %lld, ffn %lld, vocab %lld",
(long long)g.n_layer, (long long)n_attn, (long long)(g.n_layer - n_attn),
(long long)m.width, (long long)g.n_head, (long long)g.n_head_kv,
(long long)g.head_dim, (long long)g.n_ff, (long long)g.n_vocab);
return RAD_OK;
}
/* The convolution is issued once per half of the step, like the PLE's and the gated delta net's:
* the decode rows [0, D) with `num_accepted`, leaving the window in the layout a partly rejected
* verify reads back from, and the prefill chunks [D, S) without it, each leaving its tail at
* offset zero. `has_init` is `ctx_lens` (a sequence with earlier tokens has a history). The
* prefill half's per-sequence arrays start at `+ D`; the token operands stay at their base, since
* the kernel reads rows at the absolute offsets in `cu`. */
static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch* batch, int l) {
const int64_t T = batch->n_tok, S = batch->n_seq;
const RadKVGroupBatch* cv = kv_batch(batch, m.kv_conv);
const int32_t* idx = cv ? cv->state_index : nullptr;
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
const int64_t P = S - D;
if (D > 0)
RAD_ISSUE_N(c, L.op_conv, DT,
brows(m.b_conv_in, DT), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
praw(batch->cu_seqlens, RAD_I32, D + 1), praw(idx, RAD_I32, D),
praw(batch->ctx_lens, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
brows(m.b_conv_out, DT));
if (P > 0)
RAD_ISSUE_N(c, L.op_conv, T,
brows(m.b_conv_in, T), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
praw(batch->cu_seqlens + D, RAD_I32, P + 1),
praw(idx ? idx + D : nullptr, RAD_I32, P),
praw(batch->ctx_lens + D, RAD_I32, P), RAD_NONE,
brows(m.b_conv_out, T));
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Geom& g = m.g;
if (batch->draft_pass || batch->spec_parent ||
(!m.media && (batch->enc || batch->n_mm_rows > 0))) {
rad_step_fail(c, "lfm2_bf16: this step asks for an encoder, a draft pass or media rows, "
"and the program declares none of them");
return;
}
/* An encoder pass runs only the vision tower (RadBatch::enc). */
if (batch->enc) {
m.vit.step(c, batch);
return;
}
const int64_t T = batch->n_tok, n = g.n_embd;
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
m.mrows.step(c, batch, m.b_x, T);
for (int l = 0; l < (int)m.layers.size(); ++l) {
const Layer& L = m.layers[(size_t)l];
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
if (L.attention) {
const RadKVGroupBatch* kv = kv_batch(batch, m.kv_attn);
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_q, T));
RAD_ISSUE(c, L.op_k, brows(m.b_h, T), RAD_W(L.w_k), brows(m.b_k, T));
RAD_ISSUE(c, L.op_v, brows(m.b_h, T), RAD_W(L.w_v), brows(m.b_v, T));
RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm),
brows(m.b_q, T));
RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm),
brows(m.b_k, T));
RAD_ISSUE(c, L.op_rope_q, brows(m.b_q, T), rope_pos1(batch, T));
RAD_ISSUE(c, L.op_rope_k, brows(m.b_k, T), rope_pos1(batch, T));
RAD_ISSUE(c, L.op_store, brows(m.b_k, T), brows(m.b_v, T),
praw(kv ? kv->slot_mapping : nullptr, RAD_I32, T), kv_cache(m.kv_attn, l));
RAD_ISSUE_N(c, L.op_attn, batch->max_q_len,
brows(m.b_q, T), kv_cache(m.kv_attn, l),
praw2(kv ? kv->block_table : nullptr, RAD_I32, batch->n_seq,
kv ? kv->block_table_pitch : 0),
praw(kv ? kv->seqused : nullptr, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(m.b_attn, T));
RAD_ISSUE(c, L.op_out, brows(m.b_attn, T), RAD_W(L.w_out), brows(m.b_h, T));
} else {
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_bcx, T));
RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T),
brows(m.b_conv_in, T));
conv_step(m, L, c, batch, l);
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
brows(m.b_conv_out, T));
RAD_ISSUE(c, L.op_out, brows(m.b_conv_out, T), RAD_W(L.w_out), brows(m.b_h, T));
}
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
L.mlp.step(c, batch);
}
/* The lm_head runs only on the rows the sampler asked for; a prefill chunk that finishes no
* sequence skips it. */
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_x, T),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_out_norm), brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
}
}
} /* namespace lfm2_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.1.0",
"LiquidAI LFM2 / LFM2-VL, bf16: short gated convolutions and GQA attention in the "
"checkpoint's own schedule, one rank; LFM2-VL's SigLIP2 tower for images")
#endif
+325
View File
@@ -0,0 +1,325 @@
/* siglip2.h -- LFM2-VL's image encoder: the SigLIP2 NaFlex tower and the projector after it.
*
* Per encoder pass (RadBatch::enc):
*
* x = patches @ Wp^T + bp the patch embedding, a linear layer over a patch
* row (y, x, channel)
* x += pos_table resampled to each segment's grid torch's antialiased half-pixel bilinear
* (grid_embed_aa), rounded before the add
* depth times:
* x += out(attn(qkv(LN1(x)))) full attention within a segment (one tile or the
* thumbnail), no rotary
* x += fc2(gelu_tanh(fc1(LN2(x))))
* y = post_LN(x)
* out = l2(gelu(l1([LN](y viewed [P/merge^2, merge^2 * width])))) the projector
*
* i.e. transformers' Siglip2VisionModel (no pooling head) then Lfm2VlMultiModalProjector. The
* projector's pixel unshuffle is a view: the processor stores each segment's patches in
* merge-block order (core/mm/processor.cpp, image_lfm2), so a block's merge^2 patches are
* consecutive rows, dy then dx, the order the unshuffle concatenates them. The tower is
* order-independent: attention within a segment is permutation-equivariant, every other layer is
* per patch, and the position table is resampled at each patch's own (row, column).
*
* q, k and v are one fused weight, concatenated at convert (map_concat), so a layer is one QKV
* GEMM; the attention reads the three as column slices.
*
* Replicated, per-request weights and pass-sized activations, as in arch/common/rad_block_vit.h's
* tower.
*/
#ifndef LFM2_SIGLIP2_H
#define LFM2_SIGLIP2_H
#include <arch/rad_arch.h>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace lfm2_bf16 {
using namespace rad::arch;
struct Siglip2 {
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, merge = 0, side = 0;
int64_t head_dim = 0, patch_dim = 0, proj_hidden = 0, n_embd = 0, P = 0;
float eps = 1e-6f;
bool proj_norm = false, on = false;
struct Layer {
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0;
rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
rad_weight up_w = 0, up_b = 0, down_w = 0, down_b = 0;
rad_op ln1 = 0, qkv = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
};
std::vector<Layer> L;
rad_weight w_patch = 0, b_patch = 0, w_pos = 0, pn_w = 0, pn_b = 0;
rad_weight mn_w = 0, mn_b = 0, m1_w = 0, m1_b = 0, m2_w = 0, m2_b = 0;
rad_op op_patch = 0, op_pos = 0, op_post = 0, op_mln = 0, op_m1 = 0, op_m2 = 0;
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_mh = 0, b_mn = 0, b_mf = 0;
rad_buf b_out = 0;
/* A tower to declare: the container is an LFM2-VL one, whose vision_config is SigLIP2's. */
static bool present(const RadModelMeta* m) {
return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "siglip2_vision_model") &&
rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
}
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 Siglip2::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.num_hidden_layers", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
eps = (float)rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-6);
const int64_t chans = rad_meta_geti(m, "vision_config.num_channels", 3);
const int64_t npos = rad_meta_geti(m, "vision_config.num_patches", 0);
merge = rad_meta_geti(m, "downsample_factor", 0);
proj_hidden = rad_meta_geti(m, "projector_hidden_size", 0);
n_embd = model_embd;
side = (int64_t)std::llround(std::sqrt((double)npos));
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || merge <= 0 ||
proj_hidden <= 0 || side <= 0 || side * side != npos || width % heads || chans != 3) {
fprintf(stderr, "radiance: lfm2: the container's SigLIP2 vision_config is incomplete or "
"inconsistent (layers %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
"positions %lld, channels %lld; downsample_factor %lld, projector %lld)\n",
(long long)depth, (long long)width, (long long)heads, (long long)ff,
(long long)patch, (long long)npos, (long long)chans, (long long)merge,
(long long)proj_hidden);
return RAD_E_INVAL;
}
/* The pooling head is SigLIP2's contrastive readout; LFM2-VL reads the patch rows, so a
* checkpoint that ships a head is refused by name rather than loading unused weights. */
if (rad_meta_geti(m, "vision_config.vision_use_head", 0) != 0 ||
!std::strcmp(rad_meta_gets(m, "vision_config.vision_use_head", ""), "true")) {
fprintf(stderr, "radiance: lfm2: this SigLIP2 tower has a pooling head, which LFM2-VL does "
"not read and this plugin does not serve\n");
return RAD_E_UNSUPPORTED;
}
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu_pytorch_tanh");
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
if (std::strcmp(act, "gelu_pytorch_tanh") || std::strcmp(pact, "gelu")) {
fprintf(stderr, "radiance: lfm2: the tower's activation '%s' and the projector's '%s' are "
"not gelu_pytorch_tanh and gelu, which is what this plugin serves\n",
act, pact);
return RAD_E_UNSUPPORTED;
}
const char* pb = rad_meta_gets(m, "projector_bias", "true");
if (std::strcmp(pb, "true") && std::strcmp(pb, "1")) {
fprintf(stderr, "radiance: lfm2: a projector without biases is not served\n");
return RAD_E_UNSUPPORTED;
}
proj_norm = !std::strcmp(rad_meta_gets(m, "projector_use_layernorm", "true"), "true") ||
!std::strcmp(rad_meta_gets(m, "projector_use_layernorm", "true"), "1");
head_dim = width / heads;
patch_dim = chans * patch * patch;
const int64_t mm = merge * merge, mw = mm * width;
P = ctx->max_enc_patches;
/* The longest segment attention sees: a tile or the largest thumbnail, which the processor
* keeps within max_num_patches. It selects the attention kernel's block height, so a sizing
* declare uses the real value too. */
const int64_t seg = rad_meta_geti(m, "processor.image_processor.max_num_patches",
rad_meta_geti(m, "max_num_patches", P));
const int64_t max_seg = std::min<int64_t>(P, seg);
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;
auto bw = [&](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);
};
const char* tw = "model.vision_tower.vision_model.";
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("%sembeddings.patch_embedding.weight", tw),
{ width, patch_dim }, grp_model());
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("%sembeddings.patch_embedding.bias", tw),
{ width }, grp_model());
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%sembeddings.position_embedding.weight", tw),
{ npos, 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;
const char* e = "%sencoder.layers.%d.%s";
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt(e, tw, li, "layer_norm1.weight"), { width }, g);
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt(e, tw, li, "layer_norm1.bias"), { width }, g);
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt(e, tw, li, "layer_norm2.weight"), { width }, g);
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt(e, tw, li, "layer_norm2.bias"), { width }, g);
/* q, k, v fused at convert: one GEMM per layer. */
const char* qw = nm.f("v.blk.%d.qkv.weight", li);
const char* qb = nm.f("v.blk.%d.qkv.bias", li);
if (map_concat(b, qw, { nm.ckpt(e, tw, li, "self_attn.q_proj.weight"),
nm.ckpt(e, tw, li, "self_attn.k_proj.weight"),
nm.ckpt(e, tw, li, "self_attn.v_proj.weight") }) < 0 ||
map_concat(b, qb, { nm.ckpt(e, tw, li, "self_attn.q_proj.bias"),
nm.ckpt(e, tw, li, "self_attn.k_proj.bias"),
nm.ckpt(e, tw, li, "self_attn.v_proj.bias") }) < 0)
return RAD_E_INVAL;
l.qkv_w = decl_w(b, qw, RAD_BF16, { 3 * width, width }, ACC, RAD_SHARD_NONE, g);
l.qkv_b = decl_w(b, qb, RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g);
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt(e, tw, li, "self_attn.out_proj.weight"), { width, width }, g);
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt(e, tw, li, "self_attn.out_proj.bias"), { width }, g);
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt(e, tw, li, "mlp.fc1.weight"), { ff, width }, g);
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt(e, tw, li, "mlp.fc1.bias"), { ff }, g);
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt(e, tw, li, "mlp.fc2.weight"), { width, ff }, g);
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt(e, tw, li, "mlp.fc2.bias"), { width }, g);
if (!l.n1w || !l.n1b || !l.n2w || !l.n2b || !l.qkv_w || !l.qkv_b || !l.out_w ||
!l.out_b || !l.up_w || !l.up_b || !l.down_w || !l.down_b)
return RAD_E_INVAL;
}
pn_w = bw(nm.f("v.post_norm.weight"), nm.ckpt("%spost_layernorm.weight", tw), { width }, grp_model());
pn_b = bw(nm.f("v.post_norm.bias"), nm.ckpt("%spost_layernorm.bias", tw), { width }, grp_model());
const char* pj = "model.multi_modal_projector.";
if (proj_norm) {
mn_w = bw(nm.f("v.proj.norm.weight"), nm.ckpt("%slayer_norm.weight", pj), { mw }, grp_model());
mn_b = bw(nm.f("v.proj.norm.bias"), nm.ckpt("%slayer_norm.bias", pj), { mw }, grp_model());
if (!mn_w || !mn_b) return RAD_E_INVAL;
}
m1_w = bw(nm.f("v.proj.fc1.weight"), nm.ckpt("%slinear_1.weight", pj), { proj_hidden, mw }, grp_model());
m1_b = bw(nm.f("v.proj.fc1.bias"), nm.ckpt("%slinear_1.bias", pj), { proj_hidden }, grp_model());
m2_w = bw(nm.f("v.proj.fc2.weight"), nm.ckpt("%slinear_2.weight", pj), { n_embd, proj_hidden }, grp_model());
m2_b = bw(nm.f("v.proj.fc2.bias"), nm.ckpt("%slinear_2.bias", pj), { n_embd }, grp_model());
if (!w_patch || !b_patch || !w_pos || !pn_w || !pn_b || !m1_w || !m1_b || !m2_w || !m2_b)
return RAD_E_INVAL;
/* ---- activations. `mh` is the post-norm's output declared at the merged width: the norm
* writes P rows of `width` and the projector reads the same bytes as P/mm rows of
* mm * width. */
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_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mw });
if (proj_norm) b_mn = decl_b(b, nm.f("v.mn"), RAD_BF16, { R, mw });
b_mf = decl_b(b, nm.f("v.mf"), RAD_BF16, { R, proj_hidden });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_qkv || !b_att || !b_ff || !b_mh || (proj_norm && !b_mn) || !b_mf ||
!b_out)
return RAD_E_INVAL;
auto gemm = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
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", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
RAD_WEIGHTS(w, bias));
};
auto lnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_weight bias) -> rad_op {
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));
};
op_patch = rw(b, gemm(P, width, patch_dim, "none", w_patch, b_patch), {}, { b_x });
op_pos = rw(b, RAD_OP(b, "grid_embed_aa",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("side", side), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_pos)),
{ b_x }, { b_x });
for (Layer& l : L) {
l.ln1 = rw(b, lnorm(P, width, l.n1w, l.n1b), { b_x }, { b_h });
l.qkv = rw(b, gemm(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.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.proj = rw(b, gemm(P, width, width, "none", l.out_w, l.out_b), { b_att, b_x }, { b_x });
l.ln2 = rw(b, lnorm(P, width, l.n2w, l.n2b), { b_x }, { b_h });
l.up = rw(b, gemm(P, ff, width, "gelu_tanh", l.up_w, l.up_b), { b_h }, { b_ff });
l.down = rw(b, gemm(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_x }, { b_x });
}
op_post = rw(b, lnorm(P, width, pn_w, pn_b), { b_x }, { b_mh });
if (proj_norm) op_mln = rw(b, lnorm(R, mw, mn_w, mn_b), { b_mh }, { b_mn });
op_m1 = rw(b, gemm(R, proj_hidden, mw, "gelu", m1_w, m1_b), { proj_norm ? b_mn : b_mh }, { b_mf });
op_m2 = rw(b, gemm(R, n_embd, proj_hidden, "none", m2_w, m2_b), { b_mf }, { 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, "SigLIP2 tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"%lld x %lld position table; projector %lld -> %lld -> %lld%s; %lld patches a "
"pass -> %lld rows",
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
(long long)ff, (long long)patch, (long long)side, (long long)side,
(long long)mw, (long long)proj_hidden, (long long)n_embd,
proj_norm ? " behind a layer norm" : "", (long long)P, (long long)R);
}
on = true;
return RAD_OK;
}
inline void Siglip2::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 || batch->enc != RAD_MM_IMAGE || Pn <= 0 || Pn > P || Pn % mm || S <= 0) {
rad_step_fail(c, "lfm2: an encoder pass this program's SigLIP2 tower cannot serve: no "
"tower, not images, more patches than it was declared for, or not whole "
"merged rows");
return;
}
/* The patches, their coordinates (a dense [4, P] of row, column, segment height and width,
* read by the position resample) and the segment boundaries. */
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, 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));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
for (const Layer& l : L) {
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));
RAD_ISSUE_N(c, l.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.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.ln2, Pn, brows(b_x, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
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));
}
/* The post-norm writes Pn rows of `width` into the merged-width buffer, which the projector
* reads as Pn/mm rows: the pixel unshuffle. */
RAD_ISSUE_N(c, op_post, Pn, brows(b_x, Pn), RAD_W(pn_w), RAD_W(pn_b), brows(b_mh, Rn));
if (proj_norm)
RAD_ISSUE_N(c, op_mln, Rn, brows(b_mh, Rn), RAD_W(mn_w), RAD_W(mn_b), brows(b_mn, Rn));
RAD_ISSUE_N(c, op_m1, Rn, brows(proj_norm ? b_mn : b_mh, Rn), RAD_W(m1_w), RAD_W(m1_b),
RAD_NONE, brows(b_mf, Rn));
RAD_ISSUE_N(c, op_m2, Rn, brows(b_mf, Rn), RAD_W(m2_w), RAD_W(m2_b), RAD_NONE,
brows(b_out, Rn));
}
} /* namespace lfm2_bf16 */
#endif /* LFM2_SIGLIP2_H */
+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/llama_dense_fp8 -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/llama_dense_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(llama_dense_fp8 LANGUAGES CXX)
+8 -11
View File
@@ -1,16 +1,13 @@
/* llama_dense_fp8 -- arch/llama_fp8 over a checkpoint that was never quantised.
/* llama_dense_fp8 -- arch/llama_fp8 over a bf16 checkpoint quantised by rad-convert.
*
* MiniCPM5-2B is the model this exists for: OpenBMB publishes it in bf16 and nothing else, so
* "MiniCPM5-2B FP8A8" is a statement about what this engine runs rather than about what the
* checkpoint holds. rad-convert does the quantising, by the recipe
* data/recipes/minicpm5-2b-dspark.recipe -- one amax per 128x128 block, scale = amax/448 rounded to
* bf16 -- so the container it writes holds what a checkpoint that shipped fp8 would, and every
* kernel, every layout and every placement decision downstream is the same.
* For MiniCPM5-2B, which OpenBMB publishes only in bf16. The recipe
* data/recipes/minicpm5-2b-dspark.recipe takes one amax per 128x128 block with scale = amax/448
* rounded to bf16, so the container matches what a checkpoint shipped in fp8 would hold and every
* kernel, layout and placement decision downstream is the same.
*
* A SEPARATE .so BECAUSE THE SELECTION KEY IS THE PAIR (spec §2.4): one plugin claims one
* (architecture, quantisation), and the descriptor a dense checkpoint carries is the empty one.
* Everything else is arch/llama_fp8/llama_fp8.cpp; `#if LLAMA_DENSE_SRC` there changes only the
* descriptor check and what the graph dump says.
* A separate .so because the selection key is the (architecture, quantisation) pair (spec §2.4),
* and a dense checkpoint's descriptor is empty. Everything else is arch/llama_fp8/llama_fp8.cpp;
* `#if LLAMA_DENSE_SRC` there changes only the descriptor check and the graph dump text.
*/
#define LLAMA_DENSE_SRC 1
#define LLAMA_NS llama_dense_fp8
+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/llama_fp8 -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/llama_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(llama_fp8 LANGUAGES CXX)
+137 -287
View File
@@ -2,43 +2,34 @@
*
* ============================== WHAT IT SERVES ==============================
*
* `model_type: llama` with `LlamaForCausalLM`, which is the most widely shared decoder shape there
* is and is what MiniCPM5-2B reports: 42 layers, hidden 2048, 16 query heads over 2 KV heads at
* head_dim 128, SwiGLU at 6144, RMS norms, full rotary at theta 5e6, an untied 130560-row head,
* and no biases anywhere. Every layer is full attention; there is no gated delta net, no layer
* schedule, no output gate and no per-head q/k norm, which is precisely what separates this file
* from arch/qwen35_fp8.
* `model_type: llama` with `LlamaForCausalLM`, as MiniCPM5-2B reports: 42 layers, hidden 2048, 16
* query heads over 2 KV heads at head_dim 128, SwiGLU at 6144, RMS norms, full rotary at theta
* 5e6, an untied 130560-row head, and no biases. Every layer is full attention; unlike
* arch/qwen35_fp8 there is no gated delta net, layer schedule, output gate or per-head q/k norm.
*
* ============================== TWO CHECKPOINT FORMATS, ONE GRAPH ==============================
*
* The selection key is the PAIR (architecture, quantisation) -- spec §2.4 -- and one .so claims one
* The selection key is the (architecture, quantisation) pair (spec §2.4) and one .so claims one
* pair, so this source builds twice:
*
* llama_fp8 quant "fp8_e4m3" the checkpoint already holds E4M3 codes and a
* `weight_scale_inv` plane, which are the two planes of
* each linear as the engine reads them.
* llama_dense_fp8 quant "" the checkpoint is one dense bf16 tensor per linear, and
* a RECIPE quantises each to those two planes at convert
* time (data/recipes/minicpm5-2b-dspark.recipe). The
* container then holds what the first one's checkpoint
* does.
* llama_fp8 quant "fp8_e4m3" the checkpoint holds E4M3 codes and a `weight_scale_inv`
* plane per linear, as the engine reads them.
* llama_dense_fp8 quant "" the checkpoint is dense bf16, and a recipe quantises each
* linear to those two planes at convert time
* (data/recipes/minicpm5-2b-dspark.recipe: amax per 128x128
* block, scale = amax/448 rounded to bf16).
*
* THE SECOND IS THE ONE MiniCPM5-2B NEEDS, because OpenBMB publishes it in bf16 and nothing else.
* "MiniCPM5-2B FP8A8" is therefore a statement about what this engine RUNS and not about what the
* checkpoint holds, and the conversion is where the two meet: one pass per 128x128 block, amax,
* scale = amax/448 rounded to bf16, divide and encode. Both builds declare the same weights and
* the same ops, so nothing downstream -- the kernels, the container, the placement plan -- can
* tell which one ran; the descriptor is the only reason there are two.
* MiniCPM5-2B needs the second, since it is published only in bf16. Both builds declare the same
* weights and ops, so nothing downstream can tell which one ran.
*
* ============================== WHAT IS AND IS NOT FP8 ==============================
*
* E4M3 + a bf16 [N/128][K/128] plane self_attn.{q,k,v,o}_proj, mlp.{gate,up,down}_proj
* BF16, no plane every norm and the embedding
*
* The lm_head is declared at whatever the model holds it as: bf16 as every llama checkpoint ships
* it, or block fp8 where a recipe quantised it -- the widest GEMM in the model at half the bytes.
* The logits kernel that reads that encoding is the one selected. Both vocabulary edges are
* ROW-SHARDED with the vocabulary.
* The lm_head is declared at whatever the model holds: bf16 as llama checkpoints ship it, or block
* fp8 where a recipe quantised it (the widest GEMM at half the bytes), and the logits kernel for
* that encoding is selected. Both vocabulary edges are row-sharded with the vocabulary.
*/
#ifndef LLAMA_DENSE_SRC
#define LLAMA_DENSE_SRC 0
@@ -84,22 +75,21 @@ struct Model {
rad_buf b_gate_up = 0;
ActFP8 a_ffn{};
/* THE AUXILIARY HIDDEN-STATE TAPS, declared only when the container carries a drafter that
* asks for them. A DSpark or DFlash drafter does not read the trunk's FINAL hidden state --
* it reads the RESIDUAL STREAM at several intermediate layers and projects the concatenation
* down, so its `fc` is [n_embd, n_taps * n_embd] and the input has to be one contiguous row.
* The trunk keeps one residual buffer that every layer overwrites, so the rows are copied out
* as they pass, into the column slice that tap owns. This is arch/qwen35_fp8's mechanism and
* the comments there carry the reasoning; what is here is the same thing over this graph. */
/* Auxiliary hidden-state taps, declared only when the container carries a drafter that wants
* them. A DSpark or DFlash drafter reads the residual stream at several intermediate layers
* and projects the concatenation down (`fc` is [n_embd, n_taps * n_embd]), so the input must
* be one contiguous row. The trunk's one residual buffer is overwritten by every layer, so
* each tap's rows are copied into its column slice as they pass. Same mechanism as
* arch/qwen35_fp8. */
enum { MAX_TAPS = 8 };
int n_taps = 0;
int tap_layer[MAX_TAPS] = {};
rad_buf b_dfsrc = 0; /* [max_tok, n_taps * n_embd] */
rad_op op_tap = 0;
/* THE DRAFTER, declared only when the container carries one and this serve intends to
* speculate. Its layers get absolute layer indices AFTER the trunk's, so the KV group's
* layer_slot lookup finds them and its weights land in layer groups of their own. */
/* The drafter, declared only when the container carries one and this serve speculates. Its
* layers get absolute indices after the trunk's, so the KV group's layer_slot lookup finds
* them and its weights land in layer groups of their own. */
Dspark ds{};
Dspark::Wire dsw{};
rad_kvgroup kv_draft = 0;
@@ -111,44 +101,24 @@ struct Model {
std::vector<Layer> layers;
};
/* "1 10 20 30 39" -> the layers whose output a drafter wants. rad-convert flattens a config.json
* array into a space-separated string (tools/rad_convert.cpp, flatten_json), so this is the shape
* every list-valued key arrives in. Out-of-range entries are DROPPED rather than clamped: a
* drafter naming a layer this model does not have is paired with the wrong target, and silently
* reading layer 41 instead of 49 would turn that into a quality mystery. */
static int parse_tap_layers(const char* s, int64_t n_layer, int* out, int max) {
if (!s) return 0;
int n = 0;
for (const char* p = s; *p && n < max;) {
while (*p == ' ' || *p == ',') ++p;
if (!*p) break;
char* e = nullptr;
const long v = std::strtol(p, &e, 10);
if (e == p) break;
p = e;
if (v >= 0 && v < n_layer) out[n++] = (int)v;
}
return n;
}
static Model g_model[MAX_RANKS];
/* THE CONTAINER'S QUANTISATION DESCRIPTOR IS THE SELECTION KEY AND IT IS CHECKED ANYWAY, because
* `--arch` can override the architecture id at convert time and a plugin that is handed the wrong
* checkpoint should say which half disagrees rather than fail at a name map. */
/* The quantisation descriptor is the selection key but is checked anyway: `--arch` can override
* the architecture id at convert time, and a plugin handed the wrong checkpoint should say which
* half disagrees rather than fail at a name map. */
static int check_format(const RadModelMeta* meta) {
const char* q = meta->quant ? meta->quant : "";
#if LLAMA_DENSE_SRC
if (*q) {
fprintf(stderr, "radiance: llama_dense_fp8 serves an UNQUANTISED checkpoint and this one "
"declares '%s'. The fp8 sibling (llama_fp8) reads that one.\n", q);
fprintf(stderr, "radiance: llama_dense_fp8 serves an unquantised checkpoint and this one "
"declares '%s'; llama_fp8 serves it\n", q);
return RAD_E_UNSUPPORTED;
}
#else
if (std::strncmp(q, "fp8", 3) != 0) {
fprintf(stderr, "radiance: llama_fp8 serves a block-scaled fp8 checkpoint and this one "
"declares '%s'. A dense bf16 one is served by llama_dense_fp8, after a "
"recipe has quantised it.\n", *q ? q : "(unquantised)");
"declares '%s'; llama_dense_fp8 serves a dense bf16 one\n",
*q ? q : "(unquantised)");
return RAD_E_UNSUPPORTED;
}
#endif
@@ -160,62 +130,23 @@ static int check_format(const RadModelMeta* meta) {
return RAD_OK;
}
/* THE DSPARK DRAFTER. The Geom is the TRUNK'S with the drafter's own geometry substituted in: the
* vocabulary, the deployment bounds, the rank and the wire stay the trunk's (they are properties
* of this serve, not of the checkpoint) and everything about the layers comes from `draft.*`.
/* The DSpark drafter. Its Geom is the trunk's with the drafter's layer geometry from `draft.*`
* substituted; the vocabulary, deployment bounds, rank and wire stay the trunk's.
*
* Nothing here is defaulted quietly. A container whose `draft.` config does not describe this
* drafter, or describes one this file does not implement, is refused BY NAME: a drafter that
* silently ignored a scale factor or a head type would simply accept less, which reads as a
* quality mystery and not as a missing feature (spec §17).
* Nothing is defaulted quietly: a `draft.` config that does not describe a drafter this file
* implements is refused by name, because a silently ignored scale factor or head type would only
* lower acceptance (spec §17).
*
* THE ONE THING THAT IS DELIBERATELY IGNORED is the confidence head, and rad_block_dspark.h argues
* it: `AcceptRatePredictor` exists so a serving loop can shorten the block adaptively, this
* engine's depth is fixed at declare time, and the head changes nothing the drafter proposes. */
* The confidence head (`AcceptRatePredictor`) is deliberately ignored: it drives adaptive block
* length, this engine's depth is fixed at declare, and it changes nothing the drafter proposes
* (rad_block_dspark.h). */
static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
Model& m, int base_layer) {
Names& nm = m.nm;
Geom dg = m.g; /* n_embd, the vocabulary, the deployment bounds, the rank, the wire */
dg.n_layer = rad_meta_geti(meta, "draft.num_hidden_layers", 0);
dg.head_dim = rad_meta_geti(meta, "draft.head_dim", 0);
dg.n_head_all = rad_meta_geti(meta, "draft.num_attention_heads", 0);
dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0);
dg.n_ff_all = rad_meta_geti(meta, "draft.intermediate_size", 0);
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
rad_meta_getf(meta, "draft.rope_theta", 0.0));
/* PLAIN RMS NORM: the reference norms with Qwen3RMSNorm and the config says `model_type:
* qwen3`. It happens to agree with this MiniCPM5 target, and it is asked of the DRAFTER's
* config anyway -- two conventions in one process is exactly why this is a second Geom. */
dg.wadd = 0.0f;
dg.wadd_qk = 0.0f;
if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 ||
dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) {
fprintf(stderr, "radiance: the container's `draft.` config does not describe a DSpark "
"drafter: layers %lld, heads %lld / kv %lld, head_dim %lld, ffn %lld, "
"rms_eps %g, rope_theta %g\n",
(long long)dg.n_layer, (long long)dg.n_head_all, (long long)dg.n_head_kv_all,
(long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
int s;
if ((s = divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)) < 0) return s;
if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s;
if ((s = divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff)) < 0) return s;
/* THE DRAFTER BORROWS THE TARGET'S EMBEDDING TABLE AND lm_head -- it ships neither -- so a
* vocabulary that disagrees is not a drafter for this target at all. */
const long long dvocab = rad_meta_geti(meta, "draft.vocab_size", dg.n_vocab_all);
if (dvocab != dg.n_vocab_all) {
fprintf(stderr, "radiance: the DSpark drafter claims a %lld-token vocabulary and the "
"target has %lld. The drafter ships no embedding table and no lm_head; it "
"reads the target's, so the two have to be the same vocabulary.\n",
dvocab, (long long)dg.n_vocab_all);
return RAD_E_UNSUPPORTED;
}
Geom dg{};
/* Plain RMS norm: the reference uses Qwen3RMSNorm (`model_type: qwen3`). It matches this
* MiniCPM5 target, but it is the drafter's convention, set on the drafter's own Geom. */
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "DSpark"));
Dspark::Config dc{};
dc.n_taps = m.n_taps;
@@ -223,11 +154,10 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
dc.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0;
if (rad_meta_geti(meta, "draft.use_sliding_window", 0))
dc.window = rad_meta_geti(meta, "draft.sliding_window", 0);
/* HOW MANY CANDIDATES THE MARKOV WALK RE-RANKS. The reference biases all 130560 logits and
* takes the argmax; this re-ranks the base head's top K, which is the only approximation in
* the head and it can cost acceptance and nothing else (rad_block_dspark.h). K is bounded by
* the selector at 32; 16 is 8 KiB of codebook a position, which is free, and it is read from
* the container so a checkpoint can ask for more. */
/* How many candidates the Markov walk re-ranks. The reference biases all 130560 logits and
* takes the argmax; this re-ranks the base head's top K, the head's only approximation, which
* can cost acceptance but not correctness (rad_block_dspark.h). The selector bounds K at 32;
* the default 16 is 8 KiB of codebook per position, and a checkpoint may ask for more. */
dc.top_k = rad_meta_geti(meta, "draft.markov_top_k", 16);
if (dc.top_k < 1 || dc.top_k > 32) {
fprintf(stderr, "radiance: draft.markov_top_k is %lld; the Markov walk scores at most 32 "
@@ -235,15 +165,14 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
return RAD_E_UNSUPPORTED;
}
/* THE BLOCK IS THE NUMBER OF NOISE ROWS AND ALSO THE NUMBER OF DRAFTS -- every row predicts
* the token after it, the anchor row included. So the engine's depth IS `block_size`, where a
* Dflash2 container's is `block_size - 1`, and that off-by-one is the whole reason
* RadDrafterDecl carries a `block` field. Getting it wrong runs, drafts, and accepts nothing.
/* 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`, where a DFlash2
* container's is `block_size - 1` (see RadDrafterDecl::block). A wrong value runs but accepts
* nothing.
*
* A BLOCK-DIFFUSION DRAFTER WAS TRAINED FOR ONE BLOCK LENGTH, so a serve that asks for another
* depth is refused here rather than run: the reference denoises exactly `block_size` masked
* positions and there is no partial block. The probe reports `draft_depth_fixed`, so the
* engine will normally have picked this already. */
* A block-diffusion drafter is trained for one block length and has no partial block, so any
* other depth is refused. The probe reports `draft_depth_fixed`, so the engine normally picks
* this already. */
const long long trained = rad_meta_geti(meta, "draft.block_size", 0);
if (trained < 2) {
fprintf(stderr, "radiance: this DSpark checkpoint declares no draft.block_size; the "
@@ -260,8 +189,8 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
}
dc.block = trained;
/* Two things this drafter's family can carry that this implementation does not apply. Each
* changes what the drafter proposes, which is why neither is ignored quietly. */
/* Two variants this implementation does not apply; each changes the proposals, so neither is
* ignored quietly. */
const char* mh = rad_meta_gets(meta, "draft.markov_head_type", "vanilla");
if (dc.rank <= 0 || !mh || std::strcmp(mh, "vanilla") != 0) {
fprintf(stderr, "radiance: this DSpark checkpoint has markov_rank %lld and "
@@ -276,26 +205,12 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
return RAD_E_UNSUPPORTED;
}
/* THE DRAFTER'S OWN KV CACHE, a group of its own. It cannot share the trunk's: five layers
* against forty-two, and -- when the checkpoint asks for one -- a WINDOW. RAD_KV_WINDOW
* recycles the blocks that fall below it; DSpark's published config sets `sliding_window:
* null`, so this is normally a full cache of five layers. Its width is the trunk's,
* --kv-cache-dtype: one flag says what every attention cache of the deployment is made of. */
RadKVGroupDecl dd{};
dd.kind = dc.window > 0 ? RAD_KV_WINDOW : RAD_KV_FULL;
dd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
dd.window = dc.window;
dd.n_head_kv = dg.n_head_kv;
dd.head_dim = dg.head_dim;
m.kv_draft = rad_decl_kv_group(b, nm.f("kv_draft"), &dd);
for (int64_t l = 0; l < dg.n_layer; ++l)
RAD_ARCH_TRY(rad_bind_layer_kv(b, base_layer + (int)l, m.kv_draft));
dg.kv_dtype = rad_dtype_name(dd.dtype);
/* DSpark's published config sets `sliding_window: null`, so this is normally a full cache. */
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, &m.kv_draft));
/* Activation buffers. The context pass is one row a COMMITTED TOKEN and runs over a whole
* prefill chunk; everything after it is one row a DRAFT POSITION, `block` of them a sequence,
* so the two halves are sized apart. None of it is large -- the drafter's cost is its
* weights, not its activations. */
/* Activations. The context pass has one row per committed token over a whole prefill chunk;
* the query pass one row per draft position, `block` per sequence; the two are sized apart.
* All are small: the drafter's cost is its weights. */
const int64_t qd = dg.n_head * dg.head_dim;
const int64_t kvd = dg.n_head_kv * dg.head_dim;
int64_t qr = dg.max_seqs * dc.block;
@@ -308,9 +223,8 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
dw.c = decl_b(b, nm.f("ds_c"), dg.act_dtype, {dg.max_tok, dg.n_embd});
dw.ck = decl_b(b, nm.f("ds_ck"), dg.act_dtype, {dg.max_tok, kvd});
dw.cv = decl_b(b, nm.f("ds_cv"), dg.act_dtype, {dg.max_tok, kvd});
/* THE FP8 TWINS OF THE CONTEXT PASS. `srcq` is the largest of them by a distance -- 20 MiB at
* a 2048-token chunk, five taps and hidden 2048, against the 40 MiB `draft_src` it shadows --
* and it buys half the bytes of the one GEMM the context pass spends its time in. */
/* FP8 copies for the context pass. `srcq` is the largest (20 MiB at a 2048-token chunk, five
* taps, hidden 2048) and halves the bytes of the context pass's dominant GEMM. */
dw.srcq = decl_b(b, nm.f("ds_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd});
dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32,
{dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)});
@@ -335,12 +249,11 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
dw.sel_h = decl_b(b, nm.f("ds_selh"), dg.act_dtype, {sr, dg.n_embd});
dw.dq = decl_b(b, nm.f("ds_dq"), RAD_I8, {sr, dg.n_embd});
dw.ds = decl_b(b, nm.f("ds_ds"), RAD_F32, {sr, 1});
/* GROUP-major, [n_embd/group][ceil(M/16)*16] -- quant_act_i8's asum plane, whose first
* dimension is the K group and not the token. */
/* Group-major, [n_embd/group][ceil(M/16)*16]: quant_act_i8's asum plane, whose first
* dimension is the K group, not the token. */
dw.dsum = decl_b(b, nm.f("ds_dsum"), RAD_F32, {dg.n_embd / 128, spad});
/* THIS RANK'S plane. `head_rows` is the block's own answer to whether the 2-bit head is
* vocab-sharded, asked here rather than re-derived, because a buffer that disagreed with the
* op declared over it is a read past its end. */
/* This rank's plane. `head_rows` is the block's own answer to whether the 2-bit head is
* vocab-sharded; asking it keeps the buffer consistent with the op declared over it. */
dw.dlog = decl_b(b, nm.f("ds_dlog"), dg.act_dtype, {sr, Dspark::head_rows(dg)});
dw.cand = decl_b(b, nm.f("dspark_cand"), RAD_I32, {sr, dc.top_k});
dw.unary = decl_b(b, nm.f("ds_unary"), RAD_F32, {sr, dc.top_k});
@@ -348,23 +261,21 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
dw.dpair = decl_b(b, nm.f("ds_dpair"), RAD_F32, {sr, dc.top_k, 2});
dw.dgath = decl_b(b, nm.f("ds_dgath"), RAD_F32, {sr, (int64_t)dg.world * dc.top_k, 2});
}
/* NAMED, because the engine reads the draft out of it by name: a block pass proposes through
* the drafter's own walk and never through the sampler's token buffer. */
/* 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("dspark_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
/* A TIED lm_head IS THE ALTERNATIVE SOURCE, and it has to be the same pair the trunk's own
* head reads or the drafter would be projecting onto a different vocabulary. */
/* The same lm_head sources as the trunk's head (embedding as the tied alternative), so both
* project onto one vocabulary. */
RAD_ARCH_TRY(m.ds.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft",
nm.ckpt("lm_head.weight"), nm.ckpt("model.embed_tokens.weight"),
dw));
m.have_ds = true;
/* WHAT THE ENGINE DRIVES. Block: a context pass that mirrors the trunk step, then ONE pass
* that fills the whole block. `block` is `depth` and not `depth + 1`, which is this drafter's
* trained convention and the field's reason for existing. `window` must be the number this
* plugin gated its OWN attention with, because the scheduler stages the block pass against
* it: two readings of "how far back can the drafter see" is a drafter attending to positions
* the scheduler did not stage. */
/* Block drafter: a context pass mirroring the trunk step, then one pass filling the whole
* block. `block` is `depth`, not `depth + 1` (this drafter's training convention). `window`
* must be the one this plugin gated its own attention with, since the scheduler stages the
* block pass against it. */
RadDrafterDecl drf{};
drf.name = "dspark";
drf.kind = RAD_DRAFT_BLOCK;
@@ -377,27 +288,22 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
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 DSpark checkpoint declares no mask_token_id, and every "
"position the block has not filled embeds it -- there is nothing to "
"run.\n");
fprintf(stderr, "radiance: this DSpark checkpoint 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, "the DSpark drafter is declared: %lld layers of its own at absolute %d..%d, "
"%lld heads / %lld kv x %lld, ffn %lld, %s attention with a %lld-token window, "
"reading the trunk at %d tap(s). ONE forward over %lld noise row(s) proposes "
"%lld tokens -- there are no rounds -- and EVERY row predicts, the anchor "
"included, so the block is `depth` rows and not `depth + 1`",
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 window, %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, dc.causal ? "causal" : "non-causal", (long long)dc.window,
m.n_taps, (long long)dc.block, (long long)dc.steps());
rad_note(b, "the rank-%lld Markov bigram head runs as the candidate walk with no hidden "
"projection: `unary + <markov_w1[prev], markov_w2[cand]>` over the draft head's "
"top %lld, decoded greedily. The confidence head is present in the checkpoint and "
"deliberately not applied -- it drives adaptive block length, which this engine "
"does not have, and it changes nothing the drafter proposes",
rad_note(b, "the rank-%lld Markov bigram head walks `unary + <markov_w1[prev], "
"markov_w2[cand]>` over the draft head's top %lld, greedily; the confidence head "
"(adaptive block length) is not applied",
(long long)dc.rank, (long long)dc.top_k);
return RAD_OK;
}
@@ -410,17 +316,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(check_format(meta));
/* "bf16" is the ACTIVATION dtype: everything but the two GEMM operands runs at it. */
/* "bf16" is the activation dtype: everything but the two GEMM operands runs at it. */
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
Geom& g = m.g;
Names& nm = m.nm;
m.n_main = g.n_layer;
/* THE ROTARY WIDTH IS THE WHOLE HEAD unless the config says otherwise. LLaMA rotates every
* dimension; `partial_rotary_factor` exists in this config schema and Phi-style models set it,
* so it is read rather than assumed -- but the DEFAULT is the family's answer and not a
* refusal, because a checkpoint that states nothing is stating "all of it". */
/* The rotary width is the whole head unless `partial_rotary_factor` says otherwise (Phi-style
* models set it). A config that states nothing means the full head. */
{
double prf = rad_meta_getf(meta, "partial_rotary_factor", 0.0);
if (!(prf > 0.0)) prf = rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", 0.0);
@@ -456,22 +360,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff));
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
/* ---- the drafter's taps. Gated on BOTH halves of the question: the container has to carry a
* drafter that reads them, and the deployment has to intend to speculate. The buffer is one
* residual stream per tap -- 40 MiB at a 2048-token chunk, five taps and hidden 2048 -- which
* a server that never drafts should not be carrying.
/* ---- the drafter's taps, only when the container carries a drafter that reads them and the
* deployment speculates: the buffer is one residual stream per tap, 40 MiB at a 2048-token
* chunk with five taps and hidden 2048.
*
* TWO KEY SPELLINGS, because the two checkpoints spell it differently and both are real. A
* SpecForge DFlash config nests the drafter's wiring under `dflash_config`; the published
* DSpark configs (openbmb/MiniCPM5-2B-DSpark and its siblings) put the same fields at the top
* level. Reading the flat one first and falling back keeps one plugin serving both rather
* than making the spelling an architecture. */
* Two key spellings: a SpecForge DFlash config nests the wiring under `dflash_config`, while
* the published DSpark configs (openbmb/MiniCPM5-2B-DSpark and siblings) put it at the top
* level. The flat key is read first. */
if (ctx->max_spec > 0) {
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (da && (std::strstr(da, "DSpark") || std::strstr(da, "DFlash"))) {
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);
m.n_taps = parse_tap_layers(ids, m.n_main, m.tap_layer, Model::MAX_TAPS);
m.n_taps = parse_layer_ids(ids, m.n_main, m.tap_layer, Model::MAX_TAPS);
if (m.n_taps > 0) {
m.b_dfsrc = decl_b(b, nm.f("draft_src"), g.act_dtype,
{g.max_tok, (int64_t)m.n_taps * g.n_embd});
@@ -493,11 +394,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
/* ---- the vocabulary edges, both ROW-SHARDED with the vocabulary. A tied head is expressed by
* the alternative source: a model that ships no `lm_head.weight` reads the embedding table as
* both, which is what every small LLaMA derivative does. The head is declared at its codes'
* dtype -- bf16, or E4M3 where a recipe made it block fp8 -- after its map, which is how the
* model is asked. */
/* ---- the vocabulary edges, both row-sharded with the vocabulary. A tied head is the
* alternative source: without `lm_head.weight` the embedding table serves as both, as in small
* LLaMA derivatives. The head is declared at its codes' dtype (bf16, or E4M3 where a recipe
* made it block fp8), queried after its name map entry. */
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"),
@@ -516,9 +416,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(m.w_tok)),
{}, {m.b_x});
/* EXACT, unconditionally: each token's embedding comes from exactly 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 same argument arch/qwen35_fp8 makes about its own. */
/* Always exact: each token's embedding comes from one rank and the others contribute zero, so
* a lossy wire would only add error. */
if (g.world > 1)
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -532,37 +431,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
MlpFP8::Wire mw{};
mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn;
auto is_tap = [&](int64_t l) {
for (int t = 0; t < m.n_taps; ++t)
if (m.tap_layer[t] == (int)l) return true;
return false;
};
m.layers.resize((size_t)m.n_main);
for (int64_t l = 0; l < m.n_main; ++l) {
Layer& lay = m.layers[(size_t)l];
/* THE RESIDUAL FOLD, and the rule is arch/qwen35_fp8's with exactly one of its exceptions:
* there are no ablation switches here, so every block folds its predecessor's delta into
* its own norm and the LAST layer's feed-forward keeps its own add -- for the final norm,
* which is a plain `rmsnorm` with no residual operand.
*
* A TAP IS THE OTHER READER OF `x` BETWEEN BLOCKS, and it forces the add to stay where it
* was. What the drafter conditions on has to be that layer's REAL output, so a tap layer's
* feed-forward keeps its own add and the block after it has nothing left to fold. Get this
* wrong and the taps carry a residual stream missing its last delta -- a drafter that
* still runs, still proposes, and is quietly conditioned on the wrong thing.
*
* `ar_in`/`ar_out` move the collective with the add, one boundary at a time, at two ranks
* only: at tp1 there is none and at four the fused kernel does not exist. They need no
* change for the taps -- a tap layer's MLP has `add`, so it does not defer its all-reduce,
* and the next mixer does not fold, so it looks for none. The two stay consistent because
* both are derived from the same two flags. */
const bool tp2 = g.world == 2;
const bool mix_fold = l > 0 && !is_tap(l - 1);
const bool mlp_add = is_tap(l) || (l + 1 >= m.n_main);
const int mix_ar_in = !tp2 ? kArNone
: mix_fold ? kArAny
: (l == 0 && m.op_embed_ar) ? kArExact : kArNone;
/* Residual fold and collective placement: rad_fp8.h, layer_fold. */
const LayerFold f = layer_fold(g, l, m.n_main, m.tap_layer, m.n_taps, m.op_embed_ar != 0);
const char* pre = "model.layers";
AttnFP8::Src as{};
@@ -573,15 +446,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
as.o = nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l);
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as,
mix_fold, /*add_out=*/false, mix_ar_in, tp2));
f.mix_fold, false, f.mix_ar_in, f.mix_ar_out));
MlpFP8::Src ms{};
ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l);
ms.gate = nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l);
ms.up = nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l);
ms.down = nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l);
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, /*fold=*/true, mlp_add,
tp2 ? kArAny : kArNone, !mlp_add && tp2));
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, true, f.mlp_add,
f.mlp_ar_in, f.mlp_ar_out));
}
m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
@@ -602,27 +475,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_WEIGHTS(m.w_lm_head)),
{m.b_hout}, {m.b_logits});
/* THE DRAFTER IS DECLARED LAST, AFTER `op_logits`, AND THE ORDER IS LOAD-BEARING.
/* The drafter is declared last, after `op_logits`. Do not move it.
*
* DECLARATION ORDER IS WHAT THE BUFFER PLANNER'S LIVENESS IS: a transient's range is
* [first_def, last_use] over OP INDICES, and two buffers whose ranges are disjoint may share
* bytes (core/build/rad_bufplan.cpp). The drafter's passes run AFTER the whole trunk pass, so
* declaring them here is the order that says so. Declared in the MIDDLE -- before
* `op_final_norm`, say -- the trunk's own tail ops get indices past the drafter's, the planner
* reads that as "these live after the drafter is done", and it shares bytes between a trunk
* buffer and a drafter buffer that are both live inside one engine step.
* Declaration order is the buffer planner's liveness: a transient lives over [first_def,
* last_use] in op indices, and buffers with disjoint ranges may share bytes
* (core/build/rad_bufplan.cpp). The drafter's passes run after the whole trunk, so they must
* be declared after it; declared earlier, the trunk's tail ops would look live after the
* drafter, and trunk and drafter buffers live in one step would share bytes.
*
* THE SYMPTOM OF GETTING IT WRONG IS NOT A CRASH: the trunk's output stays fluent, because row
* 0 of a verify step is computed before the clobber lands, and EVERY DRAFT IS REJECTED, because
* rows 1..n_spec are not. Speculation looks broken and the drafter looks wrong while it is
* proposing exactly the right tokens. It is the one class of fault the op oracle cannot see: a
* buffer clobbered before an op runs makes the device and the host compute the same wrong
* answer and agree.
*
* The same declaration can be correct at one world size and wrong at another: the shard
* halves every sharded buffer and the greedy packer's offsets are a function of the sizes.
* arch/qwen35_fp8 declares its drafter here for the same reason; this is not a stylistic
* match. */
* The failure is silent: the trunk output stays correct (row 0 of a verify step is computed
* before the clobber) but every draft is rejected. The op oracle cannot see it, since device
* and host compute the same wrong answer from a clobbered input. It can also depend on world
* size, because sharding changes buffer sizes and so the packer's offsets. */
if (m.n_taps > 0)
RAD_ARCH_TRY(declare_dspark(b, meta, ctx, m, (int)m.n_main));
@@ -632,51 +496,41 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
(long long)g.head_dim, (long long)m.n_rot, (long long)g.n_ff,
(long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab));
#if LLAMA_DENSE_SRC
rad_note(b, "the checkpoint is DENSE bf16 and its recipe quantised every linear to E4M3 with "
"a bf16 [N/%d,K/%d] scale plane -- one amax per block, scale = amax/448 rounded "
"to bf16. The container is half the checkpoint's size and the graph is the one "
"llama_fp8 declares over a checkpoint that shipped that way",
rad_note(b, "a dense bf16 checkpoint, every linear quantised by the recipe to E4M3 with a "
"bf16 [N/%d,K/%d] scale plane (scale = block amax / 448, rounded to bf16)",
RAD_FP8_BLOCK, RAD_FP8_BLOCK);
#else
rad_note(b, "weights are block-scaled fp8: E4M3 [N,K] with a bf16 [N/%d,K/%d] scale plane, "
"one stored weight taken by gemm_nt_q as two operands",
RAD_FP8_BLOCK, RAD_FP8_BLOCK);
#endif
rad_note(b, "NOT fp8 in the checkpoint: every norm, the embedding and the lm_head. The head "
"is declared at what the model holds -- block fp8 where a recipe made it so");
rad_note(b, "bf16 in the checkpoint: every norm, the embedding and the lm_head, which is "
"declared at what the container holds");
if (m.n_taps > 0) {
char ids[64] = {};
int off = 0;
for (int t = 0; t < m.n_taps && off < (int)sizeof(ids) - 8; ++t)
off += snprintf(ids + off, sizeof(ids) - (size_t)off, t ? " %d" : "%d",
m.tap_layer[t]);
rad_note(b, "the drafter reads the residual stream at layer(s) %s into a [%lld, %lld] "
"buffer -- %lld tap(s) x %lld. Those layers keep their own residual add and "
"the layer after each one has nothing to fold, so the tap sees the real "
"output rather than a stream still missing its last delta",
ids, (long long)g.max_tok, (long long)((int64_t)m.n_taps * g.n_embd),
(long long)m.n_taps, (long long)g.n_embd);
rad_note(b, "the drafter reads the residual stream after layer(s) %s into a [%lld, %lld] "
"buffer; those layers keep their own residual add",
ids, (long long)g.max_tok, (long long)((int64_t)m.n_taps * g.n_embd));
}
rad_note(b, "q, k and v are ONE fused [%lld, %lld] projection and `rope` rotates the fused "
"row in place -- q heads then k heads, v untouched. There is no per-head q/k norm "
"and no output gate in this family; qwen35 has both and that is the whole "
"difference between the two attention blocks",
rad_note(b, "q, k and v are one fused [%lld, %lld] projection, rotated in place by `rope` "
"(q heads, then k heads); no per-head q/k norm and no output gate",
(long long)(q_dim + 2 * kv_dim), (long long)g.n_embd);
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = g_model[rad_rank(c)];
/* A DRAFTER PASS, AND THE SIGN SAYS WHICH KIND. For a block-diffusion drafter the two kinds
* are the two passes: POSITIVE is the QUERY pass, which proposes the whole block in one go,
* and NEGATIVE is the CONTEXT pass, which turns the tokens the trunk just committed into the
* drafter's own K and V. There is no third kind and no round counter -- this drafter runs its
* layers once per step. Zero is a trunk step, so a zeroed RadBatch runs the model. */
/* A drafter pass; the sign gives the kind. Positive is the query pass, proposing the whole
* block at once; negative is the context pass, turning the tokens the trunk just committed
* into the drafter's own K and V. Zero is a trunk step. */
if (batch->draft_pass != 0) {
if (!m.have_ds) {
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
"container carries no `draft.` block, or declare ran at max_spec 0, "
"which is the engine saying it would not draft");
"container carries no `draft.` block, or declare ran at max_spec 0");
return;
}
if (batch->draft_pass > 0) m.ds.step(c, batch);
@@ -694,9 +548,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
for (size_t li = 0; li < m.layers.size(); ++li) {
m.layers[li].attn.step(c, batch);
m.layers[li].mlp.step(c, batch);
/* The tap, into the column slice this one owns. It runs on the PREFILL and DECODE passes
* alike, because the drafter conditions on every committed token's residual stream and
* the rows it wants are whatever this batch just computed. */
/* The tap, into its column slice. Runs on prefill and decode alike: the drafter
* conditions on every committed token's residual stream. */
for (int t = 0; t < m.n_taps; ++t) {
if (m.tap_layer[t] != (int)li) continue;
RAD_ISSUE(c, m.op_tap, brows(m.b_x, batch->n_tok),
@@ -717,15 +570,12 @@ static void step(RadCtx* c, const RadBatch* batch) {
}
}
/* WHAT THIS CONTAINER CAN SPECULATE TO. A plain llama container answers zero -- there is no MTP
* head in this family and no draft block -- and one converted with `--draft-model` against a
* DSpark checkpoint answers its trained block length.
/* The speculation depth this container supports: zero for a plain llama container (no MTP head
* in this family), or the trained block length of a DSpark drafter added with `--draft-model`.
*
* `draft_depth` IS `block_size` AND NOT `block_size - 1`, which is the one number a reader coming
* from arch/qwen35_fp8 will expect to be different: DSpark's anchor row predicts the token after
* it like every other row, so seven noise rows are seven drafts. `draft_depth_fixed` says the
* engine may not pick another -- the drafter denoises a fixed number of masked positions and was
* trained for exactly one block length. */
* `draft_depth` is `block_size`, not `block_size - 1` as in arch/qwen35_fp8: DSpark's anchor row
* predicts too. `draft_depth_fixed` forbids any other depth, since the drafter was trained for
* exactly one block length. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
@@ -743,14 +593,14 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
} /* namespace LLAMA_NS */
#ifndef RAD_ARCH_NO_EXPORTS
/* One more level of expansion so `#NS` sees the expanded namespace; arch/qwen35_fp8 explains it. */
/* One more level of expansion so `#NS` sees the expanded namespace. */
#define LLAMA_PROBE_X(NS) RAD_ARCH_PROBE(NS)
#define LLAMA_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
LLAMA_PROBE_X(LLAMA_NS)
#if LLAMA_DENSE_SRC
LLAMA_PLUGIN_X(LLAMA_NS, "llama", LLAMA_QUANT, "0.1.0",
"LLaMA-shaped decoders (MiniCPM5, Llama 3, and every derivative that reports "
"model_type llama) from a DENSE bf16 checkpoint, made block-scaled fp8 by a recipe "
"model_type llama) from a dense bf16 checkpoint, made block-scaled fp8 by a recipe "
"at convert time and served fp8 weights / fp8 activations")
#else
LLAMA_PLUGIN_X(LLAMA_NS, "llama", LLAMA_QUANT, "0.1.0",
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/ltx2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(ltx2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(ltx2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/ltx2.cpp)
+4193
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/minimaxh3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(minimaxh3 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.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/minimaxmusic3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(minimaxmusic3 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(minimaxmusic3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxmusic3.cpp)
File diff suppressed because it is too large. Load diff
+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/qwen35_bf16 -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/qwen35_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(qwen35_bf16 LANGUAGES CXX)
+100 -200
View File
@@ -1,45 +1,38 @@
/* qwen35_bf16 -- Qwen3.5 / 3.6 / 3.8 dense, bf16 weights and bf16 activations.
*
* Qwen3.5, Qwen3.6 and Qwen3.8 dense models all report the architecture id `qwen35`, and
* `qwen35moe` is the same graph with a routed FFN. Dimensions come from model metadata, so this
* one file serves every size in the family -- 0.8B through 27B. docs/ARCHITECTURES.md has the
* geometry and the traps that stay plausible when they are wrong.
* Qwen3.5, 3.6 and 3.8 dense models report the architecture id `qwen35`; `qwen35moe` is the same
* graph with a routed FFN. Dimensions come from metadata, so this file serves every size (0.8B to
* 27B). docs/ARCHITECTURES.md has the geometry and its plausible-but-wrong traps.
*
* One plugin implements one architecture id for one quantisation scheme (spec §2.4). A
* `qwen35_w8a8` sibling is a different directory that composes the same blocks against
* rmsnorm_had_quant_i8, gemm_nt_q and gdn_gated_norm_had_quant_i8 -- not a branch in here. That is
* why the declare function below is a list of what runs, in order, with no branch on quant in it.
* One plugin implements one architecture id for one quantisation scheme (spec §2.4); a quantised
* variant is a separate plugin composing the same blocks against other ops (e.g.
* rmsnorm_had_quant_i8, gemm_nt_q), so declare() below has no branch on quantisation.
*
* ============================== WHAT IT SERVES ==============================
*
* The unquantised release -- Qwen3.8-27B in bf16, quantisation descriptor "" -- served at its own
* precision: every projection a bf16 GEMM. The block-scaled fp8 release is qwen35_fp8's, which
* declares the same graph over fp8 linears. The lm_head here is declared at whatever the model
* holds it as, so a container whose recipe made it block fp8 reads it through the fp8 logits
* kernel and a checkpoint loaded as it stands through the bf16 one.
* The unquantised release (quantisation descriptor ""), every projection a bf16 GEMM. The
* block-scaled fp8 release is qwen35_fp8's. The lm_head is declared at whatever the model holds,
* so a recipe-made block-fp8 head uses the fp8 logits kernel.
*
* ============================== THE SHAPE, AT 27B ==============================
*
* 64 layers, full_attention_interval 4 -> layers 3,7,...,63 are FULL ATTENTION (16 of them),
* the other 48 are GATED DELTA NET
* hidden 5120 ffn 17408 vocab 248320 (lm_head NOT tied)
* 24 heads / 4 kv heads / head_dim 256 -> GQA 6, and head_dim is READ, not derived:
* n_embd / n_head is 213 and every shape after it
* would be wrong.
* 64 layers, full_attention_interval 4 -> layers 3,7,...,63 are full attention (16 of them),
* the other 48 are gated delta net
* hidden 5120 ffn 17408 vocab 248320 (lm_head not tied)
* 24 heads / 4 kv heads / head_dim 256 -> GQA 6; head_dim is read, not derived
* (n_embd / n_head would be 213)
* attn_output_gate -> q_proj is [n_embd, 2 * n_head * head_dim], query and gate interleaved
* partial_rotary_factor 0.25 -> MROPE over the first 64 of 256 head dims, theta 1e7
* linear: 16 key heads / 48 value heads of 128, conv width 4, fp32 recurrent state
*
* ============================== WHAT THIS PLUGIN DOES NOT DECLARE ==============================
*
* The MTP / NextN head (one extra decoder block plus fc, enorm, hnorm) is real scope and is NOT
* here. It does not block text generation, and it has to be declared from tensor names read off
* the checkpoint -- a name map written from memory is a model that loads half its weights and
* says nothing. It sits BESIDE the trunk under an `mtp.` prefix of its own, so
* `nextn_predict_layers` is not subtracted from the layer count (see declare()), and declaring
* the MTP block as a trunk layer would run it in the main pass, which is a different model.
* The MTP / NextN head (one extra decoder block plus fc, enorm, hnorm) is not declared here; it
* is not needed for text generation. It sits beside the trunk under its own `mtp.` prefix, so
* `nextn_predict_layers` is not subtracted from the layer count (see declare()); running it as a
* trunk layer would be a different model.
*
* The VISION TOWER (27 blocks, hidden 1152, 16 heads of 72, patch 16, out 5120) is declared
* The vision tower (27 blocks, hidden 1152, 16 heads of 72, patch 16, out 5120) is declared
* through arch/common/rad_block_vit.h, only when the container carries one and the deployment
* asked for media.
*/
@@ -55,10 +48,8 @@ namespace qwen35_bf16 {
using namespace rad::arch;
/* One trunk layer. A hybrid model's layer is one of two kinds and the plugin holds both structs
* rather than a union: they are small, and a variant would buy nothing except a cast at every use.
* `full` is the only branch in step(), and it is a branch on the MODEL, not on a configuration --
* the same layer is the same kind on every step and in every deployment. */
/* One trunk layer, of one of two kinds; both small structs are held rather than a union. `full`
* is the only branch in step(), and it is fixed per layer by the model. */
struct Layer {
int full = 0;
AttnGatedBF16 attn;
@@ -97,65 +88,10 @@ struct Model {
std::vector<Layer> layers;
};
/* Declare runs once per rank, in one process, on the rank's own thread (spec §1, §9). A single
* static Model would have rank 1's declare overwrite rank 0's handles; this is indexed by rank and
* read back in step() with rad_rank(). */
/* Declare runs once per rank, in one process, on the rank's own thread (spec §1, §9), so the
* model state is indexed by rank and read back in step() with rad_rank(). */
static Model g_model[MAX_RANKS];
/* Layer kind. llama.cpp is ground truth: `is_recr(i) = (i < n_main) && ((i + 1) % interval != 0)`,
* so with interval 4 the FULL-ATTENTION layers are 3, 7, ... and everything else is linear. */
static inline bool is_full_attention(int64_t l, int64_t interval) {
return interval > 0 && ((l + 1) % interval == 0);
}
static int check_layer_schedule(const RadModelMeta* meta, int64_t n_layer, int64_t interval) {
const char* s = rad_meta_gets(meta, "qwen35.layer_types", nullptr);
if (!s) s = rad_meta_gets(meta, "text_config.layer_types", nullptr);
if (!s) s = rad_meta_gets(meta, "layer_types", nullptr);
if (!s || !*s) return RAD_OK;
int64_t l = 0;
for (const char* p = s; *p; ) {
while (*p == ' ') ++p;
if (!*p) break;
const char* tok = p;
while (*p && *p != ' ') ++p;
const size_t len = (size_t)(p - tok);
const bool says_full = len == 14 && std::strncmp(tok, "full_attention", 14) == 0;
const bool says_lin = len == 16 && std::strncmp(tok, "linear_attention", 16) == 0;
if (!says_full && !says_lin) {
fprintf(stderr, "radiance: qwen35: layer_types[%lld] is '%.*s'; this plugin knows "
"'full_attention' and 'linear_attention' and will not guess at a "
"third kind of layer.\n", (long long)l, (int)len, tok);
return RAD_E_UNSUPPORTED;
}
/* Past the trunk is the MTP block, which the array may or may not include; it is not a
* trunk layer and its kind is the drafter's business (see declare_draft). */
if (l >= n_layer) break;
if (says_full != is_full_attention(l, interval)) {
fprintf(stderr, "radiance: qwen35: the container says layer %lld is %s, and "
"full_attention_interval %lld makes it %s. The interval rule is "
"llama.cpp's and it is not a property of this family -- a model whose "
"layer_types differ from it would be built with the wrong layers "
"linear, and would load and generate fluent text from an architecture "
"that is not the one in the checkpoint. Read layer_types directly "
"before serving this model.\n",
(long long)l, says_full ? "full_attention" : "linear_attention",
(long long)interval,
is_full_attention(l, interval) ? "full_attention" : "linear_attention");
return RAD_E_UNSUPPORTED;
}
++l;
}
if (l && l < n_layer) {
fprintf(stderr, "radiance: qwen35: layer_types names %lld layers and the model has %lld. "
"A short schedule is not a schedule.\n", (long long)l, (long long)n_layer);
return RAD_E_UNSUPPORTED;
}
return RAD_OK;
}
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;
@@ -165,7 +101,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
/* A routed model is a different graph, not a flag on this one. qwen35moe_bf16 serves it. */
/* A routed model is a different graph, served by the qwen35moe plugin. */
if (meta->n_expert > 0) {
fprintf(stderr, "radiance: qwen35_bf16 refuses a checkpoint with %lld experts; that is "
"qwen35moe\n", (long long)meta->n_expert);
@@ -175,9 +111,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
Geom& g = m.g;
Names& nm = m.nm;
/* ---- geometry that RadModelMeta does not name, read from the container's free-form header.
* Both spellings are accepted: a .rad converted from the FP8 safetensors carries the
* HuggingFace keys and one converted from a GGUF carries llama.cpp's. */
/* ---- geometry RadModelMeta does not name, from the container's free-form header. Both
* spellings are accepted: HuggingFace keys (from safetensors) and llama.cpp's (from GGUF). */
bool have_interval = false;
const int64_t interval = meta_int2(meta, "qwen35.full_attention_interval",
"full_attention_interval", 4, &have_interval);
@@ -189,43 +124,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
(long long)interval, (long long)nextn, (long long)g.n_layer);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(check_layer_schedule(meta, g.n_layer, interval));
/* EVERY DECLARED LAYER IS A TRUNK LAYER. `mtp_num_hidden_layers` is NOT part of
* `num_hidden_layers` in this family -- Qwen3.8-27B-FP8 ships layers-0..63 under
* `model.language_model.layers.N` and its one MTP block separately, under an `mtp.` prefix of
* its own, in mtp.safetensors. Subtracting it here would drop layer 63, which is a
* full-attention layer, and the model would answer with the trunk one layer short: still a
* distribution, still self-consistent op by op, and wrong. `nextn` is kept for the note below,
* which is the only thing the count is good for until the MTP head is declared. */
RAD_ARCH_TRY(check_layer_schedule("qwen35", meta_text_gets(meta, "layer_types", nullptr),
g.n_layer, interval, {"full_attention"}));
/* Every declared layer is a trunk layer: `mtp_num_hidden_layers` is not part of
* `num_hidden_layers` in this family (the MTP block ships separately under `mtp.`).
* Subtracting it would drop full-attention layer 63 and silently run a trunk one layer short.
* `nextn` is used only for the note below. */
m.n_main = g.n_layer;
/* Qwen3.5's norms are GemmaRMSNorm: `x_hat * (1 + w)`, not `x_hat * w`. vLLM says so by
* importing it under the family's own name -- `from ...layernorm import GemmaRMSNorm as
* Qwen3_5RMSNorm` -- and the checkpoint says so too: `input_layernorm.weight` sits around 0.07
* to 0.29, which is a gain of 1.1 to 1.3 the right way round and a five-to-ten-times shrink
* the wrong way. It applies to input_layernorm, post_attention_layernorm, the model's final
* norm and the q/k head norms -- and NOT to the delta net's ssm_norm, which is a plain
* RMSNormGated with gains around 0.88.
*
* The checkpoint answers two of the three families by itself: the layer norms (0.07..0.29)
* and the q/k head norms (partly NEGATIVE) can only be `1 + w`. The model's FINAL norm sits at
* 0.68..0.96, which reads as either, and takes `1 + w` because the reference implementation
* does. */
/* Qwen3.5's norms are GemmaRMSNorm, `x_hat * (1 + w)` (vLLM imports GemmaRMSNorm as
* Qwen3_5RMSNorm). This covers input_layernorm, post_attention_layernorm, the final norm and
* the q/k head norms, but not the delta net's ssm_norm, a plain RMSNormGated (gains ~0.88).
* The checkpoint confirms it: layer norm weights of 0.07..0.29 and partly negative q/k norm
* weights only make sense as `1 + w`. The final norm (0.68..0.96) is ambiguous and follows the
* reference implementation. */
g.wadd = 1.0f;
g.wadd_qk = 1.0f;
const float final_wadd = 1.0f;
/* The rotary width. partial_rotary_factor 0.25 over head_dim 256 is 64, and a container that
* omits it is refused rather than defaulted to head_dim: a full rotation is a different model
* and its symptom is fluent wrong text, which is exactly what spec §17 is about. */
/* The rotary width: partial_rotary_factor 0.25 over head_dim 256 is 64. A container that
* omits it is refused rather than defaulted to a full rotation, which would give fluent wrong
* text (spec §17). */
m.n_rot = meta_int2(meta, "qwen35.rope.dimension_count", "rope_dimension_count", 0);
if (m.n_rot <= 0) {
/* BOTH SPELLINGS, because the family uses both. Qwen3.8-27B-FP8 states
* `partial_rotary_factor` at the text_config level AND inside `rope_parameters`;
* Qwen3.5-0.8B states it ONLY inside `rope_parameters`, and rad-convert flattens nested
* config with a dot. Reading only one spelling refuses a container of the same
* architecture with "no usable rotary width", which is a true statement about the key and
* a false one about the model. */
/* Both spellings occur in this family: Qwen3.8-27B-FP8 states `partial_rotary_factor`
* at the top level and inside `rope_parameters`, Qwen3.5-0.8B only inside
* `rope_parameters` (rad-convert flattens nested config with a dot). */
double prf = rad_meta_getf(meta, "partial_rotary_factor", 0.0);
if (!(prf > 0.0)) prf = rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", 0.0);
if (prf > 0.0) m.n_rot = (int64_t)(g.head_dim * prf);
@@ -263,10 +187,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
(long long)gc.head_v, (long long)gc.conv_width);
return RAD_E_INVAL;
}
/* The chunked scan's tile length. Not a model parameter: it is libr4d's
* gdn_chunk_scan_k128_v128_c64_bf16, and it is also the interval a linear-state checkpoint is
* snapshotted at (spec §7.3). Note that gdn_conv_prep takes it while gdn_chunk_scan derives it
* from the kernel, and nothing checks that the two agree. */
/* The chunked scan's tile length, not a model parameter: libr4d's
* gdn_chunk_scan_k128_v128_c64_bf16, and also the linear-state checkpoint interval
* (spec §7.3). Note: gdn_conv_prep takes it while gdn_chunk_scan derives it from the kernel,
* and nothing checks that the two agree. */
gc.chunk = 64;
int s;
@@ -280,13 +204,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
const int64_t v_dim = gc.v_dim();
const int64_t conv_dim = gc.conv_dim();
/* ---- THREE KV groups, which is why hybrid KV groups are first-class rather than an
* extension (spec §7.2). Every layer is bound to the group it owns state in, below: a group
* with no bound layers is a declare error, because how many state instances a sequence holds
* is the layer count and assuming one would make the page size a guess.
/* ---- three KV groups (spec §7.2). Every layer is bound below to the group it owns state
* in; a group with no bound layers is a declare error, since the bound layer count is how
* many state instances a sequence holds.
*
* The block size is NOT declared for the full-attention group -- it comes off the resolved
* attention kernel's constraints and is read back with rad_kv_block_size() inside the block. */
* The full-attention group's block size is not declared: it comes from the resolved attention
* kernel and is read back with rad_kv_block_size() inside the block. */
RadKVGroupDecl fd{};
fd.kind = RAD_KV_FULL;
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
@@ -295,12 +218,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
g.kv_dtype = rad_dtype_name(fd.dtype);
/* The recurrent state is fp32 because that is the only state width libr4d has a kernel for
* (gdn_recurrent_update_k128_v128_bf16_fp32state) and what `mamba_ssm_dtype: float32` asks
* for. It costs 48 x 128 x 128 x 4 = 3 MiB a layer and 144 MiB across the 48 linear layers,
* PER SEQUENCE, which is the largest single number in this deployment's memory plan.
* An fp16 state would halve that and cost a little step time, but declaring it here would be
* declaring a geometry no kernel serves, so it waits for the kernel. */
/* The recurrent state is fp32, as `mamba_ssm_dtype: float32` asks; an f16 state changes the
* generated text (qwen35_fp8.cpp). It costs 48 x 128 x 128 x 4 = 3 MiB per layer, 144 MiB
* across the 48 linear layers per sequence, the largest item in the memory plan. */
RadKVGroupDecl sd{};
sd.kind = RAD_KV_LINEAR;
sd.dtype = RAD_F32;
@@ -309,7 +229,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
sd.state_dim[1] = gc.head_k;
m.kv_state = rad_decl_kv_group(b, nm.f("kv_gdn_state"), &sd);
/* The conv window: conv_width-1 + n_spec entries of the whole convolved row, counted in HEADS
/* The conv window: conv_width-1 + n_spec entries of the whole convolved row, counted in heads
* so the channel split never straddles a q/k/v boundary at any tensor-parallel width. */
RadKVGroupDecl cd{};
cd.kind = RAD_KV_CONV;
@@ -319,18 +239,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
cd.conv_width = gc.conv_width;
m.kv_conv = rad_decl_kv_group(b, nm.f("kv_gdn_conv"), &cd);
/* ---- activation buffers, sized at max_tok because that is the worst step. Every layer of a
* kind shares these: layers that share a geometry share the buffer, and the buffer plan's
* liveness analysis over the declared read and write sets is what makes one arena enough
* (spec §3.1, §8). */
/* ---- activation buffers, sized at max_tok (the worst step) and shared by every layer of a
* kind; liveness analysis over the declared read and write sets fits them in one arena
* (spec §3.1). */
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
/* The query-and-gate projection is declared RANK 3, [tokens, heads, 2*head_dim], because that
* is what makes the interleaving addressable: the query is the first head_dim columns of the
* last dimension and the gate is the second head_dim, so both are ordinary column slices whose
* row stride is the declared width. Flattened to [tokens, 2*q_dim] the same bytes describe a
* per-head view no operand can name. */
/* The query-and-gate projection is rank 3, [tokens, heads, 2*head_dim], so the per-head
* interleaving is addressable: query and gate are the first and second head_dim columns of the
* last dimension, i.e. ordinary column slices. Flattened, no operand could name them. */
m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {g.max_tok, g.n_head, 2 * g.head_dim});
m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim});
m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, kv_dim});
@@ -343,45 +260,37 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.b_gq = decl_b(b, nm.f("gdn_q"), g.act_dtype, {g.max_tok, gc.n_head_k, gc.head_k});
m.b_gk = decl_b(b, nm.f("gdn_k"), g.act_dtype, {g.max_tok, gc.n_head_k, gc.head_k});
m.b_gv = decl_b(b, nm.f("gdn_v"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v});
/* The decay, beta and the chunk inverse are f32 and not bf16. The decay is a cumulative sum
* whose intra-chunk span reaches hundreds of nats on real prefill inputs; a bf16 running sum
* loses the low bits of exactly the quantity every decay factor is an exponent of. */
/* Decay and beta are f32: the decay is a cumulative sum whose intra-chunk span reaches
* hundreds of nats on real prefill inputs, and a bf16 running sum would lose the low bits that
* every decay factor exponentiates. */
m.b_gdec = decl_b(b, nm.f("gdn_g"), RAD_F32, {g.max_tok, gc.n_head_v});
m.b_beta = decl_b(b, nm.f("gdn_beta"), RAD_F32, {g.max_tok, gc.n_head_v});
/* BF16, not f32: gdn_kkt_solve writes this plane as bf16 and gdn_chunk_scan reads it as bf16
* (libr4d's own row text, and the casts in both .hip files). See qwen35_fp8.cpp. */
/* bf16, not f32: gdn_kkt_solve writes this plane as bf16 and gdn_chunk_scan reads it as
* bf16. */
m.b_kkt = decl_b(b, nm.f("gdn_kkt"), RAD_BF16, {g.max_tok, gc.n_head_v, gc.chunk});
m.b_go = decl_b(b, nm.f("gdn_o"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v});
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
/* The lm_head runs over the SAMPLED ROWS, not over every token of the chunk. `max_logit_rows`
* is one row per sequence, or one per verified draft position per sequence -- at 248320 vocab
* that is the difference between 63 MiB and 8 GiB, and between one GEMM per sequence and one
* per token. `b_hout` is where gather_rows puts the hidden states it selects; it is narrow
* (n_embd, not n_vocab) which is why gathering before the GEMM and not after is the whole
* point. */
/* The lm_head runs over the sampled rows only: `max_logit_rows` is one row per sequence, or
* per verified draft position. At 248320 vocab that is 63 MiB of logits instead of 8 GiB.
* gather_rows selects the hidden states into the narrow `b_hout` (n_embd wide) before the
* GEMM. */
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
/* ---- vocabulary edges.
* BOTH ENDS OF THE VOCABULARY ARE ROW-SHARDED. Replicating the embedding while sharding the
* lm_head would put 248320 x 5120 in bf16 -- 2.43 GiB -- on every rank, for a table each rank
* uses a slice of. `embed_lookup` takes a `vocab_offset`: a rank gathers the ids in its own
* slice, writes a zero row for every id belonging to another rank, and the all_reduce below
* sums the ranks into x. lm_head is sharded because the sampler runs a distributed top-k and full
* logits are never gathered anywhere (spec §9, §13); the embedding is sharded because the
* other end of the same vocabulary already was. */
/* ---- vocabulary edges, both row-sharded. The lm_head is sharded because the sampler runs a
* distributed top-k and full logits are never gathered (spec §9, §13); replicating the
* embedding would cost 248320 x 5120 bf16 (2.43 GiB) per rank. `embed_lookup` takes a
* `vocab_offset`: a rank gathers the ids in its slice and writes zero rows for the rest, and
* the all_reduce below sums the ranks into x. */
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_norm.weight"),
nm.ckpt("model.language_model.norm.weight")));
/* This model does NOT tie its lm_head -- `tie_word_embeddings: false`, and the checkpoint
* ships lm_head.weight beside the embedding. The second source is for the small members of the
* family that do tie; first source present wins, and without it a family whose members differ
* only in tying needs two plugins. The maps come first: they are how the model is asked what
* each weight is. */
/* The 27B does not tie its lm_head (`tie_word_embeddings: false`); the second source serves
* the small family members that do. The first source present wins. */
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("model.language_model.embed_tokens.weight")));
@@ -389,10 +298,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
/* ROW-SHARDED with the vocabulary: g.n_vocab is THIS RANK'S share and rad_arch.h says what
* the split is and what it buys. The two change together. Declared at its codes' dtype: bf16
* as the checkpoint ships it, E4M3 where a recipe made it block fp8 -- and the logits kernel
* that reads that encoding is the one selected. */
/* Row-sharded with the vocabulary: g.n_vocab is this rank's share (rad_arch.h). Declared at
* its codes' dtype (bf16 as shipped, E4M3 where a recipe made it block fp8), which selects the
* logits kernel. */
m.w_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());
@@ -403,12 +311,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(m.w_tok)),
{}, {m.b_x});
/* THE ENCODER'S ROWS, over the lookup and before its reduction (MediaRows says why). */
/* The encoder's rows overwrite the lookup before its reduction (see MediaRows). */
m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
/* EXACT, and not g.wire_exact: this sums DISJOINT rows -- every token comes from exactly one
* rank and the others contribute zeros -- so a lossy wire would be loss on a value that is
* already the answer, not a bandwidth trade against a partial product. */
/* Always exact, not g.wire_exact: this sums disjoint rows (each token from one rank, zeros
* from the others), so a lossy wire would only add error. */
if (g.world > 1)
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -417,7 +324,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_NOWEIGHTS),
{m.b_x}, {m.b_x});
/* ---- the layers. This loop is the model card. */
/* ---- the layers. */
AttnGatedBF16::Wire aw{};
aw.x = m.b_x; aw.h = m.b_h; aw.qg = m.b_qg; aw.k = m.b_k; aw.v = m.b_v;
aw.q = m.b_q; aw.gate = m.b_gate; aw.attn = m.b_attn;
@@ -491,7 +398,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_WEIGHTS(m.w_lm_head)),
{m.b_hout}, {m.b_logits});
/* ---- what a reader of --debug-graph should be told, in the plugin's own words. */
/* ---- notes for --debug-graph. */
rad_note(b, "rank %d/%d: %lld trunk layers, %lld full attention + %lld gated delta net, "
"n_head=%lld n_head_kv=%lld head_dim=%lld n_ff=%lld vocab=[%lld,%lld)",
g.rank, g.world, (long long)m.n_main,
@@ -503,27 +410,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
(long long)gc.n_head_k, (long long)gc.head_k, (long long)gc.n_head_v,
(long long)gc.head_v, (long long)gc.conv_width, (long long)gc.chunk,
(long long)conv_dim, (long long)gc.in_dim());
rad_note(b, "ssm_a_log carries A_log AS A LOG: the kernels form -exp(A_log)*softplus(a+dt). "
"A container built from a GGUF has ssm_a = -exp(A_log) already applied and must "
"undo it, or every head's decay collapses");
rad_note(b, "rope is mrope over %lld of %lld head dims, sections [11,11,10]; RadBatch carries "
"one position component per token, so the three sections see the same position -- "
"exact for text, wrong for an image span",
(long long)m.n_rot, (long long)g.head_dim);
rad_note(b, "ssm_a_log holds A_log itself: the kernels form -exp(A_log) * softplus(a + dt), "
"so a GGUF's ssm_a = -exp(A_log) must be converted back");
rad_note(b, "rope: %s over %lld of %lld head dims%s%s", g.rope_mode, (long long)m.n_rot,
(long long)g.head_dim, g.rope_mc ? ", sections " : "", g.rope_sections);
if (!have_interval)
rad_note(b, "the container did not state full_attention_interval; assuming %lld, which "
"makes layers 3,7,... full attention", (long long)interval);
rad_note(b, "logits are computed for the %lld sampled rows of a step, not for all %lld "
"tokens: RadBatch::out_ids names them and gather_rows selects the hidden states "
"before the lm_head, which is the difference between 63 MiB and 8 GiB at this "
"vocabulary", (long long)g.max_logit_rows, (long long)g.max_tok);
rad_note(b, "logits for at most %lld sampled rows a step (of %lld tokens): gather_rows "
"selects RadBatch::out_ids before the lm_head", (long long)g.max_logit_rows,
(long long)g.max_tok);
if (nextn > 0)
rad_note(b, "%lld MTP/NextN layer(s) sit BESIDE the %lld trunk layers -- under an `mtp.` "
"prefix of their own, not as layers %lld.. -- and are NOT declared: this "
"plugin serves the trunk only",
(long long)nextn, (long long)m.n_main, (long long)m.n_main);
rad_note(b, "the %lld MTP/NextN layer(s) under `mtp.` are not declared: this plugin "
"serves the trunk only", (long long)nextn);
/* THE VISION TOWER, LAST, so its activations share the arena with every buffer above. */
/* The vision tower, last, so its activations share the arena with every buffer above. */
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
return RAD_OK;
}
@@ -531,7 +432,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = g_model[rad_rank(c)];
/* AN ENCODER PASS RUNS THE VISION TOWER AND NOTHING ELSE (RadBatch::enc). */
/* An encoder pass runs only the vision tower (RadBatch::enc). */
if (batch->enc) {
m.vit.step(c, batch);
return;
@@ -555,9 +456,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
RAD_ISSUE(c, m.op_final_norm,
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok));
/* The lm_head runs on the rows the sampler asked for and on nothing else. A prefill chunk in
* the middle of a long prompt sets n_out to zero: it finishes no sequence, so there is no
* distribution to draw from and the widest GEMM in the model is not issued at all. */
/* The lm_head runs only on the rows the sampler asked for; a mid-prompt prefill chunk has
* n_out zero and skips it. */
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
brows(m.b_h, batch->n_tok),
+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/qwen35_fp8 -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/qwen35_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(qwen35_fp8 LANGUAGES CXX)
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/qwen35_w8a8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(qwen35_w8a8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwen35_w8a8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35_w8a8.cpp)
+19
View File
@@ -0,0 +1,19 @@
/* qwen35_w8a8 -- Qwen3.5 / 3.6 / 3.8 dense with an int8 trunk: i8 weights with a bf16 scale a 128
* of K, rotated by a 128-wide Hadamard, against int8 activations quantised under the same rotation.
*
* This is arch/qwen35_fp8/qwen35_fp8.cpp built again, as qwen35moe_fp8 is: the same gated
* attention, gated delta net, MLP, layer schedule, rope, vocabulary edges, drafters and vision
* tower. A linear's weight encoding makes it int8 (arch/common/rad_fp8.h: LinearFP8):
* `i8*bf16[1x128]/fwht128` is gemm_nt_q at i8a8h behind had_quant_act_i8g, each linear quantising
* its own input from the bf16 plane its producer already writes. The places this build differs are
* behind `#if QWEN35_W8A8` in that file.
*
* A plugin of its own rather than qwen35_fp8 serving any encoding it is handed, because the
* quantisation descriptor is half of the selection key (spec §2.4): a container converted with
* data/recipes/q38-27b-w8a8-df2.recipe says `w8a8_fwht128`.
*/
#define QWEN35_W8A8 1
#define QWEN35_NS qwen35_w8a8
#define QWEN35_ARCH_ID "qwen35"
#include "../qwen35_fp8/qwen35_fp8.cpp"
+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/qwen35moe_fp8 -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/qwen35moe_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(qwen35moe_fp8 LANGUAGES CXX)
+8 -15
View File
@@ -1,21 +1,14 @@
/* qwen35moe_fp8 -- Qwen3.5 / 3.6 MoE (35B-A3B), block-scaled FP8 weights and FP8 activations.
*
* IT IS arch/qwen35_fp8/qwen35_fp8.cpp WITH THE FEED-FORWARD ROUTED, and that is the whole of this
* file: three macros and an include. Everything above the FFN -- the gated attention, the gated
* delta net, the layer schedule, the rope, the vocabulary edges, the MTP head, every switch and
* every bisect -- is identical between the two members of this family, and reading the two
* config.json files side by side that is not an approximation. The six places where a routed
* feed-forward differs are behind `#if QWEN35_MOE` in that file, each with its own comment.
* This is arch/qwen35_fp8/qwen35_fp8.cpp with a routed feed-forward: three macros and an include.
* Everything above the FFN (gated attention, gated delta net, layer schedule, rope, vocabulary
* edges, MTP head) is identical between the dense and MoE configs. The places where a routed
* feed-forward differs are behind `#if QWEN35_MOE` in that file.
*
* WHY A SECOND TRANSLATION UNIT AT ALL, rather than one plugin that branches on `n_expert`: the
* architecture id and the quantisation descriptor are the SELECTION KEY (spec §2.4). A container
* converted from `model_type: qwen3_5_moe` reports `qwen35moe`, the dense one reports `qwen35`, and
* the loader picks by that pair. One .so cannot claim both ids, and it should not: an operator
* looking at what is installed should see two plugins for two architectures.
*
* The precedent is libr4d's attention dispatches -- one set of kernel templates, three translation
* units instantiating them at three geometries. The alternative is a second 1300-line plugin kept
* in step by hand.
* A second translation unit rather than a branch on `n_expert`, because the architecture id and
* quantisation descriptor are the selection key (spec §2.4): a container converted from
* `model_type: qwen3_5_moe` reports `qwen35moe`, the dense one `qwen35`, and one .so cannot claim
* both ids.
*/
#define QWEN35_MOE 1
#define QWEN35_NS qwen35moe_fp8
+11
View File
@@ -0,0 +1,11 @@
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
# radiance (`cmake -S arch/qwen3asr_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the
# same rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(qwen3asr_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwen3asr_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen3asr_bf16.cpp)
+623
View File
@@ -0,0 +1,623 @@
/* qwen3asr_bf16 -- Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, bf16
* weights and bf16 activations.
*
* A speech recogniser served as the generative model it is: the clip goes through the audio
* encoder (RadEncoderDecl, RAD_MM_AUDIO), its rows replace the prompt's <|audio_pad|>
* placeholders, and the decoder writes the transcript, after "language <Name><asr_text>" when the
* request forces a language and after naming it when it does not. POST /v1/audio/transcriptions
* builds the prompt from rad_arch_audio_format (below); /v1/chat/completions takes the clip as an
* input_audio part. The reference is transformers' modeling_qwen3_asr (5.18) with its
* Qwen3ASRFeatureExtractor, which core/mm reproduces (AudioFamily::Qwen3ASR).
*
* ============================== THE SHAPE, AT 1.7B ==============================
*
* audio encoder: log-mel [frames, 128], convolved one second (100 frames) at a time: three
* Conv2d 3x3 / stride 2 / pad 1 over [mel, time] with 480 channels and exact gelu, 128 mel ->
* 16 and 100 frames -> 13 rows; a row's 16 x 480 features through a 7680 -> 1024 linear (no
* bias); sinusoidal positions 0..12 added to each second's rows; 24 pre-LayerNorm layers (eps
* 1e-5), d_model 1024, 16 heads of 64, biased q/k/v/o and FFN linears, FFN 4096 with exact
* gelu, attention bidirectional in blocks of 104 rows (n_window_infer 800 frames = 8 s) from
* the clip's start; a final LayerNorm.
* projector: 1024 -> 1024, gelu, 1024 -> 2048.
* decoder: Qwen3-1.7B: 28 layers, hidden 2048, 16 heads over 8 KV heads of 128 (GQA 2), per-head
* q/k RMS norms, NeoX rope over the whole head at theta 1e6, SwiGLU 6144, RMS eps 1e-6,
* vocab 151936, the lm_head tied to the embedding.
*
* ============================== WHAT IS EASY TO GET WRONG ==============================
*
* Each second is convolved on its own. The core lays a clip out so one convolution over it does
* that (core/mm/processor.h, AudioFamily::Qwen3ASR): a whole second is staged as 104 frames whose
* last four read as zero (RadBatch::enc_coord plane 1), and the last, shorter second as 8 x the
* rows the reference keeps of it. `conv2d`'s `valid` at strides 1, 2 and 4 keeps one second's
* convolution out of the next's, and every row the tower writes is a row the reference keeps, so
* nothing is compacted.
*
* The convolutions run over [mel, time], so PyTorch's kernel is [cout, cin, mel, time] with time
* last, where `conv2d` convolves (time, width); `t_last` reads the checkpoint as it is. The 7680 ->
* 1024 linear takes its input channel-major (c * 16 + f) where the convolution writes
* frequency-major (f * 480 + c); as a 1 x 16 convolution over the frequency axis, the checkpoint's
* [1024, 7680] is the kernel [1024, 480, 1, 16] in PyTorch's layout, and nothing is permuted.
*
* The 480-channel convolutions are GEMMs. Two of them and the 7680 -> 1024 linear are 95% of the
* tower's arithmetic outside its transformer (68 GMAC for 30 s), and a direct convolution re-reads
* the weights for every output. `conv2d_unfold` writes each output position's receptive field as
* a row, its columns in the weight's own order, so `gemm_nt_bias` against the checkpoint's kernel
* read as [cout, cin * 9] (a reshape, not a relayout) is the convolution, with the bias and the
* gelu in its epilogue. The first convolution has one input channel and nine taps, too narrow a K
* for a GEMM, so it stays a `conv2d`.
*
* Positions restart every 13 rows (`seg_sinusoid`, per clip), and attention runs in blocks of 104
* rows from the clip's start, the last one short (`attn_dense`'s `block`). A clip is one encoder
* segment, so the segment bounds (in frames, read at cu_div 8) are the clip's.
*
* The decoder's positions are the tokens' indices. The checkpoint's text_config is plain Qwen3
* (no mrope_section), and the reference's position ids count the placeholders like text.
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_attn.h>
#include <arch/rad_block_mlp.h>
#include <arch/rad_block_vit.h>
#include <cmath>
#include <cstring>
#include <vector>
namespace qwen3asr_bf16 {
using namespace rad::arch;
/* The longest clip one encoder pass carries, in seconds: the reference extractor's own chunk
* length (`chunk_length`), and the clip the transcription route cuts longer audio into. */
constexpr int64_t kPassSeconds = 30;
/* Rows a chunk of `frames` keeps: three convolutions of kernel 3, stride 2, padding 1. */
static int64_t post_cnn(int64_t frames) {
for (int i = 0; i < 3; ++i) frames = frames > 0 ? (frames - 1) / 2 + 1 : 0;
return frames;
}
/* ============================== THE AUDIO ENCODER ============================== */
struct AudioTower {
struct Layer {
rad_weight ln1w = 0, ln1b = 0, qkv_w = 0, qkv_b = 0, o_w = 0, o_b = 0;
rad_weight ln2w = 0, ln2b = 0, fc1_w = 0, fc1_b = 0, fc2_w = 0, fc2_b = 0;
rad_op op_ln1 = 0, op_qkv = 0, op_attn = 0, op_o = 0, op_ln2 = 0, op_fc1 = 0, op_fc2 = 0;
};
bool on = false;
int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffn = 0, C = 0, nmel = 0, f3 = 0, w3 = 0;
int64_t chunk_rows = 0, block = 0, n_embd = 0;
static constexpr int64_t kMerge = 8; /* three stride-2 convolutions: 8 frames a row */
rad_weight w_c1 = 0, b_c1 = 0, w_c2 = 0, b_c2 = 0, w_c3 = 0, b_c3 = 0, w_co = 0;
rad_weight ln_w = 0, ln_b = 0, p1_w = 0, p1_b = 0, p2_w = 0, p2_b = 0;
rad_op op_c1 = 0, op_u2 = 0, op_c2 = 0, op_u3 = 0, op_c3 = 0, op_uo = 0, op_co = 0;
rad_op op_pos = 0, op_add_pos = 0;
rad_op op_ln = 0, op_p1 = 0, op_p2 = 0;
rad_buf b_s1 = 0, b_u = 0, b_s2 = 0, b_s3 = 0, b_uo = 0, b_x = 0, b_h = 0, b_pos = 0;
rad_buf b_qkv = 0, b_att = 0;
rad_buf b_f = 0, b_p1 = 0, 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, "qwen3_asr_encoder");
}
/* The frames a pass of kPassSeconds stages: whole seconds of merge x 13 rows each. */
static int64_t frames_for(const RadModelMeta* m) {
const int64_t nw = rad_meta_geti(m, "audio_config.n_window", 0);
if (nw <= 0) return 0;
return kPassSeconds * kMerge * post_cnn(2 * nw);
}
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;
auto gi = [&](const char* k, int64_t d) {
char key[96];
std::snprintf(key, sizeof key, "audio_config.%s", k);
return rad_meta_geti(m, key, d);
};
H = gi("d_model", 0);
heads = gi("encoder_attention_heads", 0);
ffn = gi("encoder_ffn_dim", 0);
C = gi("downsample_hidden_size", 0);
nmel = gi("num_mel_bins", 0);
const int64_t depth = gi("encoder_layers", 0);
const int64_t nw = gi("n_window", 0);
const int64_t nwi = gi("n_window_infer", 0);
const int64_t out = gi("output_dim", 0);
const int64_t kvh = gi("num_key_value_heads", heads);
const char* act = rad_meta_gets(m, "audio_config.activation_function", "");
hd = heads > 0 ? H / heads : 0;
f3 = ((((nmel + 1) / 2) + 1) / 2 + 1) / 2;
chunk_rows = post_cnn(2 * nw);
block = nw > 0 && nwi % (2 * nw) == 0 ? chunk_rows * (nwi / (2 * nw)) : 0;
/* What this tower does not carry is refused by name: a scaled embedding, grouped heads,
* an activation other than exact gelu, a projector into some other width. */
if (H <= 0 || heads <= 0 || hd * heads != H || ffn <= 0 || C <= 0 || nmel <= 0 ||
depth <= 0 || nw <= 0 || block <= 0 || kvh != heads || out != model_embd ||
std::strcmp(act ? act : "", "gelu") ||
rad_meta_geti(m, "audio_config.scale_embedding", 0)) {
fprintf(stderr, "radiance: qwen3asr: the container's audio_config is not the encoder "
"this plugin serves (d_model %lld, heads %lld, ffn %lld, channels %lld, "
"mel %lld, layers %lld, n_window %lld/%lld, output %lld for a %lld-wide "
"decoder, act %s)\n", (long long)H, (long long)heads, (long long)ffn,
(long long)C, (long long)nmel, (long long)depth, (long long)nw,
(long long)nwi, (long long)out, (long long)model_embd, act ? act : "");
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
P = ctx->max_audio_frames;
if (P % kMerge) return RAD_E_SHAPE;
R = P / kMerge;
const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
const char* T = "model.audio_tower";
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);
};
/* q, k and v into one projection, weights and biases alike: one GEMM a layer, and the
* attention reads three column slices of its row. */
auto wcat = [&](const char* dn, std::initializer_list<const char*> src,
std::initializer_list<int64_t> shp, RadWeightGroup g) -> rad_weight {
if (map_concat(b, dn, src, 0) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, AC, N, g);
};
w_c1 = w(nm.f("a.conv1.w"), nm.ckpt("%s.conv2d1.weight", T), {C, 1, 3, 3}, grp_model());
b_c1 = w(nm.f("a.conv1.b"), nm.ckpt("%s.conv2d1.bias", T), {C}, grp_model());
/* The two 480-channel kernels as the [cout, cin * 9] matrices their GEMMs read: the
* checkpoint's [C, C, 3, 3], row-major, is that matrix. */
w_c2 = w(nm.f("a.conv2.w"), nm.ckpt("%s.conv2d2.weight", T), {C, C * 9}, grp_model());
b_c2 = w(nm.f("a.conv2.b"), nm.ckpt("%s.conv2d2.bias", T), {C}, grp_model());
w_c3 = w(nm.f("a.conv3.w"), nm.ckpt("%s.conv2d3.weight", T), {C, C * 9}, grp_model());
b_c3 = w(nm.f("a.conv3.b"), nm.ckpt("%s.conv2d3.bias", T), {C}, grp_model());
w_co = w(nm.f("a.conv_out.w"), nm.ckpt("%s.conv_out.weight", T), {H, C * f3}, grp_model());
ln_w = w(nm.f("a.ln_post.w"), nm.ckpt("%s.ln_post.weight", T), {H}, grp_model());
ln_b = w(nm.f("a.ln_post.b"), nm.ckpt("%s.ln_post.bias", T), {H}, grp_model());
p1_w = w(nm.f("a.proj1.w"), nm.ckpt("model.multi_modal_projector.linear_1.weight"), {H, H}, grp_model());
p1_b = w(nm.f("a.proj1.b"), nm.ckpt("model.multi_modal_projector.linear_1.bias"), {H}, grp_model());
p2_w = w(nm.f("a.proj2.w"), nm.ckpt("model.multi_modal_projector.linear_2.weight"), {n_embd, H}, grp_model());
p2_b = w(nm.f("a.proj2.b"), nm.ckpt("model.multi_modal_projector.linear_2.bias"), {n_embd}, grp_model());
if (!w_c1 || !b_c1 || !w_c2 || !b_c2 || !w_c3 || !b_c3 || !w_co || !ln_w || !ln_b ||
!p1_w || !p1_b || !p2_w || !p2_b)
return RAD_E_INVAL;
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;
const char* S = "model.audio_tower.layers";
l.ln1w = w(nm.f("a.blk.%d.ln1.w", li), nm.ckpt("%s.%d.self_attn_layer_norm.weight", S, li), {H}, g);
l.ln1b = w(nm.f("a.blk.%d.ln1.b", li), nm.ckpt("%s.%d.self_attn_layer_norm.bias", S, li), {H}, g);
l.qkv_w = wcat(nm.f("a.blk.%d.qkv.w", li),
{ nm.ckpt("%s.%d.self_attn.q_proj.weight", S, li),
nm.ckpt("%s.%d.self_attn.k_proj.weight", S, li),
nm.ckpt("%s.%d.self_attn.v_proj.weight", S, li) }, {3 * H, H}, g);
l.qkv_b = wcat(nm.f("a.blk.%d.qkv.b", li),
{ nm.ckpt("%s.%d.self_attn.q_proj.bias", S, li),
nm.ckpt("%s.%d.self_attn.k_proj.bias", S, li),
nm.ckpt("%s.%d.self_attn.v_proj.bias", S, li) }, {3 * H}, g);
l.o_w = w(nm.f("a.blk.%d.o.w", li), nm.ckpt("%s.%d.self_attn.out_proj.weight", S, li), {H, H}, g);
l.o_b = w(nm.f("a.blk.%d.o.b", li), nm.ckpt("%s.%d.self_attn.out_proj.bias", S, li), {H}, g);
l.ln2w = w(nm.f("a.blk.%d.ln2.w", li), nm.ckpt("%s.%d.final_layer_norm.weight", S, li), {H}, g);
l.ln2b = w(nm.f("a.blk.%d.ln2.b", li), nm.ckpt("%s.%d.final_layer_norm.bias", S, li), {H}, g);
l.fc1_w = w(nm.f("a.blk.%d.fc1.w", li), nm.ckpt("%s.%d.fc1.weight", S, li), {ffn, H}, g);
l.fc1_b = w(nm.f("a.blk.%d.fc1.b", li), nm.ckpt("%s.%d.fc1.bias", S, li), {ffn}, g);
l.fc2_w = w(nm.f("a.blk.%d.fc2.w", li), nm.ckpt("%s.%d.fc2.weight", S, li), {H, ffn}, g);
l.fc2_b = w(nm.f("a.blk.%d.fc2.b", li), nm.ckpt("%s.%d.fc2.bias", S, li), {H}, g);
if (!l.ln1w || !l.ln1b || !l.qkv_w || !l.qkv_b || !l.o_w || !l.o_b || !l.ln2w ||
!l.ln2b || !l.fc1_w || !l.fc1_b || !l.fc2_w || !l.fc2_b)
return RAD_E_INVAL;
}
/* ---- activations: the convolutions' planes at their own widths, (time, mel, channel)
* with the channel innermost; the rest at R rows. */
/* The second and third convolutions' outputs are their GEMMs' [positions, C], which is the
* same bytes as [time rows, width * C]: the next unfold reads them that way. */
const int64_t w2 = (nmel + 1) / 2;
w3 = (w2 + 1) / 2;
b_s1 = decl_b(b, nm.f("a.s1"), RAD_BF16, {P / 2, w2 * C});
b_u = decl_b(b, nm.f("a.unfold"), RAD_BF16, {P / 4 * w3, 9 * C});
b_s2 = decl_b(b, nm.f("a.s2"), RAD_BF16, {P / 4 * w3, C});
b_s3 = decl_b(b, nm.f("a.s3"), RAD_BF16, {R * f3, C});
b_uo = decl_b(b, nm.f("a.unfold_out"), RAD_BF16, {R, f3 * C});
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_pos = decl_b(b, nm.f("a.pos"), RAD_BF16, {R, H});
b_qkv = decl_b(b, nm.f("a.qkv"), RAD_BF16, {R, 3 * H});
b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H});
b_f = decl_b(b, nm.f("a.f"), RAD_BF16, {R, ffn});
b_p1 = decl_b(b, nm.f("a.p1"), RAD_BF16, {R, H});
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd});
/* The first convolution has one input channel, so it is direct: nine taps are too narrow
* a K for a GEMM. */
auto conv1 = [&](rad_weight wt, rad_weight bias) {
return RAD_OP(b, "conv2d",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("width", nmel),
RAD_INT("cin", 1), RAD_INT("cout", C), RAD_INT("kh", 3),
RAD_INT("kw", 3), RAD_INT("stride", 2), RAD_INT("pad", 1),
RAD_INT("cu_div", 1), RAD_INT("valid_stride", 1),
RAD_STR("dtype", "bf16"), RAD_INT("t_last", 1),
RAD_STR("act", "gelu")),
RAD_WEIGHTS(wt, bias));
};
auto gemm_m = [&](int64_t rows, int64_t Nn, int64_t K, const char* act_, rad_weight wt,
rad_weight bias) {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn), RAD_INT("K", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", act_)),
RAD_WEIGHTS(wt, bias));
};
auto gemm = [&](int64_t Nn, int64_t K, const char* act_, rad_weight wt, rad_weight bias) {
return gemm_m(R, Nn, K, act_, wt, bias);
};
auto unfold = [&](int64_t rows, int64_t width, int64_t kh, int64_t kw, int64_t stride,
int64_t pad, int64_t cu_div, int tlast) {
return RAD_OP(b, "conv2d_unfold",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width),
RAD_INT("cin", C), RAD_INT("kh", kh), RAD_INT("kw", kw),
RAD_INT("stride", stride), RAD_INT("pad", pad),
RAD_INT("cu_div", cu_div), RAD_INT("valid_stride", cu_div),
RAD_INT("t_last", tlast), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
auto lnorm = [&](rad_weight wt, rad_weight bias) {
return RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H), RAD_F64("eps", 1e-5),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(wt, bias));
};
op_c1 = rw(b, conv1(w_c1, b_c1), {}, {b_s1});
op_u2 = rw(b, unfold(P / 2, w2, 3, 3, 2, 1, 2, 1), {b_s1}, {b_u});
op_c2 = rw(b, gemm_m(P / 4 * w3, C, 9 * C, "gelu", w_c2, b_c2), {b_u}, {b_s2});
op_u3 = rw(b, unfold(P / 4, w3, 3, 3, 2, 1, 4, 1), {b_s2}, {b_u});
op_c3 = rw(b, gemm_m(R * f3, C, 9 * C, "gelu", w_c3, b_c3), {b_u}, {b_s3});
/* The 7680 -> 1024 linear as a 1 x f3 convolution over the frequency axis, unfolded: its
* rows are (channel, frequency), the checkpoint's own [H, C * f3] column order. */
op_uo = rw(b, unfold(R, f3, 1, f3, 1, 0, kMerge, 0), {b_s3}, {b_uo});
op_co = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", H),
RAD_INT("K", C * f3), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_co)),
{b_uo}, {b_x});
op_pos = rw(b, RAD_OP(b, "seg_sinusoid",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
RAD_INT("period", chunk_rows),
RAD_F64("max_timescale", 10000.0),
RAD_INT("cu_div", kMerge), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{}, {b_pos});
op_add_pos = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_x, b_pos}, {b_x});
for (Layer& l : L) {
l.op_ln1 = rw(b, lnorm(l.ln1w, l.ln1b), {b_x}, {b_h});
l.op_qkv = rw(b, gemm(3 * H, H, "none", l.qkv_w, l.qkv_b), {b_h}, {b_qkv});
l.op_attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, R), 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", R),
RAD_INT("cu_div", kMerge),
RAD_INT("block", block)),
RAD_NOWEIGHTS),
{b_qkv}, {b_att});
/* The output projection and the second FFN linear add the residual in their epilogue,
* rounded after the biased product as the reference's two tensors are. */
l.op_o = rw(b, gemm(H, H, "none", l.o_w, l.o_b), {b_att, b_x}, {b_x});
l.op_ln2 = rw(b, lnorm(l.ln2w, l.ln2b), {b_x}, {b_h});
l.op_fc1 = rw(b, gemm(ffn, H, "gelu", l.fc1_w, l.fc1_b), {b_h}, {b_f});
l.op_fc2 = rw(b, gemm(H, ffn, "none", l.fc2_w, l.fc2_b), {b_f, b_x}, {b_x});
}
op_ln = rw(b, lnorm(ln_w, ln_b), {b_x}, {b_h});
op_p1 = rw(b, gemm(H, H, "gelu", p1_w, p1_b), {b_h}, {b_p1});
op_p2 = rw(b, gemm(n_embd, H, "none", p2_w, p2_b), {b_p1}, {b_out});
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "audio";
e.modalities = RAD_MM_AUDIO;
e.patch_dim = nmel;
e.merge = kMerge;
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: 3 convolutions of %lld channels over %lld mel bins, %lld "
"layers of %lld (%lld heads x %lld), ffn %lld, attention in blocks of %lld "
"rows; %lld frames a pass (%lld s) -> %lld rows of %lld",
(long long)C, (long long)nmel, (long long)depth, (long long)H,
(long long)heads, (long long)hd, (long long)ffn, (long long)block,
(long long)P, (long long)kPassSeconds, (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 % kMerge || 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 / kMerge;
const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel);
/* Plane 1: whether a frame takes part in the convolution (item.cpp). */
const RadOperand valid = praw(batch->enc_coord + Pn, RAD_I32, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_c1, Pn, frames, RAD_W(w_c1), cu, valid, brows(b_s1, Pn / 2),
RAD_W(b_c1));
const int64_t n2 = Pn / 4 * w3, n3 = Rn * f3;
RAD_ISSUE_N(c, op_u2, Pn / 2, brows(b_s1, Pn / 2), cu, valid, brows(b_u, n2));
RAD_ISSUE_N(c, op_c2, n2, brows(b_u, n2), RAD_W(w_c2), RAD_W(b_c2), RAD_NONE,
brows(b_s2, n2));
RAD_ISSUE_N(c, op_u3, Pn / 4, brows(b_s2, n2), cu, valid, brows(b_u, n3));
RAD_ISSUE_N(c, op_c3, n3, brows(b_u, n3), RAD_W(w_c3), RAD_W(b_c3), RAD_NONE,
brows(b_s3, n3));
RAD_ISSUE_N(c, op_uo, Rn, brows(b_s3, n3), cu, RAD_NONE, brows(b_uo, Rn));
RAD_ISSUE_N(c, op_co, Rn, brows(b_uo, Rn), RAD_W(w_co), brows(b_x, Rn));
RAD_ISSUE_N(c, op_pos, Rn, cu, brows(b_pos, Rn));
RAD_ISSUE_N(c, op_add_pos, Rn, brows(b_x, Rn), brows(b_pos, Rn), brows(b_x, Rn));
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.op_ln1, Rn, brows(b_x, Rn), RAD_W(l.ln1w), RAD_W(l.ln1b),
brows(b_h, Rn));
RAD_ISSUE_N(c, l.op_qkv, Rn, brows(b_h, Rn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
brows(b_qkv, Rn));
RAD_ISSUE_N(c, l.op_attn, Rn, bcol(b_qkv, 0, H, Rn), bcol(b_qkv, H, H, Rn),
bcol(b_qkv, 2 * H, H, Rn), cu, brows(b_att, Rn));
RAD_ISSUE_N(c, l.op_o, Rn, brows(b_att, Rn), RAD_W(l.o_w), RAD_W(l.o_b),
brows(b_x, Rn), brows(b_x, Rn));
RAD_ISSUE_N(c, l.op_ln2, Rn, brows(b_x, Rn), RAD_W(l.ln2w), RAD_W(l.ln2b),
brows(b_h, Rn));
RAD_ISSUE_N(c, l.op_fc1, Rn, brows(b_h, Rn), RAD_W(l.fc1_w), RAD_W(l.fc1_b), RAD_NONE,
brows(b_f, Rn));
RAD_ISSUE_N(c, l.op_fc2, Rn, brows(b_f, Rn), RAD_W(l.fc2_w), RAD_W(l.fc2_b),
brows(b_x, Rn), brows(b_x, Rn));
}
RAD_ISSUE_N(c, op_ln, Rn, brows(b_x, Rn), RAD_W(ln_w), RAD_W(ln_b), brows(b_h, Rn));
RAD_ISSUE_N(c, op_p1, Rn, brows(b_h, Rn), RAD_W(p1_w), RAD_W(p1_b), RAD_NONE,
brows(b_p1, Rn));
RAD_ISSUE_N(c, op_p2, Rn, brows(b_p1, Rn), RAD_W(p2_w), RAD_W(p2_b), RAD_NONE,
brows(b_out, Rn));
}
};
/* ============================== THE DECODER ============================== */
struct Layer {
AttnBF16 attn;
MlpBF16 mlp;
};
struct Model {
Names nm{""};
Geom g{};
rad_kvgroup kv = 0;
rad_buf b_x = 0, b_h = 0, b_q = 0, b_k = 0, b_v = 0, b_attn = 0;
rad_buf b_gate_up = 0, b_ffn = 0, b_hout = 0, b_logits = 0;
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
bool media = false;
MediaRows mrows{};
AudioTower aud{};
std::vector<Layer> layers;
};
static Model g_model[MAX_RANKS];
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;
Model& m = g_model[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
Geom& g = m.g;
Names& nm = m.nm;
/* Plain Qwen3: every layer full attention, no sliding window, plain RMS gains. */
if (meta->n_expert > 0 || rad_meta_geti(meta, "text_config.use_sliding_window", 0)) {
fprintf(stderr, "radiance: qwen3asr: the decoder has experts or a sliding window; this "
"plugin serves the dense, full-attention Qwen3 decoder\n");
return RAD_E_UNSUPPORTED;
}
if (!(g.theta > 0.0f)) g.theta = (float)rad_meta_getf(meta, "rope_parameters.rope_theta", 0.0);
if (!(g.theta > 0.0f) || g.head_dim <= 0 || g.n_head % g.n_head_kv) {
fprintf(stderr, "radiance: qwen3asr: the decoder's geometry is incomplete (theta %g, "
"head_dim %lld, heads %lld over %lld)\n", (double)g.theta,
(long long)g.head_dim, (long long)g.n_head, (long long)g.n_head_kv);
return RAD_E_INVAL;
}
g.wadd = 0.0f;
g.wadd_qk = 0.0f;
RadKVGroupDecl fd{};
fd.kind = RAD_KV_FULL;
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
fd.n_head_kv = g.n_head_kv;
fd.head_dim = g.head_dim;
m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
g.kv_dtype = rad_dtype_name(fd.dtype);
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, g.q_dim()});
m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, g.kv_dim()});
m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, g.kv_dim()});
m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, g.q_dim()});
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
/* ---- the vocabulary edges, both row-sharded; the head is tied to the embedding
* (tie_word_embeddings, and the checkpoint ships no lm_head.weight). */
const char* pre = "model.language_model";
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.norm.weight", pre)));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("%s.embed_tokens.weight", pre)));
m.w_tok = 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.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.w_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.op_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.w_tok)),
{}, {m.b_x});
/* The encoder's rows, over the lookup and before its reduction (MediaRows says why). */
m.media = AudioTower::present(meta) && ctx->max_audio_frames > 0;
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
if (g.world > 1)
m.op_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.b_x}, {m.b_x});
AttnBF16::Wire aw{};
aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn;
MlpBF16::Wire mw{};
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_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];
const char* lp = "model.language_model.layers";
const long long li = (long long)l;
AttnBF16::Src as{};
as.norm = nm.ckpt("%s.%lld.input_layernorm.weight", lp, li);
as.q = nm.ckpt("%s.%lld.self_attn.q_proj.weight", lp, li);
as.k = nm.ckpt("%s.%lld.self_attn.k_proj.weight", lp, li);
as.v = nm.ckpt("%s.%lld.self_attn.v_proj.weight", lp, li);
as.q_norm = nm.ckpt("%s.%lld.self_attn.q_norm.weight", lp, li);
as.k_norm = nm.ckpt("%s.%lld.self_attn.k_norm.weight", lp, li);
as.o = nm.ckpt("%s.%lld.self_attn.o_proj.weight", lp, li);
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv));
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv, aw, as));
MlpBF16::Src ms{};
ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", lp, li);
ms.gate = nm.ckpt("%s.%lld.mlp.gate_proj.weight", lp, li);
ms.up = nm.ckpt("%s.%lld.mlp.up_proj.weight", lp, li);
ms.down = nm.ckpt("%s.%lld.mlp.down_proj.weight", lp, li);
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms));
}
m.op_final_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", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.w_out_norm)),
{m.b_x}, {m.b_h});
m.op_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.b_h}, {m.b_hout});
m.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),
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.w_lm_head)),
{m.b_hout}, {m.b_logits});
rad_note(b, "rank %d/%d: %lld decoder layers, n_head=%lld n_head_kv=%lld head_dim=%lld "
"n_ff=%lld theta=%g vocab=[%lld,%lld), lm_head tied",
g.rank, g.world, (long long)g.n_layer, (long long)g.n_head, (long long)g.n_head_kv,
(long long)g.head_dim, (long long)g.n_ff, (double)g.theta, (long long)g.vocab_off,
(long long)(g.vocab_off + g.n_vocab));
/* The audio tower last, so its activations share the arena with every buffer above. */
if (m.media) RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = g_model[rad_rank(c)];
/* An encoder pass runs the audio tower and nothing else (RadBatch::enc). */
if (batch->enc) {
m.aud.step(c, batch);
return;
}
const int64_t T = batch->n_tok;
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
m.mrows.step(c, batch, m.b_x, T);
if (m.op_embed_ar)
RAD_ISSUE_N(c, m.op_embed_ar, T * m.g.n_embd, brows(m.b_x, T), RAD_NONE);
for (const Layer& l : m.layers) {
l.attn.step(c, batch);
l.mlp.step(c, batch);
}
RAD_ISSUE(c, m.op_final_norm, brows(m.b_x, T), RAD_W(m.w_out_norm), brows(m.b_h, T));
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
}
}
/* Before declare: the frames a pass carries, so the core sizes the audio encoder's pass. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
if (AudioTower::present(meta)) out->audio_frames = AudioTower::frames_for(meta);
return RAD_OK;
}
/* Qwen3-ASR's audio format (RadAudioFormat): its clip markers; its transcription turn, which is
* the reference processor's chat template with the request's prompt as the system text and the
* clip as the user turn; and the forced-language prefix the model was trained with,
* "language <Name><asr_text>". The language names are the reference processor's
* LANGUAGE_CODE_TO_NAME. */
static const char* const kLanguages[] = {
"ar", "Arabic", "yue", "Cantonese", "zh", "Chinese", "cs", "Czech",
"da", "Danish", "nl", "Dutch", "en", "English", "fil", "Filipino",
"fi", "Finnish", "fr", "French", "de", "German", "el", "Greek",
"hi", "Hindi", "hu", "Hungarian", "id", "Indonesian", "it", "Italian",
"ja", "Japanese", "ko", "Korean", "mk", "Macedonian", "ms", "Malay",
"fa", "Persian", "pl", "Polish", "pt", "Portuguese", "ro", "Romanian",
"ru", "Russian", "es", "Spanish", "sv", "Swedish", "th", "Thai",
"tr", "Turkish", "vi", "Vietnamese",
};
static const RadAudioFormat* audio_format(const RadModelMeta* meta) {
if (!AudioTower::present(meta)) return nullptr;
static const RadAudioFormat f = {
(uint32_t)sizeof(RadAudioFormat),
"<|audio_start|>",
"<|audio_end|>",
"<|im_start|>system\n{context}<|im_end|>\n<|im_start|>user\n{audio}<|im_end|>\n"
"<|im_start|>assistant\n{language}",
"language {language}<asr_text>",
"<asr_text>",
"language ",
kLanguages,
(uint32_t)(sizeof(kLanguages) / sizeof(kLanguages[0]) / 2),
};
return &f;
}
} /* namespace qwen3asr_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PLUGIN(qwen3asr_bf16, "qwen3asr", "", "0.1.0",
"Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder; bf16 weights "
"and activations")
RAD_ARCH_PROBE(qwen3asr_bf16)
RAD_ARCH_AUDIO_FORMAT(qwen3asr_bf16)
#endif
+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/qwen4exp_fp8 -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/qwen4exp_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(qwen4exp_fp8 LANGUAGES CXX)
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/qwenimage21 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(qwenimage21 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwenimage21 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwenimage21.cpp)
File diff suppressed because it is too large. Load diff
+27 -6
View File
@@ -1,5 +1,5 @@
#!/bin/sh
# build.sh -- configure and build.
# build.sh -- configure, build and run the fast tests.
#
# With no arguments the build configures itself: if hipcc is present and a card can be enumerated,
# device kernels are compiled for that card's architecture, and otherwise the host backend is
@@ -10,19 +10,29 @@
# have. Which of them actually get kernels is decided by the kernel libraries present; each one
# declares the architectures it serves.
#
# ./build.sh configure + build + test
# ./build.sh configure + build + the fast tests (ctest -L fast)
# ./build.sh -c wipe the build directory first
# ./build.sh --no-hip force the host backend even where hipcc exists
# ./build.sh --asan AddressSanitizer + UBSan, host backend, in build-asan/
# ./build.sh --tsan ThreadSanitizer, host backend, in build-tsan/
# ./build.sh --debug CMAKE_BUILD_TYPE=Debug
# ./build.sh -b DIR build in DIR instead of build/ (or build-asan/, build-tsan/)
#
# The other tiers (docs/GUIDE.md §1.3): ctest --test-dir build -LE 'gpu|oot' for everything that
# runs without a card, plain ctest --test-dir build for everything.
set -e
BUILD=build
BUILD=
CLEAN=0
SAN=
CMAKE_ARGS=""
while [ $# -gt 0 ]; do
case "$1" in
-c|--clean) rm -rf "$BUILD" ;;
-c|--clean) CLEAN=1 ;;
--no-hip) CMAKE_ARGS="$CMAKE_ARGS -DRAD_WITH_HIP=OFF" ;;
--asan) CMAKE_ARGS="$CMAKE_ARGS -DRAD_ASAN=ON" ;;
--asan) SAN=asan ;;
--tsan) SAN=tsan ;;
--debug) CMAKE_ARGS="$CMAKE_ARGS -DCMAKE_BUILD_TYPE=Debug" ;;
-b) shift; BUILD="$1" ;;
*) echo "build.sh: unknown option $1" >&2; exit 2 ;;
@@ -30,6 +40,17 @@ while [ $# -gt 0 ]; do
shift
done
# A sanitised build gets a directory of its own, so it never reconfigures the normal tree. Host
# code only: device kernels are not sanitised, and a sanitised engine is not one to serve from.
case "$SAN" in
asan) CMAKE_ARGS="$CMAKE_ARGS -DRAD_ASAN=ON -DRAD_TSAN=OFF -DRAD_WITH_HIP=OFF"
BUILD=${BUILD:-build-asan} ;;
tsan) CMAKE_ARGS="$CMAKE_ARGS -DRAD_TSAN=ON -DRAD_ASAN=OFF -DRAD_WITH_HIP=OFF"
BUILD=${BUILD:-build-tsan} ;;
*) BUILD=${BUILD:-build} ;;
esac
[ "$CLEAN" = 1 ] && rm -rf "$BUILD"
cmake -S . -B "$BUILD" -G Ninja $CMAKE_ARGS
cmake --build "$BUILD" -j"$(nproc)"
ctest --test-dir "$BUILD" --output-on-failure
ctest --test-dir "$BUILD" -L '^fast$' -j8 --no-tests=error --output-on-failure
+85 -99
View File
@@ -1,19 +1,10 @@
# rad_add_plugin / rad_hipify -- the ONE definition of how a source file becomes a loadable
# radiance plugin, shared by the in-tree build and by an out-of-tree one.
# rad_add_plugin / rad_hipify -- the single definition of how sources become a loadable radiance
# plugin, shared by the in-tree and out-of-tree builds.
#
# This file is included from two different worlds. The top-level CMakeLists.txt includes it while
# the ABI target is being built in this very tree; the installed radiance-config.cmake includes it
# after pulling the same target in as an import from radianceTargets.cmake. It is a file of its own
# because a third party who runs find_package(radiance) needs it as much as the tree does: the
# single call that decides what a plugin links, where it lands, and how its device sources reach
# hipcc cannot be a private detail of radiance's own build, or every out-of-tree plugin has to
# reinvent it by reading our CMakeLists.
#
# Copying the function into the package config instead is the worse option. Two copies of the rule
# that fixes the plugin layout drift, and the drift does not present as a build error: it presents
# as a plugin that loads in the tree it was written in and is silently absent everywhere else,
# because it was emitted one directory level away from where the loader scans. So there is one
# file, and both worlds include it.
# The top-level CMakeLists.txt includes it while building the ABI target; the installed
# radiance-config.cmake includes it after importing that target from radianceTargets.cmake. Keep
# one copy: a drifted duplicate would emit plugins where the loader does not scan, with no build
# error.
#
# What an includer must set first:
# radiance::abi the ABI interface target -- an in-tree ALIAS, or the imported target
@@ -22,35 +13,30 @@
# RAD_GPU_TARGETS the offload architectures this build targets. Any gfx name; a library that
# serves only some of them narrows the list with rad_plugin_gpu_targets()
# RAD_HIP_RUNTIME the amdhip64 library a device plugin links
# The top-level file sets all five as it detects them. radiance-config.cmake sets all five from what
# the install recorded, so that an out-of-tree plugin is compiled against the same runtime as the
# engine that will dlopen it; its GPU targets are the consumer's to name (-DRAD_GPU_TARGETS) and
# default to the ones the engine was built for.
# The top-level file sets all five as it detects them. radiance-config.cmake sets them from what the
# install recorded, so an out-of-tree plugin uses the engine's runtime; its GPU targets default to
# the engine's and can be overridden with -DRAD_GPU_TARGETS.
#
# And one an includer MAY set:
# Optional:
# RAD_PLUGIN_INSTALL_HOME the $RADIANCE_HOME `cmake --install` puts a plugin under. Unset in
# the tree, where a plugin installs beside the engine under the same prefix;
# radiance-config.cmake sets it to the found installation's home, so a plugin
# built out of tree installs where that engine's loader scans.
# the tree (plugins install beside the engine under the same prefix);
# radiance-config.cmake sets it to the found installation's home.
# RAD_HIP_VOPD_REPEATABLE ON when the HIP compiler's VOPD pairing is repeatable; unset is OFF,
# which turns the pairing off on LLVM 24 (rad_hip_repeatable, below).
# For CMAKE_INSTALL_DATADIR, below. Idempotent, and included here rather than left to the includer
# because this file is what needs it: a consumer project has no reason to have included it, and the
# install destination would silently become the relative path "radiance/kernels" -- interpreted
# against the prefix, so it lands in <prefix>/radiance/kernels and the loader never looks there.
# For CMAKE_INSTALL_DATADIR. Included here because a consumer may not have; without it plugins
# would install to <prefix>/radiance/<kind>, where the loader never looks.
include(GNUInstallDirs)
# What radiance's own tree sets for every plugin it builds, for a plugin built on its own against
# an installed radiance: C++20, and a build type that optimises when none was asked for. Every
# plugin directory in radiance's tree opens with the same few lines a third party's does --
# The tree's defaults for a plugin built standalone: C++20 and an optimised build type when none was
# given. Every plugin directory, in tree or not, opens with:
#
# if(NOT COMMAND rad_add_plugin) # on its own, not inside radiance's tree
# if(NOT COMMAND rad_add_plugin) # standalone, not inside radiance's tree
# cmake_minimum_required(VERSION 3.21)
# project(mylib LANGUAGES CXX) # CXX HIP for device code
# find_package(radiance REQUIRED)
# rad_plugin_defaults()
# endif()
#
# -- so the libraries radiance ships are built and installed exactly as anyone else's are.
macro(rad_plugin_defaults)
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 20)
@@ -61,10 +47,24 @@ macro(rad_plugin_defaults)
endif()
endmacro()
# A kernel, architecture or quantiser plugin: one call, so a new plugin is a directory and a line.
# `kind` is the $RADIANCE_HOME directory the engine scans for it. An installed plugin must name one
# of the three the engine scans -- a misspelt kind would build, install, and never be loaded; the
# test plugins, which are never installed (RAD_PLUGIN_INSTALL below), use directories of their own.
# CMake leaves two HIP rule variables empty. Without CMAKE_DEPFILE_FLAGS_HIP, Ninja records no
# header as a dependency of a .hip object (`ninja -t deps` shows #deps 0), so editing a header
# relinks a plugin around stale objects, which can leave engine and plugin disagreeing on a
# signature. Without CMAKE_INCLUDE_SYSTEM_FLAG_HIP, SYSTEM include directories reach .hip sources as
# `-I` and their warnings become ours. A macro, so the variables land in the caller's scope; values
# already set are kept.
macro(rad_hip_rule_fixes)
if(NOT CMAKE_DEPFILE_FLAGS_HIP)
set(CMAKE_DEPFILE_FLAGS_HIP "-MD -MT <DEP_TARGET> -MF <DEP_FILE>")
endif()
if(NOT CMAKE_INCLUDE_SYSTEM_FLAG_HIP)
set(CMAKE_INCLUDE_SYSTEM_FLAG_HIP "-isystem ")
endif()
endmacro()
# Build a kernel, architecture or quantiser plugin. `kind` is the $RADIANCE_HOME directory the engine
# scans for it; an installed plugin must use one of the three, or it would never be loaded. Test
# plugins (never installed, see RAD_PLUGIN_INSTALL) use their own directories.
function(rad_add_plugin name kind)
cmake_parse_arguments(P "" "" "SOURCES;HIP_SOURCES;LIBS;INCLUDES;GPU_TARGETS" ${ARGN})
if((NOT DEFINED RAD_PLUGIN_INSTALL OR RAD_PLUGIN_INSTALL) AND
@@ -75,37 +75,29 @@ function(rad_add_plugin name kind)
endif()
set(srcs ${P_SOURCES})
if(P_HIP_SOURCES AND NOT RAD_HIP_FOUND)
# Said rather than skipped in silence: a kernel library whose device sources were dropped
# builds, installs, and has rows with no kernels behind them.
# Warn: a kernel library without its device sources still installs, with rows that have no
# kernels behind them.
message(WARNING
"rad_add_plugin(${name}) was given HIP_SOURCES but this radiance has no device build "
"(RAD_HIP_FOUND is OFF), so they are left out. A radiance configured without ROCm, or on a "
"machine with no card and no -DRAD_GPU_TARGETS, has none.")
endif()
if(RAD_HIP_FOUND AND P_HIP_SOURCES)
# The HIP language has to be enabled by the project that owns the target, not by us:
# enable_language() is a project-scope decision and a library file that reaches out and enables
# a language behind the consumer's back changes their compiler set. In-tree the top-level file
# does it. Out-of-tree it is one line in the consumer's CMakeLists, and the failure without it
# is "Cannot find source file" or a source compiled as C++ with --offload-arch on the command
# line, neither of which names the missing enable_language(HIP).
# The owning project must enable HIP itself; enable_language() is project scope and changes the
# consumer's compiler set. Without it CMake fails with errors that do not name the cause, so
# check here.
get_property(_rad_langs GLOBAL PROPERTY ENABLED_LANGUAGES)
if(NOT "HIP" IN_LIST _rad_langs)
message(FATAL_ERROR
"rad_add_plugin(${name}) was given HIP_SOURCES but the HIP language is not enabled in this "
"project. Add `enable_language(HIP)` after project() -- radiance cannot enable it for you, "
"because the language a project compiles in is the project's own decision.")
"project. Add `enable_language(HIP)` after project(); the project must enable it itself.")
endif()
set_source_files_properties(${P_HIP_SOURCES} PROPERTIES LANGUAGE HIP)
# EVERY DEVICE SOURCE NAMES ITS OWN COMPILATION UNIT ID, from the plugin's name and the
# source's path inside the plugin's directory. Left to clang, the ID is a hash of the absolute
# input path, the output path and the command line, so one source built in two directories --
# the tree and an out-of-tree build of the same plugin -- gets two IDs. The ID becomes a symbol
# (__hip_cuid_<hash of it>) whose name is not of fixed length, and a longer one shifts the code
# object's read-only data and with it every PC-relative address .text forms into it: the same
# instructions, different bytes. Named from what identifies the unit and nothing about where it
# was built, the ID is the same wherever the plugin is built and still differs between any two
# sources, which is the property clang needs of it.
# Each device source gets a compilation unit ID from the plugin name and its relative path.
# clang's default hashes absolute paths and the command line, and the resulting
# __hip_cuid_<hash> symbol has variable length, which shifts read-only data and every
# PC-relative address into it. A location-independent ID keeps code objects identical wherever
# the plugin is built, while still unique per source.
foreach(src ${P_HIP_SOURCES})
get_filename_component(_rad_abs "${src}" ABSOLUTE)
file(RELATIVE_PATH _rad_rel "${CMAKE_CURRENT_SOURCE_DIR}" "${_rad_abs}")
@@ -118,11 +110,8 @@ function(rad_add_plugin name kind)
add_library(${name} MODULE ${srcs})
target_link_libraries(${name} PRIVATE radiance::abi ${P_LIBS})
target_include_directories(${name} PRIVATE ${P_INCLUDES})
# The build tree is a working $RADIANCE_HOME, and it is created here rather than assumed: a
# LIBRARY_OUTPUT_DIRECTORY that does not exist is created by the build, but the engine scans the
# directory at startup and an out-of-tree build with one kernel plugin and no architectures would
# otherwise have no architectures/ for the scan to find and fail at the scan rather than at the
# lookup.
# The build tree is a working $RADIANCE_HOME. Create the kind directory at configure time: the
# engine scans it at startup, and a missing one fails the scan rather than the lookup.
file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/${kind})
set_target_properties(${name} PROPERTIES
PREFIX "" OUTPUT_NAME "${name}"
@@ -131,16 +120,9 @@ function(rad_add_plugin name kind)
rad_hipify(${name} ${P_GPU_TARGETS})
endif()
# ...and so is the install tree, in the same shape. RAD_DEFAULT_HOME points at
# <prefix>/share/radiance, and without this rule nothing is installed into it, so the only
# $RADIANCE_HOME that works is somebody's build directory. A plugin built and not installed is the
# same class of defect as a plugin built and never loaded.
#
# RAD_PLUGIN_INSTALL is the opt-out, and it has exactly one in-tree user: core/plugin/testplugin
# (set in core/CMakeLists.txt, where that subtree is reached), whose .so files exist to be
# refused, to conflict, to report a stale ABI and to stand in for a card. Shipping those
# into a prefix would put rows into a real installation that implement nothing -- see the same
# argument, made about the build tree, in core/plugin/testplugin/CMakeLists.txt.
# The install tree has the same shape, under RAD_DEFAULT_HOME (<prefix>/share/radiance).
# RAD_PLUGIN_INSTALL=OFF opts out; its only in-tree user is core/plugin/testplugin (set in
# core/CMakeLists.txt), whose plugins must never reach a real installation.
if(NOT DEFINED RAD_PLUGIN_INSTALL)
set(RAD_PLUGIN_INSTALL ON)
endif()
@@ -154,29 +136,39 @@ function(rad_add_plugin name kind)
endif()
endfunction()
# Mark a target's device sources as HIP and pin the architecture. -ffp-contract=off is mandatory
# for any quantised cross-rank op: two ranks see the two dequantised products in the opposite order
# and contracting either into an FMA makes them disagree by ~1 ULP, which breaks the
# replicated-state invariant.
# Repeatable device code on LLVM 24. ROCm 10.1's clang (AMD clang 24) is not deterministic: the
# post-RA VOPD pairing pass (GCNVOPDUtils.cpp) caches each load's transitive load dependencies, a
# fusion adds edges behind that cache, and which entries are cached follows the iteration order of
# a pointer-keyed set. So two compiles can pair differently, giving different .text and speed.
# LLVM 22 (ROCm 7.2) has no such cache and is repeatable.
#
# The docker image patches libLLVM to drop the cache after every fusion
# (docker/llvm-vopd-pairing.patch) and sets RAD_HIP_VOPD_REPEATABLE=ON. Any other LLVM 24 gets VOPD
# disabled, which costs 1.4 to 3.5% on the fp8 prefill tiles.
function(rad_hip_repeatable tgt)
if(CMAKE_HIP_COMPILER_ID STREQUAL "Clang" AND CMAKE_HIP_COMPILER_VERSION VERSION_GREATER_EQUAL 24
AND NOT RAD_HIP_VOPD_REPEATABLE)
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:-mllvm=-amdgpu-enable-vopd=false>)
endif()
endfunction()
# Set a target's HIP architectures and device flags. -ffp-contract=off is mandatory for any
# quantised cross-rank op: two ranks sum the dequantised products in opposite order, and an FMA on
# either side makes them differ by ~1 ULP, breaking the replicated-state invariant.
function(rad_hipify tgt)
# Any extra arguments are the architectures THIS target is compiled for, which is how a library
# that serves one generation stays out of the build for the others. With none given the target
# takes the whole build's list.
# Extra arguments narrow the architectures for this target; default is RAD_GPU_TARGETS.
set(arches "${ARGN}")
if(NOT arches)
set(arches "${RAD_GPU_TARGETS}")
endif()
set_target_properties(${tgt} PROPERTIES HIP_ARCHITECTURES "${arches}")
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:-ffp-contract=off>)
# THE DEVICE OPTIMISATION LEVEL, ON THE TARGET, because CMake supplies no usable one for HIP:
# depending on its version CMAKE_HIP_FLAGS_<CONFIG> is empty -- the kernels compile at -O0 with
# asserts live -- or the host-style '-O2 -g'. The top-level CMakeLists.txt sets the variables for
# the tree; a plugin built out of tree gets the same levels here, after the toolchain's flags on
# the command line, so they win. A later -O replaces an earlier one but a later -O does not undo
# -g, so the levels outside Debug end in -g0: device debug info costs compile time, inhibits
# scheduling, and makes an out-of-tree build's code objects differ from the tree's. NDEBUG is not
# decoration on the device: an assert is a hostcall, and the engine's queues provide no hostcall
# buffer (docs/PLUGIN.md). RAD_HIP_FLAGS_<CONFIG> overrides, as it does in the tree.
# Device optimisation level, set on the target because CMake's CMAKE_HIP_FLAGS_<CONFIG> is,
# depending on version, empty (-O0 with asserts) or host-style '-O2 -g'. These come after the
# toolchain flags, so they win. Non-Debug levels end in -g0 because a later -O does not undo -g,
# and device debug info slows compiles, inhibits scheduling and changes code objects. NDEBUG is
# required: a device assert is a hostcall, and the engine's queues have no hostcall buffer
# (docs/PLUGIN.md). RAD_HIP_FLAGS_<CONFIG> overrides, as in the tree.
foreach(cfg DEBUG RELEASE RELWITHDEBINFO MINSIZEREL)
if(RAD_HIP_FLAGS_${cfg})
set(lvl "${RAD_HIP_FLAGS_${cfg}}")
@@ -190,23 +182,17 @@ function(rad_hipify tgt)
separate_arguments(lvl)
target_compile_options(${tgt} PRIVATE "$<$<AND:$<COMPILE_LANGUAGE:HIP>,$<CONFIG:${cfg}>>:${lvl}>")
endforeach()
# AN UNCOMPRESSED FAT BINARY, because the engine reads the code object out of it itself
# (core/device/aql_code.cpp) and refuses a compressed one -- at the first launch, as a kernel
# failure. A toolchain or a CMAKE_HIP_FLAGS that turns compression on is overridden here.
# Uncompressed fat binary: the engine extracts the code object itself (core/device/aql_code.cpp)
# and rejects a compressed one at first launch. This overrides any toolchain setting.
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:--no-offload-compress>)
target_link_options(${tgt} PRIVATE $<$<LINK_LANGUAGE:HIP>:--no-offload-compress>)
target_link_libraries(${tgt} PRIVATE ${RAD_HIP_RUNTIME})
rad_hip_repeatable(${tgt})
endfunction()
# Narrow RAD_GPU_TARGETS to the architectures ONE kernel library actually serves. A library states
# its coverage as regular expressions -- "^gfx12" for a generation, "^gfx1201$" for a single chip --
# and gets back the intersection with what this build is targeting, which may be empty.
#
# AN EMPTY RESULT IS NOT AN ERROR. It means this build's cards are served by some other kernel
# library, and the right response is for the plugin to skip itself and say so, leaving the rest of
# the tree to configure normally. A kernel library that failed the configure instead would make
# every card it does not cover an unbuildable project rather than an unserved one -- which is the
# opposite of what a plugin boundary is for.
# Narrow RAD_GPU_TARGETS to the architectures one kernel library serves, given as regular
# expressions ("^gfx12" for a generation, "^gfx1201$" for a chip). The result may be empty; the
# plugin should then skip itself with a message rather than fail the configure.
function(rad_plugin_gpu_targets out)
set(keep "")
foreach(t ${RAD_GPU_TARGETS})
+19 -38
View File
@@ -1,9 +1,7 @@
# radiance-config.cmake -- what `find_package(radiance)` gets.
#
# This file exists so that a plugin can be built from a repository that is not this one, against
# the installed ABI headers rather than a copy of abi/ taken out of a checkout, and installed into
# the $RADIANCE_HOME the engine's loader scans. A plugin boundary that can only be crossed from
# inside the tree is not a plugin boundary; it is a build layout.
# Lets a plugin in another repository build against the installed ABI headers and install into
# the $RADIANCE_HOME the engine's loader scans.
#
# What a consumer gets:
# radiance::abi the header-only ABI target -- abi/ plus RAD_DEFAULT_HOME,
@@ -21,49 +19,39 @@
# target (arch/common/ is installed under ${RADIANCE_INCLUDE_DIR}/arch)
# RAD_GPU_TARGETS the offload architectures a device plugin is compiled for: the
# consumer's -DRAD_GPU_TARGETS when given, else the ones radiance was
# built for. The engine itself runs on every AMD GPU family, so a
# plugin for a card the engine's build machine does not have is
# ordinary.
# built for. The engine itself runs on every AMD GPU family.
@PACKAGE_INIT@
# The ABI version is not written here; it is read out of abi/rad_abi.h at radiance's
# configure time and carried through. One number, in the header the loader compares against, so a
# bump cannot be half-applied.
# Read from abi/rad_abi.h at radiance's configure time, so the header stays the single source.
set(RADIANCE_ABI_VERSION @RAD_ABI_VERSION@)
set_and_check(RADIANCE_INCLUDE_DIR "@PACKAGE_RAD_INCLUDE_RELDIR@")
# $RADIANCE_HOME, as a CACHE PATH so that a consumer building a plugin for an installed engine can
# see and override where it is going in ccmake, and so that `cmake --install` on their project puts
# the .so where this engine's loader will scan for it. Computed from PACKAGE_PREFIX_DIR rather than
# baked absolute, so a relocated prefix still answers correctly.
# $RADIANCE_HOME as a CACHE PATH, so a consumer can override it. Relative to PACKAGE_PREFIX_DIR, so
# a relocated prefix still resolves.
set(RADIANCE_HOME "@PACKAGE_RAD_HOME_RELDIR@" CACHE PATH
"\$RADIANCE_HOME of the radiance installation found by find_package(radiance)")
set(RADIANCE_KERNELS_DIR "${RADIANCE_HOME}/kernels")
set(RADIANCE_ARCHITECTURES_DIR "${RADIANCE_HOME}/architectures")
set(RADIANCE_QUANTIZERS_DIR "${RADIANCE_HOME}/quantizers")
# Where rad_add_plugin installs: under the home of the engine this consumer built against, which is
# the one whose loader will scan it. A consumer installing somewhere else -- a home of its own on
# $RADIANCE_HOME's search path, say -- sets this.
# Where rad_add_plugin installs: the home of the engine this consumer built against. Override to
# install elsewhere.
set(RAD_PLUGIN_INSTALL_HOME "${RADIANCE_HOME}" CACHE PATH
"the \$RADIANCE_HOME rad_add_plugin installs plugins under")
# The imported targets: radiance::abi, and whatever else the export set carries.
# The imported targets, including radiance::abi.
include("${CMAKE_CURRENT_LIST_DIR}/radianceTargets.cmake")
# The device-build facts rad_add_plugin needs, recorded at radiance's configure time and replayed
# here under the same names the in-tree build uses -- one function body, one set of variable names.
# A plugin compiled for a different gfx target than the engine that dlopens it is not a link error
# and not a load error: it is a kernel that launches and computes garbage, so the target list is
# carried across rather than re-detected.
# Device-build facts rad_add_plugin needs, recorded at radiance's configure time under the in-tree
# names. The target list is carried over, not re-detected: a plugin built for the wrong gfx target
# loads and launches, then computes garbage.
set(RAD_HIP_FOUND @RAD_HIP_FOUND@)
if(NOT DEFINED RAD_GPU_TARGETS)
set(RAD_GPU_TARGETS "@RAD_GPU_TARGETS@")
endif()
# The HIP runtime and headers as radiance found them, and where this machine has them when the
# recorded path is not here -- a consumer building against an installed radiance on another
# machine, or inside a container whose ROCm sits elsewhere.
# The HIP runtime and headers as radiance found them, or this machine's copies when the recorded
# path does not exist (another machine, or a container with ROCm elsewhere).
set(RAD_HIP_RUNTIME "@RAD_HIP_RUNTIME@")
if(RAD_HIP_FOUND)
if(NOT EXISTS "${RAD_HIP_RUNTIME}")
@@ -81,24 +69,17 @@ if(RAD_HIP_FOUND)
set_property(TARGET radiance::abi APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${_rad_rocm_inc}")
set_property(TARGET radiance::abi APPEND PROPERTY INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${_rad_rocm_inc}")
endif()
# The HIP compiler's two omissions the tree fixes for itself (CMakeLists.txt): no depfile, so no
# header is a dependency of a .hip object, and no system-include flag. Only where unset.
if(NOT CMAKE_DEPFILE_FLAGS_HIP)
set(CMAKE_DEPFILE_FLAGS_HIP "-MD -MT <DEP_TARGET> -MF <DEP_FILE>")
endif()
if(NOT CMAKE_INCLUDE_SYSTEM_FLAG_HIP)
set(CMAKE_INCLUDE_SYSTEM_FLAG_HIP "-isystem ")
endif()
endif()
# The build-tree $RADIANCE_HOME for the CONSUMER's build, so that a freshly built out-of-tree plugin
# can be exercised with RADIANCE_HOME=<their build dir>/radiance_home before it is installed --
# which is how an in-tree plugin is tested, and there is no reason the boundary should make that
# harder. Not forced: a consumer who has already set it keeps their own.
# The consumer's build-tree $RADIANCE_HOME, so a plugin can be tested with
# RADIANCE_HOME=<build dir>/radiance_home before install. A value already set is kept.
if(NOT DEFINED RAD_PLUGIN_OUT)
set(RAD_PLUGIN_OUT ${CMAKE_BINARY_DIR}/radiance_home)
endif()
include("${CMAKE_CURRENT_LIST_DIR}/RadAddPlugin.cmake")
if(RAD_HIP_FOUND)
rad_hip_rule_fixes()
endif()
check_required_components(radiance)
Loaded 100 of 927 files, more files were not shown because too many files have changed in this diff. Show more