Compare commits

..
278 Commits
Author SHA1 Message Date
aneinanderandClaude Opus 5.5 b52a180141 libxe2: split the ESIMD GEMV along K for wide outputs too
gemv_esimd_splits only aimed at ~8192 threads, so an output wide enough to
fill the card at one split (the lm head, N = 248320) ran S = 1: each thread
walked all of K alone and was latency-bound at ~350-530 GB/s. The split now
also keeps K a thread at ~1024 or less.

rad-kbench, B65, cold weights (us):
  logits_gemm n_vocab 248320 n_embd 5120 M=1  4710 -> 4255   M=4 4674 -> 4289
  logits_gemm n_vocab 248320 n_embd 4096 M=1  3652 -> 3418
  gemm_nt N 34816 K 5120 M=1                   621 ->  605
other gemm_nt shapes unchanged. kbench 1989/1989 replay, model checks pass;
Qwen3.8-27B greedy output unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:20:16 +01:00
aneinanderandClaude Opus 5.5 eda5b01708 kbench: calibrate ungated on a backend without gates
The launch floor and the read-bandwidth probe needed a gate and gave up
without one, which withheld every device timing on SYCL once its gates
were removed (8931aae8). Both now run ungated there: the read probe's
launches move megabytes each, so the queue stays ahead of the host; the
floor then includes the host's submission time where that is longer,
and the header says so. Gated backends are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:01:16 +01:00
aneinanderandClaude Opus 5.5 8931aae8b2 sycl: keep the device out of plain system memory
On kernel 7.0 the xe driver can oops (drm_pagemap_zdd_destroy from
__drm_pagemap_migrate_to_ram) when the CPU faults on a page its shared
virtual memory had migrated into VRAM. The backend reached plain system
memory in several ways; each now uses USM the runtime knows:

- RAD_MEM_HOST_PINNED/_MAPPED are sycl::aligned_alloc_host, not
  posix_memalign + prepare_for_device_copy. O_DIRECT cannot target those
  pages (EFAULT), so DirectFile bounces such transfers through an 8 MiB
  buffer. The 27B load is not slower (10.8 s read, disk-bound).
- Copies with a pageable side are staged through a host-USM bounce,
  synchronously (rare: startup and tests). The ranged copy stages a host
  range list even when its source is on the card, and refuses a pageable
  destination, which its kernel would write.
- scatter_rows' bad-index flag is host USM, not shared.
- Gates are gone (the documented state): a spinning kernel never sees a
  host store to host USM, and a device flag opened by a copy from another
  queue deadlocks behind copies queued past the gate. rad-kbench times
  ungated; the gate tests skip on backends without gates.

Checked: device_test (sycl) 70 cases, 0 failed; rad-kbench fixture
1989/1989; 27B int4 chat output byte-identical (c4c5ba5e727c) at
30.6 tok/s; no xe messages in the kernel log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:56:05 +01:00
aneinanderandClaude Opus 5.5 4b70a96378 Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port
102 upstream commits. Nine conflicts resolved. Fork side of the merge:
- libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it
  from libavx and libref; the device libraries now each carry it).
- plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table
  regenerated, kTableAbi = 42.

Known before the PR: arch_test (MTP lint and pinned graph hashes for
qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:06:17 +01:00
aneinanderandClaude Opus 5.5 ca793ea99a libxe2: gate_quant_fp8 (output gate, multiply and quantiser in one launch)
The gated attention block (qwen35 family, Qwen4exp, lfm2, krea2) takes
gate_quant_fp8 when a library declares it, otherwise sigmoid + mul (+
quant_act_fp8). One sub-group per (row, 128-column group), the sigmoid
rounded to bf16 before the multiply, xe2_sigmoid's float exp with the
double one near a bf16 tie (always double under XE2_EXACT): byte-identical
to libxe2's sigmoid -> mul -> quant_act_fp8, which the row declares as its
chain (.replaces) for rad-kbench's fusion oracle. out_bf16 may alias x.

xe2_sigmoid and xe2_mul get [M, n] shape hooks (libr4d's unary/binary),
which the oracle sizes the chain's temporaries from.
XE2_NO_FUSED_GATE=1 hides the row for an A/B.

kbench: fixture 2144/2144; fusion oracle 40/40 byte-identical on the 9B,
the 27B, and the 9B under XE2_EXACT. 27B int4, spec off: 646 -> 630
launches a decode step, same output hash, decode 30.6 tok/s either way
(the saving is ~16 dispatch gaps, ~0.3%), prefill 2.4k 1387 -> 1400 tok/s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:09:46 +01:00
Code000andClaude Opus 5.5 b8bca7885a sched: --draft-suffix on, SuffixDecoding as a step selector on the MTP chain
After each commit the scheduler looks in the sequence's own prompt and output
for the latest earlier occurrence of its last --draft-suffix-min-match tokens;
the next step then verifies what followed it (up to --draft-suffix-max rows,
cut where the product of the follower frequencies falls under
--draft-suffix-min-score) in place of the head's draft. The verify window
becomes the larger of the two while the head keeps its own rounds. A sequence
whose history ended in a recurring pattern is not issued ahead, since the step
is built after the commit where the lookup can read the committed end.

It works with the fixed MTP chain, with --draft-depth adaptive and with
--draft-verify traversal. A suffix chain carries no coupled row
(Request::draft_suffix): the sampler binds none of the head's staged states to
its rows, so each row is the target's plain draw and the rows are leaves of the
traversal walk; mtp_rrs_test checks the law with a negative control that fails.
--draft-verify block is refused. The window is at most 7 rows on Flash-Next (the
delta-net fold's register window).

On Flash-Next IQR-V4 (TP2) on our branch, window 7 on chain 3 with coupling:
+1.4% overall, +2.9% on repetitive tasks, +11% on quoting, free chat unchanged;
beside adaptive depth +0.2% [-1.0, +1.5] overall, code +1.0%. Off by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:11:30 +01:00
Code000andClaude Opus 5.5 e78d484e60 spec: --draft-depth adaptive stops the MTP chain inside the step
A coupled serial chain stops as soon as the product of the head's own
probabilities along it falls under --draft-depth-stop (default 0.85; top or
path statistic, at most --draft-depth-max rounds, at least --draft-depth-min),
and the next verify carries exactly the drafts made. The decision trails the
chain by --draft-depth-lag rounds (default 1), so the host's readback of one
state row and its issue of the next round hide behind the running round.

The rule reads the draft's laws and the tokens drawn before the one a decision
admits, never the target and never the admitted token, so the row-wise and the
traversal verify stay exact; mtp_rrs_test checks it by chi-square with two rules
that must fail (one reads the admitted draft's own mass, one the target).

It excludes --draft-window adaptive, which picks the next step's window from
earlier acceptance and step cost and so is a second controller on the same chain.

The recorded-pass cache holds 48 passes instead of 24: every row count is its
own pass shape and the adaptive chain makes more of them than 24 hold.

On Flash-Next IQR-V4 (TP2) on our branch, against chain 3 with coupling and
traversal: +3.0% tok/s [+1.0, +5.0] over 117 paired requests; the 48-entry cache
is +1.7% [+1.1, +2.3] of that for this mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:11:30 +01:00
Code000andClaude Opus 5.5 d0fd4aa1bb spec: --draft-verify token|block|traversal for the coupled MTP chain
--draft-coupling verifies each row of the chain on its own. Two lossless
sequence-level verifiers accept more drafts from the same chain: Block
Verification (arXiv 2403.10444) decides the whole chain at once, Traversal
Verification (arXiv 2505.12398) walks a path from its last draft back to its
first. --draft-verify token (default) is the engine as it was; block switches
the coupling on; traversal needs it and is refused otherwise.

Block: the sampler marks the consecutive bound rows of a request with the
block's length (RadMtpCoupleState::blk) and mtp_couple_verify decides the block
on the workgroup of its round-1 row, every FP64 sum a fixed lane tree so the
result is the host reference's bit for bit. The wide-plane serial helper is a
kernel of its own, which leaves couple_verify without scratch.

Traversal: a new op mtp_trav_verify takes the step's topology (parent row, draft
token per row) and decides a request on one workgroup, 0 bytes of scratch: the
target's law as integer masses of a fixed-point exponential, the walk in FP64.
Its header and kernel also handle nodes with several children (Gumbel-top-k and
RheoSampling siblings); the serial head here drafts one, so that part has no
producer yet and is covered by the tests only.

RadMtpCoupleState grows from 152 to 168 bytes (nkids, scheme, blk), so
RAD_ABI_VERSION is 41.

Exactness: mtp_block_test enumerates the draft tree of a toy model and runs
chi-square over the real verify code; mtp_rrs_test runs chi-square and an
exhaustive enumeration of the walk (worst |joint - P| 7e-14) with negative
controls that fail; spechub_device_test compares the device rows with the host
rows. Measured on Qwen3.8-Flash-Next IQR-V4 (TP2, MTP chain 3, coupling) on our
branch: about +1% tok/s with traversal, +4.6% at T 1.0 top_k 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:49:45 +01:00
Deadcode 9b6eba80c6 arch/common: the clamp refusal reads the codebook-down flag (#503)
The W6NL change renamed down_w5_fp8 to down_codebook_fp8, and the Ling-3.0-flash change, merged
after it, still read the old name, so no target that includes rad_block_moe_fp8.h built. A W6NL
down projection takes the W5NL route (rotated E4M3 codes), which no clamp writes, so a clamped
layer is refused before either.

Reported by DokterSmol.
2026-11-17 21:25:44 +01:00
Code000andClaude Opus 5.5 e912b04f5a libr4d: skip the scalar-cache invalidate behind chained waits in kernels that make no scalar load after the wait
r4d_chain_wait() ends in r4d_chain_acquire(): the agent-scope fence for the
vector caches and s_dcache_inv for the scalar data cache. The latter is needed
only by a kernel that reads, behind the wait, something an earlier launch of the
chain wrote through a scalar load (a value all lanes share). s_dcache_inv also
costs the refetch of every kernel argument afterwards, on every wave.

New r4d_chain_wait_vec() waits with the fence alone. It is used at 41 wait
sites in 20 units (the IQR m16/m64, w2a8/w4a8/w8a8/bf16/i8_kpar and fp8a8
GEMMs, the activation quantisers, the attention decode and paged-window
kernels, hc_*, the norm and activation kernels of r4d_model_bf16, rowtopk,
ple_gate, prefetch, dflash_conv, the all-reduce). A wait site keeps the full
flush when any instantiation of its kernel has a scalar load after the acquire.
-DR4D_CHAIN_SCINV_ALWAYS puts the instruction behind every wait again.

tests/chain_scalar_audit.py (ctest chain_scalar_audit, label slow, no card)
keeps this honest: it compiles every chained HIP unit to gfx1201 assembly with
the flags of compile_commands.json and fails when a chained kernel without
s_dcache_inv has a scalar load, from a base other than the kernarg segment
s[0:1], behind its global_inv. Building the audit with
-DR4D_CHAIN_SURVEY_NO_SCALAR (every wait skips the flush) flags 1123 kernels,
so the check does detect the real cases; as committed it reports 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:43:11 +01:00
Code000andClaude Opus 5.5 ca7a7212ec qwen4exp: verify/decode pass launch order, prefetch width, chain polling, turnover slots
Lossless (no kernel arithmetic or operand change): the router weight is read beside the mixer
all-reduce; k/v projections before q|gate; the indexer's keys behind the attention launches within
the exact bound; verify-height prefetch at 32 workgroups (`prefetch` takes an optional `blocks`
param) and the shared down arm before the routed down from 2 rows (kVerifyRows); chain waits poll by
grid size (R4D_CHAIN_TINY/SMALL/MID); the mover's kept-free turnover slots follow the swaps the
engine asked for (MoverConfig::turnover_adaptive) instead of a fixed 640.

arch_test: new a_flash_next_decode_step_orders_its_small_launches; the pinned graph fingerprints and
step hashes of qwen4exp_fp8 move (re-pinned). place_test: the adaptive turnover. r4d_selftest: the
`blocks` param of prefetch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:33:07 +01:00
Code000andClaude Opus 5.5 946a6f9e2b aql: the prefetch stream takes the half-lap system acquire too
The expert-prefetch stream (rad_xp_stream_create, agent_only) downgraded every system-scope
acquire to agent scope because it reads no host-written data. Its kernel arguments are
host-written into its own ring, though: after a wrap, an agent-scope acquire leaves the slot's
old line in the L2 and the launch runs with the previous lap's arguments. Keep the exemption
for host writes and epochs; take the system acquire on the ring's half lap (one in 2048
prefetch launches). New device test: launches on a prefetch stream across three ring laps read
their own arguments -- 8709 of 12805 stale without the fix, 0 with it.

Fixes #491

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:32:20 +01:00
Code000andClaude Opus 5.5 01f08152dc aql: no packet-header acquire on chained launches whose kernels acquire for themselves
A chained kernel that has lost its barrier bit is launched ahead of the kernels
it depends on and reads nothing until its prologue wait has passed, where it
acquires itself (and, since the previous change, empties the scalar cache). The
acquire in its packet header runs when the packet processor launches the kernel,
before the launches in front have written, so it guards nothing the kernel
reads and only holds the packet processor: on an R9700, 2.1 us per launch with
the agent-scope acquire against 1.2 us without.

rad_kernel_chain may now answer 2 (libr4d's rows do): the chained forms' acquire
covers everything they read. The loader records it (KernelRow::chain_fenced);
the engine asks rad_dev_chain_infer(2) when chaining pays and every row that can
chain, from every loaded library, says 2 (one row answering 1 keeps the acquire
on all chained packets). The backend then issues a chained dispatch without its
barrier bit with no header acquire, live and in played passes, unless the ring,
the host epoch or a copy asks for one; releases, barrier packets, plain kernels
and the prefetch stream are untouched, and a card with its arguments in VRAM
and no HDP flush register keeps the acquire. RADIANCE_AQL_CHAIN_FENCE=1 puts it
back on every chained launch.

Qwen3.8-Flash-Next IQR-V4, TP2, MTP chain 3 with coupling, ABBA over 2 pairs:
+0.75% tok/s [0.73, 0.78], all 156 texts identical. The three device tests
added before now also run with the packets unacquired, and a shipped-plugins
test requires libr4d's chained rows to answer 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:21:59 +01:00
Code000andClaude Opus 5.5 304597970f libr4d: register form of the fused all-reduce writes with a wake store into the idle peer path
ar_hc_write / ar_gather_hc_write get a register form when every thread owns at most one
16-byte word (up to 12 rows of 2560, P2P instances): y, inj and h are loaded into registers
before the first atomic and not re-read after the handshake; LDS-only barriers instead of
__syncthreads; the flag poll is a relaxed system-scope load (the push check with retry behind
a system acquire stays). Before waiting on its chain turn each block stores one word into the
peer's memory: the P2P path between the cards goes idle after ~20 us, and the next store then
becomes visible ~4 us later; the wake store hides that. Wire format, flags, counters, check word
and arithmetic unchanged, mixable with the plain kernels on one instance; host-mailbox twins
keep the plain kernels. The chained wait the forms sit behind ends in r4d_chain_acquire (the
previous commit's s_dcache_inv). 63 new r4d_selftest cases: register form against plain form,
byte-identical, M = 1..8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:01:12 +01:00
Code000andClaude Opus 5.5 cfec01ec8d qsa: skip score/select where no attention reads them; select once per pass below the exact bound
Architecture-only (no kernel, op schema or graph change). The attention block tells the indexer
whether it reads the selection (AttnGatedFP8::qsa_use): dense steps (<= 1024 tokens of context)
issue no query norm, qsa_score or qsa_select; single-row-per-sequence steps under the exact bound
read the block table; multi-row steps under the bound select once per pass (the selection is
layer-invariant there, every complete block in block order) and the other QSA layers reuse it.
Block keys and tail run every step. The exact host bound (RadBatch::kv_used_max_h) decides which
side of the bound a step is on and keys the pass. RADIANCE_DEBUG_QSA_EAGER=1 restores the old
issue pattern.

arch_test: the pinned step hashes of qwen4exp_fp8 move (graphs unchanged) and two tests pin the
new issue pattern; ref_test pins the equalities it rests on (qsa_select below the bound).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:41:16 +01:00
Constantin 315aea7db9 test(libr4d): benchmark W6NL expert down against W5NL 2026-11-17 18:35:11 +01:00
Constantin d1b5a45e31 feat(qwen4exp): support U4 gate with W6NL down experts 2026-11-17 18:35:11 +01:00
John 590dbcc178 fix(minimaxh3): keep mixed-site encoder operands host-readable 2026-11-17 18:28:50 +01:00
keptn42 73a284d799 data/recipes: ling-3.0-flash-iq8r-w4nl64
The recipe of Ling-3.0-flash and its fine-tunes on an IQ8R trunk: the trunk lines of
ling-3.0-tiny-iq8r.recipe, the 512 routed experts of a layer as rotated four-bit codes into the w4nl
codebook at an E4M3 scale a (row, 64 of K). An empty CALIB directory rounds the experts to nearest
with a scale search.

Ling-3.0-flash-Sante converted with it (experts rounded to nearest) on four R9700 against the bf16
original, 80 MT-Bench questions, 42,767 tokens: mean KL 0.00461, 99th percentile 0.0494, top token
the same 98.0 %.

the_ling_flash_iq8r_w4nl64_recipe_decides_the_model_it_was_written_for reads the recipe as it ships
over the plugin's names: the IQ8R trunk, the w4nl64 experts, the shared down projection, the f32
casts and the weights kept bf16. recipe_test: 14 of 14 cases; ctest -LE 'gpu|oot': 181 of 181 (3
skipped).
2026-11-17 18:26:13 +01:00
keptn42 33f9644701 bailing_hybrid: Ling-3.0-flash on an IQ8R trunk
Flash clamps its SwiGLU in its last layers (routed 35-41, shared 34-41). The plugin and MoeFP8's
check for int8 activations refused a rotated int8 trunk over them, since the int8 gated products
had no clamped form. With the previous commit they have one, so both refusals go. MoeFP8
keeps the refusal for a W5NL down projection: no clamp writes its rotated E4M3 codes.

flash_iq8r_clamps_its_gated_products_then_quantises_them_rotated declares flash's IQ8R container
at one, two and four ranks, every rank: 15 swiglu_step, each followed by had_quant_act_i8g reading
its plane at group 128; against the same container without the clamp lists 15 ops more and 15
gated_had_quant_i8g fewer, and no unrotated int8 or E4M3 quantiser. The steps run lint-clean. It
fails without the previous commit. The graph hashes of the bf16 and four-bit containers stay the
same. bailing_hybrid_arch_test: 9 of 9 pass; ctest -LE 'gpu|oot': 181 of 181 (3 skipped).
2026-11-17 18:26:13 +01:00
keptn42 2e558e2dcc arch/common: a clamped gated product writes rotated int8 codes
GateQuantFP8's clamped branch (swiglu_clamped, swiglu_step) refused an output of rotated int8
codes, since its quantiser was the unrotated quant_act_i8g. A down projection stored at i8a8h reads
rotated codes, so a model that clamps its SwiGLU had no form with int8 activations.

The branch now picks had_quant_act_i8g for rotated int8 codes, at the consumer's group (128, or 256
through had_quant_act_iq8r for IQ8R), the quantiser the rotated trunk's other inputs use. The clamp
still writes the bf16 plane first: one launch more than the unclamped gated_had_quant_i8g, in the
clamped layers only. E4M3 and plain int8 outputs are unchanged.
2026-11-17 18:26:13 +01:00
Constantin 79ac2bd50d Add Muse Glimmer IQ4R-V4 with quantized DFlash2 2026-11-17 18:24:56 +01:00
forest 742191a244 dashboard: fix dashboard not supporting reverse proxy via rel path 2026-11-17 18:20:56 +01:00
Code000andClaude Opus 5.5 73f94b4345 engine: do not load the vision tower in a build without a media decoder
With --mm-max-patches auto, a container that carries a vision tower gets 16384
patches and the tower on the card. A build without a media decoder
(RAD_WITH_FFMPEG off: mm::decoder_available() is false) refuses every media
part -- MultimodalBridge::accepts() says no -- so the tower can never run a
pass; it only holds card memory the routed experts are short of. On
Qwen3.8-Flash-Next at tp 2 on two R9700 that is 857 MiB a rank, about 800
expert units a rank, which the routed GEMMs then read from the pinned pool over
the link instead of from the card.

The automatic choice is now 0 in such a build, with an info line and a
decision-table entry that say why; the audio encoder's automatic size already
follows --mm-max-patches 0. An explicit --mm-max-patches N still loads the
tower. The flag's help and the GUIDE row say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:19:58 +01:00
Code000andClaude Opus 5.5 7bd195d394 vram: charge the runtime's resident queue scratch to the card budget
Once a kernel with a private segment has been dispatched (rad_step_advance has
544 bytes a lane), the HSA runtime hands its queue scratch memory and keeps it:
about +114 MiB on a card after the first speculative step, +150 MiB with a
larger segment, with or without HSA_NO_SCRATCH_RECLAIM. The VRAM budget does
not count it, so a serving process was left with only 27-65 MiB free after its
first speculative steps -- a thin margin for any kernel that later takes a
bigger private segment (the runtime then faults the queue with OUT_OF_RESOURCES
instead of failing the load).

The backend now reports rad_dev_resident_scratch_bytes(): 5 MiB per CU (160 MiB
on an R9700, which reports 32), over the measured 114-150 MiB, and 0 on the
host backend and on unified memory. The engine puts it into VramFacts::
queue_scratch, and the budget charges it with the hardware queues (the
resolver, vram_budget_need, and the report line).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:18:56 +01:00
Code000andClaude Opus 5.5 b2228c176b sched: size the pinned staging ring for 16 builds instead of 3
A speculative step makes four builds (history pass, draft rounds 2-3, the
next verify). With room for three, the next verify's reserve() waited in
retire_oldest() on one of the current step's draft-pass uploads, so
issue-ahead returned only ~0.1-0.5 ms before the card needed the step and
every host hiccup became card idle.

The ring now holds kRingBuilds = 16 worst-case builds (it must stay below
kFlights). On Qwen3.8-Flash-Next IQR-V4 (MTP chain 3) step_next returns
11-13 ms ahead, and the card's idle time before the verify drops from 317 to
74 us (from 1243 to 470 us mean under host load). The pinned host ring grows
from 753 KiB to 3.9 MiB; the device slab is unchanged. Outputs are identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:18:02 +01:00
Code000andClaude Opus 5.5 8dcd8fdcd7 place: --expert-pin-top cuts fractional profile shares correctly
pin_hot() set the pin threshold to the share at the cut minus 1.0, which
assumes integer gaps between shares. A profile's per-layer shares are
fractions in [0, 1] (xs_profile_load divides by the layer's total), so the
threshold went negative and every resident expert counted as pinned at any
--expert-pin-top, leaving the heat engine no slab slots (decode -4..9% on
Qwen3.8-Flash-Next IQR-V4 against the same run without pinning).

The threshold is now the share just below the hot set (-1 when the hot set
is every expert, so everything pins). A test with fractional shares pins the
hottest quarter and fails without the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:17:08 +01:00
Code000andClaude Opus 5.5 8f2e511fcc aql: flush the host data path before every doorbell; empty the scalar cache behind a chained wait
Two latent bugs that the packet processor's acquire (about 0.9 us a launch) has
been hiding by timing.

1. Kernel arguments and the chain record are written into VRAM through the BAR,
   and the card's host data path keeps such a write until it is flushed. Nothing
   ordered that against the doorbell (the sfence only orders the CPU's own
   buffers). A kernel the card starts a microsecond or two after its doorbell
   reads the slot as the launch one lap of the ring before left it: old
   arguments, or no chain record, in which case the launch counts nothing and
   the chained launch behind it waits for good. The backend now stores to the
   card's HDP flush register (HSA_AMD_AGENT_INFO_HDP_FLUSH) in front of every
   doorbell, in publish() and in a played pass's ring(). Without a register
   (the argument ring in host memory, or a driver that gives none) nothing
   changes, and a warning says so at startup.

2. rad_chain_wait()/r4d_chain_wait() end in an agent-scope acquire fence, which
   invalidates the vector caches. A load whose address every lane shares is a
   scalar load, served from the scalar data cache, and nothing but the packet
   processor's acquire (which runs when the kernel is launched, before the
   launch in front has written) empties that. A chained kernel can therefore
   read a stale scale, count or activation from the arena address an earlier
   launch read. The waits now issue s_dcache_inv behind the fence
   (r4d_chain_acquire in libr4d, chain_kernel.h in the core's blit kernels).

Evidence on an R9700 with the packet acquire left as it is: a probe of
1024-block readers behind a chained wait saw a stale shared value in 1 launch
of 1800 without the s_dcache_inv and in none with it; card-side copies issued
one by one with 50 us between them stalled the queue in its first lap, four
runs in four, and six runs in nine of 300000 back to back ended with a unit
moved by another launch's arguments, when the packets went without their
acquire and without the flush, and in none with the flush.

New device tests: a chained reader sees a shared value the launch in front
wrote, a chained launch reads its own arguments after the ring has lapped, and
a copy issued after a pause finds the record written for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:16:12 +01:00
DokterSmol 78ad2096a3 docs: lfm3 IQ8R container 2026-11-17 18:12:32 +01:00
DokterSmol bfadfbee76 tests: lfm3 int8 and IQ8R trunks
Declare and step of the IQ8R container, the plain int8 trunk beside the
bf16 one, the trunks the plugin refuses, and the shipped recipe's
container against the bf16 container of the same tiny checkpoint.
2026-11-17 18:12:32 +01:00
DokterSmol 1f50d235ed recipes: lfm3-1.7b-iq8r
LFM3-1.7B with every trunk linear but the attention gate as IQ8R (rotated
int8, a u8 scale per 256 of K under a bf16 scale a row), round to nearest.
The gate, the short convolution, the norms, the embedding and the tied
lm_head stay bf16.
2026-11-17 18:12:32 +01:00
DokterSmol df453ff434 lfm3_bf16: int8 and IQ8R trunks
The trunk's format is read off layer 0's first linear, as lfm2_bf16 reads it:
plain bf16 runs as before; an int8 weight (i8a8, or IQ8R at i8a8h) gives the
four activations int8 code pairs at the weights' scale group and each linear
quantises its input. Every linear of the trunk must have that format; the gate
stays bf16 in every container; a block-fp8 or narrower trunk is refused by
name. The lm_head is declared at its stored codes.
2026-11-17 18:12:32 +01:00
DokterSmol eaa14ac72a lfm3_bf16: linears through LinearFP8
Every linear but the attention gate is declared and issued through the shared
LinearFP8 (arch/common/rad_fp8.h), as lfm2_bf16's are, over four ActFP8
activations whose bf16 planes are the buffers the graph already had. A bf16
container declares the same weights and the same gemm_nt ops as before; the
name maps move into LinearFP8::declare. The gate keeps its own declaration:
its weight is gate_proj's rows repeated (RAD_MAP_ROWS). No change in what a
bf16 model computes.
2026-11-17 18:12:32 +01:00
DokterSmol ceb92ea701 docs: lfm3 in the README's model table; libr4d README names the h128/gqa4 window rows
The README's table gains a row for LFM3-1.7B (bf16, converted from the checkpoint as it ships).
libr4d's README said of head_dim 128 at 4 queries a KV head that there is no prefill row; the
window rows added for LFM3 serve that geometry past the decode band, and the line now says so.
2026-11-17 18:12:32 +01:00
DokterSmol 2e0945c106 docs: lfm3 raw prompts and BOS
The checkpoint's tokenizer adds no BOS to a raw prompt, and without it some first tokens put
the model where bf16 departs from float32. Say so among the traps, with the two ways round it.
2026-11-17 18:12:32 +01:00
DokterSmol 6b96295f54 tests: lfm3's config.json through the checkpoint reader
The rotary per attention class with the full layers' partial factor, the
window, the layer list and the booleans arrive as the keys the plugin reads;
the typed rope_theta is the default, which the plugin does not read.
2026-11-17 18:12:32 +01:00
DokterSmol 29057b0c6b lfm3_bf16: the sandwich joins as norm_add_norm where a library serves it
A layer's post norm, residual add and feed-forward norm are one launch, and so
are its feed-forward's post norm, add and the next layer's input norm: 50
launches for the chain's 144 at 24 layers. The op is asked for with
rad_op_declared, as gemma4 does; libref and libavx do not carry it and run the
rmsnorm / add / rmsnorm chain, as does the last layer's feed-forward. The arm's
output has its own buffer, since a join reads it beside x and writes h.
2026-11-17 18:12:32 +01:00
DokterSmol 09ad42e633 libhalo selftest: rope_rows and rmsnorm_rows give rope's and rmsnorm's bytes
At LFM3's shapes: the per-head norm over head_dim-wide rows, and the full
layers' partial rotary (64 of 128 at theta 1e6 on the head ladder) with
positions past 250000.
2026-11-17 18:12:32 +01:00
DokterSmol 1f00224501 libhalo: windowed attention at head_dim 128 with 4 queries per kv head, and the row-form names of rope and rmsnorm
What LFM3 needs on gfx1151 beyond the rows libhalo has. The window kernel is
instantiated at (128, 4) as in libr4d: the decode leg keeps q_len <= 16 and
every longer q_len, windowed or not, lands on the new pair. rope_rows and
rmsnorm_rows are registered under their row-form names and launched as rope
and rmsnorm, as libavx and libref register them, so a plugin written for
libr4d's row forms resolves on this part instead of falling to the host.

Emulator cases as libr4d's (split verify, ragged window, fp8, non-causal with
a missing block, WMMA prefill with and without the window) and selftest
launches.
2026-11-17 18:12:32 +01:00
DokterSmol 21c4544b61 tests: lfm3 resumed from the prefix cache equals a cold run
The full-attention layers resume from cached blocks, the sliding layers from a
window snapshot and the convolutions from the same checkpoint slot; under
--prefix-resume exact and nearest the reply and its probabilities equal a cold
run's.
2026-11-17 18:12:32 +01:00
DokterSmol f5d2d74a20 docs: the lfm3 section of ARCHITECTURES.md
Geometry, the traps (the gate is one sigmoid, two rotaries, the window on the
sliding layers only, four norms a layer), what is refused, and which kernels
serve it.
2026-11-17 18:12:32 +01:00
DokterSmol 6997f8da14 tests, docs: lfm3 in the family tests, with its golden and declare cases
A tiny LFM3 (conv, full attention, conv, sliding attention; window 8, conv
width 7) joins the engine tests every family runs: the golden against the
reference implementation, chunking and batching, libavx against libref,
decode against prefill, concurrent requests and speculation by prompt lookup.
Its golden is made by mklfm3golden.py from the modelling code LiquidAI ships
with the checkpoint, since transformers has no LFM3 class.

arch_test covers what the plugin declares for each layer kind, what it
refuses, and a step through both attention groups.
2026-11-17 18:12:32 +01:00
DokterSmol 6c7bcefefa arch: lfm3_bf16, LiquidAI's LFM3 at bf16
LFM2's hybrid with sliding-window attention layers as a third kind,
sandwich norms, a partial rotary on the head ladder for the full layers
and a sigmoid gate per query head on the attention output. The gate is
computed at the output's width (gate_proj's rows repeated by the name
map), so it needs no op beyond gemm_nt, sigmoid and mul. One rank, bf16
linears; everything else is refused by name.
2026-11-17 18:12:32 +01:00
DokterSmol 660d410196 libr4d: windowed attention at head_dim 128 with 4 queries per kv head
LFM3's attention: 16 query heads over 4 kv heads at head_dim 128, in full
layers and in sliding layers with a 256-token window. The decode leg
(r4d_attn_paged_h128_gqa4.hip) serves q_len <= 16 and ranks above; every
longer q_len had no row at this geometry. A row pair (bf16 and int8
cache), its constraints, selftest launches and emulator cases (split
verify, ragged window, int8 cache, non-causal with a missing block, WMMA
prefill with and without the window).
2026-11-17 18:12:32 +01:00
Victor Ionescu 38c182a2ba chat: a tool-call delimiter is not a turn terminator
A converted checkpoint can name a token end-of-generation that the chat format
itself writes as one of its call delimiters -- Qwen3.8-Flash-Next's
`</tool_call>` is a single added token, and a container that lists it in
generation_config's eos list stops every tool-calling turn the moment the call
closes. The damage is worse than a late stop: a second call is never written,
finish_reason says "stop" on a tool-calling turn, and a reply that quotes the
tag as that token is cut mid-sentence (seen in a coding session where the model
wrote about the template and the turn ended between two tokens).

The bridge already derives the format, so it knows what the model writes as a
call boundary. It now reports the end-of-generation ids whose spelling is one
of those markers, leaves them out of the reply parser's terminators, and the
engine demotes them in the decoder's stop predicate with a warning. The
template's real terminator (<|im_end|>) is untouched, and a model without
tools, or a container that names nothing extra, is unchanged.
2026-11-16 18:03:16 +01:00
Victor Ionescu b988378e70 chat: read a function name that ends at whitespace (Ling 3.0)
Ling-3.0-flash's template writes a call as the opener, the function name, a
newline, and only then the argument tags:

    <tool_call>read
    <arg_key>path</arg_key>
    <arg_value>/a</arg_value>
    </tool_call>

The differential analysis names the function between the opener and the first
argument tag, so its end is the bare newline and name_suffix comes out as
whitespace alone. chat_format_check refused that, so every request carrying
tools answered 501 with "this model's tool calls cannot be read back:
name_suffix must end the function name with something besides whitespace" --
the whole tool-calling surface, for every Ling-3.0 checkpoint.

A suffix with no core of its own is the suffixless ending written out: the
name stops at the whitespace. The reader now takes it that way (name_open keys
on the trimmed core, so the name runs to the first arg_prefix or call_end,
whitespace trimmed), while the grammar still writes the template's newline.
The object family has no such terminator -- its brace ends the name -- and
keeps the refusal, as does the wrapped format whose bare name_prefix would
otherwise read as a call.

Adds the real template as a fixture and a regression test that derives the
format, builds the grammar, and reads a two-call reply built from the derived
fields; a second test pins the object family's refusal.
2026-11-16 18:03:16 +01:00
mici81andClaude Opus 5.5 bd3fa646bc libr4d: hc_read decode forms G, S and kernel B3 back, B3 without a lane branch after its WMMA
2.0.0 dropped #396's hc_read decode forms. With ROCm 7.2.1 (clang 22) they gave NaN logits (#413's report);
ROCm 10.1 was fine. The cause is kernel B3 alone: clang 22's backend sinks its WMMA up product into the
lane-divergent `if (col < RG && col < rows)` around the store of x, so the WMMA runs with part of EXEC off
(an s_and_saveexec right before the first v_wmma). In the IR the WMMA is convergent and outside the branch.
At 16 rows every lane passes the test, which is why form S at 16 rows was right.

- Forms G (1..8 rows) and S (9..16) and kernel B3 at Flash-Next's shape, the bodies of #396, chained in
  2.1's style (r4dchain / R4dUnchained), hc_rot_group<I8>. They take these rows from the fused grid and the
  tiled read; from 17 rows nothing changes.
- B3: a lane past the step's rows takes the last row and every lane stores, bit for bit what that row's own
  lane stores, so there is no branch after the WMMA.
- hc_decode_forms is #396's again (d against fp64, x within rounding up to 16 rows), with 2.1's rq dtype, a
  count of non-finite outputs (the error sums went through std::max and >, which pass NaN) and rows 9 and 12.

r4d_selftest --case hc_read_e4m3: 66 passed with ROCm 7.2.1 and with 10.1; 27 failed with 7.2.1 without
B3's change. Flash-Next on 2x R9700, ABBA, ms per decode step at 1/2/4/8/16 streams: 15.72/20.62/26.83/
37.37/51.89 -> 14.92/18.61/26.67/37.15/50.83; prefill unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 18:02:02 +01:00
Constantin 1d94e416a6 libr4d: keep short IQR verification on the decode path
A speculative verify issues several rows where a plain decode issues one.
Two IQR kernels accumulated those rows differently, so the same weights and
activations could round to different bf16 outputs. A greedy choice near a
tie could therefore diverge even though every draft was accepted.

gemm_iqr_nt_m64: a U5 row-scale trellis (computed trellis, 5-bit, one f32
scale a row) already folds one to four rows as a GEMV in the single-token
order. Above that, through the GEMV's eight-row limit, the multi-row fold
differs. Those rows now run as independent single-row GEMV blocks on
grid.y, including a chained launch. Gated GEMMs and every other form keep
their dispatch.

moe_gemm_iqr: a short token-order gate/up batch (more than one token, at
most eight times top_k, top_k below the one-wave threshold, K at least
eight 128-blocks, and a one-token step inside the decode band) used the
run grid. Several tokens on one expert then took the WMMA tile instead of
the one-row dot. Those batches now give each sorted slot its own block and
the same wide-K dot reduction as a one-token gate/up. Sorted down
projections, longer batches and the prefill map are unchanged.

r4d_selftest checks both against independent single-row launches, bit for
bit, including an untouched output tail on the dense row. The existing
grouped numerical suite still passes.

Measured on an R9700, the dense U5 path at N=8192 K=2560 is 26.5 us at
M=1, 51.2 at M=4 and 105.2 at M=7. A 512-expert Qwen3.8-Flash-Next gate/up
(768:512 x 2560, 5-bit, ten slots a token) is 28.9 us at one token, 52.4
at four and 82.2 at seven. Prefill remains the old kernel.

On the isolated build, Qwen3.8-Flash-Next U5-gate/W5-down matched its
non-speculative token ids at MTP 3 and 6 on arithmetic, writing, code,
explanation and JSON. StillDeadcode's IQR-V4 control matched on the
arithmetic and writing prompts at MTP 3. A layer trace of the previously
divergent writing token was bit-identical between the two schedules.
2026-11-16 17:59:42 +01:00
Constantin ba3ebd380f feat(qwen4exp): support calibrated U5 gate/W5 down recipe 2026-11-16 17:58:41 +01:00
keptn42 157959fd80 server: a control-vector variant, MODEL:NAME, that runs with the vector on
A request turns the control vector on with the `control_vector` body field, or the deployment's
default applies. A client that can only choose a model cannot send the field, and a gateway can
allow or refuse a model by its name but not a field. --control-vector-variant NAME lists
MODEL:NAME as a child of the model, the way an adapter is listed, and a request naming it runs
with the vector on whatever the default; the model's own name keeps the default. Unset, the
default, lists nothing.

The key needs --control-vector off or on. NAME keeps the rule model names keep (no ':' or
whitespace), and may not be a --lora adapter's name or the served model's own. The variant's
name with "control_vector": false is refused, since the request asks for both. With adapters
enabled the variant takes no adapter lookup, and /v1/load_lora_adapter refuses its name.

config_test 68, fleet_config_test 18 and server_test 191 cases pass, and the host suite
(ctest -LE 'gpu|oot') passes. On two R9700s at TP2 (Qwen3.8-Flash-Next IQR-V4 with the shipped
vector), through the front: /v1/models lists MODEL:uncensored and GET /v1/models/MODEL:uncensored
answers; a policy prompt to the variant is answered and to the model's own name refused; the
variant with "control_vector": false is a 400.
2026-11-16 17:57:46 +01:00
keptn42 aadabde0de http: a route's captures replace those the request already carries
Router::dispatch put a route's captures into the request with std::map::insert, which keeps a key
the request already has. The front matches /v1/models/ID itself and hands the request to the
model's router with the path rewritten, an alias as the model's name and base:adapter as the
adapter's, so the model read the front's id: through the front, GET /v1/models/ALIAS and
GET /v1/models/base:adapter answered 404. The captures of the route that matched now replace those
of the same name; nothing sets a request's params before a dispatch otherwise.

server_test: a_request_handed_on_reads_the_capture_of_the_route_that_matched_it fails without the
change and passes with it.
2026-11-16 17:57:46 +01:00
Jintak Han b27f352259 Adapt gemma4_bf16's SWA implementation to gemma4 2026-11-16 17:53:54 +01:00
fl0l0u c9bce68d45 museglimmer: the reply-format table moves to arch/common
chat.h sat in arch/museglimmer/ while the ct plugin and chatparse_test
included it across the directory boundary -- a shared reply-format
table, and the house answer for that already exists twice over:
rad_gemma4_chat.h and rad_deepseek41_chat.h in arch/common. Moved to
rad_museglimmer_chat.h beside them; the three consumers take the same
<arch/...> include the other two already use.

Standards axis of the 2.1.0 review pass, finding 9.
2026-11-15 22:02:30 +00:00
fl0l0u a8d82678fa fp8: the trunk-rotation question lives beside its predicates
"The trunk is rotated int8 (linear_is_w8h or linear_is_wnh), its
activation codes one scale a trunk_g8 columns: 256 for IQ8R, 128 for
the other rotated forms" was written twice, verbatim, in flint's and
bailing_hybrid's field declarations, and the probe that answers it --
weight_enc, the two predicates, linear_w8h_group -- was re-typed at
both arches' layer-0 sites. museglimmer_ct carries the near-variant;
its question is narrower (exactly-IQ8R, not rotated-at-all), so it
keeps its own predicate.

rad_fp8.h now answers it once: trunk_rotation(enc, &g8), beside the
predicates it is made of, so the group-width semantics travel with the
forms that define them instead of with three copies of a comment. The
two call sites shrink to the probe and the named question.

Standards axis of the 2.1.0 review pass, finding 4.
2026-11-15 22:02:30 +00:00
fl0l0u 8ac613ddb9 museglimmer: the two plugins read their text_config through the common helpers
cfg_f/cfg_i/cfg_s -- the "text_config.<key>, else <key>" fallback that a
multimodal config's language half needs -- exist in rad_arch.h as
meta_text_getf/geti/gets, and have since 1.7.0. Both muse plugins grew
a byte-identical private copy in the same commit, the two copies
identical to each other. Deleted; the call sites name the common
helpers. museglimmer_test drives every one of the replaced reads.

Standards axis of the 2.1.0 review pass, finding 2.
2026-11-15 22:02:30 +00:00
fl0l0u 97b4590761 mm+text+tests: three one-line residues the 2.1.0 review pass logged
The ATEM handoff's think_out called touch(0) twice on the hold branch
(harmless -- touch is edge-triggered -- but a merge artifact in an
otherwise surgical state machine); processor.cpp grew a second,
byte-identical Python-rounding helper 700 lines below the one it
already has, renamed only by an underscore; and the rewritten
RAD_TESTS_NO_CORE comment hand-enumerated eight tests while the set
below it names nine -- the comment now points at the set instead of
drifting from it again.

Standards axis of the 2.1.0 review pass, findings 6, 7 and 10.
2026-11-15 22:02:30 +00:00
fl0l0u c256342bc1 tests: the hash-check tests read the shared timeout, not a literal
artifact_sums and vendor_sums each set TIMEOUT 120 outright, where the
tests around them use ${RAD_TEST_TIMEOUT}. In the fast (Release) gate
the variable is 120, so the fast suite is unchanged -- but under ASAN,
TSAN or a Debug build it rises to 600 for every sibling, and these two
shelled-out hash sweeps over the vendor and artifact trees stayed pinned
at 120 there, the one config where a filesystem walk can be slowest.

Same idiom as the neighbours now: one knob, no per-test literal to
forget when the budget moves.
2026-11-15 22:02:30 +00:00
fl0l0u 66b0dcf019 server: the guarded-route set is declared once, at registration
The front kept its own list of which routes answer the local operator
keyless -- guarded_route spelled out the same eight (method, path)
pairs Server::register_routes registers with a local_operator handler,
and its comment admitted the copy ("Kept in step with Server::register
routes"). A new guarded route meant editing the registration AND the
front's list AND the test that pins the list against drift; miss one and
the front wakes a parked model for a stranger who is then refused -- the
exact A-05 bug class -- silently.

Router::add now takes a `guarded` flag, set on the six registrations
that guard (and their DELETE siblings). Router::guarded(method, path)
asks the matcher -- the same split_path + :label match that reaches the
handler -- and the front copies the flag as it mirrors each model route,
so guarded_route is one line reading the front's own copied marks. One
declaration per guarded route, at its registration; the matcher that
decides the wake is the matcher that dispatches, so slash and :label
forms cannot disagree with the handler and the drift risk is gone.

front_test still pins every shape (guarded: slashes, /sessions/:label,
the trailing-slash collapse; not: GET /sessions, /stats, inference,
/sessions/a/b) and transport_test exercises real dispatch through them.
Behaviour unchanged -- the same eight routes wake nothing for a stranger.
2026-11-15 22:02:30 +00:00
fl0l0u 0f011f27e1 fleet: the local-operator rule is one predicate, read twice
add_routes' guard and the front's operator rule computed the same
expression byte for byte -- !c.api_key.empty() || server::local_operator(
q, c.host, c.allow_hosts) -- once to answer a fleet admin route with a
403 and once to decide whether a guarded route may wake a model. The
second-pass audit had to touch both to move them together, which is the
telling.

Fleet::operator_ok(q) owns it now; both callers call it. The two must
agree or the front lets through a request the handler then refuses (or
wakes a model the guard would not have admitted), so a single source is
the point -- keyed deployments pass, keyless ones answer the three-leg
local-operator rule exactly as before. No behaviour change.
2026-11-15 22:02:29 +00:00
fl0l0u c3a4775f54 util: a log_once for the warnings that speak once per process
Three sites -- the kvstream clamp (L-02), the batch overlap guard and
the bidi-plane belt -- each open-coded the same four lines: a function-
local static atomic<bool>, a bool expected, and a compare_exchange to
decide which of the many steps gets to print. The pattern is the point,
not the flag name (said, said2), so it moved to rad_internal.h as
log_once(flag): true on the first call, false after.

No behaviour change -- same first-of-many warnings, same compare-exchange
thread-safety, exactly one winner per flag -- only the idiom is now named
instead of re-typed where a fourth once-warning is ever needed.
2026-11-15 22:02:29 +00:00
fl0l0u b9ecbde0d6 util: one wording for the bounded read's refusal
The refuse sites that read a container file all re-typed the same
two-branch message -- over ? "carries far too many values"
: "nests far too deep" -- six times, and the copies had already
drifted: gen_config said "carries far too many JSON values", xstats
"far too many values", tokenizer_config "it does not parse" for the
discarded case. The bounds themselves (2^24, 256) were also spelled
as literals in tokenizer_json's refusal, so a bound change there
would make its message a lie.

Json::bound_why(over, deep) is the phrase, owned beside the read that
sets the flags, and the two bounds are exported as kContainerBudget /
kContainerDepth so the one message that states them reads them from
the constants. Every refuse site now calls it; the wording is one, the
numbers cannot drift. No behaviour change -- the same flags map to the
same failure paths, only the text they print is unified.
2026-11-15 22:02:29 +00:00
fl0l0u 5e2e596644 format: bound the geometry the bailing layout products are built from
The layer-count cap made the walk safe; the arithmetic was still open.
The rebuild multiplies container-supplied widths in int64 -- heads *
(nope + rope) rows for the q_b split, heads * 256 * latent for the
fused kv -- and hands the products to sized allocations and a
comparison. A wrapped q_b product that coincidentally equalled the
tensor's rows would run the split at a wrong per-head boundary (the
bytes stayed the file's own, but the weights went to the wrong names);
on the 32-bit tier, an overflowed element count truncates through
size_t to a small allocation the copy then overruns.

The family gate now caps what these products are built from -- heads
and the MLA rank at 4096, rope at 256 dimensions, the full query width
at 65536, the layer group within the stack; the shipped geometry is
128/64/512 with tens of heads -- and the q_b row product is computed
with overflow checks instead of trusted. checkpoint_test pins the wide
heads and rank against the honest small stack.

Found by the 2.1.0 review pass (axis: hostile model files); widened
past the reported site to the fused-kv product the same axes cleared
only as file-bounded.
2026-11-15 22:02:27 +00:00
fl0l0u 3bf9dc9593 diag: the report writes take the atomic, link-safe path
diagnose wrote diagnose.json and diagnose.md with plain ofstreams into
the configured report dir. That dir is a shared place in practice -- a
/srv/reports, a fleet peer's mount -- and a local user who can write it
can pre-create DIR/diagnose.json as a symlink: the serving-user process
then truncates and overwrites whatever the link names, with report text
whose category strings a corpus file partly shapes. A reader polling the
dir also sees a half-written report.

This is the hazard xs_write_atomic exists for -- xstats' comment
describes exactly this pre-created-symlink story -- and xstats.h is
what xstats uses to write the very same kind of file. Both report
writes go through it now: temp file, no follow, rename.

Found by the 2.1.0 review pass (axis: hostile sockets / runtime).
2026-11-15 22:02:27 +00:00
fl0l0u d893fd05d1 diag: the baseline and corpus files are read like the reports they are
Both files diagnose consumes are written by other runs and pasted
between people: --diagnose-baseline is an earlier report, the corpus a
forwarded file. Neither was read like a supplied file. The baseline got
the unbounded Json::parse, and compare_outputs then walked it with
throwing accessors -- a member it does not expect throws, and nothing
between run_diagnose and main catches -- so a crafted "earlier report"
aborted a run with std::terminate after hours of benchmarking work. The
corpus got a hand-rolled unbounded fread loop and a raw parser per
line: a deep line recursed the parse to a stack overflow before the
fingerprint check could ever run.

Now: capped read and parse_container on both (the corpus's size refusal
lands before the bytes are read), a per-line over/deep refusal that
names the line, and one try around the comparison so any structure the
comparison does not expect is the refusal it should be -- "the baseline
is not shaped like a report", parity not compared, the run keeps its
own results. diagnose_test pins the deep line.

Found by the 2.1.0 review pass (both security axes, independently).
2026-11-15 22:02:27 +00:00
fl0l0u 5c66eecc8e device: the stuck-exit watchdog does not fire during load
scheduler.stuck-exit (2.1.0, 60 s by default everywhere) turns the stall
verdict into a process exit so a restart policy can act on a hung card.
The verdict watches queue read-indices and the direct-IO counter -- and
a cold load moves neither: a mapped tier faulting its tables through the
page cache is not counted, a barrier-waiting rank parks its index, and
"zero progress for 60 s" is then a description of a big model starting,
not of a hang. Under a restart policy that misfire is a crash loop with
a captive audience: the same load runs on every restart, and the exit
was armed from process start.

The watchdog now reads dev_engine_ready: set when an Engine::start()
completed once, never unset, and the exit fires only after it. A hang
during the very first bringup is what it always was -- dumps, the log
line, /health 503; the supervisor's hammer hits a process that has not
started serving, which is exactly the case the exemption keeps it off.
The verdict's own log line says which of the two futures it has, per
this file's rule that a report never states less than it will do.

No fast-suite test reaches the backend watchdog thread (the exit path
kills the process and the watch ticks in wall-clock seconds); the
config parse stays pinned by fleet_config_test and the exemption is one
flag read at the fatal's gate. Found by the 2.1.0 review pass
(axis: hostile sockets / runtime; the load-phase scenario is the
mapped-tier fault storm the release itself describes).
2026-11-15 22:02:27 +00:00
fl0l0u f4981154fc text: the tool-call arguments probe parses under bounds
bad_arguments names the offending tool_calls[].function.arguments when a
refused conversation reaches it -- and it probed each string with the
plain Json::parse. The HTTP edge depth-caps these strings (its comment
is explicit that the strings could otherwise overflow a worker's stack),
but nothing capped the VALUE COUNT: a client whose conversation had
already failed the template -- exactly the path this refusal exists on
-- could hand the probe a few million flat values, and the probe grew a
DOM no one would ever read, once per request, inside the body's 512 MiB.
Offline callers (fleet, diagnose) reach the same path with no edge at
all.

The probe is parse_bounded now, at the same depth the edge enforces and
a values budget a tool call cannot approach; over, too deep, and not
JSON each name themselves in the refusal, and the honest case still
refuses in the template's own words. chat_test pins all three bounds.

Found by the 2.1.0 review pass (axis: hostile sockets).
2026-11-15 22:02:27 +00:00
fl0l0u 392746da6b museglimmer: the vision tower bounds the config it allocates by
MuseTower::declare read vision_config.num_hidden_layers and the position
grid with only a positive check, then handed them to host vectors --
full.assign(depth), L.assign(depth) -- before any weight was consulted.
A container stating 2^62 layers threw std::length_error (or bad_alloc
just below max_size) out of the declare phase, and nothing between there
and main catches: the process died with a SIGABRT and no report, where
every other bad config in this file says what it dislikes on stderr and
refuses with RAD_E_INVAL. The grid sides were the same story multiplied:
pos_emb_height x pos_emb_width is a signed product of container values
that can overflow before any comparison could see it.

The gate now refuses depth past 128 and a grid side past 512, against
published maxima rather than round numbers: the deepest vision encoder
ever shipped is 48 layers (ViT-22B, InternViT-6B -- this family's towers
are SigLIP-class, tens), and the largest stored position table a side of
92 (SigLIP at 1292 px over patch 14; CLIP 16, SAM 64; native-resolution
towers store no side x side table). The caps sit ~2.6x and ~5.5x past
those, so they never bite an honest container, and at the cap itself the
guarded shapes are harmless: the depth vectors cost KiB and the grid
products top out at 2^18, too small to wrap signed 64 before a
comparison sees them. museglimmer_test pins both caps at their boundary
and far past it -- the grid at both sides together, since one side
alone the height==width rule refuses before the cap is consulted.

Found by the 2.1.0 review pass (axis: hostile model files); caps
sourced against published encoders and tightened at the operator's
request, from the first pass's wide 512/4096 margins.
2026-11-15 22:02:26 +00:00
fl0l0u 4943bba2fb format: a bailing container must promise a walkable layer count
bailingmoe3_layouts rebuilds the release GGUF's layouts by walking every
layer the container claims -- and it runs on the open path, before any
plugin gets a vote. Its gate checked the counts were positive and nothing
more: a GGUF naming 2^62 blocks sends the name-probe loops over centuries
of iterations. The process never listens, never refuses; StallWatch notes
the silence after two minutes and stops there. A negative
first_k_dense_replace opens a second loop of the same order, starting
below zero. This is a hostile container's permanent hang, the same
supply-chain class as the round-two finding on the shard index: the
refusal must land before the walk.

The gate now caps n_layers at 4096 (the family's real models are an order
of magnitude below; 4096 layers is not a slow load either) and requires
the dense prefix to lie inside the stack. checkpoint_test pins all three
shapes -- 2^62 layers refused, negative prefix refused, a small honest
stack opens as before -- and the test GGUF writer gains the INT64 KV type
they are spelled in, which the u32 field could not carry.

Found by the 2.1.0 review pass (axis: hostile model files).
2026-11-15 21:15:23 +00:00
fl0l0u 6e8a2f0a94 engine: the scored step refuses its union before pinning tries it
The scheduler caps one request's scored candidate list at 4096 ids;
nothing bounded the step's UNION. A step packed with maxed scored
requests unions toward the whole vocabulary, the pinned readback
buffer is sized from that union, and its size was discovered by
ATTEMPTING it: a gigabyte-scale page-locked allocation whose only
check was whether the box survived it. Survive it and the bytes stay
pinned forever -- the buffer is grow-only. This was L-04: the
round-one cancel-path invariant held (the engine never died on it),
but the residual was an attacker-sized lever on page-locked memory.

The cap is the step-wide sibling of the per-request one: 65536 unique
candidate rows, sixteen maximally-loaded requests, while real scored
questions name a few dozen ids each. A step past it takes the refusal
the allocation failure already took -- the scored requests cancel,
the engine and every other request on the step keep running -- except
before the box is asked to pin anything to find out. The logits-row
mode needs no sibling cap: its rows are one per scored request,
bounded by the batch's max_seqs by construction.
2026-11-15 20:38:10 +00:00
fl0l0u 9a960c3da9 spec: the dependency table says what HTTP and JSON are now
The table still listed vendor/nlohmann as "lifted, unmodified": the
directory is gone, displaced by core/util/json.{h,cpp} on the yyjson
reader, and vendor/UPSTREAM has recorded the removal since (audit
I-04). And no cell said cpp-httplib carries a local patch -- it has
for as long as 0022 has existed, so "unmodified" sat next to a
directory that is not.

The row now names both facts at the place a reader looks up what is
lifted and what is ours: httplib lifted with the one patch, the DOM
rewritten into core/.
2026-11-15 20:38:10 +00:00
fl0l0u 79cc319db2 vendor: cpp-httplib 0.66.0 -- the thread-creation failure stops aborting
0.64.0's ThreadPool spawns a dynamic worker inside the accept loop with
no guard: when the process runs out of threads, std::thread's
std::system_error escapes the loop and std::terminate takes the whole
server down. A client that opens enough connections makes thread
exhaustion a scheduled event; radiance's socket gate and drain budget
narrowed that window but never closed it. 0.66.0 wraps the spawn in
try/catch and keeps the job queued for an existing worker -- the abort
becomes a queue.

The pair moves to what llama.cpp carries at b8abe41a5 ("vendor: update
cpp-httplib to 0.66.0 (#32049)"), byte for byte; the LICENSE was already
byte-identical. Patch 0022 re-verified, not rewritten: the same hunk at
a +26-line offset with no fuzz, upstream still bounds the keep-alive
drain only by the connection's timeout, so the 5 s budget still stands.
The six CPPHTTPLIB_* defines vendor/CMakeLists.txt passes were each
re-checked as live knobs in the new pair. UPSTREAM carries the new
record and the audit note; the manifest re-hashes in this commit.
2026-11-15 20:38:10 +00:00
fl0l0u 0ff61a19a2 sched: the preemption gate credits only what the recompute adopts
The gate that admits a preempted request back subtracted the raw
attention prefix hit from every paged group's need. Admission does not
adopt that deep: under checkpoints the linear layers replay from the
last checkpoint whatever the attention matched, so the adopted prefix is
clamped to the linear hit, exact mode floors it to its chunk grid, and
one token always stays outside for the logits. Every block of that
difference was a block the recompute would really need and the gate
pretended was free: the request is admitted against a loan it cannot
repay, the next ensure preempts it again -- the exact loop the gate's
own comment describes.

The gate now runs the plain count first, which passes without touching
the cache at all when the pools plainly hold the recompute, and consults
the hash-chain lookup -- request-length CPU, under mu_, per waiting slot
per round -- only when the credit decides, crediting the clamped,
floored, capped depth admission actually adopts. Under-crediting delays
a re-admission by a round; over-crediting, which is what this was,
loops.
2026-11-15 20:38:10 +00:00
fl0l0u b98c2eb13e vendor: the shims that hold lifted code say so in the record
The five files under vendor/shim/ are hashed by the manifest and
tamper-visible, but LIFTED FILES named only one of them
(ryml_impl.cpp, beside the rapidyaml entry). The other four carry
upstream's shape or text -- common.h transcribes llama.cpp's string
helpers unchanged, MIT, at the recorded commit; ggml.h, llama.h and
log.h declare the macros, types and log surface the byte-for-byte lifts
reach for -- and "the manifest hashes it" is tamper detection, not
provenance. A refresh could meet those files with no note of what they
mirror.

They are recorded now, beside the lifts they exist for, with what each
is, what it mirrors, and why it exists rather than the upstream file it
stands in for. The manifest re-hashes with the record, in this commit.
2026-11-15 20:38:10 +00:00
fl0l0u 5736dd11c3 sched: the bidirectional plane trusts its runs no further than it checks them
h_bidi carries one slot per run that intersects the chunk, over a plane
four times the step's token capacity wide -- sound only because
RopeLayout::runs is documented ascending and pairwise disjoint, so every
accepted run can bill at least one real token of the step. Until 2.0 the
layout was built solely from the tokenizer's own placeholder scan;
request-side placement writes it now, and a layout with overlapping runs
would bill one token twice, run n_bidi past the plane, and hand the card
an index plane its shape validation waved through.

The build now checks the promise where it consumes it: a run starting
before the last accepted one's end is dropped -- those media rows simply
lose bidirectionality for the step, which is an ordinary miss -- and a
hard stop guards the plane width itself, unreachable unless the check is
wrong. Both events speak once per process, not per step.
2026-11-15 20:38:10 +00:00
fl0l0u 90b1229bfc place: the profile file is read like the untrusted file it is
--expert-profile read its file with no size cap -- any file, gigabytes,
appended into memory before a single check -- parsed the text with the
unbounded parser, and took n_trunk_layers through int32. That last one
is the quiet one: the loader refuses "this profile is for another
model" by comparing the file's layer count with the live model's, and a
value that wraps past 2^32 lands on exactly the number the comparison
asks for.

The read now caps at 64 MiB while appending -- past it, nothing further
is grown and the file is refused by name -- the parse is the container
helper (parse_container) like every other file input, and n_trunk_layers
is read as int64 and range-checked before it reaches the comparison. An
xstats_test case pins the loader's three refusals -- wrapped trunk
count, negative count, oversized contract -- and the tmp-symlink
refusal of the previous commit: the planted symlink survives untouched
and the profile file still lands.
2026-11-15 20:38:10 +00:00
fl0l0u e5862f3d26 place: the profile's tmp name is created, never overwritten
The stats file is written as "<path>.tmp.<pid>" and renamed, so a
reader never sees half a file. But the name is built from the PID --
public -- and fopen("w") happily follows a symlink planted at that name
and truncates whatever it points at. A local user who guessed the next
PID had the serving process overwrite any file that user could name,
as the serving user.

The tmp file is now opened O_CREAT|O_EXCL|O_NOFOLLOW: no symlink, no
reuse of an existing name. A stale tmp of a crashed run -- whose PID a
reboot can reuse -- is unlinked and the create retried once, exclusive
again; whoever else planted the name wins exactly a refusal.
2026-11-15 20:38:10 +00:00
fl0l0u c2403b2e29 kvstream: a stage run past the host layer says so, once
The stage copies pool ranges of one layer into the mirror row, clamping
each run to min(pool bytes, host_layer_stride) -- the clamp is what makes
the copy memory-safe. But a silent clamp is a wrong answer given quietly:
if pool and host layer ever disagree on the layout, a run naming a block
past the row's end stages nothing there, attention reads stale bytes at
those positions, and the text comes out fluent and wrong with no fault
and no line to point at.

stage_src now notices when it clamps or drops a run and warns once per
process -- the hot path is not the place for a per-step print -- naming
the group, the row's end and the stride. The behaviour is unchanged; what
is new is that it is never silent.
2026-11-15 20:38:10 +00:00
fl0l0u 444b85158b scripts: hfget refuses names curl cannot fetch faithfully
A listing entry named "weights.bin#x" downloaded cleanly, checked clean,
and was the wrong object. curl ends a URL path at '#' and '?': it
requested "weights.bin" while hfget recorded the entry as
"weights.bin#x". An attacker who lists the truncated object's real size
and oid under a decorated name passes the size check, the oid check and
the manifest -- the bytes arrive under a name nobody asked for, and the
directory reads complete. hfget's name screen checked traversal, control
characters and its own manifest, but not curl's path terminators.

The jq screen now refuses any entry whose name carries # or ?. The child
that writes each file re-screens its name too, and its old case missed a
name ending in "a/.." (the parent's regex caught those, the child's did
not) as well as the terminators -- both arms added, the `?` quoted so it
stays literal and not the single-character wildcard. Two hfget tests: a
listing carrying "model.bin#x" is refused whole, and a child handed
model.bin#x, model.bin?y or sub/.. refuses before any request or write.
2026-11-15 20:38:10 +00:00
fl0l0u 965a7caa51 hf: a lone container does not outrank weights beside it
Give --model org/repo and the engine picks what to serve from the fetched
directory: one .rad on the top level won outright, whatever else was
there -- and .rad was not in the skip list a safetensors set imposes on
.bin/.pth/.gguf, so hfget fetched the rival too. A repository that ships
a real safetensors set beside one decoy .rad chose for the operator: the
container wins, the engine loads and serves it in place of the model the
operator named.

hf_served_path no longer resolves that tie by rank -- a container among
safetensors or gguf weights is refused by name and the operator passes the
file they mean -- and hfget skips .rad when a safetensors set is present,
as it skips every other rival. A repo holding only a container still
serves it: the fix is against the silent tie-break, not against .rad.
2026-11-15 20:38:10 +00:00
fl0l0u 4c9a79ca98 tests: the served dashboard bytes get hashed from outside
dashboard_page.h is the Node build of dashboard/, committed because the
engine's build has no Node. The ctest dashboard_page compares dashboard/'s
sources against the digest recorded INSIDE that header -- which proves the
sources and the header's own claim agree, nothing more. Rewrite the header
and its embedded digest together and the check passes while the engine
serves a page nobody built from these sources.

artifact_sums.sh hashes the artifact itself from outside, the mechanical
half vendor/SHA256SUMS is to vendor/UPSTREAM: tests/ARTIFACTS names every
committed built artifact and its hash, and a lone tamper of a served byte
now fails. A rebuild re-records the manifest in the same commit. The
residual gap -- a single commit rewriting an artifact AND the manifest --
is exactly the vendor-tree gap, and documented as such.
2026-11-15 20:38:10 +00:00
fl0l0u 70be48c6fa scripts: the expert report never prints an untrusted string raw
The stats file a colleague hands over is data, not the operator's own:
its model, arch and map strings are printed straight to the terminal, and
a ESC in one starts an OSC sequence that retitles the window, moves the
cursor, or worse in terminals that honour it. Malformed numbers beneath a
well-formed format header crashed the report with a raw Python traceback
the operator has to read past.

Strings for display now pass through safe(), which turns every control
character -- C0, DEL, and the C1 range -- into '?', on model, arch and
the map list alike. The whole run is wrapped so a file that passes the
format check but is malformed underneath exits with one line naming the
fault instead of a stack. --json output is untouched: it is data, not a
terminal.
2026-11-15 20:38:10 +00:00
fl0l0u be09d90c71 libquant: the codebook loader caps as it reads and refuses an infinite unit
vq= is the one codebook path that reads a file; table= caps its values
at 4096 but vq= appended every line to a growing vector and checked the
count only after reading the whole file, so a 10 GB codebook grew 10 GB
of vector before anything said no. And its "# unit X" line parsed X with
sscanf %lf -- which accepts "inf" -- while the fallback guard was
!(unit > 0.0), an infinity passes. A "# unit inf" file set every decoded
value to infinity.

The count is now checked as rows append, at 4096: the widest code the
grid emits is u12, so past 4096 codewords could not be indexed even with
the memory read, and the old code silently mis-indexed the over-4095 case
itself. And only a finite positive names a unit -- "inf" and "nan" fall
back to the entries' own rms, as a malformed value already did. A
quant_test case pins the 4096/4097 boundary and that "# unit inf" now
decodes finite.
2026-11-15 20:38:10 +00:00
fl0l0u 3ac3954fea sample: the schema reaches the converter through the bounded read
grammar.cpp guarded the json-schema-to-grammar converter with a depth
check -- kMaxSchemaDepth, added because a deeply nested schema crashes
the converter -- but it built the tree to measure with Json::parse, the
unbounded read. A schema nested past the guard's own reach was already a
stack overflow by the time json_depth ran: the check sat after the thing
it was written against.

The schema is now read with parse_bounded at exactly the depth the check
promises, plus a 2^20 value cap, so the refusal fires during the read,
before any nested tree exists to be walked, dumped or destroyed. Every
current caller already hands over a bounded body, but this entry point
does not know that -- it takes a string.
2026-11-15 20:38:10 +00:00
fl0l0u 9bfdd95cb6 server: a wrong api key closes the connection it guessed on
A failed authentication answered 401 and kept the connection alive, so a
client guessing credentials over one keep-alive paid for the socket once
and then streamed a thousand tries down it. The gate can refuse the
request; it was not refusing the session.

The 401 now carries Connection: close. A guessing client pays a fresh
connect -- and on TLS, a fresh handshake -- per guess, while every
correctly-keyed request keeps its warm connection untouched.
2026-11-15 20:38:10 +00:00
fl0l0u e30ada33e8 server: the worker-start failure logs its reason sanitized
The HTTP pool's start() caught std::system_error and printed e.what()
raw. An OS message carries no socket bytes, but every other catch in the
transport reads it through log_sanitize, and consistency is the cheap
half of the guarantee: a message that ever carried a token or a control
character would print straight into the operator's log.

One call to log_sanitize, and every line this transport writes from a
caught exception now says so through the same filter.
2026-11-15 20:38:10 +00:00
fl0l0u 1231eefbd3 server: the model card hides the expert-profile path keyless
One member of the card's capabilities object -- expert_stats.file -- is
a path on this machine, the --expert-stats file the engine reports. The
card's `root` field already answers to the operator keyless and rides
with the key to everyone else; this one member skipped that rule and
leaked the deployment's file layout to any client that asked /v1/models.

handle_models now strips expert_stats.file from the capabilities dump
for a request that is neither keyless-local-operator nor api-keyed,
matching `root` exactly. The rest of the object -- counts, tiers, the
planner's shape -- is not a path and still ships.
2026-11-15 20:38:10 +00:00
fl0l0u 51e4c7f0f0 server: what a client put in a request never reaches the log raw
log_admitted printed the request's model name and last user text through
%s, unsanitized -- the one entry point that skipped the log_sanitize
every other request-side field passes through. Both come straight from a
client's JSON; control characters in a model field or the tail of a
message let a client forge log lines, inject terminal escapes, or make
the log read as if the operator said something the server never saw.

The two strings now pass through log_sanitize at the print, exactly as
the peer address already does, so the admission line carries the same
guarantee the rest of the log does.
2026-11-15 20:38:10 +00:00
fl0l0u 1b4e405969 server: /props keeps the model path to the operator
The llama-server compatibility payload carries model_path -- a path on
this machine -- to whoever asked, keyless included. It travels the same
class of information /v1/models already gates its `root` field with, and
that gate exists: a stranger enumerating models should learn the model's
name, not where its file lives.

The field now answers for an api-keyed request or a local operator and
comes back empty otherwise -- which is also what it already was for a
--model stdin read, so no client finds the member missing, only the
strangers learn nothing new.
2026-11-15 20:38:10 +00:00
fl0l0u d7e3c2a58a sched: an anchor row with no anchor is row zero, not row minus one
LiLiCorr's correlator gathers each sequence's context state by the row
the advance pass wrote into h_arow (RadBatch::anchor_rows), and the
gather validates the index plane in shape, not values: an index of -1
reaches one int32 before the context buffer and reads off the end of a
device allocation. The reset that opens a build filled the plane with
-1 -- honest for a host reader, poison for an index -- so a row that
reached the query pass without advancing, in any path that skips the
advance, gathered out of bounds instead of gathering a wrong row.

The sentinel becomes row 0: always in range, and a row that really did
skip its advance reads an anchor that fails acceptance and is discarded,
which is the same outcome with no fault and no neighbour's state read.
2026-11-15 20:38:10 +00:00
fl0l0u b44f7a9bb1 sched: an over-cap request would stall every queue behind it
A plugin that declared plugin_words gets a fixed carrier in the batch --
[max_seqs * plugin_words] rows, carved only because the program said how
many words a sequence may carry. The build stage already refuses a
sequence past that bound, but nothing at admission did, and a refused
build restages its step forever: one request carrying more words than the
plugin declared stalls every queue behind it, permanently.

add_locked now reads the same bound the batch carves by (BatchBuilder::
plugin_words_cap, the program's declaration) and refuses an over-cap
request with RAD_E_INVAL, where the server turns it into a clean 400.
The current route caps its own words already; this is the promise no
future route can miss, checked once at the gate every request passes.
2026-11-15 20:38:09 +00:00
fl0l0u 981cd1e4e1 format: the index does not get to reach outside the model dir
hfget screens the names a repository LISTING carries, but the shard
index is one of those listed files, and nothing screened what its
weight_map names. An index of "../../etc/passwd" led the loader to open
that path -- outside the model directory, as the serving user -- and a
directory merging two checkpoints has every reason to hold a real index.

shard_name_ok now reads every weight_map value before the first open:
no absolute name, no empty, "." or ".." component; relative subdirs,
which real repos do use, still pass. The refusal names the index and
the offending shard. A checkpoint_test case opens a poisoned index in
six shapes and the honest one once, and only the honest one reads.
2026-11-15 20:38:09 +00:00
fl0l0u 50ea36f283 place: a profile's counts must be unsigned to steer anything
The expert-profile loader summed whatever JSON numbers it found and the
planner's arithmetic read them as unsigned. A negative count read as
uint64_t wraps to a value near 2^64, which reads back as a ~100% share:
whoever wrote the file could point the pinning at any expert they named.
Under the old JSON library a negative threw its way out of here; the
facade's arithmetic read does not, so the file is now refused by name.

Every entry of a decode row must now be a non-negative JSON integer;
the offender's layer and expert are printed, and RAD_E_INVAL comes back
before a single wrapped share reaches the planner.
2026-11-15 20:38:09 +00:00
fl0l0u f2f94fc6e7 util: one bounded read for the files a container supplies
tokenizer.json, gen_config.json, an adapter's adapter_config.json and
the container's generation.* whitelist are all container-supplied, and
all read through the unbounded parser: a hostile file was refused only
by running out of stack -- the tree it grows is walked, dumped and
destroyed recursively on the way.

Json::parse_container is the wire's bounded read sized for files
instead: 2^24 values, because a tokenizer's vocabulary legitimately
carries a million flat strings, and 256 levels, because nothing
legitimate nests deeper. A file past either bound comes back discarded,
like a syntax error, and the four readers map that onto the failure
paths they already had -- ignore with a warning, refuse the adapter,
refuse the vocab. The bound fires during the read; no hostile tree
exists to be walked.
2026-11-15 20:38:09 +00:00
fl0l0u e46a8ba3d4 util: the bounded read refuses before the tree exists
yy_convert enforced its value budget and depth bound in a second pass
that ran only after every frame of the document had been collected into
a scratch vector. The bound that promises a refused body has not grown
memory grew its scratch with the body: a 200k-empty-array swarm counts
no scalar at all, and the old code refused it after the whole swarm sat
in the frame list.

Both bounds are now enforced where a value is DISCOVERED -- every value
counted, containers included, which is what the pre-migration parser
callback counted and what the tests already pinned -- so a body past
either bound ends the walk while the scratch is still budget-sized. What
stays proportional to the body is yyjson's own read arena, capped by the
byte bound at its open, and oai.cpp's comment now says exactly that. A
json_test case carries the swarm.
2026-11-15 20:38:09 +00:00
fl0l0u 7b9f33653f vendor: the jinja engine budgets its nesting and its range()
A container's chat template is server-side attacker data the engine
parses and runs without any budget. The parser recursed once per nesting
block or paren: tens of KB of "{{ (((" or "{% if %}" in one
tokenizer.chat_template stack-overflowed whoever read it -- the
capability probe or the first render -- past every catch, and errors-
as-values cannot hold a stack overflow. And range() materialised one
array element per step: {{ range(4000000000) }} was an OOM per render.

Both entry points now share one 128-level guard whose throw is the same
exception class a malformed template already raises, and range() refuses
above 65536 values -- far past any template that exists, small enough
that the whole range stays transient. The refusals cross the ChatTemplate
seam as the error values the seam promises (a chat_test case pins that
both shapes refuse and that real nesting still renders). UPSTREAM keeps
the addition under the chat lift's record; the manifest re-hashes.
2026-11-15 20:38:09 +00:00
fl0l0u 2fda03ccdd vendor: the pattern parser counts its nesting, and refuses past 64
A tool schema's `pattern` reaches the grammar converter as client data,
and the group scanner recursed once per nested '(': a few tens of KB of
brackets inside one JSON string was an uncatchable stack overflow of the
request worker. The body's depth and value bounds never saw it -- the
brackets are string content, not JSON nesting -- and 0003, the patch that
made this same function survive a hostile pattern, hardened the empty and
the looping cases but never the recursing one. It is the one remote crash
in the audit, and one request is the whole attack.

transform() now counts its nesting and records the refusal once, where
every unwinding frame met the same '(' and repeated it; check_errors turns
it into the clean throw the server already answers with a 400. Proven on
the compile host against the real converter: the 20000-group pattern is
refused by name, a 40-group pattern -- far past anything a real schema
nests -- still compiles. The record keeps the addition under 0003's name,
whose footing it stands on.
2026-11-15 20:38:09 +00:00
fl0l0u b83d53cf19 front: a refused request does not wake a model to be refused
Every forwarded request leased its model, and the lease fired demand for a
cold or parked one before any handler ran. On the guarded routes -- the lora
admin, /diagnostics, /reset_prefix_cache, DELETE /sessions, the control
vector -- the handler then answered 403 keyless: the wake had already asked
the scheduler for a real load, which can fetch the repository and evict
residents to make room. Loop one cheap GET over an enumerated model name and
the fleet churns for an audience that never gets an answer.

The front already knows reads that report on a model are no reason to bring
one back; the same courtesy is now owed to a request the guard will refuse.
The fleet hands the front its operator rule -- the very predicate its admin
guard reads -- and a guarded route from anyone else reads the not-open state
and stops. Open models still dispatch, keyed boxes still wake everything,
and the operator keeps the diagnostics that bring a parked model forward.
2026-11-15 20:38:09 +00:00
fl0l0u 41a1aa00fe fleet: the admin routes read all three legs, as the engine's guards do
The fleet front guarded its admin routes with the loopback socket alone.
The socket is the one leg that forges: a DNS-rebinding page is same-origin
with its victim's browser and dials through loopback, and a localhost proxy
delivers remote clients on loopback sockets carrying the public Host. With
CORS open by default, a web page in the operator's browser could unload and
park any model, reload the fleet, and read the topology -- disk paths in
the body -- from outside the machine.

The three-leg rule (loopback socket, no foreign Origin, a Host that names
this box) was Server::local_operator's, locked inside Server. Hoist it to
server::local_operator(request, bind_host, local_hosts) beside the request
whose fields it reads, keep the member as the delegate it now is, and let
the fleet's guard call the very same predicate with its own config's host
and --allow-host names. One rule, two callers, no forked wording.
2026-11-15 20:38:09 +00:00
Deadcode 2a2b756371 radiance 2.1.0
New models. Recursive Flint (39.8B, about 2.5B active) by everplays (#422): `arch/flint`, as an
IQ8R container with rotated int8 experts or a four-bit one, with a sink-aware WMMA prefill
attention and the fused attention prologue at `rotary_dim` 0. Meta Muse Glimmer 30B by
launch80_assets (#423): bf16, an int4 trunk or IQ8R, its windowed vision tower, its DFlash
drafter, the ATEM tool dialect and context extension. Ling-3.0-tiny by RikshaDriver (#441):
served from its GGUF releases or as IQ8R on `bailing_hybrid`, with six more libr3d kernels. Block
FP8, MXFP4 and NVFP4 conversions of the three are not served. IQ8R containers of all three
(round to nearest, no calibration) are on Hugging Face under StillDeadcode: flint-iq8r,
muse-glimmer-30b-iq8r-dflash and ling-3.0-tiny-iq8r. They were checked for sane answers on two
R9700; nothing was benchmarked, and Muse Glimmer's pictures, video and tool calls were not tried.

Speech. Breeze-TTS-2 clones a voice from a reference recording and its transcript, with an
optional delivery direction, by farcryjohn (#436). The published Breeze container needs
converting again with the updated recipe before it can.

Tools. A model entry with `diagnose: DIR` runs a fixed workload on the engine instead of serving
and writes a report: step times, tokens a step, draft acceptance, TTFT and prefill rates by
category, concurrency and prompt length, and with `diagnose-baseline` a token-for-token comparison
against an earlier report (docs/DIAGNOSE.md), by Code000 (#418).

Scheduler. `mixed-step-target-ms` holds a mixed prefill and decode step to a service time, off by
default, by tnhnyzc (#413). `scheduler.stuck-exit` (60s by default, 0 never) ends the process when
the device has advanced nothing for that long, so a restart policy brings a hung server back
(#409, #415, #428).

Fixed. Draft trees with the int8 KV cache, which stopped Gemma 4 31B with DFlash2 on its first
request (#454, diagnosed by aelfwyne). The expert loan held at zero by a few leftover cache blocks
after long sessions (#455, diagnosed by thekk1). The mapped tier's pages kept in the page cache
across a load and a restore, by C_Tamas (#421). Replayed tool calls with blank arguments, and
arguments that are not JSON refused naming the call, by dschmitz (#444). The dashboard's card
temperature reads the junction sensor, by dschmitz (#453). The VRAM shortfall report says what the
KL mode needs, by baKon (#448). The out-of-tree plugin test builds its plugins in parallel and
takes its toolchain from the tree.

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

Thanks to @everplays, @launch80_assets, @RikshaDriver, @farcryjohn, @Code000, @tnhnyzc, @C_Tamas, @dschmitz, @baKon, @aelfwyne and @thekk1.
2026-11-15 16:00:05 +01:00
Deadcode ddcb9c69bb radiance 2.0.0
Radiance becomes a multi-model engine: one process serves several models behind one port, loads
each when a request names it, parks it in host memory or restores it from its container, and
shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the
command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Also: the gqa 7 rows against libref on the real 33B weights, 216/216 cases, and rad-kbench -m
with every fusion byte-identical (worst rel-L2 2.08e-3).
2026-11-11 22:32:57 +01:00
neuromanMD c6ef279a12 libr3d: branch-free, bit-identical e4m3_to_f32
The old decode looped over a subnormal's shift, so every fp8 staging loop diverged on gfx11. Normals
re-bias the exponent (+120), a subnormal m is exactly m * 2^-9, S1111111 is the NaN: bit-identical on all
256 codes (the old form is kept as e4m3_to_f32_ref for the check). W7900: the fp8-KV prefill attention
tile 71.6 -> 67.3 ms at 30K keys, output unchanged.
2026-11-11 22:31:33 +01:00
aneinanderandClaude Opus 5.5 e1d612b29d docs: SYCL_PROGRESS -- change 11's commit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:55:06 +01:00
aneinanderandClaude Opus 5.5 0a1fed0bcf libxe2: GDN recurrent state store through local memory, out as whole lines
The register kernel stored a lane's own 512-byte state row, so each float4 store
touched 16 cache lines. A sub-group's 16 rows now go through a 9-float4-pitch tile,
32 columns at a time, and out coalesced. Bit-identical (rad-kbench gdn rows rel_l2 0,
greedy hashes unchanged). 9B 58.9 -> 59.2 tok/s, 27B 30.4 -> 30.6 (spec off).
XE2_GDN_ROWSTORE=1 restores the row store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:55:00 +01:00
neuromanMD aafec91773 libr3d: mxfp4a8 -- do not scan a VRAM e8 plane from the host
e8_scan_once used hipHostGetDevicePointer to decide whether the host can read the e8 plane. It succeeds
for device memory on a large-BAR discrete GPU, so the host byte-scanned VRAM over PCIe (~12 MB/s measured
on a Radeon Pro W7900: 8 s for a 34816 x 5120 plane), and the 16-entry cache was smaller than a DFlash2
drafter's ~36 MXFP4 planes, so every issued pass rescanned most of them -- 70-120 s first requests and
~1 tok/s decode at long context. Scan only host memory (hipPointerGetAttributes), unbounded seen-set; the
kernel's e8 guard already gives reserved values the scale zero in device planes.
2026-11-11 16:53:54 +01:00
aneinanderandClaude Opus 5.5 0aad575475 docs: SYCL_PROGRESS -- generic change 10 (gated prologue), 27B re-bench
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 11:51:00 +01:00
aneinanderandClaude Opus 5.5 9aef29661b libxe2: fused gated-attention prologue (qk_norm_rope_gate, qk_norm_rope_gate_kv_store)
The one-launch prologue that the qwen35 family (Qwen3.5, Qwen3.8), Qwen4-Exp, FishOmni and the MTP
heads request where a kernel library declares it (libr4d did; libxe2 did not, so those models ran
q_norm, k_norm, rope_q, rope_k and kv_store: five launches an attention layer). It splits the
interleaved [q|gate] projection per head, norms q and k, applies the partial NeoX rotary from the
cos/sin table rope_table already fills each step, and with _kv_store stores k and v.

docs/OPS.md requires it byte-identical to the unfused chain, so each step is libxe2's own:
xe2_rmsnorm's bf16 head-row norm (XE2_EXACT=1: libref's ascending sum, as xe2_rmsnorm then takes),
the bf16 rounding the norm stores, cos/sin as xe2_rope_table wrote them (xe2_rope's arithmetic), and
xe2_kv_store's conversion. A sub-group a (token, head), as qkv_norm_rope; that kernel is untouched.
The schemas are libr4d's. The _kv_store row declares its chain (qk_norm_rope_gate, kv_store) and both
rows describe their operands, so rad-kbench draws them and checks the fold byte for byte.
XE2_NO_FUSED_PROLOGUE=1 now hides these two rows as well: the A/B and an escape hatch.

rad-kbench fusion oracle: 28/28 byte-identical on Qwen3.5-9B and on Qwen3.8-27B; default fixture
2144/2144. Greedy A/B (400-token story, 2.4k and 382-token prompts), twice each, spec off: outputs
identical; Qwen3.5-9B w4a16 decode 58.3 -> 58.9 tok/s, Qwen3.8-27B int4 30.1 -> 30.4. Prefill
unchanged (the fused rows serve steps up to 64 tokens).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 11:50:39 +01:00
aneinanderandClaude Opus 5.5 47d1a952e9 docs: SYCL_PROGRESS -- Gemma 4 E2B on Intel, changes 6-9
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:10:37 +01:00
aneinanderandClaude Opus 5.5 dd20835f18 libxe2: sliding-window attention on the DPAS kernels
attn_paged_fast sent any window > 0 to the SIMT split-KV kernel, so every sliding-window layer
(Gemma 2/3/4, Mistral-style and gpt-oss models) missed the DPAS decode and prefill kernels. They now
take the window: each 8-row block starts at its first row's bound (pos - window + 1, on a whole
32-key step; the split decode form partitions from there) and the mask hides keys below each row's
own bound, as libref's attn_paged. The window form is its own instantiation (WIN), so the window-0
kernels are unchanged: the Qwen3.5-9B's attention times match a rebuild of the old code to 0.5%.
The quad prefill form keeps window 0; a windowed prefill takes the esimd prefill form.

rad-kbench, Gemma 4 E2B (head_dim 256, window 512): decode 101 -> 23.5 us and 23 -> 18 us;
q_len 128 757 -> 92 us; q_len 512 2833 -> 98 us; 320/320 within tolerance. Qwen3.5-9B 160/160,
default fixture 2144/2144.

Gemma 4 E2B end to end: decode 63.0 -> 74.4 tok/s, 2.4k-token prefill 1537 -> 1886 tok/s; a story,
a 120-paragraph count and a password at paragraph 77 of 120 answered correctly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:08:31 +01:00
aneinanderandClaude Opus 5.5 d35027aaf7 libxe2: split-KV paged attention up to head_dim 512
attn_paged_fast stopped at head_dim 256 (16 values a lane) and sent wider heads to the exact
kernel, so Gemma 4's global layers (head_dim 512) ran xe2_attn_paged_ref at decode and prefill.
The kernel is now instantiated at 16 values a lane (head_dim <= 256: unchanged, its times match
to 0.1%) and at 32 (head_dim 512, four 16-byte value loads a lane).

rad-kbench on the Gemma 4 E2B container, head_dim 512: decode 192 -> 43 us (short context) and
2040 -> 256 us (long); q_len 256 55.4 -> 19.6 ms; 320/320 cases within tolerance. Gemma 4 E2B
end to end: decode 58.6 -> 63.0 tok/s, 2.4k-token prefill 724 -> 1537 tok/s, decode at that
context 29 -> 59 tok/s; answers checked (a story, a 120-paragraph count).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 20:29:25 +01:00
aneinanderandClaude Opus 5.5 0c7606423b libxe2: fused attention prologue (qkv_norm_rope, qkv_norm_rope_kv_store)
The one-launch prologue that Gemma 3, Gemma 4, Hunyuan v3 and the DFlash2 drafter use where a
kernel library declares it (libr4d did; libxe2 did not, so those models ran the unfused five or six
launches a layer). docs/OPS.md requires it byte-identical to the unfused ops, so each step is
libxe2's own: xe2_rmsnorm's bf16 head-row norm (its partition and reduce_over_group; XE2_EXACT=1
libref's ascending sum, as xe2_rmsnorm then takes), the bf16 rounding the norm stores, xe2_rope's
arithmetic on its frequency table, xe2_kv_store's conversion. A sub-group a (token, head), the head
staged in local memory for the rotary pairs. The schemas are libr4d's.

XE2_NO_FUSED_PROLOGUE=1 leaves the two rows undeclared, so an architecture takes its unfused chain:
the A/B, and an escape hatch.

Gemma 4 E2B: greedy outputs identical with and without (4 requests), decode 58.0 -> 58.6 tok/s.
A random Gemma 3 (v_norm 0): identical, 1570 -> 1600 tok/s. Default fixture 2144/2144.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 20:29:25 +01:00
aneinanderandClaude Opus 5.5 25c8fbd136 libxe2: qk_norm_rope, conv1d_dw, conv2d, attn_local_rel rows
The encoder towers' ops that had only a host kernel: on the SYCL backend every op runs on the card,
so a container carrying Gemma 4's vision tower (qk_norm_rope, blocks mode, v_norm) or its audio
conformer (conv2d subsampler, conv1d_dw, attn_local_rel) refused to start. qk_norm_rope also serves
GLM's vision tower (axial) and any QK-norm model that declares the fused op.

Each is libref's loop, a work-item an output (a (row, head) for qk_norm_rope and attn_local_rel),
for passes that run once a picture or clip. cu_seqlens stays on the card, so each work-item finds
its own segment.

rad-kbench, Gemma 4 E2B container: qk_norm_rope 80/80, conv1d_dw 64/64, conv2d 34/34,
attn_local_rel 64/64; default fixture 2144/2144. Gemma 4 E2B now serves on Intel: text and an
image request answer correctly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 14:28:38 +01:00
aneinanderandClaude Opus 5.5 ff4b7c9fb4 libxe2: rmsnorm_p, relu, logit_softcap, rel_sinusoid, pool_rows rows; rope to head_dim 512
Gemma 4 E2B did not start on Intel: five weightless ops had no device row (rmsnorm_p, the bare
value norm, in 15 bands; relu; logit_softcap; rel_sinusoid; pool_rows), and xe2_rope was selected
for its global layers (head_dim 512, proportional rope widened to the full head) and refused them
at launch: the frequency table held head_dim <= 256. It now holds 512, its component index as int8
so the by-value table stays at 1.25 KB.

rmsnorm_p is xe2_rmsnorm with the gain absent; the others are libref's chains (tanh, exp, sin, cos
in double rounded once; pool_rows' f32 sum in row order, rounded, times mult, rounded).

rad-kbench on the Gemma 4 E2B container: rmsnorm_p 20, relu 20, logit_softcap 4, rel_sinusoid 5,
pool_rows 6 cases ok, rope 300/300; default fixture rope 162/162.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 14:15:31 +01:00
aneinanderandClaude Opus 5.5 e1e21935cc docs: SYCL_PROGRESS, generic backend work of 2026-11-08 (changes 1-5, op coverage, gdn analysis)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:28:22 +01:00
aneinanderandClaude Opus 5.5 b0ac7fd42c libxe2: device rows for gelu, silu, gelu_tanh, scale, mul_weight, clamp, fill, iota, act_mul, gelu_mul
These weightless elementwise ops had no libxe2 row, and an op with no weights cannot be placed on
the host, so a model whose graph declares one refused to start on Intel ("no device kernel for op
'gelu_mul' in any plugin"). libr4d serves them; the architectures that use them include Gemma 3
and 4, the embedding models (nomic-bert, embgemma, nemotron-embed), Qwen3-ASR, LFM2's SigLIP2,
Nemotron-H and the diffusion and audio models.

Each is libref's chain element by element (xe2_elem_act.cpp): erf, tanh and exp in double rounded
once to float; silu (alone or in act_mul) to a bf16 result takes the float exp and libref's chain
again near a rounding tie, as silu_mul and sigmoid do. gelu and gelu_tanh stay in double: 1 +
erf(x) cancels for negative x, so a float erf's error is not bounded by the result's.

rad-kbench: the nemotronh + moe + default fixtures, 339/339 (act_mul 60, mul_weight 10, iota 9,
silu 20); a random-weight 2-layer Gemma3 converted to .rad, every resolved kernel agrees with
libref (gelu_mul 10 cases). That Gemma3 now serves (1.5k tok/s decode on the B65); without these
rows it does not start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:15:46 +01:00
aneinanderandClaude Opus 5.5 d04a27fad3 libxe2: gemm_nt_bias on the fast GEMMs, the epilogue in libref's order
gemm_nt_bias (Y = A B^T + bias, then gelu / gelu_tanh and a residual) had only the
correctness-first row: one work-item an output over ascending k. 22 architectures use it
(the ViT, SigLIP2, GLM-vision, SAM and Gemma4-audio blocks, Qwen3-ASR, nomic-bert, the
diffusion VAEs and UNets). The new row forms A B^T on the existing bf16 kernels (the skinny
GEMV at M <= 16, XMX above; each falls back to the exact kernel where its layout is refused)
into an f32 workspace, and gemm_plain runs only its epilogue on it, so the bias, activation,
residual and their roundings are the reference row's. XE2_EXACT=1 keeps the ref row.

rad-kbench: fixture 210/210 (worst rel_l2 1.7e-4), full fixture 2144/2144; the
Qwen3.5-9B vision tower's shapes all agree with libref. N = K = 4608 + gelu on the B65:
M = 1 1,627 -> 81 us, M = 16 8,221 -> 104, M = 128 74,573 -> 253, M = 512 302,924 -> 721.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:54:54 +01:00
claudeandClaude Opus 5.5 6abca01f17 libxe2: w4a16 decode GEMM in 16-row blocks, each group's codes decoded once
gemm_nt_q at w4a16_asym (M <= 64) ran 8-row blocks, each reading and decoding the whole 4-bit weight:
16 rows paid twice, 64 rows eight times. launch16x2 takes two 8-row bands against each group's codes,
loaded and decoded once, the activation loaded 32 columns at a time so both bands fit the default
register file (no spill). The per-row arithmetic is launch16<8>'s. XE2_W4_RB8=1 keeps 8-row blocks.

Qwen3.8-27B int4 (RedHatAI, as shipped), MTP depth 3, Arc Pro B65: 4 concurrent 256-token streams
97.6-99.2 -> 109.4-110.0 tok/s aggregate (+12%); one stream unchanged (43.1 -> 43.2). XE2_W4_CHECK=50
against libref's loop on the host: rel_l2 <= 6.6e-5 on every shape, tens of ties in ~10^5 outputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 01:53:59 +01:00
claudeandClaude Opus 5.5 2f1fdd4d11 libxe2: bf16 GEMV at 9-16 rows on DPAS, the weight read once
At 9 <= M <= 16 the bf16 skinny GEMM (gemm_nt, logits_gemm) fell to the SIMT kernel's one column a
sub-group, 6-8x the 8-row DPAS kernel's time on the same weight. The ESIMD kernel gains RC = 16: two
8-row DPAS on each transposed weight tile, rows past M clamped by the 2D load and not stored.

MiniCPM5-2B bf16 on the Arc Pro B65 (rad-kbench --bench, cold weights, M = 16): gate_up
712 -> 104 us, down 465 -> 61, qkv 148 -> 29, o 145 -> 25. Twelve concurrent 256-token streams:
198 -> 654 tok/s aggregate. rad-kbench gemm_nt + logits_gemm: MiniCPM5 360/360, fixture 686/686.
XE2_GEMV_SIMT=1 keeps the SIMT form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 01:38:14 +01:00
claudeandClaude Opus 5.5 3582900903 libxe2: DPAS flash attention at head_dim 64 and 128, not only 256
attn_flash_esimd (decode / verify and prefill) and attn_flash_quad (prefill) were written over HD
but gated to head_dim 256 (Qwen3.8's full attention); every other model fell to the SIMT kernel.
Both now dispatch 64, 128 and 256; the decode merge takes HD / 16 values a lane.

MiniCPM5-2B bf16 (head_dim 128, gqa 8) on the Arc Pro B65, same build, XE2_ATTN_SIMT=1 as before:
decode 69.3 -> 83.1 tok/s, prefill at ~2k tokens 1806 -> 8080 tok/s. rad-kbench attn_paged:
fixture 207/207, MiniCPM5 160/160, Qwen3.8-27B 160/160. KL against XE2_EXACT=1 over the
12-document corpus: mean 0.00060, top-1 98.59% (the SIMT kernel: 0.00060, 98.59%).
Qwen3.8-27B int4 unchanged (30.1 tok/s, 1361 tok/s prefill).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 01:16:14 +01:00
claudeandClaude Opus 5.5 989db71bfc docs: the engine baseline, RedHatAI Qwen3.8-27B-INT4 as shipped, with and without MTP, beside stock vLLM 0.33
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 00:45:10 +01:00
claudeandClaude Opus 5.5 098b1779fc docs: the PARO-M2XFP4 baseline on the v1.17 merge (bench-standard quick)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 22:46:43 +01:00
claudeandClaude Opus 5.5 45f3b510c7 Merge upstream main (v1.15.1 -> v1.17.0, 152 commits) into the SYCL port
Conflicts, both sides kept:
- abi: RAD_ABI_VERSION 37 (upstream); the fork's RadBuildCtx.plain_norm after upstream's
  expert_file_tier, widened to int64_t so it starts past ABI 37's 208-byte struct instead of in
  its tail padding (abi_layout_test); RadSyclStream rows after RadShapeGen*.
- arch/common/rad_block_gdn_fp8.h: upstream's q8_rot guard and the fork's o_plain guard
  combined; the decode-row q_o.step only where q_o is declared (!o_plain).
- docs/OPS.md: upstream's optional params on sample_logprobs, the fork's q_temp on
  mtp_couple_propose.

Also ignores /baseline-models/ (local model copies).

Host tests: arch_test's MTP lint/graph-pin failures are unchanged from before the merge (the
fork's mtp.fc LinearFP8, 10a99a5); avx_check's hand-built moe_gemm_q w4a8 case also fails on
upstream's own files; images/videos need FFmpeg; three binaries over their CPU budget on this VM.
SYCL card tests 3/3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 22:13:08 +01:00
Code000 451b136874 tests: the preemption cases pin --prefill-interleave 0
The served default --prefill-interleave auto:1 (previous commit) follows measured step times, so the
four sequences of preemption_by_recompute_continues_each_stream_exactly sometimes never overlapped
enough to preempt and the test's CHECK(n > 0) failed in about half the runs under a loaded host
(plain main: 6/6 pass). The cases are sized for the fixed schedule they were written against;
small_pool_args() now pins it. Nothing they check is loosened: the streams must still match and
preemption still happen. With the flag: 6/6 alone and 3/3 beside 40 busy threads, and the case
takes 3 s again instead of 5-12 s.
2026-11-05 20:37:24 +01:00
Code000 a58304632a scheduler: --prefill-interleave defaults to auto:1 where nothing pins the schedule
Cause: with --prefill-interleave 0 every step carries a chunk while a prompt prefills, so a
sequence already decoding gets one token group per chunk step. On Qwen3.8-Flash-Next fp8 (TP2,
MTP 3 drafts) with 8 sessions decoding while 64K-token prompts prefill, that is 12.3 tokens/s a
session against ~83 alone; with 4 such prompts at once, 5.4.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

download.test.js 31 -> 34 checks:

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

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

history.test.js 29 -> 37 checks:

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

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

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

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

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

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

The blocking pair:

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

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

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

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

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

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

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

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

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

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

Docs only, no code touched.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Not deployed. Goes to review with the separator commits.

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

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

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

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

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

Not deployed. Goes to review with the separator commits.

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

So the history line now reads:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Found by an independent review pass on the previous changeset.

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

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

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

Found by an independent review pass on the fix itself.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Thanks to @RikshaDriver, @keptn42, @mici81 and @gostar.
2026-11-02 18:35:02 +01:00
1036 changed files with 214858 additions and 62662 deletions

No files matched your search

+2
View File
@@ -5,3 +5,5 @@ build*
.claude
**/*.rad
compile_commands.json
dashboard/node_modules
dashboard/dist
+1
View File
@@ -6,3 +6,4 @@ compile_commands.json
/sync-jarvis.sh
__pycache__/
.cache/
/baseline-models/
-22
View File
@@ -1,22 +0,0 @@
# Codeberg CI (Woodpecker): the full suite on a machine without ROCm -- the CPU-only build, the
# same posture as `./build.sh --no-hip` -- on the current Ubuntu LTS. The LTS is chosen, not
# assumed: the media codecs must be new enough for the FFmpeg >= 7 callback signatures the mp4
# writer binds (24.04's 6.1 does not compile), and the card suites (`*_card`, LABELS "gpu") want
# hardware this runner does not have, so the run is the host preset -- everything but gpu and oot.
# vendor_sums runs here as everywhere: a changed lift that the vendor record does not carry fails
# CI before it fails a user.
when:
- event: [push, pull_request, tag]
steps:
test:
image: ubuntu:26.04
commands:
- export DEBIAN_FRONTEND=noninteractive
- apt-get update -qq
- apt-get install -y -qq --no-install-recommends git cmake ninja-build g++ pkg-config jq
ca-certificates libavformat-dev libavcodec-dev libavutil-dev libswscale-dev
libswresample-dev
- cmake -S . -B build -G Ninja -DRAD_WITH_HIP=OFF -DRAD_WITH_FFMPEG=AUTO
- cmake --build build -j "$(nproc)"
- ctest --preset host # everything but gpu and oot, in the configured build dir
+14 -10
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.21)
# 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.15.1 LANGUAGES C CXX)
project(radiance VERSION 2.1.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -20,6 +20,7 @@ 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_ENABLE_KV_ROLLBACK_TEST_HOOK "Compile the test-only device KV rollback observer" OFF)
option(RAD_ASAN "Build host code with AddressSanitizer and UBSan" OFF)
option(RAD_TSAN "Build host code with ThreadSanitizer" OFF)
# LLVM 24's VOPD pairing is not repeatable unless patched (docker/llvm-vopd-pairing.patch); when
@@ -194,7 +195,7 @@ file(MAKE_DIRECTORY ${RAD_PLUGIN_OUT}/kernels ${RAD_PLUGIN_OUT}/architectures)
# 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:
# IQ8R container that carries its DFlash2 drafter:
#
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels.rkb
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb)
@@ -205,8 +206,8 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels.rkb)
endif()
# 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
# The 27B is dense with a DFlash2 drafter and gqa 6; the 35B-A3B IQ8R container is routed
# (moe_gemm_q, the fused router, moe_gather, scale_rows) with an MTP head and gqa 8. Re-record with
#
# rad-kbench -m <model.rad> --max-cases 1 --record data/kernels_moe.rkb
#
@@ -258,8 +259,8 @@ foreach(tok 1 8 16 128)
list(APPEND RAD_M2XFP4_FIXTURES ${RAD_PLUGIN_OUT}/kernels_m2xfp4_m${tok}.rkb)
endif()
endforeach()
# 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.
# The downloader behind a model source naming a repo, `model: <owner/name>` (core/hf_model.cpp).
# The engine looks in <bin>/../libexec/radiance/, so the build tree mirrors that layout.
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
${CMAKE_BINARY_DIR}/libexec/radiance/hfget.sh COPYONLY)
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
@@ -391,8 +392,9 @@ if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt)
endif()
# libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP
# toolchain. It declares itself for `^gfx11` and returns without a target when the build's
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it. A card
# with no kernel library of its own refuses device-only ops (docs/PLUGIN.md §10).
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it, and
# declines every machine without a gfx11 card (rad_plugin_open). A card with no kernel library of
# its own refuses device-only ops (docs/PLUGIN.md §10).
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt)
add_subdirectory(libr3d)
endif()
@@ -479,9 +481,11 @@ install(FILES
install(FILES LICENSE NOTICE DESTINATION ${CMAKE_INSTALL_DOCDIR})
install(FILES vendor/llama/LICENSE
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME llama.cpp.LICENSE)
install(FILES vendor/nlohmann/LICENSE.MIT
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME nlohmann-json.LICENSE)
install(FILES vendor/yyjson/LICENSE
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME yyjson.LICENSE)
install(FILES vendor/cpp-httplib/LICENSE
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME cpp-httplib.LICENSE)
install(FILES core/server/LICENSE.lfm
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME liquidai-d1.LICENSE)
install(FILES dashboard/THIRD-PARTY-LICENSES.txt
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME dashboard.LICENSES)
+11 -8
View File
@@ -28,10 +28,12 @@
# and refuses a compressed bundle.
#
# 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:
# ./build.sh. They are the targets of the shipped kernel libraries, each of which keeps only its own
# family: libr4d takes gfx1201 (RDNA4), libr3d gfx11-generic (every RDNA3 chip) and gfx1151, and
# libhalo gfx1151 (Strix Halo), where the loader prefers it over libr3d. On any one card the other
# libraries decline or are left out, so the default image serves all three. The engine's own
# kernels carry the generic family targets and run on every AMD GPU family, so a kernel library for
# another card is added by mounting it on the search path:
# docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance
#
# The image's ROCm userspace must be supported by the host's amdgpu kernel driver; it is pinned to
@@ -131,7 +133,7 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
# ------------------------------------------------------------------------------------------ build
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build
ARG GPU_TARGETS=gfx1201
ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
# Parallel compile jobs; empty means one per core. A device-kernel translation unit takes 2-3 GB
# of RAM under hipcc, so lower it on a host that is also serving.
ARG JOBS=
@@ -227,11 +229,12 @@ ARG TEST_EXCLUDE=
# 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).
# (tests/oot_plugins.sh). The `parity` entry (halo_parity: libhalo's tables against libr4d's) is
# left out until libhalo has ported the ops libr4d added after it (the test names each one).
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
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}"} \
ctest --test-dir /build -LE 'gpu|oot|parity' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \
-j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \
&& touch /build/host-tests-passed
@@ -283,7 +286,7 @@ RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \
# ---------------------------------------------------------------------------------------- runtime
FROM scratch AS runtime
ARG GPU_TARGETS=gfx1201
ARG GPU_TARGETS="gfx1201;gfx11-generic;gfx1151"
ARG VERSION=dev
ARG REVISION=unknown
+77 -16
View File
@@ -19,13 +19,31 @@ Written by Deadcode, with contributions from:
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared
layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio
encoder, its i8a8 linears and its KV heads replicated over ranks, 4-bit weights at decode heights
through w4a16_asym, and the Ornith-1.5-122B compose files
through w4a16_asym, the Ornith-1.5-122B compose files, the Gemma 4 31B's asymmetric int5
linears (w5a8i8 and w5a16), the junctions at quant_act_i8g's grid (rmsnorm_quant_i8g,
gelu_mul_quant_i8g and ar_rmsnorm_quant_i8g) with the prefill overlap on the i8a8, a4 and w5
grids, the 31B's i8g, heretic-ara-i8g and w5 compose files, and Ling-3.0-flash (bailing_hybrid:
KDA, dense latent attention, group-limited sigmoid routing, the clipped SwiGLU and its MTP layer as
a serial drafter) with mla_attn_paged, its w4a8 recipes and compose files, possessive quantifiers
in the tokenizer's patterns, the Grafana dashboard's first screen, and Gemma 4 12B (its picture
and audio embedders, a picture's placeholders read both ways on the sliding layers, the windowed
attention at head_dim 512, suppress_tokens) with its compose files, and
NVIDIA-Nemotron-3.5-Bolt-74B-A9B (nemotronh: Mamba-2 with ssd_update and ple_conv_bias, the
latent MoE's ungated relu^2 experts, NoPE attention with KV heads replicated over ranks, the
paged attention at head_dim 128 and gqa 16, attention sinks) with NVIDIA's LiLiCorr drafter
(RadBatch::anchor_rows, the candidate correlator), the C-RADIO vision tower and video tubelets,
calibration in layer ranges, its recipes and compose files, and the kernel report's fixture
- mechkbfan: the token embedding in the pinned host pool
- Code000: the n-gram gather on the card and the MTP head's history-pass skip, and the MTP draft
coupling with its cooperative verify (--draft-coupling), the W4A8 prefill's tail scale read, the
ISA instruments' VGPR granule, back-edge count and fail-closed parse, scored steps
(rad_declare_scores, RadBatch::score_only), the gated prefill fold, the short-prompt split row and
the rows forms of rmsnorm and rope, and LFM2's 8-bit trunk with the d1-3B recipe
the rows forms of rmsnorm and rope, LFM2's 8-bit trunk with the d1-3B recipe, the file tier's
routed reads with their own router's counts and its deposit wait, the stop-string hold-back, and
the sampler's planes by the step's token bound, its n-gram ban beside a drafter and no candidate
cut over a top-1 row, and --prefill-interleave auto[:SHARE], sized from measured step times and
served by default, and the diagnose mode, in which the engine measures itself, with its token
parity and reproducibility checks
- 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
@@ -38,11 +56,11 @@ Written by Deadcode, with contributions from:
host) and decode-hot residency (--expert-profile, --expert-pin-top), prefix hits over KV groups of
different block sizes and a hybrid's window in the checkpoint slot, --prefix-resume exact,
DeepSeek-V4.1-Flash's conversion from its release (the Engram tables, the fused imatrix, the
UD-IQ1_S recipe and rad-convert --chat-template), a preempted prefill admitted only with its
whole recompute and the running sequences' next blocks free and the bound on its wait
(--preempt-wait-ms), prompt lookup alone (--spec-ngram) with each sequence's n-gram index and
the gate that verifies a proposal only when it pays, and DeepSeek-V4.1's reply format with its
DSML tool calls
UD-IQ1_S recipe and rad-convert --chat-template), a preempted prefill admitted only with its whole
recompute and the running sequences' next blocks free and the bound on its wait
(--preempt-wait-ms), prompt lookup alone (--spec-ngram) with each sequence's n-gram index and the
gate that verifies a proposal only when it pays, and DeepSeek-V4.1's reply format with its DSML
tool calls, and expert_stats_report.py, and the KL mode's own line in the VRAM shortfall report
- 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
@@ -85,7 +103,10 @@ Written by Deadcode, with contributions from:
split by depth, the delta net's out-projection read beside its decode recurrent update, the MXFP4
feed-forward's gated fold up to 16 rows, the three-wave verify floor bounded by the batch's
workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6
paged prefill, and the preempted-prefill gate past a KV group that holds no blocks
paged prefill, the preempted-prefill gate past a KV group that holds no blocks, and the norms'
lane sum issuing its reads eight at a time, chained forms for every kernel of
Qwen3.8-Flash-Next's decode step with hc_read's forms G, S and B3, and a preempted request
publishing its prefix with an overdue one keeping its place
- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the
out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8
linears' operands directly
@@ -106,21 +127,32 @@ Written by Deadcode, with contributions from:
one-sequence KV floor over the live plan, and prefill staging paid by expert residency
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and
the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped
rotation
rotation, the dashboard's history line, session extremes, card-count changes and Requests-header
JSON export, with the page's JavaScript driven by tests/js
- C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual
projection, KV streaming for a context bigger than VRAM (--kv-resident), and the dashboard's
request history, KV streaming traffic and one-unit KV meter
request history, KV streaming traffic and one-unit KV meter, and the mapped tier kept in the page
cache across a load
- J-Nova: Unlimited-OCR, and Sage-A1.5 with its vision tower and its DFlash2 drafter
- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8)
- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8), and the
diagnosis of the expert loan held at zero by leftover cache blocks
- lortht: Krea 2's rebalance of the text taps and its presets, MiniMax-H3's modulation rows, and
keyframes carried through a latent upscale
- Quackster: cards with a small PCI BAR, their kernel arguments kept in host memory
- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix
- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix, and
Breeze-TTS-2's native voice cloning with its delivery direction (the Qwen3-TTS reference encoder,
vq_euclidean and elu)
- gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its
BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode
(the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds)
(the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds),
and the head-256 prefill softmax rescaled by row rather than by wave, Spark 2.5 (spark25: bf16 and
rotated-int8 IQ8R checkpoints, tensor parallelism with exact collectives, reasoning and tagged
tool calls) with its DSpark drafter (exact attention and Markov walk ops), the prefill split keyed
by live KV bounds, and --gpu-memory-mib
- launch80_assets: tuning collectives as the exchange they serve at the served configuration, the
per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch
per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch, and
Meta Muse Glimmer 30B -- the museglimmer plugins, its windowed vision tower, its DFlash drafter,
the ATEM tool dialect and its context extension
- hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2
drafter -- and the ParoQuant M2XFP4 import
- steki: Gemma 4 E2B's per-layer MLP width and the bf16 descriptor for Google's E2B/E4B
@@ -134,7 +166,12 @@ Written by Deadcode, with contributions from:
- Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid
wait trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS
and its gated three-tile form at 8 waves
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library, and its wave-matrix rewrite: the GEMMs
retiled to 16x128 blocks, the grouped MoE GEMMs, the norms and quantisers, and the QSA and MoE
router rows, its MoE GEMMs at w4a8 and w4a4 with dequant_w4, row_topk_merge, ngram_ids and the
biased and short GEMMs, and w4a4's reference implementation, and Ling-3.0-tiny on bailing_hybrid
from its GGUF releases (the K-quant and IQ4_NL imports, the MLA query LoRA) with libr3d's
gemm_nt_f32, ple_conv, grouped router, kda_update, mla_project and mla_attn_paged
- fl0l0u: every request entry point bounded, gated and sanitised (JSON parses bounded in depth,
errors safe on invalid UTF-8, control bytes kept off the log, the dashboard's CSP, cross-origin
browsers refused on the loopback-only routes, method-scoped API-key exemptions), prompt ids that
@@ -150,6 +187,23 @@ Written by Deadcode, with contributions from:
hot VRAM cache with its deposits and copyless relabels, and GLM-5.3-Flash's experts read
file-direct under expert parallelism -- the stall watch counting drive reads as progress, and
the DMA lane's lists fenced so a stalled read pointer no longer fills its ring
- pokesjw: the n-gram reader refilling its reads as they land, and a decode gather waiting on the
other rank's read of a row instead of reading it again
- AnimusNull: GLM-5.3-Flash on four cards -- its experts split by width, the small-M MXFP4 expert
form at the TP4 slices, the indexer's take-all steps -- its E4M3 latent cache (mla_attn's fp8kv
rows), and the DMA lane's room check over a reused fence slot
- neuromanMD: libr3d's MXFP4 GEMM leaving VRAM exponent planes unscanned from the host, and its
branch-free e4m3_to_f32
- everplays: the paged attention at seven queries a KV head, head_dim 128 (Nanbeige4.3-33B), and
Recursive Flint -- its plugin, the sink-aware WMMA prefill attention and the fused prologue at
rotary_dim 0
- Kezi: the decode tile arms of the int4 and int5 x int8 GEMM
- dschmitz: the two-rank fused writes' host-mailbox twins taking their chained forms, the card
telemetry's junction temperature, and a replayed tool call's blank arguments read as the empty
object with arguments that are not JSON refused naming the call
- eniga: the diagnosis of GLM-5.3-Flash's template refused for tools (jinja's unique filter)
- tnhnyzc: the mixed-step service-time target (mixed-step-target-ms)
- aelfwyne: the diagnosis of draft trees refusing the int8 KV cache's rows
This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each.
@@ -158,9 +212,16 @@ license text is in the file named beside each.
vendor/llama/, and the code lifted or ported from it: core/sample/gbnf.*, the
host samplers in core/sample/host_ref.*, the tokenisers in core/text/, and
libquant/lq_ggml_*
nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT
yyjson Copyright (c) 2020 YaoYuan vendor/yyjson/LICENSE
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
The dashboard's page, compiled into the server from core/server/dashboard_page.h, carries
third-party software built into it: React, Base UI and Floating UI, uPlot, shadcn/ui's components
and helpers, Tailwind CSS's generated style and tw-animate-css (MIT), class-variance-authority
(Apache-2.0), the Lucide icons (ISC), and the Geist and Geist Mono typefaces (SIL Open Font License
1.1, Copyright the Geist Project Authors). dashboard/THIRD-PARTY-LICENSES.txt lists every package
with its version and license text, as the page's build wrote it.
tests/data/chat/hyv3/chat_template.jinja is Tencent's Hy-Memory-30B-A3B chat template,
copied unchanged from tencent/Hy-Memory-30B-A3B on Hugging Face.
Copyright (C) 2026 Tencent. All rights reserved. Licensed under Apache-2.0 (LICENSE).
+214 -137
View File
@@ -6,7 +6,8 @@ APIs, Anthropic's Messages API and llama-server's native one, so their clients a
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
The bundled device kernels target AMD RDNA4 (`libr4d`: `gfx1200`, `gfx1201`), RDNA3 (`libr3d`:
`gfx11xx`) and Strix Halo (`libhalo`: `gfx1151`). The serve settings
below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family;
another card needs a kernel library for it. A machine with no GPU builds the host backend, whose
AVX-512/AVX2 kernels (`libavx`) serve every model here: the small ones (EmbeddingGemma 2,
@@ -86,61 +87,63 @@ it (`-DRAD_XE2_MKL=OFF`, or `XE2_NO_MKL=1` at run time, keeps the hand-written p
## Models
| model | container | get it | compose file |
| model | container | get it | fleet file |
|---|---|---|---|
| Qwen3.8-Flash-Next: 4-bit experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-fp8-iq4r-moe.rad` (114 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe) | `flashnext.yaml` |
| Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` |
| Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` |
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
| 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` |
| Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` |
| Ornith-1.5-122B FP8, MTP, vision, four cards | `ornith-1.5-122b-fp8.rad` (118 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-fp8) | `ornith-1.5-122b.yaml` |
| Ornith-1.5-122B FP8, DFlash2 drafter, vision, four cards | `ornith-1.5-122b-fp8-dflash2.rad` (116 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-fp8-dflash2) | `ornith-1.5-122b-df2.yaml` |
| Ornith-1.5-122B w4a8: 4-bit experts (GPTQ), MTP, vision, four cards | `ornith-1.5-122b-w4a8.rad` (65 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-w4a8) | `ornith-1.5-122b-w4a8.yaml` |
| Ornith-1.5-122B w4a8: 4-bit experts (GPTQ), DFlash2 drafter, vision, four cards | `ornith-1.5-122b-w4a8-dflash2.rad` (64 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-w4a8-dflash2) | `ornith-1.5-122b-w4a8-df2.yaml` |
| Sage-A1.5 FP8, MTP, vision | `sage-a1.5-fp8.rad` (35 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8) | `sage-a1.5.yaml`, `sage-a1.5-tp1.yaml` |
| Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.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 w5: GPTQ int5 trunk (a scale and a zero point per 128 weights), MTP, vision | `gemma4-31b-w5.rad` (23 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w5) | `gemma4-31b-w5.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` |
| Gemma 4 31B: int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-i8g) | `gemma4-31b-i8g.yaml` |
| Gemma 4 31B heretic-ara (refusals removed): int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-heretic-ara-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-i8g) | `gemma4-31b-heretic-ara-i8g.yaml` |
| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (22 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash) | `gemma4-31b-w4a8-df.yaml` |
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` |
| Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` |
| Gemma 4 31B on four or two cards: int4 trunk, int8 activations and lm_head, a block-16 DFlash2 drafter (15 drafts a step, verified as a tree), vision | `gemma4-31b-dense-w4a8-df2b16-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2-b16) | `gemma4-31b-w4a8-df2b16-tp4.yaml`, `gemma4-31b-w4a8-df2b16-tp2.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16 (Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-bf16.rad` (17 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-bf16) | `nemotron-3.5-bolt-e4b-bf16.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-i8g.rad` (13 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-i8g) | `nemotron-3.5-bolt-e4b-i8g.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-E4B 4-bit (int4 feed-forward, GPTQ, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-a4.rad` (12 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-a4) | `nemotron-3.5-bolt-e4b-a4.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` |
| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | `unlimited-ocr-bf16.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` |
| Fish Audio drama-3: speech with speaker tags and inline direction, voices cloned from reference clips, whole, streamed or live; block-FP8 experts, two cards | `drama3-fp8.rad` (36 GiB) | [convert](#convert-a-checkpoint) | `drama3.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, vision, eight cards | `glm53-flash-mxfp4.rad` (172 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` |
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | `sdxl.yaml` |
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
| nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | - |
| Qwen3.8-Flash-Next: IQR-V4 experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-iqr-v4.rad` (113 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-iqr-v4) | `tp1.yaml`, `tp2.yaml` |
| Qwen3.8-27B IQ8R (rotated int8), DFlash2 drafter, vision | `qwen3.8-27b-iq8r-dflash.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iq8r-dflash) | `tp2.yaml` |
| Qwen3.8-27B IQR-V4, 2.5 to 8 bits a weight ([docs/IQR.md](docs/IQR.md)), DFlash2 drafter, vision | `qwen3.8-27b-iq2r-v4.rad` .. `qwen3.8-27b-iq8r-v4.rad` (10 to 28 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4) | `tp1.yaml` (IQ4R-L) |
| Qwen3.6-35B-A3B IQ8R, MTP | `qwen3.6-35b-a3b-iq8r.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-iq8r) | — |
| MiniCPM5-2B IQ8R, DSpark drafter | `minicpm5-2b-iq8r.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r) | `tp1.yaml`, `tp2.yaml` |
| MiniCPM5-2B bf16 (served without its drafter) | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | — |
| Spark X2.6 4B bf16: thinking and tool calls, one to four cards | `spark-x2.6-4b-bf16.rad` (8.3 GiB) | [convert](#convert-a-checkpoint) | — |
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | — |
| Gemma 4 31B w5: GPTQ int5 trunk (a scale and a zero point per 128 weights), MTP, vision | `gemma4-31b-w5.rad` (23 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w5) | — |
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | — |
| Gemma 4 31B: int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-i8g) | — |
| Gemma 4 31B heretic-ara (refusals removed): int8 trunk and lm_head (no calibration), MTP, vision | `gemma4-31b-heretic-ara-i8g.rad` (33 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-i8g) | — |
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | — |
| Gemma 4 12B bf16: MTP, vision, audio | `gemma4-12b-bf16.rad` (25 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-bf16) | — |
| Gemma 4 12B int8 (i8a8): MTP, vision, audio | `gemma4-12b-i8g.rad` (14 GiB) | [download](https://huggingface.co/keptn/gemma4-12b-i8g) | — |
| Qwen-Image 2.1 IQ8R: text to image and image edits | `qwen-image-2.1-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-iq8r) | `tp1.yaml`, `tp2.yaml` |
| Qwen-Image 2.1 Turbo IQ8R: the same in 8 steps | `qwen-image-2.1-turbo-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-iq8r) | — |
| Krea 2 Turbo IQ8R: text to image, one card | `krea-2-turbo-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-iq8r) | — |
| Krea 2 Raw IQ8R: the same, undistilled | `krea-2-raw-iq8r.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-iq8r) | — |
| FLUX.3 [klein] IQ8R: text to image and edits from up to ten pictures, one card | `flux-3-klein-iq8r.rad` (9.4 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-iq8r) | — |
| FLUX.3 [klein] base IQ8R | `flux-3-klein-base-iq8r.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-iq8r) | — |
| LTX-2.5 distilled IQ8R: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-iq8r.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-iq8r) | — |
| LTX-2.5 base IQ8R | `ltx-2.5-iq8r.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-iq8r) | — |
| MiniMax-H3, int8 DiT: video with its stereo soundtrack from text | `minimax-h3-i8.rad` (63 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-i8) | `tp2.yaml` |
| FastH3 8-Step V2, int8 DiT: the same in eight steps | `fasth3-8-step-v2-i8.rad` (65 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-i8) | — |
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `tp1.yaml`, `tp2.yaml` |
| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | — |
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `tp1.yaml`, `tp2.yaml` |
| TranslateGemma 27B, int8 trunk: translation | `translategemma-27b-i8.rad` (28 GiB) | [download](https://huggingface.co/StillDeadcode/translategemma-27b-i8) | — |
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | — |
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | — |
| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | — |
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `tp1.yaml`, `tp2.yaml` |
| nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | — |
| LiquidAI LFM3-1.7B IQ8R: rotated int8 trunk, bf16 head; text, tool calls and reasoning, one card | `lfm3-1.7b-iq8r.rad` (2.5 GiB) | [convert](#convert-a-checkpoint) with `data/recipes/lfm3-1.7b-iq8r.recipe` | — |
| LiquidAI LFM3-1.7B bf16: text, tool calls and reasoning, one card | `lfm3-1.7b-bf16.rad` (3.8 GiB) | [convert](#convert-a-checkpoint) | — |
| Meta Muse Glimmer 30B bf16: text, images and video; sliding-window rotary layers between NoPE full ones, a windowed ViT | `muse-glimmer-30b-bf16.rad` (56 GiB) | [convert](#convert-a-checkpoint) | — |
| Meta Muse Glimmer 30B w4a8: int4 trunk, images and video, one card | `muse-glimmer-30b-w4a8.rad` (16 GiB) | [convert](#convert-a-checkpoint) | — |
| Meta Muse Glimmer 30B IQ8R: rotated int8 trunk, int8 head, DFlash drafter, images and video | `muse-glimmer-30b-iq8r-dflash.rad` (36 GiB) | [download](https://huggingface.co/StillDeadcode/muse-glimmer-30b-iq8r-dflash) | — |
| Recursive Flint (39.8B, about 2.5B active) IQ8R: rotated int8 trunk and experts, two cards | `flint-iq8r.rad` (38 GiB) | [download](https://huggingface.co/StillDeadcode/flint-iq8r) | — |
| Ling-3.0-tiny IQ8R: rotated int8 trunk and experts, one card | `ling-3.0-tiny-iq8r.rad` (7.9 GiB) | [download](https://huggingface.co/StillDeadcode/ling-3.0-tiny-iq8r) | — |
| Nemotron 3.5 Embed 1B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-1B-BF16) | — |
| Nemotron 3.5 Embed 8B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16) | — |
| Nemotron 3.5 Rerank 8B BF16: text/image document relevance, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16) | — |
| Anima Aesthetic FP8: anime and illustration, text to image, one card (Base and Turbo convert the same way) | `anima-aesthetic-fp8.rad` (3.0 GiB) | [convert](#convert-a-checkpoint) | `anima.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) | — |
| Nemotron 3.5 Rerank 8B BF16: text/image document relevance, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16) | `tp1.yaml`, `tp2.yaml` |
| Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | `tp1.yaml`, `tp2.yaml` |
**Not served by this version.** A container whose weights are block FP8, MXFP4, M2XFP4 or
ParoQuant, or whose experts read E4M3 activations, is refused at startup by the name of the first
such weight. That is every FP8 and MXFP4 container of the models above, and the models that have
no int8 container yet: Ornith-1.5 (35B-A3B and 122B), Sage-A1.5,
NVIDIA-Nemotron-3.5-Bolt-74B-A9B, GLM-5.3-Flash, Ling-3.0-flash-Sante, Fish Audio drama-3 and
Anima's FP8 container (Anima converted to bf16 is served). Each returns with an int8 container.
A container with an int8 or bf16 trunk and a block-FP8 drafter (NVIDIA-Nemotron-3.5-Bolt-E4B,
the Gemma 4 31B DFlash and DFlash2 containers, MiniCPM5-2B bf16) serves without the drafter
under `num-speculative-tokens: 0`.
A container holds everything the server needs: the weights, the tokeniser, the chat template and
any drafter. Each download link's repository has the recipe and the exact command that made the
@@ -148,7 +151,7 @@ file. Download one into your models directory (the transfer resumes if interrupt
```sh
mkdir -p /srv/models/rad && cd /srv/models/rad
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/minicpm5-2b-fp8.rad
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-iq8r/resolve/main/minicpm5-2b-iq8r.rad
```
The Gemma 4 container is keptn42's: GPTQ calibrated in transformers, with an int8 lm_head; its
@@ -158,38 +161,22 @@ with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkp
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 172 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.
Pictures go through its own vision tower, up to 4096 tokens an image at the default encoder pass
(`--mm-max-patches 32000` serves the checkpoint's 8000); the KV cache is bf16. 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.
TranslateGemma 27B is converted from Google's bf16 checkpoint with
`data/recipes/translategemma-27b-i8a8.recipe`, an int8 trunk rounded without calibration data.
Its chat template takes structured turns
naming the two languages and refuses the plain turn the server renders at startup, so its entry
serves a plain Gemma 3 template, `deploy/compose/gemma3.jinja` (`override-chat-template` names it;
in a compose file, mount it into the container), and a client sends on `/v1/completions` the prompt
the checkpoint's template renders.
The Qwen-Image containers serve OpenAI's images API (`/v1/images/generations`, `/v1/images/edits`):
pictures from a prompt, and edits of up to ten pictures with an optional mask, 2048x2048 by default.
On two R9700s a 2048x2048 picture takes 61 s at the base model's 40 steps and 13 s with Turbo (56 and
12 s with `--tp-wire wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research
license, which is non-commercial.
12 s with `tp-wire: wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research
license, which is non-commercial. Krea 2 is under the Krea 2 Community License and Krea's
acceptable use policy, FLUX.3 [klein] under the FLUX Kommunity License (non-commercial use),
LTX-2.5 under the LTX-2.x Community License, and an SDXL finetune under its checkpoint's own
license.
The MiniMax-H3 containers serve OpenAI's video jobs (`/v1/videos`): a video with its stereo
soundtrack from a prompt, 5 to 14 s, up to 1344x768. On two R9700s a 5.17 s clip at 1344x768 takes
@@ -219,21 +206,28 @@ card works best with Resizable BAR on (Above 4G Decoding and Resizable BAR in th
without it the engine keeps kernel arguments in pinned host memory, and every dispatch reads them
over the link. The image
is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels
built for `gfx1201`. Pull it, clone this repository for its compose files, then start a model from
one of them:
built for `gfx1201` (RDNA4), `gfx11-generic` (RDNA3) and `gfx1151` (Strix Halo). Pull it, clone
this repository for its compose files, then start one of them:
```sh
docker pull stilldeadcode/radiance
git clone https://codeberg.org/StillDeadcode/radiance.git
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_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
docker compose -f tp2.yaml up -d # two cards; tp1.yaml for one (RADIANCE_GPU)
docker compose -f tp2.yaml logs -f
docker compose -f tp2.yaml down
```
Every model 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).
A file serves all its models from one container behind one port, and brings a model onto the cards
when a request names it ([`docs/MULTIMODEL.md`](docs/MULTIMODEL.md)): a request's `model` is the
entry's name (`flashnext`, `qwen3.8-27b`, `minicpm5-2b`, ...). The entries are in
`tp1.radiance.yaml` and `tp2.radiance.yaml` beside the compose files, the server's configuration as
it reads it. Delete the entries of the containers
you do not have; any other model from the table is added as an entry with its keys from the table
under [Run without Docker](#run-without-docker). The two files take the same port, so run one at a
time. Running without compose, and the reason for each `docker run` option, is in
[`docs/DOCKER.md`](docs/DOCKER.md).
To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'`
in the clone (it needs `docker buildx` and tests the build as it goes). Then set
@@ -262,74 +256,141 @@ prefix gets `bin/`, `include/radiance/`, `lib/cmake/radiance/`, `libexec/radianc
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
on prefill GEMMs; a compiler that has the same fix is declared with
`-DRAD_HIP_VOPD_REPEATABLE=ON`. ROCm 7.2 is unaffected.
## Run without Docker
```sh
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an 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>
The server reads its settings from a YAML file: `server:` holds the listener, `memory:` the
per-card VRAM budget, and `models:` one entry whose name is the model id requests use. Every key
is named as in the [`docs/GUIDE.md`](docs/GUIDE.md) §4.11 reference; `radiance --help` prints it.
```yaml
# radiance.yaml
server:
port: 8000
models:
minicpm5-2b-iq8r:
model: /srv/models/rad/minicpm5-2b-iq8r.rad # or a Hugging Face repo id: StillDeadcode/minicpm5-2b-iq8r
```
`--model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
and `jq` (`scripts/hfget.sh`) into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere),
```sh
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an install finds its own
build/bin/radiance --config radiance.yaml --check # validate the file, serve nothing
build/bin/radiance --config radiance.yaml
```
`model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
and `jq` (`scripts/hfget.sh`) into `~/.cache/radiance/hf` (`server.download-dir` puts it elsewhere),
serves the container it holds, and checks it for changes at every start; a start that cannot reach
the hub serves the copy it has. The Docker image carries both tools; in a container,
`--download-dir` must name a writable mount, since the compose files mount `/models` read-only.
`server.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.
The server takes no other command-line options. A command line written for an earlier release
(`radiance --model ... --tp 2`) is refused with the same settings printed as YAML, and
`rad-yaml FLAGS...` prints that file without starting anything:
`rad-yaml --model x.rad --tp 2 > radiance.yaml`. [`docs/MULTIMODEL.md`](docs/MULTIMODEL.md) §4
describes the file's levels.
| model | flags |
Each row holds the keys a model is served with in a file of its own (the Flash-Next rows leave out
`prefix-cache-mib`). They go under the model's entry, except `gpu-headroom-mib`, which goes under
`memory:` and in a file of several models holds for all of them. `tp1.radiance.yaml` and
`tp2.radiance.yaml` carry their models' entries as set for sharing the cards; a model added to either takes its row from
here.
| model | keys |
|---|---|
| Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
| Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `--tp 3 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
| Qwen3.8-27B FP8 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` |
| Fish Audio drama-3 | `--tp 2` |
| Qwen3.8-Flash-Next | `tp: 2, tp-wire: wht6, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 24576, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
| Qwen3.8-Flash-Next, one card | `tp: 1, max-num-seqs: 4, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 43000, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 4096, checkpoint-interval: 4096` |
| Qwen3.8-Flash-Next, four ranks | `tp: 4, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 49152, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `tp: 3, max-num-seqs: 8, max-model-len: 200000, placement: expert_tiered, host-pool-mib: 24576, gpu-headroom-mib: 96, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048` |
| Qwen3.8-27B IQ8R and IQR-V4, Qwen3.6-35B-A3B | `tp: 2, max-num-seqs: 32, max-model-len: 200000, kv-cache-dtype: i8` |
| Qwen3.8-27B bf16 | `tp: 2, max-num-seqs: 8, max-model-len: 200000, kv-cache-dtype: i8` |
| MiniCPM5-2B IQ8R and bf16 | `tp: 2, max-num-seqs: 32, max-model-len: 131072, kv-cache-dtype: i8, gpu-headroom-mib: 160, max-num-batched-tokens: 512` |
| Qwen3.8-Flash-Next bf16 | `tp: 2, max-model-len: 32768, placement: expert_tiered, weights-disk-tier: true, host-pool-mib: 24576, gpu-headroom-mib: 768, deterministic: true, max-num-seqs: 32, max-num-batched-tokens: 32768, num-speculative-tokens: 0` |
| Qwen-Image 2.1 and 2.1 Turbo | `tp: 2, tp-wire: wht6` |
| MiniMax-H3 and FastH3 | `tp: 2, vision-tower-placement: ram` |
| MiniMax-Music3 | `tp: 2`, or `tp: 1` (20.5 GiB of weights on the card) |
| Breeze-TTS-2 | `tp: 1` |
| Gemma 4 31B (GPTQ int4) | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 3, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
| Gemma 4 31B w5, heretic-ara int4, int8 and heretic-ara int8 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, vision-tower-placement: ram, num-speculative-tokens: 3, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
| Gemma 4 31B Q8 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: i8, num-speculative-tokens: 0, max-num-batched-tokens: 2048, temp: 1.0, top-p: 0.95, top-k: 64` |
| Gemma 4 12B bf16 | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 3, max-num-batched-tokens: 2048, mm-max-patches: 1120, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}` |
| Gemma 4 12B int8 | `tp: 1, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 3, max-num-batched-tokens: 2048, mm-max-patches: 1120, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}` |
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16, int8 and 4-bit, without the drafter | `tp: 2, max-num-seqs: 8, max-model-len: 65536, kv-cache-dtype: bf16, num-speculative-tokens: 0, mm-max-patches: 2520, vision-tower-placement: ram, temp: 1.0, top-p: 0.95, top-k: 64, chat-template-kwargs: {"enable_thinking":false}`; `tp: 1` on one card |
| TranslateGemma 27B | `tp: 2, max-num-seqs: 8, max-model-len: 16384, kv-cache-dtype: i8`, and `override-chat-template` naming `deploy/compose/gemma3.jinja` |
| Unlimited-OCR | `tp: 1, max-num-seqs: 8, max-model-len: 32768, kv-cache-dtype: i8, gpu-headroom-mib: 96`, and `override-chat-template` naming `deploy/chat-templates/unlimited-ocr-parser.jinja` (`/chat-templates/unlimited-ocr-parser.jinja` in the compose files' container) |
| Krea 2 Turbo and Raw, FLUX.3 [klein] and its base, Stable Diffusion XL | `tp: 1` |
| LTX-2.5 distilled and base | `tp: 1, vision-tower-placement: ram` |
| EmbeddingGemma 2 | `tp: 1, max-num-seqs: 64, max-num-batched-tokens: 8192` |
| Qwen3-ASR 1.7B | `tp: 1, max-num-seqs: 16` |
Every model 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
The 27B in IQ8R and IQR-V4, the 35B-A3B, MiniCPM5 and the Flash-Next bf16 reference run at up to
32 sequences a step. The other Flash-Next rows and the 27B in bf16 keep 8, the one-card Flash-Next
row 4: on a hybrid model each sequence holds its own recurrent state, and 32 of them take that
memory from the attention cache and, on Flash-Next, from the expert slab. See
[`docs/GUIDE.md`](docs/GUIDE.md) §4.4.
At `--tp 4`, decode and verify steps carry the exact all-reduce in the gated residual's write, with
On one card a Flash-Next prefill step copies every pooled expert across the link once, so a
4096-token step shares that copy among twice the tokens of a 2048-token one (26K-token prompts:
2545 against 1413 tok/s); the checkpoint interval matches the step because a prefill chunk never
crosses a checkpoint. At 4 sequences that row's cache holds 301K tokens. The Flash-Next bf16 row
is a reference to calibrate and compare against, a step taking tens of seconds whatever its size;
its 32K of context keeps QSA's score plane for a 32K-token step at 1 GiB.
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
`tp-wire: wht6` selects a different lossy wire, tiered int8 over the two-shot, above
`tp-wire-min-kb`. Eight ranks have no lossy wire, so `tp: 8` with `tp-wire: wht6` stops at startup
naming the all-reduce.
Four ranks is a capacity configuration: its per-step rate against `--tp 2` on the same cards has
not been measured, and its tiering flags are the two-rank recipe carried over. As at two ranks, each
Four ranks is a capacity configuration: its per-step rate against `tp: 2` on the same cards has
not been measured, and its tiering keys are the two-rank recipe carried over. As at two ranks, each
rank owns a slice of every expert's width: each parity's 128-column blocks are cut contiguously over
the ranks and the odd block alternates with the parity, so every rank's share is whole blocks and
every block has one owner. The resident expert bytes per rank are smaller, so the elastic window
has a different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before
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
`host-pool-mib` is what a model pins for its weights in all, each rank an equal share: the
four-rank row pins 48 GiB of RAM (12 GiB a rank) that nothing else can use and the kernel cannot
swap out. The amdgpu driver caps what all processes
together pin at the machine's RAM less 1/64 and 1.5 GiB; the pool is locked user memory, which
`ttm.pages_limit` does not count. A 64 GiB machine serves `flashnext-tp1.yaml` with 49 GiB pinned
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
`ttm.pages_limit` does not count. A 64 GiB machine serves the one-card Flash-Next row alone, with
`prefix-cache-mib: 4096`, at about 49 GiB pinned ([`docs/GUIDE.md`](docs/GUIDE.md) §7). In
`tp1.yaml` its entry carries `prefix-cache-mib: 1024` so its host pins fit such a host beside the
8 GiB the fleet keeps free; there it is unloaded when another model loads, and on a 61 GB host it
answered its next request after 17 to 19 s, loaded from its container again.
Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `--debug-graph`
The Gemma 4 rows sample as the checkpoint's `generation_config` states, and a request switches
thinking (`chat_template_kwargs`). `vision-tower-placement: ram` keeps the vision tower in host
memory, so its VRAM goes to the KV cache. The 31B takes its full 262,144-token context at
`max-model-len: 262144, max-num-seqs: 2`. The 12B keeps a bf16 cache because an 8-bit one costs it
more than it saves; on Bolt-E4B an E4M3 cache cost 9x the KL and the int8 cache is unmeasured. The
Bolt-E4B row serves without speculation because the published containers' drafters are block FP8.
EmbeddingGemma 2 takes an input in one step, so its `max-num-batched-tokens` is the longest input
as well as the batch. A live Qwen3-ASR session holds one sequence, so its `max-num-seqs` is the
most sessions served at once. On one card LTX-2.5's adapter slots fit at `max-lora-rank: 16,
max-loras: 1` (433 MiB).
In a file of several models, Qwen-Image's grant counts two sequences of `max-model-len` tokens of
cache, which at the model's own 33600 tokens is 55.8 GiB on one card and 32.6 GiB a card on two,
more than the cards. `tp1.yaml` sets `max-model-len: 8192` (it needs 29.7 GiB; pictures up to
about 1.9 megapixels, 1024x1024 being 4096 tokens) and `tp2.yaml` `20480` (25.4 GiB a card; the
default 2048x2048 is 16384 tokens). Alone in a file it loads at its own length, its cache taking
what the cards have left. It sizes its buffers itself and warns that it does not take
`image-gen-max-pixels` or `image-gen-max-refs`.
Add `server.api-key: KEY` (or `server.api-key-env: VAR`, which reads it from the environment) to
require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). `debug-graph: true` on the model
prints every op and the kernel it resolved to, then exits without serving. A chat request:
```sh
curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
-d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
-d '{"model":"minicpm5-2b-iq8r","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
```
An image model answers OpenAI's images API instead, with base64 pictures:
@@ -349,6 +410,8 @@ budgets, long context, speculative decoding and operating a server.
`data/recipes/` names. Download checkpoints with `scripts/hfget.sh <org/repo> <dir>`.
```sh
# Spark X2.6 uses the checkpoint's BF16 weights, tokenizer and chat template; no recipe required.
build/bin/rad-convert /srv/models/hf/XHToken-Spark-X2.6-4B -o spark-x2.6-4b-bf16.rad --max-ctx 4096
build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \
--recipe data/recipes/q38-27b-bf16.recipe
build/bin/rad-convert /srv/models/hf/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096
@@ -364,9 +427,17 @@ build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-q
--recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \
--set quantization_config.quant_method=compressed-tensors \
--draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash
build/bin/rad-convert /srv/models/hf/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
# Meta's Muse Glimmer 30B, as it ships (bf16), with an int4 trunk and int8 attention values, or
# with an IQ8R trunk and an int8 head
build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-bf16.rad \
--recipe data/recipes/museglimmer-30b-bf16.recipe
build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-w4a8.rad \
--recipe data/recipes/museglimmer-30b-w4a8.recipe \
--set quantization_config.quant_method=compressed-tensors
build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-iq8r-dflash.rad \
--draft-model /srv/models/hf/meta-models/Muse-Glimmer-30B-assistant \
--recipe data/recipes/museglimmer-30b-iq8r.recipe \
--set quantization_config.quant_method=compressed-tensors
build/bin/rad-convert /srv/models/hf/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ -o swift15-27b-w4a16.rad \
--recipe data/recipes/q38-27b-w4a16.recipe
# Any single-file SDXL checkpoint (SDXL 1.0, Illustrious, NoobAI, Pony, a civitai finetune), with
@@ -378,15 +449,20 @@ build/bin/rad-convert /srv/models/hf/OnomaAIResearch/Illustrious-XL-v2.0/Illustr
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
own precision needs no container: its directory is the entry's `model`
(`model: /srv/models/hf/Qwen/Qwen3.8-27B`). A release someone else quantised to an integer grid is
written at its own numbers where the kernels read them (an int4 W4A16 release, compressed-tensors'
AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with `data/recipes/q38-27b-w4a16.recipe`). Block
FP8, MXFP4, NVFP4 and ParoQuant releases are not served: convert the model's bf16 checkpoint with
an int8 recipe. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
with their `rad-convert` commands.
Spark X2.6 runs BF16 at `tp: 1`, `2`, `3` or `4` -- and `8`, the worlds libr4d has an exact
all-reduce for -- without a drafter or quantisation recipe. Its checkpoint's chat template enables
thinking by default; replies return reasoning in `reasoning_content`. Set
`chat_template_kwargs.enable_thinking` to `false` for a non-thinking request. Tool calls use the
checkpoint's tagged format and are returned as OpenAI `tool_calls`.
## Test
```sh
@@ -405,6 +481,7 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out o
|---|---|
| [`docs/GUIDE.md`](docs/GUIDE.md) | installing, converting, serving, the HTTP API, operating a server |
| [`docs/TOOLS.md`](docs/TOOLS.md) | every flag of every tool, and the recipe syntax |
| [`docs/DIAGNOSE.md`](docs/DIAGNOSE.md) | `diagnose`: the engine measures itself, and what makes a run a measurement |
| [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files |
| [`docs/PREPARING_YOUR_RIG.md`](docs/PREPARING_YOUR_RIG.md) | a two-R9700 machine from firmware setup to a serving model |
| [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card |
File diff suppressed because it is too large. Load diff
+40 -5
View File
@@ -21,7 +21,7 @@ extern "C" {
* (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default.
* rad_sycl.h is versioned on its own (RAD_SYCL_STREAM_VERSION), since only SYCL kernel libraries
* read it. */
#define RAD_ABI_VERSION 32u
#define RAD_ABI_VERSION 42u
/* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
@@ -62,6 +62,16 @@ typedef struct RadArgs {
void* instance; /* whatever init() returned for this resolved instance */
int rank; /* tensor-parallel rank and world size, for collectives */
int world_size;
/* ABI 35: host-side maximum KV length represented by this exact launch operand (a seqused
* span or a supported one-sequence prefill boundary), or -1 when it cannot be proven. In a
* decode, verify or draft pass it is instead the step's context bound plus its longest query,
* which the recorded pass's key holds. Plugins
* must not infer it from a device pointer or synchronously read device memory to get it. */
int32_t kv_used_max_h;
/* The current rank's WGP count (HIP multiProcessorCount on RDNA); lets split launchers use
* exactly the same per-device occupancy as architecture pass-key callbacks without querying
* the process-global current device on the hot path. */
int32_t wgp_count;
} RadArgs;
/* Read a parameter by key. Inline definitions, because a plugin links only the ABI headers and
@@ -154,7 +164,8 @@ typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEnc
/* 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 container read,
* so it has to keep pace with the disk. */
* so it has to keep pace with the disk. The planes are read only: the loader may hand them
* straight out of its read buffer, which the copies for other ranks read at the same time. */
typedef int (*RadRelayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes, void* dst,
int64_t dst_bytes);
@@ -467,15 +478,20 @@ typedef struct RadKernelInfo {
* against: a named skip, not a failure. */
RadUnrelayoutFn unrelayout;
/* 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.
* fusion. Non-null also counts in rad-kbench's fusion-claim column. */
RadFuseFn replaces;
/* Flags describing runtime behavior relevant to core safety decisions. Zero means none.
*
* 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;
uint64_t capabilities;
} RadKernelInfo;
/* This row's launch grid can depend on live seqused during prefill. */
#define RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT (1ull << 0)
/* ================================================================== kernel plugin exports */
/* Every kernel plugin exports the whole set. The 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
@@ -502,6 +518,15 @@ const RadKernelInfo* rad_kernel_at(int i);
typedef int (*RadPluginOpenFn) (void);
typedef void (*RadPluginCloseFn)(void);
/* Optional, symbol `rad_plugin_freed`. The core has freed the device memory [base, base + bytes)
* and nothing launched against it runs any more. A kernel library that keeps state keyed by an
* operand's address (a counter block per output buffer, made at the first launch and replayed by
* recorded passes) drops what it keeps for addresses inside the range. A process serving several
* models frees an engine's memory when it unloads the model, so state kept past that would pile
* up with every load. Called from the freeing thread, any number of times, possibly for ranges the
* plugin never saw. */
typedef void (*RadPluginFreedFn)(const void* base, int64_t bytes);
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means every launch reads and writes
* only its operands and the scratch it was handed (no allocation it keeps, no counter kept between
* launches), so two launches may run at once on one device when their operands and scratch do not
@@ -521,7 +546,17 @@ typedef int (*RadKernelConcurrentFn)(int i);
* do, adds exactly once. The record is RAD_CHAIN_REC_BYTES at byte RAD_CHAIN_KARG_OFF of the
* kernel's argument segment: { magic, target, ctr, check }, with check = magic ^ target ^ ctr ^
* RAD_CHAIN_CHECK. A record whose magic or check does not match means: run without waiting and do
* not add. Without the symbol, or with 0, the engine never asks. Symbol name: `rad_kernel_chain`. */
* not add. Without the symbol, or with 0, the engine never asks.
*
* 2 instead of 1 adds a second promise: the chained form's own acquire covers everything it reads
* behind the wait, scalar loads included. A compiler's agent-scope fence invalidates the vector
* caches only; a load every lane shares may be a scalar one, served from the scalar data cache,
* which still holds what was there before the launch in front wrote. A form that invalidates that
* cache behind its acquire (`s_dcache_inv`), or reads no operand through it, may say 2. Where
* every chainable row an engine loads says 2, the engine issues a chained launch that has lost
* its barrier bit without the packet processor's acquire as well: on an R9700 that acquire holds
* the processor ~0.9 us a launch, and it comes too early to serve a kernel that then waits for
* the launch in front. With 1 the packets keep it. Symbol name: `rad_kernel_chain`. */
typedef int (*RadKernelChainFn)(int i);
#define RAD_CHAIN_KARG_OFF 992
#define RAD_CHAIN_REC_BYTES 32
+64 -3
View File
@@ -17,7 +17,7 @@ ABI_FIELD(RadArchProbe, gen_patches)
ABI_FIELD(RadArchProbe, gen_audio)
ABI_FIELD(RadArchProbe, gen_ctx)
ABI_FIELD(RadArchProbe, gen_video)
ABI_FIELD(RadArchProbe, kv_quant_ok)
ABI_FIELD(RadArchProbe, kv_fp8_ok)
ABI_FIELD(RadArchProbe, chain_pays)
ABI_FIELD(RadArchProbe, kv_stream_ok)
ABI_FIELD(RadArchProbe, control_vector_ok)
@@ -26,6 +26,7 @@ ABI_FIELD(RadArchProbe, state_f16_ok)
ABI_FIELD(RadArchProbe, tree_pays)
ABI_FIELD(RadArchProbe, gen_max_pixels)
ABI_FIELD(RadArchProbe, gen_max_refs)
ABI_FIELD(RadArchProbe, gen_shape)
ABI_STRUCT(RadArgs)
ABI_FIELD(RadArgs, t)
ABI_FIELD(RadArgs, n_t)
@@ -36,6 +37,8 @@ ABI_FIELD(RadArgs, scratch_bytes)
ABI_FIELD(RadArgs, instance)
ABI_FIELD(RadArgs, rank)
ABI_FIELD(RadArgs, world_size)
ABI_FIELD(RadArgs, kv_used_max_h)
ABI_FIELD(RadArgs, wgp_count)
ABI_STRUCT(RadBatch)
ABI_FIELD(RadBatch, phase)
ABI_FIELD(RadBatch, step)
@@ -93,6 +96,15 @@ ABI_FIELD(RadBatch, plugin_words)
ABI_FIELD(RadBatch, plugin_cu)
ABI_FIELD(RadBatch, plugin_words_h)
ABI_FIELD(RadBatch, plugin_cu_h)
ABI_FIELD(RadBatch, sgen_b)
ABI_FIELD(RadBatch, kv_used_max_h)
ABI_FIELD(RadBatch, positions_h)
ABI_FIELD(RadBatch, n_bidi)
ABI_FIELD(RadBatch, bidi_row)
ABI_FIELD(RadBatch, bidi_n)
ABI_FIELD(RadBatch, bidi_seq)
ABI_FIELD(RadBatch, bidi_used)
ABI_FIELD(RadBatch, anchor_rows)
ABI_STRUCT(RadBufDecl)
ABI_FIELD(RadBufDecl, dtype)
ABI_FIELD(RadBufDecl, rank)
@@ -118,8 +130,6 @@ ABI_FIELD(RadBuildCtx, max_enc_patches)
ABI_FIELD(RadBuildCtx, max_out_rows)
ABI_FIELD(RadBuildCtx, max_audio_frames)
ABI_FIELD(RadBuildCtx, max_mixed_tok)
ABI_FIELD(RadBuildCtx, kv_quant)
ABI_FIELD(RadBuildCtx, attn_prefill_fp8)
ABI_FIELD(RadBuildCtx, kv_resident_blocks)
ABI_FIELD(RadBuildCtx, kv_stream_ok)
ABI_FIELD(RadBuildCtx, cvec)
@@ -134,6 +144,8 @@ ABI_FIELD(RadBuildCtx, calib_layer_hi)
ABI_FIELD(RadBuildCtx, calib_tokens)
ABI_FIELD(RadBuildCtx, gen_max_pixels)
ABI_FIELD(RadBuildCtx, gen_max_refs)
ABI_FIELD(RadBuildCtx, expert_file_tier)
ABI_FIELD(RadBuildCtx, slot_base)
ABI_FIELD(RadBuildCtx, plain_norm)
ABI_STRUCT(RadAudioGenBatch)
ABI_FIELD(RadAudioGenBatch, n_lane)
@@ -181,6 +193,7 @@ ABI_FIELD(RadAudioGenBatch, ref_cu)
ABI_FIELD(RadAudioGenBatch, ref_cu_h)
ABI_FIELD(RadAudioGenBatch, ref_frame)
ABI_FIELD(RadAudioGenBatch, ref_frame_h)
ABI_FIELD(RadAudioGenBatch, prompt_cu_h)
ABI_STRUCT(RadAudioGenDecl)
ABI_FIELD(RadAudioGenDecl, name)
ABI_FIELD(RadAudioGenDecl, tmpl)
@@ -221,6 +234,8 @@ ABI_FIELD(RadAudioGenDecl, ref_rate)
ABI_FIELD(RadAudioGenDecl, ref_hop)
ABI_FIELD(RadAudioGenDecl, ref_max_samples)
ABI_FIELD(RadAudioGenDecl, ref_max)
ABI_FIELD(RadAudioGenDecl, tmpl_ref_instruct)
ABI_FIELD(RadAudioGenDecl, neg_tmpl_ref)
ABI_STRUCT(RadControlVector)
ABI_FIELD(RadControlVector, dir)
ABI_FIELD(RadControlVector, scales)
@@ -267,6 +282,7 @@ ABI_FIELD(RadChatFormat, object_string_close)
ABI_FIELD(RadChatFormat, object_bare_keys)
ABI_FIELD(RadChatFormat, reasoning_anywhere)
ABI_FIELD(RadChatFormat, arg_json_value_prefix)
ABI_FIELD(RadChatFormat, content_open)
ABI_STRUCT(RadConstraint)
ABI_FIELD(RadConstraint, key)
ABI_FIELD(RadConstraint, op)
@@ -312,6 +328,7 @@ ABI_FIELD(RadEncoderDecl, max_patches)
ABI_FIELD(RadEncoderDecl, n_embd)
ABI_FIELD(RadEncoderDecl, out)
ABI_FIELD(RadEncoderDecl, one_grid)
ABI_FIELD(RadEncoderDecl, bidirectional)
ABI_STRUCT(RadEncoding)
ABI_FIELD(RadEncoding, scheme)
ABI_FIELD(RadEncoding, transform)
@@ -501,6 +518,7 @@ ABI_FIELD(RadKVGroupBatch, state_index_pitch)
ABI_FIELD(RadKVGroupBatch, block_size)
ABI_FIELD(RadKVGroupBatch, max_blocks)
ABI_FIELD(RadKVGroupBatch, stream)
ABI_FIELD(RadKVGroupBatch, seqused_h)
ABI_STRUCT(RadKVGroupDecl)
ABI_FIELD(RadKVGroupDecl, kind)
ABI_FIELD(RadKVGroupDecl, dtype)
@@ -542,6 +560,7 @@ ABI_FIELD(RadKernelInfo, relayout)
ABI_FIELD(RadKernelInfo, opd_shape)
ABI_FIELD(RadKernelInfo, unrelayout)
ABI_FIELD(RadKernelInfo, replaces)
ABI_FIELD(RadKernelInfo, capabilities)
ABI_STRUCT(RadLayout)
ABI_FIELD(RadLayout, tag)
ABI_FIELD(RadLayout, dtype)
@@ -700,6 +719,44 @@ ABI_FIELD(RadSampleParams, hist_len)
ABI_FIELD(RadSampleParams, mask_row)
ABI_FIELD(RadSampleParams, flags)
ABI_FIELD(RadSampleParams, dry_rep_limit)
ABI_STRUCT(RadShapeGenBatch)
ABI_FIELD(RadShapeGenBatch, lane)
ABI_FIELD(RadShapeGenBatch, patches)
ABI_FIELD(RadShapeGenBatch, step)
ABI_FIELD(RadShapeGenBatch, n_steps)
ABI_FIELD(RadShapeGenBatch, sigma)
ABI_FIELD(RadShapeGenBatch, sigma_next)
ABI_FIELD(RadShapeGenBatch, cfg)
ABI_FIELD(RadShapeGenBatch, pair)
ABI_FIELD(RadShapeGenBatch, lanes)
ABI_FIELD(RadShapeGenBatch, flags)
ABI_FIELD(RadShapeGenBatch, seed)
ABI_FIELD(RadShapeGenBatch, lat_cu)
ABI_FIELD(RadShapeGenBatch, n_query)
ABI_FIELD(RadShapeGenBatch, query)
ABI_FIELD(RadShapeGenBatch, query_cu)
ABI_STRUCT(RadShapeGenDecl)
ABI_FIELD(RadShapeGenDecl, name)
ABI_FIELD(RadShapeGenDecl, canvas)
ABI_FIELD(RadShapeGenDecl, border_ratio)
ABI_FIELD(RadShapeGenDecl, enc_size)
ABI_FIELD(RadShapeGenDecl, enc_patch)
ABI_FIELD(RadShapeGenDecl, pix_mean)
ABI_FIELD(RadShapeGenDecl, pix_std)
ABI_FIELD(RadShapeGenDecl, latent_rows)
ABI_FIELD(RadShapeGenDecl, latent_channels)
ABI_FIELD(RadShapeGenDecl, step_rows)
ABI_FIELD(RadShapeGenDecl, default_steps)
ABI_FIELD(RadShapeGenDecl, max_steps)
ABI_FIELD(RadShapeGenDecl, default_guidance)
ABI_FIELD(RadShapeGenDecl, bounds)
ABI_FIELD(RadShapeGenDecl, level)
ABI_FIELD(RadShapeGenDecl, default_resolution)
ABI_FIELD(RadShapeGenDecl, min_resolution)
ABI_FIELD(RadShapeGenDecl, max_resolution)
ABI_FIELD(RadShapeGenDecl, max_lanes)
ABI_FIELD(RadShapeGenDecl, max_query)
ABI_FIELD(RadShapeGenDecl, field_out)
ABI_STRUCT(RadSyclStream)
ABI_FIELD(RadSyclStream, magic)
ABI_FIELD(RadSyclStream, version)
@@ -899,3 +956,7 @@ ABI_FIELD(RadMtpCoupleState, x)
ABI_FIELD(RadMtpCoupleState, count)
ABI_FIELD(RadMtpCoupleState, ids)
ABI_FIELD(RadMtpCoupleState, q)
ABI_FIELD(RadMtpCoupleState, nkids)
ABI_FIELD(RadMtpCoupleState, scheme)
ABI_FIELD(RadMtpCoupleState, blk)
ABI_FIELD(RadMtpCoupleState, pad_)
+201 -65
View File
@@ -56,35 +56,27 @@ double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt);
const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt);
/* ================================================================== build context */
/* RadBuildCtx::kv_quant. A layout groups each head's dims by 32 with an f16 scale per group, the
* group's absmax over the largest code. A token's row in a head, at head_dim HD (a multiple of 32):
/* A paged cache group's dtype says how a token's row in a head is laid out, at head_dim HD:
*
* RAD_KVQ_V4 (fp8_v4), 25 * HD / 16 bytes:
* [0, HD) K, E4M3 as the fp8 cache stores it
* [HD, 3HD/2) V's int4 codes, dim d in the nibble at bit 4 * (d % 2) of byte d / 2
* [3HD/2, 25HD/16) V's scales (absmax / 7)
* RAD_KVQ_K6V4 (k6_v4), 22 * HD / 16 bytes:
* [0, HD/2) K's low four bits, as V's codes above
* [HD/2, 3HD/4) K's high two bits, a 4-byte word per 16 dims whose byte j holds dims 2j
* and 2j+1 in bits 0-3 and dims 8+2j and 9+2j in bits 4-7
* [3HD/4, 5HD/4) V's int4 codes
* [5HD/4, 21HD/16) K's scales (absmax / 31)
* [21HD/16, 22HD/16) V's scales (absmax / 7)
*
* Codes are two's complement (int4 -7..7, int6 -31..31). The group is declared at RAD_F8E4M3 with
* head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read
* it. */
enum {
RAD_KVQ_NONE = 0,
RAD_KVQ_V4 = 1,
RAD_KVQ_K6V4 = 2
};
* RAD_BF16, 4 * HD bytes: K then V, as the model computes them.
* RAD_I8, 2 * HD + 4 bytes: K and V as int8 codes with one f16 scale each per (token, head):
* [0, HD) K's int8 codes (two's complement, -127..127)
* [HD, 2HD) V's int8 codes
* [2HD, 2HD + 2) K's scale (the head's absmax / 127)
* [2HD + 2, 2HD + 4) V's scale (absmax / 127)
* The plugin declares HD; the core adds the scales' bytes (rad_kv_row_elems). */
/* The products of the prefill attention a deployment accepts in e4m3 (RadBuildCtx::
* attn_prefill_fp8, `attn_paged`'s `prefill_fp8`): bits, so both is 3. */
/* Elements of a token's row in one head of a paged group declared at `dtype` and `head_dim`: K
* then V, and under the int8 cache the two f16 scales after them. */
static inline int64_t rad_kv_row_elems(uint32_t dtype, int64_t head_dim) {
return 2 * head_dim + (dtype == RAD_I8 ? 4 : 0);
}
/* RadArchProbe::chain_pays. */
enum {
RAD_ATTN_FP8_QK = 1, /* Q.K^T, the query rounded to e4m3 after the softmax scale */
RAD_ATTN_FP8_PV = 2 /* P.V, the probabilities rounded to e4m3 */
RAD_CHAIN_NONE = 0,
RAD_CHAIN_SPEC = 1, /* with a drafter decoding speculatively */
RAD_CHAIN_ALWAYS = 2 /* with or without one */
};
typedef struct RadBuildCtx {
@@ -111,17 +103,16 @@ typedef struct RadBuildCtx {
int64_t tp_wire_min_bytes;
/* The KV cache dtype, a deployment choice rather than a property of the checkpoint: fp8
* weights may want a bf16 cache and vice versa.
/* The KV cache dtype, a deployment choice rather than a property of the checkpoint.
*
* RAD_DT_INVALID (the zero-initialised default) means the plugin's default, bf16 for every
* architecture in this tree. RAD_F8E4M3 is the only other implemented value: the fp8kv
* attention family is band-gated on it, and the store side writes E4M3 with per-(sequence,
* head) descales. `kv_quant` below narrows the trunk's attention cache further.
* architecture in this tree. RAD_I8 is the other value every paged attention serves, the
* int8 cache above: the attention kernels band on it and the store writes each token's codes
* and scales. RAD_F8E4M3 reaches only a plugin whose probe sets RadArchProbe::kv_fp8_ok.
*
* An ABI field rather than an environment variable because it changes what the model
* computes, so it must have one visible answer: --kv-cache-dtype. */
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); or RAD_F8E4M3 */
int kv_dtype; /* RAD_DT_INVALID = the plugin's default (bf16); RAD_I8; RAD_F8E4M3 */
int is_draft; /* this builder scope is a drafter (spec §10) */
const char* scope; /* "", "draft", "vision", "audio" -- prefixes declared names */
@@ -172,25 +163,6 @@ typedef struct RadBuildCtx {
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int64_t max_mixed_tok;
/* A narrower layout of the trunk's attention cache under kv_dtype RAD_F8E4M3, from
* --kv-cache-dtype fp8_v4 or k6_v4: a RAD_KVQ_* (below). The engine sets it only for a plugin
* whose probe has the layout's bit in RadArchProbe::kv_quant_ok and refuses the flag
* otherwise, so no plugin sees it that would store plain E4M3 instead. A drafter's cache stays
* E4M3.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int kv_quant;
/* ---- appended in ABI 26 (fp8 prefill attention) */
/* RAD_ATTN_FP8_* bits from --attn-prefill-fp8: the attention products the deployment accepts
* in e4m3 rather than exactly. 0 (the zero-initialised default) is exact. A plugin passes a
* nonzero value on as `attn_paged`'s `prefill_fp8` (docs/OPS.md) and omits the parameter at
* 0, so an exact declare is unchanged. The engine refuses to start when no resolved kernel
* takes it, so a plugin that ignores the field is refused rather than silently exact.
*
* Zero-defaulted and in the padding after kv_quant, so no other field moves. */
int attn_prefill_fp8;
/* ---- appended in ABI 30 (KV streaming) */
/* --kv-resident in tokens, 0 when nothing streams: the ring a streamed group carves is this in
* whole blocks, raised to the engine's floors and clamped to the context. A plugin states it as
@@ -295,18 +267,39 @@ typedef struct RadBuildCtx {
* fixed buffers ignores them, and the core says so at startup. */
int64_t gen_max_pixels;
int64_t gen_max_refs;
/* ---- appended in the SYCL fork (the plain block norm) */
/* ---- appended in ABI 37 (where a routed expert may live) */
/* --weights-disk-tier: nonzero when weights may stay in the container. An expert read from the
* drive has to be stored whole, so a plugin that can lay its routed experts out either way
* keeps them whole for this; 0 leaves it free to split them across the ranks by width. */
int expert_file_tier;
/* ---- appended in ABI 38 (several engines in one process) */
/* The first of this engine's slots. Each engine in the process holds a contiguous block of
* slots, one per rank, so an instance's slot, `slot_base + rank` (rad_build_slot), is unique
* among the ranks of every engine alive, where `rank` is unique only within one engine. A
* plugin keeps per-instance state (handles, geometry, its step's view of the model) indexed by
* the slot, and reads it back in step() with rad_slot(). Zero, the default, makes the slot the
* rank: one engine in a process, or a test driving a plugin alone. Two engines may serve the
* same plugin at once only when it says so (rad_arch_multi_instance). */
int slot_base;
/* ---- appended in ABI 42 (the plain block norm) */
/* Nonzero: where no reader of a block norm's output takes its E4M3 code pair (every reader a
* 4-bit or plain bf16 projection, which reads the bf16 plane), the plugin may run the norm as
* `add` (the residual stored first, as `rmsnorm_quant_fp8` stores it) then `rmsnorm`: the same
* bf16 values, without codes nobody reads. The engine sets it on the SYCL backend, whose
* quantising norm is bound by libref's ordered sum of squares while its `rmsnorm` is a fast
* row (docs/SYCL_PROGRESS.md); 0 elsewhere, so other backends declare what they did.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
* row (docs/SYCL_PROGRESS.md); 0 elsewhere, so other backends declare what they did. */
int plain_norm;
} RadBuildCtx;
/* The most instances (engine ranks) one process holds at once; every slot is below it. */
#define RAD_MAX_SLOTS 32
/* The declaring instance's slot (see RadBuildCtx::slot_base). */
static inline int rad_build_slot(const RadBuildCtx* c) { return c->slot_base + c->rank; }
/* ================================================================== control vectors */
/* A direction per layer, in the shape llama.cpp's `--cvec-mode project` applies it:
*
@@ -838,6 +831,23 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
* the drafter's passes (the KL mode drafts nothing, so trees do not apply there). */
int rad_drafter_tree(RadBuilder* b, rad_buf parents);
/* The model's routing counts live in `table`: an i32 RAD_BUF_PERSIST device buffer of at least
* [layers, n_expert], one row per layer that reports (rad_route_report's `layer`, so a head past
* the trunk counts) and n_expert the model's expert count. Each layer's router writes its counts
* into its own row and the report names that row as RadRouting::expert_count; the core takes it
* in place and copies the pass's rows to the host once, at the end of the pass. Without a table
* the core keeps the rows itself and a report costs one copy dispatch per routed layer on the
* compute stream, since a plugin cannot bind the core's rows as operands of a recorded pass. A
* report naming any other buffer is still copied, into the layer's row of the table.
*
* A row per layer also means a consumer that reads a layer's counts later in stream order (the
* file stager, at the layer's first expert op) reads that layer's, which one buffer shared by
* every layer does not guarantee once a later layer's router has run.
*
* Called at most once. The row count is checked when a context binds, where the reporting layers
* are known. Additive export; RAD_ABI_VERSION does not move. */
int rad_route_table(RadBuilder* b, rad_buf table);
/* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on
* the AQL backend only, which keeps a completion counter per queue, where the model's plugin
* measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
@@ -896,6 +906,13 @@ typedef struct RadEncoderDecl {
* position tables or kernels are per geometry; the core ends a pass where the grid changes.
* 0 packs segments of any grid into a pass. */
int32_t one_grid;
/* ---- appended in ABI 32 (runs the language model reads both ways) */
/* 1: the language model attends the placeholders of one picture or video frame to each other
* both ways (Gemma 4's use_bidirectional_attention "vision"), text before and after them
* causally. The core then ends no prefill chunk inside such a run and states each trunk pass's
* runs (RadBatch::n_bidi). 0 for an audio encoder. */
int32_t bidirectional;
} RadEncoderDecl;
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
@@ -1256,13 +1273,22 @@ typedef struct RadAudioGenDecl {
* prepare() has limited to those a caller may write), and so is the text after it. A clip is
* mono f32 in [-1, 1] at `ref_rate`, right-padded with zeros to a whole number of `ref_hop`
* samples, each `ref_hop` samples one frame; a request's clips hold at most `ref_max_samples`
* samples together. NULL `tmpl_ref`: references are refused. */
* samples together. With two branches, references require default_cfg 1 and a plain
* neg_tmpl: guidance 1 repeats the conditional prompt and frame map in both branches.
* Reference direction is opt-in through the templates appended below. NULL `tmpl_ref`:
* references are refused. */
const char* tmpl_ref;
const char* ref_item;
int64_t ref_rate;
int64_t ref_hop;
int64_t ref_max_samples;
int32_t ref_max;
/* ABI 40: reference-plus-instructions uses tmpl_ref_instruct ({references},
* {instructions}, {input} once each). Its guidance baseline is neg_tmpl_ref
* ({references}, {input}, no instructions). Both branches retain the same clips;
* their text lengths and reference-frame maps may differ. NULL: direction refused. */
const char* tmpl_ref_instruct;
const char* neg_tmpl_ref;
} RadAudioGenDecl;
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
@@ -1481,6 +1507,87 @@ typedef struct RadVideoGenDecl {
int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d);
/* ================================================================== the shape generator */
/* A program that makes a 3-D shape from one picture: an image encoder reads the picture, a
* denoiser steps a set of latent rows by flow matching, guided against an unconditioned branch,
* and a decoder turns the latent into an occupancy field that the core samples at points of its
* choosing and meshes. The core drives the passes (RadBatch::gen, RadShapeGenBatch), one request
* a pass:
*
* RAD_GEN_PASS_SCOND the request's picture through the image encoder into the request's
* lane: what the denoiser reads of it at every step, for both branches
* (the picture's and the unconditioned one).
* RAD_GEN_PASS_SSTEP one denoising step of one lane over both branches, `step_rows` rows:
* each branch's conditioning and latent, laid out as the plugin likes, the
* latents two entries of `latent_rows` (the conditioned first) for the
* image generator's sampler ops. The first step draws the lane's noise.
* RAD_GEN_PASS_SLATENT the lane's final latent through the decoder's network, into the lane:
* what every query pass of the request reads. Runs once, after the last
* step.
* RAD_GEN_PASS_SQUERY the field at `n_query` points (RadShapeGenBatch::query, at most
* `max_query`), one f32 a point in `field_out`, which the core reads
* back.
*
* The picture. The core decodes it with its alpha (opaque without one) and prepares it as
* Hunyuan3D-2's ImageProcessorV2 and image encoder do: the alpha's bounding box (its last row and
* column left out, as the reference's slice leaves them) scaled with OpenCV's INTER_AREA to
* (1 - border_ratio) of the longer side of the square that holds the picture, centred on it and
* flattened onto white; that square resized to `canvas` x `canvas` with INTER_CUBIC; then as 0..1
* values bilinearly resized to `enc_size` x `enc_size` (half-pixel centres, torchvision's), each
* channel normalised by `pix_mean` and `pix_std`, and cut into (enc_size / enc_patch)^2 patches of
* enc_patch x enc_patch pixels, row-major, each patch's values channel-major then row-major (a
* convolution's weight order). An SCOND pass carries those patches.
*
* The sampler: a request's `steps` are sigma grid points, sigma_i = i / (steps - 1) for i in
* [0, steps), numpy's linspace(0, 1) taken to f32; the latent starts as noise at sigma 0 and an
* evaluation at each sigma but the last steps it to the next (the reference evaluates at the
* last too, against itself, a step of zero). The model's timestep is sigma, the guided velocity
* neg + cfg (pos - neg), and the step x + (sigma_next - sigma) v.
*
* The field: the decoder's logit at a point, inside the shape above `level`. The core samples the
* cube [-bounds, bounds]^3 on a grid of `resolution` cells a side ((resolution + 1)^3 points,
* numpy's linspace in f32 along each axis), coarse to fine as FlashVDM's hierarchical decoding
* does: the whole grid at the coarsest level (resolution halved while it stays at least 63), then
* at each finer level only the points near where the coarser one crosses `level` or is within
* 0.95 of it. The surface is marching cubes over the finest grid, a vertex at grid index g placed
* at g 2 bounds / (resolution + 1) - bounds, as the reference places it.
*
* A program declares exactly one of this, the other generators, logits or pooled vectors. */
enum { RAD_GEN_PASS_SCOND = 15, RAD_GEN_PASS_SSTEP = 16, RAD_GEN_PASS_SLATENT = 17,
RAD_GEN_PASS_SQUERY = 18 };
typedef struct RadShapeGenDecl {
const char* name; /* "hunyuan3d-2" -- the served model id and messages */
/* The picture (above). */
int64_t canvas;
double border_ratio;
int64_t enc_size, enc_patch;
double pix_mean[3], pix_std[3];
/* The latent: `latent_rows` rows of `latent_channels` a branch; a step's rows, both branches
* with their conditioning. */
int64_t latent_rows, latent_channels, step_rows;
/* The sampler (above) and the guidance a request that names none runs at. */
int64_t default_steps, max_steps;
double default_guidance;
/* The field (above): the cube's half side, the iso value, and the grid's resolution a request
* that names none is sampled at, with the range a request may name. */
double bounds;
double level;
int64_t default_resolution, min_resolution, max_resolution;
/* `max_lanes` requests may hold state at once. `field_out` is a device f32 buffer of at least
* `max_query` elements. */
int64_t max_lanes;
int64_t max_query;
rad_buf field_out;
} RadShapeGenDecl;
int rad_declare_shape_generator(RadBuilder* b, const RadShapeGenDecl* d);
/* ================================================================== diagnostics */
/* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */
void rad_note(RadBuilder* b, const char* fmt, ...);
@@ -1509,6 +1616,13 @@ const char* rad_arch_quant(void);
* move. */
int rad_arch_serves_imports(void);
/* Nonzero when every piece of per-instance state the plugin keeps is indexed by
* rad_build_slot() / rad_slot(), so several engines in one process may run it at once
* (docs/MULTIMODEL.md §3.3). Optional: absent or zero, the core runs the plugin for one engine at
* a time and refuses a second engine on it by name. arch/common/rad_arch.h writes it with
* RAD_ARCH_MULTI_INSTANCE(). */
int rad_arch_multi_instance(void);
/* What the plugin can say before it declares anything. Optional: a plugin that does not export
* it answers zero to everything, each field's default.
*
@@ -1568,17 +1682,18 @@ typedef struct RadArchProbe {
* `gen_rows` (its largest pass: a step's packed sequence at the largest size and length). It
* keeps no KV. */
int32_t gen_video;
/* The RadBuildCtx::kv_quant layouts the plugin serves for this model, bit 1 << RAD_KVQ_*:
* libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at
* startup with the plugin named. */
int32_t kv_quant_ok;
/* Nonzero when the plugin serves an E4M3 cache for this model (--kv-cache-dtype fp8,
* RadBuildCtx::kv_dtype RAD_F8E4M3): GLM-5.3's latent attention. The engine refuses the flag
* for a plugin that leaves it zero, naming the int8 cache every paged attention serves. */
int32_t kv_fp8_ok;
/* ---- appended in ABI 26 (chained launches, control vectors) */
/* Nonzero when this plugin measured its speculative step faster with chained launches
* (RadKernelChainFn: a dependent kernel waits in its own prologue rather than behind the
* queue's barrier bit). With a drafter decoding speculatively on the AQL backend, the core
* then takes them. Zero keeps them off: plain decode measured slower chained, and a plugin
* that never measured them asks for nothing. */
/* How this plugin measured chained launches (RadKernelChainFn: a dependent kernel waits in its
* own prologue rather than behind the queue's barrier bit), a RAD_CHAIN_*. SPEC: its
* speculative step is faster with them, and the core takes them on the AQL backend while a
* drafter decodes speculatively. ALWAYS: its plain decode is faster too, and the core takes
* them with or without a drafter. Zero keeps them off: some models' plain decode measured
* slower chained, and a plugin that never measured them asks for nothing. */
int32_t chain_pays;
/* ---- appended in ABI 30 (KV streaming) */
/* Nonzero when the architecture can stream a KV group between host memory and a VRAM ring: its
@@ -1615,6 +1730,12 @@ typedef struct RadArchProbe {
* gen_patches answer for them. */
int64_t gen_max_pixels;
int64_t gen_max_refs;
/* ---- appended in ABI 33 (the shape generator) */
/* Nonzero for a shape generator, which the engine sizes as it does a video generator from
* `gen_rows` (its largest pass: a step's two branches, or a query pass's points). It keeps no
* KV. */
int32_t gen_shape;
} RadArchProbe;
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
@@ -1744,6 +1865,13 @@ typedef struct RadChatFormat {
* decides how its value is read, whatever the schema says; the grammar writes the one the
* schema calls for. NULL: the schema alone types a value. */
const char* arg_json_value_prefix;
/* A header the model writes first when it answers without reasoning, in place of
* reasoning_open: the reply then starts with this literal, which is dropped, and the rest is
* content. A reply that starts with anything else, or with only part of it, is read as
* written. When the model does reason, its header after the block is reasoning_close's.
* NULL or "": the reply starts with its content. */
const char* content_open;
} RadChatFormat;
/* Return the format, or NULL for "derive it from the chat template". Called once at startup. */
@@ -1856,6 +1984,14 @@ int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadB
struct RadCtx;
struct RadBatch;
void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch);
/* Optional. Return a stable fingerprint of actual dispatch geometry whose grid depends on live
* per-group seqused values. `kv_used_max_h[g]` is the host maximum for batch->kv[g], and
* rad_ctx_wgp_count(c) supplies the device's WGP count. Return 0 when exact geometry is unknown;
* that pass runs live and is not recorded. Only prefill and mixed launches read the live maximum:
* in a decode, verify or draft pass every launch reads the step's keyed context bound
* (RadArgs::kv_used_max_h), so such a pass needs no geometry here and returns nonzero. */
uint64_t rad_arch_pass_key(struct RadCtx* c, const struct RadBatch* batch,
const int32_t* kv_used_max_h);
#ifdef __cplusplus
} /* extern "C" */
+323
View File
@@ -0,0 +1,323 @@
/* rad_mtp_block.h -- BLOCK VERIFICATION of a linear MTP draft chain (--draft-verify block).
*
* Sun, Mendlovic, Leviathan, Aharoni, Beirami, Ro, Suresh, "Block Verification Accelerates
* Speculative Decoding" (arXiv 2403.10444): the chain's draft tokens X_1 .. X_g are accepted or
* rejected JOINTLY. Token-wise speculative sampling (what --draft-coupling does at each row) is
* optimal per token; block verification is optimal for the whole block: the expected number of
* accepted tokens is never lower and the output law is the target's, exactly.
*
* With P_i = the target's law after X^i (the sampler's filtered candidate softmax at verify row i,
* i = 0 .. g-1) and Q_{i+1} = the head's law the draft X_{i+1} was sampled from (the coupled state
* of round i + 1, the FP64 softmax of the reranked top 8):
*
* p_0 = 1, p_i = min(1, p_{i-1} P_{i-1}(X_i) / Q_i(X_i)) i = 1 .. g
* S_i = sum_x max(p_i P_i(x) - Q_{i+1}(x), 0) i = 0 .. g-1
* h_i = S_i / (S_i + 1 - p_i) (i < g), h_g = p_g
*
* for i = g, g-1, ..., 0: accept the block's first i tokens with probability h_i; the first
* success is tau. (h_0 = 1: it always stops.)
* tau = g: X_1 .. X_g are emitted and the next token is the ordinary draw from P_g.
* tau < g: X_1 .. X_tau are emitted, then Y ~ max(p_tau P_tau - Q_{tau+1}, 0) normalised.
*
* Exactness is checked in tests/mtp_block_test.cpp by exact enumeration of the draft tree of a toy
* model (the law of the emitted tokens computed in closed form, to 1e-12) and by a chi-square of the
* real device-shared code, with a negative control (the same rule with a wrong residual).
*
* Y may equal X_{tau+1}; the core then takes that draft as accepted (ADV_ACCEPT: "the draft is the
* sampler's token at this row") and reads the next row, which keeps its ordinary pick: a draw from
* the target's law given exactly the tokens emitted so far, so the extra tokens continue the same
* autoregressive sample. The verify op therefore writes only rows 0 .. tau of the block and leaves
* every later row alone.
*
* Relation to --draft-coupling: the DRAFT half is shared (x ~ Q at temperature 1 from the head's
* top 8, coupled states with their FP64 Q); only the verify half differs. Maximal coupling decides
* row k from P_k and Q_{k+1} alone, so it is a per-row rule the core's token comparison walks
* unchanged. Block verification decides row k from the rows after it (h_i for i > k), so the two
* rules cannot be applied to the same row; `--draft-verify block` replaces the coupling's verify
* and requires the coupled drafting (it switches it on), and it is for a LINEAR chain; Traversal
* Verification (abi/rad_mtp_traversal.h, 2505.12398) is the walk that also covers a node with
* several children.
*/
#ifndef RAD_MTP_BLOCK_H
#define RAD_MTP_BLOCK_H
#include "rad_spechub.h"
#ifdef __cplusplus
#ifdef __HIPCC__
#define RAD_BLK_HD __host__ __device__
#else
#define RAD_BLK_HD
#endif
#define RAD_MTP_BLOCK_MAX RAD_MTP_COUPLE_MAX_ROUNDS /* g: the chain's longest block */
#define RAD_MTP_BLOCK_KEY_STOP 0x424c4b53544f5000ull /* the h_i uniforms, per block */
/* Summation structure. The device decides a block with one workgroup of RAD_MTP_BLOCK_LANES
* threads, so every FP64 sum over a row's candidate plane is DEFINED as this fixed tree, which the
* host reference mirrors operation for operation (FP64 addition is not associative: the tree is
* the definition, not an approximation):
* - plane slot j belongs to lane j % LANES; a lane adds its live slots in ascending j;
* - the lanes are reduced inside each group of RAD_MTP_BLOCK_WAVE by the butterfly
* a[l] = a[l] + a[l ^ d], d = 16, 8, 4, 2, 1 (every lane of a group ends with the same bits),
* and the LANES / WAVE group sums are added as ((g0 + g1) + (g2 + g3)).
* The exp() of a slot is the same libm / device function on both sides, as before. */
#define RAD_MTP_BLOCK_LANES 128
#define RAD_MTP_BLOCK_WAVE 32
/* One verify row's candidate plane, dense (n slots, holes id < 0 and -inf scores skipped), with
* `valid` and `top` the scan of the whole plane (rad_mtp_block_scan makes it on the host; the
* device reduces the same two values across its workgroup: a max and an OR are order free). */
struct RadBlockRow {
const int32_t* ids;
const float* val;
int64_t n;
int valid;
float top;
};
/* The dense row's validity and maximum, as rad_mtp_couple_decide scans them. */
static inline RAD_BLK_HD void rad_mtp_block_scan(RadBlockRow* r, int64_t vocab) {
float top = -INFINITY;
int valid = 1;
for (int64_t j = 0; j < r->n; ++j) {
if (r->ids[j] < 0) continue;
if (r->ids[j] >= vocab || r->val[j] != r->val[j] || r->val[j] == INFINITY) valid = 0;
else if (r->val[j] > top) top = r->val[j];
}
r->valid = valid;
r->top = top;
}
static inline RAD_BLK_HD bool rad_mtp_block_live(int32_t id, float v) { return id >= 0 && v != -INFINITY; }
/* A lane's partial sums of one row: v[0..7] the mass on Q's ids (by their place in the state),
* v[8] the mass off Q's support, v[9] the total. */
struct RadBlockAcc { double v[10]; };
static inline RAD_BLK_HD int rad_mtp_block_find(const RadMtpCoupleState& s, int32_t id) {
int k = 0;
while (k < s.count && id != s.ids[k]) ++k;
return k;
}
/* Adds the live slot (id, v) to a lane's partial. */
static inline RAD_BLK_HD void rad_mtp_block_acc_add(RadBlockAcc* a, const RadMtpCoupleState& s,
int32_t id, float v, float top) {
const double w = ::exp((double)v - top);
const int k = rad_mtp_block_find(s, id);
for (int kk = 0; kk < 8; ++kk) a->v[kk] += kk == k ? w : 0.0;
a->v[8] += k >= s.count ? w : 0.0;
a->v[9] += w;
}
/* The lanes' partials reduced by the tree above (the host form; the device does the butterfly with
* shuffles and adds the four group sums the same way). */
static inline RAD_BLK_HD RadBlockAcc rad_mtp_block_tree(const RadBlockAcc* lane) {
RadBlockAcc grp[RAD_MTP_BLOCK_LANES / RAD_MTP_BLOCK_WAVE];
for (int w = 0; w < RAD_MTP_BLOCK_LANES / RAD_MTP_BLOCK_WAVE; ++w) {
RadBlockAcc a[RAD_MTP_BLOCK_WAVE], t[RAD_MTP_BLOCK_WAVE];
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l) a[l] = lane[w * RAD_MTP_BLOCK_WAVE + l];
for (int d = RAD_MTP_BLOCK_WAVE / 2; d > 0; d >>= 1) {
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l) t[l] = a[l];
for (int l = 0; l < RAD_MTP_BLOCK_WAVE; ++l)
for (int c = 0; c < 10; ++c) a[l].v[c] = t[l].v[c] + t[l ^ d].v[c];
}
grp[w] = a[0];
}
RadBlockAcc o;
for (int c = 0; c < 10; ++c) o.v[c] = (grp[0].v[c] + grp[1].v[c]) + (grp[2].v[c] + grp[3].v[c]);
return o;
}
/* P_i over Q_{i+1}'s support (pq, normalised, duplicate candidates aggregated), the mass off that
* support (pout), the normaliser `sum` and the index `ix` of the draft token in the state's ids. */
struct RadBlockStat {
double pq[8];
double pout, sum;
int ix;
};
/* The stat from the reduced partials `t` (what the device builds from its workgroup's tree). */
static inline RAD_BLK_HD bool rad_mtp_block_stat_from(const RadBlockAcc& t, int valid, float top,
const RadMtpCoupleState& s, RadBlockStat* o) {
if (!valid || top == -INFINITY) return false;
const double sum = t.v[9];
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
o->ix = -1;
for (int k = 0; k < 8; ++k) o->pq[k] = k < s.count ? t.v[k] : 0.0;
for (int k = 0; k < s.count; ++k) {
o->pq[k] /= sum;
if (s.ids[k] == s.x) o->ix = k;
}
o->pout = t.v[8] / sum;
o->sum = sum;
return o->ix >= 0;
}
static inline RAD_BLK_HD bool rad_mtp_block_stat(const RadBlockRow& r, const RadMtpCoupleState& s,
RadBlockStat* o) {
if (!r.valid || r.top == -INFINITY) return false;
RadBlockAcc lane[RAD_MTP_BLOCK_LANES];
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l)
for (int c = 0; c < 10; ++c) lane[l].v[c] = 0;
for (int64_t j = 0; j < r.n; ++j)
if (rad_mtp_block_live(r.ids[j], r.val[j]))
rad_mtp_block_acc_add(&lane[j % RAD_MTP_BLOCK_LANES], s, r.ids[j], r.val[j], r.top);
return rad_mtp_block_stat_from(rad_mtp_block_tree(lane), r.valid, r.top, s, o);
}
/* The block's weights. p[i] (i = 0 .. g), h[i] (i = 0 .. g). */
struct RadBlockPlan {
int g;
double p[RAD_MTP_BLOCK_MAX + 1];
double h[RAD_MTP_BLOCK_MAX + 1];
double s[RAD_MTP_BLOCK_MAX + 1]; /* S_i, the residual's mass (s[g] unused) */
};
/* The residual mass of one token of row i at weight p: max(p P(x) - Q(x), 0) on Q's support,
* p P(x) off it. */
static inline RAD_BLK_HD double rad_mtp_block_resid_sum(const RadMtpCoupleState& s,
const RadBlockStat& t, double p) {
double r = p * t.pout;
for (int k = 0; k < s.count; ++k) r += rad_spechub_positive(p * t.pq[k] - s.q[k]);
return r;
}
/* st[i] / stat[i] for i = 0 .. g-1. */
static inline RAD_BLK_HD void rad_mtp_block_plan(const RadMtpCoupleState* st,
const RadBlockStat* stat, int g,
RadBlockPlan* o) {
o->g = g;
o->p[0] = 1.0;
for (int i = 0; i < g; ++i) {
const double ratio = stat[i].pq[stat[i].ix] / st[i].q[stat[i].ix];
const double v = o->p[i] * ratio;
o->p[i + 1] = v < 1.0 ? v : 1.0;
}
for (int i = 0; i < g; ++i) {
const double S = rad_mtp_block_resid_sum(st[i], stat[i], o->p[i]);
o->s[i] = S;
const double den = S + (1.0 - o->p[i]);
o->h[i] = (den > 0 && rad_spechub_finite(den)) ? S / den : 1.0;
}
o->s[g] = 0;
o->h[g] = o->p[g];
}
/* tau: the first i, counting down from g, whose uniform falls below h_i. The uniforms are keyed by
* the block's first output position, so no row's own draws are reused. */
static inline RAD_BLK_HD int rad_mtp_block_tau(const RadBlockPlan& pl, uint64_t seed, uint64_t pos0) {
for (int i = pl.g; i > 0; --i)
if (rad_spechub_uniform(seed, pos0, RAD_MTP_BLOCK_KEY_STOP + (uint64_t)i) < pl.h[i]) return i;
return 0;
}
/* One lane's partials of the residual draw: `off` the off-support masses p * (w / sum) (slots whose
* id is not among Q's), `all` the plain weights (the fallback draw from P itself), and the last
* positive id of each, in the lane's slot order. */
struct RadBlockLane { double off, all; int32_t last_off, last_all; };
static inline RAD_BLK_HD void rad_mtp_block_lane_add(RadBlockLane* a, const RadMtpCoupleState& s,
const RadBlockStat& t, double p, int32_t id,
float v, float top) {
const double w = ::exp((double)v - top);
a->all += w;
if (w > 0) a->last_all = id;
if (rad_mtp_block_find(s, id) >= s.count) {
const double m = p * (w / t.sum);
a->off += m;
if (m > 0) a->last_off = id;
}
}
/* Y ~ max(p P - Q, 0) normalised (state s, row r, stat t) with the uniform u in [0, 1). The mass
* is walked in a fixed order: the ids of Q (place k = 0 .. count-1, mass max(p pq[k] - q[k], 0)),
* then the other live slots lane by lane (the lanes of the tree above, each lane's slots in
* ascending order; the lane totals are added in lane order). The walk subtracts the masses from
* c = u * total and stops at the first negative; inside the lane it stops in, the walk restarts
* from the c at the lane's start, so the structure is exactly what the workgroup computes. When
* the total underflows to zero (FP64 cancellation with p = 1: P == Q) Y is drawn from P itself
* over all live slots in the same lane order, a branch that depends on (P, Q) only. False: no live
* candidate. */
static inline RAD_BLK_HD bool rad_mtp_block_resid_walk(const RadBlockRow& r,
const RadMtpCoupleState& s,
const RadBlockStat& t, double p, double u,
const RadBlockLane* lane, int32_t* out) {
double on[8];
double total = 0;
for (int k = 0; k < s.count; ++k) { on[k] = rad_spechub_positive(p * t.pq[k] - s.q[k]); total += on[k]; }
double offt = 0;
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) offt += lane[l].off;
total += offt;
const bool resid = total > 0 && rad_spechub_finite(total);
double c = resid ? u * total : u * t.sum;
int32_t last = -1;
if (resid) {
for (int k = 0; k < s.count; ++k)
if (on[k] > 0) { last = s.ids[k]; c -= on[k]; if (c < 0) { *out = last; return true; } }
}
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) {
const double T = resid ? lane[l].off : lane[l].all;
const int32_t ll = resid ? lane[l].last_off : lane[l].last_all;
if (!(T > 0)) continue;
if (ll >= 0) last = ll;
if (c - T < 0) {
double cl = c;
int32_t lastl = -1;
for (int64_t j = l; j < r.n; j += RAD_MTP_BLOCK_LANES) {
if (!rad_mtp_block_live(r.ids[j], r.val[j])) continue;
const double w = ::exp((double)r.val[j] - r.top);
double m;
if (resid) {
if (rad_mtp_block_find(s, r.ids[j]) < s.count) continue;
m = p * (w / t.sum);
} else {
m = w;
}
if (m > 0) { lastl = r.ids[j]; cl -= m; if (cl < 0) { *out = lastl; return true; } }
}
*out = lastl >= 0 ? lastl : ll;
return *out >= 0;
}
c -= T;
}
*out = last;
return last >= 0;
}
static inline RAD_BLK_HD bool rad_mtp_block_resid_draw(const RadBlockRow& r,
const RadMtpCoupleState& s,
const RadBlockStat& t, double p, double u,
int32_t* out) {
RadBlockLane lane[RAD_MTP_BLOCK_LANES];
for (int l = 0; l < RAD_MTP_BLOCK_LANES; ++l) lane[l] = RadBlockLane{ 0, 0, -1, -1 };
for (int64_t j = 0; j < r.n; ++j)
if (rad_mtp_block_live(r.ids[j], r.val[j]))
rad_mtp_block_lane_add(&lane[j % RAD_MTP_BLOCK_LANES], s, t, p, r.ids[j], r.val[j], r.top);
return rad_mtp_block_resid_walk(r, s, t, p, u, lane, out);
}
/* The whole decision on the host: rows[0 .. g-1] / st[0 .. g-1] are the block's verify rows and
* their coupled states (round i + 1 at row i), pos0 the first row's output position. Writes tau and
* *y; *y = -1 when tau == g (the g-th row's ordinary draw stands). False for an invalid target. */
static inline RAD_BLK_HD bool rad_mtp_block_decide(const RadMtpCoupleState* st,
const RadBlockRow* rows, int g, uint64_t seed,
uint64_t pos0, int* tau, int32_t* y) {
RadBlockStat stat[RAD_MTP_BLOCK_MAX];
RadBlockPlan pl;
if (g < 1 || g > RAD_MTP_BLOCK_MAX) return false;
for (int i = 0; i < g; ++i)
if (!rad_mtp_block_stat(rows[i], st[i], &stat[i])) return false;
rad_mtp_block_plan(st, stat, g, &pl);
const int t = rad_mtp_block_tau(pl, seed, pos0);
*tau = t;
*y = -1;
if (t >= g) return true;
return rad_mtp_block_resid_draw(rows[t], st[t], stat[t], pl.p[t],
rad_spechub_uniform(seed, pos0 + (uint64_t)t, RAD_SAMPLE_KEY_RESID), y);
}
#endif /* __cplusplus */
#endif /* RAD_MTP_BLOCK_H */
+426
View File
@@ -0,0 +1,426 @@
/* rad_mtp_rrs.h -- recursive rejection sampling over a node's SIBLING drafts under
* --draft-coupling on: the draft side (children sampled without replacement from Q) and the
* verify side (the walk over a node's children against the target's P), as plain code the host
* oracle, the device kernels and the tests share, so they cannot drift. Traversal verification
* (abi/rad_mtp_traversal.h) walks nodes that drafted several children; the serial head of this
* engine drafts one (nkids <= 1, the chain), so nothing in the engine draws siblings yet: the
* header is the verify side's definition and its tests (tests/mtp_rrs_test.cpp). The short proof:
*
* Draft. A node whose head pass left the law Q (the FP64 T1 softmax of the reranked top 8,
* rad_mtp_couple_build_q) drafts its children x_1, x_2, ... by Gumbel-top-k over log Q: add an
* independent Gumbel to every log q_i and take the entries in descending order. That is sampling
* without replacement (Plackett-Luce): x_1 ~ Q, x_2 ~ Q(. | not x_1), ... The first m of them are
* the node's children, m chosen by anything that does not read the values x_j it applies to
* (a fixed count, or a rule over the slot priorities, the j-th largest q of Q, never the drawn
* token).
*
* Verify (Sequoia, Chen et al. 2024, Alg. 1; SpecInfer's multi-step verification with the draft
* law renormalised after each removal). P_1 = the target's law, q_1 = Q. For i = 1..m:
* accept x_i with probability min(1, P_i(x_i) / q_i(x_i));
* on rejection P_{i+1} = norm(max(P_i - q_i, 0)), q_{i+1} = q_i with x_i removed, renormalised.
* All rejected: the token is a draw from P_{m+1}. Exactness (induction on m): after a rejection of
* the first draft the continuation depends on x_1 only through q_2, and P_2 = norm(max(P - q, 0))
* does not depend on x_1 at all, so by the hypothesis it emits ~ P_2 whatever x_1 was; then
* P(emit y) = sum_x q(x) min(1, P(x)/q(x)) [x = y] + P(reject) P_2(y) = min(P, q)(y) +
* max(P - q, 0)(y) = P(y). The emitted token is the accepted child's token, or a residual draw that
* has no mass on any rejected child (P_{i+1}(x_i) = 0 after a rejection), so the core's rule "follow
* the first child whose token is the sampler's token at the row" (ADV_ACCEPT) walks exactly the
* decision made here and needs no change.
*
* Wire: the node's RadMtpCoupleState holds Q (ids, q), the children in draft order in ids[0 ..
* nkids), x = ids[0]. A state with nkids <= 1 is the chain's (rad_mtp_couple_decide, bit for bit).
*/
#ifndef RAD_MTP_RRS_H
#define RAD_MTP_RRS_H
#include "rad_spechub.h"
#ifdef __cplusplus
#ifdef __HIPCC__
#define RAD_RRS_HD __host__ __device__
#else
#define RAD_RRS_HD
#endif
#define RAD_MTP_RRS_KEY_TREE 0x4d54524545474d42ull /* the draft's Gumbel stream */
#define RAD_MTP_RRS_KEY_ACCEPT 0x41435054ull
static inline RAD_RRS_HD uint64_t rad_mtp_rrs_mix(uint64_t z) {
z += 0x9e3779b97f4a7c15ull;
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
return z ^ (z >> 31);
}
/* The open-interval uniform of candidate `c` of draft node `node`: (seed, base) name the draft
* stream (the request's seed and its pre-commit output length, which no later step reuses). */
static inline RAD_RRS_HD double rad_mtp_rrs_gumbel_u(uint64_t seed, uint64_t base,
uint64_t node, int c) {
uint64_t z = rad_mtp_rrs_mix(seed ^ RAD_MTP_RRS_KEY_TREE);
z = rad_mtp_rrs_mix(z ^ base);
z = rad_mtp_rrs_mix(z + node * 16u + (uint64_t)c);
return ((double)(z >> 11) + 0.5) * 0x1p-53;
}
/* Gumbel-top-k order of Q's support: order[0 .. s.count) are indices into s.ids, the draft order
* (descending of log q + Gumbel, ties to the lower index). Draws one uniform per support entry from
* the state's own draw, node `node`. */
static inline RAD_RRS_HD void rad_mtp_rrs_order(const RadMtpCoupleState& s, uint64_t node,
int* order) {
double key[8];
for (int i = 0; i < s.count; ++i) {
const double u = rad_mtp_rrs_gumbel_u(s.draw.seed, s.draw.base, node, i);
key[i] = ::log(s.q[i]) - ::log(-::log(u));
order[i] = i;
}
for (int i = 1; i < s.count; ++i) { /* insertion sort, stable */
const int o = order[i];
int j = i;
while (j > 0 && key[order[j - 1]] < key[o]) { order[j] = order[j - 1]; --j; }
order[j] = o;
}
}
/* Draw the node's children: reorder Q's support into the draft order (ids and q together), set
* x = ids[0] and nkids = `nkids`. */
static inline RAD_RRS_HD void rad_mtp_rrs_draw(RadMtpCoupleState* s, uint64_t node, int nkids) {
int order[8];
rad_mtp_rrs_order(*s, node, order);
int32_t ids[8];
double q[8];
for (int i = 0; i < s->count; ++i) { ids[i] = s->ids[order[i]]; q[i] = s->q[order[i]]; }
for (int i = 0; i < s->count; ++i) { s->ids[i] = ids[i]; s->q[i] = q[i]; }
s->x = s->ids[0];
s->nkids = nkids < s->count ? nkids : s->count;
}
/* The SLOT priorities of a node's law: slot j carries the log of the j-th LARGEST q of Q
* (descending, ties by position), -inf past the support. They are a function of Q alone, never of
* which token was drawn into which slot, so a rule that reads only them admits children by a
* quantity independent of the values the children take. `s` is read before the draw reorders it
* or after (the multiset of q is the same). */
static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq(const RadMtpCoupleState& s, float* ov) {
double qs[8];
const int n = s.count < 8 ? s.count : 8;
for (int i = 0; i < n; ++i) qs[i] = s.q[i];
for (int i = 1; i < n; ++i) {
const double v = qs[i];
int j = i;
while (j > 0 && qs[j - 1] < v) { qs[j] = qs[j - 1]; --j; }
qs[j] = v;
}
for (int c = 0; c < 8; ++c) ov[c] = c < n ? (float)::log(qs[c]) : -INFINITY;
}
/* The longest prefix of the state's children that are the first `n` of `kid[]` (the tree's
* children of this row, in node order, repeats dropped): what a verify may keep when a window cut
* the tree short. 0 when even the first differs. */
static inline RAD_RRS_HD int rad_mtp_rrs_prefix(const RadMtpCoupleState& s, const int32_t* kid,
int n) {
const int have = s.nkids >= 1 ? s.nkids : 1;
int m = 0;
while (m < have && m < n && m < s.count && s.ids[m] == kid[m]) ++m;
return s.nkids >= 2 ? m : (n >= 1 && s.x == kid[0] ? 1 : 0);
}
/* The acceptance uniform of the i-th child at output position `pos`: the first is the chain's. */
static inline RAD_RRS_HD double rad_mtp_rrs_uaccept(uint64_t seed, uint64_t pos, int i) {
return rad_spechub_uniform(seed, pos, i == 0 ? (uint64_t)RAD_SAMPLE_KEY_ACCEPT
: RAD_MTP_RRS_KEY_ACCEPT ^ rad_mtp_rrs_mix((uint64_t)i));
}
/* The verify of a node with nkids >= 2 children: the recursion above over the sampler's surviving
* candidates (ids/val, n of them, FP64 P = softmax of val). Writes the emitted token to *out and
* returns true, or false for an invalid target (the row keeps the ordinary token).
*
* The decision reads the live candidates (id >= 0, value not -inf) in ascending order through a view
* `C::each(f)`, f(id, w, k) -> bool (false stops): w = exp(val - top) in FP64, k the id's slot in the
* state's support (the first match) or s.count when it is outside. The host view (RadRrsHostCands)
* computes them on the fly; the device verify (plugin/spechub/spechub.hip) compacts the live
* candidates and computes every w and k with the whole workgroup, then runs this same function on one
* lane over the stored values, so the ordered sums, and with them the token, are the host's. `pq_out`
* and `sum_out` (optional) hand back P's masses on the support and their normaliser (the export). */
template <class C>
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_over(const RadMtpCoupleState& s, const C& cs,
uint64_t seed, uint64_t pos, int32_t* out,
double* pq_out = nullptr,
double* sum_out = nullptr) {
double sum = 0, pq[8] = {}, wout = 0;
cs.each([&](int32_t, double w, int k) {
sum += w;
if (k < s.count) pq[k] += w; else wout += w;
return true;
});
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
if (pq_out) for (int k = 0; k < 8; ++k) pq_out[k] = pq[k];
if (sum_out) *sum_out = sum;
/* P over Q's support (normalised), and the off-support mass's scale `so` (P_i(y) = so * w / sum
* there). qr: the draft law with the drawn children removed. */
double r[8], qr[8], so = 1.0;
for (int k = 0; k < s.count; ++k) { r[k] = pq[k] / sum; qr[k] = s.q[k]; }
const double pout = wout / sum;
bool direct = false;
for (int i = 0; i < s.nkids && !direct; ++i) {
double sq = 0;
for (int k = 0; k < s.count; ++k) sq += qr[k];
if (!(sq > 0)) break;
const double qx = qr[i] / sq;
if (r[i] >= qx || rad_mtp_rrs_uaccept(seed, pos, i) * qx < r[i]) { *out = s.ids[i]; return true; }
double z = so * pout;
for (int k = 0; k < s.count; ++k) {
const double d = r[k] - qr[k] / sq;
r[k] = d > 0 ? d : 0;
z += r[k];
}
if (!(z > 0) || !rad_spechub_finite(z)) { direct = true; break; }
for (int k = 0; k < s.count; ++k) r[k] /= z;
so /= z;
qr[i] = 0;
}
const double u = rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID);
double c;
int32_t last = -1;
if (direct) {
c = u * sum;
bool hit = false;
cs.each([&](int32_t id, double w, int) {
if (w > 0) { last = id; c -= w; if (c < 0) { hit = true; return false; } }
return true;
});
*out = last;
(void)hit;
return true;
}
double total = 0;
for (int k = 0; k < s.count; ++k) total += r[k];
total += so * pout;
c = u * total;
unsigned seen = 0;
bool hit = false;
cs.each([&](int32_t id, double w, int k) {
double m;
if (k < s.count) {
if (seen & (1u << k)) return true;
seen |= 1u << k;
m = r[k];
} else {
m = so * (w / sum);
}
if (m > 0) { last = id; c -= m; if (c < 0) { hit = true; return false; } }
return true;
});
*out = last;
(void)hit;
return last >= 0;
}
/* The host view: the candidates as the sampler wrote them, weights computed as they are read. */
struct RadRrsHostCands {
const RadMtpCoupleState& s;
const int32_t* ids; const float* val; int64_t n; float top;
template <class F> RAD_RRS_HD void each(F&& f) const {
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
int k = 0;
while (k < s.count && ids[j] != s.ids[k]) ++k;
if (!f(ids[j], ::exp((double)val[j] - top), k)) return;
}
}
};
static inline RAD_RRS_HD bool rad_mtp_rrs_decide(const RadMtpCoupleState& s, const int32_t* ids,
const float* val, int64_t n, int64_t vocab,
uint64_t seed, uint64_t pos, int32_t* out) {
float top = -INFINITY;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
if (val[j] > top) top = val[j];
}
if (top == -INFINITY) return false;
return rad_mtp_rrs_decide_over(s, RadRrsHostCands{ s, ids, val, n, top }, seed, pos, out);
}
/* ================================================================== RheoSampling siblings
*
* --draft-siblings rheo (--draft-rheo-m m). Hu et al. 2025 (arXiv 2502.18779, Thm 8, the greedy
* multi-draft verifier) and RheoSampling (arXiv 2609.21827): instead of Gumbel-top-k siblings, a node's
* children are
* T = the m tokens of largest Q, in descending q order (deterministic, rank slots 0 .. m-1), and
* u ~ Qt, ONE token sampled from the tail law Qt(x) = Q(x) / z over the support outside T,
* z = Q(outside T), in slot m;
* the draft order stored in the state is ids = [T..., u, the rest of the support in descending q],
* scheme = m + 1. A node whose support has no more than m tokens has no tail child (all of it is T).
*
* Verify (derived here, not quoted; the law is checked by tests/mtp_rrs_test.cpp by exhaustive
* enumeration). P = the target's law, children present = the first nkids of the draft order.
* tail child present (nkids > |T|, which with a prefix draft order means every T token is a child):
* accept u with probability min(1, P(u) / Qt(u)) -> emit u
* else emit y ~ R / |R|, R(y) = P(y) y in T or off Q's support,
* R(y) = max(P(y) - Qt(y), 0) y in the tail support (R(u) = 0 here)
* otherwise (the tail slot was pruned or cut by a window, or Q has no tail): emit y ~ P directly.
* Exactness: P(emit y) = min(P, Qt)(y) [y in tail] + (1 - A) R(y) / |R| with |R| = 1 - A,
* A = sum_tail min(P, Qt), and min(P, Qt) + R = P on the tail, R = P elsewhere: P(emit y) = P(y).
* It needs only that u ~ Qt independently of the verifier's uniforms (a separate draft stream), and
* that WHICH slots exist depends on Q and the tree's budget alone (never on the value of u): both
* hold, the slot priorities are rad_mtp_rrs_slot_logq_rheo. The emitted token is a child with
* probability P(T) + A = sum_T P + sum_tail min(P, Qt), Thm 8's value, and a residual draw never
* lands on u (R(u) = 0 when u was rejected), so the core's "follow the first child whose token is
* the sampler's" walks the decision made here.
* m = 0 is the single-draft maximal coupling of the chain (rad_mtp_couple_decide) with the sampled
* child in slot 0.
*/
#define RAD_MTP_RRS_KEY_TAIL_C 8 /* candidate index of the tail draw in the draft stream (0..7 are Gumbel's) */
/* Slot priorities of a rheo node (functions of Q alone, non-increasing): slots 0 .. m-1 carry the
* log of the j-th largest q, slot m RheoSampling's proxy log min{q_(m-1), z} (z = the tail mass; with
* m = 0, z = 1), -inf for the other slots and for slots past the support. */
static inline RAD_RRS_HD void rad_mtp_rrs_slot_logq_rheo(const RadMtpCoupleState& s, int m, float* ov) {
double qs[8];
const int n = s.count < 8 ? s.count : 8;
for (int i = 0; i < n; ++i) qs[i] = s.q[i];
for (int i = 1; i < n; ++i) {
const double v = qs[i];
int j = i;
while (j > 0 && qs[j - 1] < v) { qs[j] = qs[j - 1]; --j; }
qs[j] = v;
}
const int nt = m < n ? m : n;
for (int c = 0; c < 8; ++c) ov[c] = c < nt ? (float)::log(qs[c]) : -INFINITY;
if (n > nt) {
double z = 0;
for (int i = nt; i < n; ++i) z += qs[i];
if (z > 1) z = 1;
const double ref = nt > 0 ? qs[nt - 1] : 1.0;
ov[nt] = (float)::log(z < ref ? z : ref);
}
}
/* Draw a rheo node's children: reorder Q's support into [top-m by q desc, the sampled tail child,
* the rest by q desc], set x = ids[0], scheme = m + 1 and nkids = min(nkids, children possible). The
* tail child is the inverse-CDF draw of Qt with the draft stream's uniform of (seed, base, node). */
static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo_u(RadMtpCoupleState* s, double ut, int nkids, int m) {
int ord[8];
const int n = s->count;
for (int i = 0; i < n; ++i) ord[i] = i;
for (int i = 1; i < n; ++i) { /* descending q, stable */
const int o = ord[i];
int j = i;
while (j > 0 && s->q[ord[j - 1]] < s->q[o]) { ord[j] = ord[j - 1]; --j; }
ord[j] = o;
}
const int nt = m < n ? m : n;
if (n > nt) {
double z = 0;
for (int i = nt; i < n; ++i) z += s->q[ord[i]];
double c = ut * z;
int pick = n - 1;
for (int i = nt; i < n; ++i) { c -= s->q[ord[i]]; if (c < 0) { pick = i; break; } }
const int o = ord[pick];
for (int i = pick; i > nt; --i) ord[i] = ord[i - 1];
ord[nt] = o;
}
int32_t ids[8];
double q[8];
for (int i = 0; i < n; ++i) { ids[i] = s->ids[ord[i]]; q[i] = s->q[ord[i]]; }
for (int i = 0; i < n; ++i) { s->ids[i] = ids[i]; s->q[i] = q[i]; }
const int cap = nt + (n > nt ? 1 : 0);
s->x = s->ids[0];
s->scheme = m + 1;
s->nkids = nkids < cap ? nkids : cap;
}
static inline RAD_RRS_HD void rad_mtp_rrs_draw_rheo(RadMtpCoupleState* s, uint64_t node, int nkids, int m) {
rad_mtp_rrs_draw_rheo_u(s, rad_mtp_rrs_gumbel_u(s->draw.seed, s->draw.base, node, RAD_MTP_RRS_KEY_TAIL_C),
nkids, m);
}
/* The verify of a rheo node (any nkids >= 0): the rule above. Same contract as rad_mtp_rrs_decide. */
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo_u(const RadMtpCoupleState& s, const int32_t* ids,
const float* val, int64_t n, int64_t vocab,
double u_accept, double u_resid, int32_t* out) {
float top = -INFINITY;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
if (val[j] > top) top = val[j];
}
if (top == -INFINITY) return false;
double sum = 0, pq[8] = {};
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
const double w = ::exp((double)val[j] - top);
sum += w;
for (int k = 0; k < s.count; ++k)
if (ids[j] == s.ids[k]) { pq[k] += w; break; }
}
if (!(sum > 0) || !rad_spechub_finite(sum)) return false;
const int m = s.scheme - 1;
const int nt = m < s.count ? m : s.count;
const bool tail = m >= 0 && s.count > nt && s.nkids > nt;
double qt[8] = {}, r[8] = {};
bool dominated = true;
for (int k = 0; k < s.count; ++k) pq[k] /= sum;
if (tail) {
double z = 0;
for (int k = nt; k < s.count; ++k) z += s.q[k];
for (int k = nt; k < s.count; ++k) {
const double v = nt == 0 ? s.q[k] : s.q[k] / z;
qt[k] = v > 1 ? 1 : v; /* clamp: rounding must not push a one-token tail past 1 */
dominated = dominated && pq[k] >= qt[k];
}
for (int k = 0; k < s.count; ++k) r[k] = k < nt ? pq[k] : rad_spechub_positive(pq[k] - qt[k]);
}
/* mass of candidate j in R (the tail case) or in P (otherwise); Q tokens count once. */
unsigned seen = 0;
auto mass = [&](int64_t j) -> double {
if (ids[j] < 0 || val[j] == -INFINITY) return 0;
for (int k = 0; k < s.count; ++k)
if (s.ids[k] == ids[j]) {
if (seen & (1u << k)) return 0;
seen |= 1u << k;
return tail ? r[k] : pq[k];
}
return ::exp((double)val[j] - top) / sum;
};
double resid = 0;
if (tail) {
for (int64_t j = 0; j < n; ++j) resid += mass(j);
seen = 0;
}
if (!tail || (!dominated && !(resid > 0 && rad_spechub_finite(resid)))) {
double c = u_resid * sum; /* P itself, in the sampler's candidate order */
int32_t last = -1;
for (int64_t j = 0; j < n; ++j)
if (ids[j] >= 0 && val[j] != -INFINITY) {
const double w = ::exp((double)val[j] - top);
if (w > 0) { last = ids[j]; c -= w; if (c < 0) { *out = last; return true; } }
}
*out = last;
return last >= 0;
}
const int iu = nt;
if (pq[iu] >= qt[iu] || u_accept * qt[iu] < pq[iu]) {
*out = s.ids[iu];
return true;
}
double c = u_resid * resid;
int32_t last = -1;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] == s.ids[iu]) continue;
const double mm = mass(j);
if (mm > 0) { last = ids[j]; c -= mm; if (c < 0) { *out = last; return true; } }
}
*out = last;
return last >= 0;
}
static inline RAD_RRS_HD bool rad_mtp_rrs_decide_rheo(const RadMtpCoupleState& s, const int32_t* ids,
const float* val, int64_t n, int64_t vocab,
uint64_t seed, uint64_t pos, int32_t* out) {
return rad_mtp_rrs_decide_rheo_u(s, ids, val, n, vocab,
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_ACCEPT),
rad_spechub_uniform(seed, pos, RAD_SAMPLE_KEY_RESID), out);
}
#endif /* __cplusplus */
#endif /* RAD_MTP_RRS_H */
+549
View File
@@ -0,0 +1,549 @@
/* rad_mtp_traversal.h -- Traversal Verification (Weng et al., arXiv 2505.12398) of a draft under
* sampling (--draft-verify traversal, needs --draft-coupling on). The walk is defined on a tree; the
* serial head of this engine drafts a chain, a tree of one child a node, which the sampler stages
* (core/sample/sampler.cpp). Plain code shared by the host oracle, the device kernel and the tests;
* the short form of the argument:
*
* Row-wise verification (rad_mtp_rrs_decide) decides each node on its own. Traversal verification
* decides a whole ROOT-TO-LEAF PATH at once, bottom-up, and so can accept a longer prefix from the
* same tree (for a chain it is Block Verification, never worse than token-level rejection sampling).
*
* State of a node v during the walk: p_v (its acceptance rate, a sequence-level ratio), the target
* law M_b(.|v) restricted to what has not been rejected below it (r), and the law the NEXT child of
* v was drawn from.
* - A child c of v enters with p_c = min(1, p_v * r(c)/qn(c)), qn the law c was drawn from GIVEN
* the children tried before it.
* - The walk descends to the first leaf and tests eta < p_leaf. Accept: the path is accepted and
* the final token is drawn from that node's current residual law r (the plain target if none of
* its children was rejected). Reject: the leaf is deleted and its parent v is updated:
* S = sum_x [ p_v r(x) - qn(x) ]+
* p_v' = S / (S + 1 - p_v)
* r' = [ p_v r - qn ]+ / S
* and the walk continues with v's next child, or tests v itself once it has none.
* The walk keeps the PRODUCT m(x) = p_v r(x) (on the draft support per slot, and one number for
* everything off it, where qn is zero), which is all the rules read: p_c = min(1, m(c)/qn(c)), and
* the update is one division, m' = [m - qn]+ / (S + 1 - p_v), p_v' = S / (S + 1 - p_v), the
* off-support mass scaled alike; the final token is drawn in proportion to m. A node entered with
* rate p keeps its target law unscaled and the factor p beside it (sc) until its first child is
* rejected, so entering a node costs one division (the child's rate) and no pass over its law.
* Exactness (Theorem 3.3 of the paper, Lemma A.2 by induction over a node's descendants): the
* subtree of v is accepted with probability p_v and, given that, the token after v follows r. One
* step of the induction, for a child drawn from ANY law qn that may depend on the children before
* it: P(accepted through a child x) = qn(x) min(1, p_v r(x)/qn(x)) = min(qn(x), p_v r(x));
* P(the child's subtree is rejected) = 1 - p_v + S; the rest then accepts with p_v' and r', which
* adds (1 - p_v + S) p_v' r'(x) = [p_v r(x) - qn(x)]+, and the two sum to p_v r(x). It needs the
* tree's shape to be independent of the drawn tokens (a chain's is), and each child's own law:
* - Gumbel-top-k siblings (the default, Plackett-Luce without replacement): qn is the node's Q
* with the children already tried removed, renormalised;
* - RheoSampling siblings (state.scheme = m + 1, abi/rad_mtp_rrs.h): the
* sampled tail child is tried FIRST with qn = Qt, the tail law, then the deterministic top-q
* children in their order, each with qn = a point mass on its token. A point mass accepts with
* p_v r(c) and leaves r without c; tried in this order the node's children take
* sum_tail min(P, Qt) + P(T) of the target, the greedy multi-draft verifier's value (Hu et al.
* 2025, Thm 8).
* tests/mtp_rrs_test.cpp checks the walk by exact enumeration and by chi-square, and shows that
* plausible mistakes (token-level ratios, no (1 - p) term, with-replacement update for
* without-replacement drafts, a rheo node walked as a Gumbel one) fail the same statistic.
*
* THE TARGET LAW IN FIXED POINT. The walk reads a row's target law only through its mass on the
* node's draft support (eight ids), the mass off it and the total; the final token needs the
* off-support candidates in order. Each live candidate's weight is an INTEGER:
*
* m_j = floor(2^40 * e(val_j - top)), e(x) = rad_mtp_trav_mass's FP32 exponential
*
* (top the row's largest value; the scale drops a bit per doubling of the plane past 4096 slots so
* a row's total stays below 2^53). Integer addition is associative, so the sums are the same bits
* whatever order a workgroup adds them in: the device kernel (plugin/spechub/spechub.hip) splits a
* row over its threads any way it likes and still equals this header's serial loops, with no
* reduction tree to mirror. e() is basic FP32 arithmetic and integer shifts, identical on host and
* device (no libm call, no contraction: -ffp-contract=off, and the attribute below for a host
* build that enables FMA).
* Why FP32 suffices: the algorithm is exact for whatever positive weights define the law, as long as
* every decision reads the same ones, which the integers guarantee. The law it realises is
* P~(y) = m_y / sum m, within 2^-22 relative per candidate (e's error, tests/mtp_rrs_test.cpp checks
* it) plus 2^-40 absolute of the softmax of the sampler's FP32 candidates: the accuracy class of the
* uncoupled sample_pick (FP32 expf, FP32 running sum, a 24-bit uniform), which is the law a request
* gets without speculation. The 8-wide FP64 sums of the walk are a fixed tree (rad_mtp_trav_sum8),
* so a device may run them on one lane or across eight.
*
* Wire: no new state. The walk reads the same RadMtpCoupleState rows as the row-wise verify and
* writes the SAME plane the core already walks (ADV_ACCEPT: the first child whose token is the
* sampler's token at the row): on the accepted path every row's token is its path child's token and
* the last row's token is the final one; the other rows are not on the walk and keep the pick.
*/
#ifndef RAD_MTP_TRAVERSAL_H
#define RAD_MTP_TRAVERSAL_H
#include "rad_spechub.h"
#include "rad_mtp_rrs.h"
#ifdef __cplusplus
#define RAD_MTP_TRAV_MAX_DEPTH 16
#define RAD_MTP_TRAV_MAX_ROWS 64 /* rows of one request the walk reads (its first ones) */
#define RAD_MTP_TRAV_KEY 0x54524156ull /* "TRAV": the walk's acceptance uniforms */
#define RAD_MTP_TRAV_QBITS 40 /* the unit of a candidate's mass: 2^-40 of the top's */
/* A host build with FMA enabled must not contract the exponential's products into its sums: the
* device does not (-ffp-contract=off), and the masses have to be the same bits. */
#if defined(__GNUC__) && !defined(__clang__)
#define RAD_TRAV_STRICT __attribute__((optimize("fp-contract=off")))
#else
#define RAD_TRAV_STRICT
#endif
/* Test-only switches; the engine passes the zero value. */
struct RadMtpTravOpt {
int ctl = 0; /* negative controls: 1 token-level ratios, 2 no (1 - p) term, 3 q never
renormalised (the with-replacement update on without-replacement drafts),
4 a RheoSampling node walked as a Gumbel one */
/* Enumeration (tests): >= 0 replaces the uniforms -- test number `accept_at` (1-based) accepts
* and every earlier one rejects; `p_test[i]` receives the acceptance rate of test i + 1 and
* `*n_tests` their count. */
int accept_at = -1;
double* p_test = nullptr;
int* n_tests = nullptr;
int max_tests = 0;
double u_final = -1.0; /* >= 0: the final token's uniform (rad_mtp_trav_walk) */
};
struct RadMtpTravOut {
int n = 0; /* nodes on the path, root first */
int node[RAD_MTP_TRAV_MAX_DEPTH + 2] = {};
int32_t y = -1; /* the final token ... */
bool has_y = false; /* ... when the last node carries a valid state */
};
/* ---------------------------------------------------------------- the target law in fixed point */
/* The mass unit of a plane of n candidates: 2^-qbits of the top candidate's weight, so that a
* row's total stays below 2^53 (exact in FP64). */
static inline RAD_RRS_HD int rad_mtp_trav_qbits(int64_t n) {
int q = RAD_MTP_TRAV_QBITS;
for (int64_t c = 4096; c < n && q > 20; c <<= 1) --q;
return q;
}
/* floor(2^qbits * e^(v - top)) for a live candidate (v <= top, both finite): the FP32 exponential
* of Cephes' expf (argument reduction by n ln 2 in two parts, a degree-5 polynomial in the reduced
* argument), taken as a 24-bit mantissa and shifted. Zero below 2^-41 of the top. Basic IEEE FP32
* operations and integer shifts only. */
RAD_TRAV_STRICT static inline RAD_RRS_HD uint64_t rad_mtp_trav_mass(float v, float top, int qbits) {
#if defined(__clang__)
#pragma clang fp contract(off)
#endif
const float x = v - top;
if (!(x > -28.5f)) return 0;
const int n = (int)(x * 1.44269504088896341f - 0.5f); /* round(x / ln 2), x <= 0 */
const float fn = (float)n;
float r = x - fn * 0.693359375f;
r = r - fn * -2.12194440e-4f;
const float z = r * r;
float y = 1.9875691500e-4f;
y = y * r + 1.3981999507e-3f;
y = y * r + 8.3334519073e-3f;
y = y * r + 4.1665795894e-2f;
y = y * r + 1.6666665459e-1f;
y = y * r + 5.0000001201e-1f;
y = y * z + r;
y = y + 1.0f; /* e^r, in [0.70, 1.42] */
const uint32_t mant = (uint32_t)(y * 8388608.0f); /* y * 2^23, below 2^24 */
const int sh = qbits + n - 23;
if (sh >= 0) return (uint64_t)mant << sh;
return sh > -32 ? (uint64_t)(mant >> -sh) : 0;
}
/* An integer below 2^53 as a double, exactly, the same way on host and device. */
static inline RAD_RRS_HD double rad_mtp_trav_u2d(uint64_t x) {
return (double)(uint32_t)(x >> 32) * 4294967296.0 + (double)(uint32_t)x;
}
/* The integer part of a double in [0, 2^53). */
static inline RAD_RRS_HD uint64_t rad_mtp_trav_d2u(double d) {
const uint32_t hi = (uint32_t)(d * (1.0 / 4294967296.0));
const double lo = d - (double)hi * 4294967296.0;
return ((uint64_t)hi << 32) + (uint64_t)(uint32_t)lo;
}
/* Candidate id's slot in a node's support (the first match), or cnt when it is outside. */
static inline RAD_RRS_HD int rad_mtp_trav_slot(const int32_t* sid, int cnt, int32_t id) {
int k = 0;
while (k < cnt && id != sid[k]) ++k;
return k;
}
/* A row's validity and largest value, as rad_mtp_couple_decide scans them: false for an id past the
* vocabulary, a NaN or +inf among the ids >= 0, or no finite value at all. */
static inline RAD_RRS_HD bool rad_mtp_trav_row_top(const int32_t* ids, const float* val, int64_t n,
int64_t vocab, float* top_out) {
float top = -INFINITY;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0) continue;
if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false;
if (val[j] > top) top = val[j];
}
*top_out = top;
return top != -INFINITY;
}
/* One row's target law over a node's support `sid[0 .. cnt)`: the masses on the support slots
* (duplicate candidates aggregated at the first matching slot), off it, and the total. The serial
* definition; a workgroup adds the same integers in its own order. */
struct RadTravLaw {
uint64_t pq[8];
uint64_t off, sum;
};
static inline RAD_RRS_HD void rad_mtp_trav_row_law(const int32_t* ids, const float* val, int64_t n,
float top, const int32_t* sid, int cnt,
RadTravLaw* o) {
const int qb = rad_mtp_trav_qbits(n);
for (int k = 0; k < 8; ++k) o->pq[k] = 0;
o->off = 0; o->sum = 0;
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
const uint64_t m = rad_mtp_trav_mass(val[j], top, qb);
o->sum += m;
const int k = rad_mtp_trav_slot(sid, cnt, ids[j]);
if (k < cnt) o->pq[k] += m; else o->off += m;
}
}
/* The off-support candidate that holds unit `t` of the off-support mass, candidates in ascending
* slot order (t < the row's off-support mass). -1 when there is none. */
static inline RAD_RRS_HD int32_t rad_mtp_trav_off_token(const int32_t* ids, const float* val,
int64_t n, float top, const int32_t* sid,
int cnt, uint64_t t) {
const int qb = rad_mtp_trav_qbits(n);
for (int64_t j = 0; j < n; ++j) {
if (ids[j] < 0 || val[j] == -INFINITY) continue;
if (rad_mtp_trav_slot(sid, cnt, ids[j]) < cnt) continue;
const uint64_t m = rad_mtp_trav_mass(val[j], top, qb);
if (t < m) return ids[j];
t -= m;
}
return -1;
}
/* ---------------------------------------------------------------- the prepared tree */
/* The eight-wide FP64 sums of the walk, as one fixed tree: the xor-4, xor-2, xor-1 butterfly of
* eight lanes (IEEE addition is commutative, so every lane of the butterfly ends with these bits). */
static inline RAD_RRS_HD double rad_mtp_trav_sum8(const double* v) {
return ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7]));
}
/* A node's draft side in the walk's canonical order: the children first, in draft order (a chain's
* one child is x). `nk` the children the walk may try, `nt` -1 for Gumbel-top-k siblings, else the
* number of deterministic top-q children of a RheoSampling node (its tail child is slot nt, `tail`
* whether the node carries it), `swap` the stored slot that changed places with slot 0 (a chain row
* whose x was not first; else 0).
* False when the state names no child (unreachable for a rad_mtp_couple_state_valid state). */
static inline RAD_RRS_HD bool rad_mtp_trav_canon(const RadMtpCoupleState& s, int ctl, int32_t* ids,
double* q, int* nk, int* nt, int* tail, int* swap) {
/* Every index below is a constant: a device lane keeps the state and the result in registers. */
*swap = 0;
*tail = 0;
if (s.scheme > 0 && ctl != 4) {
for (int k = 0; k < 8; ++k) {
ids[k] = k < s.count ? s.ids[k] : -1;
q[k] = k < s.count ? s.q[k] : 0.0;
}
const int m = s.scheme - 1;
const int t = m < s.count ? m : s.count;
const int cap = t + (s.count > t ? 1 : 0);
*nt = t;
*nk = s.nkids < cap ? (s.nkids > 0 ? s.nkids : 0) : cap;
*tail = *nk > t;
return true;
}
*nt = -1;
*nk = s.nkids >= 2 ? (s.nkids < s.count ? s.nkids : s.count) : 1;
/* a chain row: x to the front (the first slot that holds it changes places with slot 0) */
int kx = 0;
if (s.nkids < 2) {
kx = 8;
for (int k = 7; k >= 0; --k)
if (k < s.count && s.ids[k] == s.x) kx = k;
}
const bool found = kx < 8;
int32_t idx = -1;
double qx = 0.0;
for (int k = 0; k < 8; ++k) {
idx = k == kx ? s.ids[k] : idx;
qx = k == kx ? s.q[k] : qx;
}
for (int k = 0; k < 8; ++k) {
const bool in = found && k < s.count;
const int32_t idk = k == 0 ? idx : (k == kx ? s.ids[0] : s.ids[k]);
const double qk = k == 0 ? qx : (k == kx ? s.q[0] : s.q[k]);
ids[k] = in ? idk : -1;
q[k] = in ? qk : 0.0;
}
*swap = found ? kx : 0;
return found;
}
/* One request's tree as the walk reads it, node-indexed (node 0 the root, parents before
* children). Plain data: the device keeps it in LDS and fills it with a workgroup. */
struct RadTravTree {
int n; /* nodes */
int ok[RAD_MTP_TRAV_MAX_ROWS]; /* an eligible state with a valid target law */
int nk[RAD_MTP_TRAV_MAX_ROWS]; /* children the walk tries */
int nt[RAD_MTP_TRAV_MAX_ROWS]; /* -1 Gumbel; else a rheo node's deterministic children */
int tail[RAD_MTP_TRAV_MAX_ROWS]; /* a rheo node that carries its sampled tail child */
int ci[RAD_MTP_TRAV_MAX_ROWS]; /* children tried so far */
int child[RAD_MTP_TRAV_MAX_ROWS][8]; /* slot k's child node, or -1 */
int32_t ids[RAD_MTP_TRAV_MAX_ROWS][8]; /* the support, canonical order, -1 past it */
double qr[RAD_MTP_TRAV_MAX_ROWS][8]; /* the draft law (Gumbel: tried children zeroed) */
double m[RAD_MTP_TRAV_MAX_ROWS][8]; /* rate * residual on the support slots (the target's
law itself until the node is entered) */
double moff[RAD_MTP_TRAV_MAX_ROWS]; /* the same off the support, in all */
double sc[RAD_MTP_TRAV_MAX_ROWS]; /* the factor m and moff still owe: the node's rate from
its entry to its first rejected child, then 1 */
double p[RAD_MTP_TRAV_MAX_ROWS]; /* the node's acceptance rate */
uint64_t off[RAD_MTP_TRAV_MAX_ROWS]; /* the off-support mass in units (the final draw) */
float top[RAD_MTP_TRAV_MAX_ROWS]; /* the row's largest value */
int stack[RAD_MTP_TRAV_MAX_DEPTH + 1];
};
/* Node v's laws from its canonical draft side and its row's integer law (`valid`: the row scanned
* clean and its total is positive). */
static inline RAD_RRS_HD void rad_mtp_trav_set_law(RadTravTree* t, int v, bool valid, float top,
const RadTravLaw& w) {
const bool ok = valid && w.sum > 0;
const double sum = ok ? rad_mtp_trav_u2d(w.sum) : 1.0;
for (int k = 0; k < 8; ++k) t->m[v][k] = ok ? rad_mtp_trav_u2d(w.pq[k]) / sum : 0.0;
t->moff[v] = ok ? rad_mtp_trav_u2d(w.off) / sum : 0.0;
t->off[v] = ok ? w.off : 0;
t->top[v] = top;
t->ci[v] = 0;
t->ok[v] = ok;
}
/* The slot of node v's j-th tried child. Gumbel: the draft order. Rheo: the sampled tail child
* first (when the node carries it), then the deterministic ones. */
static inline RAD_RRS_HD int rad_mtp_trav_try_slot(const RadTravTree& t, int v, int j) {
const int nt = t.nt[v];
if (nt < 0) return j;
return t.tail[v] ? (j == 0 ? nt : j - 1) : j;
}
/* The law node v's j-th tried child was drawn from, at support slot k. `isq` is the reciprocal of
* rad_mtp_trav_try_norm: the sum of the node's remaining draft law (Gumbel) or of its tail's (rheo). */
static inline RAD_RRS_HD double rad_mtp_trav_try_norm(const RadTravTree& t, int v) {
const int nt = t.nt[v];
if (nt < 0) return rad_mtp_trav_sum8(t.qr[v]);
double tail[8];
for (int k = 0; k < 8; ++k) tail[k] = k >= nt ? t.qr[v][k] : 0.0;
return rad_mtp_trav_sum8(tail);
}
static inline RAD_RRS_HD double rad_mtp_trav_try_q(const RadTravTree& t, int v, int j, double isq,
int k) {
const int nt = t.nt[v];
if (nt < 0) return t.qr[v][k] * isq;
const int slot = rad_mtp_trav_try_slot(t, v, j);
if (slot != nt) return k == slot ? 1.0 : 0.0; /* a deterministic child: a point mass */
if (k < nt) return 0.0;
const double q = nt == 0 ? t.qr[v][k] : t.qr[v][k] * isq;
return q > 1.0 ? 1.0 : q; /* clamp: rounding must not push a one-token tail past 1 */
}
/* m / q for node v's j-th tried child at its own slot i, m the child's mass in the node's law: the
* child's rate before the cap, in one division (m * sq / qr rather than m / (qr / sq)). Negative
* when the law has no mass there (the child is not tried). */
static inline RAD_RRS_HD double rad_mtp_trav_try_ratio(const RadTravTree& t, int v, int j, int i,
double m) {
const int nt = t.nt[v];
const double q = t.qr[v][i];
if (nt >= 0 && i != nt) return m; /* a point mass */
if (!(q > 0)) return -1.0;
if (nt == 0) return q < 1.0 ? m / q : m;
const double sq = rad_mtp_trav_try_norm(t, v);
return q < sq ? m * sq / q : m; /* the law's value is at most 1 */
}
/* The walk over a prepared tree: the accepted path into path[0 .. *n_path). Returns false when
* nothing was decided (an invalid root state: every row keeps the pick). `pos0` is the root row's
* output position, the coordinate of the acceptance uniforms. Updates the tree in place: the last
* node's m / moff are its residual law (up to the node's factor sc), which
* rad_mtp_trav_final_pick reads. */
static inline RAD_RRS_HD bool rad_mtp_trav_walk_tree(RadTravTree& t, uint64_t seed, uint64_t pos0,
int* path, int* n_path,
const RadMtpTravOpt& opt = RadMtpTravOpt{}) {
int top = 0, tests = 0;
t.stack[0] = 0;
t.p[0] = 1.0;
t.sc[0] = 1.0; /* the root's m is the target's law itself */
*n_path = 0;
if (!t.ok[0]) return false;
for (;;) {
const int v = t.stack[top];
if (t.ok[v] && t.ci[v] < t.nk[v]) {
const int j = t.ci[v];
const int i = rad_mtp_trav_try_slot(t, v, j);
/* p_c = min(1, p_v r(c) / qn(c)); control 1 drops p_v (token-level ratios) */
const double f = opt.ctl == 1 ? (t.p[v] > 0 ? t.sc[v] / t.p[v] : 0.0) : t.sc[v];
const double ratio = rad_mtp_trav_try_ratio(t, v, j, i, f * t.m[v][i]);
const int c = top < RAD_MTP_TRAV_MAX_DEPTH && ratio >= 0 ? t.child[v][i] : -1;
if (c < 0) { t.nk[v] = j; continue; } /* a child the verify no longer carries: cut here */
const double pc = ratio < 1.0 ? ratio : 1.0;
t.p[c] = pc;
t.sc[c] = pc; /* the child's law becomes rate * law, when it is first needed */
t.stack[++top] = c;
continue;
}
/* a leaf: the sequence-level test */
++tests;
bool accept;
if (opt.accept_at >= 0) {
if (opt.p_test && tests <= opt.max_tests) opt.p_test[tests - 1] = t.p[v];
if (opt.n_tests) *opt.n_tests = tests;
accept = tests == opt.accept_at;
} else {
const double u = rad_spechub_uniform(
seed, pos0, RAD_MTP_TRAV_KEY ^ rad_mtp_rrs_mix((uint64_t)tests));
accept = u < t.p[v];
}
if (accept) {
*n_path = top + 1;
for (int i = 0; i <= top; ++i) path[i] = t.stack[i];
return true;
}
if (top == 0) return false; /* the root always accepts (p = 1); only roundoff gets here */
--top;
const int g = t.stack[top];
const int j = t.ci[g];
const double isq = 1.0 / rad_mtp_trav_try_norm(t, g);
const double pold = t.p[g], sc = t.sc[g];
double d[8];
for (int k = 0; k < 8; ++k) {
const double x = sc * t.m[g][k] - rad_mtp_trav_try_q(t, g, j, isq, k);
d[k] = x > 0 ? x : 0;
}
const double moff = sc * t.moff[g];
const double S = moff + rad_mtp_trav_sum8(d);
if (!(S > 0) || !rad_spechub_finite(S)) {
/* nothing of the target is left above the draft: this node cannot accept, nor a child of it */
t.p[g] = 0;
t.sc[g] = 0;
} else {
const double den = opt.ctl == 2 ? S : S + 1.0 - pold;
const double inv = 1.0 / den;
const double pn = S * inv;
t.p[g] = pn < 1.0 ? pn : 1.0; /* a rate is at most 1: rounding may not push it past */
for (int k = 0; k < 8; ++k) t.m[g][k] = d[k] * inv;
t.moff[g] = moff * inv;
t.sc[g] = 1.0;
}
/* Gumbel siblings are drawn WITHOUT replacement: the remaining Q renormalises */
if (t.nt[g] < 0 && opt.ctl != 3) t.qr[g][j] = 0;
++t.ci[g];
}
}
/* The final token of node v's residual law (in proportion to m on the support slots and moff off it:
* the node's factor sc is common to both and cancels), by the uniform
* u: the support slots first, in the canonical order, then the off-support candidates in slot
* order. kind 0: no token (the row keeps the pick); 1: the token of support slot `slot`; 2: the
* off-support candidate holding unit `t` of the row's off-support mass (rad_mtp_trav_off_token). */
struct RadTravPick {
int kind, slot;
uint64_t t;
};
static inline RAD_RRS_HD RadTravPick rad_mtp_trav_final_pick(const RadTravTree& t, int v, double u) {
RadTravPick o;
o.kind = 0; o.slot = -1; o.t = 0;
const double woff = t.moff[v];
const double total = rad_mtp_trav_sum8(t.m[v]) + woff;
if (!(total > 0) || !rad_spechub_finite(total)) return o;
double c = u * total;
int last = -1;
for (int k = 0; k < 8; ++k) {
const double m = t.m[v][k];
if (m > 0) {
last = k;
c -= m;
if (c < 0) { o.kind = 1; o.slot = k; return o; }
}
}
const uint64_t off = t.off[v];
if (woff > 0 && off > 0) {
const double frac = c / woff;
uint64_t tt = frac < 1.0 ? rad_mtp_trav_d2u(frac * rad_mtp_trav_u2d(off)) : off - 1;
if (tt >= off) tt = off - 1;
o.kind = 2; o.t = tt;
return o;
}
if (last >= 0) { o.kind = 1; o.slot = last; }
return o;
}
/* ---------------------------------------------------------------- a tree behind an interface
*
* The tree the walk reads (a Tree type provides):
* const RadMtpCoupleState* state(int v) the node's bound state, or null (node is a leaf)
* bool cand(int v, const int32_t** ids, const float** val, int64_t* n) target candidates
* int child(int v, int32_t token) the node's first child row with that token, or -1
* int64_t vocab()
* rad_mtp_trav_walk prepares the nodes the walk can reach (in discovery order, at most
* RAD_MTP_TRAV_MAX_ROWS), walks and draws the final token: the host reference and the tests. */
template <class Tree>
static inline bool rad_mtp_trav_walk(const Tree& T, int root, uint64_t seed, uint64_t pos0,
RadMtpTravOut* out, RadMtpTravOpt opt = RadMtpTravOpt{},
RadTravTree* keep = nullptr, int* ids_out = nullptr) {
RadTravTree local;
RadTravTree& t = keep ? *keep : local;
int id[RAD_MTP_TRAV_MAX_ROWS]; /* node -> the tree's own id */
struct Row { const int32_t* ids; const float* val; int64_t n; };
Row rows[RAD_MTP_TRAV_MAX_ROWS];
t.n = 1;
id[0] = root;
for (int a = 0; a < t.n; ++a) {
const int v = id[a];
t.ok[a] = 0; t.nk[a] = 0; t.nt[a] = -1; t.tail[a] = 0; t.ci[a] = 0;
t.moff[a] = 0; t.sc[a] = 1.0; t.p[a] = 0; t.off[a] = 0; t.top[a] = -INFINITY;
for (int k = 0; k < 8; ++k) { t.child[a][k] = -1; t.ids[a][k] = -1; t.qr[a][k] = 0; t.m[a][k] = 0; }
rows[a] = Row{ nullptr, nullptr, 0 };
const RadMtpCoupleState* sp = T.state(v);
if (!sp) continue;
int swap = 0;
if (!rad_mtp_trav_canon(*sp, opt.ctl, t.ids[a], t.qr[a], &t.nk[a], &t.nt[a], &t.tail[a], &swap)) continue;
const int32_t* ids = nullptr; const float* val = nullptr;
int64_t n = 0;
if (!T.cand(v, &ids, &val, &n)) continue;
rows[a] = Row{ ids, val, n };
float top = -INFINITY;
RadTravLaw w{};
const bool valid = rad_mtp_trav_row_top(ids, val, n, T.vocab(), &top);
if (valid) rad_mtp_trav_row_law(ids, val, n, top, t.ids[a], sp->count, &w);
rad_mtp_trav_set_law(&t, a, valid, top, w);
if (!t.ok[a]) continue;
for (int k = 0; k < t.nk[a]; ++k) {
const int c = T.child(v, t.ids[a][k]);
if (c < 0 || t.n >= RAD_MTP_TRAV_MAX_ROWS) continue;
t.child[a][k] = t.n;
id[t.n++] = c;
}
}
int path[RAD_MTP_TRAV_MAX_DEPTH + 1], np = 0;
if (ids_out) for (int a = 0; a < t.n; ++a) ids_out[a] = id[a];
if (!rad_mtp_trav_walk_tree(t, seed, pos0, path, &np, opt)) return false;
out->n = np;
for (int i = 0; i < np; ++i) out->node[i] = id[path[i]];
out->has_y = false;
const int f = path[np - 1];
if (t.ok[f]) {
const double ur = opt.u_final >= 0 ? opt.u_final
: rad_spechub_uniform(seed, pos0 + (uint64_t)(np - 1), RAD_SAMPLE_KEY_RESID);
const RadTravPick pk = rad_mtp_trav_final_pick(t, f, ur);
if (pk.kind == 1) { out->y = t.ids[f][pk.slot]; out->has_y = true; }
if (pk.kind == 2) {
int cnt = 0;
while (cnt < 8 && t.ids[f][cnt] >= 0) ++cnt;
out->y = rad_mtp_trav_off_token(rows[f].ids, rows[f].val, rows[f].n, t.top[f], t.ids[f], cnt, pk.t);
out->has_y = out->y >= 0;
}
}
return true;
}
#endif /* __cplusplus */
#endif /* RAD_MTP_TRAVERSAL_H */
+55
View File
@@ -0,0 +1,55 @@
/* rad_prefill_split.h -- host-pure live-KV prefill split law shared by libr4d launchers and
* architecture pass-key callbacks. Keep this independent of HIP so callbacks can run before tape
* lookup without a device copy or launch.
*/
#pragma once
#include <algorithm>
#include <cstdint>
/* `bq` query positions per workgroup, `tile` keys per KV tile. `units` counts the workgroups that
* do work: a ragged batch's grid is sized from its longest sequence, but a shorter sequence's
* tiles past its end exit at once. Each split keeps at least eight tiles of the supplied context.
*/
static inline int rad_prefill_splits_law(int bq, int tile, int q_len, int total_q, int num_seqs,
int kv_heads, int max_ctx, int wgps) {
const long n = std::max(1, num_seqs);
const long qt = std::min(n * ((std::max(1, q_len) + bq - 1) / bq),
(std::max(1, total_q) + (long)(bq - 1) * n) / bq);
const long units = (long)std::max(1, kv_heads) * std::max(1L, qt);
if (units >= wgps) return 1;
const int s1 = (int)(wgps / units), s2 = (int)(2L * wgps / units);
int sp = s2 > 2 * s1 ? s2 : s1;
const int cap = ((max_ctx > 0 ? max_ctx : (1 << 30) - 1) + tile - 1) / tile / 8;
sp = std::min(sp, std::max(1, cap));
return std::max(1, std::min(sp, 64));
}
/* The launcher's live-context refinement of the initial model-bound law. */
static inline int rad_prefill_splits_for_live(int bq, int tile, int q_len, int total_q,
int num_seqs, int kv_heads, int max_ctx,
int used_ctx, int wgps) {
int splits = rad_prefill_splits_law(bq, tile, q_len, total_q, num_seqs, kv_heads, max_ctx,
wgps);
if (splits > 1 && used_ctx > 0 && (max_ctx <= 0 || used_ctx < max_ctx))
splits = rad_prefill_splits_law(bq, tile, q_len, total_q, num_seqs, kv_heads, used_ctx,
wgps);
return splits;
}
/* Fingerprint one actual launch tuple in packet-global sizes. Use this instead of the raw context
* so equal split grids share a recording key as live context advances. */
static inline uint64_t rad_prefill_grid_key(int q_len, int bq, int splits, int kv_heads,
int num_seqs, int threads) {
const uint64_t gx = (uint64_t)((std::max(1, q_len) + bq - 1) / bq) *
(uint64_t)std::max(1, splits) * (uint64_t)threads;
const uint64_t gy = (uint64_t)std::max(1, kv_heads);
const uint64_t gz = (uint64_t)std::max(1, num_seqs);
uint64_t h = 0x9e3779b97f4a7c15ull;
const uint64_t grid[3] = {gx, gy, gz};
for (uint64_t v : grid) {
h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
h *= 0xbf58476d1ce4e5b9ull;
}
return h | 1;
}
+88 -2
View File
@@ -68,8 +68,10 @@ typedef struct RadKVGroupBatch {
int64_t state_index_pitch;
int64_t block_size;
int64_t max_blocks;
/* Null unless this group streams (RadKVStream). Trailing and zero-defaulted. */
/* Null unless this group streams (RadKVStream). */
const RadKVStream* stream;
/* ABI 35: host mirror of seqused, retained through this batch for exact sliced-launch bounds. */
const int32_t* seqused_h;
} RadKVGroupBatch;
typedef struct RadBatch {
@@ -325,6 +327,42 @@ typedef struct RadBatch {
const int32_t* plugin_cu; /* [n_seq + 1] device */
const int32_t* plugin_words_h;
const int32_t* plugin_cu_h;
/* ---- appended in ABI 33 (the shape generator) */
/* A shape generator's pass (rad_declare_shape_generator; `gen` is one of its
* RAD_GEN_PASS_S*): its payload. Null on every other step. */
const struct RadShapeGenBatch* sgen_b;
/* ---- appended in ABI 34: host-side max seqused per entry of kv[], for an architecture's
* optional recorded-pass geometry key. Null when the batch has no host summary. */
const int32_t* kv_used_max_h;
/* ABI 35: host mirror of positions, for a one-sequence prefill op whose exact KV bound is the
* position immediately after its first query piece. Valid through the batch's issue pass. */
const int32_t* positions_h;
/* ---- appended in ABI 35 (runs read both ways) */
/* The runs of a trunk pass whose rows attend to each other both ways
* (RadEncoderDecl::bidirectional): a picture's or a video frame's placeholders inside one
* sequence's chunk. The pass attends them causally like every other row; the plugin attends a
* run's rows again without the causal bound, over the keys before `bidi_used` (the position
* after the run's last token), in place of that result. The scheduler ends no chunk inside such
* a run, so its keys are this pass's or, after a prefix hit, the cache's; a run longer than any
* step is cut where its chunk ends, and that chunk's rows see the run up to the cut.
*
* host: n_bidi and, per run, its first row in this pass, its rows and the index of its sequence
* in the per-sequence arrays; device: [n_bidi] the keys a run's rows see. 0 runs on every other
* pass. */
int64_t n_bidi;
const int32_t* bidi_row; /* host */
const int32_t* bidi_n; /* host */
const int32_t* bidi_seq; /* host */
const int32_t* bidi_used; /* device */
/* ---- appended in ABI 36 (a block drafter's anchor row) */
/* A block drafter's query pass (draft_pass 1): [n_seq] device, for each drafting sequence the
* row of its last committed position in the context pass just run, whose rows are the verify
* step's in order. -1 for a row the card did not position. A drafter that conditions on the
* context state at the anchor (LiLiCorr) gathers it there; the query rows themselves sit past
* that position. Null on every other pass. */
const int32_t* anchor_rows;
} RadBatch;
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
@@ -587,6 +625,9 @@ typedef struct RadAudioGenBatch {
const int32_t* ref_cu_h;
const int32_t* ref_frame;
const int32_t* ref_frame_h;
/* ABI 40: PROMPT branch boundaries on the host, [n_seq + 1], including unequal
* reference-direction branches. Same rows as RadBatch::cu_seqlens on device. */
const int32_t* prompt_cu_h;
} RadAudioGenBatch;
/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear
@@ -688,7 +729,8 @@ typedef struct RadVideoGenBatch {
/* VENCODE: f32 [enc_frames, enc_height, enc_width, 3] RGB in 0..255, the frames padded to
* whole clips by repeating the last (rad_arch_encode_geom's entry 23). AENCODE: f32
* [enc_channels, enc_n_samples], each channel padded with zeros to the hop (entry 0). Both:
* the pass's geometry as rad_arch_encode_geom gave it, i32 on the device, and the media's
* the pass's geometry as rad_arch_encode_geom gave it, i32 in pinned host memory also readable
* by device kernels (mixed-site encoders share it), and the media's
* kind (RAD_ENC_*, below) and its number within the kind from 1. */
const float* enc_pixels;
int32_t enc_frames, enc_height, enc_width;
@@ -712,6 +754,44 @@ typedef struct RadVideoGenBatch {
enum { RAD_SAMPLER_EULER = 0, RAD_SAMPLER_RES_MULTISTEP = 1 };
/* What a shape generator's pass carries beside the step batch's own fields (rad_builder.h,
* RadShapeGenDecl, describes the passes). Every pass is one request's, in lane `lane`:
*
* SCOND `n_tok` is the picture's patches, `patches` [n_tok, 3 enc_patch^2] f32.
* SSTEP `n_tok` is step_rows. The two branches' latents are entries 0 (the picture's) and 1
* (the unconditioned one) of the image generator's sampler ops (`randn_lanes`,
* `lane_gather`, `flow_euler`): `lat_cu` bounds them and the per-entry arrays are
* theirs, entry 0 guided against entry 1 (`pair` {1, -2}) at the request's scale.
* SLATENT `n_tok` is latent_rows; nothing of the pass's own.
* SQUERY `n_tok` is n_query, `query` [n_query, 3] f32: x, y, z a point, and `query_cu`
* {0, n_query}.
*
* `lanes` and `lat_cu` are staged on every pass; the latent's rows are lat_cu[0..1]. Every
* pointer is device memory. */
typedef struct RadShapeGenBatch {
int32_t lane;
/* ---- SCOND */
const float* patches;
/* ---- SSTEP: the step (from 0) of the request's `n_steps` evaluations, then the two
* entries' sampler operands, [2] each but `seed` [2, 2] (low word first) and `lat_cu` [3]. */
int32_t step, n_steps;
const float* sigma;
const float* sigma_next;
const float* cfg;
const int32_t* pair;
const int32_t* lanes;
const int32_t* flags; /* RAD_GEN_F_FIRST on entry 0 of the first step */
const uint32_t* seed;
const int32_t* lat_cu;
/* ---- SQUERY */
int64_t n_query;
const float* query;
const int32_t* query_cu;
} RadShapeGenBatch;
/* RadVideoGenBatch::enc_kind: the media an encode pass carries, numbered from 1 within a kind. A
* keyframe is 1 for the first frame and 2 for the last. */
enum {
@@ -860,7 +940,13 @@ int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGrou
int layer);
int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer);
int rad_rank(RadCtx* c);
/* The instance's slot, rad_build_slot() of the declare that built it: what a plugin indexes its
* per-instance state by. */
int rad_slot(RadCtx* c);
int rad_world_size(RadCtx* c);
/* Workgroups the current rank's card can run concurrently (HIP multiProcessorCount on RDNA;
* 32 on the host backend or when the backend has no positive count). */
int rad_ctx_wgp_count(RadCtx* c);
RadStream rad_stream(RadCtx* c);
/* The routing result for a MoE layer, resolved on device against the current residency table.
+22 -1
View File
@@ -37,7 +37,23 @@ typedef struct RadMtpCoupleState {
int32_t status, round, x, count;
int32_t ids[8];
double q[8];
/* The node drafted `nkids` children, sampled without replacement from q, and ids[0 .. nkids) are
* them in draft order (x == ids[0]; ids[nkids .. count) the rest of the support). nkids <= 1 is
* the linear chain's single draw, whose ids keep the shortlist's order, and what the serial
* MTP head writes (abi/rad_mtp_rrs.h states the siblings' law; the traversal walk of
* abi/rad_mtp_traversal.h reads it). Zero from every writer that is not a sibling draw. */
int32_t nkids;
/* The sibling scheme of those children: 0 = Gumbel-top-k without replacement (the only one a
* writer in this engine produces), m + 1 = RheoSampling's m deterministic top-q children plus one
* sampled from the tail law (abi/rad_mtp_rrs.h). Zero from every other writer. */
int32_t scheme;
/* --draft-verify block (abi/rad_mtp_block.h): the length g of the block this row's chain is
* verified as one (the rows 0 .. g-1 bound to rounds 1 .. g, staged on every row of it); 0 for
* token-by-token verification. Written by the sampler's staging only; zero from the device. */
int32_t blk;
int32_t pad_;
} RadMtpCoupleState;
#define RAD_MTP_COUPLE_MAX_RHEO_M 7
#define RAD_MTP_COUPLE_DRAW_WORDS (sizeof(RadMtpCoupleDraw) / 4)
#define RAD_MTP_COUPLE_STATE_WORDS (sizeof(RadMtpCoupleState) / 4)
#define RAD_MTP_COUPLE_MAX_ROUNDS 8
@@ -46,7 +62,7 @@ typedef struct RadMtpCoupleState {
#define RAD_MTP_COUPLE_KEY_DRAFT 0x4d5450434f55504cull
#ifdef __cplusplus
static_assert(sizeof(RadMtpCoupleDraw) == 32, "MTP coupling draw wire");
static_assert(sizeof(RadMtpCoupleState) == 152, "MTP coupling state wire");
static_assert(sizeof(RadMtpCoupleState) == 168, "MTP coupling state wire");
static_assert(offsetof(RadMtpCoupleState, q) % 8 == 0, "MTP coupling q alignment");
#endif
@@ -101,6 +117,9 @@ static inline RAD_SPECHUB_HD bool rad_mtp_couple_state_valid(const RadMtpCoupleS
sum += s.q[i];
has_x |= s.ids[i] == s.x;
}
if (s.nkids < 0 || s.nkids > s.count || (s.nkids >= 2 && s.ids[0] != s.x)) return false;
if (s.scheme < 0 || s.scheme > RAD_MTP_COUPLE_MAX_RHEO_M + 1 || (s.scheme && s.nkids >= 1 && s.ids[0] != s.x))
return false;
return has_x && (sum - 1) <= 1e-12 && (1 - sum) <= 1e-12;
}
@@ -327,6 +346,8 @@ static inline RAD_SPECHUB_HD int32_t rad_dflash_couple_step(const float* sc, con
s->pos = 0;
s->round = round;
s->count = 0;
s->nkids = 0; /* a walk's position is one draw: the chain's wire */
s->scheme = 0;
for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; }
if (d.mode != 1) {
s->status = 0;
+7 -4
View File
@@ -184,7 +184,7 @@ struct Model {
std::string mul, add;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype,
std::initializer_list<int64_t> shape, int access, int group) {
@@ -978,8 +978,9 @@ static int find_prefix(RadBuilder* b, Model& m, const char** marker) {
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];
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(check_format(meta, ctx));
@@ -1335,7 +1336,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
if (!batch->gen || !batch->gen_b) {
rad_step_fail(c, "anima is an image generator and runs generator passes only");
return;
@@ -1361,6 +1362,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(anima)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(anima, "anima", "", "0.1.0",
"Anima (Base, Aesthetic, Turbo): Qwen3-0.6B through the LLM adapter, Cosmos-Predict2's "
"2B diffusion transformer and the Qwen-Image VAE; bf16 or block-fp8 linears")
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/bailing_hybrid -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(bailing_hybrid LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(bailing_hybrid architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid.cpp)
File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/bailing_hybrid_gguf -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(bailing_hybrid_gguf LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(bailing_hybrid_gguf architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf.cpp)
@@ -0,0 +1,12 @@
/* bailing_hybrid_gguf -- the GGUF variant of bailing_hybrid for the tiny family's IQ4_NL release: the same
* declaration and step, claiming the ftype-25 descriptor so the quantised GGUF converts
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
* namespace, the plugin name and the quant redefined. */
#define bailing_hybrid bailing_hybrid_gguf
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf"
#define BAILING_HYBRID_QUANT "gguf_ftype_25"
#include "../bailing_hybrid/bailing_hybrid.cpp"
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
RAD_ARCH_SERVES_IMPORTS(0)
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/bailing_hybrid_gguf_q4km -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(bailing_hybrid_gguf_q4km LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(bailing_hybrid_gguf_q4km architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q4km.cpp)
@@ -0,0 +1,12 @@
/* bailing_hybrid_gguf_q4km -- the GGUF variant of bailing_hybrid for the tiny family's Q4_K_M release: the same
* declaration and step, claiming the ftype-15 descriptor so the quantised GGUF converts
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
* namespace, the plugin name and the quant redefined. */
#define bailing_hybrid bailing_hybrid_gguf_q4km
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q4km"
#define BAILING_HYBRID_QUANT "gguf_ftype_15"
#include "../bailing_hybrid/bailing_hybrid.cpp"
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
RAD_ARCH_SERVES_IMPORTS(0)
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/bailing_hybrid_gguf_q5km -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(bailing_hybrid_gguf_q5km LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(bailing_hybrid_gguf_q5km architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q5km.cpp)
@@ -0,0 +1,12 @@
/* bailing_hybrid_gguf_q5km -- the GGUF variant of bailing_hybrid for the tiny family's Q5_K_M release: the same
* declaration and step, claiming the ftype-17 descriptor so the quantised GGUF converts
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
* namespace, the plugin name and the quant redefined. */
#define bailing_hybrid bailing_hybrid_gguf_q5km
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q5km"
#define BAILING_HYBRID_QUANT "gguf_ftype_17"
#include "../bailing_hybrid/bailing_hybrid.cpp"
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
RAD_ARCH_SERVES_IMPORTS(0)
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/bailing_hybrid_gguf_q6k -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(bailing_hybrid_gguf_q6k LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(bailing_hybrid_gguf_q6k architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q6k.cpp)
@@ -0,0 +1,12 @@
/* bailing_hybrid_gguf_q6k -- the GGUF variant of bailing_hybrid for the tiny family's Q6_K release: the same
* declaration and step, claiming the ftype-18 descriptor so the quantised GGUF converts
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
* namespace, the plugin name and the quant redefined. */
#define bailing_hybrid bailing_hybrid_gguf_q6k
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q6k"
#define BAILING_HYBRID_QUANT "gguf_ftype_18"
#include "../bailing_hybrid/bailing_hybrid.cpp"
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
RAD_ARCH_SERVES_IMPORTS(0)
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/bailing_hybrid_gguf_q80 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(bailing_hybrid_gguf_q80 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(bailing_hybrid_gguf_q80 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q80.cpp)
@@ -0,0 +1,12 @@
/* bailing_hybrid_gguf_q80 -- the GGUF variant of bailing_hybrid for the tiny family's Q8_0 release: the same
* declaration and step, claiming the ftype-7 descriptor so the quantised GGUF converts
* and serves. As in hyv3_gguf, a thin include over the family's implementation with the
* namespace, the plugin name and the quant redefined. */
#define bailing_hybrid bailing_hybrid_gguf_q80
#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q80"
#define BAILING_HYBRID_QUANT "gguf_ftype_7"
#include "../bailing_hybrid/bailing_hybrid.cpp"
/* GGUF file_type names the quant, never an imported tool descriptor: imports stay
* with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */
RAD_ARCH_SERVES_IMPORTS(0)
+145 -34
View File
@@ -1,8 +1,9 @@
/* breeze -- Breeze-TTS-2: speech from text, with an optional description of the voice; 24 kHz mono.
/* breeze -- Breeze-TTS-2: speech from text, voice design or a reference recording; 24 kHz mono.
*
* ============================== THE MODEL ==============================
*
* Four networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer):
* Four generation networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer),
* plus the reference-audio encoder in reference.h for voice cloning:
*
* Text encoder: T5Gemma 2's text encoder, Gemma 3 1B's shape (26 layers of 1152, 4 query heads
* over one KV head of 256, gelu-tanh GLU 6912, sandwich RMS norms with a (1 + w) gain), read
@@ -85,6 +86,8 @@ constexpr int64_t kVocChunk = 4, kConvCtx = 12, kAttnWin = 72;
constexpr int64_t kVocContext = 2 + (kAttnWin - 1) + kConvCtx;
constexpr int64_t kConvFrames = kConvCtx + kVocChunk;
constexpr int64_t kCbBins = 2048, kCbDim = 256;
/* One clean reference of at most ten seconds (rounded to complete codec frames). */
constexpr int64_t kMaxRefFrames = 125, kMaxRefSamples = kMaxRefFrames * kSamplesPerFrame;
/* The codec's sequence rates, rows a frame: the transformer's frames, the convolutions' frames,
* the two upsamplings', and each decoder block's output (8, 5, 4, 3 times). */
constexpr int kRates = 8;
@@ -160,7 +163,34 @@ struct Llama3 {
double factor = 0, low = 0, high = 0, orig = 0;
};
struct RefConv {
rad_weight w = 0, b = 0;
rad_op op = 0;
};
struct RefLayer {
rad_weight n1 = 0, b1 = 0, n2 = 0, b2 = 0, qkv = 0, o = 0, fc1 = 0, fc2 = 0;
rad_weight ls1 = 0, ls2 = 0;
rad_op norm1 = 0, norm2 = 0, proj = 0, rope = 0, attn = 0, out = 0;
rad_op f1 = 0, act = 0, f2 = 0, scale1 = 0, scale2 = 0, add1 = 0, add2 = 0;
};
struct Reference {
RefConv first{}, res1[4]{}, res2[4]{}, down[4]{}, last{}, sample{};
rad_buf x[5]{}, a[5]{}, h[4]{}, z = 0, pad = 0, sampled = 0;
rad_op elu[5]{}, elu_h[4]{};
rad_buf th = 0, qkv = 0, attn = 0, o = 0, ff = 0, act = 0;
RefLayer layer[8]{};
rad_buf index = 0, cu = 0, text_pos = 0, text_cu = 0;
rad_op indices = 0, copy_i = 0, copy_f = 0, text_indices = 0;
rad_buf q[2]{}, codes = 0, eos_codes = 0;
rad_weight qi[2]{}, cb[16]{};
rad_op project[2]{}, quant[16]{}, embed = 0, eos = 0;
};
struct Model {
Reference ref{};
/* The model holds the reference encoder (reference_stored), whose first weight is then already
* in the name map. */
bool ref_stored = false;
Names nm{""};
Llama3 l3{};
Geom ge{}, gl{}, gd{}; /* the text encoder's, the backbone's, the depth decoder's */
@@ -225,7 +255,7 @@ struct Model {
rad_buf b_vout = 0, b_audio = 0;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* ================================================================== declare helpers */
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x,
@@ -1183,10 +1213,13 @@ static int check_format(const RadModelMeta* meta) {
return RAD_OK;
}
#include "reference.h"
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];
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(check_format(meta));
@@ -1213,6 +1246,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ARCH_TRY(declare_encoder(b, meta, m));
RAD_ARCH_TRY(declare_frame(b, meta, m));
RAD_ARCH_TRY(declare_codec(b, meta, m));
/* A container converted before the reference encoder was in the recipe holds the generator
* alone: it serves speech as before, and with no reference templates declared below the
* server refuses a request that brings references, saying the model clones no voice. */
m.ref_stored = reference_stored(b, m);
if (m.ref_stored) RAD_ARCH_TRY(declare_reference(b, meta, m));
if (!ctx->shape_probe) {
RadAudioGenDecl d{};
@@ -1220,6 +1258,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
d.tmpl = kTemplate;
d.tmpl_plain = kPlain;
d.neg_tmpl = kPlain;
d.branches = 2;
if (m.ref_stored) {
d.tmpl_ref = "{references}<bos>[S0]{input}";
d.tmpl_ref_instruct = "{references}<bos>[S0]<ins_bos>{instructions}<ins_eos>{input}";
d.neg_tmpl_ref = d.tmpl_ref;
d.ref_item = "<bos>[S0]{text}{audio}<|audio_eos|>";
d.ref_rate = kSampleRate;
d.ref_hop = kSamplesPerFrame;
d.ref_max_samples = kMaxRefSamples;
d.ref_max = 1;
}
d.prompt_whole = 1;
d.first_frame = 0;
d.max_prompt = kMaxPrompt;
@@ -1266,34 +1315,91 @@ static void step_backbone(RadCtx* c, const RadBatch* batch, const Model& m) {
m.b_h2, m.b_gu, m.b_ff, pos, cu, layer++);
}
static void step_text(RadCtx* c, const Model& m, int64_t T, RadOperand tokens,
RadOperand pos, RadOperand cu, RadOperand output) {
const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim;
/* The encoder over each branch's prompt, bidirectional within it; its projection is the
* backbone's input. */
RAD_ISSUE_N(c, m.op_eembed, T, tokens, RAD_W(m.w_etok),
brows(m.b_ex, T));
for (const EncLayer& L : m.enc) {
RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T));
RAD_ISSUE_N(c, L.op_qkv, T, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T));
RAD_ISSUE_N(c, L.op_qknr, T, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn));
RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T),
bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T));
RAD_ISSUE_N(c, L.op_o, T, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T));
RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T));
RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
RAD_ISSUE_N(c, L.op_n3, T, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T));
RAD_ISSUE_N(c, L.op_gu, T, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T));
RAD_ISSUE_N(c, L.op_act, T, brows(m.b_egu, T), brows(m.b_eff, T));
RAD_ISSUE_N(c, L.op_down, T, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T));
RAD_ISSUE_N(c, L.op_n4, T, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T));
RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
}
RAD_ISSUE_N(c, m.op_enorm, T, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T));
RAD_ISSUE_N(c, m.op_eproj, T, brows(m.b_eh, T), RAD_W(m.w_eproj), output);
}
/* rvq_embed reads codebook 0 from its first table and codebooks 1..15 from its
* second table, whose row zero must therefore be the start of codebook 1. */
static RadOperand residual_codebooks(const Model& m) {
RadOperand t = RAD_W(m.w_cb);
t.offset = (int64_t)kVocab * m.gl.n_embd;
t.rows = (int64_t)(kCodes - 1) * kVocab;
return t;
}
static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) {
const RadAudioGenBatch* A = batch->agen_b;
const int64_t T = batch->n_tok;
const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim;
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1);
const RadOperand pos = praw(batch->positions, RAD_I32, T);
/* The encoder over each branch's prompt, bidirectional within it; its projection is the
* backbone's input. */
RAD_ISSUE(c, m.op_eembed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_etok),
brows(m.b_ex, T));
for (const EncLayer& L : m.enc) {
RAD_ISSUE(c, L.op_n1, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T));
RAD_ISSUE(c, L.op_qkv, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T));
RAD_ISSUE(c, L.op_qknr, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn));
RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T),
bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T));
RAD_ISSUE(c, L.op_o, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T));
RAD_ISSUE(c, L.op_n2, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T));
RAD_ISSUE(c, L.op_add1, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
RAD_ISSUE(c, L.op_n3, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T));
RAD_ISSUE(c, L.op_gu, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T));
RAD_ISSUE(c, L.op_act, brows(m.b_egu, T), brows(m.b_eff, T));
RAD_ISSUE(c, L.op_down, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T));
RAD_ISSUE(c, L.op_n4, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T));
RAD_ISSUE(c, L.op_add2, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T));
if (A->n_ref) {
if (!A->prompt_cu_h || A->prompt_cu_h[0] != 0 ||
A->prompt_cu_h[batch->n_seq] != T) {
rad_step_fail(c, "breeze: reference prompt needs its host branch boundaries");
return;
}
step_reference(c, batch, m);
const Reference& E = m.ref;
RAD_ISSUE_N(c, E.text_indices, kMaxPrompt, brows(E.text_pos, kMaxPrompt));
RAD_ISSUE_N(c, E.eos, 16, brows(E.eos_codes, 16));
/* Each branch has two independent text-encoder segments around its audio. The
* backbone alone attends across the concatenation. Never encode audio placeholders
* or the audio EOS as text, and reset rotary positions for each text segment. */
for (int64_t branch = 0; branch < batch->n_seq; ++branch) {
const int64_t end = A->prompt_cu_h[branch + 1];
for (int64_t t = A->prompt_cu_h[branch]; t < end;) {
const int32_t f = A->ref_frame_h[t];
if (f >= 0) {
int64_t n = 1;
while (t + n < end && A->ref_frame_h[t + n] == f + n) ++n;
if (t + n >= end) {
rad_step_fail(c, "breeze: reference frames need their audio EOS row");
return;
}
RAD_ISSUE_N(c, E.embed, n, bcol(E.codes, f, n, 16), RAD_W(m.w_cb),
residual_codebooks(m), brow_slice(m.b_x, t, n, m.gl.n_embd));
t += n;
RAD_ISSUE_N(c, E.embed, 1, brows(E.eos_codes, 16), RAD_W(m.w_cb),
residual_codebooks(m), brow_slice(m.b_x, t, 1, m.gl.n_embd));
++t;
} else {
int64_t n = 1;
while (t + n < end && A->ref_frame_h[t + n] < 0) ++n;
ref_bounds(c, E, E.text_cu, n);
step_text(c, m, n, praw(batch->token_ids + t, RAD_I32, n),
brows(E.text_pos, n), brows(E.text_cu, 2),
brow_slice(m.b_x, t, n, m.gl.n_embd));
t += n;
}
}
}
} else {
step_text(c, m, T, praw(batch->token_ids, RAD_I32, T),
praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(m.b_x, T));
}
RAD_ISSUE(c, m.op_enorm, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T));
RAD_ISSUE(c, m.op_eproj, brows(m.b_eh, T), RAD_W(m.w_eproj), brows(m.b_x, T));
step_backbone(c, batch, m);
bool any_last = false;
for (int64_t i = 0; i < A->n_lane; ++i) any_last = any_last || A->last_h[i];
@@ -1357,10 +1463,8 @@ static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) {
/* 3. the frame into its lane's history, and the backbone over the frame's embedding */
RAD_ISSUE_N(c, m.op_store, n, brows(m.b_codes, kCodes), lanes, frame,
brows(m.b_status, m.lanes), brows(m.b_codes_all, m.lanes * kCodes));
RadOperand t1 = RAD_W(m.w_cb);
t1.offset = (int64_t)kVocab * D;
t1.rows = (int64_t)(kCodes - 1) * kVocab;
RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), t1, brows(m.b_x, S));
RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), residual_codebooks(m),
brows(m.b_x, S));
step_backbone(c, batch, m);
store_hidden(c, m, A, S, A->last_row, S);
}
@@ -1475,7 +1579,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
if (!batch->gen || !batch->agen_b) {
rad_step_fail(c, "breeze is an audio generator and runs generator passes only");
return;
@@ -1503,6 +1607,11 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
static int64_t text_prepare(int field, const char* in, char* out, int64_t cap) {
if (!in) return RAD_E_INVAL;
std::string r = in;
if (field == RAD_TEXT_REFERENCE) {
for (const char* marker : {"<bos>", "<eos>", "<|AUDIO|>", "<|audio_eos|>",
"<ins_bos>", "<ins_eos>"})
if (r.find(marker) != std::string::npos) return RAD_E_INVAL;
}
if (field == RAD_TEXT_INSTRUCTIONS) {
const size_t a = r.find_first_not_of(" \t\r\n"), z = r.find_last_not_of(" \t\r\n");
r = a == std::string::npos ? std::string() : r.substr(a, z - a + 1);
@@ -1521,6 +1630,8 @@ RAD_ARCH_PROBE(breeze)
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
return breeze::text_prepare(field, in, out, cap);
}
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(breeze, "breeze", "", "0.1.0",
"Breeze-TTS-2: a T5Gemma 2 text encoder over a Qwen3 backbone with a 16-codebook "
"depth decoder and the Qwen3-TTS 12 Hz codec; 24 kHz mono speech")
+281
View File
@@ -0,0 +1,281 @@
/* Breeze's Qwen3-TTS/Mimi reference encoder. Included inside namespace breeze after the
* ordinary networks. Kept in f32, as the released audio tokenizer encodes references. */
static rad_op ref_rows(RadBuilder* b, const char* op, int64_t rows, int64_t n,
std::initializer_list<rad_buf> in, std::initializer_list<rad_buf> out,
const char* dtype = "f32") {
return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_STR("dtype", dtype)), RAD_NOWEIGHTS), in, out);
}
static rad_op ref_gemm(RadBuilder* b, int64_t rows, int64_t n, int64_t k, rad_weight w,
rad_buf x, rad_buf y) {
return rw(b, RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n),
RAD_INT("K", k), RAD_STR("dtype", "f32")), RAD_WEIGHTS(w)), {x}, {y});
}
static int ref_conv(RadBuilder* b, Model& m, RefConv& C, const char* name, const char* src,
int64_t ci, int64_t co, int64_t k, int64_t st, int64_t rate, int64_t rows,
rad_buf x, rad_buf res, rad_buf y, bool bias = true) {
/* The first convolution's weight is mapped by reference_stored when that ran. */
C.w = (m.ref_stored && &C == &m.ref.first)
? decl_w(b, m.nm.f("ref.%s.weight", name), RAD_F32, {co, ci, k}, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(kGrpCodec + 1))
: wcopy(b, m.nm, m.nm.f("ref.%s.weight", name), m.nm.ckpt("%s.weight", src),
RAD_F32, {co, ci, k}, kGrpCodec + 1);
if (bias) C.b = wcopy(b, m.nm, m.nm.f("ref.%s.bias", name), m.nm.ckpt("%s.bias", src),
RAD_F32, {co}, kGrpCodec + 1);
const rad_weight weights[] = {C.w, C.b};
C.op = rw(b, RAD_OP(b, "conv1d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", ci),
RAD_INT("cout", co), RAD_INT("k", k), RAD_INT("dil", 1),
RAD_INT("causal", 1), RAD_INT("stride", st), RAD_INT("cu_div", rate),
RAD_STR("dtype", "f32")), weights, bias ? 2 : 1),
{x, m.ref.cu, res}, {y});
return C.w && (!bias || C.b) && C.op ? RAD_OK : RAD_E_INVAL;
}
/* Whether the model holds the reference encoder, asked of its first convolution through the name
* map entry declared here (the one ref_conv would declare). A builder with no model behind it
* answers no. */
static bool reference_stored(RadBuilder* b, Model& m) {
const std::string dn = m.nm.f("ref.first.weight");
if (map_copy(b, dn.c_str(),
m.nm.ckpt("%s.weight", "audio_tokenizer.encoder.encoder.layers.0.conv")) < 0)
return false;
RadEncoding enc{};
return weight_enc(b, dn.c_str(), &enc);
}
static int declare_reference(RadBuilder* b, const RadModelMeta* meta, Model& m) {
Reference& E = m.ref;
Names& nm = m.nm;
const char* ec = "audio_tokenizer.encoder_config";
if (rad_meta_geti(meta, nm.f("%s.hidden_size", ec), 0) != 512 ||
rad_meta_geti(meta, nm.f("%s.num_hidden_layers", ec), 0) != 8 ||
rad_meta_geti(meta, nm.f("%s.num_filters", ec), 0) != 64 ||
rad_meta_geti(meta, nm.f("%s.use_causal_conv", ec), 1) != 1 ||
rad_meta_geti(meta, nm.f("%s.use_conv_shortcut", ec), 0) != 0) {
fprintf(stderr, "radiance: breeze: reference encoder is not the released Qwen3-TTS encoder\n");
return RAD_E_UNSUPPORTED;
}
constexpr int64_t R = kMaxRefSamples / 960; /* SEANet's 25 Hz output */
constexpr int64_t NI = 2 * kMaxPrompt + 3;
E.index = decl_b(b, nm.f("ref.index"), RAD_I32, {NI}, RAD_BUF_PERSIST);
E.indices = iota_op(b, NI, 0, 1, E.index);
E.cu = decl_b(b, nm.f("ref.cu"), RAD_I32, {2}, RAD_BUF_PERSIST);
E.text_pos = decl_b(b, nm.f("ref.text_pos"), RAD_I32, {kMaxPrompt}, RAD_BUF_PERSIST);
E.text_cu = decl_b(b, nm.f("ref.text_cu"), RAD_I32, {2}, RAD_BUF_PERSIST);
E.text_indices = iota_op(b, kMaxPrompt, 0, 1, E.text_pos);
E.copy_i = rw(b, RAD_OP(b, "int_affine", RAD_PARAMS(RAD_INT("M", 1), RAD_STR("src", "0"),
RAD_STR("mul", "1"), RAD_STR("add", "0")), RAD_NOWEIGHTS),
{E.index}, {E.cu, E.text_cu});
E.copy_f = rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 512),
RAD_STR("from", "f32"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {}, {});
int64_t rows = kMaxRefSamples, ch = 64, rate = 1;
static const int64_t stride[] = {4, 5, 6, 8};
for (int i = 0; i < 5; ++i) {
E.x[i] = decl_b(b, nm.f("ref.x%d", i), RAD_F32, {rows, ch});
E.a[i] = decl_b(b, nm.f("ref.a%d", i), RAD_F32, {rows, ch});
E.elu[i] = ref_rows(b, "elu", rows, ch, {E.x[i]}, {E.a[i]});
if (i < 4) {
E.h[i] = decl_b(b, nm.f("ref.h%d", i), RAD_F32, {rows, ch / 2});
E.elu_h[i] = ref_rows(b, "elu", rows, ch / 2, {E.h[i]}, {E.h[i]});
rows /= stride[i]; ch *= 2;
}
}
RAD_ARCH_TRY(ref_conv(b, m, E.first, "first", "audio_tokenizer.encoder.encoder.layers.0.conv",
1, 64, 7, 1, 1, kMaxRefSamples, 0, 0, E.x[0]));
rows = kMaxRefSamples; ch = 64; rate = 1;
for (int i = 0; i < 4; ++i) {
const int li = 1 + 3 * i;
RAD_ARCH_TRY(ref_conv(b, m, E.res1[i], nm.f("res%d.1", i),
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.block.1.conv", li),
ch, ch / 2, 3, 1, rate, rows, E.a[i], 0, E.h[i]));
RAD_ARCH_TRY(ref_conv(b, m, E.res2[i], nm.f("res%d.2", i),
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.block.3.conv", li),
ch / 2, ch, 1, 1, rate, rows, E.h[i], E.x[i], E.x[i]));
RAD_ARCH_TRY(ref_conv(b, m, E.down[i], nm.f("down%d", i),
nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.conv", li + 2),
ch, 2 * ch, 2 * stride[i], stride[i], rate, rows,
E.a[i], 0, E.x[i + 1]));
rows /= stride[i]; rate *= stride[i]; ch *= 2;
}
E.z = decl_b(b, nm.f("ref.z"), RAD_F32, {R, 512});
RAD_ARCH_TRY(ref_conv(b, m, E.last, "last", "audio_tokenizer.encoder.encoder.layers.14.conv",
1024, 512, 3, 1, 960, R, E.a[4], 0, E.z));
E.th = decl_b(b, nm.f("ref.th"), RAD_F32, {R, 512});
E.qkv = decl_b(b, nm.f("ref.qkv"), RAD_F32, {R, 1536});
E.attn = decl_b(b, nm.f("ref.attn"), RAD_F32, {R, 512});
E.o = decl_b(b, nm.f("ref.o"), RAD_F32, {R, 512});
E.ff = decl_b(b, nm.f("ref.ff"), RAD_F32, {R, 2048});
E.act = decl_b(b, nm.f("ref.act"), RAD_F32, {R, 2048});
for (int i = 0; i < 8; ++i) {
RefLayer& L = E.layer[i];
auto w = [&](const char* dn, const char* sn, std::initializer_list<int64_t> sh) {
return wcopy(b, nm, nm.f("ref.t%d.%s", i, dn),
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.%s", i, sn),
RAD_F32, sh, kGrpCodec + 1);
};
L.n1 = w("n1", "input_layernorm.weight", {512});
L.b1 = w("b1", "input_layernorm.bias", {512});
L.n2 = w("n2", "post_attention_layernorm.weight", {512});
L.b2 = w("b2", "post_attention_layernorm.bias", {512});
L.ls1 = w("ls1", "self_attn_layer_scale.scale", {512});
L.ls2 = w("ls2", "mlp_layer_scale.scale", {512});
const char* qn = nm.f("ref.t%d.qkv", i);
RAD_ARCH_TRY(map_concat(b, qn, {
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.q_proj.weight", i),
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.k_proj.weight", i),
nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.v_proj.weight", i)}));
L.qkv = decl_w(b, qn, RAD_F32, {1536, 512}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(kGrpCodec + 1));
L.o = w("out", "self_attn.o_proj.weight", {512, 512});
L.fc1 = w("fc1", "mlp.fc1.weight", {2048, 512});
L.fc2 = w("fc2", "mlp.fc2.weight", {512, 2048});
auto ln = [&](rad_weight nw, rad_weight nb) {
return rw(b, RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 512),
RAD_F64("eps", 1e-5), RAD_STR("dtype", "f32")), RAD_WEIGHTS(nw, nb)),
{E.z}, {E.th});
};
L.norm1 = ln(L.n1, L.b1); L.norm2 = ln(L.n2, L.b2);
L.proj = ref_gemm(b, R, 1536, 512, L.qkv, E.th, E.qkv);
L.rope = rw(b, RAD_OP(b, "rope", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", 64),
RAD_INT("n_head", 8), RAD_INT("n_head_kv", 8), RAD_F64("theta", 10000),
RAD_F64("scale", 1), RAD_STR("mode", "neox")), RAD_NOWEIGHTS),
{E.qkv, E.index}, {E.qkv});
L.attn = rw(b, RAD_OP(b, "attn_dense", RAD_PARAMS(RAD_RANGE("M", 1, R),
RAD_INT("head_dim", 64), RAD_INT("gqa", 1), RAD_INT("causal", 1),
RAD_F64("scale", 0.125), RAD_INT("window", 250), RAD_INT("max_seqlen", R),
RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {E.qkv, E.cu}, {E.attn});
L.out = ref_gemm(b, R, 512, 512, L.o, E.attn, E.o);
L.f1 = ref_gemm(b, R, 2048, 512, L.fc1, E.th, E.ff);
L.act = ref_rows(b, "gelu", R, 2048, {E.ff}, {E.act});
L.f2 = ref_gemm(b, R, 512, 2048, L.fc2, E.act, E.o);
auto scale = [&](rad_weight sw) {
return rw(b, RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R),
RAD_INT("n", 512), RAD_STR("dtype", "f32")), RAD_WEIGHTS(sw)), {E.o}, {E.o});
};
L.scale1 = scale(L.ls1); L.scale2 = scale(L.ls2);
L.add1 = ref_rows(b, "add", R, 512, {E.z, E.o}, {E.z});
L.add2 = ref_rows(b, "add", R, 512, {E.z, E.o}, {E.z});
if (!L.n1 || !L.b1 || !L.n2 || !L.b2 || !L.qkv || !L.o || !L.fc1 || !L.fc2 ||
!L.ls1 || !L.ls2 || !L.norm1 || !L.norm2 || !L.proj || !L.rope || !L.attn ||
!L.out || !L.f1 || !L.act || !L.f2 || !L.scale1 || !L.scale2 || !L.add1 || !L.add2)
return RAD_E_INVAL;
}
/* The last downsample uses replicate padding. Prepending two copies of the first row,
* using the ordinary causal conv, then dropping its first output is exactly that pad. */
E.pad = decl_b(b, nm.f("ref.pad"), RAD_F32, {R + 2, 512});
E.sampled = decl_b(b, nm.f("ref.sampled"), RAD_F32, {kMaxRefFrames + 1, 512});
RAD_ARCH_TRY(rad_op_reads(b, E.copy_f, &E.z, 1));
RAD_ARCH_TRY(rad_op_writes(b, E.copy_f, &E.pad, 1));
RAD_ARCH_TRY(ref_conv(b, m, E.sample, "sample", "audio_tokenizer.encoder.downsample.conv",
512, 512, 4, 2, 1, R + 2, E.pad, 0, E.sampled, false));
E.codes = decl_b(b, nm.f("ref.codes"), RAD_I32, {16, kMaxRefFrames}, RAD_BUF_PERSIST);
E.eos_codes = decl_b(b, nm.f("ref.eos_codes"), RAD_I32, {16, 1}, RAD_BUF_PERSIST);
for (int part = 0; part < 2; ++part) {
const char* qs = part ? "acoustic_residual_vector_quantizer" : "semantic_residual_vector_quantizer";
E.q[part] = decl_b(b, nm.f("ref.q%d", part), RAD_F32, {kMaxRefFrames, 256});
E.qi[part] = wcopy(b, nm, nm.f("ref.q%d.in", part),
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.input_proj.weight", qs),
RAD_F32, {256, 512}, kGrpCodec + 1);
/* A 1x1 Conv1d weight's trailing singleton is immaterial to GEMM's matrix view. */
E.project[part] = ref_gemm(b, kMaxRefFrames, 256, 512, E.qi[part], E.sampled, E.q[part]);
const int first = part ? 1 : 0, count = part ? 15 : 1;
for (int j = 0; j < count; ++j) {
const int k = first + j;
const char* dn = nm.f("ref.cb%d", k);
RAD_ARCH_TRY(map_ema(b, dn,
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.layers.%d.codebook.embed_sum", qs, j),
nm.ckpt("audio_tokenizer.encoder.quantizer.%s.layers.%d.codebook.cluster_usage", qs, j)));
E.cb[k] = decl_w(b, dn, RAD_F32, {2048, 256}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(kGrpCodec + 1));
E.quant[k] = rw(b, RAD_OP(b, "vq_euclidean", RAD_PARAMS(RAD_RANGE("M", 1, kMaxRefFrames),
RAD_INT("n", 256), RAD_INT("bins", 2048), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(E.cb[k])), {E.q[part]}, {E.q[part], E.codes});
if (!E.cb[k] || !E.quant[k]) return RAD_E_INVAL;
}
if (!E.qi[part] || !E.project[part]) return RAD_E_INVAL;
}
E.embed = rw(b, RAD_OP(b, "rvq_embed", RAD_PARAMS(RAD_RANGE("M", 1, kMaxRefFrames),
RAD_INT("n_embd", m.gl.n_embd), RAD_INT("n_codes", 16), RAD_INT("vocab", kVocab),
RAD_INT("off0", 0), RAD_F64("scale", 1), RAD_INT("round", 1),
RAD_STR("dtype", "bf16")), RAD_WEIGHTS(m.w_cb, m.w_cb)), {E.codes}, {m.b_x});
E.eos = iota_op(b, 16, 0, 0, E.eos_codes);
RAD_ARCH_TRY(rad_op_reads(b, E.embed, &E.eos_codes, 1));
/* Both branches' text segments are encoded separately at position zero. These buffers must
* remain live through each segment's encoder, projection and the backbone prefill. */
for (const EncLayer& L : m.enc) {
RAD_ARCH_TRY(rad_op_reads(b, L.op_qknr, &E.text_pos, 1));
RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &E.text_cu, 1));
}
return E.indices && E.copy_i && E.copy_f && E.text_indices && E.embed && E.eos ? RAD_OK : RAD_E_INVAL;
}
/* Copy the endpoints of an iota into a two-entry cu, without a host upload or ABI change. */
static void ref_bounds(RadCtx* c, const Reference& E, rad_buf cu, int64_t len) {
RAD_ISSUE_N(c, E.copy_i, 1, brow_slice(E.index, 0, 1, 1), brow_slice(cu, 0, 1, 1));
RAD_ISSUE_N(c, E.copy_i, 1, brow_slice(E.index, len, 1, 1), brow_slice(cu, 1, 1, 1));
}
static void step_reference(RadCtx* c, const RadBatch* batch, const Model& m) {
const Reference& E = m.ref;
const auto* A = batch->agen_b;
const int64_t L = A->ref_samples, R = L / 960, F = R / 2;
RAD_ISSUE_N(c, E.indices, 2 * kMaxPrompt + 3, brows(E.index, 2 * kMaxPrompt + 3));
const RadOperand raw_cu = praw(A->ref_cu, RAD_I32, 2);
auto conv = [&](const RefConv& C, RadOperand x, RadOperand res, RadOperand y,
int64_t rows, RadOperand cu) {
RAD_ISSUE_N(c, C.op, rows, x, RAD_W(C.w), cu, res, y, C.b ? RAD_W(C.b) : RAD_NONE);
};
conv(E.first, praw(A->ref_audio, RAD_F32, L), RAD_NONE, brows(E.x[0], L), L, raw_cu);
static const int64_t stride[] = {4, 5, 6, 8};
int64_t rows = L;
for (int i = 0; i < 4; ++i) {
RAD_ISSUE_N(c, E.elu[i], rows, brows(E.x[i], rows), brows(E.a[i], rows));
conv(E.res1[i], brows(E.a[i], rows), RAD_NONE, brows(E.h[i], rows), rows, raw_cu);
RAD_ISSUE_N(c, E.elu_h[i], rows, brows(E.h[i], rows), brows(E.h[i], rows));
conv(E.res2[i], brows(E.h[i], rows), brows(E.x[i], rows), brows(E.x[i], rows), rows, raw_cu);
RAD_ISSUE_N(c, E.elu[i], rows, brows(E.x[i], rows), brows(E.a[i], rows));
conv(E.down[i], brows(E.a[i], rows), RAD_NONE, brows(E.x[i + 1], rows / stride[i]), rows, raw_cu);
rows /= stride[i];
}
RAD_ISSUE_N(c, E.elu[4], R, brows(E.x[4], R), brows(E.a[4], R));
conv(E.last, brows(E.a[4], R), RAD_NONE, brows(E.z, R), R, raw_cu);
ref_bounds(c, E, E.cu, R);
const RadOperand cu = brows(E.cu, 2), pos = brows(E.index, R);
for (const RefLayer& T : E.layer) {
auto norm = [&](rad_op op, rad_weight w, rad_weight bias) {
RAD_ISSUE_N(c, op, R, brows(E.z, R), RAD_W(w), RAD_W(bias), brows(E.th, R));
};
auto gemm = [&](rad_op op, rad_buf x, rad_weight w, rad_buf y) {
RAD_ISSUE_N(c, op, R, brows(x, R), RAD_W(w), brows(y, R));
};
norm(T.norm1, T.n1, T.b1);
gemm(T.proj, E.th, T.qkv, E.qkv);
RAD_ISSUE_N(c, T.rope, R, brows(E.qkv, R), pos);
RAD_ISSUE_N(c, T.attn, R, bcol(E.qkv, 0, 512, R), bcol(E.qkv, 512, 512, R),
bcol(E.qkv, 1024, 512, R), cu, brows(E.attn, R));
gemm(T.out, E.attn, T.o, E.o);
RAD_ISSUE_N(c, T.scale1, R, brows(E.o, R), RAD_W(T.ls1), brows(E.o, R));
RAD_ISSUE_N(c, T.add1, R, brows(E.z, R), brows(E.o, R), brows(E.z, R));
norm(T.norm2, T.n2, T.b2);
gemm(T.f1, E.th, T.fc1, E.ff);
RAD_ISSUE_N(c, T.act, R, brows(E.ff, R), brows(E.act, R));
gemm(T.f2, E.act, T.fc2, E.o);
RAD_ISSUE_N(c, T.scale2, R, brows(E.o, R), RAD_W(T.ls2), brows(E.o, R));
RAD_ISSUE_N(c, T.add2, R, brows(E.z, R), brows(E.o, R), brows(E.z, R));
}
RAD_ISSUE_N(c, E.copy_f, 1, brow_slice(E.z, 0, 1, 512), brow_slice(E.pad, 0, 1, 512));
RAD_ISSUE_N(c, E.copy_f, 1, brow_slice(E.z, 0, 1, 512), brow_slice(E.pad, 1, 1, 512));
RAD_ISSUE_N(c, E.copy_f, R, brows(E.z, R), brow_slice(E.pad, 2, R, 512));
ref_bounds(c, E, E.cu, R + 2);
conv(E.sample, brows(E.pad, R + 2), RAD_NONE, brows(E.sampled, F + 1), R + 2, cu);
for (int p = 0; p < 2; ++p) {
RAD_ISSUE_N(c, E.project[p], F, brow_slice(E.sampled, 1, F, 512), RAD_W(E.qi[p]), brows(E.q[p], F));
for (int k = p ? 1 : 0; k < (p ? 16 : 1); ++k) {
RadOperand codes = brow_slice(E.codes, k, 1, kMaxRefFrames);
codes.cols = F;
RAD_ISSUE_N(c, E.quant[k], F, brows(E.q[p], F), RAD_W(E.cb[k]), codes);
}
}
}
+9 -6
View File
@@ -21,11 +21,12 @@ namespace clef_bf16 {
using namespace rad::arch;
/* One head per rank beside the trunk's own per-rank state (qwen35_bf16::g_model). */
static ClefHead g_head[MAX_RANKS];
static ClefHead g_head[MAX_SLOTS];
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
if (!ClefHead::present(meta)) {
std::fprintf(stderr, "radiance: clef_bf16 serves a container converted with "
"--set decision.type=clef and the head added (--add "
@@ -36,13 +37,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* The trunk's declare does not take part in sizing declares (no probe), so its state and the
* head's are the real ones. The head goes after the vision tower: its buffers join the same
* arena, and it reads the final norm's rows, the lm_head and the trunk's cache block size. */
qwen35_bf16::Model& m = qwen35_bf16::g_model[ctx->rank];
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_build_slot(ctx)];
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
* skips the lm_head on a step every sampled row of which carries a request's words
* (plugin_words_cover_rows) and leaves zero rows instead. */
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
if (!m.op_logits_fill) return RAD_E_INVAL;
ClefHead& h = g_head[ctx->rank];
ClefHead& h = g_head[rad_build_slot(ctx)];
h = ClefHead{};
return h.declare(b, meta, ctx, m.nm, m.g, m.b_h, m.b_logits, m.w_lm_head, m.kv_full,
(int)m.g.n_layer + 256);
@@ -52,8 +53,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
qwen35_bf16::step(c, batch);
/* An encoder pass runs the tower alone and leaves no rows for the head. */
if (batch->enc) return;
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_rank(c)];
ClefHead& h = g_head[rad_rank(c)];
qwen35_bf16::Model& m = qwen35_bf16::g_model[rad_slot(c)];
ClefHead& h = g_head[rad_slot(c)];
/* The final norm's rows are still in `h` after the trunk's step; the logits row of each
* sampled sequence has been written, and the head adds its values beside it. */
h.step_tokens(c, batch, m.b_h);
@@ -62,6 +63,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
} /* namespace clef_bf16 */
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(clef_bf16, "clef", "", "0.1.0",
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_bf16, bf16, "
"with the joint schema head on the card for /v1/systemone")
+9 -6
View File
@@ -21,11 +21,12 @@ namespace clef_fp8 {
using namespace rad::arch;
static ClefHead g_head[MAX_RANKS];
static ClefHead g_head[MAX_SLOTS];
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
if (!ClefHead::present(meta)) {
std::fprintf(stderr, "radiance: clef_fp8 serves a container converted with "
"--set decision.type=clef and the head added (--add "
@@ -33,13 +34,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_INVAL;
}
RAD_ARCH_TRY(qwen35_clef_fp8::declare(b, meta, ctx));
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[ctx->rank];
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_build_slot(ctx)];
/* The lm_head's row would be sampled once and discarded: with this fill declared, the trunk
* skips the lm_head on a step every sampled row of which carries a request's words
* (plugin_words_cover_rows) and leaves zero rows instead. */
m.op_logits_fill = clef_logits_fill(b, m.nm, m.g, m.b_logits);
if (!m.op_logits_fill) return RAD_E_INVAL;
ClefHead& h = g_head[ctx->rank];
ClefHead& h = g_head[rad_build_slot(ctx)];
h = ClefHead{};
return h.declare(b, meta, ctx, m.nm, m.g, m.a_h.x, m.b_logits, m.w_lm_head, m.kv_full,
(int)m.g.n_layer + 256);
@@ -49,8 +50,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
qwen35_clef_fp8::step(c, batch);
/* An encoder pass leaves no rows for the head, and a drafter's pass is not a trunk step. */
if (batch->enc || batch->draft_pass != 0) return;
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_rank(c)];
ClefHead& h = g_head[rad_rank(c)];
qwen35_clef_fp8::Model& m = qwen35_clef_fp8::g_model[rad_slot(c)];
ClefHead& h = g_head[rad_slot(c)];
/* The final norm's rows are in `a_h.x` after either of the trunk's step paths. */
h.step_tokens(c, batch, m.a_h.x);
if (batch->n_out > 0) h.step_heads(c, batch, m.b_logits, m.w_lm_head);
@@ -59,6 +60,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
} /* namespace clef_fp8 */
RAD_ARCH_PROBE(qwen35_clef_fp8)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(clef_fp8, "clef", "fp8_e4m3", "0.1.0",
"Cloudflare's clef / clef-flash (9B, 27B): the Qwen3.5 trunk of qwen35_fp8, "
"block-scaled fp8, with the joint schema head on the card for /v1/systemone")
+114 -25
View File
@@ -17,6 +17,7 @@
#include "rad_yarn.h"
#include "rad_abi_layout.h"
#include <cctype>
#include <cstdarg>
#include <cstdio>
#include <cstring>
@@ -36,9 +37,12 @@ namespace rad {
namespace arch {
/* One thread per tensor-parallel rank in one process (spec §1), and declare runs once per rank,
* so declared handles are per-rank state; a single global would let rank 1 overwrite rank 0.
* libr4d all-reduces over 2/4/8 ranks, hence eight. */
enum { MAX_RANKS = 8 };
* so declared handles are per-instance state; a single global would let rank 1 overwrite rank 0.
* libr4d all-reduces over 2/4/8 ranks, hence eight ranks. Several engines may run in the process
* (docs/MULTIMODEL.md), each with its own ranks, so state is indexed by the instance's slot
* (rad_build_slot at declare, rad_slot in step), unique across all of them, never by the rank two
* engines share. */
enum { MAX_RANKS = 8, MAX_SLOTS = RAD_MAX_SLOTS };
/* ================================================================== a debug residual probe
*
@@ -123,6 +127,36 @@ inline const char* calib_dir() {
return d && *d ? d : nullptr;
}
/* Whether layer `layer` taps (RADIANCE_CALIB_LAYERS: comma-separated layers and "lo-hi" ranges;
* unset, every layer). A model whose per-expert Hessians do not fit the host at once (Nemotron-3.5
* Bolt's are 169 GiB) calibrates in several runs over disjoint ranges; each run writes only its
* layers' files, so the runs share one directory. */
inline bool calib_layer_on(int layer) {
static const std::vector<std::pair<int, int>> ranges = [] {
std::vector<std::pair<int, int>> r;
const char* s = std::getenv("RADIANCE_CALIB_LAYERS");
while (s && *s) {
char* e = nullptr;
const long lo = std::strtol(s, &e, 10);
if (e == s) break;
long hi = lo;
if (*e == '-') {
const char* h = e + 1;
hi = std::strtol(h, &e, 10);
if (e == h) break;
}
r.emplace_back((int)lo, (int)hi);
s = *e == ',' ? e + 1 : e;
if (*s && *s != ',' && !std::isdigit((unsigned char)*s)) break;
}
return r;
}();
if (!std::getenv("RADIANCE_CALIB_LAYERS")) return true;
for (const auto& r : ranges)
if (layer >= r.first && layer <= r.second) return true;
return false;
}
/* Token count at which the tap dumps and switches itself off (RADIANCE_CALIB_TOKENS, default
* 65536). Whether the tap runs at all is calib_dir()'s decision. */
inline long long calib_target() {
@@ -189,13 +223,14 @@ inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const c
return calib_write_host(h.data(), k, rows, what, domain, rad_rank(c));
}
/* A pinned host buffer of at least `bytes`, one per rank, held for the process lifetime, so a tap
* that copies a scratch back every pass runs at link speed. Null (and logged) on failure. */
/* A pinned host buffer of at least `bytes`, one per instance (slot), held for the process
* lifetime, so a tap that copies a scratch back every pass runs at link speed. Null (and logged)
* on failure. */
inline float* calib_staging(RadCtx* c, int64_t bytes) {
static std::mutex mu;
static std::map<int, std::pair<void*, int64_t>> per_rank;
static std::map<int, std::pair<void*, int64_t>> per_slot;
std::lock_guard<std::mutex> lk(mu);
std::pair<void*, int64_t>& s = per_rank[rad_rank(c)];
std::pair<void*, int64_t>& s = per_slot[rad_slot(c)];
if (s.second >= bytes) return (float*)s.first;
if (s.first) rad_dev_free(s.first, RAD_MEM_HOST_PINNED);
s.first = rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED);
@@ -641,8 +676,13 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
}
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. A plugin declares
* none where the deployment turns the reads off (RadBuildCtx::weight_prefetch_off). */
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes, int64_t blocks = 0) {
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
/* `blocks`: the workgroups reading, where the architecture measured its own count (docs/OPS.md);
* 0 leaves the kernel's. Stated only when asked, so a declaration without it is what it was. */
if (blocks > 0)
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes), RAD_INT("blocks", blocks)),
RAD_WEIGHTS(w));
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
}
@@ -702,9 +742,6 @@ struct Geom {
/* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as
* `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */
int64_t wire_min_bytes = 0;
/* RAD_ATTN_FP8_* bits: the attention products accepted in e4m3 (RadBuildCtx describes it).
* decl_attn passes it on as `attn_paged`'s `prefill_fp8`. */
int attn_prefill_fp8 = 0;
/* RadBuildCtx::plain_norm: a block norm none of whose readers takes codes may run as `add` +
* `rmsnorm` (rad_fp8.h, NormQuantFP8::x_only). */
int plain_norm = 0;
@@ -743,6 +780,12 @@ struct Geom {
* setting because producers and consumers must agree; the plugin reads it off a trunk weight's
* encoding and every linear checks its own against it. */
bool w_bf16 = false;
/* The linears are rotated int8 (rad_fp8.h's linear_is_w8h: IQ8R, or the 128-group form) with
* one activation scale per `w_i8_group` columns, for a plugin whose producers are declared away
* from its probe: each then declares an int8 code pair (ActFP8::declare_pair). Model-wide as
* w_bf16 is. */
bool w_i8h = false;
int64_t w_i8_group = 128;
int64_t q_dim() const { return n_head * head_dim; }
int64_t kv_dim() const { return n_head_kv * head_dim; }
@@ -979,8 +1022,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
g.world = c->world_size ? c->world_size : 1;
g.wire_exact= c->tp_wire_lossy ? 0 : 1;
g.wire_min_bytes = c->tp_wire_min_bytes;
g.attn_prefill_fp8 = c->attn_prefill_fp8;
g.plain_norm = c->plain_norm;
g.plain_norm = c->plain_norm != 0;
g.eps = m->rms_eps;
g.theta = m->rope_theta;
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
@@ -1297,16 +1339,6 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
}
/* An `attn_paged` op with the deployment's `prefill_fp8` appended (docs/OPS.md). At 0 the
* parameters are passed unchanged, so op identities and tune keys do not change. */
inline rad_op decl_attn(RadBuilder* b, const Geom& g, const char* name,
const RadParam* params, int n, const rad_weight* weights, int nw) {
if (g.attn_prefill_fp8 == 0) return rad_decl_op(b, name, params, n, weights, nw);
std::vector<RadParam> p(params, params + n);
p.push_back(RAD_INT("prefill_fp8", g.attn_prefill_fp8));
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
}
/* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it
* after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the
* free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would
@@ -1443,6 +1475,45 @@ inline void batch_split(const RadBatch* b, int64_t* n_seq_dec, int64_t* n_tok_de
}
}
/* What a step's attention reads of the QSA selection (AttnGatedFP8::qsa_use), which decides what
* the indexer issues for the layer (QsaIndexer::step, docs/QSA.md "Below the bound"):
*
* kQsaSelect score and select, per layer: a step past the exactness bound, a streamed group,
* and every step of a block that did not ask for the forms below;
* kQsaUnread nothing reads the selection: the step is entirely at or below the bound and its
* attention is the dense one, or the sparse row over the sequence's own block table
* (one row a sequence), which is what the selection would be. The indexer stores its
* keys and tail and issues no query, score or select;
* kQsaOnce the attention reads a selection (the sparse row a query) on a step entirely at or
* below the bound: every complete block is taken whatever it scores, so the
* selection depends on the positions and the block table alone and is the same
* bytes at every layer. The first full-attention layer of the pass issues it as
* always; no later layer issues a query, a score or a select. */
enum QsaUse : int { kQsaSelect = 0, kQsaUnread = 1, kQsaOnce = 2 };
/* Ops of a chain that is independent of a block's own, for the block to issue behind its ordered
* launches. A recorded pass lets a launch start beside the last ordered one when it touches
* nothing in flight (Ctx::haz_mark). A dependent chain issued in one piece is therefore a row of
* ordered launches, each paid in turn; issued one op behind each of the block's own ordered
* launches, every op of it is unordered behind the block's launch in front of it, and still
* behind its own predecessor, which that launch already waited for. The block calls `at(k)` for
* k = 0, 1, 2, ... behind its ordered launches in turn, and the owner issues what is left once
* the block returns. The chain must read nothing the block writes and write nothing the block
* touches, and its buffers must be excluded from sharing (rad_buf_concurrent): they are in use at
* launches the linear order puts after their last declared use. */
struct SideOps {
void (*fn)(void* u, int stage) = nullptr;
void* u = nullptr;
void at(int stage) const { if (fn) fn(u, stage); }
};
/* RADIANCE_DEBUG_QSA_EAGER: every step is kQsaSelect, the issue sequence before the forms above
* existed. An instrument for comparing the two (the text must not move); read once. */
inline bool qsa_eager() {
static const bool on = std::getenv("RADIANCE_DEBUG_QSA_EAGER") != nullptr;
return on;
}
/* The step batch's entry for one declared KV group (built once per step by the core, spec §8). */
inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
for (int i = 0; i < b->n_kv_groups; ++i)
@@ -1504,7 +1575,12 @@ inline const char* drafter_layer_prefix(const RadModelMeta* meta) {
return "draft.transformer_layer_config.";
return "draft.";
}
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) {
/* `kv_repl_ok`: the drafter block reads its k and v at Geom::kv_off (rad_block_dflash2.h does), so
* fewer KV heads than ranks are replicated as geom_from replicates the target's: world a multiple
* of the head count, one KV head a rank, `kv_off` its first row in the unsharded k/v projection.
* Otherwise such a world is refused, as before. */
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what,
bool kv_repl_ok = false) {
dg = target;
const char* pre = drafter_layer_prefix(meta);
char key[160];
@@ -1529,7 +1605,15 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta,
}
RAD_ARCH_TRY(yarn_from(dg, meta, pre, dg.head_dim));
RAD_ARCH_TRY(divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head));
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv));
/* The target's kv_off is the target's; the drafter's is set here or zero. */
dg.kv_off = 0;
if (kv_repl_ok && dg.world > dg.n_head_kv_all && dg.world % dg.n_head_kv_all == 0) {
dg.n_head_kv = 1; /* world / n_head_kv_all ranks share each KV head */
dg.kv_off = (dg.rank / (dg.world / dg.n_head_kv_all)) * dg.head_dim;
} else {
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads",
&dg.n_head_kv));
}
RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff));
const long long dvocab = rad_meta_geti(meta, k("vocab_size"), dg.n_vocab_all);
if (dvocab != dg.n_vocab_all) {
@@ -1614,6 +1698,11 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge
#define RAD_ARCH_SERVES_IMPORTS(V) \
extern "C" int rad_arch_serves_imports(void) { return V; }
/* RAD_ARCH_MULTI_INSTANCE() states that the plugin keeps all per-instance state by slot, so several
* engines in one process may run it at once (rad_builder.h, rad_arch_multi_instance). */
#define RAD_ARCH_MULTI_INSTANCE() \
extern "C" int rad_arch_multi_instance(void) { return 1; }
} /* namespace arch */
} /* namespace rad */
+1 -1
View File
@@ -139,7 +139,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* 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, decl_attn(b, g, "attn_paged",
op_attn = rw(b, rad_decl_op(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
+25 -12
View File
@@ -9,6 +9,9 @@
* the GEMM output directly.
* - No output gate. The attention output goes straight into the out-projection.
*
* `rotary_dim` 0 is attention without positions (NoPE, Nemotron-H's attention layers): no `rope`
* is declared, and position reaches the model through its recurrent layers alone.
*
* 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
@@ -81,19 +84,21 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
const int64_t q_dim = g.q_dim();
const int64_t kv_dim = g.kv_dim();
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
if (n_rot < 0 || n_rot > g.head_dim || (n_rot & 1)) {
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
(long long)n_rot, (long long)g.head_dim);
return RAD_E_INVAL;
}
/* No KV-head replication: 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,
(long long)g.n_head_kv_all);
/* Above the KV head count geom_from replicates KV heads (rad_arch.h): each of the fused row's
* three parts takes its own span (as gemma4's q|k|v does), q this rank's heads and k and v the
* shared head at `kv_off`, where the even shard would hand a rank part of a head. A smaller
* attention world (Geom::attn_world) is not served here. */
const bool kv_repl = g.world > g.n_head_kv_all;
if (kv_repl && g.attn_world != g.world) {
fprintf(stderr, "radiance: %s replicates KV heads but declares no attention-zero ranks; "
"world_size = %d must be a multiple of n_head_kv = %lld.\n", __func__,
g.world, (long long)g.n_head_kv_all);
return RAD_E_UNSUPPORTED;
}
@@ -107,9 +112,17 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
0, { q_dim, kv_dim, kv_dim }));
if (kv_repl) {
const int64_t lo[3] = { g.rank * q_dim, g.kv_off, g.kv_off };
const int64_t hi[3] = { lo[0] + q_dim, lo[1] + kv_dim, lo[2] + kv_dim };
const int64_t tot[3] = { g.n_head_all * g.head_dim, g.n_head_kv_all * g.head_dim,
g.n_head_kv_all * g.head_dim };
RAD_ARCH_TRY(qkv.span_parts(b, lo, hi, tot, 3));
}
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
{w.qkv}, {w.qkv});
if (n_rot > 0)
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
{w.qkv}, {w.qkv});
/* 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
@@ -124,7 +137,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
/* 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, decl_attn(b, g, "attn_paged",
op_attn = rw(b, rad_decl_op(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
@@ -179,7 +192,7 @@ inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
qkv.step(c, w.h, w.qkv, 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));
if (op_rope) RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
/* k and v are column slices of the fused row, at q_dim and q_dim + kv_dim. */
RAD_ISSUE(c, op_kv_store,
+1 -1
View File
@@ -195,7 +195,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
*
* 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, decl_attn(b, g, "attn_paged",
op_attn = rw(b, rad_decl_op(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0),
+128 -39
View File
@@ -9,7 +9,7 @@
* 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.
* the attention family's cache rows. 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).
*
* The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, scale plane
@@ -26,14 +26,6 @@
namespace rad {
namespace arch {
/* Whether the streamed store has a row for this cache layout: libr4d's are E4M3 and bf16 only. A
* packed cache (fp8_v4, k6_v4) must not declare it, since a weightless op with no row is a hole
* that refuses startup even with --kv-resident off; kvstream_configure then names the layout. */
inline bool kv_store_streamed_dtype(const char* kv_dtype) {
return kv_dtype && (std::strcmp(kv_dtype, "fp8_e4m3") == 0 ||
std::strcmp(kv_dtype, "bf16") == 0);
}
struct AttnGatedFP8 {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
@@ -87,6 +79,21 @@ struct AttnGatedFP8 {
/* `sel`'s row pitch is `topk + 1`; the extra slot is the partial page
* (r4d_qsa_select_bf16.hip). */
int64_t qsa_topk = 0;
/* The architecture's word that a sequence with one row in the step has that row at its
* context's last position (`seqused - 1`: a plain decode row, a serial head's round), so at or
* below `qsa_exact_to` such a row's selection is the head of the sequence's block table and its
* `seqused` the sequence's (qsa_select: every complete block in block order, then the partial
* page, and `pos + 1`). The sparse row is then issued over the table and the indexer selects
* nothing (qsa_use). Off: such a step keeps the selection. */
bool qsa_table_rows = false;
/* The architecture's pass key carries whether this group's exact host bound
* (RadBatch::kv_used_max_h, the furthest context any row of the step can read) is within
* `qsa_exact_to`, so that bound may say whether the step needs scores (qsa_within) in place of
* the rounded `max_ctx_len + max_q_len`, which a 4-row step leaves at 1025 tokens. It never
* moves the choice between the dense and the sparse kernel, which stays the rounded bound's:
* the two agree on the keys, not on the last bit of the sum. Off: the rounded bound, which the
* core's key holds. */
bool qsa_exact_host = false;
/* 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
@@ -115,6 +122,18 @@ struct AttnGatedFP8 {
/* The input was normed and quantised by the caller; this block declares no norm. */
bool ext_in = false;
LinearFP8 qg{}, kp{}, vp{}, o{};
/* Set by the architecture after declare: a `prefetch` of the out projection's leading bytes
* (decl_prefetch, rad_arch.h), issued behind the q, k and v projections on decode steps
* (prefetch_beside). 0 where none is declared. */
rad_op op_pf_o = 0;
/* The same read as a second op for steps of at least pf_o_v_rows rows, where the
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
* every step takes op_pf_o. */
rad_op op_pf_o_v = 0;
int64_t pf_o_v_rows = 0;
/* The most rows of a decode step whose k and v projections are issued in front of the q|gate
* projection (step()); 0, the default, keeps the declared order on every step. */
int64_t kv_first_rows = 0;
NormQuantFP8 nq_h{};
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
@@ -125,7 +144,7 @@ struct AttnGatedFP8 {
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_attn_gq = 0; /* attn_paged + gate_quant_fp8 or gate_had_quant_i8g */
/* kv_store_streamed: the host mirror always, the ring slot when `res` says the block is resident
* (docs/OPS.md). Zero when no row serves it; a streamed group then fails the step. */
rad_op op_kv_stream = 0;
@@ -172,8 +191,12 @@ struct AttnGatedFP8 {
/* 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). */
/* `side`: an independent chain's ops, issued behind this block's ordered launches (SideOps,
* rad_arch.h): one behind the prologue and the store, one behind the attention, one behind
* the gate where the gate is a launch of its own. Null, and on the paths that return early,
* nothing is asked of it. */
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
ArPieces* pieces = nullptr) const;
ArPieces* pieces = nullptr, const SideOps* side = 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,
@@ -189,6 +212,41 @@ struct AttnGatedFP8 {
* components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and
* the gate quantised by gate_quant_fp8. A streamed group never takes it: the pieces path's
* plain store never writes the host mirror. */
/* The rounded host bound of the furthest context a row of the step reads; by it a step of
* several rows a sequence takes the dense or the sparse kernel (step(), `sparse`). */
int64_t qsa_reach(const RadBatch* batch) const {
return (int64_t)batch->max_ctx_len + batch->max_q_len;
}
/* Whether every row of the step is at or below the exactness bound, by the tightest host
* ceiling there is: the group's exact one where the pass key holds its side of the bound
* (qsa_exact_host), else the rounded one. Every row's position + 1 is at most either. */
bool qsa_within(const RadBatch* batch, const RadKVGroupBatch* kvb) const {
if (qsa_exact_to <= 0) return false;
int64_t reach = qsa_reach(batch);
if (qsa_exact_host && kvb && batch->kv && batch->kv_used_max_h) {
const int64_t tight = batch->kv_used_max_h[kvb - batch->kv];
if (tight > 0 && tight < reach) reach = tight;
}
return reach <= qsa_exact_to;
}
/* What this step's attention reads of the selection (QsaUse, rad_arch.h); the architecture
* hands it to the indexer, which runs first, and step() takes its path by the same call. */
int qsa_use(const RadBatch* batch) const {
if (!qsa_sel || !qsa_sequ || op_fill || qsa_eager()) return kQsaSelect;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
/* A streamed group may be ring-bound, where every pass is sparse and the resolve rewrites
* the selection; it keeps the selection at every context. */
if (!kvb || kvb->stream || !kvb->block_table || !kvb->seqused) return kQsaSelect;
if (!qsa_within(batch, kvb)) return kQsaSelect;
/* One row a sequence is the sparse row at every context: over the table where the
* architecture vouches for it, else over a selection. */
if (batch->n_tok == batch->n_seq)
return (qsa_table_rows && batch->max_q_len == 1) ? kQsaUnread : kQsaOnce;
/* Several rows a sequence: the dense attention, which reads the table, where the rounded
* bound is within the budget too, else the sparse row a query over a selection. */
return qsa_reach(batch) <= qsa_exact_to ? kQsaUnread : kQsaOnce;
}
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
const int64_t T = batch->n_tok;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
@@ -342,7 +400,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
/* Declared before kv_store, which reads back the resolved `block_size`
* (rad_block_attn_gated.h). */
op_attn = decl_attn(b, g, "attn_paged",
op_attn = rad_decl_op(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0),
@@ -382,8 +440,8 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
/* The streamed store: kv_store's operands and parameters plus the residency map and the layer's
* mirror row, which the batch carries (store_cache). `block_size` does not bind the group;
* `attn_paged` already has. Only for a layout with a row (kv_store_streamed_dtype). */
if (kv_store_streamed_dtype(g.kv_dtype) && rad_op_declared(b, "kv_store_streamed"))
* `attn_paged` already has. */
if (rad_op_declared(b, "kv_store_streamed"))
op_kv_stream = rw(b, RAD_OP(b, "kv_store_streamed",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("head_dim", g.head_dim),
@@ -396,7 +454,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
/* 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. */
* Resolves for either cache. */
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),
@@ -410,9 +468,8 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
/* The fold for a streamed group: also writes the mirror and consults the residency map, whose
* operands are added at issue. Gated on the same layouts. */
if (op_fused && kv_store_streamed_dtype(g.kv_dtype) &&
rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
* operands are added at issue. */
if (op_fused && rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
op_fused_stream = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store_streamed",
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
@@ -458,10 +515,12 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
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",
/* Rotated int8 codes (ActFP8::q8_rot): gate_had_quant_i8g, had_quant_act_i8g's codes. */
const char* gq = w.attn.q8_rot ? "gate_had_quant_i8g" : "gate_quant_fp8";
if (rad_op_declared(b, gq))
op_gq = rw(b, RAD_OP(b, gq,
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_INT("n", g.head_dim), RAD_INT("group", w.attn.cg()),
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});
@@ -486,10 +545,12 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
* 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",
* has no merge. Rotated int8 codes (ActFP8::q8_rot) take attn_paged_gate_had_quant, the merge
* with gate_had_quant_i8g's quantiser. */
const char* attn_gq = w.attn.q8_rot ? "attn_paged_gate_had_quant" : "attn_paged_gate_quant";
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && w.attn.cg() == RAD_FP8_BLOCK &&
rad_op_declared(b, attn_gq)) {
op_attn_gq = RAD_OP(b, attn_gq,
RAD_PARAMS(RAD_INT("q_len", 1), 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),
@@ -589,7 +650,7 @@ inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
}
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
ArPieces* pieces) const {
ArPieces* pieces, const SideOps* side) 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;
@@ -634,7 +695,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
RAD_ISSUE_N(c, op_gq, n * g.n_head,
bcol_at(w.qg, r0, qgw, hd, hd, n), brow_slice(w.attn.x, r0, n, qw),
brow_slice(w.attn.cq(), r0, n, qw),
brow_slice(w.attn.cs(), r0, n, fp8_blocks(qw)),
brow_slice(w.attn.cs(), r0, n, qw / w.attn.cg()),
brow_slice(w.attn.x, r0, n, qw));
o.step(c, w.attn, w.h.x, T, r0, n);
if (p == 0) pieces->hand(r0, n);
@@ -651,9 +712,23 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
return;
}
qg.step(c, w.h, w.qg, T);
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
/* The three projections read the same input and none reads another's output, so a recorded
* pass starts them together (Ctx::haz_mark) whatever their order; the order decides which
* the card launches first. On a decode step of up to `kv_first_rows` rows the two small ones
* go first: behind the wide q|gate projection their launches wait until its blocks are all
* on the card, and the prologue then waits for them. Qwen3.8-Flash-Next at tp 2, chain 3
* with coupling (twelve trunk layers and the head's): -0.66% a step. */
if (T <= kv_first_rows && batch->phase == RAD_PHASE_DECODE) {
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
qg.step(c, w.h, w.qg, T);
} else {
qg.step(c, w.h, w.qg, T);
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
}
/* The out projection's weight, read beside the prologue and the attention (op_pf_o). */
prefetch_beside(c, op_pf_o_v && T >= pf_o_v_rows ? op_pf_o_v : op_pf_o, o.w, T);
/* 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
@@ -698,6 +773,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
}
if (!fused_kv && !folded_stream) store_cache(c, kvb, slot, T);
if (side) side->at(0);
/* 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
@@ -710,7 +786,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
* 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 int64_t reach = qsa_reach(batch);
/* A pass on a streamed group's ring (a ring smaller than the id space, and not staged) must
* take the sparse path: on the ring a block id is not a pool address, so the dense path would
* read ring slots as pages. `T == n_seq` alone misses a verify pass, whose T is
@@ -724,6 +800,19 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
const bool sparse = qsa_sel && qsa_sequ &&
(ring_bound || T == batch->n_seq || qsa_exact_to <= 0 ||
reach > qsa_exact_to);
/* At or below the bound a step of one row a sequence has no selection (qsa_use): the sparse
* row reads the sequence's own block table and length, which is what qsa_select would have
* written for it (the field says why), so the launch, its kernel and its bytes are the sparse
* row's. */
const bool by_table = sparse && T == batch->n_seq && qsa_use(batch) == kQsaUnread;
const int64_t tpitch = kvb ? kvb->block_table_pitch : 0;
auto sel_rows = [&](int64_t off, int64_t rows) {
return by_table ? praw2(table + off * tpitch, RAD_I32, rows, tpitch)
: brow_slice(qsa_sel, off, rows, qsa_topk + 1);
};
auto sequ_rows = [&](int64_t off, int64_t rows) {
return by_table ? praw(used + off, RAD_I32, rows) : brow_slice(qsa_sequ, off, rows, 1);
};
const bool gated = sparse && op_attn_gq;
/* A streamed group's selection, per launch: make the rows' blocks resident and rewrite `sel`
* as ring slots, after this layer's store (a block copied in from the mirror must carry this
@@ -731,6 +820,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
* and never resolves, so a prefill cannot overflow the ring. */
const KVStreamLayer res_l = op_resolve ? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{};
auto resolve_sel = [&](int64_t off, int64_t rows) {
if (by_table) return; /* never a streamed group (qsa_use) */
if (kv_stage_layer(c, kv, kvb, layer)) return;
if (!res_l.host || res_l.blocks <= 0 || res_l.slots <= 0 || rows <= 0) return;
kv_resolve_issue(c, op_resolve, res_l, brow_slice(qsa_sel, off, rows, qsa_topk + 1),
@@ -752,13 +842,12 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
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),
sel_rows(off, rows), sequ_rows(off, rows),
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)));
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
}
o.step(c, w.attn, w.h.x, T, p0, pn);
if (p0 + pn < T) pieces->hand(p0, pn);
@@ -776,13 +865,12 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
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),
sel_rows(off, rows), sequ_rows(off, rows),
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)));
brow_slice(w.attn.cs(), off, rows, qw / w.attn.cg()));
}
} else if (sparse) {
const int64_t chunk = qsa_rows();
@@ -793,8 +881,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
RAD_ISSUE_N(c, op_attn, 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),
sel_rows(off, rows), sequ_rows(off, rows),
RAD_NONE, RAD_NONE, RAD_NONE,
brow_slice(w.attn.x, off, rows, qw));
}
@@ -855,6 +942,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
/* Every attention launch of this layer is issued: start the next layer's stage copy, which
* crosses the link under the out projection and the next layer's projections. */
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
if (side) side->at(1);
if (gated) {
/* the sparse attention gated and quantised in its merge */
} else if (op_sig) {
@@ -868,6 +956,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
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));
}
if (side && !gated) side->at(2);
o.step(c, w.attn, w.h.x, T);
if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
+253 -94
View File
@@ -47,6 +47,13 @@
* hp = hidden_projection(x) the selector's query, rank 256
* tokens = dflash_select(cand, unary, hp, anchor, predecessor, successor)
*
* ============================== LILICORR ==============================
*
* Config::lili is NVIDIA's LiLiCorr backbone (Nemotron-3.5-Bolt's drafter): the same layers with a
* learned sink logit a query head in the attention (attn_paged_sink, `attention_sink_bias`), and no
* selector or draft head here. The query pass ends with the gather into `sel_h`; the plugin then
* runs rad_block_lilicorr.h's correlator over those rows, which reads the target's own head.
*
* ============================== WHAT IS SHARED WITH THE TARGET ==============================
*
* The embedding table and lm_head. The checkpoint (81 tensors) ships neither, and
@@ -68,6 +75,8 @@
*
* 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.
* Fewer KV heads than ranks are replicated (drafter_geom's `kv_repl_ok`): each rank reads its
* head's k/v rows at `kv_off` and keeps that head in its cache.
*
* fc [n_embd, n_taps*n_embd], 262 MiB in fp8 at Qwen3.8's width, read whole by the
* context pass every step. Split by rows over the ranks and all-gathered, and
@@ -138,6 +147,9 @@ struct Dflash2 {
/* 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;
/* Optional DFlash2 logit transform shipped by Muse Glimmer. */
double omul = 1.0;
double scap = 0.0;
/* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
int64_t prefetch = 0;
@@ -152,6 +164,17 @@ struct Dflash2 {
* acceptance, sum min(P, Q). */
double q_temp = 1.0;
int64_t short_rows = 0;
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
* by had_quant_act_i8g. Every linear must agree. `fc_mapped`: probe_i8 made
* `dflash.fc.weight`'s name map. */
bool act_i8 = false;
int64_t act_g8 = RAD_FP8_BLOCK;
bool fc_mapped = false;
/* LiLiCorr's backbone (the LILICORR section above): sinks, and the head left to the
* plugin. sel_rank and sel_topk are then unused. */
int lili = 0;
int64_t steps() const { return block - 1; }
int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); }
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
@@ -186,7 +209,9 @@ struct Dflash2 {
rad_buf gate_up = 0;/* [qrows, 2 * n_ff] */
rad_buf ffn = 0; /* [qrows, n_ff] */
/* 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 read only by the `gemm_nt_q` linears (int8 codes with a scale per Config::act_g8,
* written by `had_quant_act_i8g`, when the drafter's linears are rotated int8:
* Config::act_i8). 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 */
@@ -248,6 +273,9 @@ struct Dflash2 {
* 31B's: the head read at w8a8, so the selector sees the candidates an 8-bit head ranks), and
* the 2-bit grid otherwise. Set by declare from the copy's encoding. */
bool head_i8 = false;
/* Muse Glimmer's 202048-token vocab is not divisible by the int8/w2a8 head kernels' 128-row
* tile; its copied draft head stays BF16 and uses gemm_nt. */
bool head_bf16 = false;
/* per-layer weights */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
@@ -294,6 +322,9 @@ struct Dflash2 {
int64_t block_lo = 0;
int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
/* LiLiCorr: the attention with each layer's sinks, a weight, so one op a layer. */
rad_weight w_sink[MAX_LAYERS] = {};
rad_op op_attn_sink[MAX_LAYERS] = {};
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
* that norm where it resolves: op_afn[i] after layer i's attention (its feed-forward norm),
@@ -309,7 +340,7 @@ struct Dflash2 {
rad_weight pfa_w[MAX_LAYERS][2] = {}, pff_w[MAX_LAYERS][2] = {}, pfo_w[MAX_LAYERS] = {};
/* head and selector */
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dcap = 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 logit_rerank can read it (fp8 or
@@ -327,6 +358,18 @@ struct Dflash2 {
* the drafter's own block is longer (rad_drafter_short_block). */
static constexpr int64_t kShortBlock = 4;
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
* declared, since it decides their dtype and scale grid. */
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
const char* fwn = nm.f("dflash.fc.weight");
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
RadEncoding fe{};
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
return RAD_OK;
}
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
const char* ck_lm, const Wire& wire);
@@ -353,7 +396,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
(long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.block < 2 || cfg.n_taps <= 0 || cfg.sel_rank <= 0 || cfg.sel_topk <= 0)
if (cfg.block < 2 || cfg.n_taps <= 0 || (!cfg.lili && (cfg.sel_rank <= 0 || cfg.sel_topk <= 0)))
return RAD_E_INVAL;
const int64_t NG = cfg.ng(g.n_embd);
@@ -366,11 +409,18 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
srows = g.max_seqs * cfg.steps();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
w_fc.w8h_ok = cfg.act_i8;
for (int i = 0; i < MAX_LAYERS; ++i)
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
w_dn[i].w8h_ok = cfg.act_i8;
/* ---------------------------------------------------------------- model-scope weights */
{
const int64_t K = cfg.n_taps * g.n_embd;
const char* fwn = nm.f("dflash.fc.weight");
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
if (!cfg.fc_mapped) RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
/* Split only block fp8 (an MXFP4 GEMM's K split is its own), into equal shares of whole
* 16-byte words (the gather's unit). */
RadEncoding fe{};
@@ -401,23 +451,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
}
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)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
nm.ckpt("%s.candidate_selector.successor_codebook", 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());
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
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, 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
@@ -427,35 +464,59 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* 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). */
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16).
*
* LiLiCorr has neither the selector nor this head (its correlator reads the target's). */
enum { DF_W2_GROUP = 128 };
const bool dh_shard = head_sharded(g);
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
const char* dhn = nm.f("dflash.draft_head.weight");
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which gemm_nt_q
* reads at w8a8 against the same quant_act_i8 activation (without its asum). */
{
RadEncoding e{};
const RadEncPlane* sc = nullptr;
head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 &&
!e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 &&
(sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 &&
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
}
if (head_i8) {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
if (!cfg.lili) {
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
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());
const char* dhn = nm.f("dflash.draft_head.weight");
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which
* gemm_nt_q reads at w8a8 against the same quant_act_i8 activation (without its asum). */
RadEncoding dhe{};
const bool head_known = weight_enc(b, dhn, &dhe);
{
const RadEncPlane* sc = nullptr;
head_i8 = head_known && rad_enc_is(&dhe, "affine") && dhe.n_planes == 2 &&
!dhe.transform[0] && dhe.plane[0].dtype == RAD_I8 && dhe.plane[0].block[1] == 1 &&
(sc = rad_enc_plane(&dhe, "scale")) && sc->dtype == RAD_F16 &&
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
}
if (head_i8) {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN,
dh_split, grp_model());
} else if (head_known && rad_enc_is(&dhe, "plain") && dhe.n_planes == 1 &&
dhe.plane[0].dtype == RAD_BF16) {
head_bf16 = true;
w_dh = decl_w(b, dhn, RAD_BF16, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN, dh_split,
grp_model());
} else {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
} else {
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split,
grp_model());
}
if (!w_dh || (!head_bf16 && !w_dhs)) return RAD_E_INVAL;
}
if (!w_dh || !w_dhs) return RAD_E_INVAL;
/* ---------------------------------------------------------------- per-layer weights */
for (int64_t l = 0; l < g.n_layer; ++l) {
@@ -492,6 +553,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
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, grp_layer(first_layer + i),
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
/* Fewer KV heads than ranks (drafter_geom's `kv_repl_ok`): k and v are this rank's
* replicated head, rows [kv_off, kv_off + kv_dim) of the unsharded projection, where the
* even shard would hand a rank part of a head. q stays an even share of the heads. */
if (g.world > g.n_head_kv_all) {
RAD_ARCH_TRY(w_k[i].span(b, g.kv_off, g.kv_off + kvd));
RAD_ARCH_TRY(w_v[i].span(b, g.kv_off, g.kv_off + kvd));
}
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, grp_layer(first_layer + i));
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
@@ -520,6 +588,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
w_fcb[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_conv_base", i), RAD_BF16,
{2, cfg.taps, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(first_layer + i));
/* LiLiCorr's sink logit a query head, split with the heads. */
if (cfg.lili) {
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_sinks", i),
nm.ckpt("%s.layers.%d.self_attn.attention_sink_bias", ck, i)));
w_sink[i] = decl_w(b, nm.f("dflash.blk.%d.attn_sinks", i), RAD_F32, {g.n_head},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i));
if (!w_sink[i]) return RAD_E_INVAL;
}
}
@@ -529,15 +605,35 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
*
* 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),
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
if (!cfg.lili) {
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),
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
} else {
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_attn_sink[i] = rw(b, RAD_OP(b, "attn_paged_sink",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block),
RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
RAD_INT("window", cfg.window),
RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs),
RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_WEIGHTS(w_sink[i])),
{w.q}, {w.attn});
if (!op_attn_sink[i]) return RAD_E_INVAL;
}
}
/* ---------------------------------------------------------------- the context pass */
/* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the
@@ -547,20 +643,43 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* 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",
/* A rotated int8 drafter (cfg.act_i8): the same five quantisers as had_quant_act_i8g at its
* scale group, and no fp8a8 fold. Its linears read one activation pair, so they are all
* i8a8h forms at one group or none is. */
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
{
auto fits = [&](const DenseFP8& d) {
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
};
bool same = fits(w_fc);
for (int64_t l = 0; l < g.n_layer; ++l)
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
fits(w_gu[l]) && fits(w_dn[l]);
if (!same) {
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
"group or all block fp8 / MXFP4; they read one activation pair, so the "
"recipe must give them one format\n");
return RAD_E_DTYPE;
}
}
op_qsrc = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
if (fc_rows) {
/* The split (SHARDING above): this rank's block-aligned rows into `cpart`, its window of
* them gathered into `c`. The GEMM takes its K split from the whole width. The gather
* rides the trunk's all-reduce instance (the same numel bound, so the same instance). */
* rides the trunk's all-reduce instance (the same numel bound, so the same instance).
* The message is a range, as the all-reduce's: a fixed numel follows max_tok, and the
* arena's sizing declare (RadBuildCtx::shape_probe) refuses a fixed parameter that
* changes with the step size. */
op_cfc = w_fc.gemm(b, crows, fc_rows, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.cpart},
g.n_embd);
op_cgath = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", crows * g.n_embd),
RAD_RANGE("numel", g.n_embd, crows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("row", fc_share)),
RAD_NOWEIGHTS),
{w.cpart}, {w.c});
@@ -576,9 +695,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.c});
/* 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",
op_qc = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.c}, {w.cq, w.cs});
for (int64_t l = 0; l < g.n_layer; ++l) {
@@ -642,19 +761,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.x}, {w.x});
/* 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",
op_qh2 = rw(b, RAD_OP(b, qop,
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_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h2}, {w.h2q, w.h2s});
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
op_qat = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn}, {w.atq, w.ats});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
op_qff = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.ffn}, {w.ffq, w.ffs});
@@ -701,7 +820,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
/* The fold saves two launches and the bf16 round trip of the [T, n_ff] product; it is an
* fp8a8 tile, so an MXFP4 or M2XFP4 gate_up takes the pair. */
if (!w_gu[i].mx && !w_gu[i].m2x)
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
{w.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});
@@ -774,12 +893,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
/* Only for a shape a library serves: an op declared for one that resolves to no device
* kernel is a hole that refuses startup (Program::device_holes), whether or not it is
* issued, so the block asks within libr4d's span for the fold (head_dim 256 to 512 in
* steps of 256, bf16 rows, an fp8 or bf16 cache). Qwen3.8's DFlash2 drafter (head_dim
* 128) keeps the chain. */
* steps of 256, bf16 rows, either cache). Qwen3.8's DFlash2 drafter (head_dim 128) keeps
* the chain. */
const bool fold_shape = g.head_dim >= 256 && g.head_dim <= 512 && g.head_dim % 256 == 0 &&
!std::strcmp(g.dtype, "bf16") &&
(!std::strcmp(g.kv_dtype, "fp8_e4m3") ||
!std::strcmp(g.kv_dtype, "bf16"));
!std::strcmp(g.dtype, "bf16");
if (fold_shape && g.yarn.factor == 0.0f &&
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
const int64_t bsz = rad_kv_block_size(b, kv);
@@ -840,12 +957,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h2}, {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", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
op_final = cfg.omul != 1.0
? 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", g.wadd),
RAD_F64("mult", cfg.omul), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h})
: 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", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
/* Each residual add and the norm after it as one launch where a library serves add_rmsnorm
* (byte-identical to the pair: the norm is taken over the bf16 sum it stores), taken only
* where every handle resolves (rad_op_resolved), all or none; the pairs declared beside it run
@@ -869,6 +993,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
op_afinal = all ? an(w_norm) : 0;
if (!op_afinal)
for (int i = 0; i < MAX_LAYERS; ++i) op_afn[i] = op_aan[i] = 0;
/* add_rmsnorm has no `mult`; keep Muse's output_multiplier on the final norm. */
if (cfg.omul != 1.0) op_afinal = 0;
}
/* ---------------------------------------------------------------- the head and the selector
@@ -884,12 +1010,21 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h}, {w.sel_h});
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.dq, w.ds, w.dsum});
op_dlogits = head_i8
/* LiLiCorr's head is the plugin's (rad_block_lilicorr.h), over sel_h. */
if (cfg.lili) return RAD_OK;
if (!head_bf16)
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.dq, w.ds, w.dsum});
op_dlogits = head_bf16
? rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_dh)),
{w.sel_h}, {w.dlog})
: head_i8
? rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
@@ -902,6 +1037,14 @@ 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});
if (cfg.scap > 0.0) {
op_dcap = rw(b, RAD_OP(b, "logit_softcap",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", head_rows(g)),
RAD_F64("cap", cfg.scap), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.dlog});
if (!op_dcap) return RAD_E_INVAL;
}
/* 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. */
@@ -1090,7 +1233,8 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
if (fc_rows) {
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.cpart, T), RAD_NONE, w_fc.bref());
RAD_ISSUE_N(c, op_cgath, T, bcol(w.cpart, fc_off, fc_share, T), brows(w.c, T));
RAD_ISSUE_N(c, op_cgath, T * g.n_embd, bcol(w.cpart, fc_off, fc_share, T),
brows(w.c, T));
} else {
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());
@@ -1188,13 +1332,22 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
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));
if (cfg.lili)
RAD_ISSUE_N(c, op_attn_sink[i], 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),
RAD_W(w_sink[i]), brows(w.attn, T));
else
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());
@@ -1238,15 +1391,21 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
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 (cfg.lili) return; /* the plugin's correlator takes sel_h from here */
/* `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, absent here. Operands are positional,
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric and
* takes no asum. */
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), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
if (head_bf16) {
RAD_ISSUE_N(c, op_dlogits, S, brows(w.sel_h, S), RAD_W(w_dh), brows(w.dlog, S));
} else {
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, absent here. Operands are positional,
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric
* and takes no asum. */
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), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
}
if (op_dcap) RAD_ISSUE_N(c, op_dcap, S, brows(w.dlog, S), brows(w.dlog, S));
/* 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) {
+93 -82
View File
@@ -93,12 +93,15 @@
*
* ============================== PRECISION ==============================
*
* E4M3 + a bf16 [N/128][K/128] plane fc, q/k/v/o, gate_up, down -- every linear
* what the recipe made them fc, q/k/v/o, gate_up, down -- every linear
* bf16, no plane every norm, and both Markov codebooks
*
* The checkpoint is dense bf16; 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.
* bf16, 324 MB at eight bits). DenseFP8 reads block fp8 or MXFP4 against E4M3 activations, or a
* rotated int8 form (IQ8R and the narrower grids under the same rotation) against int8 ones
* (Config::act_i8); one format for all of them, since they share the activation pairs. This can
* only change acceptance.
*
* The codebooks 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.
@@ -135,6 +138,14 @@ struct Dspark {
int64_t top_k = 0; /* candidates the Markov walk re-ranks */
int64_t window = 0; /* sliding attention width, 0 for none */
int causal = 0;
/* The drafter's linears are served at i8a8h (DenseFP8::w8h: IQ8R, or a rotated int8 or
* narrower form at group 128), learned by the plugin from `probe_i8` before it declares the
* activation pairs: they are then int8 codes with one f32 scale per (row, act_g8), written
* by had_quant_act_i8g and the rotating norm. Every linear must agree. `fc_mapped`:
* probe_i8 made `dspark.fc.weight`'s name map. */
bool act_i8 = false;
int64_t act_g8 = RAD_FP8_BLOCK;
bool fc_mapped = false;
/* Every row predicts, so `block`, not `block - 1` (see ROW ALIGNMENT). */
int64_t steps() const { return block; }
};
@@ -149,7 +160,10 @@ struct Dspark {
* 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] */
/* The codes and scales the linears read: e4m3 | f32 [.., /128], or with Config::act_i8
* i8 | f32 [.., /act_g8]. The same holds for the three ActFP8 pairs below, whose `q` and
* `s` are then the int8 pair. */
rad_buf srcq = 0, srcs = 0;
rad_buf cq = 0, cs = 0;
/* ---- the query pass, `block` rows per sequence */
@@ -235,6 +249,18 @@ struct Dspark {
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
rad_op op_sel = 0;
/* Whether the container's drafter is served at i8a8h and at which scale group, from its `fc`,
* whose name map this makes (set Config::fc_mapped). Asked before the activation pairs are
* declared, since it decides their dtype and scale grid. */
static int probe_i8(RadBuilder* b, Names& nm, const char* ck, bool* i8, int64_t* g8) {
const char* fwn = nm.f("dspark.fc.weight");
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
RadEncoding fe{};
*i8 = weight_enc(b, fwn, &fe) && linear_is_w8h(fe);
*g8 = *i8 ? linear_w8h_group(fe) : (int64_t)RAD_FP8_BLOCK;
return RAD_OK;
}
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
const char* ck_lm, const char* ck_lm_alt, const Wire& wire);
@@ -274,10 +300,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
srows = g.max_seqs * cfg.steps();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
/* The linears read the activation pairs the plugin declared: int8 ones take rotated int8
* weights (cfg.act_i8), E4M3 ones block fp8 or MXFP4. */
w_fc.w8h_ok = cfg.act_i8;
for (int i = 0; i < MAX_LAYERS; ++i)
w_q[i].w8h_ok = w_k[i].w8h_ok = w_v[i].w8h_ok = w_o[i].w8h_ok = w_gu[i].w8h_ok =
w_dn[i].w8h_ok = cfg.act_i8;
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dspark.fc"), g.n_embd, cfg.n_taps * g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
{ nm.ckpt("%s.fc.weight", ck) }));
{ nm.ckpt("%s.fc.weight", ck) }, {}, cfg.fc_mapped));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
@@ -379,19 +412,34 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
/* ---------------------------------------------------------------- the context pass
*
* 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",
* Every linear is a DenseFP8 GEMM over the pair its quantiser writes: `quant_act_fp8` codes
* for block fp8 or MXFP4, had_quant_act_i8g's at the weights' scale group for a rotated int8
* drafter (cfg.act_i8). The linears read one activation pair, so they are all i8a8h forms at
* one group or none is. There is no `fp8a16` band: that kernel is M <= 1, and neither pass
* runs at one row. */
const char* const qop = cfg.act_i8 ? "had_quant_act_i8g" : "quant_act_fp8";
const int64_t qgr = cfg.act_i8 ? cfg.act_g8 : (int64_t)RAD_FP8_BLOCK;
{
auto fits = [&](const DenseFP8& d) {
return d.w8h == cfg.act_i8 && (!d.w8h || d.g8 == cfg.act_g8);
};
bool same = fits(w_fc);
for (int64_t l = 0; l < g.n_layer; ++l)
same = same && fits(w_q[l]) && fits(w_k[l]) && fits(w_v[l]) && fits(w_o[l]) &&
fits(w_gu[l]) && fits(w_dn[l]);
if (!same) {
fprintf(stderr, "radiance: the drafter's linears are not all rotated int8 at one scale "
"group or all block fp8 / MXFP4; they read one activation pair, so the "
"recipe must give them one format\n");
return RAD_E_DTYPE;
}
}
op_qsrc = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
RAD_INT("K", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_fc.w, w_fc.s)),
{w.srcq, w.srcs}, {w.c});
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
* written. */
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
@@ -401,27 +449,17 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.c});
/* 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",
op_qc = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.c}, {w.cq, w.cs});
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* 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),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.cq, w.cs}, {w.ck});
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.cq, w.cs}, {w.cv});
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),
@@ -468,7 +506,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
{w.x}, {w.x});
/* 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
* NormQuantFP8 wraps), or its rotating int8 twin `rmsnorm_had_quant_i8g` for a rotated int8
* drafter, which takes the same operands. Layer 0 has no delta to fold, each later norm folds the previous
* block's delta, and op_outnorm folds the last into the final norm, so there is no `add` op.
* The final norm's fp8 output is unused (the head runs its own i8 quantiser), a few KiB of
* waste that saves a launch: libr4d has no plain `rmsnorm_add` row.
@@ -478,9 +517,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
* stream as `x` and no residual. `residual` is INOUT, so it is in both the read and write sets;
* otherwise the planner could reorder a reader in front of it. */
auto decl_norm = [&](rad_weight gain, bool fold) -> rad_op {
rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
rad_op h = RAD_OP(b, cfg.act_i8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
RAD_F64("eps", g.eps), RAD_INT("group", qgr),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(gain));
if (!h) return 0;
@@ -490,9 +529,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
rad_op_writes(b, h, wr, fold ? 4 : 3);
return h;
};
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
op_qat = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn.x}, {w.attn.q, w.attn.s});
if (!op_qat) return RAD_E_INVAL;
@@ -508,24 +547,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
const int i = (int)l;
op_anorm[i] = decl_norm(w_anorm[i], i != 0);
if (!op_anorm[i]) return RAD_E_INVAL;
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
{w.h.q, w.h.s}, {w.q});
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.h.q, w.h.s}, {w.k});
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.h.q, w.h.s}, {w.v});
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h.q, w.h.s}, {w.q});
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.k});
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.h.q, w.h.s}, {w.v});
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
@@ -538,28 +562,15 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.k});
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
{w.attn.q, w.attn.s}, {w.h.x});
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.attn.q, w.attn.s}, {w.h.x});
op_fnorm[i] = decl_norm(w_fnorm[i], true);
if (!op_fnorm[i]) return RAD_E_INVAL;
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
{w.h.q, w.h.s}, {w.gate_up});
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),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
{w.ffn.q, w.ffn.s}, {w.h.x});
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h.q, w.h.s}, {w.gate_up});
/* The fold is an fp8a8 tile, so any other gate_up takes the pair. */
if (!w_gu[i].mx && !w_gu[i].m2x && !w_gu[i].w8h)
op_gug[i] = decl_gated_fold(b, qrows, 2 * g.n_ff, g.n_embd, w_gu[i].w, w_gu[i].s,
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s}, &gated_rows);
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffn.q, w.ffn.s}, {w.h.x});
}
op_qrope = rw(b, decl_rotary(b, g, "rope",
@@ -588,9 +599,9 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ffn.x});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
op_qff = rw(b, RAD_OP(b, qop,
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", qgr), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.ffn.x}, {w.ffn.q, w.ffn.s});
/* One collective, issued after both the out and the down projection (same shape, same buffer).
@@ -687,16 +698,16 @@ inline void Dspark::context(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.c, T), RAD_NONE, RAD_NONE);
brows(w.c, T), RAD_NONE, w_fc.bref());
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
@@ -735,11 +746,11 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
* quantises; at layer 0 it norms the embedding. */
issue_norm(op_anorm[i], i != 0, w_anorm[i], T);
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
@@ -757,7 +768,7 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
brows(w.attn.x, T));
RAD_ISSUE_N(c, op_qat, T, brows(w.attn.x, T), brows(w.attn.q, T), brows(w.attn.s, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.attn.q, T), brows(w.attn.s, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, w_o[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
/* ---- the feed-forward, behind the same fused norm-add-quantise */
@@ -769,12 +780,12 @@ inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
} else {
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h.q, T), brows(w.h.s, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
RAD_NONE);
w_gu[i].bref());
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn.x, T));
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn.x, T), brows(w.ffn.q, T), brows(w.ffn.s, T));
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffn.q, T), brows(w.ffn.s, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, w_dn[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
}
+958
View File
@@ -0,0 +1,958 @@
/* rad_block_dspark_bf16.h -- the DSpark drafter over bf16 weights, at the widths a Spark layer
* uses: a few plain attention layers that denoise a whole block of masked positions in one pass,
* conditioned on the trunk's residual stream at a handful of layers, with a rank-N Markov head
* over the target's own output table.
*
* ============================== WHY A SECOND DSPARK BLOCK ==============================
*
* rad_block_dspark.h is the same drafter shape for a block-fp8 release: its linears are DenseFP8
* behind `quant_act_fp8`, its feed-forward is `silu_mul`, its norms carry q/k gains, and its draft
* head is a 2-bit copy of the target's. The published Spark drafts (`dflash` GGUFs, and the HF
* Spark drafter releases behind them) ship the other way: bf16 linears, no q/k norms, one sigmoid
* gate a head on the attention output, exact-erf GELU, one RMS gain per tap, and a sliding window.
* Those are different ops, not different parameters, so this block declares its own graph and
* uses an explicit anchor-window attention op and a full-vocabulary Markov selector so neither
* semantic distinction is silently folded into the generic per-row window or candidate-lattice ops.
*
* Nothing here is quantised. The drafter is 624M parameters read whole a draft pass, so bf16 costs
* 1.2 GiB of residency and one extra weight pass a step; quantising it is a separate measurement
* (it can only move acceptance, since every draft is verified by the target).
*
* ============================== THE FORWARD PASS ==============================
*
* The reference is llama.cpp's `llama_model_dflash::graph<false>` (XHToken/llama.cpp
* 22c0ae1871b, the branch the Spark draft cards name), which mirrors the HF export:
*
* tap(l) = rmsnorm(residual after trunk layer l) * fc_norm[l] one gain row per tap
* ctx = rmsnorm(fc(concat_l tap(l))) hidden_norm
* per draft layer (x5):
* h_n = input_layernorm(h)
* q,k,v = q_proj/k_proj/v_proj(h_n); k_ctx, v_ctx = k_proj/v_proj(ctx)
* rope(q, k); attention over [the layer's context K/V, this block] non-causally,
* inside a `window` positions
* h += o_proj(sigmoid(g_proj(h)) * attn) one gate a head, no q/k norms
* h += mlp(post_attention_layernorm(h)) gelu(gate) * up, then down
* logits = target.lm_head(output_norm(h)) + markov_w2 @ markov_w1[prev]
*
* The two projections of `ctx` are the drafter's own k_proj and v_proj, one pair per layer, and
* they run over every committed token; the drafter's layers never see the context rows. That is
* the context pass below, and the block above is the query pass -- the same split
* rad_block_dspark.h makes, and the same `RAD_DRAFT_BLOCK` drive.
*
* ============================== THE TAPS ARE NORMED, NOT JUST READ ==================
*
* `fc_norm` is [n_taps, n_embd]: the residual entering each tap layer is normed with its own gain
* before the concatenation, so `fc` sees n_taps unit-scaled streams instead of one sum whose
* magnitudes the trunk happens to have. One `rmsnorm` per tap over that tap's column slice of the
* tap buffer, into the same slice layout of a normed copy; `fc` then reads one contiguous
* [n_taps * n_embd] row.
*
* ============================== THE SHARED ANCHOR WINDOW ==========================
*
* The pinned llama.cpp oracle increments the configured history from 512 to 513 and repeats the
* anchor row's mask for every row in the denoising block. `attn_paged_anchor_window` implements
* that exact predicate: every row sees keys through the end of the staged context whose absolute
* position is less than 513 behind the anchor. The query row does not move the lower cutoff. The
* same 513-token width is passed to the KV group and scheduler, so rollback, cache recycling and
* block staging all retain the exact history the drafter reads.
*
* ============================== ROW ALIGNMENT ==============================
*
* Every row predicts, the anchor included (`dflash.sample_from_anchor`, which the GGUF import
* refuses when false): row j of [anchor, MASK x (block-1)] proposes the token at the anchor's
* position plus j + 1, so `steps()` is `block` and the head runs over all the block's rows. The
* core stages the block against `RadDrafterDecl::block` and runs the head over the last `depth`
* rows, which covers this and Dflash2's shift-by-one convention (abi/rad_builder.h).
*
* ============================== THE MARKOV HEAD ==============================
*
* The draft logits get a learned bigram bias
*
* score[l, token] = logits[l, token] + markov_w2[token] . markov_w1[prev(l)]
* prev(0) = the anchor; prev(l) = the greedy token chosen at l - 1
*
* `dflash_markov_greedy` scans the full vocabulary at every position and greedily chooses the
* largest biased score, following the structure of the pinned reference's serial Markov walk.
* Base logits are F32; reduction order and tie behavior can still differ from the reference. It
* does not prune to the base head's top K, use a joint-path heap, or apply confidence to logits.
*
* The confidence head (`conf_proj`, one sigmoid a position predicting acceptance) is imported and
* ignored: it exists to let a serving loop cut the block short, this engine's depth is fixed at
* declare, and it changes nothing the drafter proposes.
*
* ============================== PRECISION ==============================
*
* bf16 for every weight and activation except the residual stream, which is f32 exactly as the
* Spark trunk keeps it (rad_block_dspark.h's fp8 graphs fold the residual into the norm; here the
* norms read the f32 stream and write bf16, and `add` keeps the sum in f32). The reference runs
* bf16 weights against an f32 residual, so rounding the drafter's stream to bf16 would be a third
* opinion on every layer's output for no saved bytes worth having at `block` rows.
*
* ============================== NOT DONE ==============================
*
* The head and full-vocabulary Markov scan are read replicated, so a vocab-sharded deployment
* cannot draft with them. The plugin refuses `world > 1` rather than scoring only one rank's
* slice of the vocabulary.
*
* The drafter's linears are four GEMMs and one attention a layer with no folding: the norms are
* plain `rmsnorm`, not a fused norm-add-quantise, because nothing here quantises. At seven rows
* a pass the launches, not the bytes, are the cost.
*/
#ifndef RAD_BLOCK_DSPARK_BF16_H
#define RAD_BLOCK_DSPARK_BF16_H
#include "rad_arch.h"
namespace rad {
namespace arch {
/* The builder refuses a declaration it cannot serve and says why in its own words; this names which
* handle did not come back, so that message reads against a line of this file. An op that resolves
* to no kernel is recorded and handed back null -- it is only an error if the block issues it -- so
* without this a missing kernel surfaces as a bare "invalid argument" at startup. */
#define DS_REFUSED(...) ::rad::arch::drafter_refused({ __VA_ARGS__ })
inline int drafter_refused(std::initializer_list<const char*> what) {
std::string list;
for (const char* w : what) { if (!list.empty()) list += ", "; list += w; }
std::fprintf(stderr, "DSpark drafter: the builder gave no handle for %s\n", list.c_str());
return RAD_E_INVAL;
}
struct DsparkBF16 {
enum { MAX_LAYERS = 8 };
/* The drafter's config beyond its geometry. Everything here comes from the container's
* `draft.` keys; nothing is defaulted quietly, because a silently ignored gate or window only
* moves acceptance, which is the one number the user cannot see. */
struct Config {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* noise rows a sequence, and drafts (one per row) */
int64_t rank = 0; /* markov_rank: the codebooks' width */
int64_t window = 0; /* reference's anchor-aligned n_swa (configured history + 1) */
int64_t rot = 0; /* rotary dimensions a head; 0 for all of head_dim */
int causal = 0;
int tap_norm = 0; /* `fc_norm`: one RMS gain a tap before the concatenation */
int qk_norm = 0; /* per-head q/k gains, and no output gate */
int gate = 0; /* one sigmoid gate a head on the attention output */
const char* act = "gelu"; /* the feed-forward's activation */
int64_t steps() const { return block; } /* every row predicts */
};
struct Wire {
/* ---- the context pass, one row per committed token */
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
rad_buf srcn = 0; /* [max_tok, n_taps * n_embd] each tap normed, same layout */
rad_buf c = 0, cn = 0; /* [max_tok, n_embd] fc output and separately normed context */
rad_buf ck = 0, ckn = 0; /* [max_tok, kv_dim] projected and optionally normed K */
rad_buf cv = 0; /* [max_tok, kv_dim] and its V */
/* ---- the query pass, `block` rows per sequence */
rad_buf x = 0; /* [qrows, n_embd] f32 the drafter's residual stream */
rad_buf delta = 0; /* [qrows, n_embd] f32 the block a projection just wrote */
rad_buf h = 0; /* [qrows, n_embd] bf16 the normed stream, and every linear's output */
rad_buf q = 0, k = 0, v = 0, qn = 0, kn = 0;
rad_buf gate = 0, gaten = 0; /* [qrows, n_head] projection and sigmoid */
rad_buf attn = 0, attng = 0; /* [qrows, q_dim] attention and gated attention */
rad_buf gate_up = 0; rad_buf ff = 0;
/* ---- the head and the walk, one row per draft position */
rad_buf dlog = 0; /* [srows, n_vocab] f32 full-vocabulary draft logits */
rad_buf best_score = 0; /* [max_seqs, ceil(n_vocab/64)] f32 partial argmax scores */
rad_buf best_token = 0; /* [max_seqs, ceil(n_vocab/64)] i32 partial argmax ids */
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
};
Geom g{}; /* the drafter's geometry, not the trunk's */
Config cfg{};
Wire w{};
int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */
int64_t qrows = 0, crows = 0, srows = 0;
rad_kvgroup kv = 0;
/* ---- model-scope weights */
rad_weight w_fc = 0, w_hnorm = 0, w_norm = 0;
rad_weight w_fcnorm[MAX_LAYERS] = {}; /* one row of `fc_norm` a tap */
rad_weight w_mk1 = 0, w_mk2 = 0; /* markov_w1 (pred), markov_w2 (succ) */
rad_weight w_tok = 0; /* the target's embedding table */
rad_weight w_head = 0; /* the target's output table */
/* ---- per-layer weights */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
rad_weight w_q[MAX_LAYERS] = {}, w_k[MAX_LAYERS] = {}, w_v[MAX_LAYERS] = {}, w_o[MAX_LAYERS] = {};
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}, w_gate[MAX_LAYERS] = {};
rad_weight w_gu[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
/* ---- the context pass */
rad_op op_tapn[MAX_LAYERS] = {}; /* one per tap, not per layer */
rad_op op_cfc = 0, op_cnorm = 0;
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
rad_op op_crope = 0, op_cstore = 0;
/* ---- the query pass. The weightless ops are declared once and issued per layer; the ones
* with weights are per layer, since a weight's prefetch interval and residency class come
* from the op that declares it. */
rad_op op_embed = 0, op_widen = 0, op_add = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}, op_gp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {}, op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_widen2 = 0, op_widen3 = 0;
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
rad_op op_sig = 0, op_gate_heads = 0, op_act = 0;
/* ---- the head and the walk */
rad_op op_dlogits = 0, op_markov = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck, const char* ck_head,
const Wire& wire);
/* The context pass, one row per committed token. */
void context(RadCtx* c, const RadBatch* batch) const;
/* The query pass, the head and the Markov walk, `block` rows per sequence. */
void step(RadCtx* c, const RadBatch* batch) const;
private:
int64_t q_dim() const { return g.n_head * g.head_dim; }
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
};
/* ------------------------------------------------------------------------------ declare */
inline int DsparkBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
int base_layer, rad_kvgroup group, rad_weight tok_embd,
const char* ck, const char* ck_head, const Wire& wire) {
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
if (!ck || !ck_head || !w_tok) return DS_REFUSED("ck", "ck_head", "w_tok");
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: the bf16 DSpark drafter has %lld layers; this block carries at "
"most %d\n", (long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.n_taps <= 0 || cfg.n_taps > MAX_LAYERS || cfg.block < 2 || cfg.rank <= 0)
return RAD_E_INVAL;
if (cfg.qk_norm && cfg.gate) {
fprintf(stderr, "radiance: the drafter declares both per-head q/k norms and a per-head "
"output gate; no published drafter ships both, and this block would have "
"to guess which one the checkpoint trained with\n");
return RAD_E_UNSUPPORTED;
}
/* The full-vocabulary head and Markov scan are read replicated; partial-vocabulary drafting
* would need an exact distributed argmax and replicated codebook access. */
if (g.world > 1) {
fprintf(stderr, "radiance: the bf16 DSpark drafter reads the target's whole output table "
"and cannot draft at tp %d; run it at tp 1\n", g.world);
return RAD_E_UNSUPPORTED;
}
const int64_t qd = q_dim(), kvd = kv_dim(), E = g.n_embd;
crows = g.max_tok;
qrows = g.max_seqs * cfg.block;
if (qrows > g.max_tok) qrows = g.max_tok;
srows = g.max_seqs * cfg.steps(); /* every row predicts */
if (qrows <= 0 || srows <= 0 || cfg.rot < 0 || cfg.rot > g.head_dim || cfg.rot % 2)
return RAD_E_INVAL;
const int64_t rot = cfg.rot ? cfg.rot : g.head_dim;
/* One op declaration per kernel shape, shared by the layers: `rmsnorm`'s and `gemm_nt`'s
* parameters are geometry, and only the weights differ per layer. */
auto gemm = [&](int64_t rows, int64_t n, int64_t k, rad_weight wt, rad_buf x, rad_buf y) {
return rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n),
RAD_INT("K", k), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(wt)),
{x}, {y});
};
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.fc.weight"), nm.ckpt("%s.fc.weight", ck)));
w_fc = decl_w(b, nm.f("dspark.fc.weight"), RAD_BF16, {E, cfg.n_taps * E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
nm.ckpt("%s.hidden_norm.weight", ck)));
w_hnorm = decl_w(b, nm.f("dspark.hidden_norm.weight"), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_fc || !w_hnorm || !w_norm) return DS_REFUSED("w_fc", "w_hnorm", "w_norm");
/* `fc_norm` is [n_taps, n_embd]: one gain row a tap, read as that tap's slice. */
if (cfg.tap_norm) {
const char* src = nm.ckpt("%s.fc_norm.weight", ck);
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
RAD_ARCH_TRY(map_rows(b, nm.f("dspark.fc_norm.%d.weight", i),
{ { src, (int)t, 1 } }));
w_fcnorm[i] = decl_w(b, nm.f("dspark.fc_norm.%d.weight", i), RAD_BF16, {E},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_fcnorm[i]) return DS_REFUSED("w_fcnorm[i]");
}
}
/* The Markov codebooks, bf16, replicated over the whole vocabulary: both are [vocab, rank], so
* `w2 @ w1[prev]` is `<w1[prev], w2[token]>`. RAD_ACCESS_VOCAB: each walk position reads one
* predecessor row and scans every successor row. */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"),
nm.ckpt("%s.markov_head.markov_w1.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
nm.ckpt("%s.markov_head.markov_w2.weight", ck)));
w_mk1 = decl_w(b, nm.f("dspark.markov_w1"), RAD_BF16, {g.n_vocab_all, cfg.rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
if (!w_mk1 || !w_mk2) return DS_REFUSED("w_mk1", "w_mk2");
/* The target's output table under the drafter's own name: one stored tensor, two arch weights,
* as rad_block_dspark.h does for its 2-bit copy. bf16 and replicated here, since the drafter
* reads it as the head its full-vocabulary walk scores (see NOT DONE for sharding). */
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.head.weight"), ck_head));
w_head = decl_w(b, nm.f("dspark.head.weight"), RAD_BF16, {g.n_vocab_all, E},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
if (!w_head) return DS_REFUSED("w_head");
/* ---------------------------------------------------------------- per-layer weights
*
* One name map and one declaration a weight, spelled out: the list is the readable form of
* which checkpoint tensor feeds which matmul, and a drafter has few enough of them that a
* table would only hide it. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const RadWeightGroup grp = grp_layer(first_layer + i);
/* A norm gain: f32, read whole, never sharded. */
auto norm_w = [&](rad_weight* out, const char* suffix, const char* from,
std::initializer_list<int64_t> shape) -> int {
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
RAD_ARCH_TRY(map_copy(b, name, nm.ckpt("%s.layers.%d.%s", ck, i, from)));
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
return *out ? RAD_OK : RAD_E_INVAL;
};
/* A linear: bf16. More than one source is a concatenation, whose row parts say where each
* piece begins (RadWeightDecl::row_parts), so `act_mul` can read [gate | up] as one
* weight. */
auto lin_w = [&](rad_weight* out, const char* suffix,
std::initializer_list<const char*> srcs,
std::initializer_list<int64_t> shape,
std::initializer_list<int64_t> parts = {}) -> int {
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
if (srcs.size() > 1) RAD_ARCH_TRY(map_concat(b, name, srcs));
else RAD_ARCH_TRY(map_copy(b, name, *srcs.begin()));
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp, 0,
parts);
return *out ? RAD_OK : RAD_E_INVAL;
};
#define SRC(path) nm.ckpt("%s.layers.%d." path, ck, i)
RAD_ARCH_TRY(norm_w(&w_anorm[i], "attn_norm.weight", "input_layernorm.weight", {E}));
RAD_ARCH_TRY(norm_w(&w_fnorm[i], "ffn_norm.weight", "post_attention_layernorm.weight", {E}));
RAD_ARCH_TRY(lin_w(&w_q[i], "attn_q", { SRC("self_attn.q_proj.weight") }, {qd, E}));
RAD_ARCH_TRY(lin_w(&w_k[i], "attn_k", { SRC("self_attn.k_proj.weight") }, {kvd, E}));
RAD_ARCH_TRY(lin_w(&w_v[i], "attn_v", { SRC("self_attn.v_proj.weight") }, {kvd, E}));
RAD_ARCH_TRY(lin_w(&w_o[i], "attn_output", { SRC("self_attn.o_proj.weight") }, {E, qd}));
RAD_ARCH_TRY(lin_w(&w_gu[i], "ffn_gate_up",
{ SRC("mlp.gate_proj.weight"), SRC("mlp.up_proj.weight") },
{2 * g.n_ff, E}, { g.n_ff, g.n_ff }));
RAD_ARCH_TRY(lin_w(&w_dn[i], "ffn_down", { SRC("mlp.down_proj.weight") },
{E, g.n_ff}));
if (cfg.gate)
RAD_ARCH_TRY(lin_w(&w_gate[i], "attn_gate", { SRC("self_attn.g_proj.weight") },
{g.n_head, E}));
if (cfg.qk_norm) {
RAD_ARCH_TRY(norm_w(&w_qn[i], "attn_q_norm.weight", "self_attn.q_norm.weight",
{g.head_dim}));
RAD_ARCH_TRY(norm_w(&w_kn[i], "attn_k_norm.weight", "self_attn.k_norm.weight",
{g.head_dim}));
}
#undef SRC
}
/* Non-causal: every query row sees its whole block and the context the trunk committed
* (`causal` comes from `draft.is_causal`). Declared before both kv_stores, which read the
* resolved `block_size` back with rad_kv_block_size(); before it, that returns zero. */
op_attn = rw(b, RAD_OP(b, cfg.window > 0 ? "attn_paged_anchor_window" : "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.qn : w.q}, {w.attn});
if (!op_attn) return DS_REFUSED("op_attn");
/* ---------------------------------------------------------------- the context pass
*
* One row per committed token, run once per trunk step: the taps become the drafter's own K
* and V. Nothing here is per query row, so its cost follows the trunk's token count, not the
* block's. */
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
op_tapn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_fcnorm[i])),
{w.src}, {w.srcn});
if (!op_tapn[i]) return DS_REFUSED("op_tapn[i]");
}
op_cfc = gemm(crows, E, cfg.n_taps * E, w_fc, w.srcn, w.c);
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.cn});
if (!op_cfc || !op_cnorm) return DS_REFUSED("op_cfc", "op_cnorm");
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
* and residency class. */
op_ck[i] = gemm(crows, kvd, E, w_k[i], w.cn, w.ck);
op_cv[i] = gemm(crows, kvd, E, w_v[i], w.cn, w.cv);
if (!op_ck[i] || !op_cv[i]) return DS_REFUSED("op_ck[i]", "op_cv[i]");
if (cfg.qk_norm) {
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_kn[i])),
{w.ck}, {w.ckn});
if (!op_cknorm[i]) return DS_REFUSED("op_cknorm[i]");
}
}
/* K-only rope: `rope` rotates the first n_head + n_head_kv heads, so a K-only tensor is
* n_head = n_head_kv, n_head_kv = 0. Weightless, so one op serves every layer. Each context
* row is rotated by its own absolute position, as the reference's single concatenated rope
* does. */
op_crope = rw(b, decl_rope(b, g, crows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
{cfg.qk_norm ? w.ckn : w.ck}, {cfg.qk_norm ? w.ckn : w.ck});
op_cstore = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.ckn : w.ck, w.cv}, {});
if (!op_crope || !op_cstore) return DS_REFUSED("op_crope", "op_cstore");
/* ---------------------------------------------------------------- the query pass
*
* `block` rows per sequence, through the drafter's layers. The residual stream is f32 and the
* linears read bf16, exactly as the trunk keeps them: `rmsnorm` reads the stream and writes the
* activations, `cast` widens a projection's output, and `add` keeps the sum in f32. */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{}, {w.h});
op_widen = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{w.h}, {w.x});
/* One widen and one add serve both residual sites a layer: same shapes, same buffers. */
op_widen2 = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{w.h}, {w.delta});
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{w.x, w.delta}, {w.x});
if (!op_embed || !op_widen || !op_widen2 || !op_add)
return DS_REFUSED("op_embed", "op_widen", "op_widen2", "op_add");
/* Invariant: the norms are declared where step() issues them. Declaration order is the buffer
* planner's liveness (core/build/rad_bufplan.cpp), and the stream `x` lives over the ops that
* touch it: each layer's two norms in the loop, the final one after everything the layers
* issue. Declared up front, the stream's lifetime would end before the layers and the planner
* could overlay a feed-forward temporary on it. */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_anorm[i])),
{w.x}, {w.h});
op_qp[i] = gemm(qrows, qd, E, w_q[i], w.h, w.q);
op_kp[i] = gemm(qrows, kvd, E, w_k[i], w.h, w.k);
op_vp[i] = gemm(qrows, kvd, E, w_v[i], w.h, w.v);
op_op[i] = gemm(qrows, E, qd, w_o[i], cfg.gate ? w.attng : w.attn, w.h);
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_fnorm[i])),
{w.x}, {w.h});
op_gu[i] = gemm(qrows, 2 * g.n_ff, E, w_gu[i], w.h, w.gate_up);
op_dn[i] = gemm(qrows, E, g.n_ff, w_dn[i], w.ff, w.h);
if (!op_anorm[i] || !op_qp[i] || !op_kp[i] || !op_vp[i] || !op_op[i] || !op_fnorm[i] ||
!op_gu[i] || !op_dn[i])
return RAD_E_INVAL;
if (cfg.qk_norm) {
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_qn[i])),
{w.q}, {w.qn});
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.kn});
if (!op_qn[i] || !op_kn[i]) return DS_REFUSED("op_qn[i]", "op_kn[i]");
}
if (cfg.gate) {
op_gp[i] = gemm(qrows, g.n_head, E, w_gate[i], w.h, w.gate);
if (!op_gp[i]) return DS_REFUSED("op_gp[i]");
}
}
op_qrope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head, 0, rot, "neox"),
{cfg.qk_norm ? w.qn : w.q}, {cfg.qk_norm ? w.qn : w.q});
op_krope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
{cfg.qk_norm ? w.kn : w.k}, {cfg.qk_norm ? w.kn : w.k});
op_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{cfg.qk_norm ? w.kn : w.k, w.v}, {});
/* The gate the trunk uses too: one sigmoid a head, then one scale a head's whole row. */
if (cfg.gate) {
op_sig = rw(b, RAD_OP(b, "sigmoid",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_head),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.gate}, {w.gaten});
op_gate_heads = rw(b, RAD_OP(b, "scale_rows",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
RAD_INT("n", g.head_dim), RAD_STR("act", "none"),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.attn, w.gaten}, {w.attng});
if (!op_sig || !op_gate_heads) return DS_REFUSED("op_sig", "op_gate_heads");
}
/* `act_mul` with the activation the drafter was trained with: exact-erf gelu for the Spark
* drafts (`hidden_activation: gelu`), silu for a Qwen3-shaped one. `gelu_mul` is the tanh
* approximation and is not what the reference runs. */
op_act = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("act", cfg.act), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ff});
op_outnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
if (!op_qrope || !op_krope || !op_store || !op_act || !op_outnorm)
return DS_REFUSED("op_qrope", "op_krope", "op_store", "op_act", "op_outnorm");
/* ---------------------------------------------------------------- the head and full-vocabulary walk
*
* Every row predicts, so the head scores all `steps` rows, anchor included. The row order is
* sequence-major, which is the selector's [sequence, position, vocabulary] contract. The
* greedy Markov op scans all vocabulary entries at every position and feeds each winning id
* into the next position's bigram bias.
*/
op_dlogits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_head)),
{w.h}, {w.dlog});
op_markov = rw(b, RAD_OP(b, "dflash_markov_greedy_f32",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
RAD_INT("steps", cfg.steps()), RAD_INT("rank", cfg.rank),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", cfg.block),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_mk1, w_mk2)),
{w.dlog}, {w.best_score, w.best_token, w.tokens});
if (!op_dlogits || !op_markov) return DS_REFUSED("op_dlogits", "op_markov");
return RAD_OK;
}
/* ------------------------------------------------------------------------------ the context pass */
inline void DsparkBF16::context(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int64_t E = g.n_embd;
/* Each tap's slice of the residual the trunk just tapped, normed with its own gain into the
* same slice layout of one row-per-token buffer. */
for (int64_t t = 0; t < cfg.n_taps; ++t) {
const int i = (int)t;
if (!cfg.tap_norm) continue;
RAD_ISSUE_N(c, op_tapn[i], T, bcol(w.src, t * E, E, T), RAD_W(w_fcnorm[i]),
bcol(w.srcn, t * E, E, T));
}
RAD_ISSUE_N(c, op_cfc, T, cfg.tap_norm ? brows(w.srcn, T) : brows(w.src, T), RAD_W(w_fc),
brows(w.c, T));
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.cn, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cn, T), RAD_W(w_k[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cn, T), RAD_W(w_v[i]), brows(w.cv, T));
if (cfg.qk_norm)
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
brows(w.ckn, T));
RAD_ISSUE_N(c, op_crope, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_cstore, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), brows(w.cv, T),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
}
}
/* ------------------------------------------------------------------------------ the query pass */
inline void DsparkBF16::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
/* The block the core staged: the token the sampler just chose, then the mask token in every
* unfilled slot. */
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.h, T));
RAD_ISSUE_N(c, op_widen, T, brows(w.h, T), brows(w.x, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h, T), RAD_W(w_q[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h, T), RAD_W(w_k[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h, T), RAD_W(w_v[i]), brows(w.v, T));
if (cfg.qk_norm) {
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.qn, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]),
brows(w.kn, T));
}
RAD_ISSUE_N(c, op_qrope, T, brows(cfg.qk_norm ? w.qn : w.q, T), pos);
RAD_ISSUE_N(c, op_krope, T, brows(cfg.qk_norm ? w.kn : w.k, T), pos);
/* The block's own K and V go into the cache past `seqused`, which is how every row of the
* block attends to every other; the next context pass overwrites them, which is the
* reference's `crop(start)`. */
RAD_ISSUE_N(c, op_store, T, brows(cfg.qk_norm ? w.kn : w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
kv_cache(kv, first_layer + i));
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(cfg.qk_norm ? w.qn : w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T));
if (cfg.gate) {
/* One gate a head, applied to that head's whole row of the attention output, before
* o_proj. View [rows, heads * dim] and [rows, heads] as one row a head. */
RAD_ISSUE_N(c, op_gp[i], T, brows(w.h, T), RAD_W(w_gate[i]), brows(w.gate, T));
RAD_ISSUE_N(c, op_sig, T, brows(w.gate, T), brows(w.gaten, T));
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, w.attn), RAD_BF16, T * g.n_head,
g.head_dim);
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, w.gaten), RAD_BF16, T * g.n_head, 1);
const RadOperand gated = RAD_P_T2(rad_buf_ptr(c, w.attng), RAD_BF16, T * g.n_head,
g.head_dim);
RAD_ISSUE_N(c, op_gate_heads, T * g.n_head, heads, gates, RAD_NONE, gated);
}
RAD_ISSUE_N(c, op_op[i], T, brows(cfg.gate ? w.attng : w.attn, T), RAD_W(w_o[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h, T), RAD_W(w_gu[i]), brows(w.gate_up, T));
RAD_ISSUE_N(c, op_act, T, bcol(w.gate_up, 0, g.n_ff, T),
bcol(w.gate_up, g.n_ff, g.n_ff, T), brows(w.ff, T));
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ff, T), RAD_W(w_dn[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
}
RAD_ISSUE_N(c, op_outnorm, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
/* The predicting rows, named by the scheduler through `out_ids`. */
const int64_t S = batch->n_out;
if (S <= 0) return;
RAD_ISSUE_N(c, op_dlogits, S, brows(w.h, S), RAD_W(w_head), brows(w.dlog, S));
RAD_ISSUE_N(c, op_markov, batch->n_seq, brows(w.dlog, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2),
brows(w.best_score, batch->n_seq), brows(w.best_token, batch->n_seq),
brows(w.tokens, batch->n_seq));
}
/* ================================================================== the trunk's side of it
*
* The taps, and one call a target plugin makes to put a drafter on. Both live here because both
* are the drafter's contract with the trunk: which residual streams it reads, where its blocks
* live, and how deep a proposal it makes. */
/* The residual streams a drafter reads, captured as the trunk passes them. */
struct DsparkTaps {
enum { MAX_TAPS = DsparkBF16::MAX_LAYERS };
int n = 0;
int layer[MAX_TAPS] = {}; /* the trunk layer whose OUTPUT is tapped */
rad_buf src = 0; /* [rows, n * n_embd] f32, one column slice a tap */
rad_op op = 0; /* the residual stream, copied into that slice */
/* Read `draft.target_layer_ids`, which names the layers whose output is tapped. Zero taps when
* the container carries no drafter, or one that reads no trunk stream. Out-of-range ids are
* dropped, not clamped: a drafter naming a layer this model lacks belongs to another target. */
int read(const RadModelMeta* meta, int64_t n_layer) {
n = 0;
const char* ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
if (!ids) ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
if (!ids) ids = rad_meta_gets(meta, "draft.gguf_target_layers", nullptr);
n = parse_layer_ids(ids, n_layer, layer, MAX_TAPS);
return n;
}
/* The copy that saves a tap. A drafter reads the trunk's own residual stream, which is f32
* here and stays f32: the widening the fp8 graphs do is theirs, not this one's. */
int declare(RadBuilder* b, Names& nm, const Geom& g, int64_t rows, rad_buf residual) {
if (n <= 0) return RAD_OK;
src = decl_b(b, nm.f("draft_src"), RAD_F32, {rows, (int64_t)n * g.n_embd});
if (!src) return DS_REFUSED("src");
/* Declared over the trunk's own residual buffer: the op's operand pair is the stream and a
* tap's slice, and every issue site passes the slice it is writing. */
op = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_STR("from", "f32"), RAD_STR("to", "f32")),
RAD_NOWEIGHTS),
{residual}, {src});
return op ? RAD_OK : RAD_E_INVAL;
}
/* The tap that follows trunk layer `l`, if any. Issued on prefill and decode alike: the
* drafter conditions on every committed token's residual stream. */
void step(RadCtx* c, rad_buf residual, int64_t rows, int64_t l, int64_t n_embd) const {
if (!op) return;
for (int t = 0; t < n; ++t)
if (layer[t] == l)
RAD_ISSUE(c, op, brows(residual, rows),
bcol(src, (int64_t)t * n_embd, n_embd, rows));
}
};
/* Put a DSpark drafter on a trunk: its config from the container's `draft.` keys, its own KV
* group, its graph, and the drafter declaration the core drives. `base_layer` is the absolute
* layer its first block takes, one past the trunk's last.
*
* Nothing is defaulted quietly. A `draft.` key that describes a drafter this file does not
* implement is refused by name, because a silently ignored gate, window or block length only moves
* acceptance -- the one number a user cannot see in the output.
*
* The plugin calls it last, after its own head and logits: a drafter's passes run after the whole
* trunk, and the buffer planner lays an op's lifetimes out in declaration order, so declaring it
* earlier would let a trunk temporary land on the stream the drafter is still reading. */
inline int declare_dspark(DsparkBF16* ds, DsparkBF16::Wire* w, rad_kvgroup* kv, RadBuilder* b,
Names& nm, const RadModelMeta* meta, const RadBuildCtx* ctx,
const Geom& target, const DsparkTaps& taps, int base_layer,
rad_weight tok_embd, const char* ck_head) {
Geom dg{};
RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DSpark"));
/* The width the drafter concatenates and projects is the trunk's, and `drafter_geom` keeps the
* target's -- so a draft that disagrees is a draft for another model, and its `fc` would be
* read at a shape it was not trained at. */
const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size",
rad_meta_geti(meta, "draft.dflash_config.hidden_size",
dg.n_embd));
if (want_embd != dg.n_embd) {
fprintf(stderr, "radiance: the drafter reads a %lld-wide trunk and this target is %lld "
"wide; they are not the same model\n", (long long)want_embd,
(long long)dg.n_embd);
return RAD_E_UNSUPPORTED;
}
DsparkBF16::Config c{};
c.n_taps = taps.n;
c.rank = rad_meta_geti(meta, "draft.markov_rank", 0);
c.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0;
c.tap_norm = rad_meta_geti(meta, "draft.fc_norm", 0) ? 1 : 0;
c.qk_norm = rad_meta_geti(meta, "draft.qk_norm", 0) ? 1 : 0;
c.gate = rad_meta_geti(meta, "draft.headwise_attn_output_gate", 0) ? 1 : 0;
const char* act = rad_meta_gets(meta, "draft.hidden_act", "silu");
c.act = (!std::strcmp(act, "gelu") || !std::strcmp(act, "none")) ? "gelu"
: (!std::strcmp(act, "silu")) ? "silu" : nullptr;
if (!c.act) {
fprintf(stderr, "radiance: the drafter's feed-forward is '%s'; this block runs exact-erf "
"gelu (what the Spark drafts train with) or silu, and the two are not the "
"same function\n", act);
return RAD_E_UNSUPPORTED;
}
const char* gate_mode = rad_meta_gets(meta, "draft.gate_attn_act_mode", "sigmoid");
if (c.gate && std::strcmp(gate_mode, "sigmoid")) {
fprintf(stderr, "radiance: the drafter gates its attention output with '%s'; this block "
"applies a sigmoid\n", gate_mode);
return RAD_E_UNSUPPORTED;
}
/* Every row predicts, the anchor included. Without it a block row's worth of proposals is
* missing and the head reads rows the drafter never filled. */
if (!rad_meta_geti(meta, "draft.sample_from_anchor", 1)) {
fprintf(stderr, "radiance: the drafter declares sample_from_anchor false, whose bonus "
"anchor slot this block has no rows for\n");
return RAD_E_UNSUPPORTED;
}
/* The reference applies the bigram bias to the full vocabulary before each greedy choice. */
if (c.rank <= 0 || c.rank % 32 || c.rank > 512) {
fprintf(stderr, "radiance: the drafter's Markov head has rank %lld; the walk that applies "
"the bigram bias takes a multiple of 32 up to 512\n", (long long)c.rank);
return RAD_E_UNSUPPORTED;
}
/* The block is both the number of noise rows and the number of drafts: every row, the anchor
* included, predicts the token after it, so the depth is `block_size` rather than the
* `block_size - 1` a DFlash2 container's is. A block-diffusion drafter is trained for one
* block length and has no partial block, so any other depth is refused. */
const int64_t trained = rad_meta_geti(meta, "draft.block_size", 0);
if (trained < 2) {
fprintf(stderr, "radiance: this drafter declares no draft.block_size; the number of masked "
"positions it denoises is not a number this engine may choose.\n");
return RAD_E_FORMAT;
}
if ((long long)ctx->max_spec != trained) {
fprintf(stderr, "radiance: the drafter was trained at block_size %lld, which is %lld draft "
"tokens, and this serve asks for %d. A block-diffusion drafter denoises a "
"fixed number of mask positions; run it at %lld.\n",
(long long)trained, (long long)trained, ctx->max_spec, (long long)trained);
return RAD_E_UNSUPPORTED;
}
c.block = trained;
/* The reference gives every row of the block the anchor's history. `window` is the configured
* number of preceding positions; llama.cpp sets n_swa to window + 1 and masks when
* anchor - key >= n_swa. Keep that exact width in attention, the KV group and scheduler. */
int64_t window = 0;
if (rad_meta_geti(meta, "draft.use_sliding_window", 0))
window = rad_meta_geti(meta, "draft.sliding_window", 0);
if (window < 0 || (window && window < c.block)) {
fprintf(stderr, "radiance: the drafter's %lld-token window does not cover the %lld-token "
"block it denoises\n", (long long)window, (long long)c.block);
return RAD_E_UNSUPPORTED;
}
if (window > 0 && window == INT64_MAX) return RAD_E_INVAL;
c.window = window > 0 ? window + 1 : 0; /* llama.cpp dflash: n_swa += 1 */
const double prf = rad_meta_getf(meta, "draft.partial_rotary_factor",
rad_meta_getf(meta,
"draft.rope_parameters.partial_rotary_factor", 1.0));
const double rot = (double)dg.head_dim * prf;
if (!(prf > 0.0) && prf != 0.0) {
fprintf(stderr, "radiance: the drafter's partial_rotary_factor is %g\n", prf);
return RAD_E_INVAL;
}
if (std::floor(rot) != rot || (int64_t)rot % 2 || rot > (double)dg.head_dim) {
fprintf(stderr, "radiance: the drafter rotates %g of %lld head dimensions\n", rot,
(long long)dg.head_dim);
return RAD_E_INVAL;
}
c.rot = (int64_t)rot ? (int64_t)rot : dg.head_dim;
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, c.window, base_layer, kv));
/* Activations: one row per committed token for the context pass, one row per block position
* for the query pass. Both are small; the drafter's cost is its weights. */
const int64_t qd = dg.n_head * dg.head_dim, kvd = dg.n_head_kv * dg.head_dim;
int64_t qr = dg.max_seqs * c.block;
if (qr > dg.max_tok) qr = dg.max_tok;
const int64_t sr = dg.max_seqs * c.steps();
DsparkBF16::Wire& dw = *w;
dw.src = taps.src;
dw.srcn = decl_b(b, nm.f("ds_srcn"), RAD_BF16, {dg.max_tok, c.n_taps * dg.n_embd});
dw.c = decl_b(b, nm.f("ds_c"), RAD_BF16, {dg.max_tok, dg.n_embd});
dw.cn = decl_b(b, nm.f("ds_cn"), RAD_BF16, {dg.max_tok, dg.n_embd});
dw.ck = decl_b(b, nm.f("ds_ck"), RAD_BF16, {dg.max_tok, kvd});
dw.cv = decl_b(b, nm.f("ds_cv"), RAD_BF16, {dg.max_tok, kvd});
if (c.qk_norm) dw.ckn = decl_b(b, nm.f("ds_ckn"), RAD_BF16, {dg.max_tok, kvd});
dw.x = decl_b(b, nm.f("ds_x"), RAD_F32, {qr, dg.n_embd});
dw.delta = decl_b(b, nm.f("ds_delta"), RAD_F32, {qr, dg.n_embd});
dw.h = decl_b(b, nm.f("ds_h"), RAD_BF16, {qr, dg.n_embd});
dw.q = decl_b(b, nm.f("ds_q"), RAD_BF16, {qr, qd});
dw.k = decl_b(b, nm.f("ds_k"), RAD_BF16, {qr, kvd});
dw.v = decl_b(b, nm.f("ds_v"), RAD_BF16, {qr, kvd});
if (c.qk_norm) {
dw.qn = decl_b(b, nm.f("ds_qn"), RAD_BF16, {qr, qd});
dw.kn = decl_b(b, nm.f("ds_kn"), RAD_BF16, {qr, kvd});
}
dw.gate = decl_b(b, nm.f("ds_gate"), RAD_BF16, {qr, dg.n_head});
dw.attn = decl_b(b, nm.f("ds_attn"), RAD_BF16, {qr, qd});
if (c.gate) {
dw.gaten = decl_b(b, nm.f("ds_gaten"), RAD_BF16, {qr, dg.n_head});
dw.attng = decl_b(b, nm.f("ds_attng"), RAD_BF16, {qr, qd});
}
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), RAD_BF16, {qr, 2 * dg.n_ff});
dw.ff = decl_b(b, nm.f("ds_ff"), RAD_BF16, {qr, dg.n_ff});
dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_F32, {sr, dg.n_vocab});
const int64_t n_markov_tiles = (dg.n_vocab_all + 63) / 64;
dw.best_score = decl_b(b, nm.f("ds_markov_score"), RAD_F32,
{dg.max_seqs, n_markov_tiles});
dw.best_token = decl_b(b, nm.f("ds_markov_token"), RAD_I32,
{dg.max_seqs, n_markov_tiles});
/* The proposal buffer (RadDrafterDecl::proposal): a block pass proposes through the drafter's
* own walk, never through the sampler's token buffer. */
dw.tokens = decl_b(b, nm.f("ds_tokens"), RAD_I32, {dg.max_seqs, c.steps()});
if (!dw.srcn || !dw.c || !dw.cn || !dw.ck || !dw.cv ||
(c.qk_norm && (!dw.ckn || !dw.qn || !dw.kn)) ||
(c.gate && (!dw.gaten || !dw.attng)) || !dw.x || !dw.delta || !dw.h || !dw.q || !dw.k ||
!dw.v || !dw.gate || !dw.attn || !dw.gate_up || !dw.ff || !dw.dlog ||
!dw.best_score || !dw.best_token || !dw.tokens)
return RAD_E_INVAL;
RAD_ARCH_TRY(ds->declare(b, nm, dg, c, base_layer, *kv, tok_embd, "draft", ck_head, dw));
RadDrafterDecl drf{};
drf.name = "dspark";
drf.kind = RAD_DRAFT_BLOCK;
drf.depth = ctx->max_spec;
drf.block = c.block;
drf.proposal = dw.tokens;
drf.proposal_pitch = c.steps();
drf.window = c.window;
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.mask_token_id", -1);
if (drf.mask_token < 0)
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1);
if (drf.mask_token < 0) {
fprintf(stderr, "radiance: this drafter declares no mask_token_id, which every unfilled "
"block position embeds\n");
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
rad_note(b, "DSpark drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
"ffn %lld, %s attention with a %lld-token anchor-aligned window (%lld configured "
"history + 1), %lld of %lld rotary dimensions, %s, %s a head, %d trunk tap(s); one "
"forward over %lld noise row(s), the anchor included, proposes %lld tokens",
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1,
(long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim,
(long long)dg.n_ff, c.causal ? "causal" : "non-causal", (long long)c.window,
(long long)window, (long long)c.rot, (long long)dg.head_dim, c.act,
c.gate ? "sigmoid gate" : "no gate", (int)c.n_taps, (long long)c.block,
(long long)c.steps());
rad_note(b, "the rank-%lld Markov bigram head greedily scans all %lld vocabulary tokens at "
"each draft position; confidence is not applied to logits%s",
(long long)c.rank, (long long)dg.n_vocab_all,
rad_meta_geti(meta, "draft.has_confidence_head", 0)
? " (its reference role is adaptive depth, which this fixed-depth graph does not use)"
: "");
return RAD_OK;
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_DSPARK_BF16_H */
+55 -24
View File
@@ -129,12 +129,19 @@ struct GdnFP8 {
/* Geom::plain_norm with an out projection that reads no codes (a 4-bit one): the recurrent
* epilogue and the prefill quantiser leave the code pair unwritten. */
bool o_plain = false;
/* Whether op_cr writes the out projection's codes; otherwise q_o follows it. */
bool cr_codes = false;
int64_t cr_rows = 0;
/* Set by the architecture after declare: a `prefetch` of the out-projection's leading bytes
* (decl_prefetch, rad_arch.h), issued on the second lane beside the decode recurrent update on
* steps of up to pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
* (decl_prefetch, rad_arch.h), issued beside the decode recurrent update on steps of up to
* pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
rad_op op_pf_out = 0;
int64_t pf_out_rows = 0, pf_out_seqs = 0;
/* The same read as a second op for steps of at least pf_out_v_rows rows, where the
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
* every step takes op_pf_out. */
rad_op op_pf_out_v = 0;
int64_t pf_out_v_rows = 0;
rad_op op_ar = 0, op_add = 0;
/* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_fp8.h). */
bool ar_out = false;
@@ -336,12 +343,14 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
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 (int8 when ActFP8::q8_fed; the codes
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent. */
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent.
* Rotated int8 codes (ActFP8::q8_rot) only the conv fold writes (gdn_conv_recurrent_update_had);
* rows this update serves are quantised by q_o. */
if (g.plain_norm) {
RAD_ARCH_TRY(out.probe(b, nm, g, nm.f("blk.%d.ssm_out", l), { s.out }));
o_plain = out.codes_free && out.reads_x;
}
if (op_recur && w.o.cq() && !o_plain) {
if (op_recur && w.o.cq() && !o_plain && !w.o.q8_rot) {
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2));
}
@@ -349,17 +358,25 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
* tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */
{
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
op_cr = rw(b, RAD_OP(b, "gdn_conv_recurrent_update",
RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v),
RAD_INT("conv_width", cfg.conv_width),
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
RAD_STR("state_form",
g.max_spec > 0 ? "anchor" : "per_candidate")),
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias, w_out_norm)),
/* The fold's rotated epilogue writes one scale per (row, 128), or per 256 for an IQ8R
* trunk's codes (ActFP8::g8; `group`, stated to that form alone: last, and cut off
* otherwise), where this rank's value heads pair up. */
const bool cr_wide = w.o.q8_rot && w.o.g8 == RAD_I8_GROUP_WIDE && cfg.n_head_v % 2 == 0;
cr_codes = w.o.cq() && !o_plain && (!w.o.q8_rot || w.o.g8 == RAD_FP8_BLOCK || cr_wide);
const RadParam cp[] = { RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
RAD_INT("head_v", cfg.head_v),
RAD_INT("conv_width", cfg.conv_width),
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate"),
RAD_INT("group", RAD_I8_GROUP_WIDE) };
const rad_weight cw[] = { w_conv, w_a_log, w_dt_bias, w_out_norm };
op_cr = rw(b, rad_decl_op(b, w.o.q8_rot && cr_codes ? "gdn_conv_recurrent_update_had"
: "gdn_conv_recurrent_update",
cp, (int)(sizeof cp / sizeof *cp) - (cr_wide && cr_codes ? 0 : 1),
cw, 4),
{w.in.x, w.ab}, {w.o.x});
if (op_cr && w.o.cq() && !o_plain) {
if (op_cr && cr_codes) {
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
RAD_ARCH_TRY(rad_op_writes(b, op_cr, oq, 2));
}
@@ -465,8 +482,12 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
/* At decode and verify sizes the a|b projection is nearly all launch cost and reads only the
* norm's output, as the in-projection does, so it runs beside it on lane 1 and is joined before
* the convolution reads `ab`. A prefill chunk keeps one lane, where the two would share
* bandwidth. */
if (ab_lane && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) {
* bandwidth. Where launches chain it stays on lane 0: its chained form starts beside the
* in-projection without the two lane joins, each of which holds a launch back until the host
* has seen the other lane finish (Qwen3.8-27B on two cards: the projection started 55 us late
* and the update behind it another 20 to 40 us). */
if (ab_lane && !rad_chain_on() && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK &&
rad_lane(c, 1) == RAD_OK) {
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
rad_lane(c, 0);
in.step(c, w.h, w.in.x, T);
@@ -500,11 +521,18 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
/* The recurrent update at decode heights runs one workgroup per (sequence, head) and leaves the
* card's memory mostly idle, so the out-projection's weight is read into the on-die cache
* beside it, on the second lane behind a join from lane 0 (as prefetch_beside). */
* beside it: in front of the update on lane 0 where launches chain (the read's chained form
* holds nothing behind it), else on the second lane behind a join from lane 0 (as
* prefetch_beside). */
if (op_pf_out && D > 0 && D <= pf_out_seqs && P == 0 && T <= pf_out_rows) {
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
RAD_ISSUE(c, op_pf_out, RAD_W(out.w));
rad_lane(c, 0);
const rad_op pf = op_pf_out_v && T >= pf_out_v_rows ? op_pf_out_v : op_pf_out;
if (prefetch_lane0()) {
RAD_ISSUE(c, pf, RAD_W(out.w));
} else {
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
RAD_ISSUE(c, pf, RAD_W(out.w));
rad_lane(c, 0);
}
}
if (D > 0 && op_cr && qd <= cr_rows) {
RAD_ISSUE_N(c, op_cr, qd,
@@ -515,8 +543,9 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
praw(batch->cu_seqlens, RAD_I32, D + 1),
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
w.o.cq() && !o_plain ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() && !o_plain ? brows(w.o.cs(), DT) : RAD_NONE);
cr_codes ? brows(w.o.cq(), DT) : RAD_NONE,
cr_codes ? brows(w.o.cs(), DT) : RAD_NONE);
if (w.o.cq() && !o_plain && !cr_codes) q_o.step(c, T, 0, DT);
} else if (D > 0) {
RAD_ISSUE_N(c, op_conv_update, qd,
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
@@ -530,8 +559,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
praw(batch->cu_seqlens, RAD_I32, D + 1),
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
w.o.cq() && !o_plain ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() && !o_plain ? brows(w.o.cs(), DT) : RAD_NONE);
w.o.cq() && !o_plain && !w.o.q8_rot ? brows(w.o.cq(), DT) : RAD_NONE,
w.o.cq() && !o_plain && !w.o.q8_rot ? brows(w.o.cs(), DT) : RAD_NONE);
/* Rotated codes come only from the fold; here the decode rows take the quantiser. */
if (w.o.q8_rot && !o_plain) q_o.step(c, T, 0, DT);
}
/* The output a piece at a time where the caller takes the all-reduce that way (ArPieces): the
+263
View File
@@ -0,0 +1,263 @@
/* rad_block_gemma4_unified.h -- the media embedders of Gemma 4 12B ("unified", transformers'
* Gemma4UnifiedVisionEmbedder and the audio Gemma4UnifiedMultimodalEmbedder), served by gemma4_bf16.
* Neither has an encoder: the language model sees each patch or audio frame after a few norms and
* linears.
*
* image: a patch is 48 x 48 x 3 (3 x 3 of the processor's 16-pixel patches), staged by the core's
* Gemma 4 processor as u / 255 in bf16, (y, x, channel); a LayerNorm over the patch, a linear with
* a bias, a LayerNorm, plus a learned row for the patch's column and one for its row (the
* checkpoint's [npos, 2, width] table, read as its two taps of dimension 1), a LayerNorm, then the
* multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. The LayerNorms are
* nn.LayerNorm's default eps 1e-5, which no config states. One patch is one row.
* audio: a frame is 640 samples at 16 kHz as they are, the last zero-padded, in bf16; an RMS norm
* with no gain and a 640 -> n_embd linear. One frame is one row.
*
* Their rows replace the placeholders' embeddings unscaled, as the vision tower's do. Every rank
* runs them whole (RAD_SHARD_NONE). */
#ifndef RAD_BLOCK_GEMMA4_UNIFIED_H
#define RAD_BLOCK_GEMMA4_UNIFIED_H
#include "rad_arch.h"
#include <cstdio>
#include <cstring>
namespace rad {
namespace arch {
struct Gemma4UnifiedVision {
bool on = false;
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
* plugin sets it before declare. */
bool bidirectional = false;
int64_t P = 0, width = 0, patch_dim = 0, npos = 0, n_embd = 0;
rad_weight w_ln1 = 0, w_ln1b = 0, w_in = 0, w_inb = 0, w_ln2 = 0, w_ln2b = 0, w_px = 0, w_py = 0;
rad_weight w_pn = 0, w_pnb = 0, w_proj = 0;
rad_op op_ln1 = 0, op_in = 0, op_ln2 = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0;
rad_op op_pn = 0, op_norm = 0, op_out = 0;
rad_buf b_n = 0, b_x = 0, b_h = 0, b_px = 0, b_py = 0, b_out = 0;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
return t && !std::strcmp(t, "gemma4_unified_vision");
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, const char* who) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
width = rad_meta_geti(m, "vision_config.mm_embed_dim", 0);
npos = rad_meta_geti(m, "vision_config.mm_posemb_size", 0);
const int64_t side = rad_meta_geti(m, "vision_config.model_patch_size", 0);
const int64_t outd = rad_meta_geti(m, "vision_config.output_proj_dims", width);
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
if (width <= 0 || npos <= 0 || side <= 0 || outd != width) {
fprintf(stderr, "radiance: %s: the container's vision_config is incomplete or not the "
"embedder this plugin serves (mm_embed_dim %lld, mm_posemb_size %lld, "
"model_patch_size %lld, output_proj_dims %lld)\n", who,
(long long)width, (long long)npos, (long long)side, (long long)outd);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
patch_dim = 3 * side * side;
P = ctx->max_enc_patches;
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
const char* V = "model.vision_embedder";
struct { const char* to; const char* from; } cp[] = {
{ "v.ln1.weight", "patch_ln1.weight" }, { "v.ln1.bias", "patch_ln1.bias" },
{ "v.in.weight", "patch_dense.weight" }, { "v.in.bias", "patch_dense.bias" },
{ "v.ln2.weight", "patch_ln2.weight" }, { "v.ln2.bias", "patch_ln2.bias" },
{ "v.pn.weight", "pos_norm.weight" }, { "v.pn.bias", "pos_norm.bias" } };
for (const auto& e : cp)
RAD_ARCH_TRY(map_copy(b, nm.f("%s", e.to), nm.ckpt("%s.%s", V, e.from)));
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_x.weight"), nm.ckpt("%s.pos_embedding", V), 1, 0));
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_y.weight"), nm.ckpt("%s.pos_embedding", V), 1, 1));
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight")));
w_ln1 = decl_w(b, nm.f("v.ln1.weight"), RAD_BF16, {patch_dim}, A, N, grp_model());
w_ln1b = decl_w(b, nm.f("v.ln1.bias"), RAD_BF16, {patch_dim}, A, N, grp_model());
w_in = decl_w(b, nm.f("v.in.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
w_inb = decl_w(b, nm.f("v.in.bias"), RAD_BF16, {width}, A, N, grp_model());
w_ln2 = decl_w(b, nm.f("v.ln2.weight"), RAD_BF16, {width}, A, N, grp_model());
w_ln2b = decl_w(b, nm.f("v.ln2.bias"), RAD_BF16, {width}, A, N, grp_model());
w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_pn = decl_w(b, nm.f("v.pn.weight"), RAD_BF16, {width}, A, N, grp_model());
w_pnb = decl_w(b, nm.f("v.pn.bias"), RAD_BF16, {width}, A, N, grp_model());
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
b_n = decl_b(b, nm.f("v.n"), RAD_BF16, {P, patch_dim});
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width});
b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width});
b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width});
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {P, n_embd});
auto ln = [&](int64_t n, rad_weight w, rad_weight bias) {
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
auto lookup = [&](rad_weight w) {
return RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
RAD_WEIGHTS(w));
};
auto add = [&]() {
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
op_ln1 = rw(b, ln(patch_dim, w_ln1, w_ln1b), {}, {b_n});
op_in = rw(b, RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16"),
RAD_STR("act", "none")),
RAD_WEIGHTS(w_in, w_inb)),
{b_n}, {b_x});
op_ln2 = rw(b, ln(width, w_ln2, w_ln2b), {b_x}, {b_h});
op_px = rw(b, lookup(w_px), {}, {b_px});
op_py = rw(b, lookup(w_py), {}, {b_py});
op_padd = rw(b, add(), {b_px, b_py}, {b_px});
op_add = rw(b, add(), {b_h, b_px}, {b_h});
op_pn = rw(b, ln(width, w_pn, w_pnb), {b_h}, {b_x});
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_x}, {b_h});
op_out = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
RAD_INT("K", width), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_proj)),
{b_h}, {b_out});
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = 1;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.bidirectional = bidirectional ? 1 : 0;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision embedder (no tower): %lldx%lld patches of %lld values -> %lld, "
"positions %lld a side; %lld patches a pass -> %lld rows of %lld",
(long long)side, (long long)side, (long long)patch_dim, (long long)width,
(long long)npos, (long long)P, (long long)P, (long long)n_embd);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch;
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
rad_step_fail(c, "an encoder pass this program's vision embedder cannot serve: none "
"declared, or more patches than it was declared for");
return;
}
const int32_t* crd = batch->enc_coord;
RAD_ISSUE_N(c, op_ln1, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim), RAD_W(w_ln1),
RAD_W(w_ln1b), brows(b_n, Pn));
RAD_ISSUE_N(c, op_in, Pn, brows(b_n, Pn), RAD_W(w_in), RAD_W(w_inb), RAD_NONE, brows(b_x, Pn));
RAD_ISSUE_N(c, op_ln2, Pn, brows(b_x, Pn), RAD_W(w_ln2), RAD_W(w_ln2b), brows(b_h, Pn));
RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
RAD_ISSUE_N(c, op_add, Pn, brows(b_h, Pn), brows(b_px, Pn), brows(b_h, Pn));
RAD_ISSUE_N(c, op_pn, Pn, brows(b_h, Pn), RAD_W(w_pn), RAD_W(w_pnb), brows(b_x, Pn));
RAD_ISSUE_N(c, op_norm, Pn, brows(b_x, Pn), RAD_NONE, brows(b_h, Pn));
RAD_ISSUE_N(c, op_out, Pn, brows(b_h, Pn), RAD_W(w_proj), brows(b_out, Pn));
}
};
struct Gemma4UnifiedAudio {
bool on = false;
int64_t P = 0, frame = 0, n_embd = 0;
rad_weight w_proj = 0;
rad_op op_norm = 0, op_out = 0;
rad_buf b_n = 0, b_out = 0;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
return t && !std::strcmp(t, "gemma4_unified_audio");
}
/* Samples a frame: the extractor's audio_samples_per_token, else the embedder's input width. */
static int64_t frame_for(const RadModelMeta* m) {
return rad_meta_geti(m, "processor.feature_extractor.audio_samples_per_token",
rad_meta_geti(m, "audio_config.audio_embed_dim", 0));
}
/* The longest clip in frames: processor_config.json's audio_seq_length, else 30 s. */
static int64_t frames_for(const RadModelMeta* m) {
const int64_t f = frame_for(m);
const int64_t rate = rad_meta_geti(m, "processor.feature_extractor.sampling_rate", 16000);
if (f <= 0 || rate <= 0) return 0;
return rad_meta_geti(m, "processor.audio_seq_length", (30 * rate + f - 1) / f);
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, const char* who) {
on = false;
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
frame = frame_for(m);
const int64_t width = rad_meta_geti(m, "audio_config.audio_embed_dim", 0);
const double eps = rad_meta_getf(m, "audio_config.rms_norm_eps", 1e-6);
if (frame <= 0 || width != frame) {
fprintf(stderr, "radiance: %s: the container's audio frame (%lld samples) is not the "
"embedder's input (audio_embed_dim %lld)\n", who, (long long)frame,
(long long)width);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
P = ctx->max_audio_frames;
RAD_ARCH_TRY(map_copy(b, nm.f("a.embed.weight"), nm.ckpt("model.embed_audio.embedding_projection.weight")));
w_proj = decl_w(b, nm.f("a.embed.weight"), RAD_BF16, {n_embd, frame}, RAD_ACCESS_PER_REQUEST,
RAD_SHARD_NONE, grp_model());
b_n = decl_b(b, nm.f("a.n"), RAD_BF16, {P, frame});
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {P, n_embd});
op_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", frame),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{}, {b_n});
op_out = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
RAD_INT("K", frame), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_proj)),
{b_n}, {b_out});
RadEncoderDecl e{};
e.name = "audio";
e.modalities = RAD_MM_AUDIO;
e.patch_dim = frame;
e.merge = 1;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "audio embedder (no encoder): frames of %lld samples -> %lld; %lld frames a pass",
(long long)frame, (long long)n_embd, (long long)P);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch;
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
rad_step_fail(c, "an audio pass this program's audio embedder cannot serve: none "
"declared, or more frames than it was declared for");
return;
}
RAD_ISSUE_N(c, op_norm, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, frame), RAD_NONE,
brows(b_n, Pn));
RAD_ISSUE_N(c, op_out, Pn, brows(b_n, Pn), RAD_W(w_proj), brows(b_out, Pn));
}
};
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_GEMMA4_UNIFIED_H */
+4
View File
@@ -56,6 +56,9 @@ struct Gemma4Vision {
rad_op op_c[C_N] = {};
};
bool on = false, standardize = false, clip = false;
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
* plugin sets it before declare. */
bool bidirectional = false;
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
int64_t npos = 0, n_embd = 0;
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
@@ -321,6 +324,7 @@ struct Gemma4Vision {
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.bidirectional = bidirectional ? 1 : 0;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld",
+65 -16
View File
@@ -27,6 +27,9 @@ struct DsaCache {
rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0;
rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0;
rad_buf score = 0, selected = 0, nsel = 0, length = 0;
/* A taking-all step's zero scores, [max_tok, topk + 1]: such a step does not split, and
* the score plane holds only a run of rows when the step may. */
rad_buf unscored = 0;
/* TP only: a rank's rebased bounds, page tables and lengths before the gathers. */
rad_buf cu_part = 0, sel_part = 0, len_part = 0;
};
@@ -44,6 +47,7 @@ struct DsaCache {
rad_kvgroup index = 0, tail = 0, attention = 0;
rad_weight ape = 0;
rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0;
rad_op op_unscored = 0, op_select_all = 0;
rad_op op_score_part = 0, op_select_part = 0, op_gather_sel = 0, op_gather_len = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
@@ -112,6 +116,15 @@ struct DsaCache {
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.kg }, {});
/* A step whose every row reaches topk or fewer blocks selects them all (takes_all), and
* qsa_select takes any finite scores in block order then: zeros serve as well as the
* scorer's. The fill spans topk + 1 columns, at least the live reach of such a step. */
op_unscored = rw(b,
RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("n", unscored_cols()), RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{}, { w.unscored });
op_score = rw(b,
RAD_OP(b, "dsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
@@ -139,6 +152,14 @@ struct DsaCache {
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.score, w.nc }, { w.selected, w.nsel, w.length });
op_select_all = rw(b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("blocks", unscored_cols()),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.unscored, w.nc }, { w.selected, w.nsel, w.length });
if (split) {
op_select_part = rw(
b,
@@ -165,8 +186,12 @@ struct DsaCache {
if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len)
return RAD_E_INVAL;
}
return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL;
return op_query && op_work && op_tail && op_unscored && op_score && op_select &&
op_select_all
? RAD_OK
: RAD_E_INVAL;
}
int64_t unscored_cols() const { return c.topk + 1 < c.blocks ? c.topk + 1 : c.blocks; }
/* The columns a step scores: the live reach the batch bounds on the host. */
int64_t live_blocks(const RadBatch* batch) const {
const auto* ib = kv_batch(batch, index);
@@ -179,13 +204,19 @@ struct DsaCache {
}
/* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by
* the core), so every rank takes the same path and a recorded decode pass changes it only when
* that bound moves. */
* that bound moves. A step that takes all its blocks never splits: with nothing to score, every
* rank selects the whole step itself, and the gathers have nothing to save. */
bool splits(const RadBatch* batch) const {
const int64_t T = batch->n_tok;
return op_score_part && (GlmTp::splits(T, g.world) ||
(T >= GlmTp::kSplitWorkRows &&
T * live_blocks(batch) >= GlmTp::kSplitWork));
return op_score_part && live_blocks(batch) > c.topk &&
(GlmTp::splits(T, g.world) ||
(T >= GlmTp::kSplitWorkRows && T * live_blocks(batch) >= GlmTp::kSplitWork));
}
/* Every row's history fits the selection, so the query side (projection, head gates,
* quantiser, scorer) has nothing to decide: the selected table is every live block in order,
* bit for bit what scoring would select. Read from the same host bound as splits(), so every
* rank agrees. */
bool takes_all(const RadBatch* batch) const { return live_blocks(batch) <= c.topk; }
/* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of).
* A rank whose run lies wholly past a small step runs the step's first R rows instead: no
* sequence holds its run, so its scores are -inf, and its answers land past T. The caller's
@@ -210,11 +241,13 @@ struct DsaCache {
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t work = (T + 3) / 4 + S,
pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1;
const bool all = takes_all(batch);
int64_t q0 = 0, qn = T;
query_rows(batch, &q0, &qn);
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
brow_slice(w.codes, q0 * 32, qn * 32, 128),
brow_slice(w.scales, q0 * 32, qn * 32, 1));
if (!all)
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
brow_slice(w.codes, q0 * 32, qn * 32, 128),
brow_slice(w.scales, q0 * 32, qn * 32, 1));
RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch),
@@ -232,6 +265,16 @@ struct DsaCache {
step_split(ctx, batch, live);
return;
}
if (all) {
const int64_t U = unscored_cols();
RAD_ISSUE_N(ctx, op_unscored, T, brows(w.unscored, T));
RAD_ISSUE_N(ctx, op_select_all, T, bcol_at(w.unscored, 0, U, 0, live, T),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch),
brows(w.nc, S), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.selected, T),
brows(w.nsel, T), brows(w.length, T));
return;
}
// dsa_score declares ten operands, cu_part the optional tenth; the engine counts them.
RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32),
brows(w.gate, T), kv_cache(index, layer), RAD_NONE,
@@ -348,23 +391,29 @@ struct GlmIndexer {
};
int64_t r0 = 0, rows = T;
cache.query_rows(batch, &r0, &rows);
/* The key side runs on every step, since the index cache must stay current; the query
* side only where the selection is a choice (DsaCache::takes_all). */
const bool all = cache.takes_all(batch);
/* Every output row of these ops is independent of the others and of how many there are,
* except the bf16 projection's at 64 rows and under, a band whose split count a tuned
* configuration may set: it stays on the step's rows unless every run is wider. */
const bool runs = cache.splits(batch);
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
else
query.step(ctx, act(w.q_low), w.q_wide, T);
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
if (!all) {
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
else
query.step(ctx, act(w.q_low), w.q_wide, T);
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
}
key_gate.step(ctx, act(w.input), w.kg_raw, T);
RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias),
bcol(w.cache.kg, 0, 128, T));
RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T),
bcol(w.cache.kg, 128, 128, T));
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096), RAD_W(head_weight),
brow_slice(w.cache.gate, r0, rows, 32));
if (!all)
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096),
RAD_W(head_weight), brow_slice(w.cache.gate, r0, rows, 32));
cache.step(ctx, batch);
}
};
+30 -22
View File
@@ -19,6 +19,7 @@
#include "rad_glm_tp.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
namespace rad {
@@ -27,6 +28,25 @@ struct MlaLatent {
struct Config {
int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513;
};
/* The attention over the latent cache, `rows` rows of `heads` heads. The cache is Geom::kv_dtype
* (bf16, or fp8_e4m3 under --kv-cache-dtype fp8); `kv_dtype` is stated only for a cache that is
* not bf16, so a bf16 build declares the op it always did. */
static rad_op attn_op(RadBuilder* b, const Geom& g, int64_t rows, int64_t heads,
int64_t blocks, double scale) {
if (g.kv_dtype && std::strcmp(g.kv_dtype, "bf16"))
return RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
RAD_INT("block_size", 4), RAD_F64("scale", scale),
RAD_STR("dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS);
return RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
RAD_INT("block_size", 4), RAD_F64("scale", scale),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
}
struct Wire {
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
/* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`.
@@ -68,16 +88,10 @@ struct MlaLatent {
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 });
op_attn = rw(b,
attn_op(b, g, g.max_tok, c.heads, c.blocks,
1.0 / std::sqrt((double)c.head_dim)),
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL;
op_expand = rw(
b,
@@ -172,12 +186,13 @@ struct GlmMla {
RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world),
1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
w.q_low, w.core.q));
// Cache stores contiguous halves of the normalized latent, with no duplicated K/V.
/* Cache stores contiguous halves of the normalized latent, with no duplicated K/V. An E4M3
* cache (Geom::kv_dtype) stores at kv_store's default descale of 1, which mla_attn reads. */
op_store = rw(b,
RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4),
RAD_STR("kv_dtype", "bf16")),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{ w.latent }, {});
if (!op_store) return RAD_E_INVAL;
@@ -200,7 +215,7 @@ struct GlmMla {
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_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{ w.latent }, {});
/* Issued in finish, after this layer's indexer selects and before the attention reads
@@ -239,15 +254,8 @@ struct GlmMla {
{ in }, { out });
};
op_rows_absorb = project("absorb", r.q, r.q_latent);
op_rows_attn =
rw(b,
RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512),
RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks),
RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
op_rows_attn = rw(b, MlaLatent::attn_op(b, g, R, 64, core.c.blocks, 1.0 / std::sqrt(256.0)),
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
op_rows_expand = project("expand", r.attn_latent, r.attn.x);
RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384));
rows_output.stored = nm.f("blk.%d.attn_output.weight", layer);
+34 -25
View File
@@ -16,7 +16,11 @@
* before the layer's attention, `join` (the residual add and the proposal rows' selection) between
* its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's.
* Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass. */
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass.
*
* The same head serves another DeepSeek-style drafter by its checkpoint layout, set before
* declare_inputs: the residual width, the layer's checkpoint prefix and index, and the name of the
* head's final norm (Ling-3.0: 2560, `model.layers.42`, 42, `final_layernorm.weight`). */
#ifndef RAD_BLOCK_GLM_MTP_H
#define RAD_BLOCK_GLM_MTP_H
#include "rad_glm_tp.h"
@@ -31,6 +35,10 @@ struct GlmMtp {
rad_weight token = 0, head = 0;
};
static constexpr int kDepth = 3; /* --num-speculative-tokens auto */
int64_t width = 4096;
const char* prefix = "model.language_model.layers.45";
int layer = 45;
const char* norm_src = "shared_head.norm.weight";
Names nm{ "mtp" };
Geom g{};
Wire w{};
@@ -50,47 +58,48 @@ struct GlmMtp {
w = wire;
if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1)
return RAD_E_INVAL;
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, 4096 });
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST);
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, 4096 });
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 8192 });
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, 4096 });
const char* pre = "model.language_model.layers.45";
const int64_t E = width;
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, E });
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, E }, RAD_BUF_PERSIST);
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, E });
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 2 * E });
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, E });
const char* pre = prefix;
auto gain = [&](const char* n, const char* src) {
const char* name = nm.f("%s", n);
if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0;
return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(45));
return decl_w(b, name, RAD_F32, { E }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(layer));
};
en = gain("enorm.weight", "enorm.weight");
hn = gain("hnorm.weight", "hnorm.weight");
norm = gain("output_norm.weight", "shared_head.norm.weight");
norm = gain("output_norm.weight", norm_src);
RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre)));
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(45));
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { E, 2 * E }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh)
return RAD_E_INVAL;
op_prev = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", E),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.final_hidden }, { hidden });
op_embed = rw(b,
RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w.token)),
{}, { embedding });
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, 4096, embedding));
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, E, embedding));
op_embed_ar = GlmTp::reduce(b, g, embedding, true);
op_en = rmsnorm(b, en, embedding, concat);
op_hn = rmsnorm(b, hn, hidden, concat);
op_eh = rw(b,
RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096),
RAD_INT("K", 8192), RAD_STR("dtype", "bf16")),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", E),
RAD_INT("K", 2 * E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(eh)),
{ concat }, { x });
return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar)
@@ -102,14 +111,14 @@ struct GlmMtp {
int declare_join(RadBuilder* b, rad_buf y) {
op_residual = rw(b,
RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x, y }, { x });
// All history rows fill the draft cache; only proposal rows need its FFN.
op_select = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x }, { hidden });
@@ -124,7 +133,7 @@ struct GlmMtp {
op_head = rw(b,
RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", 4096),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", width),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w.head)),
{ hidden }, { w.logits });
@@ -150,9 +159,9 @@ struct GlmMtp {
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token),
brows(embedding, T));
mrows.step(c, batch, embedding, T);
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * 4096, brows(embedding, T), RAD_NONE);
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, 4096, T));
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, 4096, 4096, T));
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * width, brows(embedding, T), RAD_NONE);
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, width, T));
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, width, width, T));
RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T));
}
void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const {
@@ -175,7 +184,7 @@ private:
rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const {
return rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain)),
{ in }, { out });
@@ -183,7 +192,7 @@ private:
rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const {
return rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ in }, { out });
+25 -12
View File
@@ -1,5 +1,6 @@
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. With `groups`
* above 1 the selection is group-limited (router_sigmoid_group_topk, Ling-3.0's 8 groups, 4 kept). */
#ifndef RAD_BLOCK_GLM_ROUTER_H
#define RAD_BLOCK_GLM_ROUTER_H
#include "rad_glm_tp.h"
@@ -9,7 +10,7 @@ namespace rad {
namespace arch {
struct GlmRouter {
struct Config {
int64_t experts = 288, top_k = 8, rows = 32;
int64_t experts = 288, top_k = 8, rows = 32, groups = 1, topk_groups = 1;
int norm = 1;
double route_scale = 2.5;
};
@@ -33,8 +34,9 @@ struct GlmRouter {
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)
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 ||
c.groups < 1 || c.experts % c.groups || c.topk_groups < 1 || c.topk_groups > c.groups ||
!w.input || !w.logits || !w.ids || !w.weights || w.logits == w.weights)
return RAD_E_INVAL;
const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name);
RAD_ARCH_TRY(map_copy(b, pn, src.weight));
@@ -52,14 +54,25 @@ struct GlmRouter {
{ 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 });
if (c.groups > 1)
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_group_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("n_group", c.groups),
RAD_INT("topk_group", c.topk_groups), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
else
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
return op_project && op_select ? RAD_OK : RAD_E_INVAL;
}
void project(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
+39 -11
View File
@@ -77,12 +77,13 @@ struct HyperConn {
* 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 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. */
/* Whether the read also emits Hadamard-rotated codes of the block input, for a consumer
* whose weight carries the rotation (MoeFP8's rotated expert plane). Produced in the
* plain codes' finisher, so requires `quant`; the consumer declares no quantiser. */
int rotate = 0;
/* Whether 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. */
* (LinearFP8::i8). The rotated codes take the same dtype (had_quant_act_i8g's beside int8,
* had_quant_act_fp8's beside E4M3), so `Wire::rq` is declared to match. */
int codes_i8 = 0;
/* The most rows one read is declared for, 0 for max_tok; a wider step reads in pieces
* (read_pieces). The read's scratch is sized for its band (some 22 KiB a row at
@@ -115,6 +116,11 @@ struct HyperConn {
* `mix`), read from their encoding at declare. */
bool mix_e4m3 = false;
rad_op op_read = 0, op_write = 0;
/* The block input's own int8 pair is the rotated one (ActFP8::q8_rot, a trunk stored rotated):
* the read writes its rotated codes there and its plain ones into `pq` / `ps`, a pair of this
* connection's that nothing reads. */
bool xrot = false;
rad_buf pq = 0, ps = 0;
/* The write with the all-reduce folded in; 0 when not requested or not served.
* `op_ar_write6` is the same on the rotated 6-bit wire, declared only when a lossy payload is
* accepted and issued on the steps ar_wire_is_exact rejects (every trunk all-reduce at a
@@ -193,6 +199,17 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
return RAD_E_INVAL;
}
if (c.quant && (c.codes_i8 ? (!w.x.q8 || !w.x.s8) : (!w.x.q || !w.x.s))) return RAD_E_INVAL;
/* A trunk whose int8 linears are stored rotated reads the rotated codes alone: `x`'s int8 pair
* is then that pair (ActFP8::q8_rot), and every reader of the block input -- the trunk's
* projections and the rotated experts -- takes it. The read derives the rotated codes in its
* plain codes' finisher, so the plain ones still have somewhere to go: a pair of this
* connection's own that nothing reads. */
xrot = c.quant && c.codes_i8 && w.x.q8_rot;
if (xrot && c.rotate) {
fprintf(stderr, "radiance: %s: the block input's own codes are the rotated ones "
"(ActFP8::q8_rot), so there is no second rotated pair to ask for\n", name);
return RAD_E_INVAL;
}
if (c.rotate && (!c.quant || !w.rq || !w.rs)) {
fprintf(stderr, "radiance: %s: the rotated codes need the plain ones (quant) and the "
"rq/rs pair on the wire\n", name);
@@ -248,8 +265,16 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
rad_buf wr[6] = { w.x.x, 0, 0, 0, 0, 0 };
int n_wr = 1;
if (c.inject) wr[n_wr++] = w.inj;
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
if (xrot) {
pq = decl_b(b, nm.f("%s.plain.q8", name), RAD_I8, { g.max_tok, g.n_embd });
ps = decl_b(b, nm.f("%s.plain.s8", name), RAD_F32, { g.max_tok, fp8_blocks(g.n_embd) });
if (!pq || !ps || w.x.g8 != RAD_FP8_BLOCK) return RAD_E_INVAL;
wr[n_wr++] = pq; wr[n_wr++] = ps;
wr[n_wr++] = w.x.q8; wr[n_wr++] = w.x.s8;
} else {
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
}
op_read = RAD_OP(b, "hc_read",
RAD_PARAMS(RAD_RANGE("M", 1, c.read_rows > 0 && c.read_rows < g.max_tok
@@ -259,7 +284,7 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
RAD_F64("wadd", g.wadd), RAD_INT("inject", c.inject ? 1 : 0),
RAD_INT("group", c.quant ? RAD_FP8_BLOCK : 0),
RAD_INT("rotate", c.rotate ? 1 : 0),
RAD_INT("rotate", (c.rotate || xrot) ? 1 : 0),
RAD_STR("mix", mix_e4m3 ? "e4m3" : "bf16")),
wts, n_wts);
if (!op_read) return RAD_E_INVAL;
@@ -358,11 +383,14 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
c.inject ? RAD_W(w_inj) : RAD_NONE,
brow_slice(w.x.x, r0, rows, g.n_embd),
c.inject ? brow_slice(w.inj, r0, rows, c.hc) : RAD_NONE,
c.quant ? brow_slice(c.codes_i8 ? w.x.q8 : w.x.q, r0, rows, g.n_embd) : RAD_NONE,
c.quant ? brow_slice(c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
c.quant ? brow_slice(xrot ? pq : c.codes_i8 ? w.x.q8 : w.x.q, r0, rows,
g.n_embd) : RAD_NONE,
c.quant ? brow_slice(xrot ? ps : c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
fp8_blocks(g.n_embd)) : RAD_NONE,
c.rotate ? brow_slice(w.rq, r0, rows, g.n_embd) : RAD_NONE,
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
(c.rotate || xrot) ? brow_slice(xrot ? w.x.q8 : w.rq, r0, rows, g.n_embd)
: RAD_NONE,
(c.rotate || xrot) ? brow_slice(xrot ? w.x.s8 : w.rs, r0, rows,
fp8_blocks(g.n_embd)) : RAD_NONE);
}
/* ================================================================== the control-vector projection
+395
View File
@@ -0,0 +1,395 @@
/* rad_block_lilicorr.h -- LiLiCorr's head: the candidate correlator after a DFlash2 backbone.
*
* NVIDIA's drafter for Nemotron-3.5-Bolt (vLLM's model_executor/models/lilicorr.py). The backbone is
* rad_block_dflash2.h's, with attention sinks (Dflash2::Config::lili). Its final hidden states at
* the block's draft rows go here instead of to DFlash2's selector:
*
* candidates each draft position's top-k from the target's own lm_head (log-softmax values,
* vocab-parallel: each rank's shard, all-gathered, merged)
* lattice steps x k rows a sequence, row s * k + j:
* token_proj(embed(cand)) + pass_hidden_proj(h_s)
* + feature_mlp(layernorm(five rank features)) + slot[s] + rank[j]
* 2 layers rmsnorm, attention over the lattice with a learned slot bias (lili_attn), the
* in/out projections; rmsnorm, silu MLP with biases; residuals
* factor x = output_norm(lattice), a = anchor_norm(context_proj(the anchor's context row))
* f = silu(W [x | a | x * a] + b), [out | in] = edge heads of f
* walk normalised dot products, start from the anchor's own outgoing head, greedy
* (lili_walk)
*
* The anchor's context row is hidden_norm(fc(taps)) at the last committed position, which the
* context pass left in Dflash2's `c` (RadBatch::anchor_rows names the row). The head reads the
* target's embedding and lm_head, and its own 25 linears are bf16: ModelOpt ships them NVFP4,
* which no kernel serves, and the recipe decodes them (`cast dtype=bf16`).
*
* Every rank computes the whole lattice (vLLM: "candidate IDs and embeddings are replicated across
* TP ranks"); only the head's logits and the embedding lookup are per rank, with the merge in
* lili_cand and an exact all-reduce after the lookup.
*/
#ifndef RAD_BLOCK_LILICORR_H
#define RAD_BLOCK_LILICORR_H
#include "rad_arch.h"
namespace rad {
namespace arch {
struct LiliCorr {
enum { MAX_LAYERS = 4 };
struct Config {
int64_t steps = 0; /* draft positions a sequence: the block less the anchor */
int64_t k = 8; /* candidates a position (lilicorr_candidate_topk) */
int64_t hs = 1024; /* the lattice's width (lilicorr_hidden_size) */
int64_t n_head = 8;
int64_t mlp = 2048; /* hs * lilicorr_mlp_ratio */
int64_t fdim = 1024; /* lilicorr_factor_dim */
int64_t n_layer = 2;
double eps = 1e-6; /* rms_norm_eps, the lattice's RMS norms */
double vec_eps = 1e-4; /* lilicorr_vector_eps, F.normalize's floor */
double scale = 8.0; /* lilicorr_logit_scale */
};
/* row_k: the pairs a rank's logprob row carries, k rounded up so 2 + 2 row_k floats are whole
* 16-byte words (the all-gather's unit): 9 for k = 8. */
static int64_t row_k(int64_t k) { return (k % 2) ? k : k + 1; }
struct Wire {
/* Dflash2's */
rad_buf sel_h = 0; /* [srows, n_embd] the drafter's final hidden states, draft rows */
rad_buf c = 0; /* [max_tok, n_embd] hidden_norm(fc(taps)), the context pass's rows */
rad_buf tokens = 0; /* [max_seqs, steps] i32, the proposal */
/* the head's own */
rad_buf logits = 0; /* [srows, n_vocab] f32, this rank's shard */
rad_buf stats = 0; /* [srows, 2 + 2 row_k] f32 */
rad_buf sgath = 0; /* [srows, world * (2 + 2 row_k)] f32, world > 1 */
rad_buf pas = 0; /* [srows, hs] */
rad_buf cand = 0; /* [srows * k] i32 */
rad_buf feat = 0; /* [lrows, hs] */
rad_buf hh = 0; /* [lrows, hs] the lattice's residual stream; starts as lili_cand's base */
rad_buf emb = 0; /* [lrows, n_embd] the candidates' embeddings */
rad_buf y = 0; /* [lrows, hs] */
rad_buf qkv = 0; /* [lrows, 3 hs] */
rad_buf att = 0; /* [lrows, hs] */
rad_buf up = 0; /* [lrows, mlp] */
rad_buf ups = 0; /* [lrows, mlp] */
rad_buf cat = 0; /* [lrows, 3 hs] */
rad_buf fh = 0; /* [lrows, hs] */
rad_buf fhs = 0; /* [lrows, hs] */
rad_buf edges = 0; /* [lrows, 2 fdim] */
rad_buf anc = 0; /* [max_seqs, n_embd] */
rad_buf ast = 0; /* [max_seqs, hs] */
rad_buf an = 0; /* [max_seqs, hs] */
rad_buf aout = 0; /* [max_seqs, fdim] */
};
Geom g{};
Config cfg{};
Wire w{};
int64_t srows = 0, lrows = 0, rk = 0;
rad_weight w_lm = 0, w_tok = 0; /* the target's */
rad_weight w_tokp = 0, b_tokp = 0, w_pass = 0, b_pass = 0, w_ctx = 0, b_ctx = 0;
rad_weight w_fdn = 0, b_fdn = 0, ln_w = 0, ln_b = 0, up_w = 0, up_b = 0, w_slot = 0, w_rank = 0;
rad_weight w_anorm[MAX_LAYERS] = {}, w_in[MAX_LAYERS] = {}, b_in[MAX_LAYERS] = {};
rad_weight w_out[MAX_LAYERS] = {}, b_out[MAX_LAYERS] = {}, w_mnorm[MAX_LAYERS] = {};
rad_weight w_up[MAX_LAYERS] = {}, b_up[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
rad_weight b_dn[MAX_LAYERS] = {};
rad_weight w_rel = 0, w_same = 0, w_onorm = 0, w_annorm = 0;
rad_weight w_fac = 0, b_fac = 0, w_edge = 0, b_edge = 0, w_aout = 0, b_aout = 0;
rad_op op_logits = 0, op_stats = 0, op_sgath = 0, op_pas = 0, op_cand = 0;
rad_op op_emb = 0, op_emb_ar = 0, op_tokp = 0, op_fdn = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_in[MAX_LAYERS] = {}, op_attn = 0;
rad_op op_out[MAX_LAYERS] = {}, op_mnorm[MAX_LAYERS] = {}, op_up[MAX_LAYERS] = {};
rad_op op_dn[MAX_LAYERS] = {}, op_silu_up = 0;
rad_op op_onorm = 0, op_anc = 0, op_ctx = 0, op_annorm = 0, op_factor = 0, op_fac = 0;
rad_op op_silu_f = 0, op_edge = 0, op_aout = 0, op_walk = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, rad_weight lm_head,
rad_weight tok_embd, const char* ck, const Wire& wire);
/* After Dflash2::step, on the same query batch: `sel_h` holds the draft rows. */
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int LiliCorr::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
rad_weight lm_head, rad_weight tok_embd, const char* ck,
const Wire& wire) {
g = geom; cfg = c; w = wire; w_lm = lm_head; w_tok = tok_embd;
if (!w_lm || !w_tok || !ck || cfg.steps < 1 || cfg.k < 2 || cfg.n_layer < 1 ||
cfg.n_layer > MAX_LAYERS || cfg.hs % cfg.n_head)
return RAD_E_INVAL;
const int64_t K = cfg.k, S = cfg.steps, hs = cfg.hs, fd = cfg.fdim, E = g.n_embd;
srows = g.max_seqs * S;
lrows = srows * K;
rk = row_k(K);
const int ACC = RAD_ACCESS_PER_TOKEN;
const RadWeightGroup grp = grp_model();
/* The head's weights, all replicated. Linears and tables bf16, biases, norms and the
* feature layer f32. */
auto wt = [&](const char* dn, const char* src, uint32_t dt,
std::initializer_list<int64_t> shp) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, grp);
};
const char* L = nm.ckpt("%s.lilicorr", ck);
auto src = [&](const char* tail) { return nm.ckpt("%s.%s", L, tail); };
w_tokp = wt(nm.f("dflash.lili.token_proj.weight"), src("token_proj.weight"), RAD_BF16, { hs, E });
b_tokp = wt(nm.f("dflash.lili.token_proj.bias"), src("token_proj.bias"), RAD_F32, { hs });
w_pass = wt(nm.f("dflash.lili.pass_proj.weight"), src("pass_hidden_proj.weight"), RAD_BF16,
{ hs, E });
b_pass = wt(nm.f("dflash.lili.pass_proj.bias"), src("pass_hidden_proj.bias"), RAD_F32, { hs });
w_ctx = wt(nm.f("dflash.lili.context_proj.weight"), src("context_proj.weight"), RAD_BF16,
{ hs, E });
b_ctx = wt(nm.f("dflash.lili.context_proj.bias"), src("context_proj.bias"), RAD_F32, { hs });
ln_w = wt(nm.f("dflash.lili.feature_norm.weight"), src("feature_norm.weight"), RAD_F32, { 5 });
ln_b = wt(nm.f("dflash.lili.feature_norm.bias"), src("feature_norm.bias"), RAD_F32, { 5 });
up_w = wt(nm.f("dflash.lili.feature_up.weight"), src("feature_mlp.up_proj.weight"), RAD_F32,
{ hs, 5 });
up_b = wt(nm.f("dflash.lili.feature_up.bias"), src("feature_mlp.up_proj.bias"), RAD_F32,
{ hs });
w_fdn = wt(nm.f("dflash.lili.feature_down.weight"), src("feature_mlp.down_proj.weight"),
RAD_BF16, { hs, hs });
b_fdn = wt(nm.f("dflash.lili.feature_down.bias"), src("feature_mlp.down_proj.bias"), RAD_F32,
{ hs });
/* [1, 1, steps, 1, hs] and [1, 1, 1, k, hs], read as tables (a reshape of one whole plane). */
w_slot = wt(nm.f("dflash.lili.slot_embedding"), src("slot_embedding"), RAD_BF16, { S, hs });
w_rank = wt(nm.f("dflash.lili.rank_embedding"), src("rank_embedding"), RAD_BF16, { K, hs });
w_rel = wt(nm.f("dflash.lili.relative_slot_bias"), src("relative_slot_bias"), RAD_F32,
{ cfg.n_head, 2 * (S + 1) - 1 });
w_same = wt(nm.f("dflash.lili.same_slot_bias"), src("same_slot_bias"), RAD_F32, { cfg.n_head });
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
auto ls = [&](const char* tail) { return nm.ckpt("%s.layers.%d.%s", L, i, tail); };
w_anorm[i] = wt(nm.f("dflash.lili.blk.%d.attn_norm.weight", i), ls("attn_norm.weight"),
RAD_F32, { hs });
w_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.weight", i), ls("attn.in_proj_weight"),
RAD_BF16, { 3 * hs, hs });
b_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.bias", i), ls("attn.in_proj_bias"), RAD_F32,
{ 3 * hs });
w_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.weight", i), ls("attn.out_proj.weight"),
RAD_BF16, { hs, hs });
b_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.bias", i), ls("attn.out_proj.bias"),
RAD_F32, { hs });
w_mnorm[i] = wt(nm.f("dflash.lili.blk.%d.mlp_norm.weight", i), ls("mlp_norm.weight"),
RAD_F32, { hs });
w_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.weight", i), ls("mlp.up_proj.weight"),
RAD_BF16, { cfg.mlp, hs });
b_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.bias", i), ls("mlp.up_proj.bias"), RAD_F32,
{ cfg.mlp });
w_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.weight", i), ls("mlp.down_proj.weight"),
RAD_BF16, { hs, cfg.mlp });
b_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.bias", i), ls("mlp.down_proj.bias"),
RAD_F32, { hs });
if (!w_anorm[i] || !w_in[i] || !b_in[i] || !w_out[i] || !b_out[i] || !w_mnorm[i] ||
!w_up[i] || !b_up[i] || !w_dn[i] || !b_dn[i])
return RAD_E_INVAL;
}
w_onorm = wt(nm.f("dflash.lili.output_norm.weight"), src("output_norm.weight"), RAD_F32, { hs });
w_annorm = wt(nm.f("dflash.lili.anchor_norm.weight"), src("anchor_norm.weight"), RAD_F32, { hs });
w_fac = wt(nm.f("dflash.lili.factor_proj.weight"), src("factor_input_proj.weight"), RAD_BF16,
{ hs, 3 * hs });
b_fac = wt(nm.f("dflash.lili.factor_proj.bias"), src("factor_input_proj.bias"), RAD_F32,
{ hs });
/* [out_head | in_head] as one linear, as vLLM fuses them (`_fused_edge_weight`). */
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.weight"),
{ src("out_head.weight"), src("in_head.weight") }, 0));
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.bias"),
{ src("out_head.bias"), src("in_head.bias") }, 0));
w_edge = decl_w(b, nm.f("dflash.lili.edge.weight"), RAD_BF16, { 2 * fd, hs }, ACC,
RAD_SHARD_NONE, grp);
b_edge = decl_w(b, nm.f("dflash.lili.edge.bias"), RAD_F32, { 2 * fd }, ACC, RAD_SHARD_NONE,
grp);
w_aout = wt(nm.f("dflash.lili.anchor_out.weight"), src("anchor_out_head.weight"), RAD_BF16,
{ fd, hs });
b_aout = wt(nm.f("dflash.lili.anchor_out.bias"), src("anchor_out_head.bias"), RAD_F32, { fd });
if (!w_tokp || !b_tokp || !w_pass || !b_pass || !w_ctx || !b_ctx || !ln_w || !ln_b || !up_w ||
!up_b || !w_fdn || !b_fdn || !w_slot || !w_rank || !w_rel || !w_same || !w_onorm ||
!w_annorm || !w_fac || !b_fac || !w_edge || !b_edge || !w_aout || !b_aout)
return RAD_E_INVAL;
/* ---------------------------------------------------------------- ops */
auto gemm_b = [&](int64_t rows, int64_t N, int64_t Kd, rad_weight wgt, rad_weight bias)
-> rad_op {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", Kd),
RAD_STR("dtype", "bf16"), RAD_STR("act", "none")),
RAD_WEIGHTS(wgt, bias));
};
auto rms = [&](int64_t rows, int64_t n, rad_weight gain) -> rad_op {
return RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", cfg.eps),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain));
};
auto silu = [&](int64_t rows, int64_t n) -> rad_op {
return RAD_OP(b, "silu",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
const int64_t sw = 2 + 2 * rk;
/* The candidates: this rank's shard of the target's logits, its logprob row, the exchange. */
op_logits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_lm)),
{ w.sel_h }, { w.logits });
/* Replicated, `vocab_off` is omitted: an optional parameter present at 0 is a different
* declaration from an absent one. */
op_stats = g.world > 1
? rw(b, RAD_OP(b, "sample_logprobs",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("k", rk), RAD_INT("vocab_off", g.vocab_off)),
RAD_NOWEIGHTS),
{ w.logits }, { w.stats })
: rw(b, RAD_OP(b, "sample_logprobs",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("k", rk)),
RAD_NOWEIGHTS),
{ w.logits }, { w.stats });
if (g.world > 1)
op_sgath = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * sw), RAD_STR("dtype", "f32"),
RAD_INT("row", sw)),
RAD_NOWEIGHTS),
{ w.stats }, { w.sgath });
op_pas = rw(b, gemm_b(srows, hs, E, w_pass, b_pass), { w.sel_h }, { w.pas });
op_cand = rw(b, RAD_OP(b, "lili_cand",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("k", K),
RAD_INT("world", g.world), RAD_INT("steps", S),
RAD_INT("n", hs), RAD_STR("dtype", "bf16"),
RAD_F64("eps", 1e-5), RAD_INT("row_k", rk)),
RAD_WEIGHTS(ln_w, ln_b, up_w, up_b, w_slot, w_rank)),
{ g.world > 1 ? w.sgath : w.stats, w.pas }, { w.cand, w.feat, w.hh });
/* The lattice: candidates' embeddings (the trunk's vocab-sharded table, exact reduce), the
* token and feature projections added onto lili_cand's base in their GEMMs' residual. */
op_emb = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("n_embd", E),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{ w.cand }, { w.emb });
if (g.world > 1)
op_emb_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", E, lrows * E),
RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{ w.emb }, { w.emb });
op_tokp = rw(b, gemm_b(lrows, hs, E, w_tokp, b_tokp), { w.emb, w.hh }, { w.hh });
op_fdn = rw(b, gemm_b(lrows, hs, hs, w_fdn, b_fdn), { w.feat, w.hh }, { w.hh });
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, rms(lrows, hs, w_anorm[i]), { w.hh }, { w.y });
op_in[i] = rw(b, gemm_b(lrows, 3 * hs, hs, w_in[i], b_in[i]), { w.y }, { w.qkv });
op_out[i] = rw(b, gemm_b(lrows, hs, hs, w_out[i], b_out[i]), { w.att, w.hh }, { w.hh });
op_mnorm[i] = rw(b, rms(lrows, hs, w_mnorm[i]), { w.hh }, { w.y });
op_up[i] = rw(b, gemm_b(lrows, cfg.mlp, hs, w_up[i], b_up[i]), { w.y }, { w.up });
op_dn[i] = rw(b, gemm_b(lrows, hs, cfg.mlp, w_dn[i], b_dn[i]), { w.ups, w.hh }, { w.hh });
}
op_attn = rw(b, RAD_OP(b, "lili_attn",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("steps", S), RAD_INT("k", K),
RAD_INT("n_head", cfg.n_head),
RAD_INT("head_dim", hs / cfg.n_head),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_rel, w_same)),
{ w.qkv }, { w.att });
op_silu_up = rw(b, silu(lrows, cfg.mlp), { w.up }, { w.ups });
op_onorm = rw(b, rms(lrows, hs, w_onorm), { w.hh }, { w.y });
/* The anchor: the context pass's row at each drafting sequence's last committed position. */
op_anc = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.c }, { w.anc });
op_ctx = rw(b, gemm_b(g.max_seqs, hs, E, w_ctx, b_ctx), { w.anc }, { w.ast });
op_annorm = rw(b, rms(g.max_seqs, hs, w_annorm), { w.ast }, { w.an });
op_factor = rw(b, RAD_OP(b, "lili_factor",
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("L", S * K),
RAD_INT("n", hs), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.y, w.an }, { w.cat });
op_fac = rw(b, gemm_b(lrows, hs, 3 * hs, w_fac, b_fac), { w.cat }, { w.fh });
op_silu_f = rw(b, silu(lrows, hs), { w.fh }, { w.fhs });
op_edge = rw(b, gemm_b(lrows, 2 * fd, hs, w_edge, b_edge), { w.fhs }, { w.edges });
op_aout = rw(b, gemm_b(g.max_seqs, fd, hs, w_aout, b_aout), { w.an }, { w.aout });
op_walk = rw(b, RAD_OP(b, "lili_walk",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", S),
RAD_INT("k", K), RAD_INT("n", fd), RAD_STR("dtype", "bf16"),
RAD_F64("eps", cfg.vec_eps), RAD_F64("scale", cfg.scale)),
RAD_NOWEIGHTS),
{ w.edges, w.aout, w.cand }, { w.tokens });
if (!op_logits || !op_stats || (g.world > 1 && (!op_sgath || !op_emb_ar)) || !op_pas ||
!op_cand || !op_emb || !op_tokp || !op_fdn || !op_attn || !op_silu_up || !op_onorm ||
!op_anc || !op_ctx || !op_annorm || !op_factor || !op_fac || !op_silu_f || !op_edge ||
!op_aout || !op_walk)
return RAD_E_INVAL;
return RAD_OK;
}
inline void LiliCorr::step(RadCtx* c, const RadBatch* batch) const {
const int64_t n = batch->n_seq, S = n * cfg.steps, Lr = S * cfg.k;
if (n <= 0) return;
if (!batch->anchor_rows) {
rad_step_fail(c, "lilicorr: the query pass carries no anchor rows (RadBatch::anchor_rows): "
"this engine does not position a block drafter's anchor");
return;
}
const int64_t E = g.n_embd, hs = cfg.hs, fd = cfg.fdim;
const int64_t sw = 2 + 2 * rk;
RAD_ISSUE_N(c, op_logits, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.logits, S));
RAD_ISSUE_N(c, op_stats, S, brows(w.logits, S), RAD_NONE, brows(w.stats, S));
if (op_sgath) RAD_ISSUE(c, op_sgath, brows(w.stats, S), brows(w.sgath, S));
RAD_ISSUE_N(c, op_pas, S, brows(w.sel_h, S), RAD_W(w_pass), RAD_W(b_pass), RAD_NONE,
brows(w.pas, S));
RAD_ISSUE_N(c, op_cand, S, op_sgath ? brows(w.sgath, S) : brows(w.stats, S), brows(w.pas, S),
RAD_W(ln_w), RAD_W(ln_b), RAD_W(up_w), RAD_W(up_b), RAD_W(w_slot), RAD_W(w_rank),
brow_slice(w.cand, 0, Lr, 1), brows(w.feat, Lr), brows(w.hh, Lr));
(void)sw;
RAD_ISSUE_N(c, op_emb, Lr, brow_slice(w.cand, 0, Lr, 1), RAD_W(w_tok), brows(w.emb, Lr));
if (op_emb_ar) RAD_ISSUE_N(c, op_emb_ar, Lr * E, brows(w.emb, Lr), RAD_NONE);
RAD_ISSUE_N(c, op_tokp, Lr, brows(w.emb, Lr), RAD_W(w_tokp), RAD_W(b_tokp), brows(w.hh, Lr),
brows(w.hh, Lr));
RAD_ISSUE_N(c, op_fdn, Lr, brows(w.feat, Lr), RAD_W(w_fdn), RAD_W(b_fdn), brows(w.hh, Lr),
brows(w.hh, Lr));
for (int64_t l = 0; l < cfg.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_anorm[i], Lr, brows(w.hh, Lr), RAD_W(w_anorm[i]), brows(w.y, Lr));
RAD_ISSUE_N(c, op_in[i], Lr, brows(w.y, Lr), RAD_W(w_in[i]), RAD_W(b_in[i]), RAD_NONE,
brows(w.qkv, Lr));
RAD_ISSUE_N(c, op_attn, Lr, brows(w.qkv, Lr), RAD_W(w_rel), RAD_W(w_same), brows(w.att, Lr));
RAD_ISSUE_N(c, op_out[i], Lr, brows(w.att, Lr), RAD_W(w_out[i]), RAD_W(b_out[i]),
brows(w.hh, Lr), brows(w.hh, Lr));
RAD_ISSUE_N(c, op_mnorm[i], Lr, brows(w.hh, Lr), RAD_W(w_mnorm[i]), brows(w.y, Lr));
RAD_ISSUE_N(c, op_up[i], Lr, brows(w.y, Lr), RAD_W(w_up[i]), RAD_W(b_up[i]), RAD_NONE,
brows(w.up, Lr));
RAD_ISSUE_N(c, op_silu_up, Lr, brows(w.up, Lr), brows(w.ups, Lr));
RAD_ISSUE_N(c, op_dn[i], Lr, brows(w.ups, Lr), RAD_W(w_dn[i]), RAD_W(b_dn[i]),
brows(w.hh, Lr), brows(w.hh, Lr));
}
RAD_ISSUE_N(c, op_onorm, Lr, brows(w.hh, Lr), RAD_W(w_onorm), brows(w.y, Lr));
RAD_ISSUE_N(c, op_anc, n, RAD_B(w.c), praw(batch->anchor_rows, RAD_I32, n), brows(w.anc, n));
RAD_ISSUE_N(c, op_ctx, n, brows(w.anc, n), RAD_W(w_ctx), RAD_W(b_ctx), RAD_NONE, brows(w.ast, n));
RAD_ISSUE_N(c, op_annorm, n, brows(w.ast, n), RAD_W(w_annorm), brows(w.an, n));
RAD_ISSUE_N(c, op_factor, Lr, brows(w.y, Lr), brows(w.an, n), brows(w.cat, Lr));
RAD_ISSUE_N(c, op_fac, Lr, brows(w.cat, Lr), RAD_W(w_fac), RAD_W(b_fac), RAD_NONE,
brows(w.fh, Lr));
RAD_ISSUE_N(c, op_silu_f, Lr, brows(w.fh, Lr), brows(w.fhs, Lr));
RAD_ISSUE_N(c, op_edge, Lr, brows(w.fhs, Lr), RAD_W(w_edge), RAD_W(b_edge), RAD_NONE,
brows(w.edges, Lr));
RAD_ISSUE_N(c, op_aout, n, brows(w.an, n), RAD_W(w_aout), RAD_W(b_aout), RAD_NONE,
brows(w.aout, n));
RAD_ISSUE_N(c, op_walk, n, brows(w.edges, Lr), brows(w.aout, n),
brow_slice(w.cand, 0, Lr, 1), brows(w.tokens, n), RAD_NONE);
(void)E; (void)hs; (void)fd;
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_LILICORR_H */
+16 -7
View File
@@ -132,9 +132,9 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
swiglu_limit));
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain
* MXFP4 at one to 16 rows (eight where K is short). Other gate_up encodings (M2XFP4 included),
* and a clamped (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would
* take it, which would pin the layer's weights to the host. */
* MXFP4 at one to 16 rows (eight where K is short), decl_gated_fold_iqr for an IQR weight
* whose input and output are the rotated int8 trunk's fed pairs, to 16 rows. Other gate_up
* encodings (M2XFP4 included), and a clamped (swiglu_limit) product, take the pair. */
const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale;
if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 &&
!gate_up.i8)
@@ -144,6 +144,14 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
&gated_rows, wide_fold);
else if (fold_ok && gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.ffn.q8_fed && w.ffn.q8_rot)
op_gated = decl_gated_fold_iqr(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
{ w.h.q8, w.h.s8 },
gq_ffn.want_x
? std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8,
w.ffn.x }
: std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8 },
&gated_rows);
else if (fold_ok && gate_up.mx && !gate_up.paro)
op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
gate_up.wref, { w.h.q, w.h.s },
@@ -207,10 +215,11 @@ inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
} else if (op_gated && rows <= gated_rows) {
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff),
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
/* The fp8a8 fold's E4M3 pairs, or the IQR fold's int8 ones (cq / cs: the fed pair). */
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.cq(), r0, rows, g.n_embd),
brow_slice(w.h.cs(), r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
RAD_W(gate_up.ws), brow_slice(w.ffn.cq(), r0, rows, g.n_ff),
brow_slice(w.ffn.cs(), r0, rows, g.n_ff / RAD_FP8_BLOCK),
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
} else {
gate_up.step(c, w.h, w.gate_up, T, r0, rows);
+405 -154
View File
@@ -182,8 +182,19 @@ struct MoeFP8 {
/* Block-fp8 experts whose scale plane is f32 (format 9, dtype fp8a8f32). */
int expert_f32_scale = 0;
double route_scale = 1.0;
/* With `sigmoid_router`: group-limited selection over `n_group` groups, `topk_group` kept
* (router_sigmoid_group_topk; Ling-3.0). 1 is GLM's single group. The fused selection and
* sort is single-group, so a grouped router runs the separate pair. */
int64_t n_group = 1, topk_group = 1;
/* Clamp of the SwiGLU product (swiglu_clamped); 0 is none. */
double swiglu_limit = 0.0;
/* The shared arm's clamp where it differs from the routed one (Ling-3.0 clamps its shared
* expert at 5 or 7 and its routed ones at 4, in different layers); negative: the routed
* arm's. */
double shared_swiglu_limit = -1.0;
/* Clip after the SiLU (`swiglu_step`) rather than before it (`swiglu_clamped`), for both
* arms. */
int swiglu_step = 0;
/* With `swiglu_limit`: the clamped product and its quantiser as one launch
* (GateQuantFP8::fuse_clamped), for the routed and the shared arm. */
int swiglu_quant = 0;
@@ -196,6 +207,19 @@ struct MoeFP8 {
* At TP1 the ungated gather preserves both roundings; TP>1 reduces each arm separately
* before combining, so its gather cannot fold the shared output. */
int shared_fp32_combine = 0;
/* Experts without a gate (Nemotron-H): one projection up (`up_proj`), relu(x)^2, and down,
* so the first GEMM is n_ff_exp wide rather than 2 * n_ff_exp and the quantiser between
* the GEMMs squares rather than gates (GateQuantFP8's "relu2"). The routed arm only: such a
* family's shared expert is the caller's. */
int ungated = 0;
/* The router's input width when it is not the experts' (Nemotron-H's latent experts: the
* router scores the full hidden state, the experts read a narrower projection of it, and
* this block's Geom is the experts'). 0 means n_embd. With it the router reads
* Wire::route. The sigmoid router only. */
int64_t router_k = 0;
/* The caller reduces the block's delta across ranks, because it applies more linear work
* to it first (Nemotron-H's latent up-projection); no all-reduce is declared. */
int no_reduce = 0;
/* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for
* Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8`
* registry row). It is the stored encoding: probe() reads it from the first expert's
@@ -235,6 +259,17 @@ struct MoeFP8 {
* layer's; the 64-group codebook forms may differ by layer and projection, and declare()
* resolves each layer's (MoeFP8::fmt). */
int expert_w5 = 0;
int expert_w6 = 0; /* six-bit codebook, E4M3 scale per 64 */
/* Int8 experts (`i8*bf16[1x128]/fwht128`): codes -127..127 with a bf16 scale per (row, 128
* of K), each 128 of K rotated as `expert_rot` describes, read against int8 activations
* (dtype `i8a8h`). The eight-bit expert of an int8 model, where block fp8 is that of an
* E4M3 one. Set with `expert_rot`. */
int expert_i8 = 0;
/* Experts as IQR weights: the rotated computed trellis (libquant's tcq_code=mad) under one
* f32 scale a row, two to six bits a code, each expert decoded where the grouped GEMM
* reads it against the rotated int8 activations (dtype `i8a8h`, libr4d's moe_gemm_iqr).
* Set with `expert_rot`. */
int expert_iqr = 0;
/* Plain bf16 experts (no quantising recipe). Both GEMMs are `moe_gemm` over one table of
* whole experts with `silu_mul` between, and the shared arm follows the trunk
* (Geom::w_bf16). Not sliced by parity: each expert is served whole on its rank, which
@@ -267,6 +302,8 @@ struct MoeFP8 {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the block's delta */
/* The router's input when Config::router_k is set; `h` otherwise. */
rad_buf route = 0; /* [max_tok, router_k] bf16 */
/* Rotated codes of the same input (only `q` and `s`; `x` is `h`'s). Declared only with
* `expert_rot`: the routed gate_up reads them, the shared expert reads `h`'s. */
ActFP8 hr{}; /* [max_tok, n_embd] q + scale only */
@@ -276,6 +313,11 @@ struct MoeFP8 {
rad_buf ew = 0; /* [max_tok, top_k] F32 for sigmoid_router, BF16 otherwise */
rad_buf eoff = 0; /* [n_expert + 1] i32 */
rad_buf ecnt = 0; /* [n_expert] i32 */
/* Above 0, `ecnt` is the model's routing table (rad_route_table), [layers, ecnt_pitch],
* and this block's counts are its row `layer`: the report then costs no copy and every
* layer keeps its own counts. 0: `ecnt` is one row, which the layers sharing the wire
* overwrite in turn. */
int64_t ecnt_pitch = 0;
/* the expert planes, one row per (token, slot), a pass tall */
rad_buf sorted = 0; /* [rows * top_k] i32, pass-relative slot indices */
/* Each slot's row in `sorted`, -1 when dropped; with it the sort writes the gather's slot
@@ -338,6 +380,18 @@ struct MoeFP8 {
NormQuantFP8 nq_h{};
GateQuantFP8 gq_exp{}, gq_sh{};
/* The shared arm's gate_up and its quantiser as one launch (decl_gated_fold_iqr), and the rows
* it serves; 0 where the pair runs. */
rad_op op_sh_gated = 0;
int64_t sh_gated_rows = 0;
/* Whether the routed gate_up is a trellis weight (moe_gemm_iqr), and the routed rows from
* which the shared arm's first stage then runs beside the router instead (pass()). */
bool gu_trellis = false;
static constexpr int64_t kSharedFirstRows = 100;
/* The steps, by their rows [lo, hi], whose shared down projection is issued in front of the
* routed down GEMM instead of behind it (pass()); hi 0, the default, keeps it behind on
* every step. */
int64_t sh_down_first_lo = 0, sh_down_first_hi = 0;
LinearFP8 sh_gate_up{}, sh_down{};
rad_op op_router = 0, op_topk = 0, op_scatter = 0;
/* `op_scatter` is moe_scatter_inv and `op_gather` moe_gather_inv: the sort writes `w.inv` and
@@ -366,6 +420,16 @@ struct MoeFP8 {
* no quantiser for it. Set before declare. */
bool hr_in = false;
rad_op op_gu = 0, op_dn = 0, op_gather = 0;
/* The routed arm's activations are int8: rotated codes with an f32 scale per (row, group),
* which the grouped GEMMs meet with the iu8 WMMA (the `a8i8` and `i8a8h` dtypes). The
* architecture asks for it by feeding `Wire::eff` int8 (ActFP8::q8_fed with q8_rot); int8
* experts take nothing else, and the rotated four-bit forms take either. Resolved by
* declare(). */
bool a8 = false;
/* The codes gate_up reads and the K one of their scales covers: `h`'s own pair where the
* trunk feeds rotated int8 (at its group, 128 or IQ8R's 256), else `hr`'s. */
rad_buf gin_q = 0, gin_s = 0;
int64_t gin_g = RAD_FP8_BLOCK;
/* Protected experts: local experts a quantised layer keeps bf16, the few whose output dwarfs
* the rest (docs/MOE-W4.md). The scatter sorts them last (`protect`, `prot_list`), the
* quantised GEMMs serve the other `n_reg`, and a bf16 grouped GEMM pair serves these over the
@@ -387,9 +451,13 @@ struct MoeFP8 {
* number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4). */
int ncls = 2;
/* This layer's gate_up and down formats (format_of's numbers), resolved by declare(): the
* probed layer's, except that among the codebook forms at E4M3 scales (w4nl64a8h, w4nl32a8h,
* w5nl64a8h) each projection of each layer takes its own experts'. */
* probed layer's, except that among the forms reading one input (declare()'s `family`: the
* codebook forms at E4M3 scales, or under an int8 routed arm every form with an int8 row) each
* projection of each layer takes its own experts'. */
int fmt[2] = { 0, 0 };
/* The encoding of the layer's first quantised expert, per projection: a trellis's code width
* is the views' dtype. */
RadEncoding fenc[2]{};
std::vector<rad_weight> w_pgu, w_pdn;
rad_buf b_pgu = 0;
ActFP8 pff{};
@@ -443,11 +511,18 @@ struct MoeFP8 {
static int probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg);
/* The format `e` names: 0 block fp8, 1 four-bit, 2 four-bit rotated, 3 plain bf16, 4 the
* rotated w4nl codebook, 5 and 6 that codebook at E4M3 scales per 64 and 32 of K, 7 its
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales; RAD_E_DTYPE otherwise. */
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales, 10 rotated int8, 11 the rotated
* computed trellis under one f32 scale a row (an IQR weight an expert); RAD_E_DTYPE
* otherwise. */
static int format_of(const RadEncoding& e);
/* format_of's numbers as the grouped GEMMs' dtype strings. */
static constexpr const char* kServed[10] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8", "fp8a8f32" };
/* format_of's numbers as the grouped GEMMs' dtype strings against an E4M3 activation, and
* against an int8 one (null: the format has no such row). Int8 experts read int8 only. */
static constexpr const char* kServed[13] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8",
"fp8a8f32", nullptr, nullptr, "w6nl64a8h" };
static constexpr const char* kServed8[13] = { nullptr, nullptr, "w4a8i8h", nullptr, nullptr,
"w4nl64a8i8h", "w4nl32a8i8h", nullptr, nullptr,
nullptr, "i8a8h", "i8a8h", nullptr };
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
@@ -479,6 +554,10 @@ struct MoeFP8 {
inline int MoeFP8::format_of(const RadEncoding& e) {
if (linear_is_mxfp4(e)) return 8;
if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return 3;
/* The computed trellis under one f32 scale a row, rotated (IQR-V4's feed-forward form). */
if (rad_enc_is(&e, "trellis"))
return std::strcmp(e.transform, "fwht128") == 0 && linear_w8h_mad(e) &&
linear_w8h_rowf(e) ? 11 : RAD_E_DTYPE;
if (!rad_enc_is(&e, "affine")) return RAD_E_DTYPE;
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
/* The codebook at E4M3 scales per 64 or 32 of K under one fixed f32 (w4nl64a8h, w4nl32a8h),
@@ -495,6 +574,8 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
return sc->block[1] == RAD_FP8_BLOCK / 2 ? 5 : 6;
if (t->extent[1] == 32 && e.plane[0].dtype == RAD_U5 && sc->block[1] == RAD_FP8_BLOCK / 2)
return 7;
if (t->extent[1] == 64 && e.plane[0].dtype == RAD_U6 && sc->block[1] == RAD_FP8_BLOCK / 2)
return 12;
return RAD_E_DTYPE;
}
if (!sc) return RAD_E_DTYPE;
@@ -518,6 +599,9 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
if (!e.transform[0]) return 1;
if (std::strcmp(e.transform, "fwht128") == 0) return 2;
}
if (e.plane[0].dtype == RAD_I8 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK &&
std::strcmp(e.transform, "fwht128") == 0)
return 10;
return RAD_E_DTYPE;
}
@@ -547,17 +631,19 @@ inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const c
/* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the
* checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */
inline int moe_map_gate_up(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
long long ge) {
long long ge, bool ungated = false) {
if (src.experts_gate_up) return map_slice(b, guw, src.experts_gate_up, (int)ge);
if (src.experts_gate && src.experts_up)
return map_slice_concat(b, guw, {src.experts_gate, src.experts_up}, (int)ge);
/* Ungated experts (Nemotron-H) have no gate_proj: the first GEMM is up_proj alone. */
if (ungated) return map_copy(b, guw, nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge));
return map_concat(b, guw, {nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge),
nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge)});
}
inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
const char* dnw, long long ge, bool gate_up) {
if (gate_up) RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge));
if (gate_up) RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge, src.cfg.ungated));
if (src.experts_gate_up || src.experts_gate)
return map_slice(b, dnw, src.experts_down, (int)ge);
return map_copy(b, dnw, nm.ckpt("%s.%lld.down_proj.weight", src.experts, ge));
@@ -584,11 +670,12 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
int f = 0;
for (long long ge = g0; ge < gn && ge <= g0 + kMaxProtected; ++ge) {
const char* guw = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge);
RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge));
RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge, cfg->ungated));
cfg->probed_count = ge - g0 + 1;
RadEncoding e{};
f = 0;
if (weight_enc(b, guw, &e) && (f = format_of(e)) < 0) {
const bool known = weight_enc(b, guw, &e);
if (known && (f = format_of(e)) < 0) {
char en[256];
rad_enc_format(&e, en, sizeof en);
fprintf(stderr, "radiance: '%s' is %s, and the routed experts are served as block fp8 "
@@ -596,17 +683,23 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
"/fwht128; or u4 codes into a 16-entry f32 table, /fwht128) or plain "
"bf16; or the codebook at E4M3 scales a 64 or 32 of K under a fixed "
"f32, or its 32-entry five-bit form at a 64, or OCP MXFP4 "
"(fp4_e2m1*e8m0[1x32]). "
"Convert it with a recipe that makes one of them.\n", guw, en);
"(fp4_e2m1*e8m0[1x32]), or rotated int8 (i8*bf16[1x128]/fwht128), or "
"the rotated computed trellis under one f32 scale a row. Convert it "
"with a recipe that makes one of them.\n", guw, en);
return RAD_E_DTYPE;
}
if (known && (f == 0 || f == 8 || f == 9))
return linear_refuse_retired(guw, f == 8 ? "MXFP4" : "block fp8");
if (f != 3) break;
}
cfg->expert_w4 = (f == 1 || f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7) ? 1 : 0;
cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 0;
cfg->expert_w4 = (f == 1 || f == 2 || f == 4 || f == 5 || f == 6 || f == 7 || f == 12) ? 1 : 0;
cfg->expert_rot = (f == 2 || f == 4 || f == 5 || f == 6 || f == 7 || f == 10 || f == 11 || f == 12) ? 1 : 0;
cfg->expert_i8 = f == 10 ? 1 : 0;
cfg->expert_iqr = f == 11 ? 1 : 0;
cfg->expert_nl = (f == 4 || f == 5 || f == 6 || f == 7 || f == 12) ? 1 : 0;
cfg->expert_g64 = (f == 5 || f == 7 || f == 12) ? 2 : f == 6 ? 4 : 0;
cfg->expert_w5 = f == 7 ? 1 : 0;
cfg->expert_w6 = f == 12 ? 1 : 0;
cfg->expert_bf16 = f == 3 ? 1 : 0;
cfg->expert_mx = f == 8 ? 1 : 0;
cfg->expert_f32_scale = f == 9 ? 1 : 0;
@@ -618,6 +711,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
int ar_in, bool ar_out_) {
g = geom; c = src.cfg; w = wire; layer = l;
ar_out = ar_out_;
if (c.n_group > 1) c.router_fuse = 0;
const double sh_limit = c.shared_swiglu_limit < 0 ? c.swiglu_limit : c.shared_swiglu_limit;
/* 0 means not expert-parallel: this rank owns every expert. */
if (c.n_expert_all <= 0) c.n_expert_all = c.n_expert;
if (c.n_expert <= 0 || c.top_k <= 0 || c.top_k > c.n_expert_all || c.n_ff_exp <= 0)
@@ -639,6 +734,21 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
"BF16 shared arm and routed output\n", l);
return RAD_E_INVAL;
}
/* The first GEMM's rows per intermediate column (gate and up, or up alone) and the activation
* between the GEMMs. */
const int64_t gu = c.ungated ? 1 : 2;
const char* const gact = c.ungated ? "relu2" : "silu";
if (c.ungated && (shared || src.experts_gate_up || src.experts_gate ||
c.swiglu_limit > 0)) {
fprintf(stderr, "radiance: ungated experts are served one by one (`up_proj`), unclamped and "
"without a shared arm in this block\n");
return RAD_E_INVAL;
}
if (c.router_k && (!c.sigmoid_router || !w.route)) {
fprintf(stderr, "radiance: a router over another input than the experts' is the sigmoid "
"router reading Wire::route\n");
return RAD_E_INVAL;
}
/* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by
* the fused router's gate write (see there). */
bool sgate_concurrent = false;
@@ -648,7 +758,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* refused, since the fused all-reduce lives inside the norm. See rad_block_attn_gated_fp8.h. */
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;
if (!w.h.x || (!g.w_bf16 && (!w.h.cq() || !w.h.cs())) || ar_in != kArNone)
return RAD_E_INVAL;
} else {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l), src.norm));
w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd},
@@ -669,9 +780,12 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_ARCH_TRY(moe_map_expert(b, nm, src, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge),
nm.f("blk.%d.ffn_down_exps.%lld.weight", l, ge), ge, !probed));
}
/* The routed arm's activations (see `a8`), known before the layer's formats are resolved:
* which forms may share a model depends on the codes they read. */
a8 = w.eff.q8_fed && !c.expert_bf16;
prot.clear();
{
const int want = c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
const int want = c.expert_iqr ? 11 : c.expert_i8 ? 10 : c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w6 ? 12 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
: c.expert_g64 ? 5 : c.expert_nl ? 4
: c.expert_w4 ? (c.expert_rot ? 2 : 1) : 0;
auto fmt_of = [&](int64_t e, RadEncoding (&enc)[2], int (&fe)[2], const char* (&nmv)[2]) {
@@ -683,36 +797,54 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
if (weight_enc(b, nmv[i], &enc[i])) fe[i] = format_of(enc[i]);
}
};
/* The codebook forms at E4M3 scales differ only in the GEMM's dtype (same rotated input,
* scale views, fixed second level, accumulators), so each layer and projection may use any
* of them. The layer's first non-bf16 expert decides both; every other must match. Outside
* that family a layer uses the probed layer's form. */
auto family = [](int f) { return f == 5 || f == 6 || f == 7; };
/* The forms that read one input may differ by layer and projection: against E4M3 codes the
* codebook forms at E4M3 scales (same rotated input, scale views, fixed second level,
* accumulators; only the GEMM's dtype differs), and against the rotated int8 pair every
* form with a row for it (four-bit, the codebook at a 64 or 32 of K, int8), whose views
* efmt_of states per projection. The layer's first non-bf16 expert decides both
* projections; every other must match. Outside its family a layer uses the probed
* layer's form. */
const bool a8f = a8;
auto family = [a8f](int f) {
return a8f ? (f == 2 || f == 5 || f == 6 || f == 10 || f == 11)
: (f == 5 || f == 6 || f == 7 || f == 12);
};
fmt[0] = fmt[1] = want;
if (family(want))
for (int64_t e = 0; e < ne; ++e) {
RadEncoding enc[2]{};
int fe[2];
const char* nmv[2];
fmt_of(e, enc, fe, nmv);
if (fe[0] == 3 && fe[1] == 3) continue;
for (int i = 0; i < 2; ++i)
if (family(fe[i])) fmt[i] = fe[i];
break;
fenc[0] = fenc[1] = RadEncoding{};
for (int64_t e = 0; e < ne; ++e) {
RadEncoding enc[2]{};
int fe[2];
const char* nmv[2];
fmt_of(e, enc, fe, nmv);
if (fe[0] == 3 && fe[1] == 3) continue;
for (int i = 0; i < 2; ++i) {
/* A trellis gate_up reads rotated int8, but the down projection can use the
* W5NL E4M3 kernel: its gated intermediate is quantised independently below. */
const bool mixed_codebook_down = a8f && want == 11 && i == 1 &&
(fe[i] == 7 || fe[i] == 12);
if (family(want) && (family(fe[i]) || mixed_codebook_down)) fmt[i] = fe[i];
fenc[i] = enc[i];
}
break;
}
for (int64_t e = 0; e < ne; ++e) {
RadEncoding enc[2]{};
int fe[2];
const char* names[2];
fmt_of(e, enc, fe, names);
if (fe[0] == fmt[0] && fe[1] == fmt[1]) continue;
/* A trellis layer is one code width a projection: the views are declared at it. */
const bool same = fe[0] == fmt[0] && fe[1] == fmt[1] &&
(fmt[0] != 11 || enc[0].plane[0].dtype == fenc[0].plane[0].dtype) &&
(fmt[1] != 11 || enc[1].plane[0].dtype == fenc[1].plane[0].dtype);
if (same) continue;
if (want != 3 && fe[0] == 3 && fe[1] == 3) { prot.push_back(e); continue; }
const int i = fe[0] != fmt[0] ? 0 : 1;
char en[256];
rad_enc_format(&enc[i], en, sizeof en);
fprintf(stderr, "radiance: '%s' is %s, and this layer's experts are served as %s -- one "
"table of experts takes one encoding, and only a whole expert kept "
"plain bf16 is served beside it.\n", names[i], en, kServed[fmt[i]]);
"plain bf16 is served beside it.\n", names[i], en,
kServed[fmt[i]] ? kServed[fmt[i]] : kServed8[fmt[i]]);
return RAD_E_DTYPE;
}
}
@@ -764,9 +896,13 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rc.rows = c.rows;
rc.norm = c.norm_topk;
rc.route_scale = c.route_scale;
const GlmRouter::Wire wire{ w.h.x, w.logits, w.ids, w.ew };
rc.groups = c.n_group;
rc.topk_groups = c.topk_group;
const GlmRouter::Wire wire{ c.router_k ? w.route : w.h.x, w.logits, w.ids, w.ew };
const GlmRouter::Src rs{ src.router, src.router_bias };
RAD_ARCH_TRY(glm_router.declare(b, nm, g, l, nm.f("blk.%d.glm_router", l), rc, wire, rs));
Geom rg = g;
if (c.router_k) rg.n_embd = c.router_k;
RAD_ARCH_TRY(glm_router.declare(b, nm, rg, l, nm.f("blk.%d.glm_router", l), rc, wire, rs));
w_router = glm_router.projection;
op_router = glm_router.op_project;
op_topk = glm_router.op_select;
@@ -901,14 +1037,33 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
(long long)wq[q], (long long)g.n_embd, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
/* The codes view's dtype and planes; a codebook's table is selected with its codes so the
* relayout sees it. */
auto edt_of = [&](int f) {
return f == 8 ? (uint32_t)RAD_FP4E2M1 : f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4
: c.expert_w4 ? (uint32_t)RAD_I4 : (uint32_t)RAD_F8E4M3;
/* A format's views: the codes view's dtype and planes (a codebook's table is selected with its
* codes so the relayout sees it), and the scale view's -- bf16 per
* (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group forms E4M3 per (row, 64 of
* K) selected with the fixed second level; f32 per 128x128 tile (format 9) or E8M0 per (row, 32
* of K) for MXFP4. `sgk` is the K one declared scale column covers: a view of two planes is a
* view of the logical weight, like the codes view (rad_builder.cpp), declared at the weight's
* extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout
* hook. */
struct EFmt { uint32_t cdt; const char* cplanes; uint32_t sdt; int64_t sgk; const char* splanes; };
auto efmt_of = [](int f, const RadEncoding& fe) -> EFmt {
switch (f) {
/* An IQR weight: the codes at their stored width with the code's planes, and the row and
* block scales as one view at the weight's extents (LinearFP8's views of the same form). */
case 12: return { RAD_U6, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
case 11: return { fe.plane[0].dtype, "codes,trellis,trellis.mad", RAD_F32, 1,
"scale,scale.col" };
case 10: return { RAD_I8, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
case 9: return { RAD_F8E4M3, "codes", RAD_F32, RAD_FP8_BLOCK, "scale" };
case 8: return { RAD_FP4E2M1, "codes", RAD_E8M0, RAD_MX_GROUP, "scale" };
case 7: return { RAD_U5, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
case 5: case 6: return { RAD_U4, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
case 4: return { RAD_U4, "codes,table", RAD_BF16, RAD_FP8_BLOCK, "scale" };
case 1: case 2: return { RAD_I4, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
default: return { RAD_F8E4M3, "codes", RAD_BF16, RAD_FP8_BLOCK, "scale" };
}
};
const uint32_t edt[2] = { edt_of(fmt[0]), edt_of(fmt[1]) };
const char* const ecodes = c.expert_nl ? "codes,table" : "codes";
const EFmt ef[2] = { efmt_of(fmt[0], fenc[0]), efmt_of(fmt[1], fenc[1]) };
/* Under expert parallelism each owned expert is whole, so its weights are not sharded;
* RAD_SHARD_ROW would make the loader slice it again (and refuse). */
const bool ep = c.n_expert != c.n_expert_all;
@@ -923,33 +1078,57 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
*
* Rotation exists only for the 4-bit plane (the fp8 layout hook has no rotated form), and the
* codebook only with rotation; other combinations are refused. */
if ((c.expert_rot && !c.expert_w4) || (c.expert_nl && !c.expert_rot)) {
fprintf(stderr, "radiance: rotated experts (expert_rot) require the 4-bit expert format, "
"and a codebook (expert_nl) the rotated one; there is no rotated E4M3 "
"expert plane and no unrotated codebook\n");
if ((c.expert_rot && !c.expert_w4 && !c.expert_i8 && !c.expert_iqr) ||
(c.expert_nl && !c.expert_rot) || ((c.expert_i8 || c.expert_iqr) && !c.expert_rot)) {
fprintf(stderr, "radiance: rotated experts (expert_rot) require the 4-bit or the int8 "
"expert format, and a codebook (expert_nl) or int8 experts the rotated "
"one; there is no rotated E4M3 expert plane, no unrotated codebook and no "
"unrotated int8 expert\n");
return RAD_E_INVAL;
}
/* ---- The routed arm's activations (see `a8`). */
if ((c.expert_i8 || c.expert_iqr || fmt[0] == 10 || fmt[0] == 11 ||
fmt[1] == 10 || fmt[1] == 11) && !a8) {
fprintf(stderr, "radiance: layer %d's experts read int8 activations (int8, or an IQR weight); the "
"architecture declared the routed arm's codes E4M3\n", l);
return RAD_E_UNSUPPORTED;
}
const bool down_codebook_fp8 = a8 && fmt[0] == 11 && (fmt[1] == 7 || fmt[1] == 12);
if (a8) {
const bool pair = w.eff.q8 && w.eff.s8 && w.eff.q8_rot && w.eff.g8 == RAD_FP8_BLOCK;
const bool down_supported = down_codebook_fp8 ? (w.eff.q && w.eff.s && kServed[fmt[1]])
: kServed8[fmt[1]] != nullptr;
/* A clamped layer is served too: GateQuantFP8 clamps into the bf16 plane, then
* quantises it into the rotated codes. Not before a codebook (W5NL, W6NL) down
* projection, which reads rotated E4M3: no clamp writes those codes. */
const bool clamp_codebook = down_codebook_fp8 && c.swiglu_limit > 0;
if (!pair || !c.expert_rot || !kServed8[fmt[0]] || !down_supported || c.calib ||
clamp_codebook) {
fprintf(stderr, "radiance: layer %d: int8 activations meet rotated experts (int8, "
"four-bit, or the codebook at E4M3 scales a 64 or 32 of K) through "
"rotated codes at one scale a 128 of K, outside calibration; these "
"are %s / %s%s%s\n", l,
kServed[fmt[0]] ? kServed[fmt[0]] : kServed8[fmt[0]],
kServed[fmt[1]] ? kServed[fmt[1]] : kServed8[fmt[1]],
pair ? "" : ", and the gated product's int8 pair is not that",
clamp_codebook ? ", and a W5NL or W6NL down projection is served unclamped only"
: "");
return RAD_E_UNSUPPORTED;
}
}
const int sh_row = ep ? RAD_SHARD_NONE : RAD_SHARD_ROW;
const int sh_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL;
const int n_parts = ep ? 0 : 2;
const int n_parts = ep ? 0 : (int)gu;
/* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit (per 32
* for MXFP4). `sdiv` is how many weight rows or columns one scale covers along the split
* dimension. */
const int64_t sdiv = (c.expert_w4 || c.expert_mx) ? 1 : RAD_FP8_BLOCK;
const bool rowscale = c.expert_w4 || c.expert_mx || c.expert_i8 || c.expert_iqr;
const int64_t sdiv = rowscale ? 1 : RAD_FP8_BLOCK;
/* The dtype string per projection selects the grouped GEMM; its layout hook then accepts the
* experts' encoding or the kernel is not a candidate. */
const char* const edtype[2] = { kServed[fmt[0]], kServed[fmt[1]] };
/* The scale views: bf16 per (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group
* forms E4M3 per (row, 64 of K) selected with the fixed second level; f32 per 128x128 tile
* (expert_f32_scale) or E8M0 per (row, 32 of K) for MXFP4. With two planes it is a
* view of the logical weight, like the codes view (rad_builder.cpp): declared at the weight's
* extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout
* hook. `sgk` is the K one declared scale column covers. */
const uint32_t sdt = c.expert_f32_scale ? (uint32_t)RAD_F32
: c.expert_mx ? (uint32_t)RAD_E8M0
: c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
const int64_t sgk = c.expert_mx ? RAD_MX_GROUP : c.expert_g64 ? 1 : RAD_FP8_BLOCK;
const char* escale = c.expert_g64 ? "scale,scale.1" : "scale";
gu_trellis = fmt[0] == 11;
const char* const edtype[2] = { a8 ? kServed8[fmt[0]] : kServed[fmt[0]],
a8 && !down_codebook_fp8 ? kServed8[fmt[1]] : kServed[fmt[1]] };
/* This class's slice of each expert: gate and up rows [lo, hi), down columns [lo, hi), scale
* planes the same in their own units. */
auto span = [&](rad_weight h, int q, int64_t unit) -> int {
@@ -969,10 +1148,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
return RAD_E_INVAL;
}
for (int64_t e = 0; e < ne; ++e) {
const int64_t parts[2] = { c.n_ff_exp, c.n_ff_exp };
const int64_t parts[2] = { c.n_ff_exp, c.n_ff_exp }; /* gate, up (up alone: one) */
w_gu[(size_t)e] = decl_w_n(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
RAD_BF16, {2 * c.n_ff_exp, g.n_embd}, RAD_ACCESS_CONDITIONAL,
RAD_BF16, {gu * c.n_ff_exp, g.n_embd}, RAD_ACCESS_CONDITIONAL,
sh_row, grp_expert_slot(l, (int)e, 0), 0, parts, n_parts);
if (!w_gu[(size_t)e]) return RAD_E_INVAL;
}
@@ -986,7 +1165,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* Row orders as for the quantised GEMMs (see `a_order` below): gate_up gathers token rows,
* down reads sorted rows. */
op_gu = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * c.n_ff_exp),
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * c.n_ff_exp),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", ne),
RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"),
RAD_STR("dtype", "bf16")),
@@ -996,8 +1175,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* (rad_fp8.h: GateQuantFP8). */
Geom gx = g;
gx.w_bf16 = true;
RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k,
true, false, c.swiglu_limit));
RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
true, false, c.swiglu_limit, c.swiglu_step != 0));
op_dn = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", c.n_ff_exp), RAD_INT("n_expert", ne),
@@ -1015,7 +1194,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rad_weight& h = w_gu[(size_t)s];
h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
nullptr, ecodes, edt[0], {2 * wq[q], g.n_embd},
nullptr, ef[0].cplanes, ef[0].cdt, {gu * wq[q], g.n_embd},
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
parts, n_parts);
if (!h) return RAD_E_INVAL;
@@ -1030,9 +1209,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
(long long)(c.expert_base + e)),
nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
escale, sdt,
{(c.expert_w4 || c.expert_mx) ? 2 * wq[q] : fp8_blocks(2 * wq[q]),
(c.expert_w4 || c.expert_mx) ? g.n_embd / sgk : fp8_blocks(g.n_embd)},
ef[0].splanes, ef[0].sdt,
{rowscale ? gu * wq[q] : fp8_blocks(gu * wq[q]),
rowscale ? g.n_embd / ef[0].sgk : fp8_blocks(g.n_embd)},
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
parts, n_parts);
if (!h) return RAD_E_INVAL;
@@ -1044,7 +1223,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rad_weight& h = w_dn[(size_t)s];
h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
nullptr, ecodes, edt[1], {g.n_embd, wq[q]},
nullptr, ef[1].cplanes, ef[1].cdt, {g.n_embd, wq[q]},
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
if (!h) return RAD_E_INVAL;
RAD_ARCH_TRY(span(h, q, 1));
@@ -1057,11 +1236,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
(long long)(c.expert_base + e)),
nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
escale, sdt,
{(c.expert_w4 || c.expert_mx) ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk},
ef[1].splanes, ef[1].sdt,
{rowscale ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / ef[1].sgk},
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
if (!h) return RAD_E_INVAL;
RAD_ARCH_TRY(span(h, q, sgk));
RAD_ARCH_TRY(span(h, q, ef[1].sgk));
}
/* ---- the two grouped GEMMs. `M` is a pass's token count, not the sorted row count: kernels
@@ -1076,19 +1255,32 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The routed arm's rotated copy of the input. Not in place: the shared expert also reads
* `w.h.q` with an unrotated weight (see Config::expert_rot). Declared just before its one
* consumer so graph and issue order agree. */
if (rot) {
if (!w.hr.q || !w.hr.s) {
fprintf(stderr, "radiance: rotated experts need the `hr` (q, scale) pair on the wire; "
"the architecture declares the buffers\n");
gin_q = w.h.q;
gin_s = w.h.s;
gin_g = RAD_FP8_BLOCK;
if (a8 && w.h.q8_fed && w.h.q8_rot) {
/* The trunk's own rotated int8 codes, at its group: no second quantiser. */
gin_q = w.h.q8;
gin_s = w.h.s8;
gin_g = w.h.g8;
} else if (rot) {
if (a8 ? !(w.hr.q8 && w.hr.s8 && w.hr.q8_fed && w.hr.q8_rot) : !(w.hr.q && w.hr.s)) {
fprintf(stderr, "radiance: rotated experts need the `hr` (q, scale) pair on the wire%s; "
"the architecture declares the buffers\n",
a8 ? ", int8 and fed" : "");
return RAD_E_INVAL;
}
gin_q = w.hr.cq();
gin_s = w.hr.cs();
gin_g = w.hr.cg();
if (!hr_in)
op_hq = rw(b, RAD_OP(b, "had_quant_act_fp8",
op_hq = rw(b, RAD_OP(b, a8 ? "had_quant_act_i8g" : "had_quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", gin_g), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h.x}, {w.hr.q, w.hr.s});
{w.h.x}, {gin_q, gin_s});
}
if (!gin_q || !gin_s || g.n_embd % gin_g) return RAD_E_INVAL;
/* A table op's weights in operand order: even experts' codes and scales, then odd experts'
* (`w`, `w_scale`, `w_odd`, `w_odd_scale`), or at four classes classes 0 to 3. */
auto tables = [&](const std::vector<rad_weight>& wc, const std::vector<rad_weight>& ws) {
@@ -1105,55 +1297,64 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* and the zeros past the width are never read by that class's down projection. */
{
const std::vector<rad_weight> tab = tables(w_gu, w_gus);
/* `a_group` is stated to the int8 rows alone: last, and cut off otherwise, so an E4M3
* graph is the one it was. */
const RadParam p4[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
RAD_INT("N_1", gu * wq[1]), RAD_INT("K_1", g.n_embd),
RAD_INT("N_2", gu * wq[2]), RAD_INT("K_2", g.n_embd),
RAD_INT("N_3", gu * wq[3]), RAD_INT("K_3", g.n_embd),
RAD_INT("parts", gu), RAD_INT("a_group", gin_g) };
const RadParam p2[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
RAD_INT("N_odd", gu * wq[1]), RAD_INT("K_odd", g.n_embd),
RAD_INT("parts", gu), RAD_INT("a_group", gin_g) };
const int cut = a8 ? 0 : 1;
rad_op h = ncls == 4
? rad_decl_op(b, "moe_gemm_q_mod4",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
RAD_INT("N_1", 2 * wq[1]), RAD_INT("K_1", g.n_embd),
RAD_INT("N_2", 2 * wq[2]), RAD_INT("K_2", g.n_embd),
RAD_INT("N_3", 2 * wq[3]), RAD_INT("K_3", g.n_embd),
RAD_INT("parts", 2)),
tab.data(), (int)tab.size())
: rad_decl_op(b, "moe_gemm_q",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
RAD_INT("N_odd", 2 * wq[1]), RAD_INT("K_odd", g.n_embd),
RAD_INT("parts", 2)),
tab.data(), (int)tab.size());
op_gu = rw(b, h, {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, w.sorted, w.eoff}, {w.egu});
? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut,
tab.data(), (int)tab.size())
: rad_decl_op(b, "moe_gemm_q", p2, (int)(sizeof p2 / sizeof *p2) - cut,
tab.data(), (int)tab.size());
op_gu = rw(b, h, {gin_q, gin_s, w.sorted, w.eoff}, {w.egu});
}
/* The down projection's input can be rotated in place: `w.eff` is read only by the down GEMM,
* which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to
* the rotated op at no extra launch. */
gq_exp.fuse_clamped = c.swiglu_quant != 0;
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k,
false, rot, c.swiglu_limit));
/* Gate_up and down are separate GEMMs. A trellis gate uses int8 input while W5NL down
* reads rotated E4M3: select the latter pair only for the gated intermediate. */
ActFP8 down_eff = w.eff;
if (down_codebook_fp8) down_eff.q8_fed = down_eff.q8_rot = false;
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, down_eff, c.n_ff_exp, gact, c.rows * c.top_k,
false, rot && (!a8 || down_codebook_fp8), c.swiglu_limit,
c.swiglu_step != 0));
{
const std::vector<rad_weight> tab = tables(w_dn, w_dns);
const RadParam p4[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]),
RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]),
RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]),
RAD_INT("parts", 1), RAD_INT("a_group", RAD_FP8_BLOCK) };
const RadParam p2[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]),
RAD_INT("parts", 1), RAD_INT("a_group", RAD_FP8_BLOCK) };
const int cut = a8 && !down_codebook_fp8 ? 0 : 1;
rad_op h = ncls == 4
? rad_decl_op(b, "moe_gemm_q_mod4",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]),
RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]),
RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]),
RAD_INT("parts", 1)),
tab.data(), (int)tab.size())
: rad_decl_op(b, "moe_gemm_q",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
RAD_INT("N_odd", g.n_embd), RAD_INT("K_odd", wq[1]),
RAD_INT("parts", 1)),
tab.data(), (int)tab.size());
op_dn = rw(b, h, {w.eff.q, w.eff.s, w.sorted, w.eoff}, {w.edn});
? rad_decl_op(b, "moe_gemm_q_mod4", p4, (int)(sizeof p4 / sizeof *p4) - cut,
tab.data(), (int)tab.size())
: rad_decl_op(b, "moe_gemm_q", p2, (int)(sizeof p2 / sizeof *p2) - cut,
tab.data(), (int)tab.size());
op_dn = rw(b, h, {down_eff.cq(), down_eff.cs(), w.sorted, w.eoff}, {w.edn});
}
/* ---- The protected experts' own GEMM pair. Their weights belong to the layer group, not to
* expert slots: each container expert unit has a fixed size and these are four times larger, so
@@ -1184,7 +1385,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* the plain even split with no span. */
psh_row = RAD_SHARD_ROW;
psh_col = RAD_SHARD_COL;
pparts = 2;
pparts = (int)gu;
if (full % g.world == 0 && (full / g.world) % 64 == 0) {
wp = full / g.world;
} else if (full % 64 || full / 64 < g.world) {
@@ -1206,7 +1407,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const int64_t parts[2] = { wp, wp };
w_pgu[(size_t)j] = decl_w_n(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + prot[(size_t)j])),
RAD_BF16, {2 * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN,
RAD_BF16, {gu * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN,
psh_row, grp_layer(l), 0, parts, pparts);
if (!w_pgu[(size_t)j]) return RAD_E_INVAL;
if (phi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w_pgu[(size_t)j], plo, phi));
@@ -1221,11 +1422,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
/* The gate_up and gate outputs, bf16, one sorted row each; regular experts' rows are
* unused. */
b_pgu = decl_b(b, nm.f("blk.%d.moe_prot_gu", l), RAD_BF16, {c.rows * c.top_k, 2 * wp});
b_pgu = decl_b(b, nm.f("blk.%d.moe_prot_gu", l), RAD_BF16, {c.rows * c.top_k, gu * wp});
pff.x = decl_b(b, nm.f("blk.%d.moe_prot_ff", l), RAD_BF16, {c.rows * c.top_k, wp});
if (!b_pgu || !pff.x) return RAD_E_INVAL;
op_pgu = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wp),
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wp),
RAD_INT("K", g.n_embd), RAD_INT("n_expert", np),
RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"),
RAD_STR("dtype", "bf16")),
@@ -1233,8 +1434,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
{w.h.x, w.sorted, w.eoff}, {b_pgu});
Geom gx = g;
gx.w_bf16 = true;
RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, "silu", c.rows * c.top_k, true,
false, c.swiglu_limit));
RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, gact, c.rows * c.top_k, true,
false, c.swiglu_limit, c.swiglu_step != 0));
op_pdn = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wp), RAD_INT("n_expert", np),
@@ -1290,7 +1491,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
RAD_NOWEIGHTS),
{rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, b_gram_gu}, {b_gram_gu});
{gin_q, gin_s, b_gram_gu}, {b_gram_gu});
/* The down tap's M is the sorted height `rows * top_k` (one row per (token, slot)).
* gate_up's is the token height: every token goes to exactly top_k experts, so the gathered
* distribution is the token distribution scaled by top_k, and H is used only up to scale. */
@@ -1363,7 +1564,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const char* shared_up = src.shared_mlp_up
? src.shared_mlp_up
: nm.ckpt("%s.up_proj.weight", src.shared);
RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base, { shared_down }));
/* An architecture that sized the gate's code pair from this weight has probed it. */
if (!sh_down.mapped) RAD_ARCH_TRY(sh_down.probe(b, nm, g, down_base, { shared_down }));
/* The code pair the gate writes, E4M3 or int8 (ActFP8::q8_fed); an int8 down projection
* that quantises for itself also writes the int8 pair on this lane. */
if (w.sff.cq()) {
@@ -1374,7 +1576,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.q8));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.s8));
}
if (!w.sff.q || c.swiglu_limit>0 || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
if (!w.sff.q || sh_limit>0 || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.x));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate));
@@ -1391,7 +1593,18 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
gq_sh.fuse_clamped = c.swiglu_quant != 0;
RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, "silu", c.rows,
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8), false,
c.swiglu_limit));
sh_limit, c.swiglu_step != 0));
/* An IQR gate_up between the rotated int8 trunk's fed pairs folds SwiGLU and the rotating
* quantiser into its epilogue, to 16 rows: one launch a layer less than the pair, which
* stays declared for longer steps, other encodings and a clamped product. */
if (sh_limit <= 0 && sh_gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.sff.q8_fed &&
w.sff.q8_rot)
op_sh_gated = decl_gated_fold_iqr(
b, c.rows, sh_gate_up.N, sh_gate_up.K, sh_gate_up.w, sh_gate_up.ws,
{ w.h.q8, w.h.s8 },
gq_sh.want_x ? std::initializer_list<rad_buf>{ w.sff.q8, w.sff.s8, w.sff.x }
: std::initializer_list<rad_buf>{ w.sff.q8, w.sff.s8 },
&sh_gated_rows);
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
{ shared_down },
@@ -1515,7 +1728,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
}
if (g.world > 1) {
if (g.world > 1 && !c.no_reduce) {
const auto all_reduce = [&](const char* dtype, rad_buf buffer) {
return rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -1536,7 +1749,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
/* 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)
if (g.world > 1 && !c.no_reduce && 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),
@@ -1592,7 +1805,14 @@ inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
brow_slice(w.sgate, r0, rows, 1));
}
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
if (op_sh_gated && rows <= sh_gated_rows)
RAD_ISSUE_N(c_, op_sh_gated, rows, brow_slice(w.h.cq(), r0, rows, g.n_embd),
brow_slice(w.h.cs(), r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(sh_gate_up.w),
RAD_W(sh_gate_up.ws), brow_slice(w.sff.cq(), r0, rows, c.n_ff_shared),
brow_slice(w.sff.cs(), r0, rows, c.n_ff_shared / RAD_FP8_BLOCK),
gq_sh.want_x ? brow_slice(w.sff.x, r0, rows, c.n_ff_shared) : RAD_NONE);
else
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
}
/* One pass of at most `c.rows` tokens. Every op is per row (norm and quantiser within a row,
@@ -1611,9 +1831,10 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
/* The shared arm is interleaved with the routed arm on the same queue. It reads the same
* input and writes nothing the routed arm touches before the gather, so each of its stages
* (gate + gate_up, quantiser, down) is issued right behind the matching routed stage. A
* recorded pass leaves each such pair unordered (Ctx::haz_mark), so they overlap without a
* second queue's fork/join cost. The arm's buffers are excluded from sharing (see declare), so
* (gate + gate_up, quantiser, down) is issued right behind the matching routed stage (its
* first stage behind the router instead where `sh_first` below says so). A recorded pass
* leaves each such pair unordered (Ctx::haz_mark), so they overlap without a second queue's
* fork/join cost. The arm's buffers are excluded from sharing (see declare), so
* issuing them ahead of their declared position is safe. */
/* The routed arm. */
@@ -1626,8 +1847,11 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
* the histogram the kernel writes there never lands, and a consumer reading the reported
* counts -- the file stager, at the layer's trigger -- sees zeros and skips every expert's
* weights. The declared buffer is stable across record and replay, and route_report hands
* the same buffer on, so the stager's stream-ordered read sees this pass's counts. */
const RadOperand ecnt = brows(w.ecnt, ne);
* the same buffer on, so the stager's stream-ordered read sees this pass's counts. With a
* routing table (Wire::ecnt_pitch) the buffer is the core's rows too, and this is the
* layer's. */
const RadOperand ecnt = w.ecnt_pitch > 0 ? brow_slice(w.ecnt, layer, 1, w.ecnt_pitch)
: brows(w.ecnt, ne);
/* The fused router when it resolved and the pass fits: router, topk + scatter and (with
* `router_fused_gate`) the shared gate in one launch. Otherwise the separate ops. */
const bool rfused = op_router_fused && rows <= router_fused_rows;
@@ -1677,13 +1901,22 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
const bool rot = c.expert_rot != 0;
if (op_hq)
RAD_ISSUE_N(c_, op_hq, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
brow_slice(w.hr.q, r0, rows, g.n_embd),
brow_slice(w.hr.s, r0, rows, g.n_embd / RAD_FP8_BLOCK));
brow_slice(gin_q, r0, rows, g.n_embd),
brow_slice(gin_s, r0, rows, g.n_embd / gin_g));
/* The grouped GEMMs. Each table is the first handle of its run and its length; runs are
* contiguous (see declare), so `w_gu[q] + i` is expert 2 * i + q, or 4 * i + q at four
* classes, where class q holds ceil((n_reg - q) / 4). */
const int64_t n4[4] = { (n_reg + 3) / 4, (n_reg + 2) / 4, (n_reg + 1) / 4, n_reg / 4 };
/* Behind a trellis gate_up from kSharedFirstRows routed rows, the shared arm's first stage is
* issued here, so it overlaps the router and the routed gate_up runs alone: that GEMM is
* compute-bound at such heights, and with the arm beside it the pair ends later than the two
* in turn. Flash-Next's 16- and 32-row verify passes on two R9700: 22.1 -> 21.9 ms and
* 31.6 -> 30.95 ms. Below, the arm fits inside the routed GEMM's time and stays beside it. */
const bool sh_first = shared && gu_trellis && rows * k >= kSharedFirstRows;
if (sh_first)
shared_up(c_, T, r0, rows,
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
/* Apply the previous layer's prefetch prediction: substitute the copied experts into the
* tables. */
(void)rad_expert_prefetch_step(c_, layer);
@@ -1693,8 +1926,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
brows(w.egu, rows * k));
else if (ncls == 4)
RAD_ISSUE_N(c_, op_gu, rows,
brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
brow_slice(gin_q, r0, rows, g.n_embd),
brow_slice(gin_s, r0, rows, g.n_embd / gin_g),
RAD_WTAB(w_gu[0], n4[0]), RAD_WTAB(w_gus[0], n4[0]),
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_gu[1], n4[1]), RAD_WTAB(w_gus[1], n4[1]),
@@ -1703,22 +1936,36 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
brows(w.egu, rows * k));
else
RAD_ISSUE_N(c_, op_gu, rows,
brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
brow_slice(gin_q, r0, rows, g.n_embd),
brow_slice(gin_s, r0, rows, g.n_embd / gin_g),
RAD_WTAB(w_gu[0], n_reg / 2), RAD_WTAB(w_gus[0], n_reg / 2),
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2),
brows(w.egu, rows * k));
if (shared) shared_up(c_, T, r0, rows,
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
if (shared && !sh_first)
shared_up(c_, T, r0, rows,
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
gq_exp.step(c_, w.egu, rows * k, 0, rows * k);
if (shared) gq_sh.step(c_, w.sgu, T, r0, rows);
if (shared && !(op_sh_gated && rows <= sh_gated_rows)) gq_sh.step(c_, w.sgu, T, r0, rows);
/* The shared arm's down projection in front of the routed down GEMM on a step of
* [sh_down_first_lo, sh_down_first_hi] rows. Behind it (below) the two still run together,
* but the card launches the arm only once every block of the routed GEMM is on it; at a
* verify step's forty routed rows that is a few microseconds before that GEMM ends, and the
* gather then waits for the arm. In front, the arm is the ordered launch behind the two
* quantisers and the routed GEMM starts beside it (it reads nothing the arm writes): the same
* start for the routed GEMM, and the arm is done long before it. At one row the routed GEMM
* is a quarter of the blocks, the arm behind it is launched in time, and in front it only
* delays that GEMM's launch (+0.38% a step), hence the lower bound. The arm's buffers are
* excluded from sharing (declare), so the order is free. Qwen3.8-Flash-Next at tp 2 with
* coupling, chain 1 / 2 / 3 (two / three / four rows): -0.28% / -0.21% / -0.25% a step. */
const bool sh_dn_first = shared && T >= sh_down_first_lo && T <= sh_down_first_hi;
if (sh_dn_first) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
if (c.expert_bf16)
RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.x, rows * k), RAD_WTAB(w_dn[0], ne),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.edn, rows * k));
else if (ncls == 4)
RAD_ISSUE_N(c_, op_dn, rows,
brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
brows(gq_exp.a.cq(), rows * k), brows(gq_exp.a.cs(), rows * k),
RAD_WTAB(w_dn[0], n4[0]), RAD_WTAB(w_dns[0], n4[0]),
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_dn[1], n4[1]), RAD_WTAB(w_dns[1], n4[1]),
@@ -1727,7 +1974,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
brows(w.edn, rows * k));
else
RAD_ISSUE_N(c_, op_dn, rows,
brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
brows(gq_exp.a.cq(), rows * k), brows(gq_exp.a.cs(), rows * k),
RAD_WTAB(w_dn[0], n_reg / 2), RAD_WTAB(w_dns[0], n_reg / 2),
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_dn[1], n_reg / 2), RAD_WTAB(w_dns[1], n_reg / 2),
@@ -1747,7 +1994,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
RAD_ISSUE_N(c_, op_pdn, rows, brows(pff.x, rows * k), RAD_WTAB(w_pdn[0], np),
brows(w.sorted, rows * k), poff, brows(w.edn, rows * k));
}
if (shared) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
if (shared && !sh_dn_first) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
/* The calibration tap reads the GEMMs' operands and writes nothing they touch, so it does not
* change the model's output. */
if (op_gram_gu && !calib_done) {
@@ -1784,6 +2031,9 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
(!calib_dne_failed &&
calib_dne.write(gram_dn_stem, c.expert_base, gram_domain,
rad_rank(c_)));
/* Written: the host sums are done with (a layer's can be gigabytes). */
calib_dne.acc = {};
calib_dne.rows = {};
calib_done = true;
if (layer == 0)
std::fprintf(stderr, "radiance: calibration wrote layer Hessians after %lld "
@@ -1894,12 +2144,13 @@ inline void MoeFP8::route_report(RadCtx* c_) const {
* destination row, the copy here is skipped, and the row stays zero -- which the file stager
* read as "no expert routed" and skipped every layer's weights (NaN logits, empty text).
* Copying w.ecnt into the row (the pointers now differ) also feeds the heat engine real
* histograms instead of the zeros it saw before. */
* histograms instead of the zeros it saw before. With a routing table (Wire::ecnt_pitch) the
* router did write the core's row, as a declared operand, and the report copies nothing. */
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew, c.sigmoid_router != 0);
RadRouting r{};
r.expert_ids = (const int32_t*)rad_buf_ptr(c_, w.ids);
r.expert_w = nullptr;
r.expert_count = (const int32_t*)rad_buf_ptr(c_, w.ecnt);
r.expert_count = (const int32_t*)rad_buf_ptr(c_, w.ecnt) + (int64_t)layer * w.ecnt_pitch;
r.sorted_tok = (const int32_t*)rad_buf_ptr(c_, w.sorted);
r.expert_offset = (const int32_t*)rad_buf_ptr(c_, w.eoff);
r.top_k = c.top_k;
+65 -4
View File
@@ -152,6 +152,13 @@ struct MtpHcBlock {
MoeFP8 mlp{};
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_enter = 0, op_carry = 0;
/* The selected draft calibration also records the bf16 attention input shared by
* qg/k/v, independently of the expert gate's later input. */
rad_buf b_attn_gram = 0;
rad_op op_attn_gram = 0;
const char* attn_gram_stem = nullptr;
mutable int64_t attn_gram_rows = 0;
mutable bool attn_gram_done = false;
/* Media rows over the head's embedding (see MtpBlockFP8::media). Set before declare when the
* program has an encoder. */
@@ -258,6 +265,20 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
* 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));
if (src.mlp.cfg.calib) {
/* Only a BF16 source supplies domain-0 inputs for this calibration. The input
* is replicated, so each TP rank records the same width and GPTQ sums them. */
if (!src.mlp.cfg.expert_bf16 || !w.attn.h.x) return RAD_E_UNSUPPORTED;
attn_gram_stem = nm.f("blk.%d.attn_qg", l);
b_attn_gram = decl_b(b, nm.f("blk.%d.mtp_attn_gram", l), RAD_F32,
{g.n_embd, g.n_embd}, RAD_BUF_PERSIST);
op_attn_gram = rw(b, RAD_OP(b, "gram_accum",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{w.attn.h.x, b_attn_gram}, {b_attn_gram});
if (!b_attn_gram || !op_attn_gram) return RAD_E_INVAL;
}
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
attn.ar_out_take = hc_attn.ar_take();
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn,
@@ -282,7 +303,11 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
/* The connection's read also writes the rotated expert input, as on the trunk. */
HyperConn::Config mcfg = hc;
HyperConn::Wire mwire{w.hw, w.x, w.inj};
if (src.mlp.cfg.expert_rot) { mcfg.rotate = 1; mwire.rq = w.mlp.hr.q; mwire.rs = w.mlp.hr.s; }
if (src.mlp.cfg.expert_rot && !w.x.q8_rot) {
mcfg.rotate = 1;
mwire.rq = w.mlp.hr.cq();
mwire.rs = w.mlp.hr.cs();
}
RAD_ARCH_TRY(hc_mlp.declare(b, nm, g, nm.f("mtp.ffn_hc"), mcfg, mwire, src.hc_mlp));
mlp.ar_out_take = hc_mlp.ar_take();
mlp.hr_in = mcfg.rotate != 0;
@@ -467,6 +492,17 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const int r = batch->draft_pass;
/* Expert calibration needs real draft-layer inputs, not the trunk's Hessian. In a
* selected calibration layer, run the history's teacher-forced rows through the full
* draft block before selecting the rows needed by the drafter. Normal inference and
* a tap that has reached its target retain the ordinary history-only fast path. */
const bool tap_history = r < 0 && mlp.c.calib && !mlp.calib_done;
/* serial_batch names one trunk hidden row per history token. Refuse an incomplete
* gather instead of silently calibrating stale hin rows if that contract changes. */
if (tap_history && (batch->n_out != T || !batch->out_ids)) {
rad_step_fail(c, "MTP calibration needs one trunk hidden row per history token");
return;
}
/* The history pass continues from the trunk's wide stream; later rounds from the head's,
* which the carry left in the same buffer. */
@@ -489,11 +525,26 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
RAD_W(w_fc_h), RAD_W(w_fc_e), brows(w.hw, T));
hc_attn.read_pieces(c, T);
if (tap_history && op_attn_gram && !attn_gram_done) {
if (attn_gram_rows == 0)
rad_memset_async(rad_buf_ptr(c, b_attn_gram), 0,
g.n_embd * g.n_embd * 4, rad_stream(c));
RAD_ISSUE_N(c, op_attn_gram, T, brows(w.attn.h.x, T), RAD_NONE,
brows(b_attn_gram, g.n_embd));
attn_gram_rows += T;
if (attn_gram_rows >= calib_target()) {
if (!calib_write(c, b_attn_gram, g.n_embd, attn_gram_rows, attn_gram_stem, 0)) {
rad_step_fail(c, "MTP calibration could not write its attention input Gram");
return;
}
attn_gram_done = true;
}
}
/* 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) {
if (r < 0 && batch->n_draft_out <= 0 && !tap_history) {
qsa.store(c, attn.w.h, batch);
attn.store_kv(c, batch);
return;
@@ -501,7 +552,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
/* 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);
qsa.step(c, attn.w.h, batch, qsa_win_cu, attn.qsa_use(batch));
attn.step(c, batch);
hc_attn.write(c, T, 0, T);
@@ -509,7 +560,7 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
/* 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) {
if (r < 0 && !tap_history) {
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));
@@ -520,6 +571,16 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
mlp.step_rows(c, L);
hc_mlp.write(c, L, 0, L);
if (tap_history) {
/* History-only chunks have no proposal. For the last chunk, select the same
* round-1 rows the ordinary path would have selected before its feed-forward. */
L = batch->n_draft_out;
if (L <= 0) return;
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));
}
/* 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)
File diff suppressed because it is too large. Load diff
+584
View File
@@ -0,0 +1,584 @@
/* rad_block_museglimmer_vision.h -- Muse Glimmer's vision tower (transformers'
* MuseGlimmerVisionModel, an InternVit-shaped stack), its adapter and the perception norm, served
* by museglimmer.
*
* What it computes, per encoder pass (RadBatch::enc), in the reference's order:
*
* x = patches @ Wp^T the patch embedding as a linear layer, bias-less;
* a patch row is (temporal, channel, y, x)
* x += position table resampled to the grid `grid_embed_pad`, bilinear at half-pixel
* centres, align_corners=False, out-of-range taps
* zero-weighted (grid_sample padding zeros)
* x = LN_pre(x) LayerNorm, eps `layer_norm_eps`
* x = x[window order] `window_order`: the 32x32-patch window permutation
* (per frame, ragged edges smaller windows), its
* inverse, per-slot rotary positions and the
* per-window cumulative boundaries
* depth times:
* h = LN1(x) LayerNorm, eps 1e-5 (the blocks hard-code it)
* q|k|v = qkv(h) the reference's three biased projections, joined
* q first into one GEMM as the reference's fused
* tensors would read
* rope(q, k) `rope` axial, the whole head, sections
* head_dim/4 a side on theta^(-j/(head_dim/4)),
* positions (column + 1, row + 1) -- HF's
* position_ids.flip(-1) + 1
* x += proj(attn(q, k, v)) non-causal, scale 1/sqrt(head_dim). A
* window_attention layer attends within one window
* (cu = the per-window boundaries in permuted
* order); a full_attention layer attends within
* its frame (cu = the frame boundaries). The
* window permutation never moves a patch across
* frames, so the frame boundaries among permuted
* rows are the boundaries among natural rows:
* `enc_cu` is passed unchanged, exactly what the
* reference passes (modeling_muse_glimmer.py maps
* full_attention to the frame cu_seqlens while the
* rows stay permuted).
* x += fc2(gelu(fc1(LN2(x)))) both biased; `gelu` the exact erf form the
* config's hidden_act names, in gemm_nt_bias's
* epilogue
* x = x[inv] the window order undone (gather_rows)
* x = LN_post(x) LayerNorm, eps `layer_norm_eps`
* y = pixel_shuffle(x) the merge (`pixtral_merge`): each 2x2 block's
* four patches fold into one row of merge^2 *
* width, channels interleaved -- the reference's
* [block, merge^2, dim].permute(0, 2, 1)
* y = gelu(fc2(gelu(fc1(y)))) the adapter: both linears bias-less, TWO
* activations (projector_hidden_act)
* y = y @ Wproj^T the projection, bias-less, the model's width
* out = rms(y) `perception_emb_norm`, a weightless RMS norm at
* the TEXT model's rms_norm_eps
*
* The reference permutes AFTER ln_pre, so the tower works in window order and un-permutes before
* ln_post, exactly as above. The processor stages patches in the reference's raster order; the
* merge is a real fold (not a view: the reference interleaves the four patches' channels, which
* four consecutive rows do not spell), and its output is what the adapter reads.
*
* Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the
* weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx::
* max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's
* step; the attention's longest segment stays at the real pass so the kernel rows do not move.
*/
#ifndef RAD_BLOCK_MUSEGLIMMER_VISION_H
#define RAD_BLOCK_MUSEGLIMMER_VISION_H
#include "rad_arch.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct MuseTower {
/* Geometry, from the container's vision_config (never aliased: only the full prefix). The
* adapter's widths are top-level keys of the family config. */
int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0;
int64_t merge = 0, side = 0, npos = 0, proj_ff = 0, out_hidden = 0, n_embd = 0;
int64_t patch_dim = 0, P = 0;
double eps = 1e-5; /* ln_pre / ln_post; the blocks hard-code 1e-5 */
float theta = 10000.0f;
bool on = false;
struct Layer {
bool full = false; /* full_attention: frame-wide attention, NoPE-free (rotary runs
* on every layer of this tower, full or window) */
rad_weight n1w = 0, n1b = 0, qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
rad_weight n2w = 0, n2b = 0, up_w = 0, up_b = 0, down_w = 0, down_b = 0;
rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
int64_t max_seg = 0; /* the kernel band's longest segment */
};
std::vector<Layer> L;
rad_weight w_patch = 0, w_pos = 0, lw_pre = 0, lb_pre = 0, lw_post = 0, lb_post = 0;
rad_weight w_a1 = 0, w_a2 = 0, w_proj = 0;
rad_op op_patch = 0, op_pos = 0, op_lpre = 0, op_wo = 0, op_gidx = 0, op_ginv = 0;
rad_op op_lpost = 0, op_merge = 0, op_m1 = 0, op_g1 = 0, op_m2 = 0, op_g2 = 0, op_proj = 0,
op_perc = 0;
rad_buf b_x = 0, b_h = 0, b_p = 0, b_qkv = 0, b_att = 0, b_ff = 0;
rad_buf b_idx = 0, b_inv = 0, b_pos = 0, b_cuw = 0;
rad_buf b_mh = 0, b_m1 = 0, b_m2 = 0, b_out = 0;
char sec[48] = {};
/* Whether the container carries this family's tower. */
static bool present(const RadModelMeta* m) {
return 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 MuseTower::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);
temporal = rad_meta_geti(m, "vision_config.patch_temporal", 2);
merge = rad_meta_geti(m, "vision_config.merge_size", 2);
side = rad_meta_geti(m, "vision_config.pos_emb_height", 0);
npos = rad_meta_geti(m, "vision_config.pos_emb_height", 0) *
rad_meta_geti(m, "vision_config.pos_emb_width", 0);
eps = rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-5);
theta = (float)rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0);
proj_ff = rad_meta_geti(m, "projector_hidden_size", 4096);
out_hidden = rad_meta_geti(m, "out_hidden_size", 6144);
n_embd = model_embd;
/* Bounds the walk and the host allocations below take at face value, set against published
* maxima rather than round numbers: the deepest vision encoder ever shipped is 48 layers
* (ViT-22B, InternViT-6B; this family's towers are SigLIP-class, tens), and the largest
* stored position table a side of 92 (SigLIP at 1292 px over patch 14; CLIP 16, SAM 64 --
* native-resolution towers store no side x side table at all). The caps sit ~2.6x and
* ~5.5x past those maxima, so they never bite an honest container, and at the cap the
* guarded shapes are harmless: the depth vectors cost KiB and the grid products reach 2^18
* at most. Past the caps the container is not describing a model but a vector size
* (full.assign(depth) and L.assign(depth) would throw past max_size, and the grid products
* below overflow signed 64 before any comparison could notice). Refuse like every other
* bad config: say so and RAD_E_INVAL. */
if (depth <= 0 || depth > 128 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 ||
temporal <= 0 || merge <= 0 || side <= 0 || side > 512 || proj_ff <= 0 ||
out_hidden <= 0 || width % heads ||
rad_meta_geti(m, "vision_config.pos_emb_width", 0) != side) {
fprintf(stderr, "radiance: museglimmer: the container's vision_config is incomplete, "
"inconsistent, or past what this tower walks (depth %lld, hidden %lld, "
"heads %lld, ff %lld, patch %lld, "
"temporal %lld, merge %lld, position grid %lld x %lld, projector %lld, "
"merged %lld)\n", (long long)depth, (long long)width, (long long)heads,
(long long)ff, (long long)patch, (long long)temporal, (long long)merge,
(long long)side, (long long)rad_meta_geti(m, "vision_config.pos_emb_width", 0),
(long long)proj_ff, (long long)out_hidden);
return RAD_E_INVAL;
}
/* The merge is `pixtral_merge`, whose kernels fold a 2x2 block: the only factor Muse Glimmer
* ships and the only one the op serves. */
if (merge != 2) {
fprintf(stderr, "radiance: museglimmer: this vision tower states merge_size %lld; the "
"merge op folds a 2x2 block\n", (long long)merge);
return RAD_E_UNSUPPORTED;
}
/* The exact-erf GELU is what this tower and its adapter state; another activation is another
* tower (the reference would compute a different function). */
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu");
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial");
if (std::strcmp(act, "gelu") || std::strcmp(pact, "gelu")) {
fprintf(stderr, "radiance: museglimmer: this vision tower has hidden_act '%s' and "
"projector_hidden_act '%s'; it serves the exact gelu both call for\n",
act, pact);
return RAD_E_UNSUPPORTED;
}
/* `axial` is Meta's spelling and `default` NVIDIA's ModelOpt export of the same tower: the
* reference's vision embedder has one rotary (axial), so both name it. Anything else is
* another tower. */
if (std::strcmp(rt, "axial") && std::strcmp(rt, "default")) {
fprintf(stderr, "radiance: museglimmer: this vision tower states rope_type '%s'; it "
"serves the axial 2-D rotary the tower's rotary embedder raises on "
"leaving\n", rt);
return RAD_E_UNSUPPORTED;
}
/* The tower's full layers: every fourth, counted from the start, plus the last (the config's
* own rule, MuseGlimmerVisionConfig.__post_init__). The shipped array must say the same
* thing; a window layer where the rule puts a full one changes what the model saw. */
std::vector<int> full;
const char* kinds = rad_meta_gets(m, "vision_config.layer_types", "");
if (kinds && *kinds) {
RAD_ARCH_TRY(parse_layer_kinds("museglimmer vision", kinds, {"full_attention"},
"window_attention", &full));
if ((int64_t)full.size() != depth) {
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types names %zu layers "
"and the tower has %lld\n", full.size(), (long long)depth);
return RAD_E_INVAL;
}
for (int64_t l = 0; l < depth; ++l) {
const bool rule = is_full_attention(l, 4) || l == depth - 1;
if ((full[(size_t)l] != 0) != rule) {
fprintf(stderr, "radiance: museglimmer: vision_config.layer_types makes tower "
"layer %lld %s and the family rule (every fourth from the first, "
"plus the last) makes it %s\n", (long long)l,
full[(size_t)l] ? "full" : "window", rule ? "full" : "window");
return RAD_E_UNSUPPORTED;
}
}
} else {
full.assign((size_t)depth, 0);
for (int64_t l = 0; l < depth; ++l)
full[(size_t)l] = is_full_attention(l, 4) || l == depth - 1;
}
head_dim = width / heads;
patch_dim = 3 * temporal * patch * patch;
/* The 2-D rotary: half the head a side, each on its own ladder (arange(0, head_dim/2, 2)
* frequencies, sections head_dim/4 a side). */
if (head_dim % 4) return RAD_E_SHAPE;
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4),
(long long)(head_dim / 4));
/* The merger's rows replace token embeddings, so they must be the model's width. */
if (out_hidden != merge * merge * width) {
fprintf(stderr, "radiance: museglimmer: out_hidden_size %lld is not merge %lld squared "
"times the tower's width %lld, whose view the adapter's first layer "
"reads\n", (long long)out_hidden, (long long)merge, (long long)width);
return RAD_E_INVAL;
}
/* The tower emits merged rows the width of the model's tokens: the caller passes the model's
* width and the projection is declared at it, so no separate check exists. */
const int64_t mm = merge * merge;
P = ctx->max_enc_patches;
if (ctx->shape_probe) {
/* 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. The kernel bands stay at the
* real pass: the engine runs the real declare's kernels at every level. */
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 int64_t ACC = RAD_ACCESS_PER_REQUEST;
/* The window side in patches (the reference states it in pixels and divides by patch_size).
* A window_attention layer's longest segment is one window. */
const int64_t win_seg = side * side;
/* ---- weights, replicated. Model-level groups for the stem and the adapter; one group per
* block from `first_group` on, so a tower block is its own movement unit. */
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);
};
w_patch = bw(nm.f("v.patch.weight"),
nm.ckpt("model.vision_tower.patch_embedder.patch_embedding.weight"),
{ width, patch_dim }, grp_model());
w_pos = bw(nm.f("v.pos.weight"),
nm.ckpt("model.vision_tower.patch_embedder.position_embedding_table.weight"),
{ npos, width }, grp_model());
lw_pre = bw(nm.f("v.lnpre.weight"), nm.ckpt("model.vision_tower.ln_pre.weight"), { width },
grp_model());
lb_pre = bw(nm.f("v.lnpre.bias"), nm.ckpt("model.vision_tower.ln_pre.bias"), { width },
grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const RadWeightGroup g = grp_layer(first_group + (int)i);
const int li = (int)i;
auto src = [&](const char* s) { return nm.ckpt("model.vision_tower.layers.%d.%s", li, s); };
auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); };
l.n1w = bw(dn("norm1.weight"), src("norm1.weight"), { width }, g);
l.n1b = bw(dn("norm1.bias"), src("norm1.bias"), { width }, g);
/* The reference's three biased projections, joined q | k | v into one GEMM. */
if (map_concat(b, dn("qkv.weight"),
{ src("attn.q_proj.weight"), src("attn.k_proj.weight"),
src("attn.v_proj.weight") }) < 0)
return RAD_E_INVAL;
l.qkv_w = decl_w(b, dn("qkv.weight"), RAD_BF16, { 3 * width, width }, ACC,
RAD_SHARD_NONE, g, 0, { width, width, width });
if (map_concat(b, dn("qkv.bias"),
{ src("attn.q_proj.bias"), src("attn.k_proj.bias"),
src("attn.v_proj.bias") }) < 0)
return RAD_E_INVAL;
l.qkv_b = decl_w(b, dn("qkv.bias"), RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g, 0,
{ width, width, width });
l.out_w = bw(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g);
l.out_b = bw(dn("proj.bias"), src("attn.proj.bias"), { width }, g);
l.n2w = bw(dn("norm2.weight"), src("norm2.weight"), { width }, g);
l.n2b = bw(dn("norm2.bias"), src("norm2.bias"), { width }, g);
l.up_w = bw(dn("fc1.weight"), src("mlp.fc1.weight"), { ff, width }, g);
l.up_b = bw(dn("fc1.bias"), src("mlp.fc1.bias"), { ff }, g);
l.down_w= bw(dn("fc2.weight"), src("mlp.fc2.weight"), { width, ff }, g);
l.down_b= bw(dn("fc2.bias"), src("mlp.fc2.bias"), { width }, g);
if (!l.n1w || !l.n1b || !l.qkv_w || !l.qkv_b || !l.out_w || !l.out_b || !l.n2w || !l.n2b ||
!l.up_w || !l.up_b || !l.down_w || !l.down_b)
return RAD_E_INVAL;
l.full = full[(size_t)i] != 0;
l.max_seg = l.full ? ctx->max_enc_patches : win_seg;
}
lw_post = bw(nm.f("v.lnpost.weight"), nm.ckpt("model.vision_tower.ln_post.weight"), { width },
grp_model());
lb_post = bw(nm.f("v.lnpost.bias"), nm.ckpt("model.vision_tower.ln_post.bias"), { width },
grp_model());
w_a1 = bw(nm.f("v.mlp.fc1.weight"), nm.ckpt("model.vision_adapter.fc1.weight"),
{ proj_ff, out_hidden }, grp_model());
w_a2 = bw(nm.f("v.mlp.fc2.weight"), nm.ckpt("model.vision_adapter.fc2.weight"),
{ proj_ff, proj_ff }, grp_model());
w_proj = bw(nm.f("v.proj.weight"), nm.ckpt("model.vision_projection.weight"),
{ n_embd, proj_ff }, grp_model());
if (!w_patch || !w_pos || !lw_pre || !lb_pre || !lw_post || !lb_post || !w_a1 || !w_a2 ||
!w_proj)
return RAD_E_INVAL;
/* ---- activations. `mh` holds the merged rows: `pixtral_merge` folds each 2x2 block's four
* patch rows into one row of mm * width in the reference's pixel_shuffle layout, and the
* adapter's first layer reads it. */
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_p = decl_b(b, nm.f("v.p"), 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_idx = decl_b(b, nm.f("v.idx"), RAD_I32, { P });
b_inv = decl_b(b, nm.f("v.inv"), RAD_I32, { P });
b_pos = decl_b(b, nm.f("v.pos"), RAD_I32, { 2, P });
b_cuw = decl_b(b, nm.f("v.cuw"), RAD_I32, { P + 1 });
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mm * width });
b_m1 = decl_b(b, nm.f("v.m1"), RAD_BF16, { R, proj_ff });
b_m2 = decl_b(b, nm.f("v.m2"), RAD_BF16, { R, proj_ff });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_p || !b_qkv || !b_att || !b_ff || !b_idx || !b_inv || !b_pos || !b_cuw ||
!b_mh || !b_m1 || !b_m2 || !b_out)
return RAD_E_INVAL;
auto gemm_b = [&](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 gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op {
return RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto lnorm = [&](int64_t rows, int64_t n, double e, 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", e),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
auto attn_op = [&](int64_t max_seg) -> rad_op {
return 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);
};
/* The stem is bias-less (the reference's patch_embedding states no bias). */
op_patch = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_patch)),
{}, { b_x });
op_pos = rw(b, RAD_OP(b, "grid_embed_pad",
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 });
op_lpre = rw(b, lnorm(P, width, eps, lw_pre, lb_pre), { b_x }, { b_h });
op_wo = rw(b, RAD_OP(b, "window_order",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("window", side)),
RAD_NOWEIGHTS),
{}, { b_idx, b_inv, b_pos, b_cuw });
op_gidx = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_h, b_idx }, { b_p });
for (Layer& l : L) {
l.ln1 = rw(b, lnorm(P, width, 1e-5, l.n1w, l.n1b), { b_p }, { b_h });
l.qkv = rw(b, gemm_b(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.rope = rw(b, RAD_OP(b, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
RAD_F64("theta", theta), RAD_F64("scale", 1.0),
RAD_STR("mode", "axial"),
RAD_INT("rotary_dim", head_dim),
RAD_STR("sections", sec)),
RAD_NOWEIGHTS),
{ b_qkv, b_pos }, { b_qkv });
/* A window layer's segment bounds are the order op's per-window cu; a full layer's are
* the pass's frame bounds, raw (the permutation is within frames, so they read the same
* values in permuted order). */
l.attn = rw(b, attn_op(l.max_seg),
l.full ? std::initializer_list<rad_buf>{ b_qkv }
: std::initializer_list<rad_buf>{ b_qkv, b_cuw },
{ b_att });
l.proj = rw(b, gemm_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_p }, { b_p });
l.ln2 = rw(b, lnorm(P, width, 1e-5, l.n2w, l.n2b), { b_p }, { b_h });
l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff });
l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_p }, { b_p });
}
op_ginv = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_p, b_inv }, { b_x });
op_lpost = rw(b, lnorm(P, width, eps, lw_post, lb_post), { b_x }, { b_x });
/* The reference's pixel_shuffle: each 2x2 block's four patches fold into one row with the
* channels interleaved (block, channel, sub-patch), which is `pixtral_merge`'s layout. A view
* over four consecutive rows cannot produce it: the concatenated form is a different tensor. */
op_merge = rw(b, RAD_OP(b, "pixtral_merge",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("merge", merge), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_x }, { b_mh });
/* The adapter: both linears bias-less, gelu between and after (the reference's
* act(fc2(act(fc1(x))))). */
op_m1 = rw(b, gemm(R, proj_ff, mm * width, w_a1), { b_mh }, { b_m1 });
op_g1 = rw(b, RAD_OP(b, "gelu",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_m1 }, { b_m2 });
op_m2 = rw(b, gemm(R, proj_ff, proj_ff, w_a2), { b_m2 }, { b_m1 });
op_g2 = rw(b, RAD_OP(b, "gelu",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_m1 }, { b_m2 });
op_proj = rw(b, gemm(R, n_embd, proj_ff, w_proj), { b_m2 }, { b_out });
/* perception_emb_norm: MuseGlimmerRMSNorm(eps = the TEXT model's rms_norm_eps, with_scale
* False) -- no gain operand, no centered 1+. */
op_perc = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
RAD_F64("eps", m->rms_eps), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_out }, { b_out });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = mm;
e.max_patches = ctx->max_enc_patches;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
int64_t nfull = 0;
for (int64_t l = 0; l < depth; ++l) nfull += full[(size_t)l];
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld x "
"%lld x %lld, merge %lld, windows of %lld patches (%lld full attention); "
"%lld patches a pass -> %lld rows of %lld",
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
(long long)ff, (long long)temporal, (long long)patch, (long long)patch,
(long long)merge, (long long)side, (long long)nfull, (long long)P, (long long)R,
(long long)n_embd);
}
on = true;
return RAD_OK;
}
/* Stage taps, the same protocol as rad_block_sam.h's: RADIANCE_DEBUG_MM_BUFFERS names stages
* (comma separated, matched as substrings) and RADIANCE_DEBUG_MM_DUMP's directory receives
* tap.<tag>.bf16 -- raw bf16 rows, one file a stage. The copy is issued on the pass's stream
* behind the producing op and synced, so it reads that op's output rather than whatever writes
* the buffer later (the after-pass dump in core/engine_mm.cpp cannot see intermediates). */
inline void muse_tap(RadCtx* c, const char* tag, rad_buf b, int64_t rows, int64_t cols) {
static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP");
static const char* const env = std::getenv("RADIANCE_DEBUG_MM_BUFFERS");
if (!dir || !*dir || !env || !*env || rows <= 0 || cols <= 0 || rad_rank(c) != 0) return;
bool want = false;
const size_t tl = std::strlen(tag);
for (const char* s = env; *s && !want;) {
const char* e = s;
while (*e && *e != ',') ++e;
const size_t l = (size_t)(e - s);
for (size_t i = 0; l && i + l <= tl && !want; ++i)
want = std::strncmp(tag + i, s, l) == 0;
s = *e ? e + 1 : e;
}
if (!want) return;
void* p = rad_buf_ptr(c, b);
if (!p) return;
std::vector<uint16_t> h((size_t)(rows * cols));
if (rad_memcpy_async(h.data(), p, (size_t)(rows * cols * 2), rad_stream(c)) < 0) return;
rad_stream_sync(rad_stream(c));
char path[512];
std::snprintf(path, sizeof path, "%s/tap.%s.bf16", dir, tag);
if (FILE* f = std::fopen(path, "wb")) {
std::fwrite(h.data(), sizeof(uint16_t), h.size(), f);
std::fclose(f);
}
}
inline void MuseTower::step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
const int64_t mm = merge * merge, Rn = Pn / mm;
if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0 || !batch->enc_coord || !batch->enc_cu ||
!batch->enc_seg_h || !batch->enc_seg_w || !batch->enc_pixels) {
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or "
"more patches than it was declared for, or not whole merged rows");
return;
}
/* Windows per frame, from the pass's host grids: the window layers' cu is the per-window
* boundaries among permuted rows, `n_win + 1` entries of the order op's output. */
int64_t n_win = 0;
for (int64_t s = 0; s < S; ++s)
n_win += (batch->enc_seg_h[s] + side - 1) / side * ((batch->enc_seg_w[s] + side - 1) / side);
if (n_win > P) {
rad_step_fail(c, "an encoder pass whose window count exceeds the tower's declared rows");
return;
}
/* Patches, coordinates (planes 0-3: row, column, segment height, segment width, in patches)
* and the frame boundaries, staged by the core. The full layers read the frame boundaries
* unchanged: the window permutation is within frames, so the boundaries among permuted rows
* are these values (the reference passes its cu_seqlens the same way). */
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);
RadOperand cuw = RAD_B(b_cuw);
cuw.rows = n_win + 1;
RadOperand pos = RAD_B(b_pos);
pos.rows = 2;
pos.cols = Pn;
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
muse_tap(c, "v.patchpos", b_x, Pn, width);
RAD_ISSUE_N(c, op_lpre, Pn, brows(b_x, Pn), RAD_W(lw_pre), RAD_W(lb_pre), brows(b_h, Pn));
muse_tap(c, "v.lnpre", b_h, Pn, width);
RAD_ISSUE_N(c, op_wo, Pn, crd, cu, brows(b_idx, Pn), brows(b_inv, Pn), pos, cuw);
RAD_ISSUE_N(c, op_gidx, Pn, brows(b_h, Pn), brows(b_idx, Pn), brows(b_p, Pn));
for (size_t li = 0; li < L.size(); ++li) {
const Layer& l = L[li];
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_p, 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.rope, Pn, brows(b_qkv, Pn), pos);
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),
l.full ? cu : cuw, 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_p, Pn), brows(b_p, Pn));
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_p, 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_p, Pn), brows(b_p, Pn));
if (li == 0) muse_tap(c, "v.blk0", b_p, Pn, width);
if (li + 1 == L.size()) muse_tap(c, "v.blkL", b_p, Pn, width);
}
RAD_ISSUE_N(c, op_ginv, Pn, brows(b_p, Pn), brows(b_inv, Pn), brows(b_x, Pn));
muse_tap(c, "v.ginv", b_x, Pn, width);
/* ln_post over the P patches, then the reference's pixel_shuffle into merged rows. */
RAD_ISSUE_N(c, op_lpost, Pn, brows(b_x, Pn), RAD_W(lw_post), RAD_W(lb_post), brows(b_x, Pn));
muse_tap(c, "v.lnpost", b_x, Pn, width);
RAD_ISSUE_N(c, op_merge, Pn, brows(b_x, Pn), crd, brows(b_mh, Rn));
muse_tap(c, "v.merge", b_mh, Rn, mm * width);
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(w_a1), brows(b_m1, Rn));
muse_tap(c, "v.fc1", b_m1, Rn, proj_ff);
RAD_ISSUE_N(c, op_g1, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
RAD_ISSUE_N(c, op_m2, Rn, brows(b_m2, Rn), RAD_W(w_a2), brows(b_m1, Rn));
RAD_ISSUE_N(c, op_g2, Rn, brows(b_m1, Rn), brows(b_m2, Rn));
RAD_ISSUE_N(c, op_proj, Rn, brows(b_m2, Rn), RAD_W(w_proj), brows(b_out, Rn));
muse_tap(c, "v.proj", b_out, Rn, n_embd);
RAD_ISSUE_N(c, op_perc, Rn, brows(b_out, Rn), RAD_NONE, brows(b_out, Rn));
muse_tap(c, "v.out", b_out, Rn, n_embd);
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_MUSEGLIMMER_VISION_H */
+129 -22
View File
@@ -98,12 +98,24 @@ struct PleLayer {
rad_weight w_table = 0, w_scale = 0, w_mult = 0, w_vsz = 0, w_off = 0;
/* The table is plain bf16 as shipped (no scale weight) rather than E4M3. */
bool table_bf16 = false;
rad_weight w_key = 0, w_value = 0, w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
rad_weight w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
/* The two projections of the gathered embedding, each in the encoding its container stores:
* plain bf16 as the checkpoint ships them, or rotated int8 (or a narrower rotated form), which
* halves the bytes a pass waits for once the rows are on the card. `a_embd` is their input and
* `a_fed` the same planes for the second projection, whose codes the first one's quantiser
* wrote. */
LinearFP8 key{}, value{};
ActFP8 a_embd{}, a_fed{};
rad_kvgroup kv_tok = 0, kv_conv = 0;
rad_buf b_ids = 0, b_emb = 0, b_embd = 0, b_k = 0, b_v = 0, b_gv = 0, b_gvn = 0, b_out = 0;
rad_op op_ids = 0, op_gather = 0, op_embd = 0, op_key = 0, op_value = 0;
rad_op op_ids = 0, op_gather = 0, op_embd = 0;
rad_op op_gate = 0, op_conv = 0, op_add = 0;
/* The draft passes' hint (hint_ids, hint_fetch), where a drafter and `ngram_hint` exist: the
* per-slot tails the hash continues from, the hinted ids (host domain, as `ple_ids`) and the
* rows fetched for them, which nothing reads. */
rad_buf b_tail = 0, b_hint_ids = 0, b_hint_emb = 0;
rad_op op_hint_hist = 0, op_hint_round = 0, op_hint_gather = 0;
int64_t hn() const { return c.hc * g.n_embd; }
/* The read-ahead queue's depth in steps: batch.cpp's k_ahead_chunks steps of the following
@@ -123,6 +135,14 @@ struct PleLayer {
/* The hash, issued at the top of the step; the rest at the layer (see ids()). */
void ids(RadCtx* c_, const RadBatch* batch) const;
void step(RadCtx* c_, const RadBatch* batch) const;
/* On a draft head's pass: the ids of each sequence's newest token, first in the pass, and
* the fetch of their rows, last in it (see hint_ids()). */
void hint_ids(RadCtx* c_, const RadBatch* batch) const;
void hint_fetch(RadCtx* c_, const RadBatch* batch) const;
bool hints(const RadBatch* batch) const {
return op_hint_gather != 0 &&
(batch->draft_pass > 1 || (batch->draft_pass < 0 && batch->n_draft_out > 0));
}
};
inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg,
@@ -178,7 +198,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
/* 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) or read as that release ships it (its shards under
* recipe (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe) or read as that release ships it (its shards under
* one `weight_scale`); the gather takes them as two operands. The name map
* joins the shards along rows and is declared first, since the encoding is looked up through
* it. RAD_ACCESS_VOCAB: it is a vocabulary table, just not the token one. */
@@ -212,13 +232,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
/* ---- the projections and the three gains ------------------------------------------------ */
/* bf16: the FP8 checkpoint's `modules_to_not_convert` names both projections. */
/* bf16 as shipped (the FP8 checkpoint's `modules_to_not_convert` names both projections); a
* recipe may store them rotated int8. The name maps come first: the encodings, looked up
* through them, say whether the input needs its int8 pair. They are declared below, with the
* buffers they read and write. */
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_key.weight", layer), src.key_proj));
w_key = decl_w(b, nm.f("blk.%d.ple_key.weight", layer), RAD_BF16, {HN, c.embed_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_value.weight", layer), src.value_proj));
w_value = decl_w(b, nm.f("blk.%d.ple_value.weight", layer), RAD_BF16,
{g.n_embd, c.embed_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_key.weight", layer), src.norm_key));
w_nk = decl_w(b, nm.f("blk.%d.ple_norm_key.weight", layer), RAD_F32, {HN},
@@ -236,7 +255,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
w_conv = decl_w(b, nm.f("blk.%d.ple_conv.weight", layer), RAD_BF16, {HN, c.conv_width},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off || !w_key || !w_value ||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off ||
!w_nk || !w_nq || !w_nc || !w_conv) return RAD_E_INVAL;
/* ---- the two rolling windows ------------------------------------------------------------ */
@@ -337,22 +356,83 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
{b_ids}, {b_emb});
}
/* ---- the draft passes' hint. A verify step's rows are the token the last verify chose and
* the drafter's proposals, each known a draft pass or more before the verify hashes it,
* except the last. Each draft pass hashes its sequences' newest token (`ngram_hint`) and
* gathers those rows through the same row source, which for a table on a drive reads them
* into its row cache; the verify step's gather then waits for the last proposal's rows
* only. All three ops or none: without a drafter, or where no library hashes the hint,
* nothing is declared and the verify step reads every row itself, as before. */
if (g.max_spec > 0 && rad_op_declared(b, "ngram_hint")) {
const int64_t ctx = c.ngram - 1;
b_tail = decl_b(b, nm.f("ple_hint_tail"), RAD_I32, {g.max_seqs, 2 * ctx}, RAD_BUF_PERSIST);
RadBufDecl hi{};
hi.dtype = RAD_I32; hi.rank = 2;
hi.shape[0] = g.max_seqs; hi.shape[1] = c.heads;
hi.kind = RAD_BUF_PERSIST; hi.domain = RAD_DOMAIN_HOST;
b_hint_ids = rad_decl_buffer(b, nm.f("ple_hint_ids"), &hi);
/* PERSIST although nothing reads it: a transient's bytes are shared by declared op
* order, and the fetch runs on the host while the draft pass's other buffers are live. */
RadBufDecl he{};
he.dtype = g.act_dtype; he.rank = 2;
he.shape[0] = g.max_seqs; he.shape[1] = c.embed_dim;
he.kind = RAD_BUF_PERSIST; he.domain = RAD_DOMAIN_HOST;
b_hint_emb = rad_decl_buffer(b, nm.f("ple_hint_emb"), &he);
if (!b_tail || !b_hint_ids || !b_hint_emb) return RAD_E_INVAL;
for (const int hist : { 1, 0 })
(hist ? op_hint_hist : op_hint_round) =
rw(b, RAD_OP(b, "ngram_hint",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("heads", c.heads),
RAD_INT("ngram", c.ngram), RAD_INT("eos", c.eos),
RAD_INT("hist", hist)),
RAD_WEIGHTS(w_mult, w_vsz, w_off)),
{b_tail}, {b_tail, b_hint_ids});
const rad_weight wt[2] = { w_table, w_scale };
op_hint_gather = rw(b, RAD_OP(b, "embed_lookup_q",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs * c.heads),
RAD_INT("n_embd", HD), RAD_INT("n_vocab", c.rows),
RAD_STR("dtype", g.dtype)),
wt, table_bf16 ? 1 : 2),
{b_hint_ids}, {b_hint_emb});
if (!op_hint_hist || !op_hint_round || !op_hint_gather)
op_hint_hist = op_hint_round = op_hint_gather = 0;
}
op_embd = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{b_emb}, {b_embd});
op_key = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", HN),
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_key)),
{b_embd}, {b_k});
op_value = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_value)),
{b_embd}, {b_v});
/* The projections. An int8 one reads the embedding's int8 codes at its own scale group; the
* first such quantises the bf16 plane and a second reads those codes, so two int8 projections
* must agree in rotation and group (LinearFP8 refuses the pair otherwise). */
{
const char* kb = nm.f("blk.%d.ple_key", layer);
const char* vb = nm.f("blk.%d.ple_value", layer);
RadEncoding ke{}, ve{};
const bool kk = weight_enc(b, nm.f("%s.weight", kb), &ke);
const bool vk = weight_enc(b, nm.f("%s.weight", vb), &ve);
const bool k8 = !g.w_bf16 && kk && (linear_is_w8(ke) || linear_is_w8h(ke));
const bool v8 = !g.w_bf16 && vk && (linear_is_w8(ve) || linear_is_w8h(ve));
a_embd.x = b_embd;
if (k8 || v8)
RAD_ARCH_TRY(a_embd.declare_qs(b, nm, g, "ple_emb_dev", c.embed_dim, 0, true, false,
linear_w8h_group(k8 ? ke : ve)));
a_fed = a_embd;
if (k8 && v8) {
a_fed.q8_fed = true;
a_fed.q8_rot = linear_is_w8h(ke);
}
key.mapped = value.mapped = true;
/* Anything but an int8 form is the plain bf16 GEMM, in a quantised model too. */
Geom gb = g;
gb.w_bf16 = true;
RAD_ARCH_TRY(key.declare(b, nm, k8 ? g : gb, kb, HN, c.embed_dim, RAD_SHARD_NONE,
grp_model(), { src.key_proj }, a_embd, b_k));
RAD_ARCH_TRY(value.declare(b, nm, v8 ? g : gb, vb, g.n_embd, c.embed_dim, RAD_SHARD_NONE,
grp_model(), { src.value_proj }, a_fed, b_v));
}
/* `q` is the incoming stream, un-normed; the op applies all three norms because the third is
* over bytes it writes. */
@@ -378,7 +458,7 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
RAD_NOWEIGHTS),
{w.h, b_out}, {w.h});
if (!op_ids || !op_gather || !op_embd || !op_key || !op_value || !op_gate || !op_conv ||
if (!op_ids || !op_gather || !op_embd || !key.op || !value.op || !op_gate || !op_conv ||
!op_add)
return RAD_E_INVAL;
return RAD_OK;
@@ -433,6 +513,33 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
}
/* The hint of a draft head's pass. The history pass ends at the token the verify chose and each
* later round reads the proposal before it (RadBatch::draft_pass), so the pass's newest token per
* sequence is one the next verify step runs. hint_ids() hashes it first in the pass, so the ids
* are in host memory as the pass starts; hint_fetch() goes last, where the host has issued the
* whole pass and only waits for that one kernel, and the rows it reads arrive while the card
* drafts. A history pass that drafts nothing gets neither. */
inline void PleLayer::hint_ids(RadCtx* c_, const RadBatch* batch) const {
if (!hints(batch)) return;
const int64_t T = batch->n_tok, S = batch->n_seq;
const RadKVGroupBatch* tk = kv_batch(batch, kv_tok);
const int32_t* tk_idx = tk ? tk->state_index : nullptr;
RAD_ISSUE_N(c_, batch->draft_pass < 0 ? op_hint_hist : op_hint_round, S,
praw(batch->token_ids, RAD_I32, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
tk_idx ? praw(tk_idx, RAD_I32, S) : RAD_NONE,
RAD_B(b_tail), brows(b_hint_ids, S));
}
inline void PleLayer::hint_fetch(RadCtx* c_, const RadBatch* batch) const {
if (!hints(batch)) return;
const int64_t S = batch->n_seq;
RAD_ISSUE_N(c_, op_hint_gather, S * c.heads,
brows(b_hint_ids, S), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
brows(b_hint_emb, S), RAD_NONE);
}
inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const int64_t S = batch->n_seq;
@@ -454,8 +561,8 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
RAD_ISSUE_N(c_, op_embd, T, brows(b_emb, T), brows(b_embd, T));
RAD_ISSUE_N(c_, op_key, T, brows(b_embd, T), RAD_W(w_key), brows(b_k, T));
RAD_ISSUE_N(c_, op_value, T, brows(b_embd, T), RAD_W(w_value), brows(b_v, T));
key.step(c_, a_embd, b_k, T, 0, T);
value.step(c_, a_fed, b_v, T, 0, T);
RAD_ISSUE_N(c_, op_gate, T,
brows(b_k, T), brows(w.h, T), brows(b_v, T),
+42 -3
View File
@@ -25,7 +25,13 @@
* safetensors file per input, <dir>/<stem>.safetensors, holding `hessian_upper`, f32
* [k * (k + 1) / 2], row i's entries k2 = i .. k-1 after row i-1's, and metadata naming `k`, the
* rows summed and the checkpoint linears that read the input. H is the raw sum; divide by `rows`
* for the mean second moment. */
* for the mean second moment.
*
* An int8 trunk (site_i8, one rank only) is recorded from the codes and scales its GEMMs actually
* read, so H includes what the model's own quantisation did to the input -- the input a quantised
* model feeds each layer, for GPTQ against the error it inherits. Codes a rotating producer wrote
* are in the rotated domain; the file's metadata then names it (`domain`: the Hadamard width), as
* RADGRAM2's header does, and the reader converts. */
#pragma once
#include <arch/rad_arch.h>
@@ -52,6 +58,8 @@ struct CalibFull {
rad_op op_gather = 0; /* the columns of every rank into `gathered`; 0 when replicated */
rad_op op_gram = 0; /* declared on the owner only */
bool owner = false;
rad_buf q8 = 0, s8 = 0; /* site_i8: the int8 codes and their f32 (row, 128) scales */
uint32_t domain = 0; /* site_i8: the codes' rotation width, 0 for none */
std::vector<float> tri; /* the owner's accumulator, upper triangle packed */
};
@@ -156,6 +164,32 @@ struct CalibFull {
return RAD_OK;
}
/* One input of layer `layer` from an int8 trunk's codes `q8` and scales `s8` (see the file
* comment): the whole input on one rank, `domain` the Hadamard width the codes were rotated by
* (0 for none). */
int site_i8(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
rad_buf q8, rad_buf s8, int64_t K, uint32_t domain) {
if (world > 1 || !q8 || !s8 || K > kmax) return RAD_E_INVAL;
Site s;
s.stem = std::move(stem);
s.linears = std::move(linears);
s.K = s.k_local = K;
s.owner = true;
s.q8 = q8;
s.s8 = s8;
s.domain = domain;
(void)layer;
s.op_gram = rw(b, RAD_OP(b, "gram_accum",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
RAD_INT("group", 128), RAD_STR("dtype", "i8a8"),
RAD_INT("upper", 1)),
RAD_NOWEIGHTS),
{ q8, s8, scratch }, { scratch });
if (!s.op_gram) return RAD_E_INVAL;
sites.push_back(std::move(s));
return RAD_OK;
}
/* Site `i` over a step's T rows: gather (every rank), then on the owner the Gram into the
* scratch, copied to a free square, the scratch zeroed, and the square handed to the worker. */
void tap(RadCtx* c, size_t i, int64_t T) {
@@ -186,7 +220,10 @@ struct CalibFull {
}
}
const int64_t K = s.K;
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
if (s.q8)
RAD_ISSUE_N(c, s.op_gram, T, brows(s.q8, T), brows(s.s8, T), praw2(dev, RAD_F32, K, K));
else
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
/* `upper` 1 writes no entry below the diagonal, so only the upper triangle comes back:
* band by band of kBand rows, each from its first row's diagonal on, about half the
* square's bytes. The link is what a step's taps wait on, 25 GB a step on each rank of
@@ -317,7 +354,9 @@ private:
const uint64_t bytes = (uint64_t)s.tri.size() * 4;
std::string hdr = "{\"__metadata__\":{\"k\":\"" + std::to_string(s.K) + "\",\"rows\":\"" +
std::to_string(seen) + "\",\"layout\":\"upper triangle, row-major, packed\","
"\"linears\":\"" + s.linears + "\"},\"hessian_upper\":{\"dtype\":\"F32\","
"\"linears\":\"" + s.linears + "\"" +
(s.domain ? ",\"domain\":\"" + std::to_string(s.domain) + "\"" : std::string()) +
"},\"hessian_upper\":{\"dtype\":\"F32\","
"\"shape\":[" + std::to_string(s.tri.size()) + "],\"data_offsets\":[0," +
std::to_string(bytes) + "]}}";
while (hdr.size() % 8) hdr += ' ';
+307 -46
View File
@@ -48,6 +48,9 @@ namespace arch {
/* The scale block in both dimensions, fixed by the checkpoint (`weight_block_size`). libr4d
* compiles it in and its rows carry C_EQ("group", 128), so other widths resolve to no kernel. */
enum { RAD_FP8_BLOCK = 128 };
/* IQ8R's scale group: an int8 weight rotated 128 wide with one bf16 scale per row per 256 of K,
* met by an int8 activation with one f32 scale per (token, 256). */
enum { RAD_I8_GROUP_WIDE = 256 };
/* Rows of the scale plane for an N-row weight, and columns for a K-wide one. */
inline int64_t fp8_blocks(int64_t n) { return (n + RAD_FP8_BLOCK - 1) / RAD_FP8_BLOCK; }
@@ -63,6 +66,9 @@ struct ActFP8 {
* by the linear's own quant_act_i8g from `x`, or by the producer when `q8_fed`. */
rad_buf q8 = 0;
rad_buf s8 = 0;
/* The int8 pair's scale group: RAD_FP8_BLOCK, or RAD_I8_GROUP_WIDE for an IQ8R trunk, whose
* producers and quantisers write one scale per (row, 256). s8 has ceil(n / g8) columns. */
int64_t g8 = RAD_FP8_BLOCK;
/* The producer writes q8/s8 instead of the E4M3 pair (a connection read with
* HyperConn::Config::codes_i8, a gated quantiser, the attention gate or delta-net output
* epilogue), so an int8 linear reading it declares no quantiser. Set by the model when it
@@ -76,6 +82,8 @@ struct ActFP8 {
/* The code pair the producer writes: int8 when the model fed it, E4M3 otherwise. */
rad_buf cq() const { return q8_fed ? q8 : q; }
rad_buf cs() const { return q8_fed ? s8 : s; }
/* The scale group of cs(). */
int64_t cg() const { return q8_fed ? g8 : (int64_t)RAD_FP8_BLOCK; }
/* Declares the codes: the E4M3 pair with `fp8_pair`, the int8 pair with `i8` (an int8 model's
* activations need no E4M3 plane taking arena); `x` is set by the caller.
@@ -84,7 +92,9 @@ struct ActFP8 {
* (a MoE expert plane is `rows * top_k`, an encoder tower's its patch count); too small a value
* overruns the arena (core/runtime/issue.cpp refuses such an issue). */
int declare_qs(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
int64_t rows = 0, bool i8 = false, bool fp8_pair = true) {
int64_t rows = 0, bool i8 = false, bool fp8_pair = true,
int64_t i8_group = RAD_FP8_BLOCK) {
g8 = i8_group;
/* bf16 linears read only `x` (Geom::w_bf16), so declare no codes; an unused plane would
* still take arena space. */
if (g.w_bf16) { q = s = q8 = s8 = 0; return RAD_OK; }
@@ -96,11 +106,30 @@ struct ActFP8 {
}
if (i8) {
q8 = decl_b(b, nm.f("%s.q8", name), RAD_I8, { m, n });
s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, fp8_blocks(n) });
s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, (n + g8 - 1) / g8 });
if (!q8 || !s8) return RAD_E_INVAL;
}
return (fp8_pair || i8) ? RAD_OK : RAD_E_INVAL;
}
/* The code pair of a model that learned from a probe whether its linears are rotated int8
* (`i8`, at `i8_group` columns a scale): declare_qs's E4M3 pair for a block-fp8 model, and for
* an int8 one int8 codes. Those are written by the producer's own rotating quantiser `fed_op`
* (had_quant_act_i8g, or gated_had_quant_i8g behind a gated product) where the kernels serve
* it, and the linears reading them declare none; where they do not (the CPU kernels) the
* producer keeps its E4M3 pair and each linear quantises its own input from the bf16 plane.
* `x` is set by the caller. */
int declare_pair(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
int64_t rows, bool i8, int64_t i8_group, const char* fed_op) {
if (i8 && (i8_group <= 0 || n % i8_group)) {
fprintf(stderr, "radiance: the int8 linears keep one scale a %lld of K, which does not "
"divide this rank's %lld-wide '%s'\n",
(long long)i8_group, (long long)n, name);
return RAD_E_UNSUPPORTED;
}
if (i8 && rad_op_declared(b, fed_op)) q8_fed = q8_rot = true;
return declare_qs(b, nm, g, name, n, rows, i8, !q8_fed, i8 ? i8_group : RAD_FP8_BLOCK);
}
};
/* The fused attention prologue's row band, shared by the block issuing it, the rope table fill,
@@ -141,10 +170,11 @@ inline int QuantFP8::declare(RadBuilder* b, const Geom& g, const ActFP8& act, in
if (g.w_bf16) { op = 0; return a.x ? RAD_OK : RAD_E_INVAL; }
if (!a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL;
/* `dtype` is the input's (bf16); the op name gives the output format. An input fed at int8
* codes is quantised by quant_act_i8g into its int8 pair. */
op = rw(b, RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8",
* codes is quantised by quant_act_i8g into its int8 pair, or by had_quant_act_i8g where they
* are rotated (ActFP8::q8_rot). */
op = rw(b, RAD_OP(b, a.q8_fed ? (a.q8_rot ? "had_quant_act_i8g" : "quant_act_i8g") : "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
return RAD_OK;
@@ -154,7 +184,7 @@ inline void QuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const
if (!op) return;
if (rows <= 0) rows = T - r0;
RAD_ISSUE(c, op, brow_slice(a.x, r0, rows, n), brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
brow_slice(a.cs(), r0, rows, n / a.cg()));
}
/* ================================== the quantiser folded into the op that produces the row
@@ -465,7 +495,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
op = RAD_OP(b, hi8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype),
RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(w));
if (!op) return RAD_E_INVAL;
@@ -488,7 +518,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
op_arn = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_INT("group", a.cg()),
RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(w));
@@ -503,7 +533,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
op_arn6 = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_INT("group", a.cg()),
RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd),
RAD_INT("wire", 6)),
@@ -548,7 +578,7 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c
RAD_ISSUE_N(c, pick(rows), rows, brow_slice(src, r0, rows, n),
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
brow_slice(hi8 ? a.q8 : a.q, r0, rows, n),
brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / RAD_FP8_BLOCK),
brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / (hi8 ? a.g8 : (int64_t)RAD_FP8_BLOCK)),
brow_slice(a.x, r0, rows, n));
}
@@ -580,14 +610,20 @@ struct GateQuantFP8 {
* not resolve: `silu_mul` into the bf16 plane (`op`), then `had_quant_act_fp8` over it into the
* codes (`op_q`). */
rad_op op_q = 0;
/* act "relu2" (Nemotron-H's ungated experts): `gate_up` is one part, n wide, and `op` is
* act_mul's relu over it twice, relu(x)^2 into the bf16 plane, which `op_q` quantises (rotated
* for a rotated weight). No fused form yet: the plane is written either way. */
bool ungated = false;
/* Set before declare: the product in bf16 alone, as for bf16 linears, for a consumer that
* quantises its input itself (an int8 linear's op_q). */
bool silu_only = false;
/* `step`: with `limit`, clip after the SiLU (`swiglu_step`, Ling-3.0) rather than before it
* (`swiglu_clamped`, GLM-5.3). It has no fused quantiser, so the pair runs. */
int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n,
const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true,
bool rot = false, double limit = 0);
bool rot = false, double limit = 0, bool step = false);
void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
};
@@ -596,7 +632,7 @@ struct GateQuantFP8 {
* bf16 output is unrotated either way. */
inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act,
int64_t n, const char* act_name, int64_t max_rows,
bool bf16_out, bool rot, double limit) {
bool bf16_out, bool rot, double limit, bool step) {
a = act;
want_x = bf16_out;
op_quant = 0;
@@ -607,14 +643,39 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
clipped = limit > 0;
clamped_fused = false;
if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL;
if (clipped) {
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated; and no clamp
* with `silu_only`. */
if (!gate_up || !a.x || n <= 0 || rot || silu_only || (a.q8_fed && a.q8_rot) ||
std::strcmp(act_name, "silu"))
ungated = std::strcmp(act_name, "relu2") == 0;
if (ungated) {
if (!gate_up || !a.x || n <= 0 || clipped || (!bf16 && (!a.cq() || !a.cs())) ||
(rot && a.q8_fed))
return RAD_E_INVAL;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
if (fuse_clamped && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
want_x = true;
op = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("act", "relu"),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ gate_up }, { a.x });
if (!op) return RAD_E_INVAL;
if (bf16) return RAD_OK;
const char* qn = rot ? "had_quant_act_fp8" : a.q8_fed ? "quant_act_i8g" : "quant_act_fp8";
op_q = rw(b, RAD_OP(b, qn,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
return op_q ? RAD_OK : RAD_E_INVAL;
}
if (clipped) {
/* The clamp writes the bf16 plane and a quantiser reads it: E4M3, plain int8, or the
* rotated int8 codes an i8a8h consumer reads (had_quant_act_i8g at that consumer's
* group, the quantiser the rotated trunk's other inputs use). Against the unclamped
* gated_had_quant_i8g that is one launch more, in the clamped layers only. No clamp
* with `silu_only`, and none into a rotated E4M3 consumer (`rot`). */
if (!gate_up || !a.x || n <= 0 || rot || silu_only || std::strcmp(act_name, "silu"))
return RAD_E_INVAL;
const bool hi8 = a.q8_fed && a.q8_rot;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
if (fuse_clamped && !step && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
rad_op_declared(b, "swiglu_clamped_quant_fp8")) {
op =
RAD_OP(b, "swiglu_clamped_quant_fp8",
@@ -631,18 +692,20 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
}
want_x = true;
op = rw(b,
RAD_OP(b, "swiglu_clamped",
RAD_OP(b, step ? "swiglu_step" : "swiglu_clamped",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ gate_up }, { a.x });
if (!bf16) {
if (!a.cq() || !a.cs()) return RAD_E_INVAL;
const char* qn = hi8 ? "had_quant_act_i8g" : a.q8_fed ? "quant_act_i8g"
: "quant_act_fp8";
op_quant =
rw(b,
RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8",
RAD_OP(b, qn,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
if (!op_quant) return RAD_E_INVAL;
@@ -674,7 +737,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
if (!rot || rad_op_declared(b, "gated_had_quant_fp8"))
op = RAD_OP(b, gq,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
RAD_INT("group", a.cg()), RAD_STR("dtype", g.dtype),
RAD_STR("act", act_name)),
RAD_NOWEIGHTS);
/* The rotated op's chain, which writes the bf16 plane whether or not a consumer asked. */
@@ -701,10 +764,19 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0,
int64_t rows) const {
if (rows <= 0) rows = T - r0;
if (ungated) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, n), brow_slice(gate_up, r0, rows, n),
brow_slice(a.x, r0, rows, n));
if (op_q)
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
return;
}
if (clamped_fused) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK),
brow_slice(a.cs(), r0, rows, n / a.cg()),
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
return;
}
@@ -714,7 +786,7 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
if (op_quant)
RAD_ISSUE_N(c, op_quant, rows, brow_slice(a.x, r0, rows, n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
brow_slice(a.cs(), r0, rows, n / a.cg()));
return;
}
if (bf16 || op_q) {
@@ -722,12 +794,12 @@ inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0
if (op_q)
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
brow_slice(a.cs(), r0, rows, n / a.cg()));
return;
}
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK),
brow_slice(a.cs(), r0, rows, n / a.cg()),
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
}
@@ -779,6 +851,13 @@ struct LinearFP8 {
* writes E4M3. Read from the weight's encoding. */
bool i8 = false;
rad_op op_q = 0;
/* An int8 weight stored rotated (i8a8h, or a rotated four- or five-bit one): its activation
* codes are in the 128-wide Hadamard domain, whoever wrote them (had_quant_act_i8g or a
* rotating producer). */
bool i8_rot = false;
/* With i8_rot: an IQR weight (libr4d's r4d_iqr.h), whose codes decode where they are read: a
* u6 code under a zero, a table, a grid or a trellis. Read from the weight's encoding. */
bool iqr = false;
/* OCP-MXFP4 weight read by `gemm_nt_q` at dtype mxfp4a8 against the usual E4M3 activation pair:
* e2m1 codes with one E8M0 exponent per 32 of K (libquant `codes=fp4_e2m1 group=32
* scale=e8m0`). libr4d folds each block's exponent into the e4m3 operand against a per-row
@@ -820,6 +899,9 @@ struct LinearFP8 {
/* probe() found an int8 weight; lets a model learn its trunk's format from one linear before
* declaring activation buffers (ActFP8::declare_qs's `i8`). */
bool probed_i8 = false;
/* With probed_i8: the weight's scale group along K (linear_w8h_group), which the model's int8
* activation pairs must share (ActFP8::g8). */
int64_t probed_g8 = RAD_FP8_BLOCK;
/* Whether this linear's block-fp8 GEMM takes the short-prompt split rule
* (`gemm_nt_q_short`, narrow_ksplit's `short_unsplit`): at N <= 512, K <= 5120 and 41..64 rows
* the split's per-slice floors dominate, so the row runs unsplit. Opt-in, so every other
@@ -977,7 +1059,26 @@ inline bool linear_w8h_scale2(const RadEncoding& e) {
s2->kind == RAD_PLANE_TILED && (s2->dtype == RAD_F32 || s2->dtype == RAD_BF16) &&
(s2->block[0] == 0 || s2->block[0] == 1) && s2->block[1] == 0;
}
/* IQ8R: int8 codes rotated 128 wide with a u8 scale per [1 x 256] under one bf16 scale a row
* (libquant `codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128`), served as the
* I8 form at twice the scale group. */
inline bool linear_is_iq8r(const RadEncoding& e) {
if (!rad_enc_is(&e, "affine") || e.n_planes != 3 ||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
return false;
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
const RadEncPlane* s2 = rad_enc_plane(&e, "scale.1");
return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_U8 &&
sc->kind == RAD_PLANE_TILED && sc->block[0] == 1 && sc->block[1] == RAD_I8_GROUP_WIDE &&
s2 && s2->dtype == RAD_BF16 && s2->kind == RAD_PLANE_TILED && s2->block[0] == 1 &&
s2->block[1] == 0;
}
/* The scale group along K of a weight served at i8a8 / i8a8h. */
inline int64_t linear_w8h_group(const RadEncoding& e) {
return linear_is_iq8r(e) ? (int64_t)RAD_I8_GROUP_WIDE : (int64_t)RAD_FP8_BLOCK;
}
inline W8hForm linear_w8h_form(const RadEncoding& e) {
if (linear_is_iq8r(e)) return W8hForm::I8;
const bool trellis = rad_enc_is(&e, "trellis");
if ((!rad_enc_is(&e, "affine") && !trellis) ||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
@@ -1042,6 +1143,17 @@ inline bool linear_is_wnh(const RadEncoding& e) {
zp->block[1] == RAD_FP8_BLOCK;
}
/* Whether a trunk whose first linear probed as `e` is rotated int8 -- w8h or wnh -- and if so
* how wide its activation codes' scale group is: 256 for IQ8R, 128 for the other rotated forms
* (linear_w8h_group spells the rule). An arch learns this by probing layer 0's q projection
* before declaring activations; the probe and the fields are the arch's, the question belongs
* beside the predicates it is made of. */
inline bool trunk_rotation(const RadEncoding& e, int64_t* g8) {
if (!linear_is_w8h(e) && !linear_is_wnh(e)) return false;
*g8 = linear_w8h_group(e);
return true;
}
/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes and an E8M0 exponent per [1 x 32],
* no transform (libr4d's MXFP4 layout hook). */
enum { RAD_MX_GROUP = 32 };
@@ -1100,6 +1212,32 @@ inline bool linear_is_paro_m2xfp4(const RadEncoding& e) {
mt->block[1] == RAD_MX_GROUP;
}
/* The weight formats rad-convert reads and the engine does not serve: block fp8 (E4M3
* codes under a scale per 128 x 128), OCP MXFP4, M2XFP4 and the ParoQuant-rotated forms of the
* last two. The format's name, or nullptr for one that is served. */
inline const char* linear_retired(const RadEncoding& e) {
if (linear_is_paro_m2xfp4(e)) return "ParoQuant M2XFP4";
if (linear_is_paro_mxfp4(e)) return "ParoQuant MXFP4";
if (linear_is_givens(e)) return "ParoQuant";
if (linear_is_m2xfp4(e)) return "M2XFP4";
if (linear_is_mxfp4(e)) return "MXFP4";
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
if (rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
e.plane[0].dtype == RAD_F8E4M3 && sc && (sc->dtype == RAD_BF16 || sc->dtype == RAD_F32) &&
sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK)
return "block fp8";
return nullptr;
}
/* The refusal of a weight stored in one of them, by name, with what serves the model instead. */
inline int linear_refuse_retired(const char* weight, const char* format) {
fprintf(stderr, "radiance: '%s' is stored as %s, which this build does not serve. Convert "
"the checkpoint again with an int8 recipe (the IQ8R ones in data/recipes); if "
"the weight belongs to the container's drafter, `num-speculative-tokens: 0` "
"serves the model without it\n", weight, format);
return RAD_E_UNSUPPORTED;
}
/* A 4-bit weight with a zero point and no transform: u4 codes, an f16 scale and a u4 or u8 zero
* point per 128 of K (libquant `codes=u4 zero=u4 group=128 scale=f16`, or rad-convert's import rule
* over an int4 release). At decode w4a16_asym narrows the BF16 input to F16 on load; larger
@@ -1134,6 +1272,7 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
enc.plane[0].dtype == RAD_BF16;
probed_i8 = known && (linear_is_w8(enc) || linear_is_w8h(enc) || linear_is_wnh(enc));
probed_g8 = known ? linear_w8h_group(enc) : (int64_t)RAD_FP8_BLOCK;
/* A rotated weight rotates and quantises the bf16 plane itself; a 4-bit one casts or
* quantises it. */
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc) ||
@@ -1257,6 +1396,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const bool known = weight_enc(b, sw, &enc);
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
enc.plane[0].dtype == RAD_BF16;
if (known && !plain)
if (const char* gone = linear_retired(enc)) return linear_refuse_retired(sw, gone);
/* ---- bf16 weight, `gemm_nt` over `a.x`: every linear of a bf16 model, or one a quantised
* container keeps at checkpoint precision (e.g. the QSA indexer's projection, whose top-k is a
@@ -1310,6 +1451,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const bool asym = known && linear_is_wnh(enc);
const bool rot8 = known && (linear_is_w8h(enc) || asym);
i8 = known && (linear_is_w8(enc) || rot8);
i8_rot = i8 && rot8;
if (i8) {
if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
@@ -1329,10 +1471,18 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
"int8)\n", wn, a.q8_fed ? "" : " or the bf16 plane it quantises");
return RAD_E_DTYPE;
}
if (N % 16 || K % RAD_FP8_BLOCK) {
/* The scale group: 128, or 256 for IQ8R, which the input's int8 pair must share. */
const int64_t wg = linear_w8h_group(enc);
if (wg != a.g8) {
fprintf(stderr, "radiance: '%s' has a scale per %lld columns and its input's int8 codes "
"one per %lld; a trunk mixes IQ8R and 128-group int8 weights\n",
wn, (long long)wg, (long long)a.g8);
return RAD_E_DTYPE;
}
if (N % 16 || K % wg) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an int8 weight takes rows in "
"16s and K in whole %d-column scale groups\n",
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
"16s and K in whole %lld-column scale groups\n",
base, (long long)N, (long long)K, (long long)wg);
return RAD_E_INVAL;
}
RowParts rp;
@@ -1340,6 +1490,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const char* sn = nm.f("%s.scale", base);
/* A narrower i8a8h weight's codes view takes the plane that decodes it too. */
const W8hForm form = linear_w8h_form(enc);
iqr = rot8 && !asym && (form == W8hForm::Zero || form == W8hForm::Table ||
form == W8hForm::Grid || form == W8hForm::Trellis);
const RadEncPlane* tpl = rad_enc_plane(&enc, "trellis");
const bool trb = form == W8hForm::Trellis && tpl && tpl->block[1] > 1;
const char* cv = form == W8hForm::Zero ? "codes,zero"
@@ -1354,42 +1506,42 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
rp.w, rp.n);
/* A view of two planes is declared at the weight's logical extents and sliced in its
* columns, the stored planes left to the layout hook. */
const bool two = linear_w8h_scale2(enc) || linear_w8h_rowf(enc);
const bool iq8r = linear_is_iq8r(enc);
const bool two = linear_w8h_scale2(enc) || linear_w8h_rowf(enc) || iq8r;
ws = asym ? decl_view(b, sn, wn, "scale,zero", RAD_F16, { N, K }, access, shard, grp,
rp.w, rp.n)
: linear_w8h_rowf(enc) ? decl_view(b, sn, wn, "scale,scale.col", RAD_F32, { N, K },
access, shard, grp, rp.w, rp.n)
: two ? decl_view(b, sn, wn, "scale,scale.1", RAD_F8E4M3, { N, K }, access, shard,
grp, rp.w, rp.n)
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, access,
: two ? decl_view(b, sn, wn, "scale,scale.1", iq8r ? RAD_U8 : RAD_F8E4M3, { N, K },
access, shard, grp, rp.w, rp.n)
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / wg }, access,
shard, grp, rp.w, rp.n);
if (!w || !ws) return RAD_E_INVAL;
if (span_hi > 0) {
/* The (scale, zero) and (scale, scale.1) views are at the logical extents, sliced as
* the codes are. */
const bool col = shard == RAD_SHARD_COL && !asym && !two;
if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
if (col && (span_lo % wg || span_hi % wg)) {
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
"%d-column scale group\n", base, (long long)span_lo,
(long long)span_hi, RAD_FP8_BLOCK);
"%lld-column scale group\n", base, (long long)span_lo,
(long long)span_hi, (long long)wg);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
if ((asym || two) && shard == RAD_SHARD_COL &&
(span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
if ((asym || two) && shard == RAD_SHARD_COL && (span_lo % wg || span_hi % wg)) {
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
"%d-column scale group\n", base, (long long)span_lo,
(long long)span_hi, RAD_FP8_BLOCK);
"%lld-column scale group\n", base, (long long)span_lo,
(long long)span_hi, (long long)wg);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, col ? span_lo / RAD_FP8_BLOCK : span_lo,
col ? span_hi / RAD_FP8_BLOCK : span_hi));
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, col ? span_lo / wg : span_lo,
col ? span_hi / wg : span_hi));
}
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
if (!a.q8_fed)
op_q = rw(b, RAD_OP(b, rot8 ? "had_quant_act_i8g" : "quant_act_i8g",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("n", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
RAD_INT("group", wg), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ a.x }, { a.q8, a.s8 });
const char* qdt = asym ? (enc.plane[0].dtype == RAD_U5 ? "w5a8i8" : "w4a8i8_asym")
@@ -1404,7 +1556,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
{ a.q8, a.s8 }, { y })
: rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", qdt)),
RAD_INT("group", wg), RAD_STR("dtype", qdt)),
RAD_WEIGHTS(w, ws)),
{ a.q8, a.s8 }, { y });
return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL;
@@ -1722,9 +1874,9 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
if (i8) {
if (op_q)
RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, K), brow_slice(a.q8, r0, rows, K),
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK));
brow_slice(a.s8, r0, rows, K / a.g8));
RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K),
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK),
brow_slice(a.s8, r0, rows, K / a.g8),
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
return;
}
@@ -1798,6 +1950,17 @@ struct DenseFP8 {
bool mx = false;
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 views, the meta plane riding the weight operand. */
bool m2x = false;
/* Or a weight served at i8a8h (linear_w8h_form): IQ8R, the rotated int8 grid at 128, or a
* narrower form on it (signed codes, a zero point, a codebook, a trellis), its views as
* LinearFP8 declares them. It reads an INT8 activation pair with one scale per (row, `g8`) under
* the same rotation (had_quant_act_i8g at that group); the block declares that pair where it
* would the E4M3 one. `w_rb`: a trellis on a grid of several rows a scale says how many. */
bool w8h = false;
int64_t g8 = RAD_FP8_BLOCK;
int64_t w_rb = 0;
/* Set before declare by a block that declares the int8 activation pair such a weight reads;
* any other block's activations are E4M3, so declare refuses the weight there. */
bool w8h_ok = false;
/* `mapped`: the caller made the name map already, to ask the encoding before choosing this
* struct over another grid's -- a COPY map declared twice is refused (rad_builder.cpp). */
@@ -1829,12 +1992,42 @@ struct DenseFP8 {
RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi));
return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK);
}
/* This rank's rows [lo, hi) of a RAD_SHARD_ROW weight where the even shard is the wrong cut: a
* KV head replicated over ranks (Geom::kv_off), the same rows on every rank that shares it.
* Call after declare(), whose N is already hi - lo. The fp8 scale plane takes the span in its
* 128-row blocks; the MXFP4 and M2XFP4 planes are one row a weight row, as in LinearFP8. */
int span(RadBuilder* b, int64_t lo, int64_t hi) const {
RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi));
if (mx || m2x) {
RAD_ARCH_TRY(rad_weight_shard_span(b, s, lo, hi));
return rad_weight_shard_span(b, ref, lo, hi);
}
if (lo % RAD_FP8_BLOCK || hi % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: a row span [%lld, %lld) is not whole %d-row scale blocks\n",
(long long)lo, (long long)hi, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK);
}
/* `gemm_nt_q` over this weight, `fp8a8`, `mxfp4a8` or `m2xfp4` as it was declared, ranged
* M 1..hi. `split_n`, when set, is the stored width a row slice takes its K split from
* (docs/OPS.md). */
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes,
int64_t split_n = 0) const {
if (w8h && w_rb > 0)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", g8), RAD_STR("dtype", "i8a8h"),
RAD_INT("w_rb", w_rb)),
RAD_WEIGHTS(w, s)),
reads, writes);
if (w8h)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", g8), RAD_STR("dtype", "i8a8h")),
RAD_WEIGHTS(w, s)),
reads, writes);
if (mx || m2x)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
@@ -1876,6 +2069,53 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
const bool known = weight_enc(b, wn, &enc);
mx = known && linear_is_mxfp4(enc);
m2x = known && linear_is_m2xfp4(enc);
/* Plain MXFP4 is still read here: the published IQR-V4 containers carry their DFlash2
* drafter in it. */
if (known && !mx)
if (const char* gone = linear_retired(enc)) return linear_refuse_retired(wn, gone);
const W8hForm form = known ? linear_w8h_form(enc) : W8hForm::None;
w8h = form != W8hForm::None;
if (w8h && !w8h_ok) {
fprintf(stderr, "radiance: '%s' is a rotated int8 weight, which reads an int8 "
"activation; this block quantises its activations to E4M3 and takes "
"block fp8 or MXFP4 weights\n", base);
return RAD_E_DTYPE;
}
if (w8h) {
g8 = linear_w8h_group(enc);
if (N % 16 || K % g8) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a rotated int8 weight takes "
"rows in 16s and K in whole %lld-column scale groups\n",
base, (long long)N, (long long)K, (long long)g8);
return RAD_E_INVAL;
}
RowParts rp;
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "int8 tiles"));
/* The views LinearFP8's i8a8h branch declares: a narrower form's codes take the plane
* that decodes them, and a scale of two planes is one view at the weight's logical
* extents, which the kernel's layout combines. */
const RadEncPlane* tpl = rad_enc_plane(&enc, "trellis");
w_rb = form == W8hForm::Trellis && tpl && tpl->block[1] > 1 ? tpl->block[1] : 0;
const char* cv = form == W8hForm::Zero ? "codes,zero"
: form == W8hForm::Table ? "codes,table"
: form == W8hForm::Grid ? "codes,grid"
: form == W8hForm::Trellis ? (linear_w8h_mad(enc) ? "codes,trellis,trellis.mad"
: "codes,trellis")
: "codes";
const char* sn = nm.f("%s.scale", base);
const bool iq8r = linear_is_iq8r(enc);
w = decl_view(b, wn, nullptr, cv, enc.plane[0].dtype, { N, K }, access, shard, grp,
rp.w, rp.n);
s = linear_w8h_rowf(enc)
? decl_view(b, sn, wn, "scale,scale.col", RAD_F32, { N, K }, access, shard, grp,
rp.w, rp.n)
: (linear_w8h_scale2(enc) || iq8r)
? decl_view(b, sn, wn, "scale,scale.1", iq8r ? RAD_U8 : RAD_F8E4M3, { N, K },
access, shard, grp, rp.w, rp.n)
: decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / g8 }, access, shard, grp,
rp.w, rp.n);
return w && s ? RAD_OK : RAD_E_INVAL;
}
if (mx || m2x) {
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an %s weight takes rows "
@@ -1968,6 +2208,27 @@ inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t
return 0;
}
/* The same fold over an IQR [2n, K] gate_up weight under the rotated int8 trunk (`gemm_nt_q_gated`
* at i8a8h: the codes and scale views gemm_nt_q reads, the input's and the output's int8 pairs, both
* in the Hadamard domain), declared for M up to min(rows, 16): libr4d's gemm_iqr_gated serves its
* GEMV and 16-token tile, each byte-identical to the GEMM row of its band followed by
* gated_had_quant_i8g. Optional like decl_gated_fold, and asked for only when a loaded library
* declares the op at that dtype: a CPU-only engine takes the pair. */
inline rad_op decl_gated_fold_iqr(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
rad_weight ws, std::initializer_list<rad_buf> reads,
std::initializer_list<rad_buf> writes, int64_t* gated_rows) {
if (rows <= 0 || N % 256 || K % 256) return 0;
const int64_t hi = rows < 16 ? rows : 16;
const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "i8a8h"),
RAD_STR("act", "silu")),
RAD_WEIGHTS(w, ws)),
reads, writes);
if (op) *gated_rows = hi;
return op;
}
/* ================================================== a calibration tap */
/* One tap of the GPTQ calibration (calib_dir): the Gram of a linear's bf16 input, summed over the
* corpus in a PERSIST [K, K] f32 buffer that calib_write() saves. */
+71
View File
@@ -0,0 +1,71 @@
/* Muse Glimmer's reply format: the ATEM channel protocol its chat template renders.
*
* The template's generation prompt ends at `<|start|>assistant`, so the model opens its own
* channels: `<to=self>` reasoning first, then the answer:
*
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=user<|message|> ...answer...
*
* `reasoning_close` carries the whole channel transition, so the answer's own header is consumed
* with the reasoning block's close and the content begins at the answer's first byte. A reply
* that skips the reasoning opens on the answer's channel directly (`to=user<|message|> ...`);
* `content_open` names that header so it is dropped there too.
*
* Tool calls are the template's ATEM dialect, emitted as their own assistant turn whose channel
* names the tool (chat_template.jinja, render_atem):
*
* to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=NAME<|message|>
* <atem:function_calls>
* <atem:invoke name="NAME">
* <atem:parameter name="k">value</atem:parameter>
* </atem:invoke>
* </atem:function_calls>
*
* String parameters are written raw, everything else as JSON (the template's `tojson`); the
* section opener is the constrained-decoding trigger, and it is also the reasoning break: a call
* turn's channel header names the tool rather than `user`, so the answer's `reasoning_close`
* does not match there and the reasoning block runs to the section, swallowing the `<|eom|>` and
* the header.
*/
#pragma once
#include "rad_builder.h"
namespace museglimmer {
inline const RadChatFormat* muse_chat_format() {
static const RadChatFormat f = [] {
RadChatFormat x{};
x.struct_size = sizeof(x);
x.name = "plugin:museglimmer";
x.reasoning_open = "to=self<|message|>";
x.reasoning_close = "<|eom|><|start|>assistant to=user<|message|>";
static const char* const kBreaks[] = {"<atem:function_calls>"};
x.reasoning_breaks = kBreaks;
x.n_reasoning_breaks = 1;
/* The model opens its own channel; the prompt carries none. */
x.reasoning_in_prompt = RAD_CHAT_THINK_NEVER;
x.content_open = "to=user<|message|>";
x.section_open = "<atem:function_calls>";
x.section_close = "</atem:function_calls>";
x.call_open = "<atem:invoke ";
x.name_prefix = "name=\"";
x.name_suffix = "\">";
x.call_end = "</atem:invoke>";
x.arg_prefix = "<atem:parameter name=\"";
x.arg_name_suffix = "\">";
x.arg_value_suffix = "</atem:parameter>";
x.string_value = RAD_CHAT_VALUE_RAW; /* the template writes string arguments raw */
x.other_value = RAD_CHAT_VALUE_JSON; /* booleans, numbers, arrays, objects as tojson */
x.value_newlines = 1;
/* No grammar triggers: the reference deployment (vLLM's --tool-call-parser muse) runs
* unconstrained and parses whatever the model writes. A trigger arms the lazy tool-call
* grammar, and with the DFlash drafter the trigger fires mid-verify -- inside drafted
* text -- at the reasoning-to-call boundary, which spins the sampler and loops the
* channel header (measured: drafter on = the header repeats 3-4x and the reply stalls;
* drafter off = one header, clean call). The streaming parser reads natural ATEM as
* it is. */
return x;
}();
return &f;
}
} /* namespace museglimmer */
+80 -21
View File
@@ -9,7 +9,8 @@
* 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.
* change here. A step entirely at or below that bound therefore needs no selection at all, and
* step() issues only the block-key path for it (its `use`; docs/QSA.md, "Below the bound").
*/
#ifndef RAD_QSA_H
#define RAD_QSA_H
@@ -121,13 +122,43 @@ struct QsaIndexer {
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
const Wire& wire, const ActFP8& in, rad_kvgroup* bk);
/* `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. */
* score plane (Config::plane_rows); null where no step is.
*
* `use` is what the layer's attention reads of the selection this step (QsaUse, rad_arch.h;
* AttnGatedFP8::qsa_use): the default issues the query, the scores and the selection as every
* step did before. `first` is whether this is the first full-attention layer the pass issues:
* at or below the bound the selection is made there once and read by every layer after it (the
* buffers are the model's, live across its layers, and nothing else writes them). The default
* makes it at every layer. */
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch,
const int32_t* win_cu = nullptr) const;
const int32_t* win_cu = nullptr, int use = kQsaSelect, bool first = true) 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;
/* `part` 0 issues all of it; 1, 2 and 3 its three stages apart and in that order (the work
* list, the block keys, the tail store), for a caller that issues them behind another block's
* launches (deferrable, below). */
bool store_keys(RadCtx* c, const RadBatch* batch, int part = 0) const;
/* Whether this step's keys and tail may be issued behind the attention block's launches
* instead of in front of them (SideOps, rad_arch.h): nothing reads a selection of this
* layer's (`use` as step() resolves it), so the attention reads nothing the three ops write.
* The caller answers for the buffers (Wire: qk, stage, page, bpos, nc excluded from
* sharing). */
bool deferrable(const RadBatch* batch, int use, bool first) const {
if (!on() || qsa_eager()) return false;
/* step() stores no keys for a batch without the attention's group; leave that to it. */
if (!kv_batch(batch, c.kv_attn)) return false;
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
return use == kQsaUnread;
}
/* What step() issues on a deferrable step, a piece at a time: the projection, then
* store_keys's stages 1..3. */
void step_proj(RadCtx* c, const ActFP8& in, const RadBatch* batch) const {
proj.step(c, in, w.qk, batch->n_tok);
}
void step_part(RadCtx* c, const RadBatch* batch, int part) const {
(void)store_keys(c, batch, part);
}
};
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -267,7 +298,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
/* 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 {
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch, int part) const {
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t nw = (c.heads + 1) * c.head_dim;
const int64_t koff = c.heads * c.head_dim; /* the raw-key head, after the query heads */
@@ -289,20 +320,24 @@ inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
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;
RAD_ISSUE_N(c_, op_work, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw),
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
brows(w.nc, S));
RAD_ISSUE_N(c_, op_bkey, work,
brows(w.stage, work * c.ratio), RAD_W(w_kn),
brows(w.page, work), bpos,
kv_cache(kv_bk, layer));
if (part <= 1)
RAD_ISSUE_N(c_, op_work, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw),
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
brows(w.nc, S));
if (part == 1) return true;
if (part == 0 || part == 2)
RAD_ISSUE_N(c_, op_bkey, work,
brows(w.stage, work * c.ratio), RAD_W(w_kn),
brows(w.page, work), bpos,
kv_cache(kv_bk, layer));
if (part == 2) return true;
RAD_ISSUE_N(c_, op_tail, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
@@ -319,13 +354,31 @@ inline void QsaIndexer::store(RadCtx* c_, const ActFP8& in, const RadBatch* batc
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch,
const int32_t* win_cu) const {
const int32_t* win_cu, int use, bool first) 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;
/* What the attention reads this step (QsaUse); anything asked of a step that cannot give it is
* the full issue, which every reader accepts.
*
* kQsaOnce: the attention reads a selection on a step entirely at or below the exactness
* bound. A row there has at most `topk` complete blocks, so qsa_select takes every one whose
* key is not 0 -- every block with a page and a score that is a number, whatever the number --
* and what it writes (the pages in block order, the partial page, their count, seqused) is a
* function of the positions and the block table: the same bytes from every layer's scores. So
* the pass's first full-attention layer issues the selection exactly as it always did, and
* every later layer reads that one and issues none of its own: no query, no score. */
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
if (use != kQsaUnread) use = kQsaSelect;
/* RADIANCE_DEBUG_QSA_EAGER: the issue sequence as it was, every layer its own. */
if (qsa_eager()) use = kQsaSelect;
/* The projection always: its raw-key head is the block keys' and the tail's. */
proj.step(c_, in, w.qk, T);
/* The query heads are read by the score alone. */
if (use == kQsaSelect) {
/* 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
@@ -342,8 +395,10 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
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. */
/* The keys first: the selection below reads the blocks they complete. The stateful half runs
* whatever the attention reads: later steps score the block keys and build on the tail. */
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
if (!atb || !store_keys(c_, batch)) return;
@@ -352,6 +407,10 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
* 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;
/* Nothing reads a selection of this layer's: the step is at or below the exactness bound and
* its attention reads the block table, or the selection the pass's first full-attention layer
* made (AttnGatedFP8::qsa_use). */
if (use == kQsaUnread) return;
/* 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
+7 -4
View File
@@ -86,7 +86,7 @@ struct Model {
Gemma4Audio aud;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* 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
@@ -123,7 +123,8 @@ static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector<
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
/* A 270M encoder fits easily on one card; tensor parallelism would only add an all-reduce per
* layer, so it is not offered. */
if (ctx->world_size > 1) {
@@ -132,7 +133,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
@@ -417,7 +418,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
const Geom& g = m.g;
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
if (batch->enc) {
@@ -480,6 +481,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
} /* namespace embgemma2 */
#ifndef RAD_ARCH_NO_EXPORTS
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(embgemma2, "embeddinggemma2", "", "0.1.0",
"EmbeddingGemma 2: a bidirectional Gemma encoder with per-layer embeddings, "
"mean-pooled to one vector an input; bf16")
+7 -4
View File
@@ -322,7 +322,7 @@ struct Model {
* row's label). */
constexpr int64_t kPcW = kMaxPrompt + 1;
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* ================================================================== declare helpers */
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, double wadd,
@@ -1701,8 +1701,9 @@ static int declare_encoder(RadBuilder* b, Model& m) {
/* ================================================================== declare */
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];
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(check_format(meta));
@@ -2184,7 +2185,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
if (!batch->gen || !batch->agen_b) {
rad_step_fail(c, "fishomni is an audio generator and runs generator passes only");
return;
@@ -2352,6 +2353,8 @@ RAD_ARCH_PROBE(fishomni)
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
return fishomni::text_prepare(field, in, out, cap);
}
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(fishomni, "fishomni", "bsgemm-moe", "0.1.0",
"Fish Audio drama-3: the Qwen3.5-35B-A3B backbone (block-scaled fp8 experts), a "
"13-layer codebook tower over its full-attention cache, and Fish S2's modified "
+9
View File
@@ -0,0 +1,9 @@
# Built in radiance's tree, or standalone against an installed radiance.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(flint LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(flint architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flint.cpp)
+542
View File
@@ -0,0 +1,542 @@
/* flint -- Recursive Flint (39.8B-A2.5B): two dense layers then 47 sigmoid-routed MoE layers,
* grouped-query attention with per-head Q/K RMSNorm, a learned per-head softmax sink, and a
* 513-token sliding window on 35 of the 49 layers (the other 14 are full attention and NoPE).
*
* 2 dense layers: rmsnorm -> q/k/v -> qk-norm -> [rope] -> paged attention + sink -> o
* rmsnorm -> gate_up -> silu_mul -> down
* 47 MoE layers: same attention; rmsnorm -> router -> top-6 of 256 (sigmoid)
* -> grouped gate_up -> silu_mul -> down -> gather
* + ungated shared expert (2 x 512)
*
* Weights come from a BF16 or recipe-quantized Flint checkpoint; the blocks probe the stored
* encoding. Two trunk forms, read from layer 0's q projection:
*
* - a rotated int8 trunk (data/recipes/flint-iq8r.recipe: IQ8R linears, i8 codes rotated by a
* 128-wide Hadamard): the norms, the gated products and the attention output write
* had_quant_act_i8g's codes themselves, every linear reads them at i8a8h, and the routed
* experts are rotated int8 (or another form with an int8 row) read by the grouped GEMM's int8
* rows from the same codes (MoeFP8::a8), as qwen35moe_w8a8 serves Qwen3.6-35B-A3B;
* - any other (bf16, the four-bit attention of data/recipes/flint-bf16-q4.recipe, plain int8
* linears): each linear reads the bf16 plane or quantises it itself, and four-bit experts read
* the block input's E4M3 pair, as hyv3_bf16 serves its W4 and W8 recipes.
*
* No MTP head.
*/
#include <arch/rad_arch.h>
#include "flint_attention.h"
#include <arch/rad_block_mlp_fp8.h>
#include <arch/rad_block_moe_fp8.h>
#include "rad_abi_layout.h"
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
namespace flint {
using namespace rad::arch;
struct Layer {
bool dense = false;
bool sliding = false;
FlintAttn attn{};
MlpFP8 dense_mlp{};
MoeFP8 moe{};
};
struct Model {
Names nm{};
Geom g{};
int64_t n_ff_expert = 0, n_ff_shared = 0;
rad_kvgroup kv_full = 0, kv_win = 0;
/* Whether layer 0's probe found a rotated-int8 trunk, and its activation scale group: see
* rad_fp8.h's trunk_rotation. */
bool trunk_rot = false;
int64_t trunk_g8 = RAD_FP8_BLOCK;
rad_buf x = 0, h_out = 0, logits = 0;
ActFP8 h{};
/* The routed experts' rotated int8 copy of the block input, where a rotated trunk's norms do
* not write the codes themselves (MoeFP8::Wire::hr). */
ActFP8 hr{};
rad_buf q = 0, k = 0, v = 0;
ActFP8 attn{};
rad_buf dense_gate_up = 0;
ActFP8 dense_ffn{};
MoeFP8::Wire mw{};
rad_weight token = 0, final_norm = 0, lm_head = 0;
rad_op embed = 0, embed_ar = 0, shared_one = 0, final_rms = 0, gather = 0, logits_op = 0;
std::vector<Layer> layers;
};
/* Every per-instance state is indexed by slot (rad_build_slot at declare, rad_slot in step). */
static Model g_model[MAX_SLOTS];
/* Flint's layer schedule: full attention (and NoPE) at 0, 1, 5, 9, ..., 45, 48; the other 35
* layers are sliding (window 513) and carry RoPE. */
static bool is_full(int64_t l) {
return l == 0 || l == 1 || l == 48 || (l >= 5 && l <= 45 && (l - 5) % 4 == 0);
}
static int64_t meta_i(const RadModelMeta* meta, const char* a, const char* b, int64_t def) {
int64_t v = meta_text_geti(meta, a, INT64_MIN);
if (v == INT64_MIN && b) v = meta_text_geti(meta, b, INT64_MIN);
return v == INT64_MIN ? def : v;
}
static int check_model(const RadModelMeta* meta, const Geom& g, Model& m) {
const int64_t sliding = meta_i(meta, "sliding_window", "flint.attention.sliding_window", 513);
const int64_t n_expert = meta_text_geti(meta, "num_experts", meta->n_expert);
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
const int64_t moe_ff = meta_i(meta, "moe_intermediate_size",
"flint.expert_feed_forward_length", 512);
const int64_t shared = meta_i(meta, "shared_expert_intermediate_size",
"flint.expert_shared_feed_forward_length", 1024);
const int64_t dense_ff = meta_i(meta, "intermediate_size",
"flint.feed_forward_length", 6144);
if (g.n_layer != 49 || g.n_embd != 2048 || g.n_head_all != 32 || g.n_head_kv_all != 4 ||
g.head_dim != 128 || g.n_vocab_all != 150144 || dense_ff != 6144 ||
sliding != 513 || n_expert != 256 || top_k != 6 || moe_ff != 512 || shared != 1024) {
fprintf(stderr, "radiance: flint: unsupported geometry (49 layers, 2048-wide, 32/4 "
"heads x 128, vocab 150144, 256 experts top-6, expert width 512, shared "
"1024, sliding 513); got %lld layers, %lld-wide, %lld/%lld heads, "
"vocab %lld, %lld experts top-%lld, expert %lld, shared %lld, "
"sliding %lld, dense %lld\n",
(long long)g.n_layer, (long long)g.n_embd, (long long)g.n_head_all,
(long long)g.n_head_kv_all, (long long)g.n_vocab_all, (long long)n_expert,
(long long)top_k, (long long)moe_ff, (long long)shared, (long long)sliding,
(long long)dense_ff);
return RAD_E_UNSUPPORTED;
}
if (g.world != 1 && g.world != 2) {
fprintf(stderr, "radiance: flint supports tensor-parallel world sizes 1 and 2\n");
return RAD_E_UNSUPPORTED;
}
m.n_ff_expert = moe_ff;
m.n_ff_shared = shared;
return RAD_OK;
}
static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) {
const int64_t blocks = width / RAD_FP8_BLOCK;
const int64_t base = blocks / world, rem = blocks % world;
const int64_t first = rank * base + std::min<int64_t>(rank, rem);
const int64_t count = base + (rank < rem ? 1 : 0);
*lo = first * RAD_FP8_BLOCK;
*hi = (first + count) * RAD_FP8_BLOCK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
int status = geom_from(m.g, meta, ctx, "bf16", RAD_BF16);
if (status < 0) return status;
Geom& g = m.g;
Names& nm = m.nm;
status = check_model(meta, g, m);
if (status < 0) return status;
if (ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_I8) {
fprintf(stderr, "radiance: flint serves a bf16 or an int8 KV cache, not %s\n",
rad_dtype_name((uint32_t)ctx->kv_dtype));
return RAD_E_UNSUPPORTED;
}
status = yarn_from(g, meta, "", g.head_dim);
if (status < 0) return status;
const int64_t sliding = meta_i(meta, "sliding_window", "flint.attention.sliding_window", 513);
const int64_t n_expert_all = meta_text_geti(meta, "num_experts", meta->n_expert);
const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used);
if (n_expert_all % g.world != 0) return RAD_E_SHAPE;
const int64_t n_expert_local = n_expert_all / g.world;
/* Two paged groups: the 14 full layers grow with the context, the 35 sliding layers keep
* only 513 tokens. That is what makes 262K affordable. Both take the deployment's cache
* dtype: bf16, or with --kv-cache-dtype i8 the int8 cache (abi/rad_builder.h), K and V as
* int8 codes with one f16 scale each per token and head. */
RadKVGroupDecl kd{};
kd.kind = RAD_KV_FULL;
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
kd.n_head_kv = g.n_head_kv;
kd.head_dim = g.head_dim;
m.kv_full = rad_decl_kv_group(b, nm.f("kv_full"), &kd);
if (!m.kv_full) return RAD_E_INVAL;
RadKVGroupDecl kw = kd;
kw.kind = RAD_KV_WINDOW;
kw.window = sliding;
m.kv_win = rad_decl_kv_group(b, nm.f("kv_win"), &kw);
if (!m.kv_win) return RAD_E_INVAL;
g.kv_dtype = rad_dtype_name(kd.dtype);
const int64_t T = g.max_tok, qd = g.q_dim(), kvd = g.kv_dim();
/* The trunk's stored form, probed from layer 0's q projection: rad_fp8.h's trunk_rotation
* answers whether it is rotated int8 and how wide the activation codes' scale group is. */
m.layers.resize((size_t)g.n_layer);
RAD_ARCH_TRY(m.layers[0].attn.q.probe(b, nm, g, nm.f("blk.0.attn_q"),
{ nm.ckpt("model.layers.0.self_attn.q_proj.weight") }));
{
RadEncoding enc{};
m.trunk_rot = weight_enc(b, nm.f("blk.0.attn_q.weight"), &enc) &&
trunk_rotation(enc, &m.trunk_g8);
}
MoeFP8::Config mc{};
mc.n_expert_all = n_expert_all;
mc.n_expert = n_expert_local;
mc.expert_base = n_expert_local * g.rank;
mc.probed_expert = mc.expert_base;
mc.top_k = top_k;
mc.n_ff_exp = m.n_ff_expert;
mc.norm_topk = 1;
mc.sigmoid_router = 1;
mc.route_scale = meta_text_getf(meta, "router_scaling_factor", 1.0);
mc.shared_ungated = 1;
/* One combine at the gather, not two separately reduced arms: TP2 then matches the TP1
* arithmetic (the local routed+shared sum is rounded to bf16 once and the closing
* all-reduce reduces it), and that single collective folds into the next block's norm. */
mc.shared_fp32_combine = 0;
mc.shared_one_external = g.world == 1;
mc.router_fuse = 1;
mc.rows = T < 2048 ? T : 2048;
block_slice_128(m.n_ff_shared, g.world, g.rank, &mc.shared_lo, &mc.shared_hi);
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
/* ---- the routed experts' stored form, read from the first routed layer's first owned
* expert; every layer is declared with it (MoeFP8::declare checks each layer's own). */
const int64_t l_moe = 2;
MoeFP8::Src probe_src{};
probe_src.experts = nm.ckpt("model.layers.%lld.mlp.experts", (long long)l_moe);
RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)l_moe, probe_src, &mc));
if (m.trunk_rot && (mc.expert_bf16 || !mc.expert_rot)) {
fprintf(stderr, "radiance: flint: the trunk is rotated int8 and the routed experts are "
"%s; a rotated trunk's experts read its int8 codes and are stored rotated "
"(data/recipes/flint-iq8r.recipe)\n",
mc.expert_bf16 ? "plain bf16" : "unrotated");
return RAD_E_UNSUPPORTED;
}
if (!m.trunk_rot && (mc.expert_i8 || mc.expert_iqr)) {
fprintf(stderr, "radiance: flint: the routed experts are rotated int8 and the trunk is "
"not; they read the trunk's rotated int8 codes, so convert the trunk with "
"them (data/recipes/flint-iq8r.recipe)\n");
return RAD_E_UNSUPPORTED;
}
/* ---- activation buffers. A rotated trunk's producers write had_quant_act_i8g's codes and
* its linears declare no quantiser: the norms (rmsnorm_had_quant_i8g and, at two ranks, its
* all-reduce form) where a loaded library serves them, the attention output (q_attn), and the
* gated products (gated_had_quant_i8g). Where the norms are not served, each linear
* quantises `h` itself and the experts read `hr`, written once a layer. Any other trunk keeps
* both code pairs on `h`: E4M3 for four-bit experts, int8 for a plain int8 linear's own
* quantiser. */
const bool rot = m.trunk_rot;
const int64_t g8 = m.trunk_g8;
const bool h_fed = rot && rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g"));
m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, g.n_embd});
m.h.x = decl_b(b, nm.f("h"), RAD_BF16, {T, g.n_embd});
RAD_ARCH_TRY(m.h.declare_qs(b, nm, g, "h", g.n_embd, 0, true, !h_fed,
rot ? g8 : (int64_t)RAD_FP8_BLOCK));
m.h.q8_fed = m.h.q8_rot = h_fed;
if (rot && !h_fed) {
RAD_ARCH_TRY(m.hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false,
RAD_FP8_BLOCK));
m.hr.q8_fed = m.hr.q8_rot = true;
}
m.q = decl_b(b, nm.f("attn_q"), RAD_BF16, {T, qd});
m.k = decl_b(b, nm.f("attn_k"), RAD_BF16, {T, kvd});
m.v = decl_b(b, nm.f("attn_v"), RAD_BF16, {T, kvd});
m.attn.x = decl_b(b, nm.f("attn_out"), RAD_BF16, {T, qd});
RAD_ARCH_TRY(m.attn.declare_qs(b, nm, g, "attn_out", qd, 0, true, false,
rot ? g8 : (int64_t)RAD_FP8_BLOCK));
m.attn.q8_fed = m.attn.q8_rot = rot;
m.dense_gate_up = decl_b(b, nm.f("dense_gate_up"), RAD_BF16, {T, 2 * g.n_ff});
m.dense_ffn.x = decl_b(b, nm.f("dense_ffn"), RAD_BF16, {T, g.n_ff});
if (rot)
RAD_ARCH_TRY(m.dense_ffn.declare_pair(b, nm, g, "dense_ffn", g.n_ff, 0, true, g8,
"gated_had_quant_i8g"));
else
RAD_ARCH_TRY(m.dense_ffn.declare_qs(b, nm, g, "dense_ffn", g.n_ff, 0, true));
m.h_out = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
const int64_t R = T, S = mc.rows * top_k;
m.mw.x = m.x;
m.mw.h = m.h;
m.mw.hr = m.hr;
m.mw.logits = decl_b(b, nm.f("moe_logits"), RAD_F32, {R, n_expert_all});
m.mw.ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, top_k});
m.mw.ew = decl_b(b, nm.f("moe_weights"), RAD_F32, {R, top_k});
m.mw.eoff = decl_b(b, nm.f("moe_offsets"), RAD_I32, {n_expert_local + 1});
m.mw.ecnt = decl_b(b, nm.f("moe_counts"), RAD_I32, {n_expert_local}, RAD_BUF_PERSIST);
m.mw.sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {S});
m.mw.egu = decl_b(b, nm.f("moe_gate_up"), RAD_BF16, {S, 2 * mc.n_ff_exp});
m.mw.eff.x = decl_b(b, nm.f("moe_ffn"), RAD_BF16, {S, mc.n_ff_exp});
if (rot) {
/* The routed arm of a rotated trunk is int8 throughout: the gated product's rotated codes
* at one scale a 128 of K, which the grouped GEMM's int8 rows read (MoeFP8::a8). */
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, true, false,
RAD_FP8_BLOCK));
m.mw.eff.q8_fed = m.mw.eff.q8_rot = true;
} else {
RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, true));
}
m.mw.edn = decl_b(b, nm.f("moe_down"), RAD_BF16, {S, g.n_embd});
m.mw.sgu = decl_b(b, nm.f("shared_gate_up"), RAD_BF16, {T, 2 * mc.n_ff_shared});
m.mw.sff.x = decl_b(b, nm.f("shared_ffn"), RAD_BF16, {T, mc.n_ff_shared});
if (rot) {
/* The shared expert's down projection is a trunk linear whose input codes take the group
* its own weight is stored at, read from the first routed layer's through that layer's
* own LinearFP8 (which then maps it once). */
LinearFP8& sd = m.layers[(size_t)l_moe].moe.sh_down;
RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.%lld.ffn_down_shexp", (long long)l_moe),
{ nm.ckpt("model.layers.%lld.mlp.shared_expert.down_proj.weight",
(long long)l_moe) }));
const int64_t sg = sd.probed_i8 ? sd.probed_g8 : g8;
RAD_ARCH_TRY(m.mw.sff.declare_pair(b, nm, g, "shared_ffn", mc.n_ff_shared, 0, true, sg,
"gated_had_quant_i8g"));
} else {
RAD_ARCH_TRY(m.mw.sff.declare_qs(b, nm, g, "shared_ffn", mc.n_ff_shared, 0, true));
}
m.mw.sout = decl_b(b, nm.f("shared_out"), RAD_BF16, {T, g.n_embd});
m.mw.sgate = decl_b(b, nm.f("shared_one"), RAD_BF16, {T, 1});
if (mc.shared_one_external) {
m.shared_one = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 1),
RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)),
RAD_NOWEIGHTS), {}, {m.mw.sgate});
if (!m.shared_one) return RAD_E_INVAL;
}
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("model.embed_tokens.weight")));
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.final_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.lm_head = decl_w(b, nm.f("output.weight"),
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(m.token)),
{}, {m.x});
if (g.world > 1)
m.embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{m.x}, {m.x});
FlintAttn::Wire aw{};
aw.x = m.x; aw.h = m.h; aw.q = m.q; aw.k = m.k; aw.v = m.v; aw.attn = m.attn;
MlpFP8::Wire dw{};
dw.x = m.x; dw.h = m.h; dw.gate_up = m.dense_gate_up; dw.ffn = m.dense_ffn;
for (int64_t l = 0; l < g.n_layer; ++l) {
Layer& lay = m.layers[(size_t)l];
lay.dense = (l < 2);
lay.sliding = !is_full(l);
const char* pre = nm.ckpt("model.layers.%lld", (long long)l);
FlintAttn::Src as{};
as.norm = nm.ckpt("%s.input_layernorm.weight", pre);
as.q = nm.ckpt("%s.self_attn.q_proj.weight", pre);
as.k = nm.ckpt("%s.self_attn.k_proj.weight", pre);
as.v = nm.ckpt("%s.self_attn.v_proj.weight", pre);
as.q_norm = nm.ckpt("%s.self_attn.q_norm.weight", pre);
as.k_norm = nm.ckpt("%s.self_attn.k_norm.weight", pre);
as.o = nm.ckpt("%s.self_attn.o_proj.weight", pre);
as.sink = nm.ckpt("%s.self_attn.softmax_offset", pre);
as.use_rope = lay.sliding;
as.window = lay.sliding ? sliding : 0;
const rad_kvgroup grp = lay.sliding ? m.kv_win : m.kv_full;
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, grp));
/* Every block after the first folds the previous block's delta and, at two ranks,
* absorbs its all-reduce into its own norm; the last block keeps its add for the plain
* final norm and issues its own collective. */
const LayerFold f = layer_fold(g, l, g.n_layer, nullptr, 0, false);
status = lay.attn.declare(b, nm, g, (int)l, grp, aw, as, f.mix_fold, false, f.mix_ar_in,
f.mix_ar_out);
if (status < 0) {
fprintf(stderr, "radiance: flint: attention layer %lld declaration failed (%d)\n",
(long long)l, status);
return status;
}
if (lay.dense) {
MlpFP8::Src ds{};
const char* mlp = nm.ckpt("%s.mlp", pre);
ds.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
ds.gate = nm.ckpt("%s.gate_proj.weight", mlp);
ds.up = nm.ckpt("%s.up_proj.weight", mlp);
ds.down = nm.ckpt("%s.down_proj.weight", mlp);
status = lay.dense_mlp.declare(b, nm, g, (int)l, dw, ds, true, f.mlp_add,
f.mlp_ar_in, f.mlp_ar_out);
if (status < 0) {
fprintf(stderr, "radiance: flint: dense layer %lld declaration failed (%d)\n",
(long long)l, status);
return status;
}
} else {
MoeFP8::Src ms{};
ms.cfg = mc;
const char* mlp = nm.ckpt("%s.mlp", pre);
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
ms.router = nm.ckpt("%s.gate.weight", mlp);
/* Flint has no router correction bias. The sigmoid router's bias is
* selection-only, so the converter merges a zero [n_expert] tensor under this
* name (data/flint-zero-bias.safetensors, `rad-convert --add`). */
ms.router_bias = nm.ckpt("%s.expert_bias", mlp);
ms.experts = nm.ckpt("%s.experts", mlp);
ms.shared = nm.ckpt("%s.shared_expert", mlp);
status = lay.moe.declare(b, nm, g, (int)l, m.mw, ms, true, f.mlp_add, f.mlp_ar_in,
f.mlp_ar_out);
if (status < 0) {
fprintf(stderr, "radiance: flint: MoE layer %lld declaration failed (%d)\n",
(long long)l, status);
return status;
}
}
}
m.final_rms = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.final_norm)),
{m.x}, {m.h.x});
m.gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.h.x}, {m.h_out});
m.logits_op = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.lm_head)),
{m.h_out}, {m.logits});
rad_note(b, "Flint: %lld layers (2 dense, 47 top-%lld/%lld sigmoid MoE), %lld/%lld "
"attention/KV heads x %lld; expert width %lld, shared %lld, window %lld on %s; "
"per-head sink on every layer; %s trunk, %s KV cache",
(long long)g.n_layer, (long long)top_k, (long long)n_expert_all,
(long long)g.n_head_all, (long long)g.n_head_kv_all, (long long)g.head_dim,
(long long)m.n_ff_expert, (long long)mc.n_ff_shared, (long long)sliding,
g.world == 2 ? "both cards" : "one card",
rot ? (g8 == RAD_I8_GROUP_WIDE ? "IQ8R (rotated int8)" : "rotated int8") : "unrotated",
g.kv_dtype);
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = g_model[rad_slot(c)];
RAD_ISSUE(c, m.embed,
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.token),
brows(m.x, batch->n_tok));
if (m.embed_ar)
RAD_ISSUE_N(c, m.embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
brows(m.x, batch->n_tok), RAD_NONE);
if (m.shared_one)
RAD_ISSUE_N(c, m.shared_one, batch->n_tok, brows(m.mw.sgate, batch->n_tok));
for (Layer& layer : m.layers) {
layer.attn.step(c, batch);
if (layer.dense) layer.dense_mlp.step(c, batch);
else layer.moe.step(c, batch);
}
RAD_ISSUE(c, m.final_rms, brows(m.x, batch->n_tok), RAD_W(m.final_norm),
brows(m.h.x, batch->n_tok));
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.gather, batch->n_out,
brows(m.h.x, batch->n_tok), praw(batch->out_ids, RAD_I32, batch->n_out),
brows(m.h_out, batch->n_out));
RAD_ISSUE_N(c, m.logits_op, batch->n_out,
brows(m.h_out, batch->n_out), RAD_W(m.lm_head),
brows(m.logits, batch->n_out));
}
}
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
return RAD_OK;
}
} // namespace flint
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(flint)
static const char* const kFlintTriggers[] = { "<tool_call>" };
static const RadChatFormat kFlintChatFormat = {
.struct_size = sizeof(RadChatFormat),
.name = "flint",
.reasoning_open = "<think>",
.reasoning_close = "</think>",
.reasoning_breaks = kFlintTriggers,
.n_reasoning_breaks = 1,
.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT,
.section_open = nullptr,
.section_close = nullptr,
.call_separator = nullptr,
.call_open = nullptr,
.call_close = nullptr,
.name_prefix = "<tool_call>",
.name_suffix = "",
.call_end = "</tool_call>",
.arg_prefix = "<arg_key>",
.arg_name_suffix = "</arg_key>",
.arg_value_prefix = "<arg_value>",
.arg_value_suffix = "</arg_value>",
.string_value = RAD_CHAT_VALUE_RAW,
.other_value = RAD_CHAT_VALUE_JSON,
.value_newlines = 1,
.triggers = kFlintTriggers,
.n_triggers = 1,
.args_form = RAD_CHAT_ARGS_TAGGED,
};
extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
return &kFlintChatFormat;
}
extern "C" const char* rad_arch_id(void) { return "flint"; }
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
extern "C" const char* rad_arch_quant(void) { return ""; }
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
return flint::declare(b, m, c);
}
extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
flint::step(c, batch);
}
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
RAD_PLUGIN_ABI_LAYOUT_EXPORT
extern "C" const RadPluginInfo* rad_plugin_info(void) {
static const RadPluginInfo info = {
RAD_PLUGIN_ARCH, "flint", "0.1.0",
"Recursive Flint: 2 dense + 47 sigmoid MoE layers, sink attention, 513 window", ""
};
return &info;
}
#endif
+272
View File
@@ -0,0 +1,272 @@
/* flint_attention.h -- Flint's grouped-query attention: per-head Q/K RMSNorm, optional NeoX
* RoPE (sliding layers) or no positional encoding (full layers), a learned per-head softmax
* sink, a paged bf16 or int8 KV cache, and an optional sliding window.
*
* Derived from arch/hyv3_common/hyv3_attention.h (the same linears and activation plumbing); the
* differences are Flint's:
*
* - every layer has `self_attn.softmax_offset` (GGUF `attn_sinks`), one learned logit a query
* head added to the scaled scores before the softmax;
* - the full-attention layers are NoPE, the sliding layers carry NeoX RoPE;
* - the sliding layers bound the paged attention with `window` (513).
*
* The sink and the window ride in attn_paged_sink, which libr4d serves at h128/gqa8 on both
* caches. The block's closing all-reduce may be taken by the next block's norm (ar_out).
*/
#ifndef FLINT_ATTENTION_H
#define FLINT_ATTENTION_H
#include <arch/rad_fp8.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
namespace rad {
namespace arch {
struct FlintAttn {
struct Wire {
rad_buf x = 0; /* [max_tok, n_embd] residual stream */
ActFP8 h{}; /* [max_tok, n_embd] normed input, then o output */
rad_buf q = 0; /* [max_tok, q_dim], projected, normed and rotated */
rad_buf k = 0; /* [max_tok, kv_dim] */
rad_buf v = 0; /* [max_tok, kv_dim] */
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
};
struct Src {
const char* norm = nullptr;
const char* q = nullptr;
const char* k = nullptr;
const char* v = nullptr;
const char* q_norm = nullptr;
const char* k_norm = nullptr;
const char* o = nullptr;
/* `self_attn.softmax_offset` (no `.weight` suffix). Null declares no sink. */
const char* sink = nullptr;
bool use_rope = true;
int64_t window = 0; /* 0: full attention */
};
Geom g{};
Wire w{};
int layer = 0;
rad_kvgroup kv = 0;
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0, w_sink = 0;
LinearFP8 q{}, k{}, v{}, o{};
NormQuantFP8 nq_h{};
QuantFP8 q_attn{};
rad_op op_q_norm = 0, op_k_norm = 0;
rad_op op_rope_q = 0, op_rope_k = 0, op_attn = 0, op_kv_store = 0;
rad_op op_qkr_store = 0; /* Q/K norms, NeoX rotary (or none) and cache store, decode band */
int64_t qkr_rows = 0;
rad_op op_ar = 0, op_add = 0;
/* The next block's norm absorbs this block's closing all-reduce (NormQuantFP8::fuse_ar), so
* this one must not issue it. Counterpart of `ar_in`; both sides ask ar_taken(g, T, ...) on
* the same facts, so they agree. */
bool ar_out = false;
int ar_out_take = kArOutNorm;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int FlintAttn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
rad_kvgroup group, const Wire& wire, const Src& src,
bool fold, bool add_out, int ar_in, bool ar_out_) {
g = geom;
w = wire;
layer = l;
kv = group;
ar_out = ar_out_;
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
if (g.world > g.n_head_kv_all) {
fprintf(stderr, "radiance: flint declares no KV row span and cannot serve world_size = %d "
"with n_head_kv = %lld\n", g.world, (long long)g.n_head_kv_all);
return RAD_E_UNSUPPORTED;
}
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
if (!w_norm || !w_q_norm || !w_k_norm) return RAD_E_INVAL;
/* The learned softmax offset, one f32 a query head, sharded with the heads. */
if (src.sink) {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_sinks", l), src.sink));
w_sink = decl_w(b, nm.f("blk.%d.attn_sinks", l), RAD_F32, {g.n_head},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
if (!w_sink) return RAD_E_INVAL;
}
// As in the other pre-norm blocks, absorb a preceding delta into the residual stream.
// The fused kernel normalizes the BF16-rounded sum, not an unrounded FP32 substitute.
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
fold ? w.x : 0, 0, ar_in));
RAD_ARCH_TRY(q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), q_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), {src.q}, w.h, w.q));
RAD_ARCH_TRY(k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), {src.k}, w.h, w.k));
RAD_ARCH_TRY(v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), {src.v}, w.h, w.v));
auto head_norm = [&](int64_t heads, rad_weight wt) {
return RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(wt));
};
op_q_norm = rw(b, head_norm(g.n_head, w_q_norm), {w.q}, {w.q});
op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k});
if (src.use_rope) {
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"),
{w.q}, {w.q});
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
"neox"),
{w.k}, {w.k});
}
const rad_op attn = w_sink
? rw(b, RAD_OP(b, "attn_paged_sink",
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", src.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_WEIGHTS(w_sink)),
{w.q}, {w.attn.x})
: 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", src.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.x});
op_attn = 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}, {});
/* The fused prologue serves the rope layers and, with `rotary_dim` 0, the NoPE ones: the
* kernel then only copies the normed head through the rotary stage. Rows exist for the bf16
* and the int8 cache (qkv_norm_rope_kv_store_h128_bf16, _i8); prefill heights and libraries
* without the fold take the standalone norms, ropes and kv_store. */
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
(!std::strcmp(g.kv_dtype, "bf16") || !std::strcmp(g.kv_dtype, "i8")) &&
!g.rope_mc && g.yarn.factor == 0.0f &&
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
qkr_rows = qk_fuse_rows(g);
op_qkr_store = RAD_OP(b, "qkv_norm_rope_kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, qkr_rows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps),
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
RAD_INT("v_norm", 0),
RAD_INT("rotary_dim", src.use_rope ? g.head_dim : 0),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_WEIGHTS(w_q_norm, w_k_norm));
if (!op_qkr_store || !rad_op_resolved(b, op_qkr_store)) op_qkr_store = 0;
if (op_qkr_store)
op_qkr_store = rw(b, op_qkr_store, {w.q, w.k, w.v}, {w.q, w.k, w.v});
}
/* The out projection's input codes: where the model feeds them (a rotated int8 trunk,
* ActFP8::q8_fed), q_attn writes had_quant_act_i8g's pair and the projection declares no
* quantiser. Otherwise every form the out projection can take reads the bf16 plane or
* quantises it itself (LinearFP8 refuses the E4M3-pair formats), so no quantiser runs here. */
if (w.attn.q8_fed) RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
RAD_SHARD_COL, grp_layer(l), {src.o}, w.attn, w.h.x));
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{w.h.x}, {w.h.x});
if (add_out) op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h.x}, {w.x});
/* A rope layer needs either the fused prologue or both standalone rope ops; without this,
* step() would silently skip the rotation. */
const bool rope_ok = !src.use_rope || op_qkr_store || (op_rope_q && op_rope_k);
return op_attn && op_kv_store && rope_ok && (!add_out || op_add) &&
(op_qkr_store || (op_q_norm && op_k_norm))
? RAD_OK : RAD_E_INVAL;
}
inline void FlintAttn::step(RadCtx* c, const RadBatch* batch) const {
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
const int64_t T = batch->n_tok;
nq_h.step(c, T);
q.step(c, w.h, w.q, T);
k.step(c, w.h, w.k, T);
v.step(c, w.h, w.v, T);
if (op_qkr_store && T <= qkr_rows) {
RAD_ISSUE_N(c, op_qkr_store, T, brows(w.q, T), brows(w.k, T), brows(w.v, T),
rope_posmc(g, batch, T), RAD_W(w_q_norm), RAD_W(w_k_norm),
praw(slot, RAD_I32, T), kv_cache(kv, layer));
} else {
RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T));
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
if (op_rope_q) {
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));
}
if (w_sink)
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),
RAD_W(w_sink), brows(w.attn.x, T));
else
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn.x, T));
q_attn.step(c, T);
o.step(c, w.attn, w.h.x, T);
if (issues_ar(T)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
}
} // namespace arch
} // namespace rad
#endif /* FLINT_ATTENTION_H */
+54 -20
View File
@@ -39,7 +39,11 @@
*
* Every linear of the language model and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16
* throughout when the first joint block's projection is plain; the embedders, the timestep MLPs,
* the modulations, the output layer and the VAE stay bf16.
* the modulations, the output layer and the VAE stay bf16. That projection also says whether the
* linears are rotated int8 (IQ8R): the activations they read then carry int8 codes in place of the
* E4M3 pair, which a block's modulated norm writes in its own pass where a library serves the
* rotating twin (rms_mod_had_quant_i8g) and the rotating quantiser behind the plain norm
* elsewhere.
*
* ============================== TENSOR PARALLEL ==============================
*
@@ -113,6 +117,9 @@ struct Block {
LinearFP8 qkv{}, o{}, ff_in{}, ff_out{};
GateQuantFP8 gq{};
QuantFP8 q_attn{};
/* The normed rows' quantiser for a rotated int8 model whose norm is the unquantised one
* (Model::norm_i8 false). */
QuantFP8 q_n{};
rad_op op_n = 0, op_qkr = 0, op_attn = 0, op_sum = 0, op_ar = 0;
};
@@ -172,6 +179,14 @@ struct Model {
ActFP8 a_hm{}, a_attn{}, a_ffn{};
std::vector<Block> mode[3], single;
LinearFP8 qkv0{};
/* The linears of both networks are rotated int8 (IQ8R, or the 128-group int8 before it), read
* off qkv0's probe: the activations then carry int8 code pairs with one scale per (token, `g8`
* columns) in place of the E4M3 pair. */
bool i8 = false;
int64_t g8 = RAD_FP8_BLOCK;
/* A block's modulated norm writes those int8 codes in its own pass (rms_mod_had_quant_i8g),
* where a library serves it. */
bool norm_i8 = false;
rad_weight w_pout = 0;
/* ---- per-image state and conditioning store (PERSIST) */
@@ -184,7 +199,7 @@ struct Model {
rad_buf b_dl = 0, b_decin = 0, b_cu4 = 0, b_img = 0;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
std::vector<double> v;
@@ -276,14 +291,16 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, E });
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, E });
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", E, T));
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", E, T, m.i8, m.g8, "had_quant_act_i8g"));
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T));
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, T, m.i8, m.g8,
"had_quant_act_i8g"));
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, E });
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T));
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, T, m.i8, m.g8,
"gated_had_quant_i8g"));
m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { T, kNTaps * E });
m.b_tidx = decl_b(b, nm.f("te.rows"), RAD_I32, { T });
@@ -530,11 +547,16 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), RAD_F32,
{ hd }, RAD_ACCESS_PER_TOKEN, grp);
if (!B.w_qn || !B.w_kn) return RAD_E_INVAL;
const bool q = !g.w_bf16;
/* The norm with the quantiser in it: E4M3 for block-fp8 linears, the rotating int8 twin for
* rotated int8 ones where a library serves it. bf16 linears read its bf16 rows, and rotated
* int8 ones without the twin quantise those with the rotating quantiser (q_n). */
m.norm_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "rms_mod_had_quant_i8g") != 0;
const bool q = (!g.w_bf16 && !m.i8) || m.norm_i8;
auto norm = [&](bool gt) {
rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8",
rad_op op = q ? RAD_OP(b, m.norm_i8 ? "rms_mod_had_quant_i8g" : "rms_mod_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", D),
RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK),
RAD_F64("eps", eps),
RAD_INT("group", m.norm_i8 ? m.g8 : RAD_FP8_BLOCK),
RAD_INT("gated", gt ? 1 : 0), RAD_STR("dtype", "bf16"),
RAD_STR("norm", "layer")),
RAD_NOWEIGHTS)
@@ -546,7 +568,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
if (!op) return op;
/* The residual, the modulation table and, gated, the branch sum. */
rad_buf rd[4] = { m.b_xc, m.b_h, mod, m.b_sum };
rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h };
rad_buf wq[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h };
rad_buf wb[2] = { m.a_hm.x, m.b_h };
rad_op_reads(b, op, rd, gt ? 4 : 3);
if (q) rad_op_writes(b, op, wq, 3);
@@ -554,6 +576,7 @@ static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, con
return op;
};
B.op_n = norm(gated);
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n.declare(b, g, m.a_hm, D));
RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW,
grp_layer(grp),
{ nm.ckpt("%s.attn.to_q.weight", pre),
@@ -728,14 +751,16 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
/* ---- the blocks' buffers */
const int64_t qd = g.q_dim();
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
RAD_ARCH_TRY(m.a_hm.declare_pair(b, nm, g, "dit.hm", D, 0, m.i8, m.g8, "had_quant_act_i8g"));
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd });
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
RAD_ARCH_TRY(m.a_attn.declare_pair(b, nm, g, "dit.attn", qd, 0, m.i8, m.g8,
"had_quant_act_i8g"));
m.b_o = decl_b(b, nm.f("dit.o"), RAD_BF16, { T, D });
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
RAD_ARCH_TRY(m.a_ffn.declare_pair(b, nm, g, "dit.ffn", g.n_ff, 0, m.i8, m.g8,
"gated_had_quant_i8g"));
m.b_f = decl_b(b, nm.f("dit.f"), RAD_BF16, { T, D });
m.b_sum = decl_b(b, nm.f("dit.sum"), RAD_BF16, { T, D });
@@ -895,8 +920,9 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
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];
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(check_format(meta));
@@ -941,9 +967,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
"transformer.single_transformer_blocks.0.attn.to_k.weight",
"transformer.single_transformer_blocks.0.attn.to_v.weight" }));
RadEncoding e{};
const bool plain = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e) &&
rad_enc_is(&e, "plain");
const bool known = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e);
const bool plain = known && rad_enc_is(&e, "plain");
gd.w_bf16 = m.gt.w_bf16 = plain;
/* Or rotated int8 (IQ8R): the activations then carry int8 codes at the weights' scale
* group in place of the E4M3 pair (ActFP8::declare_pair). */
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
if (m.i8) m.g8 = linear_w8h_group(e);
}
const int64_t lane_rows = m.lanes * m.max_img;
@@ -1030,7 +1060,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
"+ %zu joint blocks (%lld heads a rank, ff %lld), %s linears",
m.gt.rank, m.gt.world, m.flow_map ? " (flow map)" : " base", kTaps[kNTaps - 1],
(long long)m.gt.n_layer, m.mode[0].size(), m.single.size(), (long long)gd.n_head,
(long long)gd.n_ff, gd.w_bf16 ? "bf16" : "block-fp8");
(long long)gd.n_ff, gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8");
return RAD_OK;
}
@@ -1125,17 +1155,19 @@ static void step_blocks(RadCtx* c, const Model& m, const std::vector<Block>& sta
const RadOperand& s, const RadOperand& gt, const RadOperand& pos) {
const Geom& g = m.gd;
const int64_t D = g.n_embd, qd = g.q_dim(), nD = D / RAD_FP8_BLOCK;
const bool q8 = !g.w_bf16;
const bool q8 = (!g.w_bf16 && !m.i8) || m.norm_i8;
const RadOperand xv = brow_slice(x, r0, R, D);
for (size_t i = 0; i < stack.size(); ++i) {
const Block& B = stack[i];
const bool gated = i > 0;
if (q8)
RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE,
s, RAD_NONE, mcu, xv, brows(m.a_hm.q, R), brows(m.a_hm.s, R), RAD_NONE);
s, RAD_NONE, mcu, xv, brows(m.a_hm.cq(), R), brows(m.a_hm.cs(), R),
RAD_NONE);
else
RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE,
s, RAD_NONE, mcu, xv, brows(m.a_hm.x, R));
B.q_n.step(c, R);
B.qkv.step(c, m.a_hm, m.b_qkv, R);
RAD_ISSUE_N(c, B.op_qkr, R, brows(m.b_qkv, R), pos, RAD_W(B.w_qn), RAD_W(B.w_kn));
RAD_ISSUE_N(c, B.op_attn, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R),
@@ -1254,7 +1286,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
if (!batch->gen || !batch->gen_b) {
rad_step_fail(c, "flux3 is an image generator and runs generator passes only");
return;
@@ -1283,6 +1315,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
/* One more level of expansion so `#NS` sees the expanded namespace. */
#define FLUX3_PROBE_X(NS) RAD_ARCH_PROBE(NS)
#define FLUX3_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
FLUX3_PROBE_X(FLUX3_NS)
FLUX3_PLUGIN_X(FLUX3_NS, FLUX3_ID, "", "0.1.0",
"FLUX.3 [klein] and its base: Qwen3-VL-4B's stacked layers, a 5.6B three-mode "
+30 -15
View File
@@ -85,7 +85,8 @@ struct ClassGeom {
* - `mx`: OCP-MXFP4 (e2m1 codes, an E8M0 exponent per [1 x 32]), gemm_nt_q at mxfp4a8 over
* quant_act_fp8's E4M3 codes, an f32 scale per (row, 128); the exponent plane is passed twice,
* as b_scale and as b_ref (arch/common/rad_fp8.h LinearFP8 says why).
* Neither has a fused norm/quantiser here, so the junctions stay off for them. */
* The i8g grid takes the `_i8g` twins of the fused junction and of the GELU quantiser, as
* gemma4_bf16's does; MXFP4 has its own junction (G3JunctionFP8). */
struct G3Linear {
rad_weight w = 0, ws = 0, wref = 0;
rad_op op = 0, op_q = 0;
@@ -192,6 +193,7 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
i8g = known && linear_is_w8(enc);
mx = known && linear_is_mxfp4(enc);
if (mx) return linear_refuse_retired(wn, "MXFP4");
/* Asymmetric int4 (libquant `codes=u4 zero=u8 group=128 scale=f16`), unrotated: gemm_nt_q at
* w4a8i8_asym over the same per-(row, 128) int8 activation as i8g. LinearFP8 serves this grid
* only under ParoQuant's rotation, which a tensor-parallel shard cannot cut; unrotated it shards
@@ -698,8 +700,9 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
RAD_NOWEIGHTS),
{w.gu}, {w.ffn});
// Not under calibration: the tap reads the bf16 activation this fusion never writes.
if (ln_down.quant && !ln_down.shared_in && !calib_dir() && rad_op_declared(b, "gelu_mul_quant_i8"))
op_gq = rw(b, RAD_OP(b, "gelu_mul_quant_i8",
const char* gq = ln_down.quant ? "gelu_mul_quant_i8" : ln_down.i8g ? "gelu_mul_quant_i8g" : nullptr;
if (gq && !ln_down.shared_in && !calib_dir() && rad_op_declared(b, gq))
op_gq = rw(b, RAD_OP(b, gq,
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gu}, {ln_down.q8, ln_down.s8});
@@ -782,7 +785,8 @@ void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
}
/* ---- one residual junction as one op (libr4d `rmsnorm_quant_i8`): [post-norm of the branch,
/* ---- one residual junction as one op (libr4d `rmsnorm_quant_i8`, on quant_act_i8g's grid
* `rmsnorm_quant_i8g`): [post-norm of the branch,
* the add into the stream,] the next block's norm and its int8 quantiser. gemma4_bf16's
* G4Junction without the layer scalar. */
struct G3Junction {
@@ -794,25 +798,27 @@ struct G3Junction {
int declare(RadBuilder* b, const Geom& g, rad_buf x_, rad_buf res_, rad_weight w_,
rad_weight wp_, const G3Linear& into) {
x = x_; res = res_; w = w_; wp = wp_; q8 = into.q8; s8 = into.s8;
if (!into.quant || into.shared_in || !q8 || !s8 || !w || (wp && !res))
if (!(into.quant || into.i8g) || into.shared_in || !q8 || !s8 || !w || (wp && !res))
return RAD_E_INVAL;
const char* rq = into.i8g ? "rmsnorm_quant_i8g" : "rmsnorm_quant_i8";
const char* arq = into.i8g ? "ar_rmsnorm_quant_i8g" : "ar_rmsnorm_quant_i8";
const RadParam p[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
RAD_F64("wadd", g.wadd) };
const rad_weight ws[2] = { w, wp };
const int nw = wp ? 2 : 1;
if (rad_op_declared(b, "rmsnorm_quant_i8"))
op = rad_decl_op(b, "rmsnorm_quant_i8", p, (int)(sizeof p / sizeof p[0]), ws, nw);
if (rad_op_declared(b, rq))
op = rad_decl_op(b, rq, p, (int)(sizeof p / sizeof p[0]), ws, nw);
if (!op) return RAD_OK;
const rad_buf rd[2] = { x, res };
const rad_buf wr[3] = { q8, s8, res };
rad_op_reads (b, op, rd, res ? 2 : 1);
rad_op_writes(b, op, wr, res ? 3 : 2);
if (res && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
if (res && g.world == 2 && rad_op_declared(b, arq)) {
const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) };
op_ar = rad_decl_op(b, "ar_rmsnorm_quant_i8", pa, (int)(sizeof pa / sizeof pa[0]), ws, nw);
op_ar = rad_decl_op(b, arq, pa, (int)(sizeof pa / sizeof pa[0]), ws, nw);
if (op_ar) {
const rad_buf wa[4] = { x, q8, s8, res };
rad_op_reads (b, op_ar, rd, 2);
@@ -1002,7 +1008,7 @@ struct Model {
bool pipe_serial_noted = false;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
* to 64 rows (qwen35_fp8 says why). */
@@ -1149,9 +1155,10 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
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;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
m = Model{};
m.nm = Names(ctx->scope);
@@ -1322,8 +1329,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
if (g.n_layer > 0 && !calib_dir()) {
bool ok = true;
for (const Layer& lay : m.layers)
ok = ok && lay.attn.ln_q.quant && lay.attn.ln_k.shared_in && lay.attn.ln_v.shared_in &&
lay.mlp.ln_gu.quant;
ok = ok && (lay.attn.ln_q.quant || lay.attn.ln_q.i8g) && lay.attn.ln_k.shared_in &&
lay.attn.ln_v.shared_in && (lay.mlp.ln_gu.quant || lay.mlp.ln_gu.i8g);
if (ok) {
RAD_ARCH_TRY(m.j0.declare(b, g, m.b_x, 0, m.layers[0].attn.w_norm, 0, m.layers[0].attn.ln_q));
ok = m.j0.op != 0;
@@ -1665,7 +1672,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = g_model[rad_rank(c)];
Model& m = g_model[rad_slot(c)];
if (batch->enc) {
rad_step_fail(c, "gemma3 serves text only");
return;
@@ -1800,11 +1807,19 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
out->draft_depth = bs > 1 ? (int)(bs - 1) : 7;
out->draft_depth_fixed = 1; /* as qwen35_fp8: the trained block */
}
/* Chained launches pay with a drafter and without one: the decode kernels of the int8 trunk
* have chained forms (libr4d's rad_kernel_chain), and the weight reads beside the reductions
* then stay on lane 0 instead of a second queue. TranslateGemma 27B int8 on two R9700, ms a
* decode step unchained / chained: 31.9 / 24.1 at one sequence, 32.2 / 24.8 at four (with
* the junctions unfused, 40.9 / 26.4 and 41.2 / 27.0). */
out->chain_pays = RAD_CHAIN_ALWAYS;
return RAD_OK;
}
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(gemma3)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(gemma3, "gemma3", "", "0.1.0",
"Gemma 3 dense text trunk (TranslateGemma), bf16 or w4a8 at convert: sliding-window "
"and linearly-scaled global attention over a (1 + w) RMSNorm stream with GELU "
+172 -91
View File
@@ -1,6 +1,6 @@
/* gemma4 -- Gemma 4 text decoders (26B-A4B MoE, and the dense members of the family): a bf16
* trunk, routed experts bf16 or block fp8 (see FP8 EXPERTS), and the DFlash block-diffusion
* drafter.
* trunk, routed experts bf16, block fp8 or rotated int8 (see FP8 EXPERTS), and the DFlash
* block-diffusion drafter.
*
* ============================== THE SHAPE (gemma-4-26B-A4B-it) ==============================
*
@@ -77,7 +77,17 @@
* blocks, which 704 is not. It stays bf16 -- unless the checkpoint is padded to 768
* first, outside the engine: zero rows of gate and up give gelu(0) * 0 = 0 in the
* padded columns, which meet zero columns of down, so the function is unchanged, and
* then both projections are fp8 (data/recipes/gemma4-26b-a4b-df-pad768.recipe).
* then both projections are fp8.
*
* Rotated int8 experts (`rtn codes=i8 group=128 scale=bf16 transform=fwht128`) take the same
* tables and the same widths through `moe_gemm_q` at i8a8h, over int8 codes of the experts' input
* that the attention join's fused route writes (`norm_add_norm_route_i8g`), or the rotating norm
* (`rmsnorm_had_quant_i8g`) where that is not served. A model's quantised experts are all one or
* all the other.
*
* The cache is bf16 or int8 with an f16 scale of K and of V per token and head
* (--kv-cache-dtype i8, libr4d's windowed kernels' int8 rows and kv_store_i8), the drafter's
* with it.
*
* ============================== NOT DECLARED ==============================
*
@@ -157,7 +167,9 @@ struct Layer {
* w_egus/w_edns, so each parity is one run (see declare). */
rad_weight w_rscale = 0, w_router = 0, w_escale = 0, w_enorm = 0, w_fpost2 = 0;
std::vector<rad_weight> w_egu, w_edn, w_egus, w_edns;
bool gu_fp8 = false, dn_fp8 = false;
/* A projection's experts are quantised (block fp8 or rotated int8: the table GEMM over a code
* pair), else plain bf16. */
bool gu_q = false, dn_q = false;
rad_op op_rnorm = 0, op_router = 0, op_topk = 0, op_escale = 0, op_emul = 0, op_enorm = 0;
rad_op op_scatter = 0, op_egu = 0, op_eact = 0, op_eq = 0, op_edn = 0, op_gather = 0;
/* libr4d's fused forms of the router, its top-k and the sort, where they resolve: the pair
@@ -177,8 +189,9 @@ struct Layer {
* then declared and issued instead. */
rad_op op_join_a = 0, op_join_f = 0;
/* op_join_r: op_join_a writing the routed arm's two inputs as well -- the router's norm into
* b_rn and the experts' fp8 codes into b_hq / b_hqs (norm_add_norm_route) -- where the
* layer's gate_up is block fp8. op_rnorm and op_enorm are then declared and not issued. */
* b_rn and the experts' codes into b_hq / b_hqs (norm_add_norm_route's E4M3, or
* norm_add_norm_route_i8g's rotated int8) -- where the layer's gate_up is quantised. op_rnorm
* and op_enorm are then declared and not issued. */
rad_op op_join_r = 0;
/* op_join_f also writes the next norm (the following layer's input norm, or the final norm
* after the last layer) into `h`, with that norm's gain `w_next`; the replaced norm is then
@@ -220,7 +233,10 @@ struct Model {
/* the experts' E4M3 inputs, declared only where some layer's projection is fp8: gate_up's
* (the normed block input, a row a token) and down's (the gated product, a row a slot) */
rad_buf b_hq = 0, b_hqs = 0, b_eq = 0, b_eqs = 0;
int n_gu_fp8 = 0, n_dn_fp8 = 0; /* layers whose projection is fp8 */
int n_gu_q = 0, n_dn_q = 0; /* layers whose projection is quantised */
/* The quantised experts are rotated int8 against int8 activations (EXP_I8), every layer's:
* the code pairs are one buffer each for the whole model. */
bool exp_i8 = false, exp_seen = false;
rad_buf b_hout = 0, b_logits = 0;
rad_weight w_tok = 0, w_onorm = 0;
@@ -245,7 +261,7 @@ struct Model {
std::vector<Layer> layers;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* ============================================================== geometry */
@@ -331,7 +347,7 @@ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuil
* plan, rad_weight_encoding), which picks the GEMM: plain bf16 is `moe_gemm`, block fp8 (fp8_e4m3
* codes, a bf16 scale per 128x128 block) is `moe_gemm_q` at fp8a8. Anything else is refused by
* name. A builder with no model behind it answers nothing, and the declared dtype bf16 is read. */
enum { EXP_BF16 = 0, EXP_FP8 = 1 };
enum { EXP_BF16 = 0, EXP_FP8 = 1, EXP_I8 = 2 };
static int expert_format(RadBuilder* b, const char* wn, int* fmt) {
RadEncoding e{};
*fmt = EXP_BF16;
@@ -341,11 +357,22 @@ static int expert_format(RadBuilder* b, const char* wn, int* fmt) {
*fmt = EXP_FP8;
return RAD_OK;
}
/* Rotated int8: codes with a bf16 scale per (row, 128 of K), each 128 of K rotated by the
* Hadamard (libquant's `codes=i8 group=128 scale=bf16 transform=fwht128`). */
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
if (rad_enc_is(&e, "affine") && e.n_planes == 2 && e.plane[0].dtype == RAD_I8 && sc &&
sc->dtype == RAD_BF16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK &&
std::strcmp(e.transform, "fwht128") == 0) {
*fmt = EXP_I8;
return RAD_OK;
}
char en[256];
rad_enc_format(&e, en, sizeof en);
fprintf(stderr, "radiance: gemma4: '%s' is %s; the routed experts are served plain bf16 or "
"block fp8 (fp8_e4m3*bf16[128x128]). Convert with no rule for them, or with "
"`rtn codes=fp8_e4m3 block=128x128 scale=bf16`.\n", wn, en);
fprintf(stderr, "radiance: gemma4: '%s' is %s; the routed experts are served plain bf16, "
"block fp8 (fp8_e4m3*bf16[128x128]) or rotated int8 "
"(i8*bf16[1x128]/fwht128). Convert with no rule for them, or with `rtn "
"codes=fp8_e4m3 block=128x128 scale=bf16` or `rtn codes=i8 group=128 "
"scale=bf16 transform=fwht128 clamp=sym rule=search`.\n", wn, en);
return RAD_E_DTYPE;
}
@@ -360,11 +387,11 @@ static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base
RAD_ARCH_TRY(expert_format(b, wn, &f));
if (e == 0) { *fmt = f; continue; }
if (f != *fmt) {
static const char* const kName[3] = { "bf16", "block fp8", "rotated int8" };
fprintf(stderr, "radiance: gemma4: '%s' is %s and expert %lld of the same layer is %s; "
"one layer's %s experts take one encoding (a recipe rule for them "
"matches all of a layer's or none)\n", wn,
f == EXP_FP8 ? "block fp8" : "bf16", (long long)base,
*fmt == EXP_FP8 ? "block fp8" : "bf16", what);
"matches all of a layer's or none)\n", wn, kName[f], (long long)base,
kName[*fmt], what);
return RAD_E_DTYPE;
}
}
@@ -375,7 +402,8 @@ static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base
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;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
if (ctx->is_draft) {
fprintf(stderr, "radiance: gemma4: this plugin has no draft scope\n");
return RAD_E_UNSUPPORTED;
@@ -388,7 +416,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
Names& nm = m.nm;
@@ -541,24 +569,45 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- the KV groups, one per geometry: the sliding layers' (256-wide heads) and the full
* layers' (512).
*
* The sliding layers' group is RAD_KV_FULL, not RAD_KV_WINDOW; the window lives on the
* attention op (`window` 1024), which reads only keys inside it. A window group is not
* prefix-cached (core/mem/prefix.cpp), so a prefix hit on a model with one reuses nothing and
* re-prefills (core/sched). As FULL the group is cached with the others and the drafter's KV
* has no hole. The only loss is recycling below the window, which gains nothing here: the
* planner gives every paged group the same block count, so the full group bounds the tokens a
* card holds anyway. */
* The sliding layers' group is RAD_KV_WINDOW, sized to the attention window, which is what
* the kernel reads anyway: attn_paged takes `window` 1024 on those layers and never looks at
* a key older than it. As a window group the pool is capped at the window plus one block per
* sequence (core/mem/kv.cpp), so 25 sliding layers cost ~1k tokens of cache each instead of
* the whole context -- at 32k and fp8 KV, 0.4 GiB a sequence where FULL costs 3.5. The full
* layers' group stays RAD_KV_FULL: it is the only one whose keys outlive a window.
*
* A windowed group is not prefix-cached (core/mem/prefix.cpp): its rows below the window are
* recycled, and adopt() would overfill a table capped at window_blocks. What that costs on
* a prefix hit is only the windowed rows; the full layers' rows still come back from the
* store. The window itself resumes from the deepest retained checkpoint at or below the
* matched end — that checkpoint's slot carries the window behind it — and only the gap between
* that checkpoint and the match end is recomputed. Only where no retained checkpoint sits at
* or below the match do the windowed layers start their cache where the hit ended
* (the re-prefill case); that is the regime gemma3 runs with a DFlash drafter on the
* same core, and it declares its sliding group exactly this way.
*
* The drafter does not read the trunk's cache. DFlash keeps its own windowed draft KV (2048),
* rebuilt each context pass from the trunk's residual taps; its rows live inside that window
* like every other draft query's, and it has no stake in the trunk's windowed rows outliving
* the window. A windowed trunk group therefore costs the drafter nothing. */
{
const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16);
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
d.kind = RAD_KV_WINDOW;
d.window = m.ks.window; /* the same 1024 the attention op reads */
d.dtype = kvdt;
d.n_head_kv = m.ks.nkv;
d.head_dim = m.ks.hd;
m.ks.kv = rad_decl_kv_group(b, nm.f("kv_swa"), &d);
d.kind = RAD_KV_FULL;
d.window = 0;
d.n_head_kv = m.kf.nkv;
d.head_dim = m.kf.hd;
m.kf.kv = rad_decl_kv_group(b, nm.f("kv_full"), &d);
g.kv_dtype = rad_dtype_name(d.dtype);
g.kv_dtype = rad_dtype_name(kvdt);
}
/* Gemma4ForConditionalGeneration keeps the text model under model.language_model;
@@ -587,26 +636,40 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
int fgu = EXP_BF16, fdn = EXP_BF16;
RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "gate_up", &fgu));
RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "down", &fdn));
y.gu_fp8 = fgu == EXP_FP8;
y.dn_fp8 = fdn == EXP_FP8;
y.gu_q = fgu != EXP_BF16;
y.dn_q = fdn != EXP_BF16;
/* One quantised format for the model: the experts' code pairs are shared buffers. */
for (const int f : { fgu, fdn }) {
if (f == EXP_BF16) continue;
const bool i8 = f == EXP_I8;
if (m.exp_seen && i8 != m.exp_i8) {
fprintf(stderr, "radiance: gemma4: layer %lld's experts are %s and an earlier "
"projection's %s; a model's quantised experts are all block "
"fp8 or all rotated int8\n", ll,
i8 ? "rotated int8" : "block fp8", i8 ? "block fp8" : "rotated int8");
return RAD_E_DTYPE;
}
m.exp_seen = true;
m.exp_i8 = i8;
}
/* moe_gemm_q's geometry, refused here by name rather than as a kernel miss. It takes
* experts as two tables by parity, so a rank must hold an even count. */
if ((y.gu_fp8 || y.dn_fp8) && NL % 2) {
fprintf(stderr, "radiance: gemma4: block fp8 experts come in pairs on a rank (the "
"fp8 grouped GEMM takes them as two tables by parity); this rank "
if ((y.gu_q || y.dn_q) && NL % 2) {
fprintf(stderr, "radiance: gemma4: quantised experts come in pairs on a rank (the "
"grouped GEMM takes them as two tables by parity); this rank "
"holds %lld\n", (long long)NL);
return RAD_E_INVAL;
}
if (y.gu_fp8 && ((2 * m.n_ffe) % 64 || E % RAD_FP8_BLOCK)) {
fprintf(stderr, "radiance: gemma4: layer %lld's gate_up experts are block fp8 at "
"%lld x %lld; the fp8 grouped GEMM takes N in 64s and K in whole "
if (y.gu_q && ((2 * m.n_ffe) % 64 || E % RAD_FP8_BLOCK)) {
fprintf(stderr, "radiance: gemma4: layer %lld's gate_up experts are quantised at "
"%lld x %lld; the grouped GEMM takes N in 64s and K in whole "
"%d-column blocks\n", ll, (long long)(2 * m.n_ffe), (long long)E,
RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
if (y.dn_fp8 && (E % 64 || m.n_ffe % RAD_FP8_BLOCK)) {
fprintf(stderr, "radiance: gemma4: layer %lld's down experts are block fp8, and "
"the experts are %lld wide: the fp8 grouped GEMM reads K in whole "
if (y.dn_q && (E % 64 || m.n_ffe % RAD_FP8_BLOCK)) {
fprintf(stderr, "radiance: gemma4: layer %lld's down experts are quantised, and "
"the experts are %lld wide: the grouped GEMM reads K in whole "
"%d-column scale blocks. Keep `ffn_down_exps` bf16 (no recipe "
"rule for it), or pad the experts to a multiple of %d (zero rows "
"of gate and up, zero columns of down) and convert the padded "
@@ -614,8 +677,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
(long long)m.n_ffe, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
m.n_gu_fp8 += y.gu_fp8;
m.n_dn_fp8 += y.dn_fp8;
m.n_gu_q += y.gu_q;
m.n_dn_q += y.dn_q;
}
}
@@ -640,10 +703,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.b_ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {T, K});
m.b_ew = decl_b(b, nm.f("moe_w"), RAD_BF16, {T, K});
m.b_es = decl_b(b, nm.f("moe_es"), RAD_BF16, {T, K});
if (m.n_gu_fp8 < m.n_layer)
if (m.n_gu_q < m.n_layer)
m.b_hx = decl_b(b, nm.f("moe_h"), RAD_BF16, {T, E});
if (m.n_gu_fp8 > 0) {
m.b_hq = decl_b(b, nm.f("moe_hq"), RAD_F8E4M3, {T, E});
if (m.n_gu_q > 0) {
m.b_hq = decl_b(b, nm.f("moe_hq"), m.exp_i8 ? RAD_I8 : RAD_F8E4M3, {T, E});
m.b_hqs = decl_b(b, nm.f("moe_hqs"), RAD_F32, {T, fp8_blocks(E)});
}
m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {P * K});
@@ -651,8 +714,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32, {m.n_local});
m.b_egu = decl_b(b, nm.f("moe_egu"), RAD_BF16, {P * K, 2 * m.n_ffe});
m.b_eact = decl_b(b, nm.f("moe_eact"), RAD_BF16, {P * K, m.n_ffe});
if (m.n_dn_fp8 > 0) {
m.b_eq = decl_b(b, nm.f("moe_eq"), RAD_F8E4M3, {P * K, m.n_ffe});
if (m.n_dn_q > 0) {
m.b_eq = decl_b(b, nm.f("moe_eq"), m.exp_i8 ? RAD_I8 : RAD_F8E4M3, {P * K, m.n_ffe});
m.b_eqs = decl_b(b, nm.f("moe_eqs"), RAD_F32, {P * K, fp8_blocks(m.n_ffe)});
}
m.b_edn = decl_b(b, nm.f("moe_edn"), RAD_BF16, {P * K, E});
@@ -769,7 +832,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* (libr4d/r4d_norm_join_bf16.hip); on a card they differ from libr4d's chain only in reduction
* order. libref deliberately has no row for them, so the chain path stays tested. */
const bool has_join_a = rad_op_declared(b, "norm_add_norm") != 0;
const bool has_join_r = rad_op_declared(b, "norm_add_norm_route") != 0;
const char* const join_r = m.exp_i8 ? "norm_add_norm_route_i8g" : "norm_add_norm_route";
const bool has_join_r = rad_op_declared(b, join_r) != 0;
const bool has_join_f = rad_op_declared(b, "join_add_scale") != 0;
const bool has_escale = rad_op_declared(b, "expert_scale") != 0;
const bool has_qrow = rad_op_declared(b, "attn_paged_qrow") != 0;
@@ -924,12 +988,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl);
}
/* The attention join. On a layer whose gate_up is block fp8 it also writes the routed
/* The attention join. On a layer whose gate_up is quantised it also writes the routed
* arm's two inputs: the router's norm (rmsnorm with mult hidden^-0.5) and the experts'
* E4M3 codes (as rmsnorm_quant_fp8), saving two launches and two reads of x per layer.
* Otherwise norm_add_norm, else the chain. */
if (has_join_r && m.moe && y.gu_fp8)
y.op_join_r = rw(b, RAD_OP(b, "norm_add_norm_route",
* codes (as rmsnorm_quant_fp8, or for rotated int8 experts rmsnorm_had_quant_i8g),
* saving two launches and two reads of x per layer. Otherwise norm_add_norm, else the
* chain. */
if (has_join_r && m.moe && y.gu_q)
y.op_join_r = rw(b, RAD_OP(b, join_r,
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16"),
RAD_F64("mult", 1.0 / std::sqrt((double)E)),
@@ -972,10 +1037,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* The experts: this rank's run of whole experts (name maps and encodings were settled
* before the buffers). Each projection's handles are declared in its GEMM's table
* order, since a table is a run of consecutively declared handles: bf16 is one run in
* expert order; block fp8 is the even local experts' codes, then the odd ones', then
* the scale views in the same two runs (`moe_gemm_q` takes two tables by parity). Codes
* expert order; block fp8 or int8 is the even local experts' codes, then the odd ones',
* then the scale views in the same two runs (`moe_gemm_q` takes two tables by parity;
* an int8 expert's scale is per row, block fp8's per 128 rows). Codes
* and scale plane are two views of one stored weight and one movement unit (slot 0
* gate_up, 1 down). */
const uint32_t cdt = m.exp_i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3;
auto experts = [&](bool fp8, const char* what, int slot, int64_t rows, int64_t cols,
std::vector<rad_weight>& wc, std::vector<rad_weight>& ws) {
wc.assign((size_t)NL, 0);
@@ -1001,18 +1068,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
rad_weight& h = (pass ? ws : wc)[(size_t)(par * half + i)];
h = pass ? decl_view(b, nm.f("blk.%lld.ffn_%s_exps.%lld.scale", ll, what, ge),
wn, "scale", RAD_BF16,
{fp8_blocks(rows), fp8_blocks(cols)},
{m.exp_i8 ? rows : fp8_blocks(rows),
fp8_blocks(cols)},
RAD_ACCESS_CONDITIONAL, N,
grp_expert_slot(li, (int)e, slot))
: decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, {rows, cols},
: decl_view(b, wn, nullptr, "codes", cdt, {rows, cols},
RAD_ACCESS_CONDITIONAL, N,
grp_expert_slot(li, (int)e, slot));
if (!h) return RAD_E_INVAL;
}
return RAD_OK;
};
RAD_ARCH_TRY(experts(y.gu_fp8, "gate_up", 0, 2 * m.n_ffe, E, y.w_egu, y.w_egus));
RAD_ARCH_TRY(experts(y.dn_fp8, "down", 1, E, m.n_ffe, y.w_edn, y.w_edns));
RAD_ARCH_TRY(experts(y.gu_q, "gate_up", 0, 2 * m.n_ffe, E, y.w_egu, y.w_egus));
RAD_ARCH_TRY(experts(y.dn_q, "down", 1, E, m.n_ffe, y.w_edn, y.w_edns));
/* An fp8 projection's op takes its weights in its table operands' order: even codes,
* even scales, odd codes, odd scales. */
auto tables = [&](const std::vector<rad_weight>& wc, const std::vector<rad_weight>& ws) {
@@ -1051,11 +1119,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
{m.b_ids}, {m.b_es});
y.op_emul = binop("mul", P, K, m.b_ew, m.b_es, m.b_ew);
}
/* The experts' input, pre_feedforward_layernorm_2 of the stream. For an fp8 gate_up it
* is normed and quantised in one pass (`rmsnorm_quant_fp8`) with no bf16 copy, since
* the fp8 GEMM reads only codes and scales. */
if (y.gu_fp8) {
y.op_enorm = RAD_OP(b, "rmsnorm_quant_fp8",
/* The experts' input, pre_feedforward_layernorm_2 of the stream. For a quantised
* gate_up it is normed and quantised in one pass (`rmsnorm_quant_fp8`, or for int8
* experts the rotating `rmsnorm_had_quant_i8g`) with no bf16 copy, since the table
* GEMM reads only codes and scales. */
if (y.gu_q) {
y.op_enorm = RAD_OP(b, m.exp_i8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", E),
RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "bf16"), RAD_F64("wadd", 0.0)),
@@ -1108,13 +1177,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* The two grouped GEMMs use different a_order: gate_up reads the block input, one row
* per token, gathered through sorted_tok; down reads gate_up's product, already one row
* per (token, slot) in scatter order (rad_block_moe_fp8.h). */
if (y.gu_fp8) {
if (y.gu_q) {
const std::vector<rad_weight> tab = tables(y.w_egu, y.w_egus);
y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe),
RAD_INT("K", E), RAD_INT("n_expert", NL),
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"), RAD_STR("dtype", "fp8a8")),
/* `a_group` is stated to the int8 rows alone, last and cut off otherwise. */
const RadParam ps[] = { RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe),
RAD_INT("K", E), RAD_INT("n_expert", NL),
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "token"),
RAD_STR("dtype", m.exp_i8 ? "i8a8h" : "fp8a8"),
RAD_INT("a_group", RAD_FP8_BLOCK) };
y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q", ps,
(int)(sizeof ps / sizeof *ps) - (m.exp_i8 ? 0 : 1),
tab.data(), (int)tab.size()),
{m.b_hq, m.b_hqs, m.b_sorted, m.b_eoff}, {m.b_egu});
} else {
@@ -1129,19 +1202,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* gelu_tanh(gate) * up over the two column halves. An fp8 down then quantises the
* product on its own launch: libr4d's fused gated quantiser is compiled for silu. */
y.op_eact = act_mul(P * K, m.n_ffe, m.b_egu, m.b_eact);
if (y.dn_fp8) {
y.op_eq = rw(b, RAD_OP(b, "quant_act_fp8",
if (y.dn_q) {
y.op_eq = rw(b, RAD_OP(b, m.exp_i8 ? "had_quant_act_i8g" : "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, P * K), RAD_INT("n", m.n_ffe),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{m.b_eact}, {m.b_eq, m.b_eqs});
const std::vector<rad_weight> tab = tables(y.w_edn, y.w_edns);
y.op_edn = rw(b, rad_decl_op(b, "moe_gemm_q",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", E),
RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL),
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "sorted"), RAD_STR("dtype", "fp8a8")),
const RadParam ps[] = { RAD_RANGE("M", 1, P), RAD_INT("N", E),
RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL),
RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("a_order", "sorted"),
RAD_STR("dtype", m.exp_i8 ? "i8a8h" : "fp8a8"),
RAD_INT("a_group", RAD_FP8_BLOCK) };
y.op_edn = rw(b, rad_decl_op(b, "moe_gemm_q", ps,
(int)(sizeof ps / sizeof *ps) - (m.exp_i8 ? 0 : 1),
tab.data(), (int)tab.size()),
{m.b_eq, m.b_eqs, m.b_sorted, m.b_eoff}, {m.b_edn});
} else {
@@ -1165,7 +1241,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
rad_op_reads(b, y.op_gather, rd, 3);
rad_op_writes(b, y.op_gather, wr, 1);
}
if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_fp8 && !y.op_eq)) return RAD_E_INVAL;
if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_q && !y.op_eq)) return RAD_E_INVAL;
if (W > 1) y.op_ar_f = allreduce(2 * T * E, m.b_ff2);
if (has_join_f)
{
@@ -1309,24 +1385,27 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
rad_note(b, "sandwich joins: %d of %lld fused (norm_add_norm / join_add_scale)%s",
n_joins, (long long)(m.moe ? 2 * m.n_layer : m.n_layer),
n_joins == 0 ? " -- not served, the rmsnorm / add / mul_weight chain" : "");
if (m.moe && m.n_gu_fp8 > 0)
rad_note(b, "routed inputs: %d of %d fp8 layers take the router's norm and the experts' "
"codes from the attention join (norm_add_norm_route)%s",
n_route, m.n_gu_fp8,
n_route ? "" : " -- the rmsnorm and rmsnorm_quant_fp8 launches instead");
if (m.moe && m.n_gu_q > 0)
rad_note(b, "routed inputs: %d of %d quantised layers take the router's norm and the "
"experts' codes from the attention join (%s)%s",
n_route, m.n_gu_q, join_r,
n_route ? "" : m.exp_i8 ? " -- the rmsnorm and rmsnorm_had_quant_i8g launches instead"
: " -- the rmsnorm and rmsnorm_quant_fp8 launches instead");
if (m.ks.nh > 0)
rad_note(b, "sliding attention: q %s", m.qrow == 1
? "read in the fused qkv row (attn_paged_qrow)"
: "lifted into a dense block for attn_paged (attn_paged_qrow not served)");
if (m.moe) {
auto how = [&](int n_fp8) {
return n_fp8 == m.n_layer ? "block fp8" : n_fp8 == 0 ? "bf16" : "mixed";
return n_fp8 == 0 ? "bf16" : n_fp8 < m.n_layer ? "mixed"
: m.exp_i8 ? "rotated int8" : "block fp8";
};
rad_note(b, "routed arm: %lld local experts from %lld of %lld, top %lld, %lld wide; "
"gate_up %s (%d of %lld layers fp8), down %s (%d fp8); passes of %lld tokens",
"gate_up %s (%d of %lld layers quantised), down %s (%d quantised); passes of "
"%lld tokens",
(long long)m.n_local, (long long)m.expert_base, (long long)m.n_expert,
(long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_fp8), m.n_gu_fp8,
(long long)m.n_layer, how(m.n_dn_fp8), m.n_dn_fp8, (long long)m.moe_rows);
(long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_q), m.n_gu_q,
(long long)m.n_layer, how(m.n_dn_q), m.n_dn_q, (long long)m.moe_rows);
if (W > 1)
rad_note(b, "prefill overlap: %s", m.overlap
? "a chunk of two routed passes or more runs as two slices, each slice's "
@@ -1394,11 +1473,11 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
}
/* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent);
* issued only where the attention join did not already write the codes. */
if (y.gu_fp8 && !y.op_join_r)
if (y.gu_q && !y.op_join_r)
RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_NONE, RAD_W(y.w_enorm),
brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK),
RAD_NONE);
else if (!y.gu_fp8)
else if (!y.gu_q)
RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_enorm),
brow_slice(m.b_hx, r0, n, E));
if (!rfused && !pair)
@@ -1407,7 +1486,7 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
/* An fp8 projection's tables: the first handle of each parity's run and its length --
* even codes, even scales, odd codes, odd scales (declare). */
const int64_t H = NL / 2;
if (y.gu_fp8)
if (y.gu_q)
RAD_ISSUE_N(c, y.op_egu, n, brow_slice(m.b_hq, r0, n, E),
brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK),
RAD_WTAB(y.w_egu[0], H), RAD_WTAB(y.w_egus[0], H),
@@ -1419,7 +1498,7 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t
brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), brows(m.b_egu, n * K));
RAD_ISSUE_N(c, y.op_eact, n * K, bcol(m.b_egu, 0, m.n_ffe, n * K),
bcol(m.b_egu, m.n_ffe, m.n_ffe, n * K), brows(m.b_eact, n * K));
if (y.dn_fp8) {
if (y.dn_q) {
RAD_ISSUE_N(c, y.op_eq, n * K, brows(m.b_eact, n * K), brows(m.b_eq, n * K),
brows(m.b_eqs, n * K));
RAD_ISSUE_N(c, y.op_edn, n, brows(m.b_eq, n * K), brows(m.b_eqs, n * K),
@@ -1737,7 +1816,7 @@ static void calib_count(RadCtx* c, Model& m, int64_t T) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
if (batch->draft_pass != 0) {
if (!m.have_df) {
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
@@ -1763,7 +1842,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
const int64_t cut = split_at(m, T);
if (cut > 0) trunk_overlap(c, m, batch, cut);
else trunk(c, m, batch);
if (m.calib && m.tap_live) calib_count(c, g_model[rad_rank(c)], T);
if (m.calib && m.tap_live) calib_count(c, g_model[rad_slot(c)], T);
if (m.op_onorm) RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T));
if (batch->n_out > 0) {
@@ -1796,6 +1875,8 @@ static const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_cha
} /* namespace gemma4 */
#ifndef RAD_ARCH_NO_EXPORTS
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(gemma4, "gemma4", "", "0.1.0",
"Gemma 4 text decoders (26B-A4B MoE, dense 31B), bf16: sliding and full attention "
"with proportional rope and K = V, a dense and a routed feed-forward side by side, "
+174 -31
View File
@@ -1,5 +1,6 @@
/* gemma4_bf16.cpp -- Gemma 4 dense, bf16, with its vision tower (rad_block_gemma4_vision.h) and,
* for E2B/E4B, its audio encoder (rad_block_gemma4_audio.h).
* for E2B/E4B, its audio encoder (rad_block_gemma4_audio.h); for the 12B ("unified"), its image and
* audio embedders in their place (rad_block_gemma4_unified.h).
*
* Two attention classes over one residual stream, alternating by layer. A "sliding" layer is
* sliding-window attention over head_dim 256 with a v projection and standard RoPE; a "global"
@@ -17,6 +18,7 @@
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_gemma4_audio.h>
#include <arch/rad_block_gemma4_unified.h>
#include <arch/rad_block_gemma4_vision.h>
#include <arch/rad_gemma4_chat.h>
#include <arch/rad_gemma4_dflash.h>
@@ -454,6 +456,16 @@ struct Gemma4Attn {
* no library serves it, which the model reads as "no trees". */
bool tree = false;
rad_op op_attn_tree = 0, op_tree_lift = 0;
/* Pictures read both ways (Model::bidi, set before declare; sliding layers only): attention
* again over a run's keys without the causal bound (RadBatch::n_bidi), reading q in the row
* (op_bidi_row) where the step's attention does, else in its own rows (op_bidi); 0 where no
* kernel serves it. */
bool want_bidi = false;
rad_op op_bidi = 0, op_bidi_row = 0;
/* The same where the window bounds the keys behind a row only: a run longer than the window
* (op_ahead_row where q is read in the row); 0 where no kernel serves it. */
rad_op op_ahead = 0, op_ahead_row = 0;
bool bidi_ok() const { return op_bidi || op_bidi_row; }
/* the feed-forward's gate_up read into the cache beside this block's all-reduce, or 0 (see
* "Prefetch beside the reductions") */
rad_op op_pf = 0;
@@ -492,6 +504,9 @@ struct Gemma4Attn {
bool slicable() const { return op_qnr_kv && (op_attn_row || op_attn); }
void attend_rows(RadCtx* c, const RadBatch* batch, int64_t r0, int64_t n,
RadOperand used) const;
/* The rows of each run read both ways, attended again (see op_bidi); `q_dense`: the step's
* attention left q in its own rows. */
void attend_bidi(RadCtx* c, const RadBatch* batch, bool q_dense) const;
};
int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
@@ -644,11 +659,12 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
/* Gemma 4 scores Q.K without the 1/sqrt(head_dim) factor (HF Gemma4TextAttention and vLLM
* use scaling = 1.0; the q/k norm gains absorb it). attn_paged defaults to 1/sqrt(head_dim),
* so 1.0 is passed explicitly. */
auto attn = [&](const char* op, std::initializer_list<rad_buf> rd, int64_t q_hi = 0) {
auto attn = [&](const char* op, std::initializer_list<rad_buf> rd, int64_t q_hi = 0,
int causal = 1) {
return rw(b, RAD_OP(b, op,
RAD_PARAMS(RAD_RANGE("q_len", 1, q_hi > 0 ? q_hi : g.max_tok),
RAD_INT("head_dim", cls.head_dim),
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1),
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", causal),
RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
@@ -729,6 +745,15 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
op_attn = attn("attn_paged", {w.q, w.qkv});
}
}
if (want_bidi) {
if (op_attn_row) {
op_bidi_row = attn("attn_paged_qrow", {w.qkv}, 0, 0);
op_ahead_row = attn("attn_paged_qrow_ahead", {w.qkv}, 0, 0);
} else {
op_bidi = attn("attn_paged", {w.q}, 0, 0);
op_ahead = attn("attn_paged_ahead", {w.q}, 0, 0);
}
}
/* The tree form over the decode rows: a verify block of 1 + n_spec rows a sequence, so the
* split-KV band (q_len * gqa <= 64) covers it at every class here. In the row where the
@@ -855,6 +880,23 @@ int Gemma4Attn::declare_shared(RadBuilder* b, Names& nm, const char* pre) {
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
if (want_bidi) {
auto bidi = [&](const char* op) {
return rw(b, RAD_OP(b, op,
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
RAD_INT("head_dim", cls.head_dim),
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 0),
RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_F64("scale", 1.0),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
};
op_bidi = bidi("attn_paged");
op_ahead = bidi("attn_paged_ahead");
}
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),
@@ -963,6 +1005,7 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn, T));
attend_bidi(c, batch, true);
return;
}
/* q, k and v where the prologue works on them: their own buffers, or on a fused layer with the
@@ -1001,6 +1044,7 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
* which come first (spec §8). */
const bool tree_step = op_attn_tree && batch->spec_parent && batch->draft_pass == 0 &&
batch->n_seq_decode > 0;
bool q_dense = true;
if (!tree_step || batch->n_seq_decode < batch->n_seq) {
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
rad_op a_op = op_attn;
@@ -1011,8 +1055,9 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
} else if (op_attn_dec && batch->max_q_len <= dec_hi) {
a_op = op_attn_dec;
a_q = Q;
q_dense = false;
} else if (row) {
if (T == 1) a_q = Q;
if (T == 1) { a_q = Q; q_dense = false; }
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
}
RAD_ISSUE_N(c, a_op, batch->max_q_len,
@@ -1039,6 +1084,44 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
brows(w.attn, Td),
praw(batch->spec_parent, RAD_I32, Td));
}
attend_bidi(c, batch, q_dense);
}
/* A run's rows (RadBatch::n_bidi) see every key of their run, later ones included: attention over
* their sequence's cache up to the run's end without the causal bound, written over what the
* causal pass left in their rows, on a sliding layer. Its window stays: (causal or the run) and
* the window, as transformers' mask has it. The window bounds the keys behind a row; within it a
* run's far end is in reach of every row up to the window's length, and a longer run is read with
* attn_paged_ahead, whose window bounds the keys behind only. The keys are all in the cache: the
* step stored its own, and a run's earlier rows are this step's or a prefix hit's. */
void Gemma4Attn::attend_bidi(RadCtx* c, const RadBatch* batch, bool q_dense) const {
if (batch->n_bidi <= 0 || !bidi_ok()) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int64_t pitch = kvb ? kvb->block_table_pitch : 0;
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0);
for (int64_t i = 0; i < batch->n_bidi; ++i) {
const int64_t r0 = batch->bidi_row[i], n = batch->bidi_n[i], s = batch->bidi_seq[i];
const RadOperand tb = praw2(table ? table + s * pitch : nullptr, RAD_I32, 1, pitch);
const RadOperand used = praw(batch->bidi_used + i, RAD_I32, 1);
const RadOperand out = brow_slice(w.attn, r0, n, qd);
/* A run longer than the window has rows that miss its far end under a two-sided window;
* transformers' mask bounds only the keys behind. */
const bool ahead = n > cls.window;
const rad_op bidi_row = ahead && op_ahead_row ? op_ahead_row : op_bidi_row;
const rad_op bidi = ahead && op_ahead ? op_ahead : op_bidi;
if (op_bidi_row) {
RAD_ISSUE_N(c, bidi_row, n, bcol_at(w.qkv, r0, qkvd, 0, qd, n),
kv_cache(kv, kv_layer), tb, used, RAD_NONE, RAD_NONE, RAD_NONE, out);
continue;
}
if (!q_dense)
RAD_ISSUE_N(c, op_lift_q, n, bcol_at(w.qkv, r0, qkvd, 0, qd, n),
brow_slice(w.q, r0, n, qd));
RAD_ISSUE_N(c, bidi, n, brow_slice(w.q, r0, n, qd), kv_cache(kv, kv_layer), tb, used,
RAD_NONE, RAD_NONE, RAD_NONE, out);
}
}
/* A slice's rows see exactly the keys they see in the whole step: the cache holds the step's
@@ -1414,10 +1497,11 @@ struct Gemma4Head {
void step(RadCtx* c, const RadBatch* batch) const;
};
/* Does the container carry an assistant head at all? */
/* Does the container carry an assistant head at all? The 12B's is the same head under another
* name (Gemma4UnifiedAssistantForCausalLM). */
static bool has_assistant(const RadModelMeta* m) {
const char* a = rad_meta_gets(m, "draft.architectures", "");
return a && std::strstr(a, "Gemma4Assistant") != nullptr;
return a && (std::strstr(a, "Gemma4Assistant") || std::strstr(a, "Gemma4UnifiedAssistant"));
}
int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, const Geom& trunk,
@@ -1459,16 +1543,17 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
}
/* The head reads the trunk's cache, so everything the cache's shape depends on must agree:
* the two head widths, the two kv head counts and the window. A head that disagrees was trained
* with another trunk. */
* with another trunk. The counts are the model's, not a rank's: a replicated kv head (fewer
* than ranks) is one head on every rank. */
if (n_trunk != trunk.n_embd || vocab != trunk.n_vocab_all || head_s != cs.head_dim ||
head_g != cg.head_dim || n_kv != cs.n_head_kv * trunk.world ||
n_kv_g != cg.n_head_kv * trunk.world || win != cs.window) {
head_g != cg.head_dim || n_kv != cs.n_head_kv_all || n_kv_g != cg.n_head_kv_all ||
win != cs.window) {
fprintf(stderr, "radiance: gemma4 assistant: this head was not made for this trunk -- it "
"states width %lld, vocabulary %lld, heads %lld/%lld x %lld/%lld kv over a "
"window of %lld; the trunk's cache is %lld/%lld kv heads of %lld/%lld over "
"%lld, at width %lld and vocabulary %lld\n",
(long long)n_trunk, vocab, n_kv, n_kv_g, head_s, head_g, win,
(long long)(cs.n_head_kv * trunk.world), (long long)(cg.n_head_kv * trunk.world),
(long long)cs.n_head_kv_all, (long long)cg.n_head_kv_all,
(long long)cs.head_dim, (long long)cg.head_dim, (long long)cs.window,
(long long)trunk.n_embd, (long long)trunk.n_vocab_all);
return RAD_E_INVAL;
@@ -1888,7 +1973,13 @@ struct Model {
* embeddings. */
Gemma4Vision vis{};
Gemma4Audio aud{};
Gemma4UnifiedVision uvis{}; /* the 12B's embedders, in place of the tower and encoder */
Gemma4UnifiedAudio uaud{};
rad_op op_mm = 0;
/* A picture's or video frame's placeholders attend to each other both ways
* (use_bidirectional_attention "vision"): every sliding layer attends a run's rows again
* (Gemma4Attn::op_bidi), and the encoder says so (RadEncoderDecl::bidirectional). */
bool bidi = false;
G4Junction j0{}; /* the first block's entry: norm + quantiser of the embedding stream */
bool fuse = false;
@@ -1922,7 +2013,7 @@ struct Model {
bool slice_attn = false;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* A DFlash2 drafter's config key, from vLLM's speculators layout (the speculator's keys at the
* top of `draft.`) or z-lab's (under `draft.dflash_config.`), whichever the checkpoint has. */
@@ -2071,17 +2162,31 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd});
dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff});
dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd});
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32,
{dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)});
dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
dw.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, dg.n_embd});
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd});
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)});
dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff});
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
/* The codes the drafter's linears read: int8 with one f32 scale per (row, group) for linears
* stored rotated int8 (the -df2 recipe's), which the drafter's `fc` tells; E4M3 with a scale
* per 128 for an MXFP4 drafter (rad_fp8.h's DenseFP8). */
RAD_ARCH_TRY(Dflash2::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
dc.fc_mapped = true;
const uint32_t dqt = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_FP8_BLOCK;
if (dc.act_i8 && ((dc.n_taps * dg.n_embd) % dqg || dg.n_embd % dqg || qd % dqg ||
dg.n_ff % dqg)) {
fprintf(stderr, "radiance: a rotated int8 drafter takes widths in whole %lld-column scale "
"groups; this one is n_embd %lld, q %lld, n_ff %lld\n", (long long)dqg,
(long long)dg.n_embd, (long long)qd, (long long)dg.n_ff);
return RAD_E_INVAL;
}
auto dqs = [&](int64_t n) { return (n + dqg - 1) / dqg; };
dw.srcq = decl_b(b, nm.f("df_srcq"), dqt, {dg.max_tok, dc.n_taps * dg.n_embd});
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, dqs(dc.n_taps * dg.n_embd)});
dw.cq = decl_b(b, nm.f("df_cq"), dqt, {dg.max_tok, dg.n_embd});
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, dqs(dg.n_embd)});
dw.h2q = decl_b(b, nm.f("df_h2q"), dqt, {qr, dg.n_embd});
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, dqs(dg.n_embd)});
dw.atq = decl_b(b, nm.f("df_atq"), dqt, {qr, qd});
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, dqs(qd)});
dw.ffq = decl_b(b, nm.f("df_ffq"), dqt, {qr, dg.n_ff});
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, dqs(dg.n_ff)});
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank});
dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd});
@@ -2170,9 +2275,10 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
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;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
@@ -2404,8 +2510,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* the lookup and before its all-reduce (RadBatch::mm_embd: rank 0 holds the rows, every other
* rank zeros). The reference scales token embeddings by sqrt(n_embd) and scatters the media
* features in unscaled. */
if ((Gemma4Vision::present(meta) && ctx->max_enc_patches > 0) ||
(Gemma4Audio::present(meta) && ctx->max_audio_frames > 0))
if (((Gemma4Vision::present(meta) || Gemma4UnifiedVision::present(meta)) &&
ctx->max_enc_patches > 0) ||
((Gemma4Audio::present(meta) || Gemma4UnifiedAudio::present(meta)) &&
ctx->max_audio_frames > 0))
m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", "bf16")),
@@ -2508,10 +2616,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
kv_shared == 0 && ctx->draft_tree != 0;
bool tree_all = tree_want;
/* Pictures read both ways where the model was trained so, on the sliding layers alone: the
* global layers stay causal (transformers' create_masks_for_vision_model, "Gemma 4 explicitly
* disables bidirectional attention on global attention layers"; KerasHub's Gemma 4 decoder
* block and vLLM agree). */
const char* bidi_cfg = meta_text_gets(meta, "use_bidirectional_attention", "");
const bool want_bidi = bidi_cfg && !std::strcmp(bidi_cfg, "vision") && ctx->max_enc_patches > 0 &&
(Gemma4Vision::present(meta) || Gemma4UnifiedVision::present(meta));
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];
lay.global = (is_global[(size_t)l] == 1);
lay.attn.want_bidi = want_bidi && !lay.global;
const ClassGeom& cgeo = lay.global ? m.cg : m.cs;
const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s;
const Gemma4Attn::Wire& aw = lay.global ? gw : sw;
@@ -2818,11 +2934,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
std::snprintf(k, sizeof k, "%snum_hidden_layers", drafter_layer_prefix(meta));
head_groups = rad_meta_geti(meta, k, 0);
}
m.bidi = want_bidi;
for (const Layer& lay : m.layers) m.bidi = m.bidi && (lay.global || lay.attn.bidi_ok());
if (want_bidi && !m.bidi)
rad_note(b, "pictures are read causally: no kernel attends a run's rows without the "
"causal bound");
m.vis.bidirectional = m.uvis.bidirectional = m.bidi;
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups),
"model.", "gemma4_bf16"));
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, g.n_embd,
(int)(m.n_main + head_groups) + (int)m.vis.L.size(), "model.",
"gemma4_bf16"));
RAD_ARCH_TRY(m.uvis.declare(b, meta, ctx, nm, g.n_embd, "gemma4_bf16"));
RAD_ARCH_TRY(m.uaud.declare(b, meta, ctx, nm, g.n_embd, "gemma4_bf16"));
}
rad_note(b, "rank %d/%d: %lld layers (%lld global, %lld sliding), sliding window %lld, "
@@ -2954,7 +3078,7 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
m.j0.step(c, T);
const size_t L = m.layers.size();
if (m.slice_attn && batch->n_seq == 1) {
if (m.slice_attn && batch->n_seq == 1 && batch->n_bidi == 0) {
/* Attention per slice (see Model::slice_attn): slice A's context end first, then each
* layer as A's attention block, B's beside A's attention-side reduction, A's feed-forward
* beside B's, B's feed-forward beside A's, and the next layer's A block beside B's. Each
@@ -3046,12 +3170,18 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = g_model[rad_rank(c)];
Model& m = g_model[rad_slot(c)];
/* An encoder pass runs only its encoder. */
if (batch->enc) {
if (batch->enc == RAD_MM_AUDIO) m.aud.step(c, batch);
else m.vis.step(c, batch);
if (batch->enc == RAD_MM_AUDIO) {
if (m.uaud.on) m.uaud.step(c, batch);
else m.aud.step(c, batch);
} else if (m.uvis.on) {
m.uvis.step(c, batch);
} else {
m.vis.step(c, batch);
}
return;
}
/* A draft pass runs only the draft model. The trunk already left its final-normed hidden state
@@ -3186,18 +3316,31 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
* DFlash2 one too (rad_block_dflash2.h). */
(void)gemma4::dflash_probe(meta, out);
(void)gemma4::dflash2_probe(meta, out);
/* Chained launches pay on the dense trunk under any drafter and without one: its decode
* kernels have chained forms (libr4d's rad_kernel_chain), the two-rank junctions among them,
* and the weight reads beside the reductions then stay on lane 0 instead of a second queue.
* Gemma 4 31B on two R9700, ms a decode step unchained / chained: grouped int8 35.81 / 27.60
* without a drafter and 42.14 / 31.23 with the assistant head (44.93 / 34.17 at four
* sequences); w4a8 26.14 / 15.78 and 32.30 / 20.36 (35.93 / 25.01). The 12B with its head:
* bf16 38.65 / 28.84, grouped int8 24.35 / 14.74. */
out->chain_pays = RAD_CHAIN_ALWAYS;
/* The tower's pooling window, so a pass size the core picks itself is whole windows. */
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 (Gemma4Audio::present(meta)) out->audio_frames = Gemma4Audio::frames_for(meta);
/* The 12B's embedders: a patch and an audio frame are a row each. */
if (Gemma4UnifiedVision::present(meta)) out->enc_merge = 1;
if (Gemma4UnifiedAudio::present(meta)) out->audio_frames = Gemma4UnifiedAudio::frames_for(meta);
return RAD_OK;
}
#ifndef RAD_ARCH_NO_EXPORTS
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0",
"Gemma 4 dense (text, images and E2B/E4B audio), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) "
"Gemma 4 dense (text, images, E2B/E4B/12B audio), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) "
"release: sliding-window and proportional-RoPE global attention over a plain "
"RMSNorm stream with GELU feed-forward, per-layer scalar scaling and soft-capped "
"logits; Google's assistant head, z-lab's DFlash drafter or a DFlash2 drafter")
+74 -28
View File
@@ -50,6 +50,12 @@ struct Model {
* form declares none of the row form's full-width weights (1.29 GiB a card at eight ranks);
* the row form is opt-in because it is not bit-identical to it (docs/ARCHITECTURES.md). */
GlmMla::Form form = GlmMla::Form::heads;
/* Routed experts whole on their rank (288/world of them) instead of split by width across
* every rank. Whole experts can be read from the drive, which two cards need; at four and
* eight the width split is the shape the MXFP4 kernels are tuned for (prefill runs about three
* times faster), so all-MXFP4 experts take it unless --weights-disk-tier asks for the drive.
* Anything else stays whole: a plain bf16 expert cannot be sliced at all. */
bool whole_experts = false;
std::vector<Layer> layers;
rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0;
/* The streams and the step's stream-wide buffers. */
@@ -73,9 +79,26 @@ struct Model {
GlmVision vit{};
MediaRows mrows{};
};
static std::unique_ptr<Model> models[MAX_RANKS];
static std::unique_ptr<Model> models[MAX_SLOTS];
static thread_local std::unique_ptr<Model> probe_model;
/* Whether every routed expert is MXFP4, asked before any buffer is sized and of the same experts on
* every rank, so all ranks reach the same layout. It reads the container's entries and declares no
* name map, so it leaves the graph as it was. One expert in another format settles it: a protected
* bf16 expert is served only whole. No answer means no container entry, and what is not known to
* be MXFP4 stays whole. */
static bool experts_are_mxfp4(RadBuilder* b, Names& nm) {
for (int l = 3; l < 45; ++l)
for (int ge = 0; ge < 288; ++ge)
for (const char* fmt : { "blk.%d.ffn_gate_up_exps.%d.weight",
"blk.%d.ffn_down_exps.%d.weight" }) {
RadEncoding e{};
if (!weight_enc(b, nm.f(fmt, l, ge), &e) || MoeFP8::format_of(e) != 8)
return false;
}
return true;
}
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
char nested[160];
std::snprintf(nested, sizeof nested, "text_config.%s", key);
@@ -211,6 +234,7 @@ static int indexer_buffers(RadBuilder* b, Model& m) {
* at 64k of context the whole step's plane would be 256 MiB. */
const int64_t scored = g.world > 1 ? std::min(T, std::max(part, GlmTp::kSplitRows)) : T;
c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { scored, blocks });
c.unscored = decl_b(b, nm.f("index_unscored"), RAD_F32, { T, std::min<int64_t>(513, blocks) });
c.selected = m.aw.core.selected;
c.length = m.aw.core.length;
c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
@@ -243,13 +267,18 @@ static int ffn_buffers(RadBuilder* b, Model& m) {
mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 });
mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 });
mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 });
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 });
/* PERSIST, as every other MoE here declares it: the router writes the counts and no declared
* op reads them (rad_route_report is a handoff), so as a transient a later buffer could share
* their bytes and an arena level would move them, while the core copies them at the block's
* end and the file stager reads them, through the address the last pass reported, at the
* layer's first expert op. */
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }, RAD_BUF_PERSIST);
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * 8 });
mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { T * 8 });
// FE: the routed experts' WHOLE intermediate (2048). Under expert parallelism a rank owns
// whole experts, so the routed arm's buffers are full-width at every world size; the SHARED
// expert stays width-sharded (F). The two coincide at world 1.
const int64_t FE = 2048;
// FE: the routed experts' intermediate. Under expert parallelism a rank owns whole experts,
// so the routed arm's buffers are full-width (2048); split by width they are F. The SHARED
// expert stays width-sharded (F) either way. The two coincide at world 1.
const int64_t FE = m.whole_experts ? 2048 : F;
mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * FE });
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, FE });
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", FE, T * 8));
@@ -266,7 +295,8 @@ static int kv_groups(RadBuilder* b, Model& m) {
auto& nm = m.nm;
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = RAD_BF16;
// bf16, or E4M3 under --kv-cache-dtype fp8 (geometry); the other groups keep their own.
d.dtype = rad_dtype_parse(g.kv_dtype);
d.n_head_kv = 1;
d.head_dim = 256;
m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d);
@@ -373,14 +403,19 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
// degenerates to the old whole-model declaration (n_expert == n_expert_all, no spans).
s.cfg.n_expert_all = 288;
s.cfg.top_k = 8;
s.cfg.n_expert = 288 / g.world;
// A shape probe may pass rank >= world (arch_test's parallel declares reuse i % 4);
// old code tolerated that because expert_base stayed 0, so clamp to rank 0's window.
const int ep_rank = g.rank < g.world ? g.rank : 0;
s.cfg.expert_base = ep_rank * (288 / g.world);
s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate
s.cfg.n_ff_shared = 2048 / g.world;
s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
if (m.whole_experts) {
s.cfg.n_expert = 288 / g.world;
// A shape probe may pass rank >= world (arch_test's parallel declares reuse i % 4);
// old code tolerated that because expert_base stayed 0, so clamp to rank 0's window.
const int ep_rank = g.rank < g.world ? g.rank : 0;
s.cfg.expert_base = ep_rank * (288 / g.world);
s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate
} else {
s.cfg.n_expert = 288;
s.cfg.n_ff_exp = GlmTp::expert_width(g.world);
}
s.cfg.rows = g.max_tok;
s.cfg.sigmoid_router = 1;
s.cfg.route_scale = 2.5;
@@ -389,12 +424,12 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
s.cfg.router_fuse = 1;
s.cfg.swiglu_quant = 1;
// At world 1 the width-slice declaration IS the whole model: keep the spans so the
// graph stays the pinned one. At world > 1 expert parallelism is in force and whole
// experts need no width spans (split && ep is refused by the helper).
if (g.world == 1) {
// graph stays the pinned one. Whole experts need no width spans (split && ep is refused
// by the helper).
if (!m.whole_experts) {
for (int q = 0; q < 2; ++q) {
s.cfg.ff_lo[q] = g.rank * (2048 / g.world);
s.cfg.ff_hi[q] = (g.rank + 1) * (2048 / g.world);
s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
}
}
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg));
@@ -430,12 +465,16 @@ static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, i
g.max_logit_rows = std::min<int64_t>(g.max_tok, g.max_seqs * (g.max_spec + 1));
if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows;
g.eps = meta->rms_eps;
/* --kv-cache-dtype names the latent cache's dtype only (kv_groups); declare refuses all but
* bf16 and fp8. */
g.kv_dtype = rad_dtype_name(rad_kv_cache_dtype(ctx, RAD_BF16));
g.wire_exact = !ctx->tp_wire_lossy;
g.wire_min_bytes = ctx->tp_wire_min_bytes;
return g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0 ? RAD_E_INVAL : RAD_OK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
const int world = ctx->world_size ? ctx->world_size : 1;
if (!GlmTp::world_ok(world)) {
@@ -468,14 +507,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
ctx->max_spec);
return RAD_E_UNSUPPORTED;
}
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) {
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin keeps its latent "
"attention, index tail and KDA caches in bf16 and has no fp8 cache, so "
"run it with --kv-cache-dtype bf16\n",
ctx->kv_dtype == RAD_F8E4M3 ? "fp8" : rad_dtype_name(ctx->kv_dtype));
/* fp8 narrows the latent attention cache to E4M3 at a descale of 1 (kv_groups); the index
* tail, the DSA index and the KDA caches keep their dtypes. */
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_F8E4M3) {
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin serves its latent "
"attention cache in bf16 or fp8 only\n",
rad_dtype_name(ctx->kv_dtype));
return RAD_E_UNSUPPORTED;
}
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
auto& slot = ctx->shape_probe ? probe_model : models[rad_build_slot(ctx)];
slot = std::make_unique<Model>();
auto& m = *slot;
auto& g = m.g;
@@ -483,6 +523,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
auto& nm = m.nm;
m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads;
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
m.whole_experts = world == 2 || (world > 2 && (ctx->expert_file_tier ||
!experts_are_mxfp4(b, nm)));
RAD_ARCH_TRY(stream_buffers(b, m));
RAD_ARCH_TRY(kda_buffers(b, m));
RAD_ARCH_TRY(mla_buffers(b, m));
@@ -584,7 +626,7 @@ static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
m.mtp.step_head(c, batch);
}
static void step(RadCtx* c, const RadBatch* batch) {
auto& m = *models[rad_rank(c)];
auto& m = *models[rad_slot(c)];
const int64_t T = batch->n_tok;
// An encoder pass runs only the vision tower (RadBatch::enc).
if (batch->enc) {
@@ -634,11 +676,15 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
}
out->shape_probe_ok = 1;
out->tp_attn_rows_ok = 1;
/* --kv-cache-dtype fp8: the latent attention cache as E4M3 (declare, kv_groups). */
out->kv_fp8_ok = 1;
return RAD_OK;
}
} // namespace glm5next
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(glm5next)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(glm5next, "glm5next", "", "0.1.0",
"GLM-5.3-Flash mixed MXFP4/FP8, mHC/KDA/MLA and native serial MTP")
#endif
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/hunyuan3d2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(hunyuan3d2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(hunyuan3d2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hunyuan3d2.cpp)
File diff suppressed because it is too large. Load diff
+10 -52
View File
@@ -38,7 +38,6 @@ struct AttnQKFP8 {
const char* q_norm = nullptr;
const char* k_norm = nullptr;
const char* o = nullptr;
double k_scale = 1.0, v_scale = 1.0; /* static FP8-cache descales; 1 for BF16 cache */
};
Geom g{};
@@ -48,11 +47,9 @@ struct AttnQKFP8 {
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
LinearFP8 q{}, k{}, v{}, o{};
rad_buf k_descale = 0, v_descale = 0;
NormQuantFP8 nq_h{};
QuantFP8 q_attn{};
rad_op op_q_norm = 0, op_k_norm = 0;
rad_op op_k_descale = 0, op_v_descale = 0;
rad_op op_rope_q = 0, op_rope_k = 0, op_attn = 0, op_kv_store = 0;
rad_op op_qkr_store = 0; /* Q/K norms, NeoX rotary and BF16 cache store, decode band */
int64_t qkr_rows = 0;
@@ -78,14 +75,6 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
(long long)g.n_head_kv_all);
return RAD_E_UNSUPPORTED;
}
const bool fp8_cache = std::strcmp(g.kv_dtype, "fp8_e4m3") == 0;
if (fp8_cache && (!std::isfinite(src.k_scale) || src.k_scale <= 0.0 ||
!std::isfinite(src.v_scale) || src.v_scale <= 0.0)) {
fprintf(stderr, "radiance: HYV3 layer %d needs positive finite static K/V descales for "
"its FP8 KV cache\n", l);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
@@ -122,23 +111,7 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int 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"),
{w.k}, {w.k});
if (fp8_cache) {
k_descale = decl_b(b, nm.f("blk.%d.attn_k_descale", l), RAD_F32,
{g.max_seqs, g.n_head_kv});
v_descale = decl_b(b, nm.f("blk.%d.attn_v_descale", l), RAD_F32,
{g.max_seqs, g.n_head_kv});
op_k_descale = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", g.n_head_kv),
RAD_STR("dtype", "f32"), RAD_F64("value", src.k_scale)),
RAD_NOWEIGHTS),
{}, {k_descale});
op_v_descale = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", g.n_head_kv),
RAD_STR("dtype", "f32"), RAD_F64("value", src.v_scale)),
RAD_NOWEIGHTS),
{}, {v_descale});
}
const rad_op attn = decl_attn(b, g, "attn_paged",
const rad_op attn = rad_decl_op(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
@@ -146,19 +119,17 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS);
op_attn = fp8_cache ? rw(b, attn, {w.q, k_descale, v_descale}, {w.attn.x})
: rw(b, attn, {w.q}, {w.attn.x});
op_attn = rw(b, attn, {w.q}, {w.attn.x});
op_kv_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype),
RAD_F64("k_scale", src.k_scale), RAD_F64("v_scale", src.v_scale)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.k, w.v}, {});
/* The standalone chain stays available for prefill, scaled/multicomponent rotary, FP8 KV,
* and libraries without the fold. A 128-channel BF16 decode prologue is otherwise five tiny
/* The standalone chain stays available for prefill, scaled/multicomponent rotary, the int8
* cache and libraries without the fold. A 128-channel BF16 decode prologue is otherwise five tiny
* launches; the fused kernel preserves the BF16 norm rounding before the rotary. */
if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") &&
!std::strcmp(g.kv_dtype, "bf16") &&
@@ -195,9 +166,7 @@ inline int AttnQKFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h.x}, {w.x});
return op_attn && op_kv_store && (!add_out || op_add) &&
(!fp8_cache || (k_descale && v_descale && op_k_descale && op_v_descale))
? RAD_OK : RAD_E_INVAL;
return op_attn && op_kv_store && (!add_out || op_add) ? RAD_OK : RAD_E_INVAL;
}
inline void AttnQKFP8::step(RadCtx* c, const RadBatch* batch) const {
@@ -223,21 +192,10 @@ inline void AttnQKFP8::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));
}
if (op_k_descale) {
RAD_ISSUE_N(c, op_k_descale, batch->n_seq, brows(k_descale, batch->n_seq));
RAD_ISSUE_N(c, op_v_descale, batch->n_seq, brows(v_descale, batch->n_seq));
}
if (k_descale && v_descale)
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), brows(k_descale, batch->n_seq),
brows(v_descale, batch->n_seq),
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T));
else
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T));
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, layer),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T));
q_attn.step(c, T);
o.step(c, w.attn, w.h.x, T);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
+11 -30
View File
@@ -56,7 +56,7 @@ struct Model {
std::vector<Layer> layers;
};
static Model models[MAX_RANKS];
static Model models[MAX_SLOTS];
static int check_format(const RadModelMeta* meta) {
const char* q = meta && meta->quant ? meta->quant : "";
@@ -153,8 +153,10 @@ static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int
}
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;
Model& m = models[ctx->rank];
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = models[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
int status = check_format(meta);
@@ -173,19 +175,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
status = check_model_config(meta, g, m);
if (status < 0) return status;
#if HYV3_FP8_SOURCE
if ((ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 &&
ctx->kv_dtype != RAD_F8E4M3) || ctx->kv_quant != RAD_KVQ_NONE) {
fprintf(stderr, "radiance: HYV3 FP8 supports BF16 or plain E4M3 KV cache, not this layout\n");
if (ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_I8) {
fprintf(stderr, "radiance: HYV3 serves a bf16 or an int8 KV cache, not %s\n",
rad_dtype_name(ctx->kv_dtype));
return RAD_E_UNSUPPORTED;
}
#else
if ((ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16) ||
ctx->kv_quant != RAD_KVQ_NONE) {
fprintf(stderr, "radiance: HYV3 BF16 supports a BF16 KV cache only\n");
return RAD_E_UNSUPPORTED;
}
#endif
status = yarn_from(g, meta, "", g.head_dim);
if (status < 0) return status;
@@ -340,21 +334,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
as.q_norm = nm.ckpt("%s.self_attn.q_norm.weight", pre);
as.k_norm = nm.ckpt("%s.self_attn.k_norm.weight", pre);
as.o = nm.ckpt("%s.self_attn.o_proj.weight", pre);
#endif
#if HYV3_FP8_SOURCE
if (kd.dtype == RAD_F8E4M3) {
const std::string sk = "hyv3.kv_cache." + std::to_string(l) + ".k_scale";
const std::string sv = "hyv3.kv_cache." + std::to_string(l) + ".v_scale";
as.k_scale = meta_text_getf(meta, sk.c_str(), NAN);
as.v_scale = meta_text_getf(meta, sv.c_str(), NAN);
if (!std::isfinite(as.k_scale) || as.k_scale <= 0.0 ||
!std::isfinite(as.v_scale) || as.v_scale <= 0.0) {
fprintf(stderr, "radiance: hyv3_fp8: FP8 KV cache needs positive finite scales "
"for layer %lld (metadata keys %s and %s)\n",
(long long)l, sk.c_str(), sv.c_str());
return RAD_E_UNSUPPORTED;
}
}
#endif
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
// Each norm folds its predecessor's residual add. The first attention reads the
@@ -462,7 +441,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = models[rad_rank(c)];
Model& m = models[rad_slot(c)];
RAD_ISSUE(c, m.embed,
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.token),
brows(m.x, batch->n_tok));
@@ -529,6 +508,8 @@ extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) {
return &kHyv3ChatFormat;
}
extern "C" const char* rad_arch_id(void) { return "hyv3"; }
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
extern "C" const char* rad_arch_quant(void) { return HYV3_QUANT; }
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
return HYV3_NS::declare(b, m, c);
+115 -41
View File
@@ -33,10 +33,15 @@
*
* ============================== WHAT IS QUANTISED ==============================
*
* One plugin serves bf16 and block-fp8 containers: every linear of the language model, of the
* text fusion and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16 throughout when the first
* DiT projection is plain. txt_in, img_in, the timestep MLP and modulation, the final layer and
* the VAE stay bf16.
* One plugin serves bf16, block-fp8 and rotated int8 (IQ8R) containers: every linear of the
* language model, of the text fusion and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16
* throughout when the first DiT projection is plain. That projection also says whether the
* linears are rotated int8: the activations they read then carry int8 codes in place of the E4M3
* pair, written by the rotating twins of the fused ops where a library serves them
* (rms_mod_had_quant_i8g for a modulated norm, gate_had_quant_i8g for an attention's output
* gate); elsewhere the norm, or the sigmoid and multiply pair, is followed by the rotating
* quantiser. txt_in, img_in, the timestep MLP and modulation, the final layer and the VAE stay
* bf16.
*
* ============================== TENSOR PARALLEL ==============================
*
@@ -132,6 +137,9 @@ struct DitLayer {
rad_op op_tab = 0; /* the shared modulation plus this block's table, into its columns */
LinearFP8 qkv{}, gate{}, o{}, gate_up{}, down{};
QuantFP8 q_attn{};
/* The two modulated norms' quantisers for a rotated int8 model whose norms are the
* unquantised form (Model::norm_i8 false). */
QuantFP8 q_n1{}, q_n2{};
GateQuantFP8 gq{};
rad_op op_n1 = 0, op_n2 = 0, op_qkr = 0, op_attn = 0, op_gq = 0, op_sig = 0;
rad_op op_ar1 = 0, op_ar2 = 0;
@@ -189,6 +197,15 @@ struct Model {
ActFP8 a_hm{}, a_attn{}, a_ffn{};
std::vector<DitLayer> dit;
LinearFP8 qkv0{};
/* The linears of every network are rotated int8 (IQ8R, or the 128-group int8 before it), read
* off qkv0's probe: the activations then carry int8 code pairs with one scale per (token, `g8`
* columns) in place of the E4M3 pair. */
bool i8 = false;
int64_t g8 = RAD_FP8_BLOCK;
/* Where a library serves the rotating twins, a DiT block's modulated norms write those int8
* codes in their own pass (rms_mod_had_quant_i8g: norm_i8) and an attention's output gate
* writes the out projection's (gate_had_quant_i8g: gate_i8, and fgate_i8 for the fusion blocks'). */
bool norm_i8 = false, gate_i8 = false, fgate_i8 = false;
rad_weight w_fn = 0, w_pout = 0, b_pout = 0;
rad_op op_fn = 0, op_pout = 0, op_euler = 0;
rad_buf b_fz = 0, b_v = 0;
@@ -205,7 +222,7 @@ struct Model {
std::string inv_std, mean, ones, zeros;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* A space-separated list off the container (rad-convert flattens arrays that way). */
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
@@ -281,14 +298,27 @@ static rad_op zc_norm(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_we
}
/* The attention's sigmoid output gate: `gate_quant_fp8` (gate, multiply and the out projection's
* quantiser in one pass) over fp8 linears, or `sigmoid` then `mul` over bf16 ones and wherever no
* loaded library declares the fused op (the out projection's quantiser then runs on its own).
* Rows are (token, head) pairs of `head_dim` columns. Returns the gate op; `sig` is the pair's
* sigmoid, written into `g` itself. */
* quantiser in one pass) over fp8 linears, rows (token, head) pairs of `head_dim` columns; over
* rotated int8 ones (`pair`) its rotating twin `gate_had_quant_i8g`, a token a row, since one
* scale covers the codes' group across heads (`fused_i8` says so); or `sigmoid` then `mul` over
* bf16 ones and wherever no loaded library declares the fused op (the out projection's quantiser
* then runs on its own). Returns the gate op; `sig` is the pair's sigmoid, written into `g`
* itself. */
static rad_op out_gate(RadBuilder* b, const Geom& g, int64_t rows, int64_t width, rad_buf gate,
const ActFP8& attn, rad_op* sig) {
const ActFP8& attn, rad_op* sig, bool pair, bool* fused_i8) {
const int64_t hd = g.head_dim;
if (g.w_bf16 || !rad_op_declared(b, "gate_quant_fp8")) {
*fused_i8 = false;
if (pair && !g.w_bf16 && attn.q8_fed && attn.q8_rot && rad_op_declared(b, "gate_had_quant_i8g")) {
*sig = 0;
*fused_i8 = true;
return rw(b, RAD_OP(b, "gate_had_quant_i8g",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_INT("group", attn.cg()), RAD_STR("dtype", "bf16"),
RAD_STR("act", "sigmoid")),
RAD_NOWEIGHTS),
{ gate, attn.x }, { attn.cq(), attn.cs(), attn.x });
}
if (g.w_bf16 || pair || !rad_op_declared(b, "gate_quant_fp8")) {
*sig = rw(b, RAD_OP(b, "sigmoid",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
@@ -369,14 +399,17 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd });
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd });
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd, T));
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", g.n_embd, T, m.i8, m.g8,
"had_quant_act_i8g"));
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T));
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, T, m.i8, m.g8,
"had_quant_act_i8g"));
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd });
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T));
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, T, m.i8, m.g8,
"gated_had_quant_i8g"));
m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { (int64_t)kTeRows * kNTaps, g.n_embd });
m.b_tidx = decl_b(b, nm.f("te.tap_idx"), RAD_I32, { T });
@@ -579,7 +612,7 @@ static int declare_fuse_block(RadBuilder* b, Model& m, FuseBlock& F, const char*
RAD_F64("scale", 1.0 / std::sqrt((double)hd))),
RAD_NOWEIGHTS),
{ m.b_fqkv }, { m.a_fattn.x });
F.op_gq = out_gate(b, g, rows, qd, m.b_fg, m.a_fattn, &F.op_sig);
F.op_gq = out_gate(b, g, rows, qd, m.b_fg, m.a_fattn, &F.op_sig, m.i8, &m.fgate_i8);
if (F.op_sig) RAD_ARCH_TRY(F.q_attn.declare(b, g, m.a_fattn, qd));
RAD_ARCH_TRY(F.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL,
grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) },
@@ -610,15 +643,35 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
const int64_t D = g.n_embd, qd = g.q_dim();
const int64_t RL = (int64_t)kCondRows * kNTaps; /* the layer-wise blocks' rows */
m.a_fh.x = decl_b(b, nm.f("fuse.h"), RAD_BF16, { RL, D });
RAD_ARCH_TRY(m.a_fh.declare_qs(b, nm, g, "fuse.h", D, RL));
RAD_ARCH_TRY(m.a_fh.declare_pair(b, nm, g, "fuse.h", D, RL, m.i8, m.g8,
"had_quant_act_i8g"));
m.b_fqkv = decl_b(b, nm.f("fuse.qkv"), RAD_BF16, { RL, 3 * qd });
m.b_fg = decl_b(b, nm.f("fuse.gate"), RAD_BF16, { RL, qd });
m.a_fattn.x = decl_b(b, nm.f("fuse.attn"), RAD_BF16, { RL, qd });
RAD_ARCH_TRY(m.a_fattn.declare_qs(b, nm, g, "fuse.attn", qd, RL));
RAD_ARCH_TRY(m.a_fattn.declare_pair(b, nm, g, "fuse.attn", qd, RL, m.i8, m.g8,
"had_quant_act_i8g"));
m.b_fo = decl_b(b, nm.f("fuse.o"), RAD_BF16, { RL, D });
m.b_fgu = decl_b(b, nm.f("fuse.gate_up"), RAD_BF16, { RL, 2 * g.n_ff });
m.a_fffn.x = decl_b(b, nm.f("fuse.ffn"), RAD_BF16, { RL, g.n_ff });
RAD_ARCH_TRY(m.a_fffn.declare_qs(b, nm, g, "fuse.ffn", g.n_ff, RL));
/* The feed-forward product's scale group is its reader's, the first block's down projection,
* which a recipe may keep narrower than the other linears: the fusion's 6912-wide product is
* 3456 a rank at two, which whole 128s tile and whole 256s do not (krea-2-iq8r.recipe). The
* probe maps the weight through the block's own LinearFP8, which then does not map it again;
* the resizes here keep the blocks the loops below declare. */
const int nlw = (int)rad_meta_geti(meta, "transformer.num_layerwise_text_blocks", 2);
const int nrf = (int)rad_meta_geti(meta, "transformer.num_refiner_text_blocks", 2);
m.lw.resize((size_t)nlw);
m.rf.resize((size_t)nrf);
int64_t ffn_g8 = m.g8;
if (m.i8 && nlw + nrf > 0) {
LinearFP8& d0 = nlw > 0 ? m.lw[0].down : m.rf[0].down;
RAD_ARCH_TRY(d0.probe(b, nm, g, nm.f("fuse.0.ffn_down"),
{ nm.ckpt("transformer.text_fusion.%s.0.ff.down.weight",
nlw > 0 ? "layerwise_blocks" : "refiner_blocks") }));
ffn_g8 = d0.probed_g8;
}
RAD_ARCH_TRY(m.a_fffn.declare_pair(b, nm, g, "fuse.ffn", g.n_ff, RL, m.i8, ffn_g8,
"gated_had_quant_i8g"));
m.b_fcu = decl_b(b, nm.f("fuse.cu"), RAD_I32, { kCondRows + 1 });
m.b_ft = decl_b(b, nm.f("fuse.out"), RAD_BF16, { kCondRows, D });
@@ -628,10 +681,6 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
RAD_INT("step", kNTaps)),
RAD_NOWEIGHTS),
{}, { m.b_fcu });
const int nlw = (int)rad_meta_geti(meta, "transformer.num_layerwise_text_blocks", 2);
const int nrf = (int)rad_meta_geti(meta, "transformer.num_refiner_text_blocks", 2);
m.lw.resize((size_t)nlw);
m.rf.resize((size_t)nrf);
for (int i = 0; i < nlw; ++i) {
RAD_ARCH_TRY(declare_fuse_block(b, m, m.lw[(size_t)i],
nm.f("transformer.text_fusion.layerwise_blocks.%d", i),
@@ -645,7 +694,7 @@ static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) {
* served bf16 as diffusers runs them: a recipe casts them. */
if (weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16) != RAD_BF16) {
fprintf(stderr, "radiance: krea2: 'fuse.mix.weight' is stored %s; convert with "
"data/recipes/krea-2-bf16.recipe or krea-2-fp8.recipe, which cast the "
"data/recipes/krea-2-bf16.recipe or krea-2-iq8r.recipe, which cast the "
"release's f32 tensors\n",
rad_dtype_name(weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16)));
return RAD_E_UNSUPPORTED;
@@ -789,15 +838,18 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
/* ---- the blocks */
m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D });
RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D));
RAD_ARCH_TRY(m.a_hm.declare_pair(b, nm, g, "dit.hm", D, 0, m.i8, m.g8,
"had_quant_act_i8g"));
m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, qd + 2 * kvd });
m.b_g = decl_b(b, nm.f("dit.gate"), RAD_BF16, { T, qd });
m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd });
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd));
RAD_ARCH_TRY(m.a_attn.declare_pair(b, nm, g, "dit.attn", qd, 0, m.i8, m.g8,
"had_quant_act_i8g"));
m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D });
m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff });
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff));
RAD_ARCH_TRY(m.a_ffn.declare_pair(b, nm, g, "dit.ffn", g.n_ff, 0, m.i8, m.g8,
"gated_had_quant_i8g"));
const std::vector<double> ax = meta_list(meta, "transformer.axes_dims_rope");
const int64_t a0 = ax.size() == 3 ? (int64_t)ax[0] : 32, a1 = ax.size() == 3 ? (int64_t)ax[1] : 48,
@@ -811,12 +863,15 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
const double theta = rad_meta_getf(meta, "transformer.rope_theta", 1000.0);
/* The modulated norm, gated by the branch before it when `gated`, into the next linear's
* input (codes for fp8, the bf16 plane for bf16). */
* input: codes for fp8 and, where the rotating twin is served, for rotated int8; the bf16
* plane for bf16 and for rotated int8 without the twin, whose codes the rotating quantiser
* then takes from it (DitLayer::q_n1 / q_n2). */
m.norm_i8 = m.i8 && m.a_hm.q8_fed && rad_op_declared(b, "rms_mod_had_quant_i8g") != 0;
auto mod_norm = [&](rad_weight w, bool gated) {
const bool q = !g.w_bf16;
rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8",
const bool q = (!g.w_bf16 && !m.i8) || m.norm_i8;
rad_op op = q ? RAD_OP(b, m.norm_i8 ? "rms_mod_had_quant_i8g" : "rms_mod_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_INT("group", m.norm_i8 ? m.g8 : RAD_FP8_BLOCK),
RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"),
RAD_F64("wadd", 1.0), RAD_INT("norm_once", 1)),
RAD_WEIGHTS(w))
@@ -827,7 +882,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
RAD_WEIGHTS(w));
if (!op) return op;
rad_buf rd[3] = { m.b_mods, m.b_h, m.b_ao };
rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h };
rad_buf wq[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h };
rad_buf wb[2] = { m.a_hm.x, m.b_h };
rad_op_reads(b, op, rd, gated ? 3 : 2);
if (q) rad_op_writes(b, op, wq, 3);
@@ -866,6 +921,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
if (!B.w_tab || !B.op_tab) return RAD_E_INVAL;
}
B.op_n1 = mod_norm(B.w_n1, l > 0);
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n1.declare(b, g, m.a_hm, D));
if (l == 0) B.qkv = m.qkv0;
RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), qd + 2 * kvd, D,
RAD_SHARD_ROW, grp_layer(grp),
@@ -893,13 +949,14 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
RAD_F64("scale", 1.0 / std::sqrt((double)hd))),
RAD_NOWEIGHTS),
{ m.b_qkv }, { m.a_attn.x });
B.op_gq = out_gate(b, g, T, qd, m.b_g, m.a_attn, &B.op_sig);
B.op_gq = out_gate(b, g, T, qd, m.b_g, m.a_attn, &B.op_sig, m.i8, &m.gate_i8);
if (B.op_sig) RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd));
RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL,
grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) },
m.a_attn, m.b_ao));
B.op_ar1 = all_reduce(b, g, m.b_ao, T);
B.op_n2 = mod_norm(B.w_n2, true);
if (m.i8 && m.a_hm.q8_fed && !m.norm_i8) RAD_ARCH_TRY(B.q_n2.declare(b, g, m.a_hm, D));
RAD_ARCH_TRY(B.gate_up.declare(b, nm, g, nm.f("%s.ffn_gate_up", dn), 2 * g.n_ff, D,
RAD_SHARD_ROW, grp_layer(grp),
{ nm.ckpt("%s.ff.gate.weight", pre),
@@ -1090,8 +1147,9 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
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];
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(check_format(meta));
@@ -1150,9 +1208,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
"transformer.transformer_blocks.0.attn.to_k.weight",
"transformer.transformer_blocks.0.attn.to_v.weight" }));
RadEncoding e{};
const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) &&
rad_enc_is(&e, "plain");
const bool known = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e);
const bool plain = known && rad_enc_is(&e, "plain");
gd.w_bf16 = gf.w_bf16 = m.gt.w_bf16 = plain;
/* Or rotated int8 (IQ8R): the activations then carry int8 codes at the weights' scale
* group in place of the E4M3 pair (ActFP8::declare_pair). */
m.i8 = known && (linear_is_w8h(e) || linear_is_wnh(e));
if (m.i8) m.g8 = linear_w8h_group(e);
}
/* ---- the per-image state, the conditioning store, and in issue order the language model,
@@ -1220,7 +1282,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.gt.rank, m.gt.world, m.turbo ? " Turbo" : "", kTaps[kNTaps - 1],
(long long)m.gt.n_layer, m.lw.size(), m.rf.size(), (long long)gd.n_layer,
(long long)gd.n_head, (long long)gd.n_head_kv, (long long)gd.n_ff,
gd.w_bf16 ? "bf16" : "block-fp8");
gd.w_bf16 ? "bf16" : m.i8 ? "rotated int8" : "block-fp8");
return RAD_OK;
}
@@ -1284,6 +1346,9 @@ static void step_fuse(RadCtx* c, const Model& m, const FuseBlock& F, int64_t r0,
RAD_ISSUE_N(c, F.op_sig, R, brows(m.b_fg, R), brows(m.b_fg, R));
RAD_ISSUE_N(c, F.op_gq, R, brows(m.a_fattn.x, R), brows(m.b_fg, R), brows(m.a_fattn.x, R));
F.q_attn.step(c, R);
} else if (m.fgate_i8) {
RAD_ISSUE_N(c, F.op_gq, R, brows(m.b_fg, R), brows(m.a_fattn.x, R),
brows(m.a_fattn.cq(), R), brows(m.a_fattn.cs(), R), brows(m.a_fattn.x, R));
} else {
const int64_t rh = R * (qd / hd), nb = hd / RAD_FP8_BLOCK;
RAD_ISSUE_N(c, F.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_fg), RAD_BF16, rh, hd),
@@ -1368,7 +1433,7 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
const RadOperand pos = praw2(G->rope_f, RAD_F32, 4, N);
auto mod = [&](int64_t l, int k, int width) { return bcol_at(m.b_mods, 0, W, (6 * l + k) * D,
width * D, S); };
const bool q8 = !g.w_bf16;
const bool q8 = (!g.w_bf16 && !m.i8) || m.norm_i8;
for (int64_t l = 0; l < L; ++l) {
const DitLayer& B = m.dit[(size_t)l];
/* The block's modulation: the shared projection plus its own table, into its columns. */
@@ -1377,11 +1442,13 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
if (q8)
RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE,
l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu,
brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE);
brows(m.b_h, N), brows(m.a_hm.cq(), N), brows(m.a_hm.cs(), N),
RAD_NONE);
else
RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE,
l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu,
brows(m.b_h, N), brows(m.a_hm.x, N));
B.q_n1.step(c, N);
B.qkv.step(c, m.a_hm, m.b_qkv, N);
B.gate.step(c, m.a_hm, m.b_g, N);
RAD_ISSUE_N(c, B.op_qkr, N, brows(m.b_qkv, N), pos, RAD_W(B.w_qn), RAD_W(B.w_kn));
@@ -1391,6 +1458,9 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
RAD_ISSUE_N(c, B.op_sig, N, brows(m.b_g, N), brows(m.b_g, N));
RAD_ISSUE_N(c, B.op_gq, N, brows(m.a_attn.x, N), brows(m.b_g, N), brows(m.a_attn.x, N));
B.q_attn.step(c, N);
} else if (m.gate_i8) {
RAD_ISSUE_N(c, B.op_gq, N, brows(m.b_g, N), brows(m.a_attn.x, N),
brows(m.a_attn.cq(), N), brows(m.a_attn.cs(), N), brows(m.a_attn.x, N));
} else {
const int64_t rh = N * (qd / hd), nb = hd / RAD_FP8_BLOCK;
RAD_ISSUE_N(c, B.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_g), RAD_BF16, rh, hd),
@@ -1403,10 +1473,12 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
if (B.op_ar1) RAD_ISSUE_N(c, B.op_ar1, N * D, brows(m.b_ao, N), RAD_NONE);
if (q8)
RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2),
cu, brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE);
cu, brows(m.b_h, N), brows(m.a_hm.cq(), N), brows(m.a_hm.cs(), N),
RAD_NONE);
else
RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2),
cu, brows(m.b_h, N), brows(m.a_hm.x, N));
B.q_n2.step(c, N);
B.gate_up.step(c, m.a_hm, m.b_gu, N);
B.gq.step(c, m.b_gu, N);
B.down.step(c, m.a_ffn, m.b_ao, N);
@@ -1467,7 +1539,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
if (!batch->gen || !batch->gen_b) {
rad_step_fail(c, "krea2 is an image generator and runs generator passes only");
return;
@@ -1493,6 +1565,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(krea2)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(krea2, "krea2", "", "0.1.0",
"Krea 2 / Krea 2 Turbo: Qwen3-VL-4B taps through a text-fusion transformer, a 12.9B "
"single-stream diffusion transformer over the joint text and image, and Wan 2.1's "
+7 -4
View File
@@ -74,7 +74,7 @@ struct Model {
std::vector<HeadLayer> head;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
@@ -115,7 +115,8 @@ static int sliding_layers(const RadModelMeta* meta, int64_t n_layer, std::vector
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: laya runs on one card (--tp 1); the largest checkpoint is "
"0.4B parameters\n");
@@ -124,7 +125,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RadArchProbe pr{};
RAD_ARCH_TRY(probe(meta, &pr));
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
@@ -409,7 +410,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
const Geom& g = m.g;
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd, F = m.F;
const int64_t P = RAD_LAYA_POOLED;
@@ -523,6 +524,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
} /* namespace laya */
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(laya, "laya", "", "0.1.0",
"Convai Innovations' Laya (laya, laya-typed-decisions, laya-multilingual): a "
"ModernBERT encoder and a decision head scoring each option at its [MASK], one "
+38 -11
View File
@@ -28,8 +28,9 @@
* block E4M3 (`codes=fp8_e4m3 block=128x128 scale=bf16`) is `gemm_nt_q` at fp8a8 over the
* activation quantised per 128 columns (one quant_act_fp8 per activation, shared by the linears
* that read it); int8 (`codes=i8 group=128 scale=bf16`) is `gemm_nt_q` at i8a8, each linear
* quantising its input. The trunk's format is read off layer 0's down projection and every linear
* must match it. The convolution, the norms and attention stay bf16; the lm_head is read at its
* quantising its input, and IQ8R (rotated int8 with a scale per 256 of K,
* data/recipes/d1-3b-iq8r.recipe) the same at i8a8h with the activation pairs at the weights'
* group. The trunk's format is read off layer 0's first linear and every linear must match it. The convolution, the norms and attention stay bf16; the lm_head is read at its
* stored codes (bf16, or E4M3 / int8 where a recipe made it so; logits_gemm_fp8 / _i8). At d1-3B
* the linears are 5.8 of the 6.3 GB a token reads, so 8-bit codes nearly halve decode and short
* prefill, both bound by that read.
@@ -106,6 +107,8 @@ struct Model {
/* The trunk's format, read off layer 0's first linear. `fused`: the fp8 trunk's fused
* producers (see the head of the file). */
bool q_fp8 = false, q_i8 = false, fused = false;
/* An int8 trunk's scale group along K, which its activation pairs share (ActFP8::g8). */
int64_t g8 = RAD_FP8_BLOCK;
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;
@@ -118,7 +121,7 @@ struct Model {
MediaRows mrows{};
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* A text_config key first, then the top level: a VL checkpoint nests the text model's settings
* and a text checkpoint does not. */
@@ -166,7 +169,9 @@ static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Lay
}
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 (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS ||
rad_build_slot(ctx) >= MAX_SLOTS)
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;
@@ -178,7 +183,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
Names& nm = m.nm;
@@ -290,14 +295,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
enc.plane[0].dtype == RAD_BF16);
g.w_bf16 = plain;
m.q_i8 = !plain && L0.in.probed_i8;
if (m.q_i8) m.g8 = L0.in.probed_g8;
m.q_fp8 = !plain && !m.q_i8;
m.fused = m.q_fp8;
}
if (m.q_i8 && (g.n_embd % m.g8 || g.q_dim() % m.g8 || g.n_ff % m.g8)) {
fprintf(stderr, "radiance: lfm2: the int8 trunk keeps one scale a %lld of K, which does not "
"divide this model's widths (hidden %lld, attention %lld, feed-forward "
"%lld)\n",
(long long)m.g8, (long long)g.n_embd, (long long)g.q_dim(), (long long)g.n_ff);
return RAD_E_UNSUPPORTED;
}
m.a_h.x = m.b_h; m.a_attn.x = m.b_attn; m.a_conv.x = m.b_conv_out; m.a_ffn.x = m.b_ffn;
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8));
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8));
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8));
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8));
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8, true, m.g8));
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8, true, m.g8));
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8, true, m.g8));
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8, true, m.g8));
/* An E4M3 activation is quantised once by the model and read by every linear on it; an int8
* linear quantises its own input (LinearFP8::op_q), and a bf16 one reads the bf16 plane. */
auto quant = [&](QuantFP8& q, const ActFP8& a, int64_t n) {
@@ -471,7 +484,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
ms.up = nm.ckpt(ffn_fmt, pre, l, "w3.weight");
ms.down = nm.ckpt(ffn_fmt, pre, l, "w2.weight");
const bool last = l + 1 == (int)m.layers.size();
/* The whole prompt in the fold: gemm_nt_q_gated_wide serves every M, so a prefill
/* The whole prompt in the fold (`wide_fold`): its row serves every M, so a prefill
* chunk does not fall back to the pair past 64 rows. */
RAD_ARCH_TRY(L.mlp8.declare(b, nm, g, l, mw, ms, /*fold=*/true, /*add_out=*/last,
0, false, 0, /*wide_fold=*/true));
@@ -572,7 +585,7 @@ static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch*
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
const Geom& g = m.g;
if (batch->draft_pass || batch->spec_parent ||
(!m.media && (batch->enc || batch->n_mm_rows > 0))) {
@@ -663,9 +676,23 @@ static void step(RadCtx* c, const RadBatch* batch) {
}
}
/* Chained launches pay on the plain-bf16 trunk: its GEMMs, norms and elementwise kernels have
* chained forms (libr4d's rad_kernel_chain); the head norms, the rotary and the convolution keep
* their plain rows, with which the long GEMMs between them run faster. The 3B text model on one
* R9700, ms a decode step unchained / chained: 12.14 / 11.31 at one sequence and 12.54 / 11.60 at
* four. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->chain_pays = RAD_CHAIN_ALWAYS;
return RAD_OK;
}
} /* namespace lfm2_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PROBE(lfm2_bf16)
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.2.0",
"LiquidAI LFM2 / LFM2-VL, bf16, or with block-fp8 or int8 linears from a recipe: "
"short gated convolutions and GQA attention in the checkpoint's own schedule, one "
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/lfm3_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(lfm3_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(lfm3_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/lfm3_bf16.cpp)
+779
View File
@@ -0,0 +1,779 @@
/* lfm3_bf16 -- LiquidAI's LFM3, bf16 activations over bf16 or int8 (IQ8R) linears, one rank.
*
* ============================== THE SHAPE ==============================
*
* LFM2's hybrid with a third layer kind, in the order the checkpoint's `layer_types` lists them
* (read, not derived):
*
* 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, a partial NeoX rotary on the "head"
* ladder (the first `partial_rotary_factor * head_dim` channels rotate, at the
* frequencies of the whole head; the rest do not), and a gate per query head
* sliding_attention the same attention over the last `sliding_window` tokens, its rotary over
* the whole head at its own theta
*
* each followed by a SwiGLU feed-forward (w1 the gate, w3 the up, w2 the down). The norms are a
* sandwich: `operator_norm` before the mixer and `post_operator_norm` on its output, before the
* residual add; `ffn_norm` and `post_ffn_norm` likewise. Every norm is a plain RMSNorm
* (`x_hat * w`), and the final one is `embedding_norm`. A post norm, its add and the norm that
* reads the sum are one `norm_add_norm` where a library serves it (Gemma's sandwich join; see
* declare). At 1.7B: 24 layers (13 conv, 6 full, 5
* sliding with a window of 256), hidden 2048, 16 heads over 4 at head_dim 128, ffn 7680,
* vocabulary 128000 with the lm_head tied to the embedding, conv width 7; theta 1e6 over half the
* head on the full layers, 1e4 on the sliding ones.
*
* ============================== THE GATE ==============================
*
* The attention output of each query head is multiplied by sigmoid(gate_proj(h)), one scalar a
* (token, head), before the out projection. `mul` multiplies planes of equal width, so the gate
* is computed at the output's width: the name map repeats each of gate_proj's n_head rows head_dim
* times (RAD_MAP_ROWS), and `gemm_nt` + `sigmoid` + `mul` then give every channel of a head that
* head's gate, with the reference's rounding (the gate and the product are each a bf16 tensor
* there). It costs n_embd * (q_dim - n_head) stored weights an attention layer, 2.6% of the
* container at 1.7B.
*
* ============================== 8-BIT LINEARS ==============================
*
* Every linear but the gate is a LinearFP8 (rad_fp8.h), as lfm2_bf16's are, so the container's
* encoding of each weight decides the GEMM: plain bf16 is `gemm_nt` over the bf16 activation,
* exactly as a bf16 model runs; int8 (`codes=i8 group=128 scale=bf16`) is `gemm_nt_q` at i8a8, and
* the rotated form (those codes under the 128-wide Hadamard, data/recipes/lfm3-1.7b-iq8r.recipe,
* or IQ8R's scale per 256 of K) the same at i8a8h, each linear quantising its input from
* the bf16 plane. The trunk's format is read off layer 0's first linear and every linear must
* match it. The gate stays bf16 in every container (n_head distinct rows; its product is a hard
* multiplier on a whole head), as do the convolution, the norms, the joins and attention. The
* lm_head is read at its stored codes.
*
* ============================== WHAT IT DOES NOT SERVE ==============================
*
* Tensor parallelism (the model needs one card), block-fp8 or narrower linears, a trunk that mixes
* formats, a quantised gate, a drafter, media, conv bias, a checkpoint without the sandwich norms,
* or a rotary other than the default type: each is refused by name.
*/
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <cmath>
#include <sstream>
#include <string>
#include <vector>
namespace lfm3_bf16 {
using namespace rad::arch;
enum Kind { kConv = 0, kFull = 1, kSliding = 2 };
/* One plain bf16 linear: its weight and the gemm_nt over it. The attention gate is the one linear
* declared this way: its weight is gate_proj's rows repeated, which the shared LinearFP8 that
* serves every other linear does not map. */
struct Linear {
rad_weight w = 0;
rad_op op = 0;
};
/* What differs between the two attention classes. */
struct AttnClass {
double theta = 0.0;
int64_t rot = 0; /* rotary_dim */
int64_t window = 0; /* 0: full */
rad_kvgroup kv = 0;
};
struct Layer {
Kind kind = kConv;
rad_weight w_norm = 0, w_post_norm = 0, w_ffn_norm = 0, w_ffn_post_norm = 0;
rad_op op_norm = 0, op_post_norm = 0, op_add = 0;
/* conv */
LinearFP8 conv_in, conv_out;
rad_weight w_conv = 0;
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
/* attention */
LinearFP8 q, k, v, out;
Linear gate;
rad_weight w_q_norm = 0, w_k_norm = 0;
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
rad_op op_store = 0, op_attn = 0, op_sigmoid = 0, op_gate_mul = 0;
/* the feed-forward: norm, gate|up (w1 | w3), SiLU(gate) * up, down (w2), norm, residual add */
LinearFP8 gate_up, down;
rad_op op_ffn_norm = 0, op_act = 0, op_ffn_post_norm = 0, op_ffn_add = 0;
/* The sandwich joins, fused: op_join is post_norm + add + ffn_norm, and op_ffn_join is
* ffn_post_norm + ffn_add + the next layer's norm, which that layer then does not declare. */
rad_op op_join = 0, op_ffn_join = 0;
};
struct Model {
Names nm{""};
Geom g{};
int64_t width = 0; /* conv_L_cache: the convolution's taps */
AttnClass full{}, sliding{};
rad_kvgroup kv_conv = 0;
rad_buf b_x = 0, b_h = 0, b_arm = 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 = 0, b_gate_up = 0, b_ffn = 0;
rad_buf b_hout = 0, b_logits = 0;
/* The four activations a linear reads, as LinearFP8 takes them: the bf16 plane is the buffer
* above. */
ActFP8 a_h{}, a_attn{}, a_conv{}, a_ffn{};
/* An int8 trunk (i8a8, or IQ8R at i8a8h), and its scale group along K, which the activations'
* int8 pairs share (ActFP8::g8). */
bool q_i8 = false;
int64_t g8 = RAD_FP8_BLOCK;
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;
const AttnClass& cls(const Layer& L) const { return L.kind == kSliding ? sliding : full; }
};
static Model g_model[MAX_SLOTS];
static int64_t meta_int(const RadModelMeta* m, const char* key, int64_t dflt) {
const char* v = rad_meta_gets(m, key, nullptr);
return v ? std::strtoll(v, nullptr, 10) : dflt;
}
static double meta_f64(const RadModelMeta* m, const char* key, double dflt) {
const char* v = rad_meta_gets(m, key, nullptr);
return v ? std::strtod(v, nullptr) : dflt;
}
static bool meta_bool(const RadModelMeta* m, const char* key, bool dflt) {
const char* v = rad_meta_gets(m, key, nullptr);
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 = rad_meta_gets(m, "layer_types", nullptr);
if (!s || !*s) {
fprintf(stderr, "radiance: lfm3: the container has no layer_types; this family's schedule "
"is read, not derived\n");
return RAD_E_FORMAT;
}
std::istringstream in(s);
std::string kind;
while (in >> kind) {
Layer l;
if (kind == "conv") l.kind = kConv;
else if (kind == "full_attention") l.kind = kFull;
else if (kind == "sliding_attention") l.kind = kSliding;
else {
fprintf(stderr, "radiance: lfm3: layer_types[%zu] is '%s'; this plugin knows 'conv', "
"'full_attention' and 'sliding_attention'\n", out->size(), kind.c_str());
return RAD_E_UNSUPPORTED;
}
out->push_back(l);
}
if ((int64_t)out->size() != n_layer) {
fprintf(stderr, "radiance: lfm3: layer_types names %zu layers and the model has %lld\n",
out->size(), (long long)n_layer);
return RAD_E_FORMAT;
}
return RAD_OK;
}
/* One class's rotary from `rope_parameters.<type>`: theta is required (the typed rope_theta is a
* top-level key this family does not write), the type must be the default, and the partial factor
* gives an even rotary width inside the head. */
static int read_rotary(const RadModelMeta* m, const char* type, int64_t head_dim, AttnClass* c) {
const std::string pre = std::string("rope_parameters.") + type + ".";
const char* rt = rad_meta_gets(m, (pre + "rope_type").c_str(), "default");
if (std::strcmp(rt, "default") != 0) {
fprintf(stderr, "radiance: lfm3: rope_parameters.%s.rope_type '%s' is not 'default'\n",
type, rt);
return RAD_E_UNSUPPORTED;
}
c->theta = meta_f64(m, (pre + "rope_theta").c_str(), 0.0);
if (!(c->theta > 0.0)) {
fprintf(stderr, "radiance: lfm3: rope_parameters.%s.rope_theta is required\n", type);
return RAD_E_INVAL;
}
const double prf = meta_f64(m, (pre + "partial_rotary_factor").c_str(), 1.0);
/* the reference's int(prf * head_dim) // 2 angles */
c->rot = 2 * ((int64_t)(prf * (double)head_dim) / 2);
if (!(prf > 0.0) || c->rot < 2 || c->rot > head_dim) {
fprintf(stderr, "radiance: lfm3: rope_parameters.%s.partial_rotary_factor %g gives a "
"rotary width %lld outside 2..head_dim\n", type, prf, (long long)c->rot);
return RAD_E_INVAL;
}
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 ||
rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: lfm3_bf16 serves one rank; run it with --tp 1\n");
return RAD_E_UNSUPPORTED;
}
if (meta->n_expert > 0 || meta_bool(meta, "conv_bias", false) ||
!meta_bool(meta, "use_sandwich_norm", true)) {
fprintf(stderr, "radiance: lfm3_bf16 serves the dense SwiGLU model with sandwich norms, "
"gated attention and bias-free convolutions; this checkpoint is not that\n");
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
Names& nm = m.nm;
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
Geom& g = m.g;
RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &m.layers));
m.width = meta_int(meta, "conv_L_cache", 0);
if (m.width < 2 || m.width > 8) {
fprintf(stderr, "radiance: lfm3: conv_L_cache %lld is outside the 2..8 the convolution "
"kernels serve\n", (long long)m.width);
return RAD_E_UNSUPPORTED;
}
bool has_full = false, has_sliding = false, has_conv = false;
for (const Layer& L : m.layers) {
has_full |= L.kind == kFull;
has_sliding |= L.kind == kSliding;
has_conv |= L.kind == kConv;
}
if (has_full) RAD_ARCH_TRY(read_rotary(meta, "full_attention", g.head_dim, &m.full));
if (has_sliding) {
RAD_ARCH_TRY(read_rotary(meta, "sliding_attention", g.head_dim, &m.sliding));
m.sliding.window = meta_int(meta, "sliding_window", 0);
if (m.sliding.window < 1) {
fprintf(stderr, "radiance: lfm3: the sliding_attention layers need a sliding_window, "
"and the container has %lld\n", (long long)m.sliding.window);
return RAD_E_INVAL;
}
}
const char* pre = "model";
/* ---- the state groups: paged KV for the full layers, the same bounded by the window for the
* sliding ones, 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. */
const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16);
g.kv_dtype = rad_dtype_name(kvdt);
if (has_full) {
RadKVGroupDecl fd{};
fd.kind = RAD_KV_FULL;
fd.dtype = kvdt;
fd.n_head_kv = g.n_head_kv;
fd.head_dim = g.head_dim;
m.full.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
if (!m.full.kv) return RAD_E_INVAL;
}
if (has_sliding) {
RadKVGroupDecl sd{};
sd.kind = RAD_KV_WINDOW;
sd.dtype = kvdt;
sd.window = m.sliding.window;
sd.n_head_kv = g.n_head_kv;
sd.head_dim = g.head_dim;
m.sliding.kv = rad_decl_kv_group(b, nm.f("kv_sliding"), &sd);
if (!m.sliding.kv) return RAD_E_INVAL;
}
if (has_conv) {
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_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});
/* a mixer's or a feed-forward's output, before its post norm: a join reads it beside x and
* writes h, so it is not h */
m.b_arm = decl_b(b, nm.f("arm"), 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 = decl_b(b, nm.f("attn_gate"), 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 trunk's format, read off layer 0's first linear before any activation is declared
* (probe() makes its name map and reads its encoding). Plain bf16, or no encoding yet, is a
* bf16 trunk: every linear is `gemm_nt` over its input's bf16 plane. An int8 weight makes the
* activations carry int8 codes beside it. */
{
Layer& L0 = m.layers[0];
const bool at = L0.kind != kConv;
LinearFP8& first = at ? L0.q : L0.conv_in;
const char* base0 = nm.f(at ? "blk.%d.attn_q" : "blk.%d.conv_in", 0);
RAD_ARCH_TRY(first.probe(b, nm, g, base0,
{ nm.ckpt(at ? "%s.layers.%d.self_attn.%s" : "%s.layers.%d.conv.%s",
pre, 0, at ? "q_proj.weight" : "in_proj.weight") }));
RadEncoding enc{};
const bool known = weight_enc(b, nm.f("%s.weight", base0), &enc);
const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
enc.plane[0].dtype == RAD_BF16);
g.w_bf16 = plain;
m.q_i8 = !plain && first.probed_i8;
if (m.q_i8) m.g8 = first.probed_g8;
if (!plain && !m.q_i8) {
char en[256];
rad_enc_format(&enc, en, sizeof en);
fprintf(stderr, "radiance: lfm3: '%s.weight' is %s; this plugin serves a bf16 trunk or "
"an int8 one (codes=i8 group=128, or IQ8R)\n", base0, en);
return RAD_E_DTYPE;
}
}
if (m.q_i8 && (g.n_embd % m.g8 || g.q_dim() % m.g8 || g.n_ff % m.g8)) {
fprintf(stderr, "radiance: lfm3: the int8 trunk keeps one scale a %lld of K, which does not "
"divide this model's widths (hidden %lld, attention %lld, feed-forward "
"%lld)\n",
(long long)m.g8, (long long)g.n_embd, (long long)g.q_dim(), (long long)g.n_ff);
return RAD_E_UNSUPPORTED;
}
m.a_h.x = m.b_h; m.a_attn.x = m.b_attn; m.a_conv.x = m.b_conv_out; m.a_ffn.x = m.b_ffn;
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8, false, m.g8));
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8, false, m.g8));
RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8, false, m.g8));
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8, false, m.g8));
/* ---- 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. */
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());
/* The head at its codes' dtype: bf16, or int8 where a recipe made it so. */
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_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});
/* `op`: "rmsnorm", or "rmsnorm_rows" for the head norms, whose short-row form a prefill's
* thousands of head_dim-wide rows take. */
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out,
const char* op = "rmsnorm") {
return rw(b, RAD_OP(b, op,
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 add = [&](rad_buf x, rad_buf h) {
return 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),
{x, h}, {x});
};
auto mul = [&](std::initializer_list<rad_buf> rd, rad_buf out, int64_t n) {
return rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
rd, {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));
};
/* A norm's gain: mapped, and declared f32. */
auto norm_w = [&](rad_weight* w, const char* name, int l, const char* src, int64_t n) -> int {
RAD_ARCH_TRY(map_copy(b, nm.f(name, l), src));
*w = layer_w(name, l, {n}, RAD_F32);
return *w ? RAD_OK : RAD_E_INVAL;
};
/* The gate: one plain bf16 linear over an already mapped weight, in every container. */
auto plain_linear = [&](Linear& lin, int l, const char* name, int64_t N, int64_t K, rad_buf in,
rad_buf out) -> int {
RadEncoding enc{};
if (weight_enc(b, nm.f(name, l), &enc) &&
!(rad_enc_is(&enc, "plain") && enc.n_planes == 1 && enc.plane[0].dtype == RAD_BF16)) {
char en[256];
rad_enc_format(&enc, en, sizeof en);
fprintf(stderr, "radiance: lfm3: '%s' is %s; the attention gate stays bf16 (leave "
"gate_proj out of the recipe)\n", nm.f(name, l), en);
return RAD_E_DTYPE;
}
lin.w = decl_w(b, nm.f(name, l), RAD_BF16, {N, K}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
if (!lin.w) return RAD_E_INVAL;
lin.op = 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(lin.w)),
{in}, {out});
return lin.op ? RAD_OK : RAD_E_INVAL;
};
/* One linear: `base` is the declared name without `.weight`, `src` its checkpoint tensor (or
* the tensors stacked along its rows, `parts` their row counts), `a` the activation it reads. */
auto linear = [&](LinearFP8& lin, int l, const char* base_fmt, int64_t N, int64_t K,
std::initializer_list<const char*> src, const ActFP8& a, rad_buf y,
std::initializer_list<int64_t> parts) -> int {
const char* base = nm.f(base_fmt, l);
RAD_ARCH_TRY(lin.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(l), src, a, y, 0,
parts));
/* Every linear has the trunk's format. LinearFP8 refuses a quantised weight in a bf16
* trunk; this refuses a bf16 or narrower one in an int8 trunk. */
if (g.w_bf16 ? !lin.bf16 : !(lin.i8 && !lin.iqr)) {
fprintf(stderr, "radiance: lfm3: '%s.weight' is not in the trunk's format (%s); "
"quantise every linear of the trunk alike\n",
base, g.w_bf16 ? "bf16" : "int8");
return RAD_E_DTYPE;
}
return RAD_OK;
};
/* q names its query heads; k is rotated as a q-only row of the kv heads (its own buffer).
* The partial rotary is on the "head" ladder; over the whole head the ladders coincide and
* the parameter is left out. */
auto rope = [&](const AttnClass& c, int64_t heads, rad_buf buf) {
const RadParam ps[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0),
RAD_F64("theta", c.theta), RAD_F64("scale", 1.0),
RAD_STR("mode", "neox"), RAD_INT("rotary_dim", c.rot),
RAD_STR("ladder", "head") };
const int n = (int)(sizeof ps / sizeof ps[0]) - (c.rot < g.head_dim ? 0 : 1);
return rw(b, rad_decl_op(b, "rope_rows", ps, n, nullptr, 0), {buf}, {buf});
};
/* ---- the sandwich joins. `norm_add_norm` is a post norm, the residual add and the norm that
* reads the sum in one launch: post_norm + add + ffn_norm inside a layer, and ffn_post_norm +
* add + the next layer's norm between two. It rounds where the chain rounds. The device
* libraries serve it and libref and libavx do not, and declaring an op no loaded library
* declares is an error, so it is asked for first; without it, or where it does not resolve,
* the rmsnorm / add / rmsnorm chain runs. The last layer's feed-forward keeps the chain: the
* final norm is on the gathered rows. */
const bool has_join = rad_op_declared(b, "norm_add_norm") != 0;
auto join = [&](rad_weight w_a, rad_weight w_y) {
return rw(b, RAD_OP(b, "norm_add_norm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_a, w_y)),
{m.b_arm, m.b_x}, {m.b_x, m.b_h});
};
int n_joins = 0;
/* Every layer's input norm gain, ahead of the layers: a feed-forward join names the next
* layer's, and an op can only name weights already declared. */
for (int l = 0; l < (int)m.layers.size(); ++l)
RAD_ARCH_TRY(norm_w(&m.layers[(size_t)l].w_norm, "blk.%d.attn_norm.weight", l,
nm.ckpt("%s.layers.%d.%s", pre, l, "operator_norm.weight"), g.n_embd));
for (int l = 0; l < (int)m.layers.size(); ++l) {
Layer& L = m.layers[(size_t)l];
const char* lay = "%s.layers.%d.%s";
RAD_ARCH_TRY(norm_w(&L.w_post_norm, "blk.%d.attn_post_norm.weight", l,
nm.ckpt(lay, pre, l, "post_operator_norm.weight"), g.n_embd));
RAD_ARCH_TRY(norm_w(&L.w_ffn_norm, "blk.%d.ffn_norm.weight", l,
nm.ckpt(lay, pre, l, "ffn_norm.weight"), g.n_embd));
RAD_ARCH_TRY(norm_w(&L.w_ffn_post_norm, "blk.%d.ffn_post_norm.weight", l,
nm.ckpt(lay, pre, l, "post_ffn_norm.weight"), g.n_embd));
/* written by the layer before, where its feed-forward join is fused */
if (!(l > 0 && m.layers[(size_t)l - 1].op_ffn_join))
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
if (L.kind != kConv) {
const AttnClass& c = m.cls(L);
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, c.kv));
const char* a = "%s.layers.%d.self_attn.%s";
/* The gate at the output's width: row h of gate_proj, head_dim times, for each head
* in turn (see the head of the file). Successive ROWS maps extend the weight. */
{
const std::string dst = nm.f("blk.%d.attn_gate.weight", l);
const std::string src = nm.ckpt(a, pre, l, "gate_proj.weight");
for (int64_t h = 0; h < g.n_head; ++h)
for (int64_t d = 0; d < g.head_dim; d += 8) {
RadNameMap mp = map_base(dst.c_str(), RAD_MAP_ROWS);
for (int64_t i = d; i < g.head_dim && i < d + 8; ++i) {
mp.src[mp.n_src] = src.c_str();
mp.src_index[mp.n_src] = (int)h;
mp.src_rows[mp.n_src] = 1;
++mp.n_src;
}
RAD_ARCH_TRY(rad_decl_name_map(b, &mp));
}
}
RAD_ARCH_TRY(linear(L.q, l, "blk.%d.attn_q", g.q_dim(), g.n_embd,
{ nm.ckpt(a, pre, l, "q_proj.weight") }, m.a_h, m.b_q, {}));
RAD_ARCH_TRY(linear(L.k, l, "blk.%d.attn_k", g.kv_dim(), g.n_embd,
{ nm.ckpt(a, pre, l, "k_proj.weight") }, m.a_h, m.b_k, {}));
RAD_ARCH_TRY(linear(L.v, l, "blk.%d.attn_v", g.kv_dim(), g.n_embd,
{ nm.ckpt(a, pre, l, "v_proj.weight") }, m.a_h, m.b_v, {}));
RAD_ARCH_TRY(plain_linear(L.gate, l, "blk.%d.attn_gate.weight", g.q_dim(), g.n_embd,
m.b_h, m.b_gate));
RAD_ARCH_TRY(norm_w(&L.w_q_norm, "blk.%d.attn_q_norm.weight", l,
nm.ckpt(a, pre, l, "q_norm.weight"), g.head_dim));
RAD_ARCH_TRY(norm_w(&L.w_k_norm, "blk.%d.attn_k_norm.weight", l,
nm.ckpt(a, pre, l, "k_norm.weight"), g.head_dim));
/* 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,
"rmsnorm_rows");
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,
"rmsnorm_rows");
L.op_rope_q = rope(c, g.n_head, m.b_q);
L.op_rope_k = rope(c, g.n_head_kv, 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", c.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),
{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, c.kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{m.b_k, m.b_v}, {});
L.op_sigmoid = rw(b, RAD_OP(b, "sigmoid",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.q_dim()),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_gate}, {m.b_gate});
L.op_gate_mul = mul({m.b_gate, m.b_attn}, m.b_attn, g.q_dim());
RAD_ARCH_TRY(linear(L.out, l, "blk.%d.attn_output", g.n_embd, g.q_dim(),
{ nm.ckpt(a, pre, l, "o_proj.weight") }, m.a_attn, m.b_arm, {}));
} 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.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
RAD_ARCH_TRY(linear(L.conv_in, l, "blk.%d.conv_in", 3 * g.n_embd, g.n_embd,
{ nm.ckpt(c, pre, l, "in_proj.weight") }, m.a_h, m.b_bcx, {}));
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
* convert, as LFM2's is. */
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
L.op_gate_in = mul({m.b_bcx}, m.b_conv_in, g.n_embd);
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 = mul({m.b_bcx, m.b_conv_out}, m.b_conv_out, g.n_embd);
RAD_ARCH_TRY(linear(L.conv_out, l, "blk.%d.conv_out", g.n_embd, g.n_embd,
{ nm.ckpt(c, pre, l, "out_proj.weight") }, m.a_conv, m.b_arm, {}));
}
/* the sandwich: the mixer's output is normed before it joins the stream, and the
* feed-forward reads the norm of the sum */
if (has_join) L.op_join = join(L.w_post_norm, L.w_ffn_norm);
if (!L.op_join) {
L.op_post_norm = rmsnorm(g.max_tok, g.n_embd, L.w_post_norm, m.b_arm, m.b_arm);
L.op_add = add(m.b_x, m.b_arm);
L.op_ffn_norm = rmsnorm(g.max_tok, g.n_embd, L.w_ffn_norm, m.b_x, m.b_h);
}
/* ---- the feed-forward */
const char* ffn = "%s.layers.%d.feed_forward.%s";
RAD_ARCH_TRY(linear(L.gate_up, l, "blk.%d.ffn_gate_up", 2 * g.n_ff, g.n_embd,
{ nm.ckpt(ffn, pre, l, "w1.weight"), nm.ckpt(ffn, pre, l, "w3.weight") },
m.a_h, m.b_gate_up, { g.n_ff, g.n_ff }));
L.op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_gate_up}, {m.b_ffn});
RAD_ARCH_TRY(linear(L.down, l, "blk.%d.ffn_down", g.n_embd, g.n_ff,
{ nm.ckpt(ffn, pre, l, "w2.weight") }, m.a_ffn, m.b_arm, {}));
if (has_join && l + 1 < (int)m.layers.size())
L.op_ffn_join = join(L.w_ffn_post_norm, m.layers[(size_t)l + 1].w_norm);
if (!L.op_ffn_join) {
L.op_ffn_post_norm = rmsnorm(g.max_tok, g.n_embd, L.w_ffn_post_norm, m.b_arm, m.b_arm);
L.op_ffn_add = add(m.b_x, m.b_arm);
}
n_joins += (L.op_join ? 1 : 0) + (L.op_ffn_join ? 1 : 0);
}
/* 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);
/* A tied head is the bf16 embedding table: a scored step leaves the final-normed rows in
* h_out and the core takes the candidates' logits from the table on the host. */
if (meta_bool(meta, "tie_word_embeddings", false))
RAD_ARCH_TRY(rad_declare_scores(b, m.b_hout, m.w_tok));
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});
int64_t n_full = 0, n_sliding = 0;
for (const Layer& L : m.layers) {
n_full += L.kind == kFull ? 1 : 0;
n_sliding += L.kind == kSliding ? 1 : 0;
}
rad_note(b, "lfm3: %lld layers, %lld full attention + %lld sliding (window %lld) + %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_full, (long long)n_sliding,
(long long)m.sliding.window, (long long)(g.n_layer - n_full - n_sliding),
(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);
rad_note(b, "sandwich joins: %d of %lld fused (norm_add_norm)%s", n_joins,
(long long)(2 * g.n_layer - 1),
n_joins == 0 ? " -- not served, the rmsnorm / add / rmsnorm chain" : "");
return RAD_OK;
}
static void lin_step(RadCtx* c, const Linear& lin, rad_buf in, rad_buf out, int64_t T) {
RAD_ISSUE(c, lin.op, brows(in, T), RAD_W(lin.w), brows(out, T));
}
/* The convolution is issued once per half of the step, as LFM2's is: 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_slot(c)];
const Geom& g = m.g;
if (batch->draft_pass || batch->spec_parent || batch->enc || batch->n_mm_rows > 0) {
rad_step_fail(c, "lfm3_bf16: this step asks for an encoder, a draft pass or media rows, "
"and the program declares none of them");
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));
for (int l = 0; l < (int)m.layers.size(); ++l) {
const Layer& L = m.layers[(size_t)l];
if (!(l > 0 && m.layers[(size_t)l - 1].op_ffn_join))
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
if (L.kind != kConv) {
const rad_kvgroup grp = m.cls(L).kv;
const RadKVGroupBatch* kv = kv_batch(batch, grp);
L.q.step(c, m.a_h, m.b_q, T);
L.k.step(c, m.a_h, m.b_k, T);
L.v.step(c, m.a_h, m.b_v, T);
lin_step(c, L.gate, m.b_h, m.b_gate, 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(grp, l));
RAD_ISSUE_N(c, L.op_attn, batch->max_q_len,
brows(m.b_q, T), kv_cache(grp, 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_sigmoid, brows(m.b_gate, T), brows(m.b_gate, T));
RAD_ISSUE(c, L.op_gate_mul, brows(m.b_gate, T), brows(m.b_attn, T), brows(m.b_attn, T));
L.out.step(c, m.a_attn, m.b_arm, T);
} else {
L.conv_in.step(c, m.a_h, 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));
L.conv_out.step(c, m.a_conv, m.b_arm, T);
}
if (L.op_join) {
RAD_ISSUE(c, L.op_join, brows(m.b_arm, T), RAD_W(L.w_post_norm), brows(m.b_x, T),
RAD_W(L.w_ffn_norm), brows(m.b_h, T));
} else {
RAD_ISSUE(c, L.op_post_norm, brows(m.b_arm, T), RAD_W(L.w_post_norm),
brows(m.b_arm, T));
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_arm, T), brows(m.b_x, T));
RAD_ISSUE(c, L.op_ffn_norm, brows(m.b_x, T), RAD_W(L.w_ffn_norm), brows(m.b_h, T));
}
L.gate_up.step(c, m.a_h, m.b_gate_up, T);
RAD_ISSUE(c, L.op_act, brows(m.b_gate_up, T), brows(m.b_ffn, T));
L.down.step(c, m.a_ffn, m.b_arm, T);
if (L.op_ffn_join) {
/* y is the next layer's input norm */
RAD_ISSUE(c, L.op_ffn_join, brows(m.b_arm, T), RAD_W(L.w_ffn_post_norm),
brows(m.b_x, T), RAD_W(m.layers[(size_t)l + 1].w_norm), brows(m.b_h, T));
} else {
RAD_ISSUE(c, L.op_ffn_post_norm, brows(m.b_arm, T), RAD_W(L.w_ffn_post_norm),
brows(m.b_arm, T));
RAD_ISSUE(c, L.op_ffn_add, brows(m.b_x, T), brows(m.b_arm, T), brows(m.b_x, T));
}
}
/* 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));
if (!batch->score_only)
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 lfm3_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(lfm3_bf16, "lfm3", "", "0.1.0",
"LiquidAI LFM3, bf16 or IQ8R: short gated convolutions, full and sliding-window GQA "
"attention with a partial rotary and a gate per head, sandwich norms, in the "
"checkpoint's own schedule, one rank")
#endif
+3 -3
View File
@@ -1,9 +1,9 @@
/* llama_dense_fp8 -- arch/llama_fp8 over a bf16 checkpoint quantised by rad-convert.
*
* 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.
* data/recipes/minicpm5-2b-iq8r.recipe stores every linear as rotated int8 with a scale per
* (row, 256 of K); data/recipes/minicpm5-2b-bf16-dspark.recipe keeps the model's own linears bf16
* and quantises only the merged drafter.
*
* 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;
+112 -28
View File
@@ -14,10 +14,10 @@
*
* 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).
* llama_dense_fp8 quant "" the checkpoint is dense bf16, and a recipe quantises its
* linears at convert time
* (data/recipes/minicpm5-2b-iq8r.recipe: rotated int8, a
* scale per (row, 256 of K)) or leaves them bf16.
*
* 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.
@@ -28,8 +28,17 @@
* BF16, no plane every norm and the embedding
*
* 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.
* fp8 or int8 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.
*
* ============================== AN INT8 TRUNK ==============================
*
* The dense build also serves a recipe that makes the linears rotated int8 (IQ8R:
* data/recipes/minicpm5-2b-iq8r.recipe). Each is a LinearFP8, which reads what the container holds,
* and declare() learns the format from the first layer's q|k|v before it declares the activations:
* they then carry int8 codes with one scale per (token, scale group) in place of the E4M3 pair,
* written by the norms, the gated product and the attention output's quantiser. The DSpark
* drafter's linears follow their own encodings the same way (rad_block_dspark.h).
*/
#ifndef LLAMA_DENSE_SRC
#define LLAMA_DENSE_SRC 0
@@ -67,6 +76,12 @@ struct Model {
rad_kvgroup kv_full = 0;
/* The trunk's linears are rotated int8 (IQ8R, or the 128-group int8 before it), read from the
* first layer's fused q|k|v: the activations then carry int8 code pairs at `trunk_g8` columns
* a scale, written by the norms, the gated product and the attention output's quantiser. */
bool trunk_i8 = false;
int64_t trunk_g8 = RAD_FP8_BLOCK;
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
ActFP8 a_h{};
rad_buf b_qkv = 0;
@@ -101,7 +116,7 @@ struct Model {
std::vector<Layer> layers;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* 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
@@ -205,6 +220,13 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
return RAD_E_UNSUPPORTED;
}
/* The drafter's own stored format, which decides its activation pairs below. */
RAD_ARCH_TRY(Dspark::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
dc.fc_mapped = true;
const uint32_t dqt = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_FP8_BLOCK;
auto dqcols = [dqg](int64_t n) { return (n + dqg - 1) / dqg; };
/* 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));
@@ -223,28 +245,35 @@ 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});
/* 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)});
dw.cq = decl_b(b, nm.f("ds_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
dw.cs = decl_b(b, nm.f("ds_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
/* Eight-bit copies for the context pass, at the code type and scale group the drafter's
* linears read. `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. */
if (dc.act_i8 && (qd % dqg || dg.n_embd % dqg || dg.n_ff % dqg)) {
fprintf(stderr, "radiance: the DSpark drafter's int8 linears keep one scale a %lld of K, "
"which does not divide its widths (hidden %lld, attention %lld, "
"feed-forward %lld)\n",
(long long)dqg, (long long)dg.n_embd, (long long)qd, (long long)dg.n_ff);
return RAD_E_UNSUPPORTED;
}
dw.srcq = decl_b(b, nm.f("ds_srcq"), dqt, {dg.max_tok, dc.n_taps * dg.n_embd});
dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32, {dg.max_tok, dqcols(dc.n_taps * dg.n_embd)});
dw.cq = decl_b(b, nm.f("ds_cq"), dqt, {dg.max_tok, dg.n_embd});
dw.cs = decl_b(b, nm.f("ds_cs"), RAD_F32, {dg.max_tok, dqcols(dg.n_embd)});
dw.x = decl_b(b, nm.f("ds_x"), dg.act_dtype, {qr, dg.n_embd});
dw.h.x = decl_b(b, nm.f("ds_h"), dg.act_dtype, {qr, dg.n_embd});
dw.h.q = decl_b(b, nm.f("ds_h.q"), RAD_F8E4M3, {qr, dg.n_embd});
dw.h.s = decl_b(b, nm.f("ds_h.s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
dw.h.q = decl_b(b, nm.f("ds_h.q"), dqt, {qr, dg.n_embd});
dw.h.s = decl_b(b, nm.f("ds_h.s"), RAD_F32, {qr, dqcols(dg.n_embd)});
dw.q = decl_b(b, nm.f("ds_q"), dg.act_dtype, {qr, qd});
dw.k = decl_b(b, nm.f("ds_k"), dg.act_dtype, {qr, kvd});
dw.v = decl_b(b, nm.f("ds_v"), dg.act_dtype, {qr, kvd});
dw.attn.x = decl_b(b, nm.f("ds_attn"), dg.act_dtype, {qr, qd});
dw.attn.q = decl_b(b, nm.f("ds_attn.q"), RAD_F8E4M3, {qr, qd});
dw.attn.s = decl_b(b, nm.f("ds_attn.s"), RAD_F32, {qr, fp8_blocks(qd)});
dw.attn.q = decl_b(b, nm.f("ds_attn.q"), dqt, {qr, qd});
dw.attn.s = decl_b(b, nm.f("ds_attn.s"), RAD_F32, {qr, dqcols(qd)});
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
dw.ffn.x = decl_b(b, nm.f("ds_ffn"), dg.act_dtype, {qr, dg.n_ff});
dw.ffn.q = decl_b(b, nm.f("ds_ffn.q"), RAD_F8E4M3, {qr, dg.n_ff});
dw.ffn.s = decl_b(b, nm.f("ds_ffn.s"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
dw.ffn.q = decl_b(b, nm.f("ds_ffn.q"), dqt, {qr, dg.n_ff});
dw.ffn.s = decl_b(b, nm.f("ds_ffn.s"), RAD_F32, {qr, dqcols(dg.n_ff)});
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});
@@ -310,9 +339,10 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
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;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(check_format(meta));
@@ -346,18 +376,58 @@ 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);
/* ---- activations. */
/* ---- the trunk's stored format, read from the first layer's fused q|k|v before any
* activation is declared: only an int8 trunk's activations carry an int8 code pair. The probe
* maps the weight through the layer's own LinearFP8, which then does not map it again; the
* resize before the layer loop keeps the layers sized here. */
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
m.layers.resize((size_t)m.n_main);
if (m.n_main > 0) {
const char* pre = "model.layers";
RAD_ARCH_TRY(m.layers[0].attn.qkv.probe(
b, nm, g, nm.f("blk.0.attn_qkv"),
{ nm.ckpt("%s.0.self_attn.q_proj.weight", pre),
nm.ckpt("%s.0.self_attn.k_proj.weight", pre),
nm.ckpt("%s.0.self_attn.v_proj.weight", pre) }));
RadEncoding enc{};
m.trunk_i8 = weight_enc(b, nm.f("blk.0.attn_qkv.weight"), &enc) &&
(linear_is_w8h(enc) || linear_is_wnh(enc));
if (m.trunk_i8) m.trunk_g8 = linear_w8h_group(enc);
}
if (m.trunk_i8 && (g.n_embd % m.trunk_g8 || q_dim % m.trunk_g8 || g.n_ff % m.trunk_g8)) {
fprintf(stderr, "radiance: llama: the int8 trunk keeps one scale a %lld of K, which does "
"not divide this rank's widths (hidden %lld, attention %lld, "
"feed-forward %lld)\n",
(long long)m.trunk_g8, (long long)g.n_embd, (long long)q_dim, (long long)g.n_ff);
return RAD_E_UNSUPPORTED;
}
/* ---- activations. An int8 trunk's quantisers sit in their producers where the kernels serve
* the rotated forms: the norms write had_quant_act_i8g's codes for q|k|v and gate|up, the
* gated product for the down projection, and the attention output's own quantiser for the
* out-projection, so no projection declares one and the activation carries no E4M3 pair.
* Where a form is not declared (the CPU kernels), the producer keeps its E4M3 pair and each
* projection quantises its own input from the bf16 plane. */
if (m.trunk_i8) {
if (rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g")))
m.a_h.q8_fed = m.a_h.q8_rot = true;
if (rad_op_declared(b, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true;
if (rad_op_declared(b, "had_quant_act_i8g")) m.a_attn.q8_fed = m.a_attn.q8_rot = true;
}
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd));
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8, !m.a_h.q8_fed,
m.trunk_g8));
m.b_qkv = decl_b(b, nm.f("attn_qkv"), g.act_dtype, {g.max_tok, q_dim + 2 * kv_dim});
m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim});
m.a_attn.x = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim});
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim));
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8,
!m.a_attn.q8_fed, m.trunk_g8));
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
m.a_ffn.x = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff));
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8, !m.a_ffn.q8_fed,
m.trunk_g8));
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
/* ---- the drafter's taps, only when the container carries a drafter that reads them and the
@@ -431,7 +501,6 @@ 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;
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];
/* Residual fold and collective placement: rad_fp8.h, layer_fold. */
@@ -496,6 +565,11 @@ 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
if (m.trunk_i8)
rad_note(b, "a dense bf16 checkpoint, every linear quantised by the recipe to rotated "
"int8 with one scale a [1 x %lld] of K, read against int8 activations with a "
"scale per (token, %lld)", (long long)m.trunk_g8, (long long)m.trunk_g8);
else
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);
@@ -523,7 +597,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)];
Model& m = g_model[rad_slot(c)];
/* 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. */
@@ -579,6 +653,14 @@ static void step(RadCtx* c, const RadBatch* batch) {
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
#if LLAMA_DENSE_SRC
/* Chained launches pay on an IQ8R trunk with and without its drafter: libr4d's
* rad_kernel_chain holds the IQ8R decode rows. MiniCPM5-2B on one R9700, ms a decode step
* unchained / chained: 5.57 / 5.17 at one sequence and 6.09 / 5.71 at eight without a drafter,
* and with DSpark 7.32 / 6.87 at one and 8.15 / 7.92 at four. A block-fp8 trunk gains less
* and loses nowhere: 5.45 / 5.40 and 5.92 / 5.89 without, 7.14 / 7.12 and 8.17 / 8.16 with. */
out->chain_pays = RAD_CHAIN_ALWAYS;
#endif
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (da && (std::strstr(da, "DSpark") || std::strstr(da, "DFlash"))) {
const long long bs = rad_meta_geti(meta, "draft.block_size", 0);
@@ -596,6 +678,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
/* 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__)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
LLAMA_PROBE_X(LLAMA_NS)
#if LLAMA_DENSE_SRC
LLAMA_PLUGIN_X(LLAMA_NS, "llama", LLAMA_QUANT, "0.1.0",
+45 -28
View File
@@ -58,7 +58,8 @@
*
* Every network computes in bf16, as the reference loads it; the latents, the guidance and the
* sampler are f32. The text encoder's, the connectors' and the DiT's large linears are bf16 or
* block fp8 as the container holds them (data/recipes/ltx-2.5-fp8.recipe); the vocoder runs in
* rotated int8 as the container holds them (data/recipes/ltx-2.5-bf16.recipe,
* ltx-2.5-iq8r.recipe), one kind a container; the vocoder runs in
* f32 (its anti-aliased activation's kernels are f32), its log-mel input rounded where the
* reference's bf16 one is.
*
@@ -182,8 +183,11 @@ static int64_t positions(const RadVideoGeom* g, float* pos, int64_t cap) {
}
/* ================================================================== linears */
/* An activation a linear reads: its bf16 plane and, for block-fp8 linears, its codes, which a
* quantiser makes from the plane (QuantFP8). */
/* An activation a linear reads: its bf16 plane and, for block-fp8 or rotated int8 linears, its
* codes, which a quantiser makes from the plane (QuantFP8: E4M3, or had_quant_act_i8g's int8 at
* the weights' scale group). Rows narrower than that group carry no codes: a bf16 linear reads
* them (the latents' projections in). Where no library serves the rotating quantiser, each int8
* linear quantises its own input and this declares none. */
struct Act {
ActFP8 a{};
QuantFP8 q{};
@@ -196,27 +200,30 @@ struct Act {
if (!a.x) return RAD_E_INVAL;
Geom gg = g;
gg.max_tok = rows;
RAD_ARCH_TRY(a.declare_qs(b, nm, gg, name, width, rows));
if (g.w_i8h && width % g.w_i8_group) return RAD_OK;
RAD_ARCH_TRY(a.declare_pair(b, nm, gg, name, width, rows, g.w_i8h, g.w_i8_group,
"had_quant_act_i8g"));
if (g.w_i8h && !a.q8_fed) return RAD_OK;
return q.declare(b, gg, a, width);
}
/* The codes of rows [r0, r0 + rows), at those rows' count. */
void step(RadCtx* c, int64_t rows, int64_t r0 = 0) const {
if (!q.op || rows <= 0) return;
RAD_ISSUE_N(c, q.op, rows, brow_slice(a.x, r0, rows, n), brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
brow_slice(a.cs(), r0, rows, n / a.cg()));
}
};
/* A linear, y = x W^T (+ b): `gemm_nt_bias` over the bf16 plane for a bf16 weight (the bias in the
* GEMM's one rounding, as torch's), or `gemm_nt_q` over the codes for a block-fp8 one with the
* bias added after (`table_add`, one more rounding). `small` keeps a weight bf16 in any container
* (a gate's logits: too few rows for 128-row fp8 blocks). The input and output rows may sit at
* different offsets of their buffers. */
* GEMM's one rounding, as torch's), or `gemm_nt_q` over the codes for a block-fp8 or rotated int8
* one with the bias added after (`table_add`, one more rounding). `small` keeps a weight bf16 in
* any container (a gate's logits: too few rows for 128-row fp8 blocks). The input and output rows
* may sit at different offsets of their buffers. */
struct Lin {
LinearFP8 l{};
rad_weight w = 0, bias = 0;
rad_op op = 0, op_b = 0;
bool fp8 = false;
bool fp8 = false; /* read through its codes: block fp8, or rotated int8 */
bool mapped = false; /* the weight's name map was made already (a probe's) */
int64_t N = 0, K = 0;
@@ -257,9 +264,11 @@ struct Lin {
l.mapped = mapped;
RAD_ARCH_TRY(l.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(group), wsrc, in.a, y,
max_rows, parts));
if (l.bf16 || l.i8 || l.mx || l.w4 || l.paro || l.paro5) {
fprintf(stderr, "radiance: ltx2: '%s' is not block fp8; this plugin reads bf16 or "
"block-fp8 linears\n", base);
const bool other = l.bf16 || l.mx || l.w4 || l.paro || l.paro5 || l.iqr;
if (other || (g.w_i8h ? !(l.i8 && l.i8_rot) : l.i8)) {
fprintf(stderr, "radiance: ltx2: '%s' is not %s as the first DiT projection is; this "
"plugin reads bf16, block-fp8 or rotated int8 linears, one kind a "
"container\n", base, g.w_i8h ? "rotated int8" : "block fp8");
return RAD_E_UNSUPPORTED;
}
op = l.op;
@@ -285,9 +294,12 @@ struct Lin {
RAD_ISSUE_N(c, op, rows, brow_slice(in.a.x, ri, rows, K), RAD_W(w), out);
return;
}
RAD_ISSUE_N(c, op, rows, brow_slice(in.a.q, ri, rows, K),
brow_slice(in.a.s, ri, rows, K / RAD_FP8_BLOCK), RAD_W(l.w), RAD_W(l.ws), out,
RAD_NONE, RAD_NONE);
if (l.i8)
l.step(c, in.a, y, ri + rows, ri, rows, ro);
else
RAD_ISSUE_N(c, op, rows, brow_slice(in.a.q, ri, rows, K),
brow_slice(in.a.s, ri, rows, K / RAD_FP8_BLOCK), RAD_W(l.w), RAD_W(l.ws),
out, RAD_NONE, RAD_NONE);
if (op_b) RAD_ISSUE_N(c, op_b, rows, out, RAD_W(bias), out);
}
};
@@ -712,7 +724,7 @@ struct Model {
rad_buf b_ddcu = 0, b_dsig = 0, b_dtg = 0, b_dgrid = 0, b_dg5 = 0;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* ================================================================== check_format */
static long long tgeti(const RadModelMeta* m, const char* key, long long def) {
@@ -2370,7 +2382,7 @@ static int declare_audio(RadBuilder* b, const RadModelMeta* meta, Model& m) {
for (const char* w : { "voc.conv_in.weight", "bwe.conv_in.weight" }) {
if (weight_codes_dtype(b, w, RAD_F32) != RAD_F32) {
fprintf(stderr, "radiance: ltx2: '%s' is stored %s; the vocoders run in f32 -- convert "
"with data/recipes/ltx-2.5-bf16.recipe or ltx-2.5-fp8.recipe, which "
"with one of data/recipes/ltx-2.5-*.recipe, which "
"cast them\n", w, rad_dtype_name(weight_codes_dtype(b, w, RAD_F32)));
return RAD_E_UNSUPPORTED;
}
@@ -3140,7 +3152,8 @@ static const double kStage2[] = { 0.909375, 0.725, 0.421875 };
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;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
if (ctx->is_draft) {
fprintf(stderr, "radiance: ltx2: this plugin has no draft scope\n");
return RAD_E_UNSUPPORTED;
@@ -3150,7 +3163,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
"every head\n");
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
Names& nm = m.nm;
@@ -3217,8 +3230,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_INVAL;
}
/* ---- bf16 or block fp8: what the container holds for the first DiT projection decides every
* large linear (rad_fp8.h, Geom::w_bf16) */
/* ---- bf16, block fp8 or rotated int8: what the container holds for the first DiT projection
* decides every large linear (rad_arch.h, Geom::w_bf16 and w_i8h) */
{
LinearFP8 probe{};
RAD_ARCH_TRY(probe.probe(b, nm, m.gd, "dit.blk.0.attn1.qkv",
@@ -3226,9 +3239,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
"transformer.transformer_blocks.0.attn1.to_k.weight",
"transformer.transformer_blocks.0.attn1.to_v.weight" }));
RadEncoding e{};
const bool plain = weight_enc(b, nm.f("dit.blk.0.attn1.qkv.weight"), &e) &&
rad_enc_is(&e, "plain");
m.gd.w_bf16 = m.gt.w_bf16 = plain;
const bool known = weight_enc(b, nm.f("dit.blk.0.attn1.qkv.weight"), &e);
m.gd.w_bf16 = m.gt.w_bf16 = known && rad_enc_is(&e, "plain");
m.gd.w_i8h = m.gt.w_i8h = known && linear_is_w8h(e);
if (m.gd.w_i8h) m.gd.w_i8_group = m.gt.w_i8_group = linear_w8h_group(e);
}
/* ---- the scheduler: the base model's shifted linspace, or the distilled release's sigmas */
@@ -3371,7 +3385,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
"bandwidth extender%s%s",
distilled ? " distilled" : "", (long long)m.tL, (long long)m.tC, m.cv.blk.size(),
m.ca.blk.size(), (long long)m.nb, (long long)m.D, (long long)m.Da,
m.gd.w_bf16 ? "bf16" : "block-fp8", m.venc ? "decoder + encoder" : "decoder",
m.gd.w_bf16 ? "bf16" : m.gd.w_i8h ? "rotated int8" : "block-fp8",
m.venc ? "decoder + encoder" : "decoder",
m.ups ? ", latent upsampler x2" : "", m.dur ? ", duration head" : "");
return RAD_OK;
}
@@ -4144,7 +4159,7 @@ static void step_upscale(RadCtx* c, const RadBatch* batch, const Model& m) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
if (!batch->gen || !batch->vgen_b) {
rad_step_fail(c, "ltx2 is a video generator and runs its generator passes only");
return;
@@ -4179,12 +4194,14 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(ltx2)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(ltx2, "ltx2", "", "0.1.0",
"LTX-2.5 (t2va, i2va): a Gemma 4 text encoder and connectors, the duration head, a "
"22B dual-stream audio-video diffusion transformer with four-way guidance, the "
"causal 3D video VAE (tiled past the default canvas) and the diffusion decoder, the "
"audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; "
"bf16 or block-fp8 linears")
"bf16, block-fp8 or rotated int8 linears")
extern "C" int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos,
int64_t cap) {
+135 -35
View File
@@ -288,10 +288,11 @@ struct DitBlock {
rad_op op_kq = 0; /* the keys to int8 codes for the attention's scores */
rad_op op_vq = 0; /* the values to E4M3 codes for the attention's P.V */
/* The three modulation projections, one a modality, this rank's share of their rows; a
* curve-form checkpoint's are bf16 (ada_w). */
* curve-form checkpoint's are bf16 (ada_w). A rotated int8 one adds its bias after the GEMM
* (op_ada_b). */
DenseFP8 ada[3];
rad_weight ada_w[3] = {}, ada_b[3] = {};
rad_op op_ada[3] = {};
rad_op op_ada[3] = {}, op_ada_b[3] = {};
};
/* A video decoder block. */
@@ -423,6 +424,7 @@ struct Model {
/* ---- the lanes (PERSIST) */
rad_buf b_text = 0; /* [lanes * kMaxText, D] bf16: the refined prompt */
rad_buf b_ada = 0; /* [lanes * S, 150 * Ws] bf16: the modulation table */
rad_buf b_adat = 0; /* [S, Ws] bf16: a rotated int8 projection's rows before its bias */
rad_buf b_nout = 0; /* [lanes * S, 3 * 2D] bf16: norm_out's, by segment */
rad_buf b_vstate = 0; /* [lanes * maxV, 96] f32 */
rad_buf b_astate = 0; /* [lanes * maxA, 32] f32 */
@@ -450,6 +452,12 @@ struct Model {
ActFP8 a_hm{}, a_attn{}, a_ffn{};
/* The DiT's linears are int8 (W8A8): their activations are int8 codes as well. */
bool dit_i8 = false;
/* The text encoder's, the refiner's and the modulation projections' linears are rotated int8
* (IQ8R, or the 128-group form where K is not whole 256s), each read off its first weight:
* their activations then carry int8 pairs at that weight's scale group in place of the E4M3
* ones (ActFP8::declare_pair). */
bool te_i8 = false, ref_i8 = false, ada_i8 = false;
int64_t te_g8 = RAD_FP8_BLOCK, ref_g8 = RAD_FP8_BLOCK, ada_g8 = RAD_FP8_BLOCK;
std::vector<DitBlock> dit;
rad_weight w_no_n = 0, w_vout = 0, b_vout = 0, w_aout = 0, b_aout = 0;
rad_op op_nout = 0, op_hcast = 0, op_vout = 0, op_aout = 0, op_ev = 0, op_ea = 0;
@@ -561,7 +569,7 @@ struct Model {
rad_buf b_enca = 0; /* [kEncSlotsA * kEncSlotRowsA, kAudioC] f32 PERSIST */
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* A space-separated list off the container (rad-convert flattens arrays that way). */
static std::vector<double> meta_list(const RadModelMeta* m, const char* key) {
@@ -704,16 +712,35 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
nm.ckpt("model.language_model.embed_tokens.weight")));
m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, g.n_embd },
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
/* The linears' format, from layer 0's projection, before the activations' codes are declared:
* rotated int8 ones read int8 pairs. */
m.te.resize((size_t)g.n_layer);
{
const char* pre = "model.language_model.layers";
RAD_ARCH_TRY(m.te[0].qkv.probe(b, nm, g, "te.blk.0.attn_qkv",
{ nm.ckpt("%s.0.self_attn.q_proj.weight", pre),
nm.ckpt("%s.0.self_attn.k_proj.weight", pre),
nm.ckpt("%s.0.self_attn.v_proj.weight", pre) }));
RadEncoding e{};
if (weight_enc(b, nm.f("te.blk.0.attn_qkv.weight"), &e) &&
(linear_is_w8h(e) || linear_is_wnh(e))) {
m.te_i8 = true;
m.te_g8 = linear_w8h_group(e);
}
}
m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd });
m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd });
RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd));
RAD_ARCH_TRY(m.a_th.declare_pair(b, nm, g, "te.h", g.n_embd, 0, m.te_i8, m.te_g8,
"had_quant_act_i8g"));
m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim });
m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim });
RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim));
RAD_ARCH_TRY(m.a_tattn.declare_pair(b, nm, g, "te.attn", q_dim, 0, m.te_i8, m.te_g8,
"had_quant_act_i8g"));
m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd });
m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff });
RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff));
RAD_ARCH_TRY(m.a_tffn.declare_pair(b, nm, g, "te.ffn", g.n_ff, 0, m.te_i8, m.te_g8,
"gated_had_quant_i8g"));
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd),
@@ -887,15 +914,32 @@ static int declare_refiner(RadBuilder* b, const RadModelMeta* meta, Model& m) {
m.b_rh = decl_b(b, nm.f("ref.h"), RAD_BF16, { T, D });
m.op_ce = dense_bias(b, nm, "ref.ctx", "transformer.context_embedder", RAD_BF16, "bf16", D,
tdim, T, m.b_tx, m.b_rh, &m.w_ce, &m.b_ce, acc, gx);
/* The refiner's linears' format, from block 0's projection (declare_te's note). */
{
const char* pre = nm.ckpt("transformer.token_refiner.refiner_blocks.0");
RAD_ARCH_TRY(m.rb[0].qkv.probe(b, nm, g, "ref.blk.0.attn_qkv",
{ nm.ckpt("%s.attn.to_q.weight", pre),
nm.ckpt("%s.attn.to_k.weight", pre),
nm.ckpt("%s.attn.to_v.weight", pre) }));
RadEncoding e{};
if (weight_enc(b, nm.f("ref.blk.0.attn_qkv.weight"), &e) &&
(linear_is_w8h(e) || linear_is_wnh(e))) {
m.ref_i8 = true;
m.ref_g8 = linear_w8h_group(e);
}
}
m.a_rh.x = decl_b(b, nm.f("ref.hn"), RAD_BF16, { T, D });
RAD_ARCH_TRY(m.a_rh.declare_qs(b, nm, g, "ref.hn", D));
RAD_ARCH_TRY(m.a_rh.declare_pair(b, nm, g, "ref.hn", D, 0, m.ref_i8, m.ref_g8,
"had_quant_act_i8g"));
m.b_rqkv = decl_b(b, nm.f("ref.qkv"), RAD_BF16, { T, 3 * qd });
m.a_rattn.x = decl_b(b, nm.f("ref.attn"), RAD_BF16, { T, qd });
RAD_ARCH_TRY(m.a_rattn.declare_qs(b, nm, g, "ref.attn", qd));
RAD_ARCH_TRY(m.a_rattn.declare_pair(b, nm, g, "ref.attn", qd, 0, m.ref_i8, m.ref_g8,
"had_quant_act_i8g"));
m.b_rao = decl_b(b, nm.f("ref.ao"), RAD_BF16, { T, D });
m.b_rgu = decl_b(b, nm.f("ref.gate_up"), RAD_BF16, { T, 2 * g.n_ff });
m.a_rffn.x = decl_b(b, nm.f("ref.ffn"), RAD_BF16, { T, g.n_ff });
RAD_ARCH_TRY(m.a_rffn.declare_qs(b, nm, g, "ref.ffn", g.n_ff));
RAD_ARCH_TRY(m.a_rffn.declare_pair(b, nm, g, "ref.ffn", g.n_ff, 0, m.ref_i8, m.ref_g8,
"gated_had_quant_i8g"));
const int64_t ff_all = g.n_ff_all;
for (int l = 0; l < 2; ++l) {
@@ -1063,13 +1107,10 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) {
m.op_ts = unary(b, "silu", TT, hd1, "f32", m.b_te1, m.b_te1s);
m.op_t2 = dense_bias(b, nm, "tmb.l2", "transformer.time_embedder.linear_2", RAD_F32, "f32",
td, hd1, TT, m.b_te1s, m.b_temb, &m.w_t2, &m.b_t2, acc, gx);
/* silu(temb) in f32, rounded once to the bf16 the projections take. */
Geom gs = g;
gs.max_tok = TT;
/* silu(temb) in f32, rounded once to the bf16 the projections take. Its codes are
* declared below, once the first projection's encoding says which they are. */
m.a_temb.x = decl_b(b, nm.f("tmb.act"), RAD_BF16, { TT, td });
m.op_ts2 = unary(b, "silu", TT, td, "f32", m.b_temb, m.a_temb.x);
RAD_ARCH_TRY(m.a_temb.declare_qs(b, nm, gs, "tmb.act", td, TT));
RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td));
if (!m.op_temb || !m.op_temb_pv || !m.op_temb_pa || !m.op_t1 || !m.op_ts || !m.op_t2
|| !m.op_ts2) return RAD_E_INVAL;
}
@@ -1106,16 +1147,58 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) {
RAD_WEIGHTS(B.ada_w[md], B.ada_b[md])),
{ m.a_temb.x }, { m.b_ada });
} else {
/* The embedding's codes, from the first projection's encoding: E4M3, or for
* rotated int8 projections the int8 pair at their scale group. */
if (l == 0 && md == 0) {
RadEncoding e{};
if (weight_enc(b, wn, &e) && linear_is_w8h(e)) {
m.ada_i8 = true;
m.ada_g8 = linear_w8h_group(e);
}
Geom gs = g;
gs.max_tok = TT;
RAD_ARCH_TRY(m.a_temb.declare_pair(b, nm, gs, "tmb.act", td, TT, m.ada_i8,
m.ada_g8, "had_quant_act_i8g"));
if (m.ada_i8 && !m.a_temb.q8_fed) {
fprintf(stderr, "radiance: minimaxh3: rotated int8 modulation projections "
"need had_quant_act_i8g, which no loaded library serves\n");
return RAD_E_UNSUPPORTED;
}
RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td));
}
/* The row slice is mapped above (DenseFP8 takes that as its argument). */
B.ada[md].w8h_ok = m.ada_i8;
RAD_ARCH_TRY(B.ada[md].declare(b, nm, base, m.Ws, td, acc, RAD_SHARD_ROW,
grp_layer(grp), { src_w }, {}, true));
B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias",
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws),
RAD_INT("K", td),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(B.ada[md].w, B.ada[md].s, B.ada_b[md])),
{ m.a_temb.q, m.a_temb.s }, { m.b_ada });
if (B.ada[md].w8h != m.ada_i8) {
fprintf(stderr, "radiance: minimaxh3: '%s' is not encoded as the first "
"modulation projection is\n", wn);
return RAD_E_DTYPE;
}
if (m.ada_i8) {
/* i8a8h has no biased row and writes whole rows: the GEMM goes to its own
* rows, and the bias is added on the way into the table's cell. */
if (!m.b_adat) m.b_adat = decl_b(b, nm.f("tmb.ada"), RAD_BF16, { S, m.Ws });
if (!m.b_adat) return RAD_E_INVAL;
B.op_ada[md] = B.ada[md].gemm(b, S, m.Ws, td,
{ m.a_temb.cq(), m.a_temb.cs() }, { m.b_adat });
B.op_ada_b[md] = rw(b, RAD_OP(b, "table_add",
RAD_PARAMS(RAD_RANGE("M", 1, S),
RAD_INT("n", m.Ws), RAD_INT("L", 1),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(B.ada_b[md])),
{ m.b_adat }, { m.b_ada });
if (!B.op_ada_b[md]) return RAD_E_INVAL;
} else {
B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias",
RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws),
RAD_INT("K", td),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(B.ada[md].w, B.ada[md].s,
B.ada_b[md])),
{ m.a_temb.q, m.a_temb.s }, { m.b_ada });
}
}
if (!B.op_ada[md]) return RAD_E_INVAL;
}
@@ -2263,7 +2346,11 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
m.ve_fold_mul = join_list(fm);
m.ve_fold_add = join_list(fa);
m.b_epix32 = decl_b(b, nm.f("venc.pix32"), RAD_F32, { Rmax, 3 });
m.b_epix = decl_b(b, nm.f("venc.pix"), RAD_BF16, { Rmax, 3 });
/* conv_in and the k=1 projections run on the host. Their activation operands must be
* pinned host buffers too: joining a device queue does not make its VRAM CPU-readable.
* Device convolutions can read/write these boundary buffers over the link in place. */
m.b_epix = decl_b(b, nm.f("venc.pix"), RAD_BF16, { Rmax, 3 },
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
m.b_egn = decl_b(b, nm.f("venc.gn"), RAD_F32, { G * (2 + 3 * 1024) });
const rad_buf st = m.b_egn;
/* The tiled encode's two planes and the quant_conv are declared ahead of the trunk, and the
@@ -2271,12 +2358,16 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
* tiled pass reruns the whole trunk once a tile while `b_vtile` holds every tile's pixels and
* `b_eqt` the finished tiles' moments, so both lifetimes must span the trunk's ops (from
* op_ve_pix's and op_ve_q's use to op_vt_crop and op_vt_join). */
m.b_tplan = decl_b(b, nm.f("venc.tplan"), RAD_I32, { m.tiles, 22 }, RAD_BUF_PERSIST);
m.b_tplan = decl_b(b, nm.f("venc.tplan"), RAD_I32, { m.tiles, 22 },
RAD_BUF_PERSIST, RAD_DOMAIN_HOST);
m.b_vtile = decl_b(b, nm.f("venc.vtile"), RAD_F32,
{ m.tiles * (int64_t)kEncMaxSide * kEncMaxSide, 3 });
m.b_eq48 = decl_b(b, nm.f("venc.q48"), RAD_BF16, { R[5], 48 });
m.b_eq2 = decl_b(b, nm.f("venc.q"), RAD_BF16, { R[5], 48 });
m.b_eqt = decl_b(b, nm.f("venc.qt"), RAD_BF16, { m.tiles * (int64_t)kTile * kTile, 48 });
m.b_eq48 = decl_b(b, nm.f("venc.q48"), RAD_BF16, { R[5], 48 },
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
m.b_eq2 = decl_b(b, nm.f("venc.q"), RAD_BF16, { R[5], 48 },
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
m.b_eqt = decl_b(b, nm.f("venc.qt"), RAD_BF16, { m.tiles * (int64_t)kTile * kTile, 48 },
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
m.ve_qw = wh(nm.f("venc.q.weight"), nm.ckpt("vae.quant_conv.weight"), { 48, 48, 1, 1, 1 });
m.ve_qb = wh(nm.f("venc.q.bias"), nm.ckpt("vae.quant_conv.bias"), { 48 });
/* The whole-canvas pass writes b_eq2; the tiled pass writes a tile's slice of b_eqt, which
@@ -2313,7 +2404,8 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
const int64_t cout = (int64_t)dims[L], cin = L == 0 ? cout : (int64_t)dims[L - 1];
const bool sc = L > 0 && cout != cin;
E.cin = cin, E.cout = cout, E.rows = R[L], E.pf = PF[L], E.frames = tf[L];
E.a = decl_b(b, nm.f("venc.l%d.a", L), RAD_BF16, { R[L], cout });
E.a = decl_b(b, nm.f("venc.l%d.a", L), RAD_BF16, { R[L], cout },
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST);
E.b = decl_b(b, nm.f("venc.l%d.b", L), RAD_BF16, { R[L], cout });
E.c = decl_b(b, nm.f("venc.l%d.c", L), RAD_BF16, { R[L], cout });
/* A level that changes the width takes its input in a buffer of that width, which the
@@ -2321,7 +2413,8 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
* none. */
if (sc) {
const bool dn_in = (int64_t)sds[L - 1] == 2 || (int64_t)tds[L - 1] == 2;
E.in = dn_in ? decl_b(b, nm.f("venc.l%d.in", L), RAD_BF16, { R[L], cin })
E.in = dn_in ? decl_b(b, nm.f("venc.l%d.in", L), RAD_BF16, { R[L], cin },
RAD_BUF_TRANSIENT, RAD_DOMAIN_HOST)
: m.v_lv[(size_t)L - 1].a;
const char* sc_src = nm.ckpt("vae.encoder.down_blocks.%d.resnets.0.conv_shortcut", L);
E.scw = wh(nm.f("venc.l%d.sc.weight", L), nm.ckpt("%s.weight", sc_src),
@@ -2798,8 +2891,9 @@ static int declare_aenc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
/* ================================================================== declare */
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];
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
Names& nm = m.nm;
@@ -2923,8 +3017,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ARCH_TRY(declare_dit(b, meta, m));
if (m.dit[0].qkv.bf16) {
fprintf(stderr, "radiance: minimaxh3: the DiT's linears are bf16; this plugin serves the "
"block-fp8 container (data/recipes/minimax-h3-fp8.recipe) or the int8 one "
"(data/recipes/minimax-h3-w8a8.recipe)\n");
"int8 container (data/recipes/minimax-h3-i8.recipe)\n");
return RAD_E_UNSUPPORTED;
}
RAD_ARCH_TRY(declare_ups(b, meta, m));
@@ -3203,10 +3296,15 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) {
const int64_t r0 = cell[(size_t)e].second;
const RadOperand out =
bcol_at(m.b_ada, base, L * kMaxSegs * m.Ws, (l * kMaxSegs + e) * m.Ws, m.Ws, S);
if (m.curve > 0)
if (m.curve > 0) {
RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.x, r0, S, td),
RAD_W(B.ada_w[md]), RAD_W(B.ada_b[md]), RAD_NONE, out);
else
} else if (m.ada_i8) {
RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q8, r0, S, td),
brow_slice(m.a_temb.s8, r0, S, td / m.ada_g8), RAD_W(B.ada[md].w),
RAD_W(B.ada[md].s), brows(m.b_adat, S), RAD_NONE, RAD_NONE);
RAD_ISSUE_N(c, B.op_ada_b[md], S, brows(m.b_adat, S), RAD_W(B.ada_b[md]), out);
} else
RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q, r0, S, td),
brow_slice(m.a_temb.s, r0, S, td / RAD_FP8_BLOCK), RAD_W(B.ada[md].w),
RAD_W(B.ada[md].s), RAD_W(B.ada_b[md]), out);
@@ -3934,7 +4032,7 @@ static void step_aenc(RadCtx* c, const RadBatch* batch, const Model& m) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
if (!batch->gen || !batch->vgen_b) {
rad_step_fail(c, "minimaxh3 is a video generator and runs its generator passes only");
return;
@@ -3987,6 +4085,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(minimaxh3)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(minimaxh3, "minimaxh3", "", "0.1.0",
"MiniMax-H3 (t2va, i2va, l2va, fl2va, ref2va): Qwen3-VL-32B conditioning, a 33B "
"single-stream diffusion transformer over text, soundtrack and video, a tiled ViT "
+7 -4
View File
@@ -208,7 +208,7 @@ struct Model {
rad_buf b_audio = 0;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* ================================================================== declare helpers */
static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x,
@@ -1083,8 +1083,9 @@ static int check_format(const RadModelMeta* meta) {
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];
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(check_format(meta));
@@ -1381,7 +1382,7 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
if (!batch->gen || !batch->agen_b) {
rad_step_fail(c, "minimaxmusic3 is an audio generator and runs generator passes only");
return;
@@ -1575,6 +1576,8 @@ RAD_ARCH_PROBE(minimaxmusic3)
extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) {
return minimaxmusic3::text_prepare(field, in, out, cap);
}
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(minimaxmusic3, "minimaxmusic3", "", "0.1.0",
"MiniMax-Music3: a Qwen3-8B music language model with a residual-code depth "
"decoder, a 2.4B flow-matching transformer over windows of frames, and a DAC "
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/museglimmer -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(museglimmer LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(museglimmer architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/museglimmer.cpp)
+198
View File
@@ -0,0 +1,198 @@
/* dflash2.h -- wire rad_block_dflash2.h onto a Muse Glimmer trunk.
*
* Meta's assistant is a plain DFlash (rad_block_muse_dflash.h). incoai's Muse-Glimmer-30B-DFlash2
* is the DFlash2 block: candidate selector, grouped convolutions, 8 KV heads. The two are
* selected by draft.architectures. Muse's DFlash2 ships output_multiplier and
* final_logit_softcapping; the block applies those (Config::omul / Config::scap).
*/
#pragma once
#include <arch/rad_block_dflash2.h>
#include <arch/rad_block_muse_dflash.h>
#include <arch/rad_fp8.h>
#include <cstring>
namespace rad {
namespace arch {
inline bool muse_draft_is_dflash2(const RadModelMeta* meta) {
const char* da = rad_meta_gets(meta, "draft.architectures", "");
return da && std::strstr(da, "DFlash2");
}
/* Same 12 MiB prefetch qwen35 measured on two R9700s. */
constexpr int64_t kMuseDf2Prefetch = (int64_t)12 << 20;
inline int declare_muse_dflash2(Dflash2* ds, Dflash2::Wire* w, rad_kvgroup* kv,
RadBuilder* b, Names& nm, const RadModelMeta* meta,
const RadBuildCtx* ctx, const Geom& target,
const MuseTaps& taps, int base_layer, rad_weight tok_embd,
rad_weight head_w) {
if (!ds || !w || !kv || !b) return RAD_E_INVAL;
Geom dg{};
RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DFlash2", /*kv_repl_ok=*/true));
const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size",
rad_meta_geti(meta, "draft.dflash_config.hidden_size",
dg.n_embd));
if (want_embd != dg.n_embd) {
fprintf(stderr, "radiance: museglimmer: the DFlash2 drafter reads a %lld-wide trunk and "
"this target is %lld wide; they are not the same model\n",
(long long)want_embd, (long long)dg.n_embd);
return RAD_E_UNSUPPORTED;
}
Dflash2::Config dc{};
dc.short_block = 1;
dc.prefetch = kMuseDf2Prefetch;
dc.n_taps = taps.n;
dc.block = ctx->max_spec + 1;
dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2);
dc.group = rad_meta_geti(meta, "draft.dflash_config.conv_group_size", 16);
dc.sel_rank = rad_meta_geti(meta, "draft.dflash_config.selector_rank", 0);
dc.sel_topk = rad_meta_geti(meta, "draft.dflash_config.selector_top_k", 0);
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.dflash_config.swa_window_size",
rad_meta_geti(meta, "draft.sliding_window", 0));
if (dc.sel_rank <= 0 || dc.sel_topk <= 0) {
fprintf(stderr, "radiance: museglimmer: the DFlash2 drafter states no selector geometry "
"(rank %lld, top_k %lld)\n",
(long long)dc.sel_rank, (long long)dc.sel_topk);
return RAD_E_INVAL;
}
const long long trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0);
if (dc.block < 2 || (dc.block & (dc.block - 1))) {
fprintf(stderr, "radiance: museglimmer: DFlash2's convolution masks the block position "
"with block_size - 1, so the query block has to be a power of two. This "
"serve asks for %d draft tokens, which makes it %lld; the checkpoint was "
"trained at %lld.\n",
ctx->max_spec, (long long)dc.block, trained);
return RAD_E_UNSUPPORTED;
}
if (trained > 0 && trained != dc.block)
rad_note(b, "DFlash2 was trained at block_size %lld (%lld draft tokens) and runs at "
"%lld; it accepts less away from its trained block length",
trained, trained - 1, (long long)dc.block);
dc.escale = rad_meta_getf(meta, "draft.dflash_config.input_embedding_scale", 1.0);
dc.omul = rad_meta_getf(meta, "draft.dflash_config.output_multiplier", 1.0);
dc.scap = rad_meta_getf(meta, "draft.dflash_config.final_logit_softcapping", 0.0);
RAD_ARCH_TRY(Dflash2::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
dc.fc_mapped = true;
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, kv));
const int64_t qd = dg.n_head * dg.head_dim;
const int64_t kvd = dg.n_head_kv * dg.head_dim;
const uint32_t act_dtype = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
const int64_t act_group = dc.act_i8 ? dc.act_g8 : RAD_FP8_BLOCK;
const auto act_groups = [act_group](int64_t n) { return (n + act_group - 1) / act_group; };
int64_t qr = dg.max_seqs * dc.block;
if (qr > dg.max_tok) qr = dg.max_tok;
const int64_t sr = dg.max_seqs * dc.steps();
const int64_t spad = ((sr + 15) / 16) * 16;
Dflash2::Wire& dw = *w;
dw.src = taps.src;
dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd});
dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd});
dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd});
dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd});
dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd});
dw.h2 = decl_b(b, nm.f("df_h2"), dg.act_dtype, {qr, dg.n_embd});
dw.coef = decl_b(b, nm.f("df_coef"), dg.act_dtype, {qr, dc.coef_dim(dg.n_embd)});
dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd});
dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd});
dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd});
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd});
dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff});
dw.srcq = decl_b(b, nm.f("df_srcq"), act_dtype,
{dg.max_tok, dc.n_taps * dg.n_embd});
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32,
{dg.max_tok, act_groups(dc.n_taps * dg.n_embd)});
dw.cq = decl_b(b, nm.f("df_cq"), act_dtype, {dg.max_tok, dg.n_embd});
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, act_groups(dg.n_embd)});
dw.h2q = decl_b(b, nm.f("df_h2q"), act_dtype, {qr, dg.n_embd});
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, act_groups(dg.n_embd)});
dw.atq = decl_b(b, nm.f("df_atq"), act_dtype, {qr, qd});
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, act_groups(qd)});
dw.ffq = decl_b(b, nm.f("df_ffq"), act_dtype, {qr, dg.n_ff});
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, act_groups(dg.n_ff)});
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank});
dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd});
dw.ds = decl_b(b, nm.f("df_ds"), RAD_F32, {sr, 1});
dw.dsum = decl_b(b, nm.f("df_dsum"), RAD_F32, {dg.n_embd / 128, spad});
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)});
{
const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16);
if (head_w && (hd == RAD_F8E4M3 || hd == RAD_I8) &&
(Dflash2::head_sharded(dg) || dg.world <= 1)) {
ds->w_lm = head_w;
ds->top_w = Dflash2::kRerankR;
}
}
const int64_t tw = ds->w_lm ? ds->top_w : dc.sel_topk;
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, tw});
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, tw});
if (Dflash2::head_sharded(dg)) {
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2});
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2});
}
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
if (ctx->draft_coupling) {
if (dc.steps() > RAD_MTP_COUPLE_MAX_ROUNDS || dc.sel_topk > RAD_DFLASH_COUPLE_MAX_K ||
dc.sel_rank % RAD_DFLASH_EDGE_PARTS || dc.sel_rank > RAD_DFLASH_COUPLE_MAX_R) {
fprintf(stderr, "radiance: museglimmer: --draft-coupling on DFlash2 needs at most "
"%d drafts, %d candidates and a selector rank that is a multiple of "
"%d up to %d\n",
RAD_MTP_COUPLE_MAX_ROUNDS, RAD_DFLASH_COUPLE_MAX_K, RAD_DFLASH_EDGE_PARTS,
RAD_DFLASH_COUPLE_MAX_R);
return RAD_E_UNSUPPORTED;
}
dc.q_temp = 0.6;
dw.couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
{dg.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS}, RAD_BUF_PERSIST);
dw.couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
{dc.steps(), dg.max_seqs, RAD_MTP_COUPLE_STATE_WORDS},
RAD_BUF_PERSIST);
if (!dw.couple_draws || !dw.couple_state) return RAD_E_INVAL;
}
RAD_ARCH_TRY(ds->declare(b, nm, dg, dc, base_layer, *kv, tok_embd, "draft",
nm.ckpt("lm_head.weight"), dw));
RadDrafterDecl drf{};
drf.name = "dflash2";
drf.kind = RAD_DRAFT_BLOCK;
drf.depth = ctx->max_spec;
drf.block = dc.block;
drf.proposal = dw.tokens;
drf.proposal_pitch = dc.steps();
drf.window = dc.window;
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1);
if (drf.mask_token < 0) {
fprintf(stderr, "radiance: museglimmer: this DFlash2 checkpoint declares no "
"dflash_config.mask_token_id\n");
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
if (ds->block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, ds->block_lo));
rad_note(b, "DFlash2 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 "
"proposes %lld tokens through the candidate selector",
(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,
taps.n, (long long)dc.steps());
if (dc.omul != 1.0 || dc.scap > 0.0)
rad_note(b, "DFlash2 logits: output_multiplier %g, softcap %g", dc.omul, dc.scap);
return RAD_OK;
}
} /* namespace arch */
} /* namespace rad */
+855
View File
@@ -0,0 +1,855 @@
/* museglimmer.cpp -- Meta's Muse Glimmer 30B, bf16 weights and bf16 activations.
*
* Muse Glimmer (HF `meta-models/Muse-Glimmer-30B`, model_type `muse_glimmer`) is a dense text
* model with a separate vision tower. The text trunk here is served by this plugin; the tower and
* its projector are declared at the bottom of declare() when the deployment asked for media.
*
* ============================== WHAT IT SERVES ==============================
*
* The unquantised release (quantisation descriptor ""), every projection a bf16 GEMM. 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 30B ==============================
*
* 52 layers, `layer_types` full_attention on every 4th layer counted back from the last
* (3, 7, ..., 51; the shipped config states the array, and this plugin checks
* it against full_attention_interval 4 rather than trusting either alone)
* hidden 6656 ffn 19968 vocab 202048 (lm_head not tied)
* 32 heads / 2 kv heads / head_dim 128 -> GQA 16
* sliding_window 2048: the sliding layers own a RAD_KV_WINDOW pool, the full layers a
* RAD_KV_FULL pool; a sequence holds one state per bound layer of each group
* q and output gate are SEPARATE checkpoint tensors (`q_proj`, `gate_proj`), unlike Qwen3.5's
* interleaved q_proj -- two GEMMs, two buffers, no fused q|gate row
* `layer_rope_theta`: 500000 on the sliding layers, 0 on the full ones. A 0 layer is NoPE: no
* rotary is declared or issued there (the reference passes
* position_embeddings=None). max_position_embeddings 131072, rope_type default
*
* ============================== WHAT DIFFERS FROM A LLAMA-LIKE ==============================
*
* Every deviation from the Qwen/Llama shape below is load-bearing; getting one wrong yields
* fluent wrong text (spec §17 refuses instead).
*
* * Four norms a layer, all Gemma-2 style "centered" norms, x_hat * (1 + w): the attention's
* input (rms_norm_eps 1e-5) and its output (post_norm_eps 1e-8), then the feed-forward's input
* (1e-5) and output (1e-8). The residual adds the *normed* branch, not the raw one.
* * The q/k "norm" is weightless: MuseGlimmerRMSNorm(with_scale=False), a plain RMS norm over
* head_dim at rms_norm_eps. The query is then multiplied by `qk_scale_factor` (3.87); the key
* is not. The attention scale stays 1/sqrt(head_dim). `rmsnorm` serves both: no gain operand,
* `mult` on the query.
* * The embedding is normed after the lookup: a weightless RMS norm at rms_norm_eps on the
* gathered rows (MuseGlimmerTextNormedEmbedding). It cannot be folded into the table because
* a drafter embeds without it, so it is an op.
* * The final norm (`model.language_model.norm.weight`) is a plain RMSNorm WITH a gain and
* without the centered 1+: wadd 0, unlike every layer norm.
* * The logits are pre-scaled by `output_multiplier` (1/sqrt(26)) before the Gemma-style tanh
* softcap: 20 * tanh(logits * mult / 20). The multiplier is carried on the final norm's
* `mult` (its output feeds only the head), the cap on `logit_softcap` over the f32 logits.
*
* ============================== WHAT THIS PLUGIN DOES NOT DECLARE ==============================
*
* The speculative drafter Meta ships beside the model (a DFlash block stack over layers
* 1, 13, 25, 37, 49) is not declared: it lives in its own checkpoint with its own `draft.`
* config, which this tree has no fixture for. Serving the trunk alone is a complete model.
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_museglimmer_vision.h>
#include <arch/rad_block_muse_dflash.h>
#include <arch/rad_calib_full.h>
#include <arch/rad_museglimmer_chat.h>
#include "dflash2.h"
#include <cmath>
#include <cstdlib>
#include <vector>
namespace museglimmer {
using namespace rad::arch;
/* ---- the checkpoint's config. A multimodal model keeps the trunk under `text_config.`; accept
* the bare spelling too, so a text-only GGUF container of the same family reads the same way. */
namespace {
} // namespace
/* One trunk layer. The rope ops exist only where layer_rope_theta says so; the branch is fixed
* per layer by the model. */
struct Layer {
int full = 0; /* full attention (no window, no rope in this family) */
int rope = 0; /* carries a rotary (the sliding layers) */
rad_weight w_norm = 0, w_post = 0, w_q = 0, w_gate = 0, w_k = 0, w_v = 0, w_o = 0;
rad_weight w_fnorm = 0, w_fpost = 0, w_gate_up = 0, w_down = 0;
rad_op op_norm = 0, op_q = 0, op_gate = 0, op_k = 0, op_v = 0;
rad_op op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0;
rad_op op_kv = 0, op_attn = 0, op_sig = 0, op_mul = 0, op_o = 0, op_ar = 0;
rad_op op_post = 0, op_add = 0;
rad_op op_fnorm = 0, op_gu = 0, op_act = 0, op_down = 0, op_far = 0, op_fpost = 0, op_fadd = 0;
/* The layer's calibration inputs (rad_calib_full.h): -1 where the run does not record it. */
int cs_in = -1, cs_o = -1, cs_mlp = -1, cs_down = -1;
};
struct Model {
Names nm{""};
Geom g{}; /* the trunk geometry, the rank's shard of it */
Geom g_rope{}; /* the same, with the sliding layers' rotary base (decl_rope reads theta) */
float qk_mult = 0; /* qk_scale_factor */
float post_eps = 0; /* post_norm_eps */
float out_mult = 0; /* output_multiplier */
float softcap = 0; /* final_logit_softcapping; 0: none */
int64_t window = 0; /* sliding_window */
rad_kvgroup kv_win = 0, kv_full = 0;
/* the residual stream and the two vocabulary edges */
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0;
rad_buf b_q = 0, b_gate = 0, b_k = 0, b_v = 0, b_attn = 0;
rad_buf b_gu = 0, b_ffn = 0;
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
rad_op op_embed = 0, op_embed_ar = 0, op_embed_norm = 0;
rad_op op_final_norm = 0, op_gather = 0, op_logits = 0, op_cap = 0;
/* ---- media (arch/common/rad_block_museglimmer_vision.h): the vision tower and the scatter of
* its rows, declared only when the container carries a tower and the deployment asked for
* media. The tower is declared last, so its activations share the arena with every buffer
* above. */
bool media = false;
rad_op op_media_rows = 0;
MuseTower vit{};
/* ---- Meta's DFlash or incoai's DFlash2, selected by draft.architectures. */
bool have_df = false, have_df2 = false;
MuseDflash df{};
MuseDflash::Wire dfw{};
Dflash2 df2{};
Dflash2::Wire df2w{};
MuseTaps taps{};
rad_kvgroup kv_draft = 0;
std::vector<Layer> layers;
/* --calib-dir: the whole Hessian of every linear's input over a --calib-corpus run. */
CalibFull calib;
int cs_head = -1;
};
/* Declare runs once per rank of an instance, on the rank's own thread (spec §1, §9); every
* instance's state is its slot's (rad_build_slot / rad_slot). */
static Model g_model[MAX_SLOTS];
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
/* A routed model is not this family. */
if (meta->n_expert > 0) {
fprintf(stderr, "radiance: museglimmer refuses a checkpoint with %lld experts\n",
(long long)meta->n_expert);
return RAD_E_UNSUPPORTED;
}
Geom& g = m.g;
Names& nm = m.nm;
/* ---- the family's own config. Everything that changes the mathematics is required or read
* from the family defaults the reference config class states; a wrong default yields fluent
* wrong text, so nothing here falls back to a "reasonable" value silently. */
m.qk_mult = (float)meta_text_getf(meta, "qk_scale_factor", 3.87);
m.post_eps = (float)meta_text_getf(meta, "post_norm_eps", 1e-8);
m.out_mult = (float)meta_text_getf(meta, "output_multiplier", 0.19611613513818404);
m.softcap = (float)meta_text_getf(meta, "final_logit_softcapping", 20.0);
m.window = meta_text_geti(meta, "sliding_window", 2048);
const double theta_rope = meta_text_getf(meta, "rope_parameters.rope_theta",
meta_text_getf(meta, "rope_theta", 0.0));
if (!(m.qk_mult > 0.0f) || !(m.out_mult > 0.0f) || !(m.post_eps > 0.0f) || m.window <= 0 ||
!(theta_rope > 0.0)) {
fprintf(stderr, "radiance: museglimmer: qk_scale_factor %g output_multiplier %g "
"post_norm_eps %g sliding_window %lld rope theta %g are all required\n",
(double)m.qk_mult, (double)m.out_mult, (double)m.post_eps,
(long long)m.window, theta_rope);
return RAD_E_INVAL;
}
if (g.rope_mc) {
fprintf(stderr, "radiance: museglimmer: the trunk has one-component rotary; a container "
"with mrope_section is not this family\n");
return RAD_E_UNSUPPORTED;
}
/* The rotary width is the full head: rope_parameters has no partial_rotary_factor and the
* reference rotates all of head_dim. */
const int64_t n_rot = g.head_dim;
/* ---- layer kinds. The config ships `layer_types`; where it does not (a GGUF container), the
* interval rule stands in. The two must agree where both exist: the schedule decides which
* layers keep a long context, and a wrong layer still generates fluent text. */
std::vector<int> full;
const char* kinds = meta_text_gets(meta, "layer_types", nullptr);
if (kinds && *kinds)
RAD_ARCH_TRY(parse_layer_kinds("museglimmer", kinds, {"full_attention"},
"sliding_attention", &full));
const int64_t interval = 4;
if ((int64_t)full.size() < g.n_layer) {
full.assign((size_t)g.n_layer, 0);
for (int64_t l = 0; l < g.n_layer; ++l) full[(size_t)l] = is_full_attention(l, interval);
if (kinds && *kinds)
rad_note(b, "the container's layer_types named %zu layers and the model has %lld; "
"building the full-attention layers by the interval %lld",
full.size() - (size_t)g.n_layer + (size_t)g.n_layer, (long long)g.n_layer,
(long long)interval);
} else {
for (int64_t l = 0; l < g.n_layer; ++l) {
if ((full[(size_t)l] != 0) != is_full_attention(l, interval)) {
fprintf(stderr, "radiance: museglimmer: layer_types makes layer %lld %s and "
"full_attention_interval %lld makes it %s\n",
(long long)l, full[(size_t)l] ? "full" : "sliding", (long long)interval,
is_full_attention(l, interval) ? "full" : "sliding");
return RAD_E_UNSUPPORTED;
}
}
}
/* Per-layer rotary: the shipped `layer_rope_theta`, else the family pattern (theta on the
* sliding layers, 0 -- NoPE -- on the full ones). */
std::vector<float> theta((size_t)g.n_layer, 0.0f);
const char* thetas = meta_text_gets(meta, "layer_rope_theta", nullptr);
if (thetas && *thetas) {
size_t i = 0;
for_each_token(thetas, [&](const char* t, size_t n) {
if (i >= theta.size()) return false;
char* e = nullptr;
const double v = std::strtod(std::string(t, n).c_str(), &e);
theta[i++] = e == t ? -1.0f : (float)v;
return true;
});
if (i < theta.size()) {
fprintf(stderr, "radiance: museglimmer: layer_rope_theta names %zu layers and the "
"model has %lld\n", i, (long long)g.n_layer);
return RAD_E_INVAL;
}
} else {
for (int64_t l = 0; l < g.n_layer; ++l)
theta[(size_t)l] = full[(size_t)l] ? 0.0f : (float)theta_rope;
}
for (int64_t l = 0; l < g.n_layer; ++l) {
if (!(theta[(size_t)l] >= 0.0f)) {
fprintf(stderr, "radiance: museglimmer: layer_rope_theta[%lld] is not a number\n",
(long long)l);
return RAD_E_INVAL;
}
}
/* Two Geoms: the trunk's for the buffers and shards, one with the sliding layers' rotary base
* for the rope ops (decl_rope takes theta from the Geom it is given). The rotary scaling is
* read into the rope Geom, against the sliding layers' own base: the extension reaches their
* rope and leaves the NoPE full layers untouched (they have no rotary to scale), and the
* mechanical extension past the trained 131072 positions -- which this family takes well, the
* full layers carrying no positions and the sliding ones reading only in-window relative
* offsets -- is the no-keys default this call returns. */
m.g_rope = g;
m.g_rope.theta = (float)theta_rope;
RAD_ARCH_TRY(yarn_from(m.g_rope, meta, "", g.head_dim));
const int64_t q_dim = g.q_dim();
const int64_t kv_dim = g.kv_dim();
/* ---- two KV groups (spec §7.2): the sliding layers' pool recycles blocks below the window,
* the full layers' does not. A group with no bound layers is a declare error. */
const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16);
RadKVGroupDecl sd{};
sd.kind = RAD_KV_WINDOW;
sd.dtype = kvdt;
sd.window = m.window;
sd.n_head_kv = g.n_head_kv;
sd.head_dim = g.head_dim;
m.kv_win = rad_decl_kv_group(b, nm.f("kv_sliding"), &sd);
RadKVGroupDecl gd{};
gd.kind = RAD_KV_FULL;
gd.dtype = kvdt;
gd.n_head_kv = g.n_head_kv;
gd.head_dim = g.head_dim;
m.kv_full = rad_decl_kv_group(b, nm.f("kv_full"), &gd);
g.kv_dtype = rad_dtype_name(kvdt);
if (m.kv_win == 0 || m.kv_full == 0) {
fprintf(stderr, "radiance: museglimmer: a KV group failed to declare\n");
return RAD_E_INVAL;
}
/* ---- activation buffers, sized at max_tok and shared by every layer; liveness 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});
m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim});
m.b_gate = decl_b(b, nm.f("attn_gate"),g.act_dtype, {g.max_tok, q_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});
m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim});
m.b_gu = 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 only (RadBatch::out_ids), not the whole step. */
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 drafter's taps. Declared before the trunk's layers: the buffer planner takes
* lifetimes in declaration order, so a tap buffer declared after them could share bytes a
* layer temporary lands on, and acceptance would collapse with no other symptom. */
if (ctx->max_spec > 0 && m.taps.read(meta, g.n_layer) > 0) {
RAD_ARCH_TRY(m.taps.declare(b, nm, g, g.max_tok, m.b_x, g.act_dtype));
if (m.taps.n <= 0) {
fprintf(stderr, "radiance: museglimmer: the container carries a drafter whose "
"draft.target_layer_ids name no layer of this %lld-layer trunk\n",
(long long)g.n_layer);
return RAD_E_INVAL;
}
}
/* ---- vocabulary edges, both row-sharded. The 30B does not tie its head; the second source
* serves family members that do, first present wins. */
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")));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("model.language_model.embed_tokens.weight")));
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());
/* A plain RMSNorm with a gain: declared at f32, cast at load, read with wadd 0. */
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});
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});
/* The embedding norm, after the vocabulary shard's reduction: a weightless RMS norm at
* rms_norm_eps, in place. Weightless because MuseGlimmerTextNormedEmbedding has no gain. */
m.op_embed_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_x}, {m.b_x});
/* The encoder's rows overwrite the lookup before its reduction (as rad_block_vit.h's
* MediaRows): declared only when the tower is served, issued on the passes that carry rows,
* so the reduction counts each row once. */
m.media = MuseTower::present(meta) && ctx->max_enc_patches > 0;
if (m.media)
m.op_media_rows = rw(b, RAD_OP(b, "scatter_rows",
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_x});
/* ---- calibration: the widest split input bounds the Hessian's width. */
RAD_ARCH_TRY(m.calib.begin(b, nm, g, ctx, g.n_layer,
std::max({g.n_embd, q_dim * g.world, g.n_ff * g.world}),
std::max({g.n_embd, q_dim * g.world, g.n_ff * g.world})));
/* ---- the layers. */
const int64_t attn_scale_num = 1; /* attention scale stays 1/sqrt(head_dim): the query's
* qk_scale_factor rides the q norm's `mult`. */
(void)attn_scale_num;
m.layers.resize((size_t)g.n_layer);
for (int64_t l = 0; l < g.n_layer; ++l) {
Layer& lay = m.layers[(size_t)l];
lay.full = full[(size_t)l];
lay.rope = theta[(size_t)l] > 0.0f;
const bool glob = lay.full;
rad_kvgroup kg = glob ? m.kv_full : m.kv_win;
const char* pre = "model.language_model.layers";
const Geom& gr = lay.rope ? m.g_rope : m.g;
/* -- weights. Shapes are [out, in]; gemm_nt reads B transposed. */
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),
nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l)));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_post.weight", l),
nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l)));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l),
nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l)));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_gate.weight", l),
nm.ckpt("%s.%lld.self_attn.gate_proj.weight", pre, (long long)l)));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l),
nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l)));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l),
nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l)));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l),
nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l)));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l),
nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l)));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_post.weight", l),
nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l)));
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ffn_gate_up.weight", l),
{nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l),
nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l)},
0));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_down.weight", l),
nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l)));
lay.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));
lay.w_post = decl_w(b, nm.f("blk.%d.attn_post.weight", l), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
lay.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));
lay.w_gate = decl_w(b, nm.f("blk.%d.attn_gate.weight", l), RAD_BF16, {q_dim, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
lay.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));
lay.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));
lay.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));
lay.w_fnorm = 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));
lay.w_fpost = decl_w(b, nm.f("blk.%d.ffn_post.weight", l), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
lay.w_gate_up= decl_w(b, nm.f("blk.%d.ffn_gate_up.weight", l), RAD_BF16,
{2 * g.n_ff, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
grp_layer(l), 0, {g.n_ff, g.n_ff});
lay.w_down = decl_w(b, nm.f("blk.%d.ffn_down.weight", l), RAD_BF16, {g.n_embd, g.n_ff},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
/* -- ops, in run order except attn_paged, declared before kv_store like every family: the
* two touch disjoint buffers and the block size comes from the resolved kernel. */
lay.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", 1.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_norm)),
{m.b_x}, {m.b_h});
lay.op_q = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_q)),
{m.b_h}, {m.b_q});
lay.op_gate = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_gate)),
{m.b_h}, {m.b_gate});
lay.op_k = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_k)),
{m.b_h}, {m.b_k});
lay.op_v = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_v)),
{m.b_h}, {m.b_v});
/* The q/k norms are weightless (no gain operand), the query carrying qk_scale_factor on
* `mult`. Both run in place: a row's scale is computed before the row is written. */
lay.op_qn = 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("mult", (double)m.qk_mult), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_q}, {m.b_q});
lay.op_kn = 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_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_k}, {m.b_k});
if (lay.rope) {
lay.op_rq = rw(b, decl_rope(b, gr, g.max_tok, g.head_dim, g.n_head, 0, n_rot, "neox"),
{m.b_q}, {m.b_q});
lay.op_rk = rw(b, decl_rope(b, gr, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, "neox"),
{m.b_k}, {m.b_k});
}
lay.op_attn = rw(b, rad_decl_op(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa()),
RAD_INT("causal", 1),
RAD_INT("window", glob ? 0 : m.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),
{m.b_q}, {m.b_attn});
lay.op_kv = 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, kg)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{m.b_k, m.b_v}, {});
/* out = attn * sigmoid(gate): two ops, as in the gated-attention block. */
lay.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),
{m.b_gate}, {m.b_gate});
lay.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),
{m.b_attn, m.b_gate}, {m.b_attn});
lay.op_o = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
RAD_INT("K", q_dim), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_o)),
{m.b_attn}, {m.b_h});
if (g.world > 1)
lay.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),
{m.b_h}, {m.b_h});
/* The branch's own norm, at post_norm_eps, before the residual add. */
lay.op_post = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", m.post_eps), RAD_F64("wadd", 1.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_post)),
{m.b_h}, {m.b_h});
lay.op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_x, m.b_h}, {m.b_x});
/* ---- the feed-forward, the same double norm. */
lay.op_fnorm = 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", 1.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_fnorm)),
{m.b_x}, {m.b_h});
lay.op_gu = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_gate_up)),
{m.b_h}, {m.b_gu});
lay.op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_gu}, {m.b_ffn});
lay.op_down = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
RAD_INT("K", g.n_ff), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_down)),
{m.b_ffn}, {m.b_h});
if (g.world > 1)
lay.op_far = 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),
{m.b_h}, {m.b_h});
lay.op_fpost = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_F64("eps", m.post_eps), RAD_F64("wadd", 1.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(lay.w_fpost)),
{m.b_h}, {m.b_h});
lay.op_fadd = 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});
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
/* -- calibration taps, the same four a dense family records. */
if (m.calib.records(l)) {
const std::string L = std::string(pre) + "." + std::to_string(l);
lay.cs_in = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".input",
L + ".self_attn.q_proj," + L + ".self_attn.k_proj," +
L + ".self_attn.v_proj," + L + ".self_attn.gate_proj",
m.b_h, g.n_embd, g.n_embd));
lay.cs_o = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".self_attn.o_proj.input", L + ".self_attn.o_proj",
m.b_attn, q_dim, q_dim * g.world));
lay.cs_mlp = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".pre_feedforward.input",
L + ".mlp.gate_proj," + L + ".mlp.up_proj",
m.b_h, g.n_embd, g.n_embd));
lay.cs_down = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".mlp.down_proj.input", L + ".mlp.down_proj",
m.b_ffn, g.n_ff, g.n_ff * g.world));
}
}
/* ---- the head. The final norm is a plain RMSNorm (wadd 0) that also carries the logits'
* pre-scale: its output feeds only the head, so mult here is logits * output_multiplier
* exactly. */
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_F64("mult", (double)m.out_mult), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.w_out_norm)),
{m.b_x}, {m.b_h});
if (m.calib.on && m.calib.hi == g.n_layer) {
m.cs_head = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site(b, g, -1, "lm_head.input", "lm_head", m.b_h, g.n_embd, g.n_embd));
}
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});
/* cap * tanh(x / cap) over the f32 logits, after the pre-scale. */
if (m.softcap > 0.0f) {
m.op_cap = rw(b, RAD_OP(b, "logit_softcap",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n", g.n_vocab), RAD_F64("cap", (double)m.softcap),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{m.b_logits}, {m.b_logits});
if (!m.op_cap)
rad_note(b, "warning: no kernel serves `logit_softcap` (load libr4d or libavx), so "
"the logits skip %g * tanh(x / %g): greedy output is unchanged, sampled "
"output draws from a sharper distribution", (double)m.softcap,
(double)m.softcap);
}
/* ---- media: the vision tower, declared last so its activations share the arena with every
* buffer above (the trunk's weights were mapped and declared first). */
if (m.media)
RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer));
/* ---- the drafter is declared last so its buffers cannot overlap trunk temporaries. */
if (m.taps.n > 0) {
if (muse_draft_is_dflash2(meta)) {
RAD_ARCH_TRY(declare_muse_dflash2(&m.df2, &m.df2w, &m.kv_draft, b, nm, meta, ctx, g,
m.taps, (int)g.n_layer, m.w_tok, m.w_lm_head));
m.have_df2 = true;
} else {
RAD_ARCH_TRY(declare_muse_dflash(&m.df, &m.dfw, &m.kv_draft, b, nm, meta, ctx, g,
m.taps, (int)g.n_layer, m.w_tok, m.w_lm_head));
m.have_df = true;
}
}
/* ---- notes for --debug-graph. */
int64_t nfull = 0, nrope = 0;
for (int64_t l = 0; l < g.n_layer; ++l) {
nfull += full[(size_t)l];
nrope += theta[(size_t)l] > 0.0f;
}
rad_note(b, "rank %d/%d: %lld layers (%lld full attention, %lld sliding over a %lld-token "
"window; %lld with rotary at theta %g), n_head=%lld n_head_kv=%lld head_dim=%lld "
"n_ff=%lld vocab=[%lld,%lld)",
g.rank, g.world, (long long)g.n_layer, (long long)nfull,
(long long)(g.n_layer - nfull), (long long)m.window, (long long)nrope,
theta_rope, (long long)g.n_head, (long long)g.n_head_kv, (long long)g.head_dim,
(long long)g.n_ff, (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab));
rad_note(b, "centered norms (1 + w): input/pre at eps %g, post at eps %g; the final norm is a "
"plain gain; the embedding and the q/k norms are weightless", (double)g.eps,
(double)m.post_eps);
rad_note(b, "attention scale 1/sqrt(%lld) with the query pre-scaled by qk_scale_factor %g; "
"logits pre-scaled by output_multiplier %g%s%g",
(long long)g.head_dim, (double)m.qk_mult, (double)m.out_mult,
m.softcap > 0.0f ? " and soft-capped at " : "", (double)m.softcap);
if (m.g_rope.theta != g.theta)
rad_note(b, "rotary runs on the sliding layers only (theta %g); the full-attention layers "
"are NoPE", (double)m.g_rope.theta);
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);
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = g_model[rad_slot(c)];
/* An encoder pass runs only the vision tower (RadBatch::enc). */
if (batch->enc) {
m.vit.step(c, batch);
return;
}
/* A draft pass runs only the drafter: >0 the query pass on the staged block, <0 the context
* pass that projects and stores K/V for the tokens the trunk just committed. */
if (batch->draft_pass != 0) {
if (m.have_df2) {
if (batch->draft_pass > 0) m.df2.step(c, batch);
else m.df2.context(c, batch);
return;
}
if (!m.have_df) {
rad_step_fail(c, "this serve stages a draft pass but the container carries no drafter");
return;
}
if (batch->draft_pass > 0) m.df.step(c, batch);
else m.df.context(c, batch);
return;
}
RAD_ISSUE(c, m.op_embed,
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok),
brows(m.b_x, batch->n_tok));
/* The encoder's rows overwrite the lookup before the vocabulary shard's reduction, so the
* reduction counts each row once. */
if (m.op_media_rows && batch->n_mm_rows > 0)
RAD_ISSUE_N(c, m.op_media_rows, batch->n_mm_rows,
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, m.g.n_embd),
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows),
brows(m.b_x, batch->n_tok));
/* The vocab shard's reduction; declared only when world > 1, so tp1 is unchanged. */
if (m.op_embed_ar)
RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
brows(m.b_x, batch->n_tok), RAD_NONE);
/* The embedding norm, after the reduction: it normalises whole rows. */
RAD_ISSUE(c, m.op_embed_norm, brows(m.b_x, batch->n_tok), RAD_NONE, brows(m.b_x, batch->n_tok));
const int64_t T = batch->n_tok;
for (size_t li = 0; li < m.layers.size(); ++li) {
const Layer& l = m.layers[li];
const rad_kvgroup kg = l.full ? m.kv_full : m.kv_win;
const RadKVGroupBatch* kvb = kv_batch(batch, kg);
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;
/* -- attention. The first Hessian sees the normalized input consumed by q/gate/k/v. */
RAD_ISSUE(c, l.op_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T));
if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, T);
RAD_ISSUE(c, l.op_q, brows(m.b_h, T), RAD_W(l.w_q), brows(m.b_q, T));
RAD_ISSUE(c, l.op_gate, brows(m.b_h, T), RAD_W(l.w_gate), brows(m.b_gate, 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_qn, T * m.g.n_head, brows(m.b_q, T), RAD_NONE, brows(m.b_q, T));
RAD_ISSUE_N(c, l.op_kn, T * m.g.n_head_kv, brows(m.b_k, T), RAD_NONE, brows(m.b_k, T));
if (l.rope) {
RAD_ISSUE(c, l.op_rq, brows(m.b_q, T), rope_posmc(m.g, batch, T));
RAD_ISSUE(c, l.op_rk, brows(m.b_k, T), rope_posmc(m.g, batch, T));
}
RAD_ISSUE(c, l.op_kv,
brows(m.b_k, T), brows(m.b_v, T), praw(slot, RAD_I32, T),
kv_cache(kg, (int)li));
/* The longest query length, not the token count, selects the attention band. */
RAD_ISSUE_N(c, l.op_attn, batch->max_q_len,
brows(m.b_q, T), kv_cache(kg, (int)li),
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(m.b_attn, T));
RAD_ISSUE_N(c, l.op_sig, T * m.g.n_head, brows(m.b_gate, T), brows(m.b_gate, T));
RAD_ISSUE(c, l.op_mul, brows(m.b_attn, T), brows(m.b_gate, T), brows(m.b_attn, T));
if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, T);
RAD_ISSUE(c, l.op_o, brows(m.b_attn, T), RAD_W(l.w_o), brows(m.b_h, T));
if (l.op_ar) RAD_ISSUE_N(c, l.op_ar, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE);
RAD_ISSUE(c, l.op_post, brows(m.b_h, T), RAD_W(l.w_post), 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));
/* -- feed-forward. */
RAD_ISSUE(c, l.op_fnorm, brows(m.b_x, T), RAD_W(l.w_fnorm), brows(m.b_h, T));
if (l.cs_mlp >= 0) m.calib.tap(c, (size_t)l.cs_mlp, T);
RAD_ISSUE(c, l.op_gu, brows(m.b_h, T), RAD_W(l.w_gate_up), brows(m.b_gu, T));
RAD_ISSUE(c, l.op_act, brows(m.b_gu, T), brows(m.b_ffn, T));
if (l.cs_down >= 0) m.calib.tap(c, (size_t)l.cs_down, T);
RAD_ISSUE(c, l.op_down, brows(m.b_ffn, T), RAD_W(l.w_down), brows(m.b_h, T));
if (l.op_far) RAD_ISSUE_N(c, l.op_far, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE);
RAD_ISSUE(c, l.op_fpost, brows(m.b_h, T), RAD_W(l.w_fpost), brows(m.b_h, T));
RAD_ISSUE(c, l.op_fadd, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
/* The drafter reads this layer's completed residual, if it taps it. */
m.taps.step(c, m.b_x, T, (int64_t)li, m.g.n_embd);
}
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));
if (m.cs_head >= 0) m.calib.tap(c, (size_t)m.cs_head, T);
m.calib.after_step(c, T);
/* 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),
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));
if (m.op_cap)
RAD_ISSUE_N(c, m.op_cap, batch->n_out, brows(m.b_logits, batch->n_out),
brows(m.b_logits, batch->n_out));
}
}
/* What the plugin says before it declares anything: this family's tower merges 4 patches into a
* row, so an automatic --mm-max-patches rounds to whole merged rows. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
if (MuseTower::present(meta)) out->enc_merge = 4;
/* DFlash2 reads block_size from dflash_config; its anchor row proposes nothing. */
if (muse_draft_is_dflash2(meta)) {
const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 16);
out->draft_depth = bs > 1 ? (int)(bs - 1) : 15;
out->draft_depth_fixed = 1;
return RAD_OK;
}
/* Meta DFlash denoises `block_size` positions; the anchor proposes nothing. */
const long long bs = rad_meta_geti(meta, "draft.block_size", 0);
if (bs > 1) {
out->draft_depth = (int)(bs - 1);
out->draft_depth_fixed = 1;
}
return RAD_OK;
}
static const RadChatFormat* chat_format(const RadModelMeta*) {
return muse_chat_format();
}
} /* namespace museglimmer */
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(museglimmer)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(museglimmer, "museglimmer", "", "0.1.0",
"Meta Muse Glimmer 30B dense, bf16 weights and activations, gated attention "
"alternating sliding-window (rotary) and NoPE full-attention layers, Gemma-2 "
"style double norms")
RAD_ARCH_CHAT_FORMAT(museglimmer)
#endif
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/museglimmer_ct -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(museglimmer_ct LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(museglimmer_ct architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/museglimmer_ct.cpp)
File diff suppressed because it is too large. Load diff
+10 -5
View File
@@ -36,7 +36,8 @@ struct Model {
std::vector<Layer> layers;
Pixtral vision;
};
static Model model;
/* One per engine instance in the process, by slot (rad_builder.h, rad_build_slot). */
static Model g_model[RAD_MAX_SLOTS];
/* JSON booleans reach plugins as 0/1, while out-of-tree callers may use their JSON spelling. */
static bool false_value(const char* s) {
@@ -86,7 +87,9 @@ static int read_rope(Geom& g, const RadModelMeta* meta) {
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->max_seqs <= 0) return RAD_E_INVAL;
if (!b || !meta || !ctx || ctx->max_seqs <= 0 || ctx->rank < 0 ||
rad_build_slot(ctx) >= RAD_MAX_SLOTS)
return RAD_E_INVAL;
if (ctx->rank != 0 || ctx->world_size > 1 || ctx->is_draft || ctx->max_spec > 0) {
std::fprintf(stderr, "radiance: nemotron35_embed serves BF16 at TP1, without drafting\n");
return RAD_E_UNSUPPORTED;
@@ -116,8 +119,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
rad_meta_geti(meta, "text_config.rope_parameters.original_max_position_embeddings", 0);
if (!std::isfinite(beta) || beta < 0 || original <= 0) return RAD_E_INVAL;
model = Model{};
Model& m = model;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.rerank =
!std::strcmp(rad_meta_gets(meta, "architectures", ""), "Mistral3ForSequenceClassification");
const char* architecture = rad_meta_gets(meta, "architectures", "");
@@ -340,7 +343,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = model;
const Model& m = g_model[rad_slot(c)];
const Geom& g = m.g;
if (batch->enc) {
m.vision.step(c, batch);
@@ -399,6 +402,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
} // namespace nemotron35_embed
#ifndef RAD_ARCH_NO_EXPORTS
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(nemotron35_embed, "mistral3", "", "0.5.0",
"Nemotron-3.5-Embed/Rerank: experimental BF16 text/image retrieval, TP1")
RAD_ARCH_PROBE(nemotron35_embed)
+7
View File
@@ -0,0 +1,7 @@
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(nemotronh LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(nemotronh architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/nemotronh.cpp)
File diff suppressed because it is too large. Load diff
+348
View File
@@ -0,0 +1,348 @@
/* radio.h -- Nemotron-H Omni's vision encoder: C-RADIO (v4-H) and the projector after it (mlp1).
*
* Per encoder pass (RadBatch::enc). The processor (core/mm, Family::Radio) gives every segment
* `n_prefix` zero rows ahead of its patches, with coordinate (-1, k):
*
* x = rows @ W^T one GEMM for both projections: a row is a
* tubelet's frames then a picture's patch, the part
* not in use zero, and W = [video_embedder |
* embedder] concatenated at convert; no bias
* x += CPE(table, row, col), or prefix[k] grid_embed_cpe: the 128 x 128 table resampled
* half-pixel bilinear onto a square of the grid's
* longer side and cropped to it; a prefix row takes
* the k-th class or register token
* depth times (pre-norm, LayerScale 1):
* x += proj(attn(qkv(LN1(x)))) full attention within a segment, no rotary
* x += fc2(gelu(fc1(LN2(x)))) exact GELU
* y = each segment's patch rows gather_rows: the prefix rows dropped
* out = l2(relu(l1(rms(y viewed [P/4, 4 * width])))^2)
*
* which is transformers' RadioModel (make_preprocessor_external) then NemotronH_Omni's vision
* projector with vision_final_layernorm off. The pixel shuffle (ps v2) is the view: the processor
* keeps a 2 x 2 block's patches consecutive, (dy, dx), the order the shuffle concatenates them;
* the tower is order-independent within a segment (attention is permutation-equivariant, every
* other layer is per row, the position term is sampled at each row's own coordinate).
*
* A pass is one grid (RadEncoderDecl::one_grid), so its segments are equally long and each
* segment's patch rows sit at a fixed offset, which `step` gathers with slices of one identity
* index. Replicated, per-request weights and pass-sized activations, as in
* arch/common/rad_block_vit.h's tower.
*/
#ifndef NEMOTRONH_RADIO_H
#define NEMOTRONH_RADIO_H
#include <arch/rad_arch.h>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace nemotronh {
using namespace rad::arch;
struct Radio {
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, merge = 0, side = 0, npre = 0;
int64_t tubelet = 0, head_dim = 0, patch_dim = 0, proj_hidden = 0, n_embd = 0, P = 0, R = 0;
float eps = 1e-6f;
bool 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, w_pos = 0, w_pre = 0, mn_w = 0, m1_w = 0, m2_w = 0;
rad_op op_patch = 0, op_pos = 0, op_seq = 0, op_gather = 0, op_mln = 0, op_m1 = 0;
rad_op op_act = 0, op_m2 = 0;
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_seq = 0, b_g = 0, b_mn = 0;
rad_buf b_mf = 0, b_ma = 0, b_out = 0;
/* A tower to declare: the container is a Nemotron-H Omni one, whose vision_config is RADIO's. */
static bool present(const RadModelMeta* m) {
return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "radio") &&
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 Radio::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 = (int64_t)std::llround(rad_meta_getf(m, "vision_config.mlp_ratio", 0.0) * (double)width);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
eps = (float)rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-6);
side = rad_meta_geti(m, "vision_config.max_img_size", 0) / (patch > 0 ? patch : 1);
npre = rad_meta_geti(m, "vision_config.num_cls_tokens", 0) +
rad_meta_geti(m, "vision_config.num_registers", 0);
tubelet = rad_meta_geti(m, "vision_config.video_temporal_patch_size",
rad_meta_geti(m, "video_temporal_patch_size", 0));
const double ratio = rad_meta_getf(m, "downsample_ratio", 0.0);
merge = ratio > 0.0 ? (int64_t)std::llround(1.0 / ratio) : 0;
proj_hidden = rad_meta_geti(m, "projector_hidden_size", 0);
n_embd = model_embd;
const int64_t chans = rad_meta_geti(m, "vision_config.num_channels", 3);
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || side <= 0 ||
npre <= 0 || tubelet <= 0 || merge <= 0 || proj_hidden <= 0 || width % heads ||
chans != 3) {
fprintf(stderr, "radiance: nemotronh: the container's RADIO vision_config is incomplete or "
"inconsistent (layers %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
"table %lld, prefix %lld, tubelet %lld, merge %lld, projector %lld)\n",
(long long)depth, (long long)width, (long long)heads, (long long)ff,
(long long)patch, (long long)side, (long long)npre, (long long)tubelet,
(long long)merge, (long long)proj_hidden);
return RAD_E_INVAL;
}
/* What this tower serves of RADIO's options: the plain GELU MLP, LayerScale 1 (no stored
* scales), q/k/v with biases, and no final layer norm before the projector. */
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu");
const bool swiglu = rad_meta_geti(m, "vision_config.use_swiglu_ffn", 0) != 0 ||
!std::strcmp(rad_meta_gets(m, "vision_config.use_swiglu_ffn", ""), "true");
const bool final_ln = rad_meta_geti(m, "vision_final_layernorm", 0) != 0 ||
!std::strcmp(rad_meta_gets(m, "vision_final_layernorm", ""), "true");
if (std::strcmp(act, "gelu") || swiglu || final_ln ||
rad_meta_getf(m, "vision_config.layerscale_value", 1.0) != 1.0) {
fprintf(stderr, "radiance: nemotronh: this RADIO tower (activation '%s'%s%s, layer scale "
"%g) is not the one served: GELU MLP, layer scale 1, no final layer norm\n",
act, swiglu ? ", SwiGLU" : "", final_ln ? ", final layer norm" : "",
rad_meta_getf(m, "vision_config.layerscale_value", 1.0));
return RAD_E_UNSUPPORTED;
}
head_dim = width / heads;
const int64_t pp = chans * patch * patch;
patch_dim = pp * (1 + tubelet);
const int64_t mm = merge * merge, mw = mm * width;
/* A pass's rows, prefix rows included; the output rows are at most a quarter of them. */
P = ctx->max_enc_patches;
const int64_t max_seg = P;
if (ctx->shape_probe) {
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
P = std::max<int64_t>(mm, r / mm * mm);
}
R = P / mm;
if (R <= 0) return RAD_E_SHAPE;
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* pg = "vision_model.radio_model.model.patch_generator.";
/* [video_embedder | embedder] along K: one GEMM for a row of either kind. */
if (map_concat(b, nm.f("v.patch.weight"),
{ nm.ckpt("%svideo_embedder.weight", pg), nm.ckpt("%sembedder.weight", pg) },
1) < 0)
return RAD_E_INVAL;
/* Whether the tower is here at all: its stem's encoding, which convert answers from the
* checkpoint and load from the container alike. A text-only cut (a few blocks for a host
* reference) or a container converted without it serves text; the map left behind is inert. */
{
RadEncoding enc;
if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) {
rad_note(b, "nemotronh: vision_config names a RADIO tower its weights are not here "
"for; serving text");
return RAD_OK;
}
}
w_patch = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim }, ACC,
RAD_SHARD_NONE, grp_model());
/* The checkpoint's [1, side * side, width] read as the [side * side, width] table. */
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%spos_embed", pg), { side * side, width }, grp_model());
w_pre = bw(nm.f("v.prefix.weight"), nm.ckpt("%scls_token.token", pg), { npre, 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 = "vision_model.radio_model.model.blocks.%d.%s";
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt(e, li, "norm1.weight"), { width }, g);
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt(e, li, "norm1.bias"), { width }, g);
l.qkv_w = bw(nm.f("v.blk.%d.qkv.weight", li), nm.ckpt(e, li, "attn.qkv.weight"), { 3 * width, width }, g);
l.qkv_b = bw(nm.f("v.blk.%d.qkv.bias", li), nm.ckpt(e, li, "attn.qkv.bias"), { 3 * width }, g);
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt(e, li, "attn.proj.weight"), { width, width }, g);
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt(e, li, "attn.proj.bias"), { width }, g);
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt(e, li, "norm2.weight"), { width }, g);
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt(e, li, "norm2.bias"), { width }, g);
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt(e, li, "mlp.fc1.weight"), { ff, width }, g);
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt(e, li, "mlp.fc1.bias"), { ff }, g);
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt(e, li, "mlp.fc2.weight"), { width, ff }, g);
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt(e, 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;
}
mn_w = bw(nm.f("v.proj.norm.weight"), nm.ckpt("mlp1.0.weight"), { mw }, grp_model());
m1_w = bw(nm.f("v.proj.fc1.weight"), nm.ckpt("mlp1.1.weight"), { proj_hidden, mw }, grp_model());
m2_w = bw(nm.f("v.proj.fc2.weight"), nm.ckpt("mlp1.3.weight"), { n_embd, proj_hidden }, grp_model());
if (!w_patch || !w_pos || !w_pre || !mn_w || !m1_w || !m2_w) return RAD_E_INVAL;
/* ---- activations. `g` holds the gathered patch rows at `width` and is read by the norm as
* R rows of mm * width (the pixel shuffle'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 });
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_seq = decl_b(b, nm.f("v.seq"), RAD_I32, { P });
b_g = decl_b(b, nm.f("v.g"), RAD_BF16, { R, mw });
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_ma = decl_b(b, nm.f("v.ma"), 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_seq || !b_g || !b_mn || !b_mf || !b_ma ||
!b_out)
return RAD_E_INVAL;
auto gemm_b = [&](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 gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op {
return RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto lnorm = [&](int64_t rows, rad_weight w, rad_weight bias) -> rad_op {
return RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
op_patch = rw(b, gemm(P, width, patch_dim, w_patch), {}, { b_x });
op_pos = rw(b, RAD_OP(b, "grid_embed_cpe",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("side", side), RAD_INT("n_prefix", npre),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_pos, w_pre)),
{ b_x }, { b_x });
op_seq = rw(b, RAD_OP(b, "iota",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("start", 0), RAD_INT("step", 1)),
RAD_NOWEIGHTS),
{}, { b_seq });
for (Layer& l : L) {
l.ln1 = rw(b, lnorm(P, l.n1w, l.n1b), { b_x }, { b_h });
l.qkv = rw(b, gemm_b(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_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_x }, { b_x });
l.ln2 = rw(b, lnorm(P, l.n2w, l.n2b), { b_x }, { b_h });
l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff });
l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_x }, { b_x });
}
op_gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_x, b_seq }, { b_g });
op_mln = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", mw), RAD_F64("eps", 1e-5),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(mn_w)),
{ b_g }, { b_mn });
op_m1 = rw(b, gemm(R, proj_hidden, mw, m1_w), { b_mn }, { b_mf });
/* relu(x)^2: act_mul's "relu" with the one tensor in both operands. */
op_act = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_hidden),
RAD_STR("act", "relu"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_mf }, { b_ma });
op_m2 = rw(b, gemm(R, n_embd, proj_hidden, m2_w), { b_ma }, { b_out });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = mm;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.one_grid = 1;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "RADIO tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld "
"(tubelet %lld), %lld x %lld position table, %lld prefix rows; projector %lld "
"-> %lld -> %lld; %lld rows a pass",
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
(long long)ff, (long long)patch, (long long)tubelet, (long long)side,
(long long)side, (long long)npre, (long long)mw, (long long)proj_hidden,
(long long)n_embd, (long long)P);
}
on = true;
return RAD_OK;
}
inline void Radio::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;
const int64_t gh = S > 0 && batch->enc_seg_h ? batch->enc_seg_h[0] : 0;
const int64_t gw = S > 0 && batch->enc_seg_w ? batch->enc_seg_w[0] : 0;
const int64_t seg = npre + gh * gw, Rn = S * gh * gw / (mm > 0 ? mm : 1);
if (!on || Pn <= 0 || Pn > P || S <= 0 || gh <= 0 || gw <= 0 || (gh * gw) % mm ||
S * seg != Pn || Rn > R) {
rad_step_fail(c, "nemotronh: an encoder pass this program's RADIO tower cannot serve: no "
"tower, more rows than it was declared for, or segments that are not one "
"grid of whole merged rows behind their prefix rows");
return;
}
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), brows(b_x, Pn));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd, RAD_W(w_pre));
RAD_ISSUE_N(c, op_seq, Pn, brows(b_seq, Pn));
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));
}
/* Each segment's patch rows, behind its prefix rows, into `g` at width: segment s's are rows
* [s * seg + npre, (s + 1) * seg) of x, which the identity index names by a slice. */
const int64_t hw = gh * gw;
for (int64_t s = 0; s < S; ++s)
RAD_ISSUE_N(c, op_gather, hw, brows(b_x, Pn), brow_slice(b_seq, s * seg + npre, hw, 1),
brow_slice(b_g, s * hw / mm, hw / mm, mm * width));
RAD_ISSUE_N(c, op_mln, Rn, brows(b_g, Rn), RAD_W(mn_w), brows(b_mn, Rn));
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mn, Rn), RAD_W(m1_w), brows(b_mf, Rn));
RAD_ISSUE_N(c, op_act, Rn, brows(b_mf, Rn), brows(b_mf, Rn), brows(b_ma, Rn));
RAD_ISSUE_N(c, op_m2, Rn, brows(b_ma, Rn), RAD_W(m2_w), brows(b_out, Rn));
}
} /* namespace nemotronh */
#endif /* NEMOTRONH_RADIO_H */
+7 -4
View File
@@ -71,7 +71,7 @@ struct Model {
std::vector<Layer> layers;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
/* The layer schedule, read from moe_every_n_layers rather than derived: a wrong interval would
* declare a MoE layer whose tensors the checkpoint does not hold. Layer l is routed when
@@ -93,7 +93,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
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;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
/* A 475M-parameter encoder fits one card; tensor parallelism would only add an all-reduce per
* layer. */
if (ctx->world_size > 1) {
@@ -102,7 +103,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
@@ -441,7 +442,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Model& m = g_model[rad_slot(c)];
const Geom& g = m.g;
const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd;
if (T <= 0 || S <= 0) return;
@@ -500,6 +501,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
} /* namespace nomicbert */
#ifndef RAD_ARCH_NO_EXPORTS
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(nomicbert, "nomicbert", "", "0.1.0",
"Nomic BERT (nomic-embed-text-v2-moe): a bidirectional post-norm encoder with "
"NeoX rotary attention, dense and routed GELU feed-forwards, mean-pooled to one "
+21 -5
View File
@@ -103,14 +103,16 @@ struct Model {
};
/* 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];
* model state is per instance: indexed by the instance's slot (unique across every engine in the
* process, rad_build_slot) and read back in step() with rad_slot(). */
static Model g_model[MAX_SLOTS];
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
@@ -479,7 +481,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)];
Model& m = g_model[rad_slot(c)];
/* An encoder pass runs only the vision tower (RadBatch::enc). */
if (batch->enc) {
@@ -539,9 +541,23 @@ static void step(RadCtx* c, const RadBatch* batch) {
}
}
/* Chained launches pay on the plain-bf16 trunk with a drafter and without one: every kernel of
* its decode step but the gated delta net's two and the vocabulary GEMM has a chained form
* (libr4d's rad_kernel_chain). Ms a decode step unchained / chained: Qwen3.5-0.8B on one R9700
* 3.89 / 3.60 at one sequence and 4.72 / 4.46 at four; Qwen3.8-27B as bf16 on two, where the
* bf16 GEMMs are nearly all of the step, 48.04 / 47.41 and 49.57 / 48.81. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->chain_pays = RAD_CHAIN_ALWAYS;
return RAD_OK;
}
} /* namespace qwen35_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PROBE(qwen35_bf16)
RAD_ARCH_PLUGIN(qwen35_bf16, "qwen35", "", "0.1.0",
"Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), bf16 weights and activations, gated "
"attention over paged KV every fourth layer and gated delta net between")
+263 -98
View File
@@ -56,16 +56,17 @@
*
* Its differences are behind `#if QWEN35_W8A8`: check_format's method, the probe that learns the
* trunk is int8 before the activations are declared (and refuses one that is not), and the plugin
* identity. The int8 activation pairs follow from the probe. */
* identity. The int8 activation pairs follow from the probe.
*
* Both macros together are `qwen35moe_w8a8`, the routed build with that trunk: the experts are
* rotated too (int8 at a bf16 scale a 128 of K, or the four-bit forms) and read the int8 codes the
* trunk's own quantisers write (rad_block_moe_fp8.h, MoeFP8::a8). */
#ifndef QWEN35_MOE
#define QWEN35_MOE 0
#endif
#ifndef QWEN35_W8A8
#define QWEN35_W8A8 0
#endif
#if QWEN35_MOE && QWEN35_W8A8
#error "qwen35_w8a8 is the dense build; a routed int8 trunk is not a format this file serves"
#endif
/* The plugin's name for a message, expanded once more so it is QWEN35_NS's value. */
#define QWEN35_STR_X(x) #x
#define QWEN35_STR(x) QWEN35_STR_X(x)
@@ -80,6 +81,7 @@
#include <arch/rad_arch.h>
#include <arch/rad_block_attn_gated_fp8.h>
#include <arch/rad_block_gdn_fp8.h>
#include <arch/rad_calib_full.h>
#include <arch/rad_block_mlp_fp8.h>
#if QWEN35_MOE
#include <arch/rad_block_moe_fp8.h>
@@ -134,6 +136,9 @@ struct Layer {
* beside the feed-forward's; 0 where none is declared. */
rad_op op_pf_gu = 0, op_pf_next = 0;
rad_weight pf_gu_w = 0, pf_next_w = 0;
/* The layer's calibration inputs (rad_calib_full.h, site_i8), -1 where this run does not record
* it: the mixer's input and its output projection's, the feed-forward's and its down's. */
int cs_in = -1, cs_o = -1, cs_mlp = -1, cs_down = -1;
};
struct Model {
@@ -148,6 +153,8 @@ struct Model {
/* The trunk's linears are int8 (LinearFP8::i8), learned before the activations are declared
* because it decides whether they carry an int8 code pair. Only qwen35_w8a8 sets it. */
bool trunk_i8 = false;
/* The int8 trunk's scale group: 128, or 256 for IQ8R (linear_w8h_group). */
int64_t trunk_g8 = RAD_FP8_BLOCK;
/* the residual stream and the two vocabulary edges */
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
@@ -208,6 +215,12 @@ struct Model {
rad_op op_tap = 0;
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
/* A vocabulary-weighted head (logits_gemm_vocab): its width classes' codes, scales and rows'
* vocabulary ids, and this rank's rows of each. */
enum { MAX_VCLS = 4 };
int n_vcls = 0;
rad_weight w_vw[MAX_VCLS] = {}, w_vs[MAX_VCLS] = {}, w_vi[MAX_VCLS] = {}, w_vrow = 0;
int64_t vcls_rows[MAX_VCLS] = {};
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
/* Set by a plugin built over this one whose head answers a request from its words
* (RadBatch::plugin_words): a `fill` of the logits rows that plugin declared. A step every
@@ -224,6 +237,7 @@ struct Model {
MediaRows mrows{};
std::vector<Layer> layers;
CalibFull calib; /* --calib-dir over an int8 trunk (rad_calib_full.h) */
/* The pipelined prefill (step_pipelined): on where declare allowed it; the bounds buffer it
* cuts a step by, rewritten by every pipelined step from the pinned table `pipe_tbl` of
@@ -236,7 +250,7 @@ struct Model {
bool pipe_serial_noted = false;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
#if !QWEN35_MOE
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
@@ -258,9 +272,9 @@ static int check_format(const RadModelMeta* meta) {
/* The format the convert stated (the recipe's --set keys); the trunk probe in declare() holds
* the weights to it. */
if (!method || std::strcmp(method, "w8a8") != 0 || !fmt || std::strcmp(fmt, "fwht128") != 0) {
fprintf(stderr, "radiance: qwen35_w8a8 serves a container converted for an int8 trunk "
"(quant_method 'w8a8', fmt 'fwht128': data/recipes/"
"q38-27b-w8a8-df2.recipe's --set keys); this one says '%s' / '%s'.\n",
fprintf(stderr, "radiance: " QWEN35_STR(QWEN35_NS) " serves a container converted for an "
"int8 trunk (quant_method 'w8a8', fmt 'fwht128': data/recipes/"
"q38-27b-iq8r.recipe's --set keys); this one says '%s' / '%s'.\n",
method ? method : "(none)", fmt ? fmt : "(none)");
return RAD_E_UNSUPPORTED;
}
@@ -390,22 +404,34 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd});
dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff});
/* FP8 copies. The drafter's six linears are block-scaled fp8 over a bf16 checkpoint
* (rad_fp8.h's DenseFP8), so every activation feeding one has an E4M3 copy and an f32 scale
* plane. `srcq` is the largest (50 MiB at a 2048-token chunk and five taps) and halves the
* bytes of the context pass's dominant GEMM. */
dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3,
{dg.max_tok, dc.n_taps * dg.n_embd});
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32,
{dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)});
dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
dw.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, dg.n_embd});
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd});
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)});
dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff});
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
/* The codes the drafter's six linears read: every activation feeding one has an 8-bit copy
* and an f32 scale plane. E4M3 with a scale per 128 for block fp8 or MXFP4 linears (rad_fp8.h's
* DenseFP8), int8 with a scale per 128 or IQ8R's 256 for rotated int8 ones, which the drafter's
* `fc` tells apart.
* `srcq` is the largest (50 MiB at a 2048-token chunk and five taps) and halves the bytes of
* the context pass's dominant GEMM. */
RAD_ARCH_TRY(Dflash2::probe_i8(b, nm, "draft", &dc.act_i8, &dc.act_g8));
dc.fc_mapped = true;
const uint32_t dqt = dc.act_i8 ? RAD_I8 : RAD_F8E4M3;
const int64_t dqg = dc.act_i8 ? dc.act_g8 : (int64_t)RAD_FP8_BLOCK;
if (dc.act_i8 && ((dc.n_taps * dg.n_embd) % dqg || dg.n_embd % dqg || qd % dqg ||
dg.n_ff % dqg)) {
fprintf(stderr, "radiance: a rotated int8 drafter takes widths in whole %lld-column scale groups; "
"this one is n_embd %lld, q %lld, n_ff %lld\n", (long long)dqg,
(long long)dg.n_embd, (long long)qd, (long long)dg.n_ff);
return RAD_E_INVAL;
}
auto dqs = [&](int64_t n) { return (n + dqg - 1) / dqg; };
dw.srcq = decl_b(b, nm.f("df_srcq"), dqt, {dg.max_tok, dc.n_taps * dg.n_embd});
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, dqs(dc.n_taps * dg.n_embd)});
dw.cq = decl_b(b, nm.f("df_cq"), dqt, {dg.max_tok, dg.n_embd});
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, dqs(dg.n_embd)});
dw.h2q = decl_b(b, nm.f("df_h2q"), dqt, {qr, dg.n_embd});
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, dqs(dg.n_embd)});
dw.atq = decl_b(b, nm.f("df_atq"), dqt, {qr, qd});
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, dqs(qd)});
dw.ffq = decl_b(b, nm.f("df_ffq"), dqt, {qr, dg.n_ff});
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, dqs(dg.n_ff)});
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank});
dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd});
@@ -509,9 +535,10 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
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;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[ctx->rank];
Model& m = g_model[rad_build_slot(ctx)];
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
m = Model{};
m.nm = Names(ctx->scope);
@@ -620,51 +647,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- the three KV groups. The attention cache is bf16 by default; `kv_dtype` follows it.
*
* --kv-cache-dtype fp8 makes it E4M3. The cache is `n_head_kv * head_dim * 2` bytes per token
* per layer (2 KiB per rank here), paid only by the 16 attention layers; the 48 delta-net
* layers carry fixed-size state. At eight sequences of 16k that is 4.3 GB of reads per step,
* most of the cost of depth at that concurrency, and fp8 halves it along with each sequence's
* KV pool footprint.
* --kv-cache-dtype i8 makes it the int8 cache (abi/rad_builder.h): K and V as int8 codes
* with one f16 scale each per token and head, half the bf16 cache's bytes. The cache is paid
* only by the 16 attention layers; the 48 delta-net layers carry fixed-size state. At eight
* sequences of 16k the bf16 cache is 8.6 GB of reads per step, most of the cost of depth at
* that concurrency, and int8 halves it along with each sequence's KV pool footprint.
*
* Off by default for quality: greedy continuations from a long prompt agree for a few hundred
* tokens and then diverge, and the fp8 side can produce syntactically broken code where bf16
* stays clean, which matters for a coding model.
*
* The descales stay at libr4d's default of 1.0 (vLLM's default too); the kernels index them
* per (sequence, head), so calibrated descales need no other mechanism. The fp8kv attention
* rows and `kv_store_fp8` are in libr4d, the core sizes a page from the group's dtype, and the
* drafter's cache takes the same dtype (declare_dflash2). */
* Off by default because it changes the model's output slightly. The core sizes a page from
* the group's dtype, and the drafter's cache takes the same dtype (declare_dflash2). */
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;
/* --kv-cache-dtype fp8_v4 / k6_v4 (RadBuildCtx::kv_quant): V as int4 in groups of 32 with f16
* scales, K E4M3 as above or int6 the same way (libr4d's fp8_v4 / k6_v4 rows). A token's row
* is 25 or 22 * head_dim / 16 bytes instead of 2 * head_dim, so the group is declared at half
* that and the core sizes pages from it; only those kernels read the layout. The drafter's
* group stays E4M3 (declare_dflash2). The engine asks only for a layout probe() offered. */
const int kvq = fd.dtype == RAD_F8E4M3 ? ctx->kv_quant : RAD_KVQ_NONE;
const char* kvq_name = kvq == RAD_KVQ_V4 ? "fp8_v4" : kvq == RAD_KVQ_K6V4 ? "k6_v4" : nullptr;
if (kvq != RAD_KVQ_NONE && !kvq_name) {
fprintf(stderr, "radiance: KV cache layout %d is not one this plugin knows\n", kvq);
return RAD_E_UNSUPPORTED;
}
if (kvq_name && !(g.head_dim == 256 && g.n_head == 6 * g.n_head_kv)) {
fprintf(stderr, "radiance: --kv-cache-dtype %s has libr4d rows at head_dim 256, gqa 6 "
"only; this model is head_dim %lld, gqa %lld\n", kvq_name,
(long long)g.head_dim, (long long)(g.n_head_kv ? g.n_head / g.n_head_kv : 0));
return RAD_E_UNSUPPORTED;
}
const int64_t row16 = kvq == RAD_KVQ_V4 ? 25 : kvq == RAD_KVQ_K6V4 ? 22 : 32;
fd.head_dim = g.head_dim * row16 / 32;
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
/* The op parameter must use the spelling the rows band on, which is rad_dtype_name's. */
g.kv_dtype = kvq_name ? kvq_name : rad_dtype_name(fd.dtype);
if (kvq_name)
rad_note(b, "kv cache %s: %s K, int4 V, in groups of 32 with f16 scales, %lld bytes a token "
"and head instead of %lld", kvq_name, kvq == RAD_KVQ_V4 ? "E4M3" : "int6",
(long long)(g.head_dim * row16 / 16), (long long)(2 * g.head_dim));
g.kv_dtype = rad_dtype_name(fd.dtype);
/* The SSM state cache is f32, or f16 under --state-cache-dtype f16 (RadBuildCtx::state_dtype).
*
@@ -707,6 +705,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RadEncoding enc{};
m.trunk_i8 = weight_enc(b, nm.f("blk.%lld.ssm_inz.weight", (long long)l), &enc) &&
(linear_is_w8h(enc) || linear_is_wnh(enc));
if (m.trunk_i8) m.trunk_g8 = linear_w8h_group(enc);
break;
}
if (!m.trunk_i8) {
@@ -724,7 +723,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* (143 MiB) beside its 285 MiB bf16 buffer. */
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8));
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8, true,
m.trunk_g8));
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});
@@ -740,7 +740,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* it must not share storage with transients. */
m.b_rope_cs = decl_b(b, nm.f("rope_cs"), RAD_F32, {rope_table_rows(g), m.n_rot},
RAD_BUF_PERSIST);
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8));
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8, true,
m.trunk_g8));
/* `gdn_in` is conv_dim + v_dim, not in_dim: a and b have their own buffer because the
* checkpoint keeps them bf16, while the fp8 output gate is the tail of this one
@@ -760,7 +761,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* Rank 3, as libr4d's scan and recurrent kernels require; the quantiser reads dim 0 as the
* row. */
m.a_go.x = decl_b(b, nm.f("gdn_o"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v});
RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim, 0, m.trunk_i8));
RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim, 0, m.trunk_i8, true,
m.trunk_g8));
#if QWEN35_MOE
/* ---- the routing geometry, read here so a refusal names the container's key. `n_ff` is
@@ -839,24 +841,60 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_BUF_PERSIST);
m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp});
m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp});
m.a_eff.q = decl_b(b, nm.f("moe_ffn.q"), RAD_F8E4M3, {K, mc.n_ff_exp});
m.a_eff.s = decl_b(b, nm.f("moe_ffn.s"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)});
if (m.trunk_i8) {
/* An int8 trunk's routed arm is int8 throughout: the gated product's rotated codes
* at one scale a 128 of K, an expert's width a rank being whole 128s and not always
* whole 256s (MoeFP8::a8). */
m.a_eff.g8 = RAD_FP8_BLOCK;
m.a_eff.q8 = decl_b(b, nm.f("moe_ffn.q8"), RAD_I8, {K, mc.n_ff_exp});
m.a_eff.s8 = decl_b(b, nm.f("moe_ffn.s8"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)});
m.a_eff.q8_fed = m.a_eff.q8_rot = true;
} else {
m.a_eff.q = decl_b(b, nm.f("moe_ffn.q"), RAD_F8E4M3, {K, mc.n_ff_exp});
m.a_eff.s = decl_b(b, nm.f("moe_ffn.s"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)});
}
m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd});
if (mc.n_ff_shared > 0) {
m.b_emoe = decl_b(b, nm.f("moe_out"), g.act_dtype, {R, g.n_embd});
m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * mc.n_ff_shared});
m.a_sff.x = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, mc.n_ff_shared});
if (m.trunk_i8) {
/* The shared expert's down projection is a trunk linear, and its input's codes
* take the group its own weight is stored at, read from layer 0's through that
* layer's own LinearFP8 (which then maps it once): a recipe keeps it at a 128
* where a rank's share of its width is not whole 256s. */
LinearFP8& sd = m.layers[0].mlp.sh_down;
RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.0.ffn_down_shexp"),
{ nm.ckpt("model.language_model.layers.0.mlp."
"shared_expert.down_proj.weight") }));
const int64_t sg = sd.probed_i8 ? sd.probed_g8 : m.trunk_g8;
RAD_ARCH_TRY(m.a_sff.declare_pair(b, nm, g, "shexp_ffn", mc.n_ff_shared, R, true,
sg, "gated_had_quant_i8g"));
} else {
m.a_sff.q = decl_b(b, nm.f("shexp_ffn.q"), RAD_F8E4M3, {R, mc.n_ff_shared});
m.a_sff.s = decl_b(b, nm.f("shexp_ffn.s"), RAD_F32, {R, fp8_blocks(mc.n_ff_shared)});
}
m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd});
m.b_sgate = decl_b(b, nm.f("shexp_gate"), g.act_dtype, {R, 1});
}
if (mc.expert_rot) RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
/* The experts' rotated copy of the block input. An int8 trunk whose norms write rotated
* int8 codes (below) needs none: the experts read `h`'s own. Where they do not (the CPU
* kernels), had_quant_act_i8g writes this one at a scale a 128. */
const bool h_fed = m.trunk_i8 && rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g"));
if (m.trunk_i8 && !h_fed) {
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false,
RAD_FP8_BLOCK));
m.a_hr.q8_fed = m.a_hr.q8_rot = true;
} else if (mc.expert_rot && !m.trunk_i8) {
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
}
}
#else
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
m.a_ffn.x = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8));
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8, true,
m.trunk_g8));
#endif
#if QWEN35_W8A8
@@ -870,8 +908,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
if (rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g")))
m.a_h.q8_fed = m.a_h.q8_rot = true;
#if !QWEN35_MOE
if (rad_op_declared(b, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true;
#endif
/* The delta net's output likewise, from the decode conv fold's epilogue
* (gdn_conv_recurrent_update_had) and had_quant_act_i8g on the other rows (GdnFP8::q_o). */
if (rad_op_declared(b, "gdn_conv_recurrent_update_had") && rad_op_declared(b, "had_quant_act_i8g"))
m.a_go.q8_fed = m.a_go.q8_rot = true;
/* And the gated attention's output, from its gate (gate_had_quant_i8g). */
if (rad_op_declared(b, "gate_had_quant_i8g") && rad_op_declared(b, "had_quant_act_i8g"))
m.a_attn.q8_fed = m.a_attn.q8_rot = true;
#endif
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
@@ -929,10 +976,45 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
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 (rad_arch.h). */
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());
/* A vocabulary-weighted head, where the model holds one in place of output.weight: the rows
* sorted by their token's probability into classes of one computed-trellis width each,
* `output.k<B>.weight`, with `output.k<B>.ids` [rows, 1] each row's vocabulary id, and
* `output.vrow` [n_vocab, 1] the inverse (each id's class width and row). Each class is
* row-sharded like any lm_head, the converter keeping an id's row among its rank's rows
* (libr4d's logits_gemm_vocab). */
for (int B = 7; B >= 2; --B) {
const char* wn = nm.f("output.k%d.weight", B);
RAD_ARCH_TRY(map_copy(b, wn, nm.ckpt("lm_head.k%d.weight", B)));
RadEncoding e{};
int64_t shp[RAD_MAX_RANK] = {};
if (rad_weight_encoding(b, wn, &e, shp, nullptr) != RAD_OK) continue;
if (m.n_vcls == Model::MAX_VCLS || shp[0] % (256 * g.world) || shp[1] != g.n_embd) {
fprintf(stderr, "radiance: '%s' is not a head class this build reads (at most %d "
"classes, rows a multiple of 256 a rank)\n", wn, (int)Model::MAX_VCLS);
return RAD_E_SHAPE;
}
const int64_t n = shp[0] / g.world;
const int k = m.n_vcls++;
m.w_vw[k] = decl_view(b, wn, nullptr, "codes,trellis,trellis.mad", e.plane[0].dtype,
{n, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.w_vs[k] = decl_view(b, nm.f("output.k%d.scale", B), wn,
rad_enc_plane(&e, "scale.col") ? "scale,scale.col" : "scale",
RAD_F32, {n, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
const char* in = nm.f("output.k%d.ids", B);
RAD_ARCH_TRY(map_copy(b, in, nm.ckpt("lm_head.k%d.ids", B)));
m.w_vi[k] = decl_w(b, in, RAD_I32, {n, 1}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.vcls_rows[k] = n;
}
if (m.n_vcls) {
RAD_ARCH_TRY(map_copy(b, nm.f("output.vrow"), nm.ckpt("lm_head.vrow")));
m.w_vrow = decl_w(b, nm.f("output.vrow"), RAD_I32, {g.n_vocab, 1}, RAD_ACCESS_VOCAB,
RAD_SHARD_ROW, grp_model());
} else {
/* Row-sharded with the vocabulary: g.n_vocab is this rank's share (rad_arch.h). */
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),
@@ -1028,6 +1110,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* unfolded: it is a separate chain over its own residual buffer and saves only two launches a
* step. */
m.layers.resize((size_t)m.n_main);
#if !QWEN35_MOE
/* GPTQ calibration over the trunk's own int8 codes (rad_calib_full.h, site_i8): one rank, the
* serial step. The scratch is the widest input's square, the feed-forward's. */
if (ctx->calib_dir && *ctx->calib_dir && g.world > 1) {
fprintf(stderr, "radiance: qwen35: --calib-dir records an int8 trunk at --tp 1 only\n");
return RAD_E_INVAL;
}
RAD_ARCH_TRY(m.calib.begin(b, nm, g, ctx, m.n_main, 0, std::max<int64_t>(g.n_ff, g.n_embd)));
#endif
for (int64_t l = 0; l < m.n_main; ++l) {
Layer& lay = m.layers[(size_t)l];
lay.full = is_full_attention(l, interval) ? 1 : 0;
@@ -1093,6 +1184,36 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
#endif
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));
#if !QWEN35_MOE
if (m.calib.records(l)) {
/* The codes each int8 GEMM reads, in the domain its weight is stored in (i8_rot). */
const ActFP8& ao = lay.full ? m.a_attn : m.a_go;
const LinearFP8& li = lay.full ? lay.attn.qg : lay.gdn.in;
const LinearFP8& lo = lay.full ? lay.attn.o : lay.gdn.out;
if (!m.a_h.q8 || !ao.q8 || !m.a_ffn.q8 || !lay.mlp.gate_up.i8 || !lo.i8) {
fprintf(stderr, "radiance: qwen35: --calib-dir records an int8 trunk; layer %lld "
"is not one\n", (long long)l);
return RAD_E_INVAL;
}
auto dom = [](const LinearFP8& w) { return w.i8_rot ? (uint32_t)RAD_FP8_BLOCK : 0u; };
const std::string L = "model.language_model.layers." + std::to_string(l);
const std::string mix = L + (lay.full ? ".self_attn" : ".linear_attn");
const std::string op = lay.full ? ".o_proj" : ".out_proj";
lay.cs_in = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, L + ".input", mix, m.a_h.q8, m.a_h.s8, g.n_embd,
dom(li)));
lay.cs_o = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, mix + op + ".input", mix + op, ao.q8, ao.s8, lo.K,
dom(lo)));
lay.cs_mlp = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, L + ".post_attention.input",
L + ".mlp.gate_proj," + L + ".mlp.up_proj", m.a_h.q8,
m.a_h.s8, g.n_embd, dom(lay.mlp.gate_up)));
lay.cs_down = (int)m.calib.sites.size();
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, L + ".mlp.down_proj.input", L + ".mlp.down_proj",
m.a_ffn.q8, m.a_ffn.s8, g.n_ff, dom(lay.mlp.down)));
}
#endif
}
#if QWEN35_MOE
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
@@ -1136,12 +1257,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_NOWEIGHTS),
{m.a_h.x}, {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});
m.op_logits = m.n_vcls
? rw(b, RAD_OP(b, "logits_gemm_vocab",
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_INT("vocab_offset", g.vocab_off),
RAD_INT("rows0", m.vcls_rows[0]), RAD_INT("rows1", m.vcls_rows[1]),
RAD_INT("rows2", m.vcls_rows[2]), RAD_INT("rows3", m.vcls_rows[3])),
RAD_WEIGHTS(m.w_vw[0], m.w_vs[0], m.w_vi[0], m.w_vw[1], m.w_vs[1], m.w_vi[1],
m.w_vw[2], m.w_vs[2], m.w_vi[2], m.w_vw[3], m.w_vs[3], m.w_vi[3],
m.w_vrow)),
{m.b_hout}, {m.b_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 multi-token-prediction head (rad_block_mtp_fp8.h).
*
@@ -1151,7 +1282,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
*
* Also only when there is no DFlash2 drafter (`n_taps` == 0): a deployment drafts with one,
* and DFlash2 (one forward per block rather than one per token) is the better one here. */
if (nextn > 0 && g.max_spec > 0 && m.n_taps == 0) {
/* (A vocabulary-weighted head has no output.weight for the draft head to read.) */
if (nextn > 0 && g.max_spec > 0 && m.n_taps == 0 && !m.n_vcls) {
/* Sized at max_tok, not max_logit_rows: a draft round is one row per sequence, but the
* history pass that fills the head's own K and V is one row per token over a whole prefill
* chunk (26 MiB at a 512-token chunk, beside 477 MiB of head weights). */
@@ -1321,6 +1453,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_OK;
}
/* The lm_head over the gathered rows: the one weight, or a vocabulary-weighted head's classes. */
static void issue_logits(RadCtx* c, const Model& m, int n) {
if (!m.n_vcls) {
RAD_ISSUE_N(c, m.op_logits, n, brows(m.b_hout, n), RAD_W(m.w_lm_head),
brows(m.b_logits, n));
return;
}
auto w = [](rad_weight h) { return h ? RAD_W(h) : RAD_NONE; };
RAD_ISSUE_N(c, m.op_logits, n, brows(m.b_hout, n), w(m.w_vw[0]), w(m.w_vs[0]), w(m.w_vi[0]),
w(m.w_vw[1]), w(m.w_vs[1]), w(m.w_vi[1]), w(m.w_vw[2]), w(m.w_vs[2]), w(m.w_vi[2]),
w(m.w_vw[3]), w(m.w_vs[3]), w(m.w_vi[3]), RAD_W(m.w_vrow), brows(m.b_logits, n));
}
#if !QWEN35_MOE
/* ============================== A prefill step in two pieces ==============================
*
@@ -1547,15 +1692,13 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
brows(m.a_h.x, 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));
issue_logits(c, m, batch->n_out);
}
}
#endif
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = g_model[rad_rank(c)];
Model& m = g_model[rad_slot(c)];
/* An encoder pass runs only the vision tower (RadBatch::enc). */
if (batch->enc) {
@@ -1628,9 +1771,15 @@ static void step(RadCtx* c, const RadBatch* batch) {
const Layer& l = m.layers[(size_t)li];
if (l.full) l.attn.step(c, batch);
else l.gdn.step(c, batch);
/* The calibration taps read the codes the block's GEMMs just read, before the next block's
* norm rewrites the shared input planes. */
if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, batch->n_tok);
if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, batch->n_tok);
prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h);
dbg_resid(c, (int)li, "mix", m.g.n_embd, m.b_x, m.a_h.x);
l.mlp.step(c, batch);
if (l.cs_mlp >= 0) m.calib.tap(c, (size_t)l.cs_mlp, batch->n_tok);
if (l.cs_down >= 0) m.calib.tap(c, (size_t)l.cs_down, batch->n_tok);
prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h);
dbg_resid(c, (int)li, "ffn", m.g.n_embd, m.b_x, m.a_h.x);
@@ -1643,6 +1792,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
}
}
m.calib.after_step(c, batch->n_tok);
RAD_ISSUE(c, m.op_final_norm,
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.a_h.x, batch->n_tok));
@@ -1655,9 +1806,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
brows(m.a_h.x, batch->n_tok),
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));
issue_logits(c, m, batch->n_out);
}
}
@@ -1676,17 +1825,22 @@ static void step(RadCtx* c, const RadBatch* batch) {
* 0 when the container carries no drafter. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
/* --kv-cache-dtype fp8_v4 / k6_v4: libr4d's rows for them are the h256/gqa6 attention
* family's (Qwen3.8-27B), so other geometries are refused at startup rather than in declare. */
{
const long long hd = meta->head_dim ? meta->head_dim
: (meta->n_head ? meta->n_embd / meta->n_head : 0);
const long long nkv = meta->n_head_kv ? meta->n_head_kv : meta->n_head;
if (hd == 256 && nkv > 0 && meta->n_head == 6 * nkv)
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
}
/* The delta-net state cache is declared at RadBuildCtx::state_dtype. */
out->state_f16_ok = 1;
#if QWEN35_W8A8 && !QWEN35_MOE
/* Chained launches pay on an int8 or a trellis trunk with and without its drafter: every
* kernel of its decode chain has a chained form (libr4d's rad_kernel_chain), the two-rank
* junctions among them. Qwen3.8-27B, ms a decode step unchained / chained, on two R9700: as
* IQ8R 32.14 / 21.98 without a drafter and 36.54 / 26.52 with DFlash2 (40.75 / 32.09 at four
* sequences), as IQ4R-S-V4 with DFlash2 29.32 / 20.46 (35.37 / 26.81). On one R9700, which
* has no junction to wait behind, the IQ8R trunk measured 49.57 / 47.94 without a drafter and
* 56.13 / 54.23 with DFlash2.
*
* Not the routed build: its grouped GEMMs, router and gather have no chained form, and
* Qwen3.6-35B-A3B on two R9700s measured a decode step of 10.27 / 11.77 / 12.35 ms at 1, 4 and
* 8 sequences with them against 10.25 / 11.58 / 12.25 without. */
out->chain_pays = RAD_CHAIN_ALWAYS;
#endif
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (da && std::strstr(da, "DFlash2")) {
const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8);
@@ -1708,8 +1862,19 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
* expanded first, so these forward the expanded namespace. */
#define QWEN35_PROBE_X(NS) RAD_ARCH_PROBE(NS)
#define QWEN35_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
QWEN35_PROBE_X(QWEN35_NS)
#if QWEN35_MOE
#if QWEN35_MOE && QWEN35_W8A8
QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "w8a8_fwht128", "0.1.0",
"Qwen3.5 / 3.6 MoE (35B-A3B), an int8 trunk and int8 experts: i8 weights rotated "
"by a 128-wide Hadamard against int8 activations the same rotation quantises; the "
"dense graph with a routed feed-forward (256 experts, 8 a token, and a shared "
"expert), gated attention over paged KV every fourth layer and gated delta net "
"between")
/* An imported checkpoint is never a rotated int8 trunk: qwen35moe_fp8 serves those. */
RAD_ARCH_SERVES_IMPORTS(0)
#elif QWEN35_MOE
QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0",
"Qwen3.5 / 3.6 MoE (35B-A3B), block-scaled fp8 weights and fp8 activations: the "
"dense graph with a routed feed-forward (256 experts, 8 a token, and a shared "
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/qwen35moe_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(qwen35moe_w8a8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwen35moe_w8a8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35moe_w8a8.cpp)
+19
View File
@@ -0,0 +1,19 @@
/* qwen35moe_w8a8 -- Qwen3.5 / 3.6 MoE (35B-A3B) with an int8 trunk and int8 experts.
*
* arch/qwen35_fp8/qwen35_fp8.cpp built a fourth time, with both of its switches: the routed
* feed-forward of qwen35moe_fp8 and the rotated int8 trunk of qwen35_w8a8. Every linear of the
* trunk is IQ8R (`i8` codes rotated by a 128-wide Hadamard, read at i8a8h against int8
* activations), and the routed experts are rotated int8 at a bf16 scale a (row, 128 of K) or one
* of the rotated four-bit forms, read by the grouped GEMM's int8 rows from the codes the trunk's
* own quantisers write (arch/common/rad_block_moe_fp8.h, MoeFP8::a8).
*
* A plugin of its own for the reason qwen35_w8a8 is: the quantisation descriptor is half of the
* selection key (spec §2.4), and a container converted with data/recipes/q36-35b-a3b-iq8r.recipe
* says `qwen35moe` and `w8a8_fwht128`.
*/
#define QWEN35_MOE 1
#define QWEN35_W8A8 1
#define QWEN35_NS qwen35moe_w8a8
#define QWEN35_ARCH_ID "qwen35moe"
#include "../qwen35_fp8/qwen35_fp8.cpp"
+7 -4
View File
@@ -411,12 +411,13 @@ struct Model {
std::vector<Layer> layers;
};
static Model g_model[MAX_RANKS];
static Model g_model[MAX_SLOTS];
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
Model& m = g_model[ctx->rank];
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS || rad_build_slot(ctx) >= MAX_SLOTS)
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
@@ -548,7 +549,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)];
Model& m = g_model[rad_slot(c)];
/* An encoder pass runs the audio tower and nothing else (RadBatch::enc). */
if (batch->enc) {
m.aud.step(c, batch);
@@ -615,6 +616,8 @@ static const RadAudioFormat* audio_format(const RadModelMeta* meta) {
} /* namespace qwen3asr_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(qwen3asr_bf16, "qwen3asr", "", "0.1.0",
"Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder; bf16 weights "
"and activations")
Loaded 100 of 1036 files, more files were not shown because too many files have changed in this diff. Show more