Compare commits

..
149 Commits
Author SHA1 Message Date
Deadcode b6b8751ccc radiance 2.2.0
New models. LiquidAI's LFM3 by DokterSmol (#449): `arch/lfm3_bf16`, bf16, int8 and IQ8R trunks,
with the windowed attention it needs on libr4d and libhalo. Ling-3.0-flash on an IQ8R trunk by
keptn42 (#474), its clamped SwiGLU layers writing rotated int8 codes. NVIDIA-Nemotron-3.5-Bolt-74B-A9B
on an int8 trunk by keptn42 (#389), with the LiLiCorr drafter. Gemma 4 26B-A4B's vision tower by
kaczy44 (#522), and `rad-convert --add-vision` to add a tower to an existing container (#523). Muse
Glimmer as IQ4R-V4 with a quantised DFlash2 drafter, W6NL routed experts beside W5NL, the calibrated
U5 gate recipe, and Qwen3.8-27B's native MTP draft head (tools/vhead.py) by gostar (#466, #468,
#493, #536).

Speed. Qwen3.8-Flash-Next IQR-V4 at tp 2 on two R9700 decodes a step in 11.2 ms at one stream (12.4
in 2.1.0), 15.0 at two (16.8) and 21.4 at four (23.2), by Code000's series (#485-#519, #544-#546):
chained launches without the packet processor's acquire where the kernels acquire for themselves,
the host data path flushed before every doorbell and the scalar cache emptied behind a chained wait,
a register form of the fused all-reduce writes, QSA's score and select skipped where nothing reads
them, a lossless coded wire for large two-rank all-reduces, hc_read's 48-row decode tile and its
prefill up product, a packed MoE prefill map, and a single routed pass over a spanned prefill; and
hc_read's decode forms restored for ROCm 7.2 by mici81 (#472). Cold prefill is 2-3% faster than in
the previous build.

Speculative decoding, all opt-in: block and traversal verification of the coupled MTP chain
(`draft-verify`), a chain that stops inside the step (`draft-depth: adaptive`) and its load-aware
rule (`draft-depth-load`), and SuffixDecoding as a step selector (`draft-suffix`), by Code000
(#500-#502, #514).

Fleets. `models.NAME.cards` places a model on chosen cards (#458), `memory.card-headroom-mib` gives
one card its own reserve (#460), and a served LoRA adapter is listed as its model's child in
/admin/fleet. Runtime LoRA on a rotated int8 trunk by dowjames (#479; the `plugin/lora_plain`
library is built by hand). A control-vector variant, `MODEL:NAME`, by keptn42 (#461).
`prefill-room-gate: on` admits a prompt only when the whole of it fits, by baKon (#548, #550).
Deployment pixel and reference limits for Qwen-Image 2.1, Krea 2 and MiniMax-H3, video jobs held
through a model's drain, and fleet host room reserved atomically, by rkcth (#508-#533).

Fixed. MiniMax-H3's reference and keyframe encoder crash (#456, by farcryjohn, #482). A second
compute lane on a kept queue slowing decode by half (#478, diagnosed by eddie168 and keptn42): kept
queues are handed out oldest first. The expert prefetch stream's argument ring (#491, #494). The
build break of #503 (reported by DokterSmol). A tool-call delimiter that ended the turn, by Itoash
(#476). Gemma 4's sliding-window attention, by jintakhan (#446). The dashboard behind a reverse proxy
at a relative path, by forestjohnson (#492). Hardening from fl0l0u's security review of 2.0 and 2.1
(#464, #465). A failed declare names where it stopped and the op forms no loaded library serves
(#462, #471, #473); the guide has a section on moving a 1.x deployment (#463).

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

Thanks to @DokterSmol, @keptn42, @kaczy44, @gostar, @Code000, @mici81, @dowjames, @baKon, @rkcth,
@farcryjohn, @Itoash, @jintakhan, @forestjohnson, @fl0l0u, @davetha and @eddie168.
2026-11-19 21:25:24 +01:00
keptn42 c07e665785 arch/nemotronh: the shared expert splits in whole scale groups of an IQ8R trunk
The shared expert's slice was cut in 128-column blocks. Its down projection reads that slice
along K, and an IQ8R trunk keeps one scale per 256 columns there. Bolt's 5376 is 42 blocks of 128
but 21 groups of 256: two ranks held 2688 columns each, 10.5 groups, and the down projection was
refused ("an int8 weight takes rows in 16s and K in whole 256-column scale groups"). At four ranks
slice_of's blocks gave ranks 0 and 1 1408 columns, also not whole groups.

The slice is now cut in the trunk's own scale group, asked after the trunk probe: 128 for block
fp8 and 128-group int8 as before, 256 for IQ8R, so two ranks hold 11 and 10 groups and four hold
6, 5, 5 and 5. A shared expert that is not whole groups is refused by name.

an_iq8r_trunk_slices_the_shared_expert_in_whole_256_column_groups declares every rank at one, two
and four with IQ8R trunk linears, rotated int8 experts and drafter, checks each slice is whole
groups and the slices cover 5376 once, and steps both ranks of two lint-clean with the drafter.
It fails without the change. nemotronh_test: 18 of 18 pass.
2026-11-19 19:53:11 +01:00
keptn42 aba6b19648 tests/nemotronh: the LiLiCorr cases run again on an int8 container
Three cases were skipped while the trunk moved to int8 ("the case returns with an int8
container"). With the 2.0 encodings and the int8 backbone they declare and step again:
lilicorr_replicates_its_two_kv_heads_at_four_ranks,
nemotronh_tp4_steps_lint_clean_with_the_lilicorr_drafter and
nemotronh_sizing_declares_match_the_real_graph_at_every_arena_level.

nemotronh_test: 17 of 17 pass, none skipped. Without the backbone change these three and
a_rotated_int8_lilicorr_backbone_reads_int8_codes fail.
2026-11-19 19:53:11 +01:00
keptn42 1e670fe110 arch/nemotronh: the LiLiCorr backbone reads int8 codes when its linears are rotated int8
radiance 2.0 serves no block fp8, so a 2.0 container stores the drafter's backbone the way the
DFlash2 recipes do: rotated int8 with a bf16 scale per (row, 128 of K). declare_lilicorr declared
the backbone's activation pairs as E4M3, and declare refused such a container: "'dflash.fc' is a
rotated int8 weight, which reads an int8 activation; this block quantises its activations to E4M3".

declare_lilicorr now asks Dflash2::probe_i8 first, as gemma4_bf16 does, and declares the pairs
int8 at the probed group when fc is rotated int8, E4M3 at 128 otherwise. A width that is not a
whole number of groups is refused by name.

The Bolt test encodings move to the 2.0 recipe's forms: the drafter rotated int8 at 128, the trunk
int8 at 128, the experts w4nl64. a_rotated_int8_lilicorr_backbone_reads_int8_codes checks at one,
two and four ranks that the five pairs are int8, that every GEMM over a dflash weight runs at
i8a8h, and that no E4M3 quantiser writes a drafter buffer.

Nemotron-3.5-Bolt-74B-A9B w4a8 converted with it (int8 trunk, rotated int8 backbone, the experts
of the 1.x file reused), one R9700, expert_tiered, bf16 KV, against the bf16 HF reference on the
80 MT-Bench questions, 41,586 tokens: KL mean 0.00390, p99 0.0459, top-1 98.17 % (the 1.x file
with a block fp8 trunk and backbone: 0.00503, 0.0602, 97.9 %).
2026-11-19 19:53:11 +01:00
keptn42 e63bb1cdcf arch/nemotronh: an int8 trunk quantises nothing to E4M3 that no op reads
With an int8 trunk each block linear reads the int8 pair and quantises its input itself, but the
attention's out quantiser and the shared expert's relu^2 product still wrote E4M3 codes, lat_in did
so for rotated experts, which read their own rotated copy, and attn_out, ssm_out and shared_ff
declared E4M3 planes: no op read any of it. A step of Bolt's nine-block cut issued 9 quant_act_fp8.

AttnFP8 declares its out quantiser only where the activation carries a code pair its producer
writes, so an IQ8R trunk keeps the one that writes its rotated int8 codes, and llama_fp8 and dspark
are unchanged. The shared expert writes the relu^2 product alone where its down projection reads
the bf16 plane (GateQuantFP8::silu_only), lat_in runs only for experts that read E4M3 codes, and
the three activations declare no E4M3 pair on an int8 trunk. Not changed: the block norms still
write E4M3 codes (NormQuantFP8 has no unrotated int8 form), and the latent keeps its E4M3 plane,
unwritten, because MoeFP8 checks that its prepared input carries codes.

nemotronh_test: an_int8_trunk_quantises_nothing_to_e4m3_that_no_op_reads (Bolt's cut at one, two and
four ranks) fails without the change (9 quant_act_fp8 a step) and passes with it.
2026-11-19 19:53:11 +01:00
keptn42 045205de16 arch/nemotronh: rotated experts read rotated int8 codes
radiance 2.0 has no rotated E4M3 quantiser (had_quant_act_fp8), so the w4nl64 experts are served at
w4nl64a8i8h. For rotated experts the plugin declares the routed arm's two activations as rotated
int8 pairs with a scale per 128: the block input's rotated copy and the relu^2 product. Both are
written by had_quant_act_i8g.

When GateQuantFP8's relu^2 branch was fed int8, it wrote unrotated codes (quant_act_i8g). Fed
rotated int8, it now uses had_quant_act_i8g at the pair's group. Nemotron-H is the only user of
this branch.

A test checks the routed arm of Bolt's nine-block cut at one, two and four ranks: eight
had_quant_act_i8g, no had_quant_act_fp8, and every grouped GEMM at w4nl64a8i8h.
2026-11-19 19:53:11 +01:00
keptn42 6813efe9b7 arch/nemotronh: an int8 trunk
radiance 2.0 does not serve block fp8, so a quantised Nemotron-H trunk needs another form. The
plugin probes the first Mamba block's out projection before it declares the activations. When that
weight is int8 (i8 codes with a bf16 scale per [1 x 128], or IQ8R's 256), every activation a trunk
linear reads declares the int8 pair too: the normed hidden state, the gated norm's output, the
attention output, the latent and the shared expert's product. Each int8 linear quantises its own
input from the bf16 plane (quant_act_i8g). The routed experts keep their own path. A bf16 trunk
declares as before.

A new test checks that Bolt's nine-block cut, with int8 block linears and w4nl64 experts, runs its
block linears at i8a8 at one, two and four ranks, each behind its own quantiser, with no block-fp8
GEMM left.
2026-11-19 19:53:11 +01:00
baKon d42b7440a4 sched: prefill-room-gate defaults off
The gate serialises long prompts: the next prompt must fit its whole prompt beside the runner whole prompt. Off is the old chunk-only admission; on is opt-in.

(cherry picked from commit cbeeda3c2219b94452ee4094445e48b46de6750c)
2026-11-19 12:45:08 -06:00
keptn42 f9dd69db4e sched: bidi_used counts from the window group's first position, as its seqused does
On Gemma 4, a picture whose placeholders start after the first prefill chunk was not read. The
plugin attends a run's rows a second time, both ways, only on its sliding layers: over the window
group's block table and the keys before RadBatch::bidi_used. The build staged bidi_used as the
absolute end of the run. After each chunk, trim_window recycles the window group's blocks below the
window, its table then starts at first_block_pos, and build_groups counts that group's seqused from
there. bidi_used did not, so the run's rows read keys first_block_pos positions too far, past the
keys the pass wrote. Gemma 4 31B at tp 2 (16-token blocks, 1024-token window, 2048-token chunks):
a picture in the first chunk was read, one from token 2150 came back as invented text, and one
from token 3900 as no picture at all.

BatchBuilder now keeps the trunk's window group (RAD_KV_WINDOW, not a drafter's) and subtracts its
first_block_pos for the sequence from the bidi_used of each run it stages, the same value
build_groups uses for that group's seqused. Without a window group, and before the window
recycles, the value is 0 and nothing changes. The ABI text of bidi_used now says how it counts; the
layout is unchanged.

sched_test: a_run_in_a_later_chunk_counts_its_keys_from_the_recycled_window (a full and a 64-token
window group, the picture at tokens 200..299 in the second chunk, the window recycled below 128):
bidi_used 300 on v2.1.0 (fails), 172 with this change (passes), equal to the window group's seqused
less the rows past the run. ctest -LE 'gpu|oot' on a host build without ROCm: 135 of 135 pass
(3 skipped), the same as on v2.1.0. On the Gemma 4 31B setup above, a picture after 800 to 90,000
tokens of text is now read at every length.

Fixes #547.
2026-11-19 18:55:24 +01:00
baKon af1557b1ef sched: a fresh prefill waits for its whole prompt, and an idle engine fails one it cannot start
Admission reserved only the first chunk, so a long prompt could fill the
pool and be preempted back to zero at its first decode step. A fresh
prefill now starts only when its whole prompt plus one decode position
fits beside every runner (--prefill-room-gate, on by default).

A refusal on an empty engine used to return kAdmitWait. Nothing was
running, so the next step never freed a block and the queue stayed
Waiting with the GPU idle. Drop the kept hit once; if the prompt still
cannot start, fail that request and ask the next.
2026-11-19 18:55:10 +01:00
Code000andClaude Opus 5.5 c349190569 sched: an in-step tail snapshot has no quarter-interval floor
Under --prefix-resume nearest, tail_checkpoint drops a prompt's tail
snapshot when its last quantum boundary lies less than a quarter interval
(512 tokens at interval 2048) past the interval boundary below it. The
floor exists because the snapshot cuts the last chunk, and the cut leaves
the last tokens a step of their own. A prefill alone in its spanned step on
a plugin that snapshots inside a step (set_ckpt_inside, the default on
Flash-Next since 64bf299e) cuts nothing, but the same floor applied: such a
prompt kept its snapshot at the interval boundary and the next turn
re-prefilled up to a quarter interval (a 39097-token prompt resumed at 38912
instead of 39040).

tail_checkpoint takes `in_step`, which plan_chunk passes for that branch:
the tail is then the last quantum boundary wherever it lies past the first
interval (one on an interval boundary is that boundary's snapshot, as
before). Cut schedules, shared steps and --prefix-resume exact are
unchanged.

Flash-Next IQR-V4, TP2, live config, 10 code sessions of 6-39K tokens with
two follow-ups each (20 follow-ups): tokens the follow-ups re-prefilled
behind the previous prompt 1745 -> 722 (worst 495 -> 63); the three
follow-ups it moved: 527 -> 271, 584 -> 264, 726 -> 278 tokens, TTFT
200/144/160 -> 111/102/102 ms. Greedy check over 12 code prompts: where
the snapshot did not move (8), turn 1 and the cached follow-up are
bit-identical to 7b62092a; where it moved (4), the split of the last chunk
moves with it and both differ at tie level, the follow-up no farther from a
cold no-cache run than before.

sched_test: a case at interval 1024 for the in-step positions, the step
sequence of a 2200-token prompt (1024, then 1176 with the snapshot at
2176), and the cut and shared schedules keeping 2048.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 18:54:53 +01:00
Code000andClaude Opus 5.5 67cf57b864 sched: concurrent prefills with nothing decoding take the span one at a time
A span was taken only by a single running request (or a single request in
an empty engine). Two to four prompts prefilling at once with nobody
decoding therefore ran every step at the shared budget (2048 tokens under
max-num-batched-tokens 8192, prefill-span 4), split between them in
unspanned chunks: about 6.5K tok/s against 8-10K tok/s for a spanned step.

Now a step is spanned whenever every running request still has prompt left
and no admission is possible. The one with the fewest prompt tokens left
takes the step alone (shortest remaining first); the others sit it out and
take no share reserve of it, so the step is planned exactly as a lone
prefill's. The running loop stops after that entry, which keeps the
RadBuildCtx::max_mixed_tok contract (a step wider than shared_tok is one
sequence). As soon as anyone decodes, or a request can be admitted, steps
are shared as before.

Spanned steps are several times as long as shared ones, and a request that
arrives while one runs waits for it. A conversation's next turn arrives a
few milliseconds after its previous reply finished, just after the next
step was planned: with the remaining prefills now spanned, follow-ups beside
them waited up to a whole spanned step (pfx4 mix: 0.68 -> 0.86 s mean
follow-up TTFT). So the one step after a request finished while others still
run (finished_beside_) is planned at the shared budget; the follow-up waits
for that step and is admitted in the next. This also covers the existing
case of one prefill left alone by a finished request.

Flash-Next IQR-V4, TP2, live config, code prompts, installed 7b62092a
against this, 2 runs each (mean TTFT, s):
  4x16K concurrent       8.77 -> 6.30   (last 11.15 -> 9.96)
  2x16K concurrent       4.50 -> 3.42
  single 16K             1.98 -> 1.95
  pfx4  turn 0 / follow  10.07/0.68 -> 10.37/0.48
  pfx2  turn 0 / follow   8.35/0.36 ->  6.55/0.30
  pfx4b turn 0 / follow  10.31/0.63 ->  9.93/0.46
  pfx2b turn 0 / follow   8.47/0.61 ->  6.67/0.28

sched_test: a new case for the step sequence (both admitted at the shared
budget, then the shorter alone in spanned steps up to its first token, then
shared steps beside its decode row; no wide step with more than one entry
over three prompts arriving together; one shared step after a finish beside
a prefill, then spans again). a_shared_step_under_a_span_is_planned_as_without_one
now compares the shared steps beside a decoding request, the regime that
stays shared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 18:54:44 +01:00
Code000andClaude Opus 5.5 0a7516441d runtime: haz_note judges the operand counts issue_body accepts (decode regression from #519)
issue_body lets an issue leave out trailing optional operands (a null tensor stands for each), but
the recorded-pass hazard note still required the schema's full count and made such an issue opaque.
Since the routed MoE GEMMs gained their optional `split` operand, every decode, verify and draft
pass issues them one operand short, so both went opaque and ordered their neighbours behind them
(the shared-expert arm no longer ran beside gate_up). The note now accepts any count between the
last required operand and the schema's; the absent operands were already skipped.

Flash-Next IQR-V4, TP2, MTP 5 + coupling + traversal + adaptive depth: the 4-row main pass goes
from 253 to 353 of 1044 dispatches unordered (each draft-head pass +1), decode +1.6..+2.0 % on six
400-token code prompts (T 0 and T 1), output byte-identical. Host suites green.

Fixes a decode regression introduced by #519 (reported in its review).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 18:54:36 +01:00
Constantin 14761df127 qwen35: drive MTP calibration without speculative proposals
Use a history-only declaration at depth zero. Do not load the U2 projection, reserve proposal rows or advance a draft chain. Reject an MTP-only calibration request from KL recording instead of completing without its Gram.
2026-11-19 18:52:59 +01:00
Constantin 66b2036eb5 vhead: publish the prepared checkpoint only after staging succeeds 2026-11-19 18:52:59 +01:00
Constantin 9ddb563c0d core: run MTP history pass for draft-head calibration 2026-11-19 18:52:59 +01:00
Constantin e3bb5b3ea2 qwen35: calibrate native MTP draft head 2026-11-19 18:52:59 +01:00
Constantin f1a1730c3c vhead: refuse to overwrite the source checkpoint directory 2026-11-19 18:52:59 +01:00
Constantin 20e7d61ec7 recipes: document and test the optional dense Qwen 27B native MTP overlay 2026-11-19 18:52:59 +01:00
Constantin 4664ac1c2d qwen35: support opt-in coupled proposals from the replicated U2 shortlist 2026-11-19 18:52:59 +01:00
Constantin 699fd85c97 qwen35: size U2 proposal scratch by drafting sequences, not verify rows 2026-11-19 18:52:59 +01:00
Constantin 1f1bc7c2b8 qwen35: draft through the native U2 head with a vocabulary-split target 2026-11-19 18:52:59 +01:00
Constantin 08968b530b vhead: hard-link indexed shards inside the prepared checkpoint 2026-11-19 18:52:59 +01:00
Constantin 8c454110d9 vhead: optionally retain the source lm_head for native drafters 2026-11-19 18:52:59 +01:00
rkcth ef84fa3f6b minimaxh3: bound video deployment plans and validate planner probes 2026-11-19 18:52:07 +01:00
rkcth a37f07b3f8 engine: restore previously yielded expert cache capacity while idle 2026-11-19 18:51:28 +01:00
rkcth e06863be2c fleet: reserve host room atomically for loads and background fills 2026-11-19 18:51:02 +01:00
rkcth 30dda03a6f server: keep model discovery from restarting idle TTLs 2026-11-19 18:50:40 +01:00
rkcth aea55a2b1c images: queue admitted adapter requests in FIFO order 2026-11-19 18:50:24 +01:00
rkcth 4cbe901054 gen: reject guidance requests that cannot fit the sequence limit 2026-11-19 18:50:14 +01:00
rkcth 36731f27d5 krea2: size image buffers from validated deployment limits 2026-11-19 18:49:59 +01:00
rkcth 109ac86d12 lora: accelerate composition with bounded pthread OpenBLAS and safe fallback 2026-11-19 18:49:48 +01:00
rkcth 6cd58a564b lora: deflate dependent columns during scalar rank truncation 2026-11-19 18:49:35 +01:00
kaczy44 a03e812360 Add RAD Vision weight repacking support 2026-11-19 18:49:00 +01:00
kaczy44 33343c4730 Add Gemma 4 26B-A4B MoE Vision inference 2026-11-19 18:48:44 +01:00
dowjames a0eb3934b5 fleet: sample the parent stats under adapter child names (#475)
Front::resolve already answers base:adapter on every route, but history_loop
sampled per-model series only under real model names, so a child listed by
status() had no series and its charts said No data yet while the parent served.
Sample the child under its own name with the parent body: same tokens, queue and
seconds, because the parent is what serves them.
2026-11-19 18:48:06 +01:00
dowjames a81a35f2a6 fleet: list loaded LoRA adapters as children in /admin/fleet and the dashboard (#475)
The fleet view knew nothing about adapters, so the built-in dashboard showed only
the base model while /v1/models answered the adapter too. Fleet::status() now
appends one child entry per loaded adapter of each resident model -- id
base:adapter, parent set, adapter true -- taking state and counters from the
parent, because the parent is what serves it. Adapters own no cards and no bytes.
2026-11-19 18:48:06 +01:00
dowjames ac6ddac7f7 lora_plain: kernel library for runtime LoRA on a rotated trunk, + docs (#475) 2026-11-19 18:48:06 +01:00
dowjames 2c81c86350 lora: prefetch ops stage weight planes and neither carry nor invalidate adapters (#475)
(cherry picked from commit 452d35f3a582eeab10d595b35a62e45316214851)
2026-11-19 18:48:06 +01:00
dowjames 06a2b18848 lora: plain fp GEMM sites may read transform-basis weights (kernel relayout presents the plain basis). #475
(cherry picked from commit b50f65b8e84fd1ae3f74da107c446c5ab50981ce)
2026-11-19 18:48:06 +01:00
Code000andClaude Opus 5.5 3deabdaeca prefill: take a lone spanned prefill's tail snapshot inside its last chunk
A lone spanned prefill now runs to the prompt's end and takes the prefix-resume snapshot mid-step
at the same position, instead of ending its last chunk at the snapshot and running the last few
dozen tokens as a step of their own (on Flash-Next that step reads nearly every routed expert for
those rows). Every stateful part (delta-net recurrence + conv slot, QSA key ring, PLE windows)
computes the rows before and after the cut as two pieces, each what a chunk of those rows
computes; rad_ckpt_snap copies each layer's state to a stage on the card between them (57.1 MiB a
rank on Flash-Next at TP2, carved from the KV pool only where prefill-span > 1 and the prefix cache
is on), then one contiguous copy goes to the host slot. The connection reads and the routed
passes restart at the cut, and moe_gemm_q gains an optional `split` operand so a step-wide routed
pass gives each expert's rows before the cut a run of their own (the 1-2-row dot-path remainder
depends on the run length). ABI 43: RadBatch::ckpt_cut/ckpt_cu (appended), RadArchProbe::
ckpt_snap_ok (in the tail padding). Snapshots and follow-up turns are bit-identical to the cut
schedule's (24 checkpoints of 9 prompts, 3.9-30.6K tokens; resumed turns identical). TTFT of 11
documentation prompts (4.3-21K tokens, span 4 at 8192, span-first on): -22.8%..+2.4% a prompt,
-2.3% in total; BetterBench filler (narrow routing, a cheap tail step) -0.5%; decode unchanged.
Off: RADIANCE_CKPT_INSIDE=0 (keeps the cut) / RADIANCE_CKPT_STAGE=0 (no stage either);
RADIANCE_CKPT_HASH=1 logs a digest of every snapshot for byte comparisons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:17:00 +01:00
Code000andClaude Opus 5.5 917d5e4b93 sched: prefill-span-first and prefill-tail-snapshot options (both default off / unchanged)
prefill-span-first on: a spanned prefill may start at the prompt's first token (the first
interval's rows read the QSA selection instead of the dense path; below the exact bound the same
keys, summed differently: deterministic, not bit-identical). Real-text prompts: 6.7K 1002 -> 857 ms,
14K 2137 -> 1905 ms, 24K -2.7%. prefill-tail-snapshot off: the last chunk runs to the prompt's end
instead of cutting a separate tail-snapshot step at the last 64-token / interval boundary (that
step touches nearly all experts: 66 ms for 51 rows); loses the follow-up-turn snapshot (turn B on a
16K prefix 49 -> 781 ms), so meant for single-shot loads only. Defaults leave the schedule and
outputs byte-identical. With span 8192 + both: BetterBench prefill ~7500-7670 tok/s from 8K tokens
(prefix cache on); decode within +-1-3%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:14:43 +01:00
Code000andClaude Opus 5.5 c48708315d libr4d: staged coded form of the 2-rank fused all-reduce writes for large prefill messages
The coded write (and its gather form) at two ranks pushes its whole range, then folds it: the
link's time plus the card memory's time. The staged form cuts each block's range into S parts
with their own handshake (flag, sequence counter, push-check word) and folds part j - 1 while
part j crosses the link, so the two phases overlap. The arithmetic, the coded words and the fold
order of every value are the coded kernel's: y and h are the same bytes.

Rule (from sweeps on 2x R9700): the write S = 8 from 4 MiB, the gather form S = 6 from 6 MiB;
decode and verify messages stay far below. R4D_AR_CODED_STAGES / R4D_AR_CODED_STAGES_G set the
parts (0: the single-phase coded kernel), R4D_AR_CODED_STAGES_MIN_KB / _G_MIN_KB the floors.
r4d_ar_coded_stages_pin is the test hook; the coded-form selftest gains three arms (single-phase
pinned, 3 parts, 16 parts) compared byte for byte with the plain kernels.

8192 rows of 2560: write 2017 -> 1623 us, gather 2231 -> 1978 us.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:24:35 +01:00
Code000andClaude Opus 5.5 e4541c7036 prefill: one routed MoE pass over a spanned step (prefill-span-pass: step)
prefill-span-pass: piece|step (default piece) and prefill-span-min: auto|N (both need prefill-span
> 1): with step, qwen4exp_fp8 runs the routed MoE of a spanned step in one pass instead of
2048-row pieces (serial step at TP1/TP2; declined with a startup note when pipelined at TP>=3 and
in calibration). New RadBuildCtx::span_pass_step appended past the struct's end (200 -> 208 bytes, so
RAD_ABI_VERSION is 42: rebuild all plugins). Defaults leave the schedule and
the output unchanged. Not bit-identical to 2048-row passes (a run of one or two rows takes the
grouped trellis GEMM's dot path, a longer one its tiles), deterministic. Measured BetterBench
prefill with max-num-batched-tokens 4096, prefill-span 2, step, span-min 0: +1.4% (1.6K) .. +6.7%
(47K) without prefix cache; costs: arena 621 MiB -> 1.17 GiB a rank, KV pool 4.58 -> 4.02 GiB a
card, no checkpoints inside a span.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:22:00 +01:00
Code000andClaude Opus 5.5 3b2050a516 libr4d: MoE prefill GEMMs: packed 128-row run map for gate_up, 64-row block for the w4nl64 down
moe_gemm_iqr: from 32 routed rows an expert on average, a packed run map with 128 rows an entry and
8 token tiles a trellis decode (instead of 64 rows / 4 tiles); the 1-2-row remainder modulo 64
keeps its own entry, so the dot-path entries and the per-element summation order are those of
the run map (byte-identical). moe_gemm_w4a8i8 (w4nl64, int8 activations): a 64-row block (MT 4,
WGM 2, 16 waves) instead of 32. At 4096/8192 tokens gate_up is ALU-bound on the trellis decode per
map entry, not on bandwidth. Engine stamps: gate_up -4.5..-11.2%, down -8.5..-19.3% a layer
(20480..81920 rows). BetterBench prefill +0.9..1.9% (2048 chunks), +2.5..3.4% (span 4096),
+2.1..3.6% (span 8192) from 8K tokens. Decode code paths unchanged. New byte-identity selftest
cases moe_iqr_pack_case / moe_down_mt_case; RADIANCE_MOE_IQR_MAP_TILES=4|8, RADIANCE_MOE_DOWN_MT=2|4
to cross-check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:20:40 +01:00
Code000andClaude Opus 5.5 5bfb69e4ad draft: load-aware draft depth with online calibration (--draft-depth-load, opt-in)
--draft-depth-load on (default off; needs --draft-depth adaptive with --draft-depth-stat top):
a step that drafts for --draft-depth-load-from sequences or more (default 5) runs round j only
for the rows whose expected accepted drafts pay their verify rows, the kernel tile they open
(past 16/32/48/64 query rows) and the round, at the measured tokens a millisecond;
--draft-depth-load-min rounds (default 2) always run. With --draft-depth-load-late on (default)
each row's verified prefix is chosen again when the next verify is issued, from the laws read
by then. Fewer drafting sequences keep the stop rule, bit for bit.

Calibration (--draft-depth-load-calib online, default): acceptance per confidence knot from the
server's own verified chains, the rate as a moving average of pure decode steps, row/round/tile
prices by ridge regression of step times, all starting from built-in tables measured on
Qwen3.8-Flash-Next at T 1.0 (or the --draft-depth-load-*-ms lists); static serves the tables as
given. Exact: within a step the rule reads draft-side laws only, the tables change between steps
from verifies that are over (mtp_rrs_test chi-square under both verifies, with tables that follow
the run, and negative controls that fail as they should).

Diagnostics: RADIANCE_DEPTH_CTL=<file> (load=0|1 late=0|1, switch the rule in a running server
for A/Bs), RADIANCE_CONC_LOG=<file> (a line a decode step), a summary line at shutdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:19:56 +01:00
Code000andClaude Opus 5.5 4366748012 libr4d: tiled prefill form of the QSA sparse attention (R4D_ATTN_USEL=1, opt-in)
At a prefill chunk the sparse launch is 2048 q_len-1 rows, each gathering its
own 2051 keys from the paged cache: 4.3 GB of K and V a layer and rank, about
3 ms, 12% of a Qwen3.8-Flash-Next prefill chunk past the exactness bound. The
rows of a chunk are consecutive queries over one history and their lists
overlap (neighbours share 53-73% of their pages).

With R4D_ATTN_USEL=1 in the environment, a launch of 256 or more q_len-1 rows
(lists up to 520 pages, bf16 cache, twelve queries a KV head: the model at two
ranks) runs as tiles of eight rows over the union of their page lists
(libr4d/r4d_attn_usel.h): a builder kernel for the unions, a tiled attention
kernel that stages K and V once a tile and masks each row to its own keys, the
decode kernel itself for tiles that share too little, and the decode launch's
merge unchanged. No operand, schema or graph changes. Default off: the form is
exact to rounding, not bit for bit (scores are bit-identical, the softmax sums
the same keys in another order; about 12-13% of bf16 outputs differ by one
ulp, as accurate as the decode kernel against f64 and libref), and a served
model's greedy text can part from the decode launch's at near-ties.

Slots past a row's context end are loaded as zeros: inf or NaN behind the end
of the context poisoned a tile (new r4d_selftest case with inf/NaN there).

Chunk at 10-35K tokens, r4d_selftest --perfusel: 2.8 -> 1.5-2.0 ms. docs/QSA.md
has the design, the exactness argument and the measurements.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:19:27 +01:00
Code000andClaude Opus 5.5 87fa1f109e libr4d: prefill form of hc_read's up product
hc_up_mix_pf3_kernel is the up product of hc_read's PF2 prefill path with
32-wide K slices, the N operand without LDS (transposed loads) and 27 KiB of
LDS, so two workgroups fit a CU. The sigmoid quotient 1 / (1 + e^-v) is taken
with v_rcp_f32, and with the exact division where the reciprocal is within one
unit in the last place of a bf16 rounding tie, or d is 2^120 or more or a NaN;
the rule is checked
exhaustively over every float it can meet (1 + e^-v lies in [1, inf]):
0 of 1082130433 differ, and every positive NaN keeps the division's result
(r4d_hc_rcp_check, called from r4d_selftest).

Byte-identical to the decode tiles and the wide kernels at M=65..4096
(r4d_selftest hc_read_e4m3 / hc_read_bf16 compare the bytes; r4d_hc_read_pin_prefill
form 4 is the rule, 3 the PF2 kernels with the wide up product). hc_read at
M=2048: 579 -> 532 us a call. On by default wherever the rule runs the PF2
form (from 512 rows); R4D_HC_PF3=0 keeps the wide kernel as the up product, for a
comparison in a running engine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:18:56 +01:00
rkcth 31467206e1 device: guard tensor-parallel queues beside single-rank engines 2026-11-18 18:18:16 +01:00
rkcth 46bce7f443 server: retain video job ownership through model drain 2026-11-18 18:17:19 +01:00
rkcth 1fd2432365 qwenimage21: honor deployment pixel and reference limits 2026-11-18 18:16:08 +01:00
Code000andClaude Opus 5.5 ca38286812 libr4d: hc_read takes a 48-row tile for 33..48 decode rows
hc_read's decode forms ran 33 to 48 rows (eight sequences at depth 3 to 5)
on the 64-row tile. What that costs is not the rows but the wave map: 4 m-tiles
x 4 n-tiles over eight waves are two 16x16 WMMA tiles a wave, so every staged K
pass is a chain of eight multiplies where the 32-row tile's is four. A 48-row
tile at 32 columns a workgroup is 3 x 2 tiles, one a wave again, on twice the
workgroups.

The K split is still counted at 64 columns (hc_down_kchunk), and there is one
row tile either way, so every element is summed in the same order: the output
is byte-identical to the 64-row tile. r4d_selftest compares the two at
M=33/40/47/48 (E4M3 and int8 codes); r4d_hc_read_pin_decode(2) keeps the 64-row
tile and (3) the 48-row tile at 64 columns, for the comparison and the timing.

r4d_selftest --perfhc at 33..48 rows: 57.7-61.1 -> 49.4-53.5 us a call (32
rows: 37.5 us, unchanged).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:12:57 +01:00
Code000andClaude Opus 5.5 a189bcc444 runtime: one patch dispatch for an op's weight tables, 40 entries a dispatch instead of 24
A routed GEMM names four to eight weight tables (a class of experts each, weights and scales),
and in a pass the stager armed for each of them changes a few entries at every issue. Each
table patched on its own: one dispatch a table, four to eight ordered launches in front of
every routed GEMM of a prefill chunk (420 a chunk on Flash-Next at two ranks). issue_body now
gathers the changed entries of all of an op's tables into one WtabPatch (Ctx::wtab_flush),
dispatched on the current stream before the op launches, and kWtabPatch goes from 24 to 40
entries (the argument block is 648 of the AQL backend's 768 bytes, within the kernel's one
64-thread workgroup): 246 dispatches a chunk. A refusal on the way (abort_step, abort_step_msg,
a table that cannot be resolved) still dispatches what was gathered, so the device arrays hold
what the host tables say. Not while recording a pass: there a refresh is host work the tape
names and replays per table.

Bit-identical: the writes and their order against every reader are the same, and no two name
one entry. New runtime_test case an_ops_weight_tables_are_patched_in_one_dispatch (5 moved
entries of two tables go out in one dispatch; more than a block's worth in ceil(n/40)); texts
identical to main's (24 of 24, greedy and sampled, prompts up to 21.7K tokens). Measured on
Flash-Next IQR-V4, TP2, 2x R9700, BetterBench prefill: +0.4 to +0.6% at 12K..47K tokens
(+0.5 to +1.5% below, noisier).

runtime_test: the repeat-mode case started its output at whatever the heap held, and a freed
arena of an earlier case held exactly the first launch's result; the output now starts at -1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:11:49 +01:00
Code000andClaude Opus 5.5 dd97f076e6 libr4d: lossless coded wire for the 2-rank fused all-reduces from 512 KiB
ar_hc_write and ar_gather_hc_write (2 ranks, one-shot P2P) push their bf16 partials in the
4-rank two-shot's lossless coded form (shared r4d_ar_arc.h): 8-value chunks, a base exponent per
64 values, sign + 7 mantissa bits + 4-bit exponent offset = 12.125 bits/value; groups with a
subnormal, inf/nan or an exponent span over 14 go raw (0.02-0.8% in practice). New slot layout
[packed][bases][spill], 1/128 more VRAM. Used from 512 KiB a message (crossover ~280 KiB; below
it the plain and register forms stay), override R4D_AR_CODED_MIN_KB. The peer decodes the bf16
words the plain push would have carried and folds them in the same order, so y and h are the
plain kernels' bytes. Host-mailbox twins and messages that are not whole 256-value waves stay
plain.

Bit-identical: r4d_selftest compares every shape against the plain kernels in four arms (104
coded-form cases each for ar_hc_write and ar_gather_hc_write), and the server's generated texts
are identical to main's (24 of 24, greedy and sampled, prompts up to 21.7K tokens, also with
every message coded). Measured on Flash-Next IQR-V4, TP2, 2x R9700, BetterBench prefill: +2.1 to
+4.1% over 1.5K..47K tokens against main; decode (messages under the floor) unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:11:14 +01:00
David 59e8dfe06f README: list the abliterated Qwen3.8-Flash-Next IQR-V4 container 2026-11-18 10:31:54 -06: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
448 changed files with 67275 additions and 2710 deletions

No files matched your search

+1 -1
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 2.0.0 LANGUAGES C CXX)
project(radiance VERSION 2.2.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
+117 -68
View File
@@ -15,24 +15,27 @@ Written by Deadcode, with contributions from:
adaptive draft window, the MoE prefill forms, the sorted operand's decode kernel, two K blocks a
pass for up to 80 routed rows, --prefill-span, the towers' lookup tables counted once, and for
Gemma 4 its assistant head as a drafter that reads the trunk's cache, bf16 checkpoints, the fused
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, the
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared
layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, the Gemma 4
31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared layers,
per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio
encoder, its i8a8 linears and its KV heads replicated over ranks, 4-bit weights at decode heights
through w4a16_asym, the Ornith-1.5-122B compose files, the Gemma 4 31B's asymmetric int5
linears (w5a8i8 and w5a16), the junctions at quant_act_i8g's grid (rmsnorm_quant_i8g,
gelu_mul_quant_i8g and ar_rmsnorm_quant_i8g) with the prefill overlap on the i8a8, a4 and w5
grids, the 31B's i8g, heretic-ara-i8g and w5 compose files, and Ling-3.0-flash (bailing_hybrid:
KDA, dense latent attention, group-limited sigmoid routing, the clipped SwiGLU and its MTP layer as
a serial drafter) with mla_attn_paged, its w4a8 recipes and compose files, possessive quantifiers
in the tokenizer's patterns, the Grafana dashboard's first screen, and Gemma 4 12B (its picture
and audio embedders, a picture's placeholders read both ways on the sliding layers, the windowed
attention at head_dim 512, suppress_tokens) with its compose files, and
NVIDIA-Nemotron-3.5-Bolt-74B-A9B (nemotronh: Mamba-2 with ssd_update and ple_conv_bias, the
latent MoE's ungated relu^2 experts, NoPE attention with KV heads replicated over ranks, the
paged attention at head_dim 128 and gqa 16, attention sinks) with NVIDIA's LiLiCorr drafter
(RadBatch::anchor_rows, the candidate correlator), the C-RADIO vision tower and video tubelets,
calibration in layer ranges, its recipes and compose files, and the kernel report's fixture
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, and Ling-3.0-flash on an IQ8R trunk with its
clamped gated products writing rotated int8 codes, Nemotron-3.5-Bolt-74B-A9B on an int8 trunk
(rotated experts and the LiLiCorr backbone reading rotated int8 codes), and the bidirectional
media span counted from the window group's first position
- 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
@@ -42,7 +45,19 @@ Written by Deadcode, with contributions from:
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
served by default, and the diagnose mode, in which the engine measures itself, with its token
parity and reproducibility checks, and the HDP flush before every doorbell and the scalar-cache
invalidate behind a chained wait, chained launches without the packet processor's acquire, the
prefetch stream's half-lap acquire, the queue scratch charged to the VRAM budget, the pinned
staging ring sized for sixteen builds, --expert-pin-top's fractional cut, the vision tower left
off a build without a media decoder, QSA's score and select skipped where no attention reads them,
the register form of the fused all-reduce writes with its wake store, Flash-Next's verify and
decode launch order, the coded lossless wire of the two-rank fused writes and its staged form, one
patch dispatch for an op's weight tables, hc_read's 48-row decode tile and its prefill up product,
the packed MoE prefill run map, the spanned prefill's routed pass and its tail snapshot inside the
last chunk, block and traversal verification of the coupled MTP chain (--draft-verify), adaptive
and load-aware draft depth (--draft-depth, --draft-depth-load), SuffixDecoding as a step selector
(--draft-suffix), and the tiled QSA prefill form
- 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
@@ -55,11 +70,12 @@ 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, and expert_stats_report.py
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,
and the fresh prefill's room gate (--prefill-room-gate)
- 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
@@ -69,12 +85,12 @@ Written by Deadcode, with contributions from:
emulator that tests them, the prefill split into two slices with their all-reduces beside the
compute, and the vocabulary-sharded draft head; Gemma 4 31B on four cards (its all-reduces fused
with the junctions, overlapped with the compute and sent compressed, chained launches with block
drafters), the embedding scale rounded as Hugging Face rounds it, block drafters' drafts
accepted on the card, z-lab's DFlash drafter drafting on after a prefix-cache hit and the 31B's
GPTQ calibration tap, and for speculation the MTP head's first draft read up to where it sits, no
step queued behind one that ends its requests, a step's tokens streamed before the drafter's
passes end, a block drafter's proposals verified as a tree, the 31B's block-16 DFlash2 tree with
its short block under load, a block drafter's window carried in the window snapshot, and window
drafters), the embedding scale rounded as Hugging Face rounds it, block drafters' drafts accepted
on the card, z-lab's DFlash drafter drafting on after a prefix-cache hit and the 31B's GPTQ
calibration tap, and for speculation the MTP head's first draft read up to where it sits, no step
queued behind one that ends its requests, a step's tokens streamed before the drafter's passes
end, a block drafter's proposals verified as a tree, the 31B's block-16 DFlash2 tree with its
short block under load, a block drafter's window carried in the window snapshot, and window
snapshots from short prompts
- redxherring: --model taking a Hugging Face repo id
- Smellyyyy: the idea behind --prefill-interleave
@@ -82,8 +98,8 @@ Written by Deadcode, with contributions from:
- devmilan: the NVFP4 and FP8 compressed-tensors imports
- sfjes: Gemma 4 31B dense -- its plugin, its two attention classes and their kernels, and prefix
reuse that leaves a windowed group alone -- and --host-headroom-mib
- zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg
PR 50, Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime, and Fish Audio drama-3 -- its
- zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg PR
50, Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime, and Fish Audio drama-3 -- its
plugin, its codec encoder and decoder, voice cloning from reference clips, and the torch.save
reader
- mici81: Gemma 3 dense (TranslateGemma 27B) -- its plugin, the windowed h128 attention, the
@@ -101,22 +117,23 @@ Written by Deadcode, with contributions from:
below the tip, Gemma 3's fused all-reduce junction on the lossy wire, the three-wave verify's
split by depth, the delta net's out-projection read beside its decode recurrent update, the MXFP4
feed-forward's gated fold up to 16 rows, the three-wave verify floor bounded by the batch's
workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6
paged prefill, the preempted-prefill gate past a KV group that holds no blocks, and the norms'
lane sum issuing its reads eight at a time, chained forms for every kernel of
Qwen3.8-Flash-Next's decode step with hc_read's forms G, S and B3, and a preempted request
publishing its prefix with an overdue one keeping its place
workgroups, the split-KV row sum read with fetch-inactive, KLATE again for the head-256 gqa6 paged
prefill, the preempted-prefill gate past a KV group that holds no blocks, and the norms' lane sum
issuing its reads eight at a time, chained forms for every kernel of Qwen3.8-Flash-Next's decode
step with hc_read's forms G, S and B3, and a preempted request publishing its prefix with an
overdue one keeping its place, and hc_read's decode forms G, S and B3 restored for ROCm 7.2
- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the
out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8
linears' operands directly
- davetha: JSON Schema patterns read unanchored, with their shorthand classes and escapes
- davetha: JSON Schema patterns read unanchored, with their shorthand classes and escapes, and the
README's abliterated Flash-Next container
- Nunze: the eight-rank all-reduce's bands, weighted shards from the PCIe links and pieces, the
sampler's candidate width at eight ranks, the image test stage's parallelism, budgets and
exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose
name the opener opens, GLM-5.3-Flash's vision tower and processor, its decode at a few rows and
its DSA indexer split over the ranks, a host-tier restore that makes room as pressure does, KV
groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA
row form (--tp-attn-split rows), DELETE /sessions, the dispatch stamps of a played pass with
groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA row
form (--tp-attn-split rows), DELETE /sessions, the dispatch stamps of a played pass with
stampgaps.py, one n-gram table for engines on separate cards (--ngram-placement ram=DIR), GGUF
Q8_0, Q4_K and Q6_K tensors imported as their planes, the dense integer rows at the group they
compute, and the GDN conv kernels on an f32 weight
@@ -124,60 +141,72 @@ Written by Deadcode, with contributions from:
sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their
reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the
one-sequence KV floor over the live plan, and prefill staging paid by expert residency
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and
the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped
rotation, the dashboard's history line, session extremes, card-count changes and Requests-header
JSON export, with the page's JavaScript driven by tests/js
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and the
bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped rotation,
the dashboard's history line, session extremes, card-count changes and Requests-header JSON
export, with the page's JavaScript driven by tests/js
- C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual
projection, KV streaming for a context bigger than VRAM (--kv-resident), and the dashboard's
request history, KV streaming traffic and one-unit KV meter
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), and MiniMax-H3's reference encoder reading host-readable operands (the
ref2va and fl2va crash)
- gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its
BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode
(the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds),
and the head-256 prefill softmax rescaled by row rather than by wave, Spark 2.5 (spark25: bf16 and
(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
by live KV bounds, and --gpu-memory-mib, and the calibrated U5 gate and W5NL down recipe, U4 gates with W6NL down experts, Muse Glimmer IQ4R-V4 with a
quantised DFlash2, and Qwen3.8-27B's native MTP draft head (vhead, the U2 head over a
vocabulary-split target, its coupled proposals and calibration)
- 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
directories, nomic-embed-text-v2-moe (the nomicbert plugin), its config key aliases and
RAD_MAP_TRANSPOSE honouring src_index, an f32 source narrowed to a bf16 declaration at load, and
the snapshot store's floor ahead of --host-headroom-mib
- steki: Gemma 4 E2B's per-layer MLP width and the bf16 descriptor for Google's E2B/E4B directories,
nomic-embed-text-v2-moe (the nomicbert plugin), its config key aliases and RAD_MAP_TRANSPOSE
honouring src_index, an f32 source narrowed to a bf16 declaration at load, and the snapshot
store's floor ahead of --host-headroom-mib
- griffin-warrior: the kernel report's consistency checks and coverage header, collective selftest
cases skipped without a peer path, the build's media capability in the diagnostics, and the
GUIDE's ROCm SDK and ffmpeg notes
- nickreese: GBNF bounded-repetition chains shared across identical operands
- Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid
wait trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS
and its gated three-tile form at 8 waves
- Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid wait
trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS and
its gated three-tile form at 8 waves
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library, and its wave-matrix rewrite: the GEMMs
retiled to 16x128 blocks, the grouped MoE GEMMs, the norms and quantisers, and the QSA and MoE
router rows, its MoE GEMMs at w4a8 and w4a4 with dequant_w4, row_topk_merge, ngram_ids and
the biased and short GEMMs, and w4a4's reference implementation
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
name no vocabulary row refused, and the telemetry the HTTP thread reads made atomic
name no vocabulary row refused, and the telemetry the HTTP thread reads made atomic, and the
security review of 2.0 and 2.1 with its hardening follow-up
- Brandon Bertelsen: Cloudflare's clef and clef-flash with their joint schema head on the card
(seg_softmax_pool, a request's words for the plugin), Convai Innovations' Laya decision models,
Mica on /v1/systemone, and Metaspace prepending only to text not already starting with its
replacement
- Gaspa79: NVIDIA's Nemotron 3.5 Embed 1B and 8B -- the nemotron35_embed plugin, its Pixtral
tower and their CPU path -- and Nemotron 3.5 Rerank 8B on /rerank, with its BF16 masked mean
- Gaspa79: NVIDIA's Nemotron 3.5 Embed 1B and 8B -- the nemotron35_embed plugin, its Pixtral tower
and their CPU path -- and Nemotron 3.5 Rerank 8B on /rerank, with its BF16 masked mean
(seg_mean_bf16_sum)
- overchop: the file tier for large MoEs -- routing-aware reads of only the routed experts, the
hot VRAM cache with its deposits and copyless relabels, and GLM-5.3-Flash's experts read
file-direct under expert parallelism -- the stall watch counting drive reads as progress, and
the DMA lane's lists fenced so a stalled read pointer no longer fills its ring
- overchop: the file tier for large MoEs -- routing-aware reads of only the routed experts, the hot
VRAM cache with its deposits and copyless relabels, and GLM-5.3-Flash's experts read file-direct
under expert parallelism -- the stall watch counting drive reads as progress, and the DMA lane's
lists fenced so a stalled read pointer no longer fills its ring
- pokesjw: the n-gram reader refilling its reads as they land, and a decode gather waiting on the
other rank's read of a row instead of reading it again
- AnimusNull: GLM-5.3-Flash on four cards -- its experts split by width, the small-M MXFP4 expert
@@ -185,10 +214,30 @@ Written by Deadcode, with contributions from:
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)
- 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
- 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
- DokterSmol: LiquidAI's LFM3 (lfm3_bf16: bf16, int8 and IQ8R trunks, the windowed attention at
head_dim 128 with four queries a KV head on libr4d and libhalo)
- rkcth: Qwen-Image 2.1's, Krea 2's and MiniMax-H3's deployment pixel and reference limits, a video
job held through its model's drain, tensor-parallel queues guarded beside single-rank engines,
guidance requests refused past the sequence limit, adapter image requests queued in order, model
discovery that leaves idle timers alone, host room reserved atomically for loads and fills, idle
expert-cache capacity restored, and LoRA rank truncation that drops dependent columns
- dowjames: runtime LoRA on a rotated int8 trunk (plain fp GEMM sites over transform-basis weights,
the lora_plain kernel library) and served adapters listed as children in /admin/fleet
- kaczy44: Gemma 4 26B-A4B's vision tower and rad-convert --add-vision
- Itoash: a tool-call delimiter that does not end the turn, and Ling 3.0's function names ending at
whitespace
- jintakhan: gemma4_bf16's sliding-window attention ported to gemma4
- forestjohnson: the dashboard behind a reverse proxy at a relative path
This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each.
+20
View File
@@ -21,6 +21,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
| model | container | get it | fleet file |
|---|---|---|---|
| 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-Flash-Next abliterated (refusals removed): IQR-V4 trunk (GPTQ), codebook experts (round to nearest), MTP, vision | `qwen3.8-flash-next-uncensored-iqr-v4.rad` (113 GiB) | [download](https://huggingface.co/davetha/qwen3.8-flash-next-uncensored-iqr-v4) | — |
| 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) | — |
@@ -54,6 +55,13 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
| 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) | `tp1.yaml`, `tp2.yaml` |
@@ -351,6 +359,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
# 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
@@ -394,6 +413,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 |
+12 -2
View File
@@ -19,7 +19,7 @@ extern "C" {
* version is refused at load with both versions printed. Each also exports the layout's fingerprint
* (rad_abi_layout.h), so two layouts given one number are refused as well. A new optional export
* (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default. */
#define RAD_ABI_VERSION 39u
#define RAD_ABI_VERSION 43u
/* ================================================================== plugin identity */
/* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin:
@@ -544,7 +544,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
+12
View File
@@ -27,6 +27,7 @@ ABI_FIELD(RadArchProbe, tree_pays)
ABI_FIELD(RadArchProbe, gen_max_pixels)
ABI_FIELD(RadArchProbe, gen_max_refs)
ABI_FIELD(RadArchProbe, gen_shape)
ABI_FIELD(RadArchProbe, ckpt_snap_ok)
ABI_STRUCT(RadArgs)
ABI_FIELD(RadArgs, t)
ABI_FIELD(RadArgs, n_t)
@@ -105,6 +106,8 @@ ABI_FIELD(RadBatch, bidi_n)
ABI_FIELD(RadBatch, bidi_seq)
ABI_FIELD(RadBatch, bidi_used)
ABI_FIELD(RadBatch, anchor_rows)
ABI_FIELD(RadBatch, ckpt_cut)
ABI_FIELD(RadBatch, ckpt_cu)
ABI_STRUCT(RadBufDecl)
ABI_FIELD(RadBufDecl, dtype)
ABI_FIELD(RadBufDecl, rank)
@@ -146,6 +149,7 @@ 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, span_pass_step)
ABI_STRUCT(RadAudioGenBatch)
ABI_FIELD(RadAudioGenBatch, n_lane)
ABI_FIELD(RadAudioGenBatch, lane)
@@ -192,6 +196,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)
@@ -232,6 +237,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)
@@ -278,6 +285,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)
@@ -945,3 +953,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_)
+40 -5
View File
@@ -283,6 +283,14 @@ typedef struct RadBuildCtx {
* 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 (--prefill-span-pass step) */
/* Nonzero: where the plugin runs a step wider than max_mixed_tok serially (it pipelines no
* part of it), its routed block may take the whole step in one pass rather than one pass a
* checkpoint interval, and size the planes that hold a row per (token, expert slot) for
* max_tok rows. 0, the zero-initialised default, keeps the interval-tall passes. A plugin
* without such a pass ignores it. */
int span_pass_step;
} RadBuildCtx;
/* The most instances (engine ranks) one process holds at once; every slot is below it. */
@@ -731,16 +739,19 @@ int rad_declare_plugin_words(RadBuilder* b, int64_t max_words);
* The kind is a drive shape, not a model. SERIAL runs `depth` dependent passes, each embedding the
* last one's proposal, so tokens arrive one at a time and a pass that declines ends the chain
* (MTP, EAGLE, Medusa-serial). BLOCK runs a context pass, then one pass that fills every drafted
* position at once (DFlash2 and other block-diffusion drafters).
* position at once (DFlash2 and other block-diffusion drafters). HISTORY runs just the serial
* history pass (draft_pass < 0, every hidden row, n_draft_out = 0) to collect calibration
* inputs. It is for --calib-corpus with max_spec = 0; it declares and produces no proposals.
*
* `proposal` is the buffer a pass writes its token ids into; 0 means the sampler's token buffer,
* which suits a head whose logits go through the ordinary sampler chain.
*
* Declaring no drafter is the normal case; the scheduler's prompt-lookup drafter still runs. */
typedef enum {
RAD_DRAFT_NONE = 0,
RAD_DRAFT_SERIAL = 1, /* `depth` dependent passes, one proposal each */
RAD_DRAFT_BLOCK = 2, /* a context pass, then one pass that fills the whole block */
RAD_DRAFT_NONE = 0,
RAD_DRAFT_SERIAL = 1, /* `depth` dependent passes, one proposal each */
RAD_DRAFT_BLOCK = 2, /* a context pass, then one pass that fills the whole block */
RAD_DRAFT_HISTORY = 3, /* calibration-only serial history pass, depth zero */
} RadDraftKind;
typedef struct RadDrafterDecl {
@@ -1264,13 +1275,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);
@@ -1718,6 +1738,14 @@ typedef struct RadArchProbe {
* `gen_rows` (its largest pass: a step's two branches, or a query pass's points). It keeps no
* KV. */
int32_t gen_shape;
/* ---- appended in ABI 43 (a checkpoint inside the step), in the tail padding behind gen_shape */
/* Nonzero when the plugin serves RadBatch::ckpt_cut: a step of one prefill sequence whose
* checkpoint lies inside it runs its recurrence in two pieces and snapshots between them
* (rad_ckpt_snap). The scheduler then takes a prompt's tail snapshot inside its last chunk
* rather than ending the chunk there and running the rows past it as a step of their own.
* Zero keeps that step. */
int32_t ckpt_snap_ok;
} RadArchProbe;
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
@@ -1847,6 +1875,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. */
+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. */
#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 */
+26 -2
View File
@@ -344,7 +344,8 @@ typedef struct RadBatch {
* (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
* after the run's last token, counted as the window group's seqused is: from the first
* position of its table), 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.
*
@@ -363,6 +364,18 @@ typedef struct RadBatch {
* 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;
/* ---- appended in ABI 43 (a checkpoint inside the step) */
/* A step of one prefill sequence (n_seq 1, no decode rows) whose linear-state checkpoint lies
* inside it rather than at its end: host, the rows before the checkpoint (its position less
* the sequence's context), 0 on every other step. Set only for a plugin that asked
* (RadArchProbe::ckpt_snap_ok). Such a plugin runs its recurrence over [0, ckpt_cut) and
* [ckpt_cut, n_tok) as two pieces -- each what a chunk of those rows computes -- and calls
* rad_ckpt_snap for each stateful layer between them, so the snapshot is the state a chunk
* ending at the checkpoint leaves, without a step of its own for the rows past it.
* `ckpt_cu` is [3] device: {0, ckpt_cut, n_tok}, a piece's cu_seqlens at +0 and +1; null when
* ckpt_cut is 0. */
int32_t ckpt_cut;
const int32_t* ckpt_cu;
} RadBatch;
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
@@ -625,6 +638,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
@@ -726,7 +742,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;
@@ -921,6 +938,13 @@ int rad_lane_join(RadCtx* c, int from, int to);
* the status it set, so a helper can `return rad_step_fail(...)`. */
int rad_step_fail(RadCtx* c, const char* what);
/* A step with a checkpoint inside it (RadBatch::ckpt_cut): copy layer `layer`'s state of the
* stateful KV group `group` -- the sequence's committed slot as the issue stands -- into the
* engine's checkpoint stage, on the current lane's stream. Called between the two pieces of the
* recurrence, once for every stateful group and layer the plugin holds. A no-op returning RAD_OK
* on a step with no checkpoint inside it, so a caller need not test. */
int rad_ckpt_snap(RadCtx* c, rad_kvgroup group, int layer);
/* ================================================================== run-phase queries */
const RadBatch* rad_batch(RadCtx* c);
/* The position of model layer `layer` among `group`'s bound layers, or -1 when this rank has no
+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;
+355 -73
View File
@@ -1,25 +1,53 @@
/* bailing_hybrid -- Ling-3.0-flash and its fine-tunes (`model_type: bailing_hybrid`,
* BailingMoeV3ForCausalLM), from the bf16 checkpoint, the routed experts as a recipe stores them
* (data/recipes/ling3-w4a8-rtn.recipe, ling3-w4a8-gptq.recipe).
/* bailing_hybrid -- Ling-3.0-flash, Ling-3.0-tiny and their fine-tunes (`model_type:
* bailing_hybrid`, BailingMoeV3ForCausalLM), from the bf16 checkpoint, the routed experts as a
* recipe stores them (data/recipes/ling3-w4a8-rtn.recipe, ling3-w4a8-gptq.recipe), an IQ8R trunk
* with rotated int8 experts (data/recipes/ling-3.0-tiny-iq8r.recipe; below), and the tiny
* family's GGUF releases (arch/bailing_hybrid_gguf and kin: IQ4_NL, Q8_0, Q4_K_M, Q5_K_M, Q6_K,
* the iq4 release's codes through data/recipes/ling-3.0-tiny-iq4.recipe).
*
* ============================== WHAT IT SERVES ==============================
*
* layers 42 in groups of six: five Kimi delta attention (KDA) layers, then one dense
* latent attention (MLA) layer, so layers 5, 11, ..., 41 are MLA
* KDA 32 heads of 128, separate q/k/v projections each with its own causal
* convolution, a full-rank per-channel forget gate (`f_proj`) and output gate
* (`g_proj`), lower bound -5
* MLA no query LoRA, a 512-wide latent and a 64-wide rotary part (interleaved pairs),
* heads of 128 + 64, values of 128, a sigmoid gate per head
* feed-forward layers 0-1 dense (6144); from layer 2, 512 experts of 768 at top-8 under
* group-limited sigmoid routing (8 groups, 4 kept, a correction bias, x2.5), an
* ungated shared expert, and a SwiGLU clipped after the SiLU in the last layers
* (`expert_swiglu_limit_list`, `share_expert_swiglu_limit_list`, as vLLM and
* SGLang serve it; HF's reference ignores it)
* layers flash: 42 in groups of six -- five Kimi delta attention (KDA) layers, then one
* dense latent attention (MLA) layer, so layers 5, 11, ..., 41 are MLA.
* tiny: 24 in groups of four, MLA at 3, 7, ..., 23.
* KDA flash: 32 heads of 128; tiny: 16. Separate q/k/v projections each with its own
* causal convolution, a full-rank per-channel forget gate (`f_proj`) and output
* gate (`g_proj`), lower bound -5
* MLA a 512-wide latent and a 64-wide rotary part (interleaved pairs), heads of
* 128 + 64, values of 128, a sigmoid gate per head. flash has no query LoRA;
* tiny projects through one: q_a and its norm feed q_b, whose rows serve the
* two query parts.
* feed-forward flash: layers 0-1 dense (6144); from layer 2, 512 experts of 768 at top-8.
* tiny: layer 0 dense (4608); from layer 1, 128 experts of 512 at top-8. Both
* under group-limited sigmoid routing (8 groups, 4 kept, a correction bias,
* x2.5), an ungated shared expert, and a SwiGLU clipped after the SiLU in the
* last layers (`expert_swiglu_limit_list`, `share_expert_swiglu_limit_list`, as
* vLLM and SGLang serve it; HF's reference ignores it)
*
* The KDA core is GLM-5.3's (KdaState), the router GLM-5.3's with groups (GlmRouter), the
* feed-forward MoeFP8. The KDA and MLA blocks around them are in this file.
*
* ============================== THE TRUNK'S FORM ==============================
*
* Read from layer 0's fused q|k|v before any activation buffer is declared. Two forms:
*
* - a rotated int8 trunk (data/recipes/ling-3.0-tiny-iq8r.recipe: IQ8R, int8 codes rotated by
* a 128-wide Hadamard under a u8 scale a (row, 256 of K) and a bf16 one a row): the block
* norms write rmsnorm_had_quant_i8g's codes at the trunk's group, read by every KDA
* projection, the shared expert's gate/up and the routed gate/up; the KDA core's gated norm
* and the MLA's expanded values are quantised by had_quant_act_i8g for their out projections;
* the dense and shared gated products write gated_had_quant_i8g's codes (the shared one at
* the group its own down weight is stored at), and the routed arm is int8 at one scale a 128
* (MoeFP8::a8), so the rotated int8 experts read those codes at i8a8h. Where no loaded
* library serves the rotating norm, each linear quantises the norm's bf16 output itself and
* the routed experts read a rotated copy written once a layer. The linears the recipe keeps
* bf16 (the KDA beta, the MLA's low-rank q and kv and its head gate) read the norm's bf16
* output in either case. A clamped SwiGLU (flash's last layers) writes the bf16 product,
* which had_quant_act_i8g quantises: one launch more than the unclamped gated product.
* - any other (bf16, the four-bit experts of ling3-w4a8-rtn and ling-3.0-tiny-iq4, the GGUF
* releases): the norms write E4M3 codes, each linear reads the bf16 plane or quantises it
* itself, and four-bit experts read the E4M3 pair (rotated ones a rotated copy of it).
*
* ============================== THE LATENT ATTENTION ==============================
*
* The MLA attends in the latent. The query projection is served as two, its heads' rotary rows and
@@ -55,11 +83,20 @@ using namespace rad::arch;
struct Shape {
int64_t n_embd = 0, n_layer = 0, heads = 0, head_dim = 0, nope = 0, rope = 0, v_dim = 0,
latent = 0, experts = 0, top_k = 0, groups = 0, topk_groups = 0, ff_exp = 0,
ff_shared = 0, ff_dense = 0, dense_layers = 0, group_size = 0, conv = 0;
ff_shared = 0, ff_dense = 0, dense_layers = 0, group_size = 0, conv = 0, q_lora = 0;
double lower = -5, route_scale = 1;
bool gguf = false; /* the checkpoint spells its tensors blk. and ssm. names (the release GGUF) */
std::vector<double> lim_exp, lim_shared;
};
/* A projection's checkpoint name: config.json's spelling under the layer prefix `pre`
* (`model.layers.%d.attention`) for the safetensors, the blk./ssm. spelling with the layer as %d
* for the release GGUF. */
static const char* ck_name(Names& nm, const Shape& sh, int l, const char* pre, const char* hf,
const char* gg) {
return sh.gguf ? nm.ckpt(gg, l) : nm.ckpt(hf, pre);
}
/* A KDA layer: the q/k/v, beta, forget and output-gate projections into KdaState, then o_proj and
* its all-reduce. */
struct LingKda {
@@ -76,40 +113,63 @@ struct LingKda {
QuantFP8 out_quant{};
rad_op op_ar = 0;
/* Maps layer l's fused q|k|v and reads its stored form (LinearFP8::probe); declare() then does
* not map it again. The model learns from it whether the trunk is rotated int8 before it
* declares any activation buffer. */
int probe_qkv(RadBuilder* b, Names& nm, const Geom& geom, const Shape& sh, int l,
const char* pre) {
return qkv.probe(b, nm, geom, nm.f("blk.%d.attn_qkv", l),
{ ck_name(nm, sh, l, pre, "%s.q_proj.weight", "blk.%d.attn_q.weight"),
ck_name(nm, sh, l, pre, "%s.k_proj.weight", "blk.%d.attn_k.weight"),
ck_name(nm, sh, l, pre, "%s.v_proj.weight", "blk.%d.attn_v.weight") });
}
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& sh, int l,
const Wire& wire, const char* pre, rad_kvgroup state, rad_kvgroup history) {
g = geom;
w = wire;
const int64_t heads = sh.heads / g.world, width = heads * sh.head_dim;
const auto grp = grp_layer(l);
/* One name a projection, the checkpoint's spelling (ck_name). */
auto ck = [&](const char* hf, const char* gg) -> const char* {
return ck_name(nm, sh, l, pre, hf, gg);
};
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), 3 * width, g.n_embd,
RAD_SHARD_ROW, grp,
{ nm.ckpt("%s.q_proj.weight", pre), nm.ckpt("%s.k_proj.weight", pre),
nm.ckpt("%s.v_proj.weight", pre) },
{ ck("%s.q_proj.weight", "blk.%d.attn_q.weight"),
ck("%s.k_proj.weight", "blk.%d.attn_k.weight"),
ck("%s.v_proj.weight", "blk.%d.attn_v.weight") },
w.input, w.core.qkv, 0, { width, width, width }));
RAD_ARCH_TRY(beta.declare(b, nm, g, nm.f("blk.%d.attn_beta", l), heads, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.b_proj.weight", pre) },
RAD_SHARD_ROW, grp, { ck("%s.b_proj.weight", "blk.%d.ssm_beta.weight") },
w.input, w.core.beta));
RAD_ARCH_TRY(forget.declare(b, nm, g, nm.f("blk.%d.attn_forget", l), width, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.f_proj.weight", pre) },
RAD_SHARD_ROW, grp, { ck("%s.f_proj.weight", "blk.%d.ssm_f_a.weight") },
w.input, w.core.a));
RAD_ARCH_TRY(gate.declare(b, nm, g, nm.f("blk.%d.attn_gate", l), width, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) },
RAD_SHARD_ROW, grp, { ck("%s.g_proj.weight", "blk.%d.ssm_g_a.weight") },
w.input, w.core.gate));
KdaState::Config kc;
kc.heads = heads;
kc.dim = sh.head_dim;
kc.width = sh.conv;
kc.lower = sh.lower;
KdaState::Src ks{ nm.ckpt("%s.q_conv1d.weight", pre), nm.ckpt("%s.k_conv1d.weight", pre),
nm.ckpt("%s.v_conv1d.weight", pre), nm.ckpt("%s.A_log", pre),
nm.ckpt("%s.dt_bias", pre), nm.ckpt("%s.o_norm.weight", pre) };
KdaState::Src ks{ ck("%s.q_conv1d.weight", "blk.%d.ssm_conv1d_q.weight"),
ck("%s.k_conv1d.weight", "blk.%d.ssm_conv1d_k.weight"),
ck("%s.v_conv1d.weight", "blk.%d.ssm_conv1d_v.weight"),
ck("%s.A_log", "blk.%d.ssm_a_raw"),
ck("%s.dt_bias", "blk.%d.ssm_dt.bias"),
ck("%s.o_norm.weight", "blk.%d.ssm_norm.weight") };
RAD_ARCH_TRY(core.declare(b, nm, g, l, state, history, kc, w.core, ks));
const char* on = nm.f("blk.%d.attn_output", l);
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.o_proj.weight", pre) }));
if (!output.reads_x) RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, width));
RAD_ARCH_TRY(output.probe(b, nm, g, on, { ck("%s.o_proj.weight", "blk.%d.attn_output.weight") }));
/* The out projection's input codes: on a rotated int8 trunk (ActFP8::q8_fed) an int8 out
* projection reads had_quant_act_i8g's, written here; otherwise a quantiser runs only for
* a weight that does not read the bf16 plane. */
if (w.core_out.q8_fed ? output.probed_i8 : !output.reads_x)
RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, width));
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, width, RAD_SHARD_COL, grp,
{ nm.ckpt("%s.o_proj.weight", pre) }, w.core_out, w.out));
{ ck("%s.o_proj.weight", "blk.%d.attn_output.weight") }, w.core_out, w.out));
op_ar = GlmTp::reduce(b, g, w.out);
return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
@@ -131,6 +191,8 @@ struct LingKda {
struct LingMla {
struct Wire {
ActFP8 input{};
ActFP8 qa{}; /* [T, q_lora], the tiny query LoRA's normed latent (the trunk's,
projected through q_a, for the parts' GEMMs) */
rad_buf q_rope = 0; /* [T, heads * rope] */
rad_buf q_nope = 0; /* [T, heads * nope] */
rad_buf row = 0; /* [T, latent + rope], the cache row */
@@ -146,11 +208,11 @@ struct LingMla {
int layer = 0;
int64_t heads = 0, qw = 0, cw = 0;
rad_kvgroup kv = 0;
LinearFP8 q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{};
QuantFP8 value_quant{};
rad_weight kv_gain = 0, kv_b = 0;
rad_op op_kv_norm = 0, op_q_rope = 0, op_k_rope = 0, op_store = 0, op_absorb = 0, op_attn = 0,
op_expand = 0, op_ar = 0;
LinearFP8 q_a_proj{}, q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{};
QuantFP8 value_quant{}, qa_quant{};
rad_weight kv_gain = 0, qa_gain = 0, kv_b = 0;
rad_op op_qa_norm = 0, op_kv_norm = 0, op_q_rope = 0, op_k_rope = 0, op_store = 0,
op_absorb = 0, op_attn = 0, op_expand = 0, op_ar = 0;
int64_t block = 0;
static constexpr int64_t kBlock = 16;
@@ -169,7 +231,17 @@ struct LingMla {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
/* One row map a part, a piece a head: [h * (nope + rope) + off, + width). Successive ROWS
* maps for one name extend it in call order (rad_builder.h), eight pieces a map. */
const char* qsrc = nm.ckpt("%s.q_proj.weight", pre);
/* flash projects the query from the trunk; tiny runs it through a LoRA first (q_a, its
* norm, then q_b), and the parts' rows come off q_b against the normed latent. */
const int64_t qk = s.q_lora ? s.q_lora : g.n_embd;
const ActFP8& qin = s.q_lora ? w.qa : w.input;
auto ck = [&](const char* hf, const char* gg) -> const char* {
/* The safetensors names are the layer prefix plus the projection (`pre`, `model.layers.%d`);
* the release GGUF spells them blk./ssm. with the layer as %d. */
return s.gguf ? nm.ckpt(gg, l) : nm.ckpt(hf, pre);
};
const char* qsrc = s.q_lora ? ck("%s.q_b_proj.weight", "blk.%d.attn_q_b.weight")
: ck("%s.q_proj.weight", "blk.%d.attn_q.weight");
auto part = [&](const char* name, int64_t off, int64_t width) -> int {
for (int64_t h0 = 0; h0 < s.heads; h0 += 8) {
RadNameMap m = map_base(name, RAD_MAP_ROWS);
@@ -183,18 +255,49 @@ struct LingMla {
}
return RAD_OK;
};
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_rope.weight", l), s.nope, s.rope));
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_nope.weight", l), 0, s.nope));
if (s.gguf) {
/* The reader split the quantised q_b into plain blocks a row map cannot see. */
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_rope.weight", l),
nm.ckpt("blk.%d.attn_q_b_rope.weight", l)));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_nope.weight", l),
nm.ckpt("blk.%d.attn_q_b_nope.weight", l)));
} else {
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_rope.weight", l), s.nope, s.rope));
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_nope.weight", l), 0, s.nope));
}
if (s.q_lora) {
RAD_ARCH_TRY(q_a_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_a", l), s.q_lora, g.n_embd,
RAD_SHARD_NONE, grp,
{ ck("%s.q_a_proj.weight", "blk.%d.attn_q_a.weight") }, w.input, w.qa.x));
const char* an = nm.f("blk.%d.attn_q_a_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, an, ck("%s.q_a_layernorm.weight", "blk.%d.attn_q_a_norm.weight")));
qa_gain = decl_w(b, an, RAD_F32, { s.q_lora }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp);
if (!qa_gain) return RAD_E_INVAL;
op_qa_norm = rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", s.q_lora),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(qa_gain)),
{ w.qa.x }, { w.qa.x });
if (!op_qa_norm) return RAD_E_INVAL;
}
q_rope_proj.mapped = q_nope_proj.mapped = true;
RAD_ARCH_TRY(q_rope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_rope", l), heads * s.rope,
g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_rope));
qk, RAD_SHARD_ROW, grp, { qsrc }, qin, w.q_rope));
RAD_ARCH_TRY(q_nope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_nope", l), heads * s.nope,
g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_nope));
qk, RAD_SHARD_ROW, grp, { qsrc }, qin, w.q_nope));
/* On a rotated int8 trunk the LoRA's latent carries an int8 pair that a part stored int8
* quantises itself (LinearFP8's own had_quant_act_i8g) and no E4M3 pair, so no quantiser
* runs here. */
if (s.q_lora && !q_nope_proj.reads_x && !w.qa.q8)
RAD_ARCH_TRY(qa_quant.declare(b, g, w.qa, s.q_lora));
RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), cw, g.n_embd,
RAD_SHARD_NONE, grp, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", pre) },
RAD_SHARD_NONE, grp,
{ ck("%s.kv_a_proj_with_mqa.weight", "blk.%d.attn_kv_a_mqa.weight") },
w.input, w.row));
const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", pre)));
RAD_ARCH_TRY(map_copy(b, kn, ck("%s.kv_a_layernorm.weight", "blk.%d.attn_kv_a_norm.weight")));
kv_gain = decl_w(b, kn, RAD_F32, { s.latent }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
if (!kv_gain) return RAD_E_INVAL;
op_kv_norm = rw(b,
@@ -217,7 +320,8 @@ struct LingMla {
RAD_NOWEIGHTS),
{ w.row }, {});
const char* bn = nm.f("blk.%d.attn_kv_b.weight", l);
RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.kv_b_proj.weight", pre)));
/* The GGUF keeps k_b and v_b head-last; the reader fuses them into this name. */
RAD_ARCH_TRY(map_copy(b, bn, ck("%s.kv_b_proj.weight", "blk.%d.attn_kv_b.weight")));
kv_b = decl_w(b, bn, RAD_BF16, { heads * (s.nope + s.v_dim), s.latent }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_ROW, grp);
if (!op_kv_norm || !op_q_rope || !op_k_rope || !op_store || !kv_b) return RAD_E_INVAL;
@@ -229,7 +333,8 @@ struct LingMla {
RAD_WEIGHTS(kv_b)),
{ w.q_nope }, { w.q_lat });
RAD_ARCH_TRY(g_proj.declare(b, nm, g, nm.f("blk.%d.attn_head_gate", l), heads, g.n_embd,
RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) },
RAD_SHARD_ROW, grp,
{ ck("%s.g_proj.weight", "blk.%d.attn_gate.weight") },
w.input, w.gate));
op_attn = rw(b,
RAD_OP(b, "mla_attn_paged",
@@ -255,10 +360,12 @@ struct LingMla {
return RAD_E_INVAL;
}
const char* on = nm.f("blk.%d.attn_output", l);
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.dense.weight", pre) }));
if (!output.reads_x) RAD_ARCH_TRY(value_quant.declare(b, g, w.value, heads * s.v_dim));
RAD_ARCH_TRY(output.probe(b, nm, g, on, { ck("%s.dense.weight", "blk.%d.attn_output.weight") }));
/* As the KDA out projection's input (LingKda::declare). */
if (w.value.q8_fed ? output.probed_i8 : !output.reads_x)
RAD_ARCH_TRY(value_quant.declare(b, g, w.value, heads * s.v_dim));
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, heads * s.v_dim, RAD_SHARD_COL, grp,
{ nm.ckpt("%s.dense.weight", pre) }, w.value, w.out));
{ ck("%s.dense.weight", "blk.%d.attn_output.weight") }, w.value, w.out));
op_ar = GlmTp::reduce(b, g, w.out);
return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
@@ -271,8 +378,14 @@ struct LingMla {
}
const int64_t T = batch->n_tok, S = batch->n_seq;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
q_rope_proj.step(c, w.input, w.q_rope, T);
q_nope_proj.step(c, w.input, w.q_nope, T);
const ActFP8& qin = s.q_lora ? w.qa : w.input;
if (s.q_lora) {
q_a_proj.step(c, w.input, w.qa.x, T);
RAD_ISSUE_N(c, op_qa_norm, T, brows(w.qa.x, T), RAD_W(qa_gain), brows(w.qa.x, T));
qa_quant.step(c, T);
}
q_rope_proj.step(c, qin, w.q_rope, T);
q_nope_proj.step(c, qin, w.q_nope, T);
kv_a.step(c, w.input, w.row, T);
g_proj.step(c, w.input, w.gate, T);
RAD_ISSUE_N(c, op_kv_norm, T, bcol(w.row, 0, s.latent, T), RAD_W(kv_gain),
@@ -308,6 +421,11 @@ struct Model {
Names nm{};
Geom g{};
Shape s{};
/* Whether layer 0's probe found a rotated-int8 trunk, and its activation scale group: see
* rad_fp8.h's trunk_rotation. `norm_fed`: the block norms write those codes themselves
* (rmsnorm_had_quant_i8g is served). */
bool trunk_rot = false, norm_fed = false;
int64_t trunk_g8 = RAD_FP8_BLOCK;
std::vector<Layer> layers;
rad_kvgroup latent = 0, state = 0, conv = 0;
rad_buf x = 0, y = 0, final_hidden = 0, logit_input = 0, logits = 0;
@@ -370,6 +488,8 @@ static int read_shape(const RadModelMeta* meta, Shape& s) {
s.dense_layers = cfg(meta, "first_k_dense_replace", 0);
s.group_size = cfg(meta, "layer_group_size", 0);
s.conv = cfg(meta, "short_conv_kernel_size", 0);
s.q_lora = cfg(meta, "q_lora_rank", 0);
s.gguf = cfg(meta, "gguf_source", 0) != 0;
s.lower = rad_meta_getf(meta, "kda_lower_bound", 0.0);
s.route_scale = rad_meta_getf(meta, "routed_scaling_factor", 0.0);
s.lim_exp = cfg_list(meta, "expert_swiglu_limit_list");
@@ -382,7 +502,11 @@ static int read_shape(const RadModelMeta* meta, Shape& s) {
{ "qk_nope_head_dim == v_head_dim (mla_project's head)", s.nope > 0 && s.nope == s.v_dim },
{ "an even qk_rope_head_dim", s.rope > 0 && !(s.rope & 1) },
{ "an even kv_lora_rank + qk_rope_head_dim", s.latent > 0 && !((s.latent + s.rope) & 1) },
{ "q_lora_rank null", cfg(meta, "q_lora_rank", 0) == 0 },
{ "q_lora_rank null, or 256 for the tiny family's query LoRA",
s.q_lora == 0 || s.q_lora == 256 },
{ "the tiny family's query LoRA in a GGUF release (the reader splits its quantised q_b; "
"a full-rank attn_q has no GGUF path)",
!s.gguf || s.q_lora != 0 },
{ "no_kda_lora", cfg(meta, "no_kda_lora", 0) != 0 },
{ "kda_safe_gate", cfg(meta, "kda_safe_gate", 1) != 0 },
{ "a negative kda_lower_bound", s.lower < 0 && std::isfinite(s.lower) },
@@ -423,18 +547,38 @@ static void slice_of(int64_t blocks, int world, int rank, int first, int64_t* lo
/* ============================== The trunk's buffers ============================== */
/* The activation code pairs follow the trunk's form (the file's head comment). On a rotated int8
* trunk every pair is int8 at the trunk's group and is declared before the wires are copied, so
* each block sees whether its producer writes the codes (ActFP8::q8_fed): the norms where
* `norm_fed`, the out projections' quantisers always, the gated products where gated_had_quant_i8g
* is served (ActFP8::declare_pair). A producer whose rotating form is not served keeps an E4M3 pair
* that no linear reads, and each int8 linear then quantises the bf16 plane itself. */
static int buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& s = m.s;
auto& nm = m.nm;
const int64_t T = g.max_tok, E = g.n_embd, H = s.heads / g.world, W = H * s.head_dim;
const bool rot = m.trunk_rot;
const int64_t g8 = m.trunk_g8;
auto bf = [&](const char* n, std::initializer_list<int64_t> shape) {
return decl_b(b, nm.f("%s", n), RAD_BF16, shape);
};
/* A rotated int8 trunk's pair on `a`, written by its producer (`fed`) or by each int8 linear
* reading it. */
auto i8_pair = [&](ActFP8& a, const char* n, int64_t width, bool fed) -> int {
RAD_ARCH_TRY(a.declare_qs(b, nm, g, n, width, 0, true, false, g8));
a.q8_fed = a.q8_rot = fed;
return RAD_OK;
};
m.x = bf("residual", { T, E });
m.y = bf("attn_delta", { T, E });
m.act.x = bf("normed", { T, E });
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E));
if (rot) {
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E, 0, true, !m.norm_fed, g8));
m.act.q8_fed = m.act.q8_rot = m.norm_fed;
} else {
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E));
}
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, E }, RAD_BUF_PERSIST);
m.logit_input = bf("logit_input", { g.max_logit_rows, E });
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
@@ -450,7 +594,10 @@ static int buffers(RadBuilder* b, Model& m) {
kw.core.gate = bf("kda_gate", { T, W });
kw.core.out = bf("kda_out", { T, W });
kw.core_out.x = kw.core.out;
RAD_ARCH_TRY(kw.core_out.declare_qs(b, nm, g, "kda_out", W));
if (rot)
RAD_ARCH_TRY(i8_pair(kw.core_out, "kda_out", W, true));
else
RAD_ARCH_TRY(kw.core_out.declare_qs(b, nm, g, "kda_out", W));
auto& aw = m.aw;
aw.input = m.act;
@@ -461,19 +608,35 @@ static int buffers(RadBuilder* b, Model& m) {
aw.q_lat = bf("mla_q_latent", { T, H * s.latent });
aw.gate = bf("mla_gate", { T, H });
aw.attn = bf("mla_attn_latent", { T, H * s.latent });
if (s.q_lora) {
aw.qa.x = bf("mla_q_a", { T, s.q_lora });
if (rot)
RAD_ARCH_TRY(i8_pair(aw.qa, "mla_q_a", s.q_lora, false));
else
RAD_ARCH_TRY(aw.qa.declare_qs(b, nm, g, "mla_q_a", s.q_lora));
}
aw.value.x = bf("mla_value", { T, H * s.v_dim });
RAD_ARCH_TRY(aw.value.declare_qs(b, nm, g, "mla_value", H * s.v_dim));
if (rot)
RAD_ARCH_TRY(i8_pair(aw.value, "mla_value", H * s.v_dim, true));
else
RAD_ARCH_TRY(aw.value.declare_qs(b, nm, g, "mla_value", H * s.v_dim));
auto& dw = m.dw;
dw.x = m.x;
dw.h = m.act;
dw.gate_up = bf("dense_gate_up", { T, 2 * g.n_ff });
dw.ffn.x = bf("dense_ff", { T, g.n_ff });
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
if (rot)
RAD_ARCH_TRY(dw.ffn.declare_pair(b, nm, g, "dense_ff", g.n_ff, 0, true, g8,
"gated_had_quant_i8g"));
else
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
return RAD_OK;
}
static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
/* `shared_g8`: on a rotated int8 trunk, the scale group of the shared expert's stored down weight,
* which its input codes take. */
static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc, int64_t shared_g8) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, E = g.n_embd, F = mc.n_ff_exp, k = mc.top_k;
@@ -491,9 +654,25 @@ static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * k });
mw.egu = bf("expert_gate_up", { T * k, 2 * F });
mw.eff.x = bf("expert_ff", { T * k, F });
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k));
if (m.trunk_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(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k, true, false,
RAD_FP8_BLOCK));
mw.eff.q8_fed = mw.eff.q8_rot = true;
} else {
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k));
}
mw.edn = bf("expert_down", { T * k, E });
if (mc.expert_rot) {
if (m.trunk_rot) {
/* The routed gate_up reads the norm's own codes where it writes them, else a rotated int8
* copy of the block input that MoeFP8 writes once a layer (Wire::hr). */
if (!m.norm_fed) {
RAD_ARCH_TRY(mw.hr.declare_qs(b, nm, g, "normed_rot", E, 0, true, false,
RAD_FP8_BLOCK));
mw.hr.q8_fed = mw.hr.q8_rot = true;
}
} else if (mc.expert_rot) {
mw.hr.q = decl_b(b, nm.f("normed_rot.q"), RAD_F8E4M3, { T, E });
mw.hr.s = decl_b(b, nm.f("normed_rot.s"), RAD_F32, { T, E / RAD_FP8_BLOCK });
if (!mw.hr.q || !mw.hr.s) return RAD_E_INVAL;
@@ -501,7 +680,11 @@ static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
if (mc.n_ff_shared > 0) {
mw.sgu = bf("shared_gate_up", { T, 2 * mc.n_ff_shared });
mw.sff.x = bf("shared_ff", { T, mc.n_ff_shared });
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", mc.n_ff_shared));
if (m.trunk_rot)
RAD_ARCH_TRY(mw.sff.declare_pair(b, nm, g, "shared_ff", mc.n_ff_shared, 0, true,
shared_g8, "gated_had_quant_i8g"));
else
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", mc.n_ff_shared));
mw.sout = bf("shared_out", { T, E });
mw.sgate = bf("shared_one", { T, 1 });
}
@@ -614,11 +797,23 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
ms.cfg = mc;
ms.cfg.swiglu_limit = limit_at(s.lim_exp, l);
ms.cfg.shared_swiglu_limit = limit_at(s.lim_shared, l);
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
ms.router = nm.ckpt("%s.mlp.gate.weight", pre);
ms.router_bias = nm.ckpt("%s.mlp.gate.expert_bias", pre);
ms.experts = nm.ckpt("%s.mlp.experts", pre);
ms.shared = nm.ckpt("%s.mlp.shared_experts", pre);
ms.norm = s.gguf ? nm.ckpt("blk.%d.ffn_norm.weight", l)
: nm.ckpt("%s.post_attention_layernorm.weight", pre);
ms.router = s.gguf ? nm.ckpt("blk.%d.ffn_gate_inp.weight", l)
: nm.ckpt("%s.mlp.gate.weight", pre);
ms.router_bias = s.gguf ? nm.ckpt("blk.%d.exp_probs_b.bias", l)
: nm.ckpt("%s.mlp.gate.expert_bias", pre);
if (s.gguf) {
/* The release GGUF stacks the experts expert-last, the block's split-stacked
* source slicing one expert off each: [E, ff, emb] gate and up, [E, emb, ff] down. */
ms.experts_gate = nm.ckpt("blk.%d.ffn_gate_exps.weight", l);
ms.experts_up = nm.ckpt("blk.%d.ffn_up_exps.weight", l);
ms.experts_down = nm.ckpt("blk.%d.ffn_down_exps.weight", l);
} else {
ms.experts = nm.ckpt("%s.mlp.experts", pre);
}
ms.shared = s.gguf ? nm.ckpt("blk.%d.mlp.shared_experts", l)
: nm.ckpt("%s.mlp.shared_experts", pre);
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, ms, &ms.cfg));
if (ms.cfg.expert_rot) mc.expert_rot = 1;
if (ms.cfg.expert_bf16) mc.expert_bf16 = 1;
@@ -645,8 +840,57 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
g.rank, (long long)mc.expert_base, (long long)(mc.expert_base + per),
(long long)s.experts);
}
/* ---- the trunk's stored form, read from layer 0's fused q|k|v through that layer's own
* LinearFP8 (layer 0 is KDA: the last of each group of `layer_group_size` > 1 is MLA). The
* activations below carry rotated int8 codes only for a rotated trunk. */
m.layers.resize((size_t)s.n_layer);
RAD_ARCH_TRY(m.layers[0].kda.probe_qkv(b, nm, g, s, 0,
nm.ckpt("%s.attention", nm.ckpt("model.layers.%d", 0))));
{
RadEncoding enc{};
m.trunk_rot = weight_enc(b, nm.f("blk.0.attn_qkv.weight"), &enc) &&
trunk_rotation(enc, &m.trunk_g8);
}
int64_t shared_g8 = m.trunk_g8;
if (m.trunk_rot) {
/* The routed experts read the trunk's rotated int8 codes (MoeFP8::a8), which only a
* rotated expert meets. A clamped layer clamps, then quantises (GateQuantFP8). */
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
const MoeFP8::Config& c = msrc[(size_t)l].cfg;
if (c.expert_bf16 || !c.expert_rot) {
fprintf(stderr, "radiance: bailing_hybrid: the trunk is rotated int8 and layer %d's "
"routed experts are %s; a rotated trunk's experts read its int8 codes "
"and are stored rotated (data/recipes/ling-3.0-tiny-iq8r.recipe)\n",
l, c.expert_bf16 ? "plain bf16" : "unrotated");
return RAD_E_UNSUPPORTED;
}
}
m.norm_fed = rad_op_declared(b, "rmsnorm_had_quant_i8g") != 0;
/* 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 MoeFP8 then does not map again). */
const int lm = (int)s.dense_layers;
if (lm < (int)s.n_layer && mc.n_ff_shared > 0) {
LinearFP8& sd = m.layers[(size_t)lm].moe.sh_down;
RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.%d.ffn_down_shexp", lm),
{ nm.ckpt("%s.down_proj.weight", msrc[(size_t)lm].shared) }));
if (sd.probed_i8) shared_g8 = sd.probed_g8;
}
} else {
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
const MoeFP8::Config& c = msrc[(size_t)l].cfg;
if (c.expert_i8 || c.expert_iqr) {
fprintf(stderr, "radiance: bailing_hybrid: layer %d's 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/ling-3.0-tiny-iq8r.recipe)\n", l);
return RAD_E_UNSUPPORTED;
}
}
}
RAD_ARCH_TRY(buffers(b, m));
RAD_ARCH_TRY(moe_buffers(b, m, mc));
RAD_ARCH_TRY(moe_buffers(b, m, mc, shared_g8));
/* ---- the caches: the MLA layers' latent rows, the KDA layers' state and convolution
* history. */
@@ -674,9 +918,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
/* ---- the embedding, the layers, the final norm and the head. */
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.word_embeddings.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
/* The release GGUF already spells the head tensors under the container's names; the first
* source the container holds wins. */
RAD_ARCH_TRY(map_copy_alt(b, nm.f("token_embd.weight"), nm.ckpt("model.word_embeddings.weight"),
nm.ckpt("token_embd.weight")));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("output.weight")));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"),
nm.ckpt("output_norm.weight")));
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, { g.n_vocab, g.n_embd },
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, g.n_embd }, RAD_ACCESS_VOCAB,
@@ -699,7 +948,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
lay.dense = l < s.dense_layers;
const char* pre = nm.ckpt("model.layers.%d", l);
const char* nn = nm.f("blk.%d.attn_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre)));
RAD_ARCH_TRY(map_copy(b, nn, s.gguf ? nm.ckpt("blk.%d.attn_norm.weight", l)
: nm.ckpt("%s.input_layernorm.weight", pre)));
lay.gain = decl_w(b, nn, RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
RAD_ARCH_TRY(lay.norm.declare(b, g, lay.gain, m.x, m.act, g.n_embd));
@@ -719,10 +969,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
{ m.x, m.y }, { m.x });
if (!lay.op_add) return RAD_E_INVAL;
if (lay.dense) {
MlpFP8::Src ds{ nm.ckpt("%s.post_attention_layernorm.weight", pre),
nm.ckpt("%s.mlp.gate_proj.weight", pre),
nm.ckpt("%s.mlp.up_proj.weight", pre),
nm.ckpt("%s.mlp.down_proj.weight", pre) };
MlpFP8::Src ds{ s.gguf ? nm.ckpt("blk.%d.ffn_norm.weight", l)
: nm.ckpt("%s.post_attention_layernorm.weight", pre),
s.gguf ? nm.ckpt("blk.%d.ffn_gate.weight", l)
: nm.ckpt("%s.mlp.gate_proj.weight", pre),
s.gguf ? nm.ckpt("blk.%d.ffn_up.weight", l)
: nm.ckpt("%s.mlp.up_proj.weight", pre),
s.gguf ? nm.ckpt("blk.%d.ffn_down.weight", l)
: nm.ckpt("%s.mlp.down_proj.weight", pre) };
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, l, m.dw, ds));
} else {
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, m.mw, msrc[(size_t)l]));
@@ -780,10 +1034,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
rad_note(b,
"Ling-3.0 (bailing_hybrid): TP%d, %lld layers, %lld KDA + %lld dense MLA, %lld experts "
"top-%lld in %lld groups (%lld kept), MTP %s",
"top-%lld in %lld groups (%lld kept), MTP %s, %s trunk",
world, (long long)s.n_layer, (long long)(s.n_layer - s.n_layer / s.group_size),
(long long)(s.n_layer / s.group_size), (long long)s.experts, (long long)s.top_k,
(long long)s.groups, (long long)s.topk_groups, m.have_mtp ? "enabled" : "not declared");
(long long)s.groups, (long long)s.topk_groups, m.have_mtp ? "enabled" : "not declared",
!m.trunk_rot ? "unrotated"
: m.trunk_g8 == RAD_I8_GROUP_WIDE ? "IQ8R (rotated int8)" : "rotated int8");
return RAD_OK;
}
@@ -879,10 +1135,36 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
} /* namespace bailing_hybrid */
/* The GGUF release wrappers (arch/bailing_hybrid_gguf* and kin) define these to their file's
* `general.file_type` and plugin name and include the file; the base plugin keeps the empty
* quant. The name is spelled by a macro, not by RAD_ARCH_PLUGIN's stringifier: a macro argument
* that reaches `#` expands as written, and a wrapper that only renames the namespace would ship
* five plugins all called "bailing_hybrid". */
#ifndef BAILING_HYBRID_QUANT
#define BAILING_HYBRID_QUANT ""
#endif
#ifndef BAILING_HYBRID_PLUGIN
#define BAILING_HYBRID_PLUGIN "bailing_hybrid"
#endif
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(bailing_hybrid)
/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */
RAD_ARCH_MULTI_INSTANCE()
RAD_ARCH_PLUGIN(bailing_hybrid, "bailinghybrid", "", "0.1.0",
"Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts")
extern "C" const char* rad_arch_id(void) { return "bailinghybrid"; }
extern "C" const char* rad_arch_quant(void) { return BAILING_HYBRID_QUANT; }
extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) {
return bailing_hybrid::declare(b, m, c);
}
extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) {
bailing_hybrid::step(c, batch);
}
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
extern "C" uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); }
extern "C" const RadPluginInfo* rad_plugin_info(void) {
static const RadPluginInfo info = {
RAD_PLUGIN_ARCH, BAILING_HYBRID_PLUGIN, "0.1.0",
"Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts", "" };
return &info;
}
#endif
+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)
+138 -30
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 */
@@ -1183,6 +1213,8 @@ 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 || rad_build_slot(ctx) >= MAX_SLOTS)
@@ -1214,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{};
@@ -1221,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;
@@ -1267,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];
@@ -1358,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);
}
@@ -1504,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);
+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);
}
}
}
+85 -7
View File
@@ -184,10 +184,9 @@ inline long long calib_target() {
* from an exercised one: libquant reads a per-expert file only when it holds several times K
* rows. `domain` is what the tap summed; a reader quantising in another domain converts the file
* itself (libquant's calib_sum). */
inline bool calib_write_host(const float* h, int64_t k, long long rows, const char* what,
uint32_t domain, int rank) {
const char* dir = calib_dir();
if (!dir || !h || k <= 0) return false;
inline bool calib_write_host_to(const char* dir, const float* h, int64_t k, long long rows,
const char* what, uint32_t domain, int rank) {
if (!dir || !*dir || !h || k <= 0) return false;
char path[512];
std::snprintf(path, sizeof path, "%s/gram.r%d.%s.bin", dir, rank, what);
FILE* f = std::fopen(path, "wb");
@@ -211,6 +210,11 @@ inline bool calib_write_host(const float* h, int64_t k, long long rows, const ch
return okw;
}
inline bool calib_write_host(const float* h, int64_t k, long long rows, const char* what,
uint32_t domain, int rank) {
return calib_write_host_to(calib_dir(), h, k, rows, what, domain, rank);
}
/* The same file from a device accumulator: copied back on the block's stream, then written. */
inline bool calib_write(RadCtx* c, rad_buf b, int64_t k, long long rows, const char* what,
uint32_t domain) {
@@ -223,6 +227,19 @@ 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 selected architecture tap may use the build context's directory directly, rather than the
* legacy process environment helper above. */
inline bool calib_write_to(RadCtx* c, rad_buf b, int64_t k, long long rows, const char* what,
uint32_t domain, const char* dir) {
if (!dir || !*dir || !b || k <= 0) return false;
void* p = rad_buf_ptr(c, b);
if (!p) return false;
std::vector<float> h((size_t)(k * k));
if (rad_memcpy_async(h.data(), p, (int64_t)h.size() * 4, rad_stream(c)) < 0) return false;
if (rad_stream_sync(rad_stream(c)) < 0) return false;
return calib_write_host_to(dir, h.data(), k, rows, what, domain, rad_rank(c));
}
/* 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. */
@@ -344,8 +361,24 @@ private:
std::string scope_;
};
/* Returns the first negative status from a declare step. */
#define RAD_ARCH_TRY(expr) do { int _s = (expr); if (_s < 0) return _s; } while (0)
/* Returns the first negative status from a declare step, and says where the status crossed. A
* step can return a status with no message of its own, and a failed declare would then report
* the status alone. Every level the status passes prints one line, innermost first, so the lines
* read as the path from the step that failed up to the plugin's declare. */
#ifdef __FILE_NAME__
#define RAD_ARCH_FILE __FILE_NAME__
#else
#define RAD_ARCH_FILE __FILE__
#endif
#define RAD_ARCH_TRY(expr) \
do { \
int _s = (expr); \
if (_s < 0) { \
fprintf(stderr, "radiance: declare: %s, from %s:%d\n", rad_strerror(_s), \
RAD_ARCH_FILE, __LINE__); \
return _s; \
} \
} while (0)
/* ================================================================== C++-side decl helpers */
/* C++ forms of rad_group_layer() and friends, which are C compound literals (a GNU extension in
@@ -676,8 +709,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));
}
@@ -1466,6 +1504,46 @@ 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;
* 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, each layer issuing its own selection. An
* instrument for comparing that sequence with the forms above (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)
+3 -2
View File
@@ -156,8 +156,9 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
{w.qkv}, {});
/* The out-projection's input quantiser; a plain `quant_act_fp8`, as there is no gate pass to
* fold it into. */
RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
* fold it into. Declared where the activation carries a code pair its producer writes: an int8
* trunk that leaves each linear to quantise its own input declares none (nemotronh). */
if (w.attn.cq()) 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));
+101 -13
View File
@@ -79,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
@@ -111,6 +126,14 @@ struct AttnGatedFP8 {
* (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 */
@@ -168,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,
@@ -185,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);
@@ -571,7 +633,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;
@@ -633,11 +695,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, o.w, T);
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
@@ -682,6 +756,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
@@ -694,7 +769,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
@@ -708,6 +783,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
@@ -715,6 +803,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),
@@ -736,8 +825,7 @@ 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),
@@ -760,8 +848,7 @@ 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),
@@ -777,8 +864,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));
}
@@ -839,6 +925,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) {
@@ -852,6 +939,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))
+68 -24
View File
@@ -147,6 +147,10 @@ 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;
/* The drafter's logit transform: `omul` multiplies the final norm's output, `scap` > 0 is
* a tanh soft cap on the draft logits. 1 and 0 leave the logits as the head gives them. */
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;
@@ -270,6 +274,10 @@ 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;
/* The copy is plain bf16 where the container holds it so, read by gemm_nt: the form for a
* vocabulary that is not a multiple of the int8 and 2-bit head kernels' 128-row tile (Muse
* Glimmer's 202048 tokens). */
bool head_bf16 = false;
/* per-layer weights */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
@@ -334,7 +342,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
@@ -482,12 +490,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
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);
{
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 &&
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) {
@@ -496,6 +505,11 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
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());
} 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());
@@ -503,7 +517,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split,
grp_model());
}
if (!w_dh || !w_dhs) return RAD_E_INVAL;
if (!w_dh || (!head_bf16 && !w_dhs)) return RAD_E_INVAL;
}
/* ---------------------------------------------------------------- per-layer weights */
@@ -945,12 +959,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
@@ -974,6 +995,9 @@ 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;
/* The output multiplier is declared on the plain final rmsnorm only: a drafter with one
* takes the unfused add and norm. */
if (cfg.omul != 1.0) op_afinal = 0;
}
/* ---------------------------------------------------------------- the head and the selector
@@ -991,12 +1015,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.h}, {w.sel_h});
/* LiLiCorr's head is the plugin's (rad_block_lilicorr.h), over sel_h. */
if (cfg.lili) return RAD_OK;
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
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),
@@ -1009,6 +1040,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. */
@@ -1359,12 +1398,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
/* `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) {
+45 -2
View File
@@ -134,6 +134,11 @@ struct GdnFP8 {
* 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;
@@ -508,11 +513,12 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
* 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) {
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, op_pf_out, RAD_W(out.w));
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, op_pf_out, RAD_W(out.w));
RAD_ISSUE(c, pf, RAD_W(out.w));
rad_lane(c, 0);
}
}
@@ -551,7 +557,43 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
* gated norm, quantiser and out projection are per row, so a pure prefill step can finish them
* a piece at a time and hand off each piece's reduction behind it. */
const bool cut = !own_ar && pieces && pieces->cuts(T) && D == 0 && P > 0 && !op_add;
/* A checkpoint inside the step (RadBatch::ckpt_cut): the convolution, solve and scan run over
* [0, cut) and [cut, T) as two pieces, each the chunk of those rows (the state handed on
* through the cache, the second piece's context its first row's position, as ArPieces' pieces
* do), and the state and convolution slots go to the checkpoint stage between them. The first
* piece is issued at the band a chunk of its rows takes, so the snapshot holds the bytes a
* step ending at the checkpoint leaves. */
const int64_t ck = batch->ckpt_cut;
const bool ck_split = P == 1 && D == 0 && ck > 0 && ck < T && batch->ckpt_cu;
if (ck_split) {
for (int64_t p = 0; p < 2; ++p) {
const int64_t n = p == 0 ? ck : T - ck;
const int32_t* cu = batch->ckpt_cu + p;
RAD_ISSUE_N(c, op_conv_prep, n,
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log),
RAD_W(w_dt_bias), kv_cache(kv_conv, layer), praw(cu, RAD_I32, 2),
bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
praw(cv_idx, RAD_I32, 1),
praw(p == 0 ? batch->ctx_lens : batch->positions + ck, RAD_I32, 1),
brows(w.q, T), brows(w.k, T), brows(w.v, T),
brows(w.gdec, T), brows(w.beta, T));
RAD_ISSUE_N(c, op_kkt, n,
brows(w.k, T), brows(w.beta, T), brows(w.gdec, T),
praw(cu, RAD_I32, 2), brows(w.kkt, T));
RAD_ISSUE_N(c, op_scan, n,
brows(w.q, T), brows(w.k, T), brows(w.v, T), brows(w.kkt, T),
brows(w.gdec, T), brows(w.beta, T),
kv_cache(kv_state, layer), praw(cu, RAD_I32, 2),
brows(w.o.x, T), kv_cache(kv_state, layer),
praw2(st_idx, RAD_I32, 1, st_w));
if (p == 0) {
rad_ckpt_snap(c, kv_state, layer);
rad_ckpt_snap(c, kv_conv, layer);
}
}
}
if (P > 0) {
if (!ck_split) {
RAD_ISSUE(c, op_conv_prep,
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log), RAD_W(w_dt_bias),
kv_cache(kv_conv, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
@@ -569,6 +611,7 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
kv_cache(kv_state, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
brows(w.o.x, T), kv_cache(kv_state, layer),
praw2(st_idx ? st_idx + D * st_w : nullptr, RAD_I32, P, st_w));
}
if (cut) {
for (int64_t r0 = 0; r0 < T; r0 += pieces->rows) {
const int64_t n = T - r0 < pieces->rows ? T - r0 : pieces->rows;
+14 -3
View File
@@ -170,10 +170,21 @@ struct HyperConn {
* (hc_down_kchunk in libr4d), so one read over twice the rows sums in a different order than
* two reads over half of them; reading a wide step in pieces computes what the narrower steps
* did. */
void read_pieces(RadCtx* c_, int64_t T) const {
void read_pieces(RadCtx* c_, int64_t T) const { read_span(c_, T, 0, T); }
/* The same with a boundary at `cut` (a checkpoint inside the step, RadBatch::ckpt_cut): rows
* [0, cut) are read as a chunk of `cut` rows reads them, then [cut, T) on their own; 0 is
* none. */
void read_pieces(RadCtx* c_, int64_t T, int64_t cut) const {
if (cut <= 0 || cut >= T) { read_span(c_, T, 0, T); return; }
read_span(c_, T, 0, cut);
read_span(c_, T, cut, T);
}
/* Rows [a, b) in pieces of Config::read_rows from `a`; one read where they fit in one. */
void read_span(RadCtx* c_, int64_t T, int64_t a, int64_t b) const {
const int64_t piece = c.read_rows;
if (piece <= 0 || T <= piece) { read(c_, T, 0, T); return; }
for (int64_t r0 = 0; r0 < T; r0 += piece) read(c_, T, r0, T - r0 < piece ? T - r0 : piece);
auto one = [&](int64_t r0, int64_t n) { read(c_, T, r0, n); };
if (piece <= 0 || b - a <= piece) { one(a, b - a); return; }
for (int64_t r0 = a; r0 < b; r0 += piece) one(r0, b - r0 < piece ? b - r0 : piece);
}
};
+139 -62
View File
@@ -259,6 +259,7 @@ 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
@@ -387,6 +388,10 @@ struct MoeFP8 {
* 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
@@ -507,22 +512,27 @@ struct MoeFP8 {
/* 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, 10 rotated int8, 11 the rotated
* computed trellis under one f32 scale a row (an IQR weight an expert); RAD_E_DTYPE
* otherwise. */
* computed trellis under one f32 scale a row (an IQR weight an expert), 12 the codebook's
* six-bit form per 64; RAD_E_DTYPE otherwise. */
static int format_of(const RadEncoding& e);
/* 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[12] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
static constexpr const char* kServed[13] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8",
"fp8a8f32", nullptr, nullptr };
static constexpr const char* kServed8[12] = { nullptr, nullptr, "w4a8i8h", nullptr, nullptr,
"fp8a8f32", nullptr, nullptr, "w6nl64a8h" };
static constexpr const char* kServed8[13] = { nullptr, nullptr, "w4a8i8h", nullptr, nullptr,
"w4nl64a8i8h", "w4nl32a8i8h", nullptr, nullptr,
nullptr, "i8a8h", "i8a8h" };
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,
int ar_in = kArNone, bool ar_out_ = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* A checkpoint inside the step (RadBatch::ckpt_cut): its token on the card, for the routed
* GEMMs' `split` operand, while step() issues a step that is one pass; null otherwise. Each
* expert's rows before the checkpoint are then a run of their own, as a step ending there
* gives them (moe_gemm_iqr's packed map), so they take the same paths. */
mutable const int32_t* split_tok = nullptr;
/* The block over the first `T` rows of its buffers, for passes that need fewer rows than the
* batch (the MTP head's history pass reads its output only at drafting rows). */
void step_rows(RadCtx* c, int64_t T) const;
@@ -556,7 +566,7 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
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),
* and its five-bit form per 64 (w5nl64a8h). */
* and its five- and six-bit forms per 64 (w5nl64a8h, w6nl64a8h). */
if (e.n_planes == 4 && sc && sc->dtype == RAD_F8E4M3) {
const RadEncPlane* s2 = rad_enc_plane(&e, "scale.1");
const RadEncPlane* t = rad_enc_plane(&e, "table");
@@ -569,6 +579,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;
@@ -685,13 +697,14 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
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 || f == 10 || f == 11) ? 1 : 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) ? 1 : 0;
cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 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;
@@ -777,7 +790,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
a8 = w.eff.q8_fed && !c.expert_bf16;
prot.clear();
{
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_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]) {
@@ -799,7 +812,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
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 == 5 || f == 6 || f == 7 || f == 12);
};
fmt[0] = fmt[1] = want;
fenc[0] = fenc[1] = RadEncoding{};
@@ -810,7 +823,12 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
fmt_of(e, enc, fe, nmv);
if (fe[0] == 3 && fe[1] == 3) continue;
for (int i = 0; i < 2; ++i) {
if (family(want) && family(fe[i])) fmt[i] = fe[i];
/* A trellis gate_up reads rotated int8, but the down projection can use the
* W5NL or W6NL 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;
@@ -1036,6 +1054,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
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) {
case 12: return { RAD_U6, "codes,table", RAD_F8E4M3, 1, "scale,scale.1" };
/* 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 11: return { fe.plane[0].dtype, "codes,trellis,trellis.mad", RAD_F32, 1,
@@ -1074,22 +1093,32 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
return RAD_E_INVAL;
}
/* ---- The routed arm's activations (see `a8`). */
if ((c.expert_i8 || c.expert_iqr || fmt[0] >= 10 || fmt[1] >= 10) && !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;
if (!pair || !c.expert_rot || !kServed8[fmt[0]] || !kServed8[fmt[1]] || c.calib ||
c.swiglu_limit > 0) {
const bool down_supported = down_codebook_fp8 ? (w.eff.q && w.eff.s && kServed[fmt[1]])
: kServed8[fmt[1]] != nullptr;
/* A clamped layer: GateQuantFP8 clamps into the bf16 plane, then quantises it into the
* rotated codes. A codebook (W5NL, W6NL) down projection reads rotated E4M3, which no
* clamp writes, so it is served unclamped only. */
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, unclamped, outside "
"calibration; these are %s / %s%s\n", l,
"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");
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;
}
}
@@ -1105,7 +1134,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* experts' encoding or the kernel is not a candidate. */
gu_trellis = fmt[0] == 11;
const char* const edtype[2] = { a8 ? kServed8[fmt[0]] : kServed[fmt[0]],
a8 ? kServed8[fmt[1]] : kServed[fmt[1]] };
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 {
@@ -1302,9 +1331,13 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* 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;
/* Fed int8, `eff` names the rotating int8 quantiser itself (ActFP8::q8_rot). */
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
false, rot && !a8, c.swiglu_limit, c.swiglu_step != 0));
/* Gate_up and down are separate GEMMs. A trellis gate uses int8 input while a codebook (W5NL,
* W6NL) 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),
@@ -1321,13 +1354,13 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
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 ? 0 : 1;
const int cut = a8 && !down_codebook_fp8 ? 0 : 1;
rad_op h = ncls == 4
? 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, {w.eff.cq(), w.eff.cs(), w.sorted, w.eoff}, {w.edn});
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
@@ -1887,6 +1920,9 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
* 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;
/* The routed GEMMs' `split` (split_tok), on a pass that is the whole step. */
const bool split_on = split_tok && r0 == 0 && rows == T;
const RadOperand sp = split_on ? praw(split_tok, RAD_I32, 1) : RAD_NONE;
if (sh_first)
shared_up(c_, T, r0, rows,
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
@@ -1897,48 +1933,71 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
RAD_ISSUE_N(c_, op_gu, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
RAD_WTAB(w_gu[0], ne), brows(w.sorted, rows * k), brows(w.eoff, ne + 1),
brows(w.egu, rows * k));
else if (ncls == 4)
RAD_ISSUE_N(c_, op_gu, rows,
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]),
RAD_WTAB(w_gu[2], n4[2]), RAD_WTAB(w_gus[2], n4[2]),
RAD_WTAB(w_gu[3], n4[3]), RAD_WTAB(w_gus[3], n4[3]),
brows(w.egu, rows * k));
else
RAD_ISSUE_N(c_, op_gu, rows,
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));
else if (ncls == 4) {
/* `split` only where set, so every other step's operand list carries none. */
const RadOperand o_[] = {
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]),
RAD_WTAB(w_gu[2], n4[2]), RAD_WTAB(w_gus[2], n4[2]),
RAD_WTAB(w_gu[3], n4[3]), RAD_WTAB(w_gus[3], n4[3]),
brows(w.egu, rows * k), sp };
rad_issue(c_, op_gu, o_, (int)(sizeof o_ / sizeof *o_) - (split_on ? 0 : 1), rows);
} else {
/* `split` only where set, so every other step's operand list carries none. */
const RadOperand o_[] = {
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), sp };
rad_issue(c_, op_gu, o_, (int)(sizeof o_ / sizeof *o_) - (split_on ? 0 : 1), rows);
}
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 && !(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.cq(), rows * k), brows(w.eff.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]),
RAD_WTAB(w_dn[2], n4[2]), RAD_WTAB(w_dns[2], n4[2]),
RAD_WTAB(w_dn[3], n4[3]), RAD_WTAB(w_dns[3], n4[3]),
brows(w.edn, rows * k));
else
RAD_ISSUE_N(c_, op_dn, rows,
brows(w.eff.cq(), rows * k), brows(w.eff.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),
brows(w.edn, rows * k));
else if (ncls == 4) {
/* `split` only where set, so every other step's operand list carries none. */
const RadOperand o_[] = {
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]),
RAD_WTAB(w_dn[2], n4[2]), RAD_WTAB(w_dns[2], n4[2]),
RAD_WTAB(w_dn[3], n4[3]), RAD_WTAB(w_dns[3], n4[3]),
brows(w.edn, rows * k), sp };
rad_issue(c_, op_dn, o_, (int)(sizeof o_ / sizeof *o_) - (split_on ? 0 : 1), rows);
} else {
/* `split` only where set, so every other step's operand list carries none. */
const RadOperand o_[] = {
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),
brows(w.edn, rows * k), sp };
rad_issue(c_, op_dn, o_, (int)(sizeof o_ / sizeof *o_) - (split_on ? 0 : 1), rows);
}
/* This layer's streamed experts are consumed; the next layer's copies may start. */
(void)rad_expert_prefetch_mark(c_);
/* The protected experts, over the trailing offsets: the quantised down GEMM zeroed their
@@ -1954,7 +2013,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) {
@@ -2075,7 +2134,25 @@ inline void MoeFP8::calib_experts_pass(RadCtx* c_, int64_t slots) const {
}
inline void MoeFP8::step(RadCtx* c_, const RadBatch* batch) const {
step_rows(c_, batch->n_tok);
const int64_t T = batch->n_tok, ck = batch->ckpt_cut;
const bool cut = ck > 0 && ck < T && batch->ckpt_cu;
if (cut && T > c.rows) {
/* A checkpoint inside a step wider than a pass: the passes start again at the checkpoint
* (as HyperConn::read_pieces does), so the rows before it are passed as a chunk ending
* there passes them, and the rows after it as the next chunk would. */
for (int64_t a = 0; a < T; a = ck > a ? ck : T) {
const int64_t b = ck > a ? ck : T;
for (int64_t r0 = a; r0 < b; r0 += c.rows)
pass(c_, T, r0, b - r0 < c.rows ? b - r0 : c.rows);
}
route_report(c_);
return;
}
/* One pass over the whole step: `split` gives the rows before the checkpoint runs of their
* own (split_tok). */
split_tok = cut ? batch->ckpt_cu + 1 : nullptr;
step_rows(c_, T);
split_tok = nullptr;
}
inline void MoeFP8::step_rows(RadCtx* c_, int64_t T) const {
+138 -45
View File
@@ -92,6 +92,7 @@
#include "rad_block_attn_gated_fp8.h"
#include "rad_block_mlp_fp8.h"
#include "rad_block_vit.h"
#include "rad_spechub.h"
namespace rad {
namespace arch {
@@ -116,6 +117,9 @@ inline bool mtp_draft_head_q2(RadBuilder* b, const char* head, const char* lm) {
* (MoeFP8's Config travels inside its Src for this reason). */
template <class Ffn>
struct MtpBlockFP8 {
/* spechub consumes a top-eight law; otherwise only the greedy token is needed. */
static constexpr int proposal_pitch(bool coupled) { return coupled ? 8 : 1; }
struct Wire {
/* [max_tok, n_embd] the trunk's final hidden states for the step just run (the plugin's
* `h`). A pass names the rows it wants through out_ids. */
@@ -128,14 +132,19 @@ struct MtpBlockFP8 {
rad_buf c = 0; /* [max_tok, 2 * n_embd] the two normed halves, fc's input */
rad_buf x = 0; /* [max_tok, n_embd] the head's own residual stream */
rad_buf logits = 0; /* [max_logit_rows, n_vocab] the trunk's, shared */
/* The 2-bit draft head's working set (see op_dlogits), sized at max_logit_rows: only
* drafting rows reach it. */
rad_buf dq = 0; /* [max_logit_rows, n_embd] int8 codes */
rad_buf ds = 0; /* [max_logit_rows, 1] f32, one scale a row */
rad_buf dsum = 0; /* [n_embd/group, mpad] f32, group-major (quant_act_i8's asum) */
rad_buf dlog = 0; /* [max_logit_rows, n_vocab] bf16, the coarse logits */
rad_buf didx = 0; /* [max_logit_rows, 1] i32, the proposed token */
rad_buf dval = 0; /* [max_logit_rows, 1] f32, its logit */
/* The 2-bit projection's scratch: at most one proposal per sequence, including the
* selected final history rows. The unselected history rows need only K/V. */
rad_buf dq = 0; /* [max_seqs, n_embd] int8 codes */
rad_buf ds = 0; /* [max_seqs, 1] f32, one scale a row */
rad_buf dsum = 0; /* [n_embd/group, mpad] f32, group-major (quant_act_i8's asum) */
rad_buf dlog = 0; /* [max_seqs, n_vocab_all] bf16, the coarse logits */
rad_buf didx = 0; /* [max_seqs, proposal_pitch] i32, proposal in column zero */
rad_buf dval = 0; /* [max_seqs, proposal_pitch] f32, shortlist logits */
bool coupled = false;
/* A targeted calib-corpus run may select the virtual MTP layer (n_main) and record the
* draft head's actual input. The trunk's CalibFull is intentionally not involved. */
const char* calib_dir = nullptr;
int64_t calib_tokens = 0;
/* The layer reuses the trunk's working set, which is dead by the time the head runs (a
* second set would be 150 MiB). */
AttnGatedFP8::Wire attn{};
@@ -147,9 +156,6 @@ struct MtpBlockFP8 {
const char* norm = nullptr;
const char* pre_norm_hidden = nullptr;
const char* pre_norm_embedding = nullptr;
/* The checkpoint's lm_head. The trunk maps it as `output.weight`; the draft head is a
* second logical weight over the same tensor, quantised to 2 bits (mtp_draft_head_q2). */
const char* lm = nullptr;
AttnGatedFP8::Src attn{};
typename Ffn::Src mlp{};
};
@@ -172,6 +178,11 @@ struct MtpBlockFP8 {
MediaRows mrows{};
rad_op op_norm = 0, op_dsel = 0, op_dback = 0, op_logits = 0;
rad_op op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
rad_buf couple_draws = 0, couple_state = 0;
rad_op op_couple[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
CalibTap draft_head_calib{};
bool draft_head_calib_on = false;
mutable int64_t draft_head_calib_rows = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup kv,
int64_t rotary_dim, rad_weight tok_embd, rad_weight lm_head, float out_wadd,
@@ -186,7 +197,25 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
const Src& src) {
g = geom; w = wire; layer = l; w_tok = tok_embd; w_lm = lm_head;
rows = g.max_tok;
if (rows <= 0 || !w_tok || !w_lm) return RAD_E_INVAL;
q2 = w.dq != 0;
draft_head_calib_on = w.calib_dir && *w.calib_dir;
if (draft_head_calib_on && (w.calib_tokens <= 0 || g.max_spec != 0 || q2 || w.coupled)) {
std::fprintf(stderr, "radiance: MTP draft-head calibration requires a non-empty corpus "
"and a history-only head (speculation off)\n");
return RAD_E_INVAL;
}
if (w.coupled && (!q2 || g.max_spec < 1 || g.max_spec > RAD_MTP_COUPLE_MAX_ROUNDS)) {
std::fprintf(stderr, "radiance: Qwen35 native MTP coupling requires the U2 draft head and "
"a draft depth in 1..%d\n", RAD_MTP_COUPLE_MAX_ROUNDS);
return RAD_E_UNSUPPORTED;
}
if (w.coupled && !rad_op_declared(b, "mtp_couple_propose")) {
std::fprintf(stderr, "radiance: load the spechub kernels for Qwen35 MTP draft coupling\n");
return RAD_E_UNSUPPORTED;
}
if (rows <= 0 || !w_tok || (!draft_head_calib_on &&
(q2 ? (!w.ds || !w.dsum || !w.dlog || !w.didx || !w.dval) : (!w_lm || !w.logits))))
return RAD_E_INVAL;
/* The normed embedding first, then the normed hidden state (see the header). */
off_e = 0;
@@ -257,17 +286,19 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
* to the front of `x` before the feed-forward, which then runs on those rows only. Goes through
* `hout` (dead between fc's read and the norm's write), since an in-place gather could
* overwrite a row not yet read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
if (!draft_head_calib_on) {
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
}
RAD_ARCH_TRY(mlp.declare(b, nm, g, l, w.mlp, src.mlp));
@@ -277,15 +308,22 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.hout});
if (!op_norm) return RAD_E_INVAL;
if (draft_head_calib_on)
return g.rank == 0 ? draft_head_calib.declare(b, nm, rows, nm.f("mtp.draft_head"),
w.hout, g.n_embd) : RAD_OK;
/* The trunk's lm_head over the head's hidden state, banded at the logits buffer's extent: it
* runs over one row per drafting sequence. */
op_logits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_lm)),
{w.hout}, {w.logits});
/* Only the fallback projects through the target's single lm_head. In particular do not
* declare an unused logits_gemm with a null weight when the target uses width classes. */
if (!q2) {
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(w_lm)),
{w.hout}, {w.logits});
if (!op_logits) return RAD_E_INVAL;
}
/* ---- The 2-bit draft head.
*
@@ -299,20 +337,26 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
* asymmetric (four levels are too few for a symmetric one), so the activation side uses
* `quant_act_i8`'s three-output form, whose per-group row sums subtract the stored zero.
*
* The draft head bypasses the sampler, which reads f32 logits: `row_topk` at R=1 takes the
* argmax on the GEMM's bf16 output and the engine reads the id from `didx`. The trunk's logits
* plane is untouched.
* The head bypasses the sampler's f32 logits. row_topk takes the argmax, or the shortlist
* when coupling is on; the engine reads the proposal from column zero of didx. The target's
* logits plane is untouched.
*/
enum { MTP_W2_GROUP = 128 }; /* libr4d's R4D_GEMM_W2A8_GROUP, and the layout's g128 tag */
/* The plugin declares the working set only when mtp_draft_head_q2 found a 2-bit head (and
* declared its name map). */
q2 = src.lm && w.dq && w.ds && w.dsum && w.dlog && w.didx && w.dval;
if (q2) {
/* Replicated over the whole vocabulary. Without the sampler's cross-rank merge, a sharded
* plane would let each rank propose only its own vocabulary slice. Replication costs 341
* MiB per card at 2 bits and keeps the draft path single-rank. (The stored bytes are also
* tile-major, 16 output rows per packed block, so a shard would have to be whole tiles.) */
const char* dhn = nm.f("mtp.draft_head.weight");
RadEncoding enc{}, expected = rad_enc_affine(RAD_U2, RAD_F16, 1, MTP_W2_GROUP);
rad_enc_add_plane(&expected, "zero", RAD_U8, 1, MTP_W2_GROUP);
if (!weight_enc(b, dhn, &enc) || !rad_enc_equal(&enc, &expected)) {
std::fprintf(stderr, "radiance: %s requires unrotated U2 codes with an F16 scale and "
"U8 zero per group of 128\n", dhn);
return RAD_E_DTYPE;
}
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {g.n_vocab_all, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
w_dhs = decl_view(b, nm.f("mtp.draft_head.scale"), dhn, "scale,zero", RAD_F16,
@@ -321,32 +365,49 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
if (!w_dh || !w_dhs) return RAD_E_INVAL;
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
RAD_INT("n", g.n_embd), RAD_INT("group", MTP_W2_GROUP),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.dq, w.ds, w.dsum});
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
RAD_INT("N", g.n_vocab_all), RAD_INT("K", g.n_embd),
RAD_INT("group", MTP_W2_GROUP), RAD_STR("dtype", "w2a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds, w.dsum}, {w.dlog});
op_dtopk = rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("N", g.n_vocab_all), RAD_INT("R", 1),
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
RAD_INT("N", g.n_vocab_all), RAD_INT("R", proposal_pitch(w.coupled)),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.didx, w.dval});
if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL;
if (w.coupled) {
/* The engine binds these persistent planes by name. The U2 projection is
* replicated over the full vocabulary, so its shortlist already holds global ids. */
couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
{g.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS}, RAD_BUF_PERSIST);
couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
{g.max_spec, g.max_seqs, RAD_MTP_COUPLE_STATE_WORDS}, RAD_BUF_PERSIST);
if (!couple_draws || !couple_state) return RAD_E_INVAL;
for (int rd = 1; rd <= g.max_spec; ++rd) {
op_couple[rd - 1] = rw(b, RAD_OP(b, "mtp_couple_propose",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("round", rd), RAD_INT("max_rounds", g.max_spec)),
RAD_NOWEIGHTS), {w.didx, w.dval, couple_draws}, {w.didx, couple_state});
if (!op_couple[rd - 1]) return RAD_E_INVAL;
}
}
}
/* Keep `hout` live through the head's last op: it is the next round's input, and if only the
* lm_head's first op read it, the planner could give its bytes to later ops (silently lowering
* acceptance). */
{
const rad_op last = q2 ? op_dtopk : op_logits;
const rad_op last = w.coupled ? op_couple[g.max_spec - 1] : q2 ? op_dtopk : op_logits;
if (rad_op_reads(b, last, &w.hout, 1) < 0) return RAD_E_INVAL;
}
return RAD_OK;
@@ -359,6 +420,11 @@ template <class Ffn>
inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const int r = batch->draft_pass;
const bool tap_history = draft_head_calib_on;
if (tap_history && (r >= 0 || batch->n_out != T || batch->n_draft_out != 0)) {
rad_step_fail(c, "MTP draft-head calibration requires every history row and no proposals");
return;
}
/* The history pass gathers; later rounds read the previous pass's output from the same
* buffer. */
@@ -367,6 +433,10 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
"the history pass (RadBatch::draft_out_ids) and has no pass of its own");
return;
}
if (w.coupled && (r == 0 || r > g.max_spec)) {
rad_step_fail(c, "Qwen35 MTP coupled round outside the declared draft depth");
return;
}
if (r < 0 && batch->n_out > 0)
RAD_ISSUE_N(c, op_gather, batch->n_out,
RAD_B(w.src), praw(batch->out_ids, RAD_I32, batch->n_out),
@@ -381,18 +451,19 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE(c, op_fc, brows(w.c, T), RAD_W(w_fc), brows(w.x, T));
/* A history pass with no drafting rows (every prefill chunk but a prompt's last) only needs
* K and V. `n_draft_out` is the same on every rank, so skipped collectives match. */
if (r < 0 && batch->n_draft_out <= 0) {
/* The ordinary history fast path only stores K/V. A selected MTP calibration layer instead
* runs every prompt row through the block so the U2 draft head gets a real, full-rank Gram. */
if (r < 0 && batch->n_draft_out <= 0 && !tap_history) {
attn.store_kv(c, batch);
return;
}
attn.step(c, batch);
/* A history pass with drafting rows continues on those rows alone (round 1): they are moved
* to the front of `x` and the rest of the head runs over them. */
* to the front of `x` and the rest of the head runs over them. Calibration uses all prompt
* rows and returns before the proposal path. */
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.x), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hout, L));
@@ -402,6 +473,22 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
mlp.step_rows(c, L);
RAD_ISSUE(c, op_norm, brows(w.x, L), RAD_W(w_norm), brows(w.hout, L));
if (tap_history) {
/* Only the owner counts and writes. Followers can replay this pass without a host tap. */
if (g.rank == 0) {
if (L > w.calib_tokens - draft_head_calib_rows) {
rad_step_fail(c, "MTP draft-head calibration would count more rows than the corpus holds");
return;
}
draft_head_calib.step(c, w.hout, L, true);
draft_head_calib_rows += L;
if (draft_head_calib_rows == w.calib_tokens &&
!calib_write_to(c, draft_head_calib.h, draft_head_calib.K, draft_head_calib_rows,
"mtp.draft_head", 0, w.calib_dir))
rad_step_fail(c, "failed to write the MTP draft-head RADGRAM2 calibration");
}
return; /* calib-corpus needs the head input, not a speculative proposal */
}
if (q2) {
/* `dsum` is group-major [n_embd/group][ceil(L/16)*16], so it has no row slice; pass it
* whole. */
@@ -413,6 +500,12 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
brows(w.dlog, L), RAD_B(w.dsum), RAD_NONE);
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
RAD_NONE); /* the `pairs` slot, absent: operands are positional */
if (w.coupled) {
const int rd = r < 0 ? 1 : r; /* history already supplied round one's rows */
RAD_ISSUE_N(c, op_couple[rd - 1], L, brows(w.didx, L), brows(w.dval, L),
praw(batch->seq_ids, RAD_I32, batch->n_seq), brows(couple_draws, L),
RAD_B(couple_state));
}
} else {
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
}
+60 -3
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,
@@ -471,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. */
@@ -493,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;
@@ -505,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);
@@ -513,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));
@@ -524,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 */
+33 -2
View File
@@ -501,7 +501,24 @@ inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
* after the step's (`tok` reaches A tokens past the step); the window left behind is the
* step's alone. */
const int64_t A = P > 0 ? ahead_rows(batch) : 0;
if (P > 0)
/* A checkpoint inside the step (RadBatch::ckpt_cut): the rows before it, the window's
* snapshot, then the rest with the ahead rows, each as a chunk of those rows hashes them. */
const int64_t ck = batch->ckpt_cut;
if (P == 1 && D == 0 && ck > 0 && ck < T && batch->ckpt_cu) {
for (int64_t p = 0; p < 2; ++p) {
const int64_t r0 = p == 0 ? 0 : ck, n = p == 0 ? ck : T - ck;
RAD_ISSUE_N(c_, op_ids, n,
praw(batch->token_ids, RAD_I32, T + A), kv_cache(kv_tok, layer_),
praw(batch->ckpt_cu + p, RAD_I32, 2),
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
praw(tk_idx, RAD_I32, 1),
praw(p == 0 ? batch->ctx_lens : batch->positions + r0, RAD_I32, 1),
RAD_NONE,
brows(b_ids, T),
p == 1 && A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
if (p == 0) rad_ckpt_snap(c_, kv_tok, layer_);
}
} else if (P > 0)
RAD_ISSUE_N(c_, op_ids, T,
praw(batch->token_ids, RAD_I32, T + A), kv_cache(kv_tok, layer_),
praw(batch->cu_seqlens + D, RAD_I32, P + 1),
@@ -577,7 +594,21 @@ inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
praw(batch->ctx_lens, RAD_I32, D),
praw(batch->num_accepted, RAD_I32, D),
brows(b_out, DT));
if (P > 0)
const int64_t ck = batch->ckpt_cut;
if (P == 1 && D == 0 && ck > 0 && ck < T && batch->ckpt_cu) {
/* A checkpoint inside the step: the window over the rows before it, its snapshot, then
* the rest (as ids()). */
for (int64_t p = 0; p < 2; ++p) {
RAD_ISSUE_N(c_, op_conv, p == 0 ? ck : T - ck,
brows(b_gvn, T), RAD_W(w_conv), kv_cache(kv_conv, layer_),
praw(batch->ckpt_cu + p, RAD_I32, 2), brows(b_gv, T),
praw(cv_idx, RAD_I32, 1),
praw(p == 0 ? batch->ctx_lens : batch->positions + ck, RAD_I32, 1),
RAD_NONE,
brows(b_out, T));
if (p == 0) rad_ckpt_snap(c_, kv_conv, layer_);
}
} else if (P > 0)
RAD_ISSUE_N(c_, op_conv, T,
brows(b_gvn, T), RAD_W(w_conv), kv_cache(kv_conv, layer_),
praw(batch->cu_seqlens + D, RAD_I32, P + 1), brows(b_gv, T),
+27 -7
View File
@@ -605,20 +605,27 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
{ 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";
/* Fed rotated int8 (ActFP8::q8_rot: a rotated down projection under an int8 routed
* arm), had_quant_act_i8g at the pair's group. */
const char* qn = rot ? "had_quant_act_fp8"
: a.q8_fed ? (a.q8_rot ? "had_quant_act_i8g" : "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_INT("group", a.cg()), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
return op_q ? RAD_OK : 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"))
/* 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")) {
@@ -644,9 +651,11 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
{ 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", a.cg()), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
@@ -1081,6 +1090,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 };
+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 */
+101 -27
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,26 +320,45 @@ 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));
RAD_ISSUE_N(c_, op_tail, 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));
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;
if (S == 1 && batch->ckpt_cut > 0 && batch->ckpt_cut < T && batch->ckpt_cu) {
/* A checkpoint inside the step (RadBatch::ckpt_cut): the ring over the rows before it,
* the snapshot, then the rest -- the ring a chunk ending there leaves, and after both
* the ring the whole step leaves (a row writes its own position's slot). */
const int64_t ck = batch->ckpt_cut;
for (int64_t p = 0; p < 2; ++p) {
RAD_ISSUE_N(c_, op_tail, p == 0 ? ck : T - ck,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
praw(batch->ckpt_cu + p, RAD_I32, 2),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw));
if (p == 0) rad_ckpt_snap(c_, c.kv_tail, layer);
}
} else
RAD_ISSUE_N(c_, op_tail, 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));
return true;
}
@@ -319,13 +369,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 in full, 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: every layer issues its own query, score and select. */
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 +410,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 +422,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
+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 */
+113 -21
View File
@@ -1,6 +1,6 @@
/* gemma4 -- Gemma 4 text decoders (26B-A4B MoE, and the dense members of the family): a bf16
/* gemma4 -- Gemma 4 decoders (26B-A4B MoE, and the dense members of the family): a bf16
* trunk, routed experts bf16, block fp8 or rotated int8 (see FP8 EXPERTS), and the DFlash
* block-diffusion drafter.
* block-diffusion drafter, with the shared Gemma 4 vision tower.
*
* ============================== THE SHAPE (gemma-4-26B-A4B-it) ==============================
*
@@ -91,13 +91,11 @@
*
* ============================== NOT DECLARED ==============================
*
* the vision tower (arch/embgemma2 declares Gemma 4's for an encoder): this plugin serves text;
* a container carrying a tower is served with --mm-max-patches 0 and media parts are refused by
* name;
* an fp8 attention or dense arm: under a tenth of the weight bytes, and the dense arm's 2112 is
* not whole 128-blocks.
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_gemma4_vision.h>
#include <arch/rad_fp8.h>
#include <arch/rad_gemma4_chat.h>
#include <arch/rad_gemma4_dflash.h>
@@ -158,6 +156,7 @@ struct Layer {
rad_op op_anorm = 0, op_qkv = 0, op_qknr = 0, op_lift = 0;
rad_op op_q = 0, op_k = 0, op_vnorm = 0, op_qn = 0, op_kn = 0, op_qrope = 0, op_krope = 0;
rad_op op_store = 0, op_attn = 0, op_o = 0, op_ar_o = 0, op_apost = 0, op_add_a = 0;
rad_op op_bidi = 0, op_ahead = 0;
/* dense arm */
rad_weight w_fnorm = 0, w_gu = 0, w_dn = 0, w_fpost1 = 0;
rad_op op_fnorm = 0, op_gu = 0, op_act = 0, op_dn = 0;
@@ -241,6 +240,8 @@ struct Model {
rad_weight w_tok = 0, w_onorm = 0;
rad_op op_embed = 0, op_embed_ar = 0, op_onorm = 0, op_gather = 0, op_logits = 0, op_cap = 0;
rad_op op_mm = 0;
Gemma4Vision vis{};
enum { MAX_TAPS = Dflash1::MAX_TAPS };
int n_taps = 0;
@@ -569,24 +570,39 @@ 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: 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 the sliding layers cost about 1k tokens of cache each
* instead of the whole context. 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. On a prefix hit the
* full layers' rows come back from the store, and the window 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 it and the match end is recomputed. Where no retained
* checkpoint sits at or below the match, the windowed layers start their cache where the hit
* ended and the prompt is prefilled again. Gemma 3 declares its sliding group the same way.
*
* The drafter does not read the trunk's cache. DFlash keeps its own windowed draft KV,
* rebuilt each context pass from the trunk's residual taps, so a windowed trunk group 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;
@@ -731,6 +747,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", m.escale)),
RAD_WEIGHTS(m.w_tok)),
{}, {m.b_x});
const bool vision = ctx->max_enc_patches > 0 && Gemma4Vision::present(meta);
const char* bidi = meta_text_gets(meta, "use_bidirectional_attention", "");
m.vis.bidirectional = vision && bidi && !std::strcmp(bidi, "vision");
if (vision)
m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{m.b_x}, {m.b_x});
if (W > 1)
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", W), RAD_RANGE("numel", E, T * E),
@@ -781,10 +805,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_NOWEIGHTS),
{buf}, {buf});
};
auto attn = [&](const Kind& k, rad_buf q, rad_buf out, const char* op = "attn_paged") {
auto attn = [&](const Kind& k, rad_buf q, rad_buf out, const char* op = "attn_paged",
int causal = 1) {
return rw(b, RAD_OP(b, op,
RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", k.hd),
RAD_INT("gqa", k.nh / k.nkv), RAD_INT("causal", 1),
RAD_INT("gqa", k.nh / k.nkv), RAD_INT("causal", causal),
RAD_INT("window", k.window), RAD_INT("n_head", k.nh),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
@@ -919,6 +944,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
{m.b_qkv}, {m.b_qs});
y.op_attn = attn(k, m.b_qs, m.b_atts);
}
if (m.vis.bidirectional) {
const bool dense_q = y.op_lift != 0;
const rad_buf q = dense_q ? m.b_qs : m.b_qkv;
y.op_bidi = attn(k, q, m.b_atts, dense_q ? "attn_paged" : "attn_paged_qrow", 0);
if (!y.op_bidi) {
fprintf(stderr, "radiance: gemma4: no sliding attention kernel for "
"bidirectional image spans\n");
return RAD_E_UNSUPPORTED;
}
const char* ahead = dense_q ? "attn_paged_ahead" : "attn_paged_qrow_ahead";
if (T > k.window && rad_op_declared(b, ahead))
y.op_ahead = attn(k, q, m.b_atts, ahead, 0);
}
y.op_store = kv_store(k, m.b_qkv, m.b_qkv);
y.op_o = gemm(T, E, k.q(), y.w_o, m.b_atts, m.b_o);
} else {
@@ -1346,9 +1384,29 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
"output draws from a sharper distribution", m.softcap, m.softcap);
}
/* The drafter last: declaration order is the buffer planner's liveness. */
/* The drafter follows the trunk: declaration order is the buffer planner's liveness. */
if (m.n_taps > 0)
RAD_ARCH_TRY(declare_dflash(b, meta, ctx, m, (int)m.n_layer));
if (vision) {
/* Reserve the draft groups even when speculation is disabled. */
const int64_t draft_layers = dflash_kind(meta) == 1
? rad_meta_geti(meta, "draft.num_hidden_layers", 0) : 0;
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, E, (int)(m.n_layer + draft_layers),
"model.", "gemma4"));
/* A declaration without a weight source is valid for graph tools and tests. When
* the trunk is backed by weights, check the tower's entry and exit before loading. */
RadEncoding enc{};
if (rad_weight_encoding(b, nm.f("token_embd.weight"), &enc, nullptr, nullptr) == RAD_OK) {
for (const char* name : { "v.patch.weight", "v.embed.weight" }) {
if (rad_weight_encoding(b, nm.f("%s", name), &enc, nullptr, nullptr) != RAD_E_NOTFOUND)
continue;
fprintf(stderr, "radiance: gemma4: vision is enabled but the model is missing "
"vision weight '%s'; use --mm-max-patches 0 for text-only serving\n",
name);
return RAD_E_NOTFOUND;
}
}
}
int nfull = 0;
for (int f : full) nfull += f;
@@ -1518,7 +1576,8 @@ static void attend(RadCtx* c, const Model& m, const Layer& y, size_t li, const R
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 bt = praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0);
const int64_t pitch = kvb ? kvb->block_table_pitch : 0;
const RadOperand bt = praw2(table, RAD_I32, batch->n_seq, pitch);
const RadOperand su = praw(used, RAD_I32, batch->n_seq);
if (!y.full) {
@@ -1530,6 +1589,24 @@ static void attend(RadCtx* c, const Model& m, const Layer& y, size_t li, const R
RAD_ISSUE_N(c, y.op_attn, batch->max_q_len,
y.op_lift ? brows(m.b_qs, T) : bcol(m.b_qkv, 0, qd, T),
kv_cache(k.kv, (int)li), bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_atts, T));
/* Recompute only the image rows, with the cache ending at the span's last row.
* The window still limits lookback; for a long span it must not limit lookahead. */
for (int64_t i = 0; y.op_bidi && i < batch->n_bidi; ++i) {
const int64_t first = batch->bidi_row[i], n = batch->bidi_n[i], s = batch->bidi_seq[i];
const rad_op op = n > k.window ? y.op_ahead : y.op_bidi;
if (!op) {
rad_step_fail(c, "gemma4: an image span exceeds the sliding window and needs "
"a paged attention kernel with unrestricted lookahead");
return;
}
RAD_ISSUE_N(c, op, n,
y.op_lift ? brow_slice(m.b_qs, first, n, qd)
: bcol_at(m.b_qkv, first, qd + 2 * kvd, 0, qd, n),
kv_cache(k.kv, (int)li),
praw2(table ? table + s * pitch : nullptr, RAD_I32, 1, pitch),
praw(batch->bidi_used + i, RAD_I32, 1),
RAD_NONE, RAD_NONE, RAD_NONE, brow_slice(m.b_atts, first, n, qd));
}
} else {
RAD_ISSUE_N(c, y.op_vnorm, T * k.nkv, brows(m.b_kf, T), RAD_NONE, brows(m.b_vf, T));
RAD_ISSUE_N(c, y.op_qn, T * k.nh, brows(m.b_qf, T), RAD_W(y.w_qn), brows(m.b_qf, T));
@@ -1808,13 +1885,24 @@ static void step(RadCtx* c, const RadBatch* batch) {
return;
}
if (batch->enc) {
rad_step_fail(c, "gemma4 declares no encoder; serve this container with --mm-max-patches 0");
if (batch->enc & ~(RAD_MM_IMAGE | RAD_MM_VIDEO))
rad_step_fail(c, "gemma4: unsupported encoder modality");
else if (!m.vis.on)
rad_step_fail(c, "gemma4: no vision tower was declared; image and video encoding "
"require vision weights and --mm-max-patches greater than 0");
else
m.vis.step(c, batch);
return;
}
const int64_t T = batch->n_tok, E = m.E;
if (T <= 0) return;
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
/* The batch supplies image rows on rank 0 and zeros on the other ranks. */
if (m.op_mm && batch->n_mm_rows > 0)
RAD_ISSUE_N(c, m.op_mm, batch->n_mm_rows,
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, E),
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, T));
if (m.op_embed_ar)
RAD_ISSUE_N(c, m.op_embed_ar, T * E, brows(m.b_x, T), RAD_NONE);
@@ -1842,6 +1930,10 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
(void)dflash_probe(meta, out);
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;
}
return RAD_OK;
}
@@ -1857,7 +1949,7 @@ static const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_cha
/* 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 "
"Gemma 4 decoders (26B-A4B MoE, dense 31B) with vision, bf16: sliding and full attention "
"with proportional rope and K = V, a dense and a routed feed-forward side by side, "
"and z-lab's DFlash block-diffusion drafter")
RAD_ARCH_PROBE(gemma4)
+1 -1
View File
@@ -2269,7 +2269,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
(long long)dg.n_layer, (long long)m.n_main, (long long)dg.n_head_all,
(long long)dg.n_head_kv_all, (long long)dg.head_dim, (long long)dg.n_ff_all,
dc.causal ? "causal" : "non-causal", (long long)dc.window, m.n_taps,
(long long)dc.steps(), m.df2.head_i8 ? "8-bit" : "2-bit");
(long long)dc.steps(), m.df2.head_i8 ? "8-bit" : m.df2.head_bf16 ? "bf16" : "2-bit");
return RAD_OK;
}
+28 -17
View File
@@ -67,7 +67,10 @@ using namespace rad::arch;
/* ================================================================== the model's constants */
/* The largest image: 2048 x 2048 pixels, 16384 latent tokens. 1024 x 1024 is the default. */
enum { kMaxImageTokens = 16384 };
static constexpr int64_t kMaxImageTokens = 16384;
static int64_t image_tokens(int64_t pixels) {
return pixels > 0 ? std::min<int64_t>(kMaxImageTokens, pixels / 256) : kMaxImageTokens;
}
/* The longest conditioning in rows: the pipeline's max_sequence_length. The prompt the language
* model reads is that plus the template's system turn, at most kTeRows. */
enum { kCondRows = 512, kTeRows = kCondRows + 64 };
@@ -155,6 +158,7 @@ enum : int {
struct Model {
Names nm{""};
int64_t max_image_tokens = kMaxImageTokens;
Geom gt{}, gf{}, gd{}; /* the language model's, the text fusion's and the DiT's geometry */
bool turbo = false;
std::string te_pre; /* the language model's tensor prefix */
@@ -752,7 +756,9 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
const int64_t C = m.C, L = g.n_layer;
const double eps = g.eps;
const int gx = kGrpDit;
const int64_t NI = std::min<int64_t>(T, 2 * (int64_t)kMaxImageTokens); /* image rows a pass */
/* Image rows a pass: a denoising branch an entry (one for an unguided image, two under
* classifier-free guidance), as many entries as max-num-seqs allows, within the step's rows. */
const int64_t NI = g.max_seqs > T / m.max_image_tokens ? T : g.max_seqs * m.max_image_tokens;
/* ---- the timestep: [cos | sin] of 1000 bf16(t) over 256, linear, gelu_tanh, linear (temb);
* the shared modulation from gelu_tanh(temb), then each block's table added (table_add), and
@@ -817,13 +823,13 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D });
m.op_randn = rw(b, RAD_OP(b, "randn_lanes",
RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C),
RAD_INT("stride", (int64_t)kMaxImageTokens),
RAD_INT("stride", (int64_t)m.max_image_tokens),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.b_state }, { m.b_state });
m.op_lgather = rw(b, RAD_OP(b, "lane_gather",
RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C),
RAD_INT("stride", (int64_t)kMaxImageTokens),
RAD_INT("stride", (int64_t)m.max_image_tokens),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.b_state }, { m.b_lat });
@@ -997,7 +1003,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
m.b_fz, m.b_v, &m.w_pout, &m.b_pout, RAD_ACCESS_PER_TOKEN, gx);
m.op_euler = rw(b, RAD_OP(b, "flow_euler",
RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C),
RAD_INT("stride", (int64_t)kMaxImageTokens),
RAD_INT("stride", (int64_t)m.max_image_tokens),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.b_v, m.b_state, m.b_prev }, { m.b_state, m.b_prev });
@@ -1016,7 +1022,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
v.scope = "vdec";
v.down = false;
v.first_group = kGrpVaeDec;
v.base_px = (int64_t)kMaxImageTokens * 4;
v.base_px = (int64_t)m.max_image_tokens * 4;
v.form = VAE_CONV_CAUSAL;
const int64_t base = rad_meta_geti(meta, "vae.base_dim", 96);
const int64_t zd = rad_meta_geti(meta, "vae.z_dim", 16);
@@ -1043,7 +1049,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
m.ones += k ? " 1" : "1";
m.zeros += k ? " 0" : "0";
}
const int64_t NT = kMaxImageTokens;
const int64_t NT = m.max_image_tokens;
m.b_dl = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { NT, 4 * zd });
m.b_dl2 = decl_b(b, nm.f("vdec.lat2"), RAD_BF16, { NT, 4 * zd });
m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { 4 * NT, zd });
@@ -1108,7 +1114,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "vae.decoder.conv_out");
if (!m.dec_out.buf) return RAD_E_INVAL;
RAD_ARCH_TRY(v.attn_reads(m.b_cu4));
const int64_t px = (int64_t)kMaxImageTokens * 256;
const int64_t px = (int64_t)m.max_image_tokens * 256;
m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST);
m.op_rgb = rw(b, RAD_OP(b, "to_rgba8",
RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3),
@@ -1126,7 +1132,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
* unpacked latent, two rows a token row, eight pixels a latent row. */
const int world = m.gt.world;
if (world > 1) {
const int64_t H0 = 4 * (int64_t)kMaxImageTokens;
const int64_t H0 = 4 * (int64_t)m.max_image_tokens;
const int64_t bpx = (H0 / world + H0 / (2 * v.halo) + 1) * 64;
m.b_rgbf = decl_b(b, nm.f("vdec.bands"), RAD_BF16, { world * bpx, 3 });
m.op_bands = rw(b, RAD_OP(b, "all_gather",
@@ -1146,12 +1152,14 @@ 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 (!b || !meta || !ctx || ctx->max_seqs <= 0) 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);
m.max_image_tokens = image_tokens(ctx->gen_max_pixels);
if (m.max_image_tokens == 0) return RAD_E_INVAL;
RAD_ARCH_TRY(check_format(meta));
RAD_ARCH_TRY(geom_from(m.gt, meta, ctx, "bf16", RAD_BF16));
Names& nm = m.nm;
@@ -1219,7 +1227,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- the per-image state, the conditioning store, and in issue order the language model,
* the text fusion, the DiT and the decoder */
const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens;
const int64_t lane_rows = (int64_t)kMaxLanes * m.max_image_tokens;
m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST);
m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST);
m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16,
@@ -1247,11 +1255,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
d.size_multiple = 16;
d.pixel_channels = 3;
d.slot_rows = 1;
d.max_tokens = kMaxImageTokens;
d.max_tokens = m.max_image_tokens;
d.max_refs = 0;
d.ref_area = 1;
d.default_width = 1024;
d.default_height = 1024;
const int64_t side = (int64_t)std::sqrt(std::min<int64_t>(m.max_image_tokens, 4096)) * 16;
d.default_width = side;
d.default_height = side;
/* Raw: 28 steps on the resolution-shifted schedule, guidance 4.5 in the card's terms.
* Turbo: 8 steps at a fixed mu of 1.15 (base and max shift equal), no guidance. */
d.default_steps = m.turbo ? 8 : 28;
@@ -1405,7 +1414,7 @@ static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) {
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1);
const RadOperand lanes = praw(G->lane, RAD_I32, S);
const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens;
const int64_t LR = (int64_t)kMaxLanes * m.max_image_tokens;
/* ---- modulation: the timestep MLP, the shared projection, each block's table, the final */
RAD_ISSUE_N(c, m.op_temb, S, praw(G->sigma, RAD_F32, S), brows(m.b_tproj, S));
@@ -1506,7 +1515,7 @@ static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) {
const RadGenBatch* G = batch->gen_b;
const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W, C = m.C;
const rad_buf src = G->dec_preview ? m.b_prev : m.b_state;
RAD_ISSUE_N(c, m.op_dinv, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C),
RAD_ISSUE_N(c, m.op_dinv, n, brow_slice(src, (int64_t)G->dec_lane * m.max_image_tokens, n, C),
brows(m.b_dl, n));
RAD_ISSUE_N(c, m.op_dadd, n, brows(m.b_dl, n), brows(m.b_dl2, n));
const int64_t zd = C / 4, H0 = 2 * H, W0 = 2 * W;
@@ -1556,7 +1565,9 @@ static void step(RadCtx* c, const RadBatch* batch) {
/* The rows a pass carries: one image at the largest size with guidance, its text both ways. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kCondRows);
const int64_t tokens = image_tokens(out->gen_max_pixels);
if (tokens == 0) return RAD_E_INVAL;
out->gen_rows = 2 * (tokens + kCondRows);
out->gen_patches = 0;
return RAD_OK;
}
+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)
+786
View File
@@ -0,0 +1,786 @@
/* 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;
/* The attention rows are keyed on a whole number of queries a KV head. */
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv != 0) {
fprintf(stderr, "radiance: lfm3: %lld attention heads over %lld key/value heads is not a "
"whole number of queries a key/value head\n",
(long long)g.n_head, (long long)g.n_head_kv);
return RAD_E_UNSUPPORTED;
}
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
+81 -41
View File
@@ -187,28 +187,35 @@ static int64_t tiles_of(int64_t lat_h, int64_t lat_w) {
}
/* Whether a frame of w x h pixels is one this model makes. */
static bool size_ok(int64_t w, int64_t h) {
static int64_t video_area(int64_t requested) {
return requested > 0 ? std::min<int64_t>(requested, kMaxArea) : kMaxArea;
}
static bool size_ok(int64_t w, int64_t h, int64_t area) {
return w % kMult == 0 && h % kMult == 0 && w >= kMinSide && h >= kMinSide &&
w * h <= kMaxArea && std::max(w, h) <= kMaxAspect * std::min(w, h);
w * h <= area && std::max(w, h) <= kMaxAspect * std::min(w, h);
}
/* The most tiles a decode pass carries, over every size. */
static int64_t max_tiles() {
static int64_t max_tiles(int64_t area) {
int64_t best = 0;
for (int64_t w = kMinSide; w <= (int64_t)kMaxArea / kMinSide; w += kMult)
for (int64_t h = kMinSide; h * w <= kMaxArea; h += kMult)
if (size_ok(w, h)) best = std::max(best, tiles_of(h / kScale, w / kScale));
for (int64_t w = kMinSide; w <= area / kMinSide; w += kMult)
for (int64_t h = kMinSide; h * w <= area; h += kMult)
if (size_ok(w, h, area)) best = std::max(best, tiles_of(h / kScale, w / kScale));
return best;
}
static int64_t max_lat_frames() { return (int64_t)kLpc * kMaxChunks + kLtail; }
static int64_t max_patches() { return (int64_t)kMaxArea / (kScale * kPatch * kScale * kPatch); }
static int64_t max_video_rows() { return max_lat_frames() * max_patches(); }
static int64_t max_audio() {
const int64_t frames = (int64_t)kFpc * kMaxChunks + kFtail;
static int64_t max_lat_frames(int64_t chunks = kMaxChunks) { return kLpc * chunks + kLtail; }
static int64_t max_video_rows(int64_t area, int64_t chunks = kMaxChunks) {
return max_lat_frames(chunks) * (area / (kMult * kMult));
}
static int64_t max_audio(int64_t chunks = kMaxChunks) {
const int64_t frames = (int64_t)kFpc * chunks + kFtail;
return (frames * kAudioRate + kFps / 2) / kFps + 1;
}
static int64_t max_step_rows() { return kMaxText + kAudioCh * max_audio() + max_video_rows(); }
static int64_t max_step_rows(int64_t area, int64_t chunks = kMaxChunks) {
return kMaxText + kAudioCh * max_audio(chunks) + max_video_rows(area, chunks);
}
/* Video sparse attention's video tiles over a grid of F x ph x pw patches, and the ones a video
* query keeps at `sparsity`: ceil((1 - sparsity) V) in f64, at least one. */
@@ -225,7 +232,7 @@ static void vsa_bounds(double sparsity, int64_t* tiles, int64_t* keep) {
int64_t best = 0;
for (int64_t w = kMinSide; w <= (int64_t)kMaxArea / kMinSide; w += kMult)
for (int64_t h = kMinSide; h * w <= kMaxArea; h += kMult)
if (size_ok(w, h))
if (size_ok(w, h, kMaxArea))
best = std::max(best, vsa_video_tiles(max_lat_frames(), h / (kScale * kPatch),
w / (kScale * kPatch)));
const int64_t prefix = ((int64_t)kMaxText + kVsaRows - 1) / kVsaRows +
@@ -387,7 +394,9 @@ struct Model {
int64_t D = 0, S = kMaxSteps;
int64_t W = 1, Ws = 0; /* ranks, and a rank's share of a modality's six vectors */
int64_t maxV = 0, maxA = 0; /* a lane's video and soundtrack latent rows */
int64_t max_area = kMaxArea;
int64_t tiles = 0, tpr = 0; /* the most tiles a decode carries, and a rank's share of them */
int64_t enc_tiles = 0; /* reference images have their own bounds */
/* ---- the text encoder */
rad_weight w_tok = 0;
@@ -1708,7 +1717,7 @@ static int declare_video(RadBuilder* b, const RadModelMeta* meta, Model& m) {
}
m.v_mean = join_list(mean);
m.v_std = join_list(sd);
const int64_t maxhw = (int64_t)kMaxArea / (kScale * kScale);
const int64_t maxhw = m.max_area / (kScale * kScale);
const int64_t vox = (int64_t)kDecLat * maxhw;
const int64_t R = m.tpr * kPeriod; /* this rank's tile rows */
const int64_t RA = (int64_t)m.W * R; /* every rank's, gathered */
@@ -1891,11 +1900,11 @@ static int declare_video(RadBuilder* b, const RadModelMeta* meta, Model& m) {
if (!m.op_vgather) return RAD_E_INVAL;
}
const int64_t fmax = (int64_t)kFpc + kFtail;
m.b_prev = decl_b(b, nm.f("lane.prev"), RAD_BF16, { (int64_t)kMaxLanes * kFtail * kMaxArea, 3 },
m.b_prev = decl_b(b, nm.f("lane.prev"), RAD_BF16, { (int64_t)kMaxLanes * kFtail * m.max_area, 3 },
RAD_BUF_PERSIST);
m.b_frames = decl_b(b, nm.f("frames_out"), RAD_U8, { fmax * kMaxArea, 3 }, RAD_BUF_PERSIST);
m.b_frames = decl_b(b, nm.f("frames_out"), RAD_U8, { fmax * m.max_area, 3 }, RAD_BUF_PERSIST);
m.op_stitch = rw(b, RAD_OP(b, "vtile_stitch",
RAD_PARAMS(RAD_RANGE("M", 1, fmax * kMaxArea), RAD_INT("tile", kTile),
RAD_PARAMS(RAD_RANGE("M", 1, fmax * m.max_area), RAD_INT("tile", kTile),
RAD_INT("overlap", kOverlap), RAD_INT("scale", kScale),
RAD_INT("pt", 4), RAD_INT("skip", 3), RAD_INT("keep", kFpc),
RAD_INT("blend", kFtail), RAD_INT("period", kPeriod),
@@ -1955,7 +1964,7 @@ static int declare_ups(RadBuilder* b, const RadModelMeta* meta, Model& m) {
/* The most voxels a frame of latents and a video hold, before or after: the small size is
* never larger than the full one. */
const int64_t V = max_lat_frames() * ((int64_t)kMaxArea / (kScale * kScale));
const int64_t V = max_lat_frames() * (m.max_area / (kScale * kScale));
const int64_t P = m.maxV;
const int acc = RAD_ACCESS_PER_TOKEN;
auto wt = [&](const char* name, uint32_t dt, std::initializer_list<int64_t> shape) {
@@ -2346,7 +2355,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
@@ -2354,12 +2367,17 @@ 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.enc_tiles = max_tiles(kMaxArea);
m.b_tplan = decl_b(b, nm.f("venc.tplan"), RAD_I32, { m.enc_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.enc_tiles * (int64_t)kEncMaxSide * kEncMaxSide, 3 });
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.enc_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
@@ -2396,7 +2414,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
@@ -2404,7 +2423,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),
@@ -2508,13 +2528,13 @@ static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) {
/* The tiled encode's ops, declared last: b_vtile and b_eqt then live across the whole trunk,
* which the tiled pass runs once a tile, so no trunk buffer shares their bytes. */
m.op_vt_plan = rw(b, RAD_OP(b, "vtile_plan",
RAD_PARAMS(RAD_RANGE("M", 1, m.tiles), RAD_INT("tile", kTile),
RAD_PARAMS(RAD_RANGE("M", 1, m.enc_tiles), RAD_INT("tile", kTile),
RAD_INT("overlap", kOverlap),
RAD_INT("ratio", kVaeRatio)),
RAD_NOWEIGHTS),
{}, { m.b_tplan });
m.op_vt_crop = rw(b, RAD_OP(b, "vtile_crop",
RAD_PARAMS(RAD_RANGE("M", 1, m.tiles * (int64_t)kEncMaxSide * kEncMaxSide),
RAD_PARAMS(RAD_RANGE("M", 1, m.enc_tiles * (int64_t)kEncMaxSide * kEncMaxSide),
RAD_INT("tile", kTile), RAD_INT("overlap", kOverlap),
RAD_INT("ratio", kVaeRatio), RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
@@ -2885,6 +2905,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_INVAL;
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.max_area = video_area(ctx->gen_max_pixels);
if (m.max_area < kMinSide * kMinSide) {
fprintf(stderr, "radiance: minimaxh3: the video pixel limit must allow a %dx%d frame\n",
kMinSide, kMinSide);
return RAD_E_INVAL;
}
m.nm = Names(ctx->scope);
Names& nm = m.nm;
RAD_ARCH_TRY(check_format(meta));
@@ -2972,21 +2998,29 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
m.gr = gd;
m.gr.max_tok = kMaxText;
m.maxV = max_video_rows();
m.maxV = max_video_rows(m.max_area);
m.maxA = kAudioCh * max_audio();
m.tiles = max_tiles();
m.tiles = max_tiles(m.max_area);
m.tpr = (m.tiles + m.W - 1) / m.W;
if (gd.n_layer >= kGrpAda - kGrpDit - 1 || gd.n_layer > kGrpVae - kGrpAda ||
m.gt.n_layer >= kGrpRefiner) {
fprintf(stderr, "radiance: minimaxh3: the networks are too deep for the weight groups\n");
return RAD_E_UNSUPPORTED;
}
if (ctx->max_tok < max_step_rows() || ctx->max_tok < m.tpr * kPeriod) {
fprintf(stderr, "radiance: minimaxh3: a pass carries %lld rows; the longest video's step "
"needs %lld and its decode %lld\n", (long long)ctx->max_tok,
(long long)max_step_rows(), (long long)(m.tpr * kPeriod));
/* The driver checks the full decode row count, even though each rank issues only its share. */
const int64_t decode_max_rows = m.tiles * kPeriod;
const int64_t min_step_rows = max_step_rows(m.max_area, kMinChunks);
if (ctx->max_tok < min_step_rows || ctx->max_tok < decode_max_rows) {
fprintf(stderr, "radiance: minimaxh3: a pass carries %lld rows; the shortest video's step "
"needs up to %lld and a decode up to %lld\n", (long long)ctx->max_tok,
(long long)min_step_rows, (long long)decode_max_rows);
return RAD_E_INVAL;
}
/* An explicit row cap can shorten the video while keeping enough room for every canvas.
* Keep the original bounds for codecs and reference buffers. References consume the
* remaining step rows and the driver checks the complete packed sequence per request. */
int64_t max_chunks = kMaxChunks;
while (max_step_rows(m.max_area, max_chunks) > ctx->max_tok) --max_chunks;
/* The vision tower, when the checkpoint or container has its weights: every MiniMax-H3 config
* names one. */
@@ -3036,16 +3070,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
d.latents_tail = kLtail;
d.dec_latents = kDecLat;
d.min_chunks = kMinChunks;
d.max_chunks = kMaxChunks;
d.max_chunks = max_chunks;
d.latent_scale = kScale;
d.latent_channels = kC;
d.patch = kPatch;
d.size_multiple = kMult;
d.min_side = kMinSide;
d.max_area = kMaxArea;
d.max_area = m.max_area;
d.max_aspect = kMaxAspect;
d.default_width = kDefW;
d.default_height = kDefH;
const double shrink = std::sqrt(static_cast<double>(m.max_area) / static_cast<double>(kMaxArea));
const int64_t scaled_h = static_cast<int64_t>(static_cast<double>(kDefH) * shrink);
const int64_t scaled_w = static_cast<int64_t>(static_cast<double>(kDefW) * shrink);
d.default_height = std::max<int64_t>(kMinSide, (scaled_h / kMult) * kMult);
const int64_t fit_w = std::min(scaled_w, m.max_area / d.default_height);
d.default_width = std::max<int64_t>(kMinSide, (fit_w / kMult) * kMult);
d.default_chunks = kDefChunks;
d.sample_rate = kRate;
d.audio_rate = kAudioRate;
@@ -3645,7 +3683,7 @@ static void step_video(RadCtx* c, const RadBatch* batch, const Model& m) {
const int64_t hp = lh * kScale, wp = lw * kScale, n = (int64_t)V->n_frames_out * hp * wp;
RAD_ISSUE_N(c, m.op_stitch, n, brows(pix, nt * kPeriod),
praw(V->geom_d + RAD_VGEOM_CHUNK_FRAMES, RAD_I32, 5),
brow_slice(m.b_prev, lane * kFtail * (int64_t)kMaxArea, (int64_t)kFtail * hp * wp, 3),
brow_slice(m.b_prev, lane * kFtail * m.max_area, (int64_t)kFtail * hp * wp, 3),
brows(m.b_frames, n));
}
@@ -3728,7 +3766,7 @@ static int64_t step_venc_tiled(RadCtx* c, const RadVideoGenBatch* V, const Model
const int64_t lat_h = H / kVaeRatio, lat_w = W / kVaeRatio;
const std::vector<int64_t> ty = tile_starts(lat_h), tx = tile_starts(lat_w);
const int64_t nh = (int64_t)ty.size(), nw = (int64_t)tx.size(), nt = nh * nw;
if (nt > m.tiles) {
if (nt > m.enc_tiles) {
rad_step_fail(c, "minimaxh3: a Vencode pass whose picture splits into more tiles than "
"the encoder declares room for");
return row0;
@@ -4066,7 +4104,9 @@ static void step(RadCtx* c, const RadBatch* batch) {
* the most tiles. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->gen_rows = std::max<int64_t>(max_step_rows(), max_tiles() * kPeriod);
const int64_t area = video_area(out->gen_max_pixels);
if (area < kMinSide * kMinSide) return RAD_E_INVAL;
out->gen_rows = std::max<int64_t>(max_step_rows(area), max_tiles(area) * kPeriod);
out->gen_video = 1;
return RAD_OK;
}
+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)
+199
View File
@@ -0,0 +1,199 @@
/* 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");
}
/* The drafter's weight prefetch window: 12 MiB, the value measured for the Qwen3.8 DFlash2
* drafter 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
+93 -28
View File
@@ -217,7 +217,8 @@ struct Mamba {
if (!op_conv || !op_prefill || !op_verify || !op_gate || !op_norm || !op_gain)
return RAD_E_INVAL;
const char* on = nm.f("blk.%d.ssm_out", l);
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.out_proj.weight", pre) }));
if (!output.mapped)
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.out_proj.weight", pre) }));
if (!output.reads_x) RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, W));
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, W, RAD_SHARD_COL, grp,
{ nm.ckpt("%s.out_proj.weight", pre) }, w.core_out, w.out));
@@ -295,8 +296,10 @@ struct LatentMoe {
RAD_ARCH_TRY(fc1.declare(b, nm, g, nm.f("blk.%d.ffn_latent_in", l), s.latent, g.n_embd,
RAD_SHARD_NONE, grp,
{ nm.ckpt("%s.fc1_latent_proj.weight", pre) }, w.h, w.lat.x));
/* The routed arm reads the latent's codes unless its experts are bf16. */
if (!ms.cfg.expert_bf16) RAD_ARCH_TRY(lat_in.declare(b, g, w.lat, s.latent));
/* The routed arm reads the latent's E4M3 codes unless its experts are bf16 or rotated
* (rotated ones read the int8 copy MoeFP8 writes, `hr`). */
if (!ms.cfg.expert_bf16 && !ms.cfg.expert_rot)
RAD_ARCH_TRY(lat_in.declare(b, g, w.lat, s.latent));
Geom ge = g;
ge.n_embd = s.latent;
ge.n_ff_all = s.ff[(size_t)l];
@@ -318,6 +321,9 @@ struct LatentMoe {
RAD_SHARD_ROW, grp,
{ nm.ckpt("%s.shared_experts.up_proj.weight", pre) }, w.h,
w.sup, 0, {}, sh_lo, sh_hi));
/* A down projection that reads the bf16 plane (an int8 one quantises it itself) takes
* the product alone, without codes no op would read. */
sh_act.silu_only = sh_down.reads_x;
RAD_ARCH_TRY(sh_act.declare(b, g, w.sup, w.sff, sh_w, "relu2", 0, true, false));
RAD_ARCH_TRY(sh_down.declare(b, nm, g, dn, g.n_embd, sh_w, RAD_SHARD_COL, grp,
{ nm.ckpt("%s.shared_experts.down_proj.weight", pre) },
@@ -367,6 +373,11 @@ struct Model {
rad_kvgroup kv_attn = 0, kv_state = 0, kv_conv = 0;
rad_buf x = 0, y = 0, final_hidden = 0, logit_input = 0, logits = 0;
ActFP8 act{};
/* An int8 trunk (i8 codes with a bf16 scale a [1 x 128], or IQ8R's 256): every activation a
* trunk linear reads declares the int8 pair too, which that linear's own quant_act_i8g writes
* from the bf16 plane. From the first Mamba block's out projection, probed in declare(). */
bool trunk_i8 = false;
int64_t trunk_g8 = RAD_FP8_BLOCK;
Mamba::Wire mw{};
AttnFP8::Wire aw{};
LatentMoe::Wire ew{};
@@ -513,7 +524,10 @@ static int buffers(RadBuilder* b, Model& m) {
m.x = bf("residual", { T, E });
m.y = bf("mixer_delta", { T, E });
m.act.x = bf("normed", { T, E });
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E));
/* An int8 trunk's linears read the int8 pair, each quantising the bf16 plane itself, so the
* activations below declare no E4M3 pair. The block norms still write E4M3 codes here, which
* no linear of an int8 trunk reads: NormQuantFP8 has no unrotated int8 form. */
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E, 0, m.trunk_i8, true, m.trunk_g8));
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, E }, RAD_BUF_PERSIST);
m.logit_input = bf("logit_input", { g.max_logit_rows, E });
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
@@ -528,7 +542,8 @@ static int buffers(RadBuilder* b, Model& m) {
mw.dt = bf("ssm_dt", { T, H });
mw.y = bf("ssm_y", { T, W });
mw.core_out.x = bf("ssm_out", { T, W });
RAD_ARCH_TRY(mw.core_out.declare_qs(b, nm, g, "ssm_out", W));
RAD_ARCH_TRY(mw.core_out.declare_qs(b, nm, g, "ssm_out", W, 0, m.trunk_i8, !m.trunk_i8,
m.trunk_g8));
auto& aw = m.aw;
aw.x = m.x;
@@ -536,7 +551,8 @@ static int buffers(RadBuilder* b, Model& m) {
aw.qkv = bf("attn_qkv", { T, g.qkv_dim() });
aw.q = bf("attn_q", { T, g.q_dim() });
aw.attn.x = bf("attn_out", { T, g.q_dim() });
RAD_ARCH_TRY(aw.attn.declare_qs(b, nm, g, "attn_out", g.q_dim()));
RAD_ARCH_TRY(aw.attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.trunk_i8, !m.trunk_i8,
m.trunk_g8));
return RAD_OK;
}
@@ -552,13 +568,17 @@ static int moe_buffers(RadBuilder* b, Model& m, const std::vector<MoeFP8::Src>&
};
auto& ew = m.ew;
ew.h = m.act;
/* The latent keeps its E4M3 pair on an int8 trunk too: MoeFP8 takes it as a prepared input
* and checks that it carries codes, also where rotated experts read their own copy `hr`
* and lat_in writes none. */
ew.lat.x = bf("latent", { T, L });
RAD_ARCH_TRY(ew.lat.declare_qs(b, nm, g, "latent", L));
RAD_ARCH_TRY(ew.lat.declare_qs(b, nm, g, "latent", L, 0, m.trunk_i8, true, m.trunk_g8));
ew.routed = m.y;
if (sh_w > 0) {
ew.sup = bf("shared_up", { T, sh_w });
ew.sff.x = bf("shared_ff", { T, sh_w });
RAD_ARCH_TRY(ew.sff.declare_qs(b, nm, g, "shared_ff", sh_w));
RAD_ARCH_TRY(ew.sff.declare_qs(b, nm, g, "shared_ff", sh_w, 0, m.trunk_i8, !m.trunk_i8,
m.trunk_g8));
ew.sout = bf("shared_out", { T, E });
}
Geom gl = g;
@@ -580,12 +600,20 @@ static int moe_buffers(RadBuilder* b, Model& m, const std::vector<MoeFP8::Src>&
w.sorted = decl_b(b, nm.f("%s.expert_sorted", tag), RAD_I32, { rows * k });
w.egu = bf(nm.f("%s.expert_up", tag), { rows * k, F });
w.eff.x = bf(nm.f("%s.expert_ff", tag), { rows * k, F });
RAD_ARCH_TRY(w.eff.declare_qs(b, nm, gl, nm.f("%s.expert_ff", tag), F, rows * k));
/* Rotated experts (w4nl64a8i8h and its kin) read rotated int8 codes, a scale per 128: the
* block input's rotated copy `hr` and the relu^2 product, each written by
* had_quant_act_i8g. This build has no rotated E4M3 quantiser. */
const bool i8arm = c.expert_rot != 0;
RAD_ARCH_TRY(w.eff.declare_qs(b, nm, gl, nm.f("%s.expert_ff", tag), F, rows * k, i8arm,
!i8arm, RAD_FP8_BLOCK));
w.eff.q8_fed = w.eff.q8_rot = i8arm;
w.edn = bf(nm.f("%s.expert_down", tag), { rows * k, L });
if (c.expert_rot) {
w.hr.q = decl_b(b, nm.f("%s.latent_rot.q", tag), RAD_F8E4M3, { T, L });
w.hr.s = decl_b(b, nm.f("%s.latent_rot.s", tag), RAD_F32, { T, L / RAD_FP8_BLOCK });
if (!w.hr.q || !w.hr.s) return RAD_E_INVAL;
if (i8arm) {
w.hr.q8 = decl_b(b, nm.f("%s.latent_rot.q8", tag), RAD_I8, { T, L });
w.hr.s8 = decl_b(b, nm.f("%s.latent_rot.s8", tag), RAD_F32, { T, L / RAD_FP8_BLOCK });
w.hr.g8 = RAD_FP8_BLOCK;
w.hr.q8_fed = w.hr.q8_rot = true;
if (!w.hr.q8 || !w.hr.s8) return RAD_E_INVAL;
}
if (!w.logits || !w.ids || !w.ew || !w.eoff || !w.ecnt || !w.sorted || !w.egu ||
!w.eff.x || !w.edn)
@@ -692,16 +720,31 @@ static int declare_lilicorr(RadBuilder* b, const RadModelMeta* meta, const RadBu
dw.attn = decl_b(b, nm.f("df_attn"), A, {qr, qd});
dw.gate_up = decl_b(b, nm.f("df_gate_up"), A, {qr, 2 * dg.n_ff});
dw.ffn = decl_b(b, nm.f("df_ffn"), A, {qr, dg.n_ff});
dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * E});
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(dc.n_taps * E)});
dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, E});
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(E)});
dw.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, E});
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(E)});
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 backbone's linears read: int8 with one f32 scale per (row, group) for linears
* stored rotated int8, which the drafter's `fc` tells (Dflash2::probe_i8, as gemma4_bf16 asks
* it); E4M3 with a scale per 128 for block fp8 or MXFP4 ones (rad_fp8.h's DenseFP8). radiance
* 2.0 serves no block fp8, so a 2.0 container's backbone is the int8 form. */
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 * E) % dqg || E % dqg || qd % dqg || dg.n_ff % dqg)) {
fprintf(stderr, "radiance: nemotronh: a rotated int8 LiLiCorr backbone 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)E, (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 * E});
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, dqs(dc.n_taps * E)});
dw.cq = decl_b(b, nm.f("df_cq"), dqt, {dg.max_tok, E});
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, dqs(E)});
dw.h2q = decl_b(b, nm.f("df_h2q"), dqt, {qr, E});
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, dqs(E)});
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"), A, {sr, E});
/* The proposal buffer (RadDrafterDecl::proposal), written by the walk. */
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
@@ -854,14 +897,37 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
c.n_ff_exp = s.ff[(size_t)l];
for (int q = 0; q < 4; ++q) c.ff_lo4[q] = c.ff_hi4[q] = 0;
}
/* The shared expert's slice: even, or slice_of's whole blocks. */
/* Whether the trunk is int8, from the first Mamba block's out projection, before the
* activations are declared: an int8 linear reads an int8 pair its input must hold. The probe
* makes that linear's name map, so Mamba::declare does not probe it again. */
m.layers.resize((size_t)s.n_layer);
for (int l = 0; l < (int)s.n_layer; ++l) {
if (s.kind[(size_t)l] != kMamba) continue;
LinearFP8& out = m.layers[(size_t)l].mamba.output;
RAD_ARCH_TRY(out.probe(b, nm, g, nm.f("blk.%d.ssm_out", l),
{ nm.ckpt("language_model.backbone.layers.%d.mixer.out_proj.weight",
l) }));
m.trunk_i8 = out.probed_i8;
m.trunk_g8 = out.probed_g8;
break;
}
/* The shared expert's slice: even, or slice_of's whole scale groups. Its down projection
* reads the slice along K, and an int8 trunk keeps one scale a group of K there: 128 columns,
* or IQ8R's 256 (asked after the probe above). Bolt's 5376 is 42 blocks of 128 but 21 groups
* of 256, so two ranks hold 11 and 10 groups, not 2688 columns each. */
const int64_t sg = m.trunk_i8 ? m.trunk_g8 : (int64_t)RAD_FP8_BLOCK;
if (s.ff_shared % sg) {
fprintf(stderr, "radiance: nemotronh: the shared expert's %lld columns are not whole "
"%lld-column scale groups\n", (long long)s.ff_shared, (long long)sg);
return RAD_E_UNSUPPORTED;
}
int64_t sh_lo = 0, sh_hi = 0, sh_w = s.ff_shared / world;
{
const int64_t sb = s.ff_shared / RAD_FP8_BLOCK;
const int64_t sb = s.ff_shared / sg;
if (sb % world) {
slice_of(sb, world, g.rank, 0, &sh_lo, &sh_hi);
sh_lo *= RAD_FP8_BLOCK;
sh_hi *= RAD_FP8_BLOCK;
sh_lo *= sg;
sh_hi *= sg;
sh_w = sh_hi - sh_lo;
}
}
@@ -942,7 +1008,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
}
m.layers.resize((size_t)s.n_layer);
for (int l = 0; l < (int)s.n_layer; ++l) {
Layer& lay = m.layers[(size_t)l];
lay.kind = s.kind[(size_t)l];
+61 -26
View File
@@ -581,6 +581,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* `model.language_model.layers.N` and its MTP block separately under `mtp.`; subtracting it
* would drop full-attention layer 63 and silently run a trunk one layer short. */
m.n_main = g.n_layer;
const bool calib_requested = ctx->calib_dir && *ctx->calib_dir;
const bool calib_mtp_layer = QWEN35_W8A8 && !QWEN35_MOE && calib_requested && nextn > 0 &&
ctx->calib_layer_lo == m.n_main && ctx->calib_layer_hi == m.n_main + 1;
#if !QWEN35_MOE
const bool calib_trunk_layers = calib_requested &&
(!ctx->calib_layer_hi || ctx->calib_layer_lo < m.n_main);
#endif
if (calib_requested && !calib_mtp_layer && ctx->calib_layer_hi > m.n_main) {
if (nextn > 0)
fprintf(stderr, "radiance: qwen35: select only the virtual MTP layer for draft-head "
"calibration on dense qwen35_w8a8\n");
else
fprintf(stderr, "radiance: qwen35: --calib-layers extends past the trunk, with no MTP "
"layer to calibrate\n");
return RAD_E_INVAL;
}
/* Qwen3.5's norms are GemmaRMSNorm, `x_hat * (1 + w)` (vLLM imports GemmaRMSNorm as
* Qwen3_5RMSNorm). This covers input_layernorm, post_attention_layernorm, the final norm and
@@ -1110,12 +1126,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
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");
* serial step. MTP-only calibration selects virtual layer n_main and does not touch this tap. */
if (calib_trunk_layers && g.world > 1) {
fprintf(stderr, "radiance: qwen35: --calib-dir records an int8 trunk at --tp 1 only; "
"select only the MTP layer for replicated-head calibration\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)));
if (calib_trunk_layers)
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];
@@ -1280,8 +1299,23 @@ 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. */
/* (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) {
if (calib_mtp_layer && m.n_taps > 0) {
fprintf(stderr, "radiance: qwen35: MTP draft-head calibration cannot use a DFlash2 drafter\n");
return RAD_E_UNSUPPORTED;
}
const bool want_mtp = nextn > 0 && (g.max_spec > 0 || calib_mtp_layer) && !m.n_taps;
const bool draft_q2 = want_mtp &&
mtp_draft_head_q2(b, nm.f("mtp.draft_head.weight"), nm.ckpt("lm_head.weight"));
if (calib_mtp_layer && !draft_q2) {
fprintf(stderr, "radiance: qwen35: MTP draft-head calibration requires a U2 "
"mtp.draft_head.weight\n");
return RAD_E_UNSUPPORTED;
}
/* A split target has no single output.weight. It can still verify the proposals of an
* independent U2 head. Older split-head containers carry neither that head nor the MTP
* block, even if the checkpoint metadata advertises NextN. Leave them trunk-only. */
if (want_mtp && (m.w_lm_head || draft_q2 || ctx->draft_coupling)) {
const int pitch = MtpHead::proposal_pitch(ctx->draft_coupling != 0);
/* 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). */
@@ -1290,19 +1324,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.b_mtp_c = decl_b(b, nm.f("mtp_c"), g.act_dtype, {g.max_tok, 2 * g.n_embd});
m.b_mtp_x = decl_b(b, nm.f("mtp_x"), g.act_dtype, {g.max_tok, g.n_embd});
/* The 2-bit draft head's working set, at max_logit_rows, since only a draft round (one row
* per sequence) uses it. `mtp_dsum` is quant_act_i8's group-major
* [n_embd/128][ceil(M/16)*16] plane, first dimension the K group, not the token. */
if (mtp_draft_head_q2(b, nm.f("mtp.draft_head.weight"), nm.ckpt("lm_head.weight"))) {
const int64_t dmpad = ((g.max_logit_rows + 15) / 16) * 16;
m.b_mtp_dq = decl_b(b, nm.f("mtp_dq"), RAD_I8, {g.max_logit_rows, g.n_embd});
m.b_mtp_ds = decl_b(b, nm.f("mtp_ds"), RAD_F32, {g.max_logit_rows, 1});
/* One row per drafting sequence, even if verification or KLD needs many more target
* logits rows. mtp_dsum is quant_act_i8's group-major [n_embd/128][ceil(M/16)*16]. */
if (draft_q2 && !calib_mtp_layer) {
const int64_t dmpad = ((g.max_seqs + 15) / 16) * 16;
m.b_mtp_dq = decl_b(b, nm.f("mtp_dq"), RAD_I8, {g.max_seqs, g.n_embd});
m.b_mtp_ds = decl_b(b, nm.f("mtp_ds"), RAD_F32, {g.max_seqs, 1});
m.b_mtp_dsum = decl_b(b, nm.f("mtp_dsum"), RAD_F32, {g.n_embd / 128, dmpad});
m.b_mtp_dlog = decl_b(b, nm.f("mtp_dlog"), g.act_dtype, {g.max_logit_rows, g.n_vocab_all});
m.b_mtp_dlog = decl_b(b, nm.f("mtp_dlog"), g.act_dtype, {g.max_seqs, g.n_vocab_all});
/* A draft round's proposal comes out of row_topk here, never through the sampler's
* token buffer. */
m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32, {g.max_logit_rows, 1});
m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32, {g.max_logit_rows, 1});
m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32, {g.max_seqs, pitch});
m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32, {g.max_seqs, pitch});
}
/* The head reuses the trunk's working buffers (`attn_qg`, `attn_k`, the ffn planes, `h`),
@@ -1318,6 +1351,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
tw.dq = m.b_mtp_dq; tw.ds = m.b_mtp_ds; tw.dsum = m.b_mtp_dsum;
tw.dlog = m.b_mtp_dlog; tw.didx = m.b_mtp_didx; tw.dval = m.b_mtp_dval;
tw.attn = tw_attn; tw.mlp = tw_mlp;
tw.coupled = !calib_mtp_layer && ctx->draft_coupling != 0;
if (calib_mtp_layer) {
tw.calib_dir = ctx->calib_dir;
tw.calib_tokens = ctx->calib_tokens;
}
MtpHead::Src ts{};
ts.fc = nm.ckpt("mtp.fc.weight");
@@ -1349,10 +1387,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
ts.mlp.up = nm.ckpt("mtp.layers.0.mlp.up_proj.weight");
ts.mlp.down = nm.ckpt("mtp.layers.0.mlp.down_proj.weight");
#endif
/* The trunk maps this same tensor as `output.weight`; the draft head maps it again under a
* name of its own, which the recipe quantises to two bits (mtp_draft_head_q2). */
ts.lm = nm.ckpt("lm_head.weight");
/* Bound as one more layer of the trunk's full-attention group, at absolute index n_main,
* so a draft round writes its K and V at the slot of the trunk's token for that position.
* A rejected draft is then overwritten rather than rolled back (rad_block_mtp_fp8.h). */
@@ -1362,15 +1396,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.w_lm_head, final_wadd, tw, ts));
m.have_mtp = true;
/* Serial drafter: `max_spec` dependent passes, each embedding the last one's proposal.
* The 2-bit head writes its own argmax into `mtp_didx`; without it `mtp_didx` is 0 and the
* bf16 head goes through the ordinary sampler chain. */
/* A U2 drafter writes a greedy or coupled proposal to column zero. The BF16 fallback
* uses the ordinary sampler. Calibration carries no projection, proposal or draft depth. */
RadDrafterDecl dd{};
dd.name = "mtp";
dd.kind = RAD_DRAFT_SERIAL;
dd.kind = calib_mtp_layer ? RAD_DRAFT_HISTORY : RAD_DRAFT_SERIAL;
dd.depth = ctx->max_spec;
dd.proposal = m.b_mtp_didx;
dd.proposal_pitch = 1;
dd.proposal_pitch = calib_mtp_layer ? 0 : pitch;
dd.mask_token = -1;
RAD_ARCH_TRY(rad_declare_drafter(b, &dd));
}
@@ -1418,7 +1451,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
rad_note(b, "MTP head: the first of %lld NextN layer(s) under `mtp.`, as absolute layer "
"%lld of the full-attention KV group",
(long long)nextn, (long long)m.n_main);
else if (nextn > 0)
else if (want_mtp && m.n_vcls)
rad_note(b, "no native MTP: this split-head container has no independent U2 draft head");
else if (nextn > 0 && !m.have_df)
rad_note(b, "the %lld MTP/NextN layer(s) under `mtp.` are not loaded: this deployment "
"does not speculate", (long long)nextn);
+224 -28
View File
@@ -114,11 +114,35 @@ using namespace rad::arch;
* and 13.17): a read here pays ~2 us of launch for what it saves. */
constexpr int64_t kGdnOutPrefetchBytes = (int64_t)8 << 20;
constexpr int64_t kGdnOutPrefetchSeqs = 4;
/* The rows from which a decode step is taken for a speculative verify, a step of several rows:
* where the shared arm's place and the reads' workgroup count below help, against the one row of
* a plain decode step, where both cost. ms a step at tp 2 with coupling, in one server with the
* rounds interleaved, at two / three / four rows (chain 1 / 2 / 3) and at one: the arm's down
* projection in front -0.28% / -0.21% / -0.25% and +0.38%; the reads at 32 workgroups -0.65% /
* -0.35% / -0.31% and +0.41%. */
constexpr int64_t kVerifyRows = 2;
/* A full-attention layer's out projection likewise, read behind its q, k and v projections
* (AttnGatedFP8::op_pf_o): the prologue and the attention between them and the projection are
* short launches with the memory idle. Twelve layers, so less: five interleaved rounds, ms a step
* without -> with, one stream 12.51 -> 12.45 (every round), two 16.88 -> 16.85. */
constexpr int64_t kAttnOutPrefetchBytes = (int64_t)8 << 20;
/* The workgroups of this model's weight reads on a verify step (the `prefetch` op's `blocks`, from
* kVerifyRows rows): 32, half the kernel's own 64. The reads run beside the delta net's update,
* the attention's prologue and the connections' reductions, all latency-bound kernels of a few
* loads a block whose loads queue behind the read's, and at four rows the update lasts half again
* as long as at one, so a slower read still lands. Chain 3 with coupling at tp 2, ms a step
* against 64 in one server, interleaved: 16 +0.77%, 24 +0.14%, 32 -0.31%, 48 -0.24%, 128 +2.0%,
* 256 +7.4%; -0.6% at 32 with the router's read beside. A one-row step keeps 64 (kVerifyRows). */
constexpr int64_t kPrefetchBlocksVerify = 32;
/* A layer's router likewise, read behind its mixer's out projection, beside the mixer's reduction
* and the feed-forward's connection read (both latency, with the card's memory mostly idle): the
* router is 2.5 MB of bf16 that its GEMM otherwise streams cold in front of a top-k that waits for
* all of it. Chain 3 with coupling at tp 2, ms a step without -> with, each the mean of two
* interleaved rounds in one server: 12.19 -> 12.13 (-0.42% and -0.93%); 12.14 -> 12.09 in another
* session. The same read of the shared expert's two weights, or of the indexer's projection, moved
* nothing (-0.02%, -0.04%, +0.04%), and of the mixer's first projection in front of its
* connection read cost 1.0%: a read there takes the memory from the connection's own. */
constexpr int64_t kRouterPrefetchBytes = (int64_t)4 << 20;
struct Layer {
int full = 0;
@@ -136,6 +160,11 @@ struct Layer {
/* The layer's calibration inputs (rad_calib_full.h, site_i8), -1 where this run records none:
* the mixer's input (the delta net's in projection, or q, k and v) and its output projection's. */
int cs_in = -1, cs_o = -1;
/* The router's weight read beside the mixer's reduction (kRouterPrefetchBytes); 0 where the
* deployment reads no weights ahead. */
rad_op op_pf_router = 0;
/* The same at a verify step's workgroup count (kPrefetchBlocksVerify), from kVerifyRows rows. */
rad_op op_pf_router_v = 0;
};
struct Model {
@@ -224,6 +253,16 @@ struct Model {
* from the real declare, so it declares the same ops. */
bool span_on = false;
bool pipe_on = false;
/* The rows of a piece of a spanned step: one checkpoint interval's, what the routed block's
* pass is without --prefill-span-pass step (`moecfg.rows`). The connections' reads, the
* indexer's windows, the delta net's pieces and the pipelined step's pieces are a piece tall
* whatever the routed pass is. */
int64_t piece_rows = 0;
/* --prefill-span-pass step (RadBuildCtx::span_pass_step) on a deployment that spans and does
* not pipeline: the routed block's pass is the whole step (`moecfg.rows` is max_tok), so a
* spanned step sorts its slots once and each expert's run is the step's. A sizing declare
* takes it from the real one, as span_on. */
bool pass_step = false;
/* {0, pass, T} for a step wider than a pass (pipe_bounds): the windows of the indexer's score
* plane and the delta net's pieces. A transient (declare), uploaded by every step that reads
* it -- the first two from the pinned host copy `pipe_cu_h`, made once. */
@@ -235,6 +274,9 @@ struct Model {
rad_weight w_tok = 0, w_lm_head = 0;
rad_op op_embed = 0, op_embed_ar = 0, op_rope_cs = 0, op_gather = 0, op_logits = 0;
/* The indexer's within-step buffers store_keys touches are excluded from sharing (declare),
* so a layer's keys may be issued behind its attention's launches (step_serial, QsaSide). */
bool qsa_defer = false;
/* ---- media (arch/common/rad_block_vit.h): the vision tower and the scatter of its rows over
* the token embeddings, declared only when the container carries a tower and the deployment
@@ -484,6 +526,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* prefill chunk to, so the shipped configuration is one pass. It also sizes four buffers at
* `rows * top_k`, so a smaller max_tok lowers it. */
mc.rows = g.max_tok < 2048 ? g.max_tok : 2048;
/* A piece of a spanned step; `mc.rows` itself grows to the step under
* --prefill-span-pass step (below, once the span is known). */
m.piece_rows = mc.rows;
if (mc.n_expert <= 0 || mc.top_k <= 0 || mc.top_k > mc.n_expert) {
fprintf(stderr, "radiance: qwen4exp: the container describes %lld expert(s) with "
"top_k %lld\n", (long long)mc.n_expert, (long long)mc.top_k);
@@ -774,21 +819,42 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
const int64_t v_dim = m.gcfg.v_dim();
const int64_t conv_dim = m.gcfg.conv_dim();
const int64_t T = g.max_tok;
const int64_t ER = m.moecfg.rows * m.moecfg.top_k;
m.b_h = decl_b(b, nm.f("h_wide"), g.act_dtype, {T, HN});
m.a_x.x = decl_b(b, nm.f("x"), g.act_dtype, {T, g.n_embd});
if (ctx->shape_probe) {
m.span_on = g_model[rad_build_slot(ctx)].span_on;
m.pipe_on = g_model[rad_build_slot(ctx)].pipe_on;
m.span_on = g_model[rad_build_slot(ctx)].span_on;
m.pipe_on = g_model[rad_build_slot(ctx)].pipe_on;
m.pass_step = g_model[rad_build_slot(ctx)].pass_step;
} else {
m.span_on = ctx->max_mixed_tok > 0 && ctx->max_mixed_tok < g.max_tok &&
g.max_tok > m.moecfg.rows;
g.max_tok > m.piece_rows;
/* Only where the blocks issue their own all-reduce at a step wider than a pass: at two
* ranks the gated residual's fused write takes every step's (ar_exact_write_rows), so such
* a step runs serially. */
m.pipe_on = m.span_on && g.world > 1 && ar_exact_write_rows(g) < g.max_tok;
/* --prefill-span-pass step, where a spanned step runs serially: nothing there needs the
* routed pass to be a piece (the pipelined step overlaps a piece's pass with the other
* piece's all-reduce, and keeps them), and a pass over the whole step reads each expert's
* weight once for two or four times the rows. A calibration run keeps its pieces: its
* statistics are taken a pass at a time. */
m.pass_step = ctx->span_pass_step != 0 && m.span_on && !m.pipe_on && !m.moecfg.calib;
if (ctx->span_pass_step != 0 && !m.pass_step && g.rank == 0)
rad_note(b, "--prefill-span-pass step: the routed pass stays one checkpoint interval "
"(%s)", !m.span_on ? "this deployment has no step wider than an interval"
: m.pipe_on ? "a spanned step is pipelined here, a pass a piece "
"beside the other piece's all-reduce"
: "a calibration run takes its statistics a pass at a "
"time");
}
/* Every op of a pass is per row, but the grouped trellis GEMM takes a run of one or two rows
* through its dot path and a longer one through its tiles, which agree only within f32
* rounding before the bf16 store: the step's longer runs move rows between the two, so the
* bytes are not those of piece-tall passes (the class of difference another chunk size makes,
* GUIDE 4.5). The planes below at `rows * top_k` grow with it. A sizing declare's max_tok is
* its level's, so a level holds one pass of its own rows. */
if (m.pass_step) m.moecfg.rows = g.max_tok;
const int64_t ER = m.moecfg.rows * m.moecfg.top_k;
/* The pipelined step's all-reduces run on the second lane, in place over `x`, so it is the one
* buffer that lane touches; it is live over the whole program anyway. */
if (m.pipe_on) RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_x.x));
@@ -801,7 +867,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* Under a span every connection reads a step wider than a pass a pass at a time
* (HyperConn::read_pieces, and the pipelined step's own reads), so the reads are declared no
* wider than a pass and their scratch is sized for that band. */
if (m.span_on) m.hccfg.read_rows = m.moecfg.rows;
if (m.span_on) m.hccfg.read_rows = m.piece_rows;
RAD_ARCH_TRY(m.a_x.declare_qs(b, nm, g, "x", g.n_embd, 0, m.trunk_i8));
/* The connections write int8 codes themselves when every reader of their codes is an int8
* linear: the trunk's are, and the routed experts then read the rotated copy or the bf16
@@ -810,9 +876,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* A read's rotated copy takes its plain codes' dtype, so beside int8 codes the routed arm is
* int8 too: the experts read had_quant_act_i8g's codes through the grouped GEMM's int8 rows
* (MoeFP8::a8), which the rotated four-bit plane, the codebook at E4M3 scales a 64 or 32 of K
* and rotated int8 experts have. The codebook at a bf16 scale a 128 and the five-bit one do
* not: under them the connections keep E4M3 codes, as for unrotated experts. */
const bool exp8 = m.moecfg.expert_rot && !m.moecfg.expert_w5 &&
* and rotated int8 experts have. The codebook at a bf16 scale a 128 and the five- and six-bit
* ones do not: under them the connections keep E4M3 codes, as for unrotated experts. */
const bool exp8 = m.moecfg.expert_rot && !m.moecfg.expert_w5 && !m.moecfg.expert_w6 &&
(!m.moecfg.expert_nl || m.moecfg.expert_g64);
m.hccfg.codes_i8 = (m.trunk_i8 && (exp8 || m.moecfg.expert_bf16)) ? 1 : 0;
m.a_x.q8_fed = m.hccfg.codes_i8 != 0;
@@ -862,8 +928,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* pass (QsaIndexer::step, with the bounds in b_pipe_cu). The plane is the largest buffer
* the span would otherwise grow, max_ctx / ratio floats a query row (512 MiB more at 4096
* rows and 256K of context). */
const int64_t qsa_rows = (m.span_on && ctx->max_mixed_tok <= m.moecfg.rows)
? m.moecfg.rows : g.max_tok;
const int64_t qsa_rows = (m.span_on && ctx->max_mixed_tok <= m.piece_rows)
? m.piece_rows : g.max_tok;
m.qsacfg.plane_rows = qsa_rows < g.max_tok ? qsa_rows : 0;
/* One row per query, not per sequence (arch/common/rad_qsa.h). The score plane is the
* only buffer whose size is the product of two deployment bounds, so an oversized one is
@@ -884,6 +950,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
{ g.max_tok, m.qsacfg.topk + 1 });
m.qsaw.nsel = decl_b(b, nm.f("qsa_nsel"), RAD_I32, { g.max_tok });
m.qsaw.sequ = decl_b(b, nm.f("qsa_sequ"), RAD_I32, { g.max_tok });
if (m.qsaw.qk && m.qsaw.stage && m.qsaw.page && m.qsaw.bpos && m.qsaw.nc) {
/* What store_keys reads and writes is in use behind the attention's launches when a
* layer's keys are deferred behind them (QsaSide), past the last use the linear order
* gives these buffers, so the planner must not lay an attention buffer over them.
* A few MiB of arena (qk is the largest, max_tok x 640 bf16). */
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.qk));
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.stage));
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.page));
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.bpos));
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.nc));
m.qsa_defer = true;
}
if (!m.qsaw.qk || !m.qsaw.q || !m.qsaw.stage || !m.qsaw.page ||
!m.qsaw.bpos || !m.qsaw.nc || !m.qsaw.score || !m.qsaw.sel || !m.qsaw.nsel ||
!m.qsaw.sequ)
@@ -936,8 +1014,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
if (m.arm8) {
/* The int8 routed arm's two pairs, rotated at a scale a 128 and written by their
* producers: the gated product's by gated_had_quant_i8g, the input's by the read. */
RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER, true, false,
RAD_FP8_BLOCK));
/* A trellis gate_up may be paired with a codebook (W5NL, W6NL) down. Keep its E4M3 pair
* as well so that the gated intermediate can use the down projection's own activation
* format. */
RAD_ARCH_TRY(m.a_eff.declare_qs(b, nm, g, "moe_eff", m.moecfg.n_ff_exp, ER, true,
m.moecfg.expert_iqr != 0, RAD_FP8_BLOCK));
m.a_eff.q8_fed = m.a_eff.q8_rot = true;
if (!m.trunk_rot) {
RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false,
@@ -1170,10 +1251,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
lay.attn.qsa_nsel = m.qsaw.nsel;
lay.attn.qsa_sequ = m.qsaw.sequ;
lay.attn.qsa_topk = m.qsacfg.topk;
/* The exactness bound, below which prefill issues the cheaper dense attention.
* Decode ignores it and always takes the sparse path, keeping that path exercised
* on every step. */
/* The exactness bound, at or below which a step of several rows a sequence
* (prefill, a verify) issues the cheaper dense attention. Plain decode keeps the
* sparse row's launch at every context, so that kernel is exercised on every
* step. */
lay.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1;
/* At or below that bound the indexer scores nothing (AttnGatedFP8::qsa_use): a
* row alone in its sequence is at the context's last position on this model (a
* plain decode row; the core's and the card's `seqused` is its position + 1), and
* pass_key() carries the exact bound's side of it. */
lay.attn.qsa_table_rows = true;
lay.attn.qsa_exact_host = true;
}
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
/* An attention-zero rank keeps no attention cache: its block is a fill of zeros
@@ -1238,6 +1326,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
MoeFP8::Src ms{};
ms.cfg = m.moecfg;
/* The expert tap can be limited to selected layers (RADIANCE_CALIB_LAYERS), the MTP
* layer below among them. The whole-expert placement m.moecfg.calib selects stays. */
ms.cfg.calib = m.moecfg.calib && calib_layer_on((int)l);
ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l);
RAD_ARCH_TRY(moe_expert_sources(b, nm, "layer",
nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l), &ms));
@@ -1313,6 +1404,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ARCH_TRY(m.mixer.declare(b, nm, g, nm.f("output_hc"), mc, mixw, mixs));
}
/* ---- the issue order of a decode step's small launches (AttnGatedFP8::kv_first_rows,
* MoeFP8::sh_down_first_lo): at decode and verify heights the k and v projections go in
* front of the q|gate projection, and from kVerifyRows rows the shared down projection in
* front of the routed down GEMM, so the card launches the small ones while the wide one is
* still being placed. The same kernels on the same operands; only what a recorded pass
* starts first changes. */
{
for (Layer& lay : m.layers) {
if (lay.full) lay.attn.kv_first_rows = kPrefetchRows;
lay.mlp.sh_down_first_lo = kVerifyRows;
lay.mlp.sh_down_first_hi = kPrefetchRows;
}
}
/* ---- the delta nets' out projections, read beside their decode recurrent updates
* (kGdnOutPrefetchBytes), and the full-attention layers' beside the attention
* (kAttnOutPrefetchBytes). At more than one rank; --weight-prefetch off declares none. */
@@ -1320,11 +1425,23 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
for (Layer& lay : m.layers) {
if (lay.full) {
lay.attn.op_pf_o = decl_prefetch(b, lay.attn.o.w, kAttnOutPrefetchBytes);
lay.attn.op_pf_o_v = decl_prefetch(b, lay.attn.o.w, kAttnOutPrefetchBytes,
kPrefetchBlocksVerify);
lay.attn.pf_o_v_rows = kVerifyRows;
continue;
}
lay.gdn.op_pf_out = decl_prefetch(b, lay.gdn.out.w, kGdnOutPrefetchBytes);
lay.gdn.pf_out_rows = kPrefetchRows;
lay.gdn.pf_out_seqs = kGdnOutPrefetchSeqs;
lay.gdn.op_pf_out_v = decl_prefetch(b, lay.gdn.out.w, kGdnOutPrefetchBytes,
kPrefetchBlocksVerify);
lay.gdn.pf_out_v_rows = kVerifyRows;
}
for (Layer& lay : m.layers) {
if (!lay.mlp.w_router) continue;
lay.op_pf_router = decl_prefetch(b, lay.mlp.w_router, kRouterPrefetchBytes);
lay.op_pf_router_v = decl_prefetch(b, lay.mlp.w_router, kRouterPrefetchBytes,
kPrefetchBlocksVerify);
}
}
@@ -1462,6 +1579,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
ts.attn.o = nm.ckpt("%s.layers.0.self_attn.o_proj.weight", mpre);
ts.mlp.cfg = m.moecfg;
ts.mlp.cfg.calib = m.moecfg.calib && calib_layer_on((int)g.n_layer);
ts.mlp.router = nm.ckpt("%s.layers.0.mlp.gate.weight", mpre);
RAD_ARCH_TRY(moe_expert_sources(b, nm, "mtp", nm.ckpt("%s.layers.0.mlp.experts", mpre),
&ts.mlp));
@@ -1473,12 +1591,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* Set before declare(), as for the trunk: `attn_paged` declares `sel` and `seqused` as
* reads, which must precede the op. */
m.mtp.attn.kv_block = 4;
/* The head's layer takes the trunk's issue order at decode heights (declare, above). */
m.mtp.attn.kv_first_rows = kPrefetchRows;
m.mtp.mlp.sh_down_first_lo = kVerifyRows;
m.mtp.mlp.sh_down_first_hi = kPrefetchRows;
if (m.qsaw.qk) {
m.mtp.attn.qsa_sel = m.qsaw.sel;
m.mtp.attn.qsa_nsel = m.qsaw.nsel;
m.mtp.attn.qsa_sequ = m.qsaw.sequ;
m.mtp.attn.qsa_topk = m.qsacfg.topk;
m.mtp.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1;
/* As the trunk's layers: a round's row is the head's context's last position
* (ADV_ROUND), and the history pass is one row only where it commits one. */
m.mtp.attn.qsa_table_rows = true;
m.mtp.attn.qsa_exact_host = true;
ts.qsa = m.qsacfg;
ts.qsa.mode = m.mtp.attn.mode;
ts.qsa.qk_proj = nm.ckpt("%s.layers.0.self_attn.indexer.index_qk_proj.weight", mpre);
@@ -1562,7 +1688,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* of the sharing pool (declare). The collectives there are declared at `overlap` 1, whose rows
* leave the CUs to the work beside them. */
static bool pipelined(const Model& m, int64_t T) {
const int64_t R = m.moecfg.rows;
const int64_t R = m.piece_rows;
if (!m.pipe_on || R <= 0 || T <= R) return false;
if (m.moecfg.calib || m.calib.on || dbg_resid_on() || !m.op_embed_ar) return false;
for (const Layer& l : m.layers) {
@@ -1600,7 +1726,7 @@ static const int32_t* pipe_bounds(RadCtx* c, const RadBatch* batch, Model& m) {
m.pipe_cu_h = (int32_t*)rad_dev_alloc(2 * sizeof(int32_t), RAD_MEM_HOST_PINNED);
if (m.pipe_cu_h) {
m.pipe_cu_h[0] = 0;
m.pipe_cu_h[1] = (int32_t)m.moecfg.rows;
m.pipe_cu_h[1] = (int32_t)m.piece_rows;
} else if (m.g.rank == 0) {
fprintf(stderr, "radiance: qwen4exp: no pinned host memory for the window bounds; a "
"step wider than a pass cannot run\n");
@@ -1608,7 +1734,7 @@ static const int32_t* pipe_bounds(RadCtx* c, const RadBatch* batch, Model& m) {
}
if (!m.pipe_cu_h) return nullptr;
int32_t* d = (int32_t*)rad_buf_ptr(c, m.b_pipe_cu);
if (batch->n_tok > m.moecfg.rows && batch->n_seq == 1) {
if (batch->n_tok > m.piece_rows && batch->n_seq == 1) {
const RadStream s = rad_stream(c);
if (rad_memcpy_async(d, m.pipe_cu_h, 2 * sizeof(int32_t), s) != RAD_OK ||
rad_memcpy_async(d + 2, batch->cu_seqlens + 1, sizeof(int32_t), s) != RAD_OK)
@@ -1619,7 +1745,7 @@ static const int32_t* pipe_bounds(RadCtx* c, const RadBatch* batch, Model& m) {
static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
const Geom& g = m.g;
const int64_t T = batch->n_tok, R = m.moecfg.rows;
const int64_t T = batch->n_tok, R = m.piece_rows;
const int64_t K = (T + R - 1) / R;
auto r0 = [&](int64_t p) { return p * R; };
auto rn = [&](int64_t p) { return T - p * R < R ? T - p * R : R; };
@@ -1652,7 +1778,8 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
/* The delta net runs a piece at a time over the bounds (ArPieces::cu) in a step of one
* prefill sequence in two pieces. */
const int32_t* gcu = pcu && K == 2 && batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL
const int32_t* gcu = pcu && K == 2 && batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL &&
batch->ckpt_cut <= 0
? pcu : nullptr;
const int64_t n = (int64_t)m.layers.size();
@@ -1660,6 +1787,9 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
if (m.ple_layer == 0) m.ple.step(c, batch);
for (int64_t p = 0; p < K; ++p) m.layers[0].hc_mix.read(c, T, r0(p), rn(p));
}
/* The pass's first full-attention layer with an indexer makes what every such layer shares of
* its step (QsaIndexer::step, `first`). */
bool qsa_first = true;
for (int64_t li = 0; li < n; ++li) {
const Layer& l = m.layers[(size_t)li];
/* The mixer finishes its output a piece at a time where its last stages are per row and
@@ -1668,7 +1798,11 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
MixAr ms{c, &l};
ArPieces pc{};
pc.rows = R; pc.done = mix_ar_piece; pc.u = &ms; pc.cu = gcu;
if (l.full) { l.qsa.step(c, l.attn.w.h, batch, pcu); l.attn.step(c, batch, false, &pc); }
if (l.full) {
l.qsa.step(c, l.attn.w.h, batch, pcu, l.attn.qsa_use(batch), qsa_first);
if (l.qsa.on()) qsa_first = false;
l.attn.step(c, batch, false, &pc);
}
else l.gdn.step(c, batch, false, &pc);
auto ar_mix = [&](int64_t p) {
if (l.full) l.attn.issue_ar(c, r0(p), rn(p));
@@ -1713,6 +1847,18 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
}
}
/* A full-attention layer's indexer keys behind its attention's launches (QsaIndexer::deferrable,
* SideOps): store_keys's three stages in turn, one a call, and whatever is left at flush(). */
struct QsaSide {
RadCtx* c = nullptr;
const QsaIndexer* q = nullptr;
const RadBatch* batch = nullptr;
int next = 1;
void one() { if (next <= 3) q->step_part(c, batch, next++); }
void flush() { while (next <= 3) one(); }
static void at(void* u, int) { ((QsaSide*)u)->one(); }
};
/* The trunk one stream at a time over the whole step: every step a span of 1 makes, and every
* other where step_pipelined's conditions do not hold. */
static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
@@ -1733,22 +1879,50 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_
if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch))
RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs));
/* The pass's first full-attention layer with an indexer makes what every such layer shares of
* its step (QsaIndexer::step, `first`). */
bool qsa_first = true;
for (int64_t li = 0; li < (int64_t)m.layers.size(); ++li) {
const Layer& l = m.layers[(size_t)li];
/* Before the attention connection reads the stream, which is where the reference puts it. */
if (li == m.ple_layer) m.ple.step(c, batch);
l.hc_mix.read_pieces(c, T);
/* A checkpoint inside the step (RadBatch::ckpt_cut) cuts the reads' pieces there. */
l.hc_mix.read_pieces(c, T, batch->ckpt_cut);
/* The calibration taps read the codes the mixer's GEMMs read: its input before it runs,
* its output projection's input before the feed-forward's connection reuses the pair. */
if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, T);
/* The indexer runs first, since the attention reads its selection. The block's input is
* already normed and quantised by the connection (`ext_in`), so `w.h` is final. */
if (l.full) { l.qsa.step(c, l.attn.w.h, batch, pcu); l.attn.step(c, batch); }
if (l.full) {
const int use = l.attn.qsa_use(batch);
/* At decode heights within the exactness bound nothing of the layer reads the
* indexer's keys or tail (they are for later steps), so only the projection stays in
* front, beside the attention's own, and the three launches behind it ride behind the
* attention's (QsaSide) instead of holding its projections back in turn: -0.3% to
* -0.8% a step on chain 3 with coupling at tp 2. */
if (m.qsa_defer && T <= kPrefetchRows && batch->phase == RAD_PHASE_DECODE &&
l.qsa.deferrable(batch, use, qsa_first)) {
QsaSide sd{c, &l.qsa, batch};
const SideOps so{QsaSide::at, &sd};
l.qsa.step_proj(c, l.attn.w.h, batch);
l.attn.step(c, batch, true, nullptr, &so);
sd.flush();
} else {
l.qsa.step(c, l.attn.w.h, batch, pcu, use, qsa_first);
l.attn.step(c, batch);
}
if (l.qsa.on()) qsa_first = false;
}
else l.gdn.step(c, batch);
if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, T);
/* The router's weight, read beside the write's reduction and the read behind it. */
if (batch->phase == RAD_PHASE_DECODE)
prefetch_beside(c, l.op_pf_router_v && T >= kVerifyRows ? l.op_pf_router_v
: l.op_pf_router,
l.mlp.w_router, T);
l.hc_mix.write(c, T, 0, T);
dbg_resid(c, (int)li, "mix", g.n_embd, m.b_h, m.a_x.x);
l.hc_ffn.read_pieces(c, T);
l.hc_ffn.read_pieces(c, T, batch->ckpt_cut);
l.mlp.step(c, batch);
l.hc_ffn.write(c, T, 0, T);
/* The request's control vector, on the stream the write just finished. */
@@ -1821,23 +1995,37 @@ static void step(RadCtx* c, const RadBatch* batch) {
uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
if (!c || !batch) return 0;
if (batch->enc) return 1;
Model& m = g_model[rad_slot(c)];
/* Which side of the indexer's exactness bound the step is on by the attention group's exact
* host bound, by which the full-attention layers and the indexer decide whether the step
* needs scores (AttnGatedFP8::qsa_within, qsa_exact_host). The core's key holds only the
* rounded context bound, so the side is keyed here: one more recording of each pass kind as a
* request crosses the bound. `sel` is 2 within the bound and 0 past it or where it is
* unknown, which is where the blocks fall back to the rounded bound the core keys. */
uint64_t sel = 0;
if (used_max_h && batch->kv && m.kv_full && m.qsacfg.budget > 0 && m.qsacfg.ratio > 0)
for (int i = 0; i < batch->n_kv_groups; ++i)
if (batch->kv[i].group == m.kv_full) {
if (used_max_h[i] > 0 &&
used_max_h[i] <= m.qsacfg.budget + m.qsacfg.ratio - 1) sel = 2;
break;
}
/* A decode pass, a speculative verify or an MTP draft included, issues every launch at the
* step's keyed context bound (RadArgs::kv_used_max_h), never the live maximum, so the core's
* key holds its geometry. */
if (batch->phase == RAD_PHASE_DECODE) return 1;
if (batch->phase == RAD_PHASE_DECODE) return 1 | sel;
/* Mixed batches split the query rows into decode and prefill subsets before attention, which
* read the live maximum. The whole-batch host summary cannot key those subset geometries
* exactly, nor a drafter's or a verify's rows inside a prefill pass. */
if (batch->phase == RAD_PHASE_MIXED || batch->draft_pass != 0 || batch->n_spec > 0) return 0;
Model& m = g_model[rad_slot(c)];
bool has_full_attention = false;
for (const Layer& layer : m.layers) {
if (!layer.full) continue;
if (layer.attn.kv_block != 4) return 0;
has_full_attention = true;
}
if (!has_full_attention) return 1;
if (!has_full_attention) return 1 | sel;
if (m.g.head_dim != 256 || (m.g.gqa() != 6 && m.g.gqa() != 12) || !m.kv_full ||
!used_max_h || !batch->kv || batch->n_kv_groups <= 0)
return 0;
@@ -1863,7 +2051,10 @@ uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
const int bq = nwarps * 16 / m.g.gqa();
const int splits = rad_prefill_splits_for_live(bq, tile, q_len, total_q, num_seqs,
kv_heads, m.g.max_ctx, used, wgps);
return rad_prefill_grid_key(q_len, bq, splits, kv_heads, num_seqs, nwarps * 32);
const uint64_t grid = rad_prefill_grid_key(q_len, bq, splits, kv_heads, num_seqs, nwarps * 32);
/* 0 stays "unknown"; the side of the bound rides in a bit the grid key's mix does not leave
* meaningful, so two sides are two keys. */
return grid ? ((grid << 2) | 1 | sel) : 0;
}
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
@@ -1881,6 +2072,11 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
* have chained forms: on two R9700 a full pass under the draft head went from 13.9 to 12.5 ms
* and the step without the head from 9.98 to 9.17 ms at one sequence. */
out->chain_pays = RAD_CHAIN_ALWAYS;
/* A step of one prefill sequence with its checkpoint inside it (RadBatch::ckpt_cut): the delta
* net runs its recurrence in two pieces and snapshots between them (rad_block_gdn_fp8.h), and
* the connection reads cut their pieces at the checkpoint (HyperConn::read_pieces), so the
* rows before it read what a chunk ending there reads. */
out->ckpt_snap_ok = 1;
return RAD_OK;
}
+62 -30
View File
@@ -76,6 +76,16 @@ enum { kMaxLanes = 16 };
* rounding (the driver's bound, core/gen/driver.cpp). */
static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 10 + 64; }
/* Every output side is a multiple of 32, so attainable areas are multiples of four
* latent tokens. Keep the model's original bounds when the operator supplies none. */
static int64_t image_tokens(int64_t pixels) {
return pixels > 0 ? std::min<int64_t>(kMaxImageTokens, pixels / 1024 * 4) : kMaxImageTokens;
}
static int64_t reference_count(int64_t refs) {
return refs > 0 ? std::min<int64_t>(refs, kMaxRefs) : kMaxRefs;
}
static const char* kSysPrompt = "Comprehend and analyze the provided prompt.";
@@ -120,6 +130,8 @@ enum : int {
struct Model {
Names nm{""};
Geom gt{}, gd{}; /* the language model's and the DiT's geometry, per rank */
int64_t max_image_tokens = kMaxImageTokens;
int64_t max_refs = kMaxRefs;
int64_t max_ref_rows = 0; /* every reference picture's latent tokens together */
bool media = false;
VisionTower vit{};
@@ -426,8 +438,8 @@ static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
v.scope = "venc";
v.down = true;
v.first_group = kGrpVaeEnc;
/* The largest picture the encoder reads: a repainted one at the largest output size. */
v.base_px = (int64_t)kMaxImageTokens * 256;
/* Repaint inputs match the output. References keep their own resize area. */
v.base_px = std::max(m.max_image_tokens, ref_tokens_max()) * 256;
const int64_t base = rad_meta_geti(meta, "vae.base_dim", 96);
const std::vector<double> mult = meta_list(meta, "vae.dim_mult");
const std::vector<double> td = meta_list(meta, "vae.temperal_downsample");
@@ -474,16 +486,16 @@ static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
{ m.enc_q.buf }, { m.b_reflat, m.b_encz });
/* A repainted picture's latent and its mask, into every lane its images run in. */
m.op_lstore_lat = rw(b, RAD_OP(b, "lane_store",
RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens),
RAD_PARAMS(RAD_RANGE("M", 1, m.max_image_tokens),
RAD_INT("n", zd),
RAD_INT("stride", (int64_t)kMaxImageTokens),
RAD_INT("stride", m.max_image_tokens),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.b_encz, m.b_inp }, { m.b_inp });
m.op_lstore_mask = rw(b, RAD_OP(b, "lane_store",
RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens),
RAD_PARAMS(RAD_RANGE("M", 1, m.max_image_tokens),
RAD_INT("n", 1),
RAD_INT("stride", (int64_t)kMaxImageTokens),
RAD_INT("stride", m.max_image_tokens),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ m.b_mask }, { m.b_mask });
@@ -497,7 +509,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
v.scope = "vdec";
v.down = false;
v.first_group = kGrpVaeDec;
v.base_px = kMaxImageTokens;
v.base_px = m.max_image_tokens;
const int64_t base = rad_meta_geti(meta, "vae.decoder_base_dim", 144);
const std::vector<double> mult = meta_list(meta, "vae.dim_mult");
const std::vector<double> td = meta_list(meta, "vae.temperal_downsample");
@@ -541,10 +553,10 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
}
x = v.norm(x, true, "vae.decoder.norm_out", 4);
m.dec_out = v.conv(x, cout, 3, 1, 1, "same", "vae.decoder.conv_out");
m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { (int64_t)kMaxImageTokens * 256 * cout },
m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { m.max_image_tokens * 256 * cout },
RAD_BUF_PERSIST);
m.op_rgba = rw(b, RAD_OP(b, "to_rgba8",
RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens * 256),
RAD_PARAMS(RAD_RANGE("M", 1, m.max_image_tokens * 256),
RAD_INT("n", cout), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.dec_out.buf }, { m.b_img });
@@ -556,11 +568,11 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
}
/* The bands, gathered. A band is ceil(H / world) latent rows, and the split is taken only where
* a band plus its two halos is smaller than the whole, so H > 2 * halo, which bounds W and
* thus the largest band: under kMaxImageTokens / world + kMaxImageTokens / (2 * halo)
* thus the largest band: under m.max_image_tokens / world + m.max_image_tokens / (2 * halo)
* tokens. */
const int world = m.gt.world;
if (world > 1) {
const int64_t bpx = (kMaxImageTokens / world + kMaxImageTokens / (2 * v.halo) + 1) * 256;
const int64_t bpx = (m.max_image_tokens / world + m.max_image_tokens / (2 * v.halo) + 1) * 256;
m.b_rgbaf = decl_b(b, nm.f("vdec.bands"), RAD_BF16, { world * bpx, cout });
m.op_bands = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", world),
@@ -569,7 +581,7 @@ static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) {
RAD_NOWEIGHTS),
{ m.dec_out.buf }, { m.b_rgbaf });
m.op_rgba_bands = rw(b, RAD_OP(b, "to_rgba8",
RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens * 256),
RAD_PARAMS(RAD_RANGE("M", 1, m.max_image_tokens * 256),
RAD_INT("n", cout), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.b_rgbaf }, { m.b_img });
@@ -628,13 +640,13 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
{ m.b_txt }, { m.b_h });
m.op_randn = rw(b, RAD_OP(b, "randn_lanes",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C),
RAD_INT("stride", (int64_t)kMaxImageTokens),
RAD_INT("stride", m.max_image_tokens),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.b_state }, { m.b_state });
m.op_lgather = rw(b, RAD_OP(b, "lane_gather",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C),
RAD_INT("stride", (int64_t)kMaxImageTokens),
RAD_INT("stride", m.max_image_tokens),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.b_state }, { m.b_lat });
@@ -820,7 +832,7 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) {
C, D, T, m.a_hm.x, m.b_v, &m.w_pout, gx);
m.op_euler = rw(b, RAD_OP(b, "flow_euler",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C),
RAD_INT("stride", (int64_t)kMaxImageTokens),
RAD_INT("stride", m.max_image_tokens),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.b_v, m.b_inp, m.b_mask, m.b_state, m.b_prev }, { m.b_state, m.b_prev });
@@ -834,6 +846,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
Model& m = g_model[rad_build_slot(ctx)];
m = Model{};
m.nm = Names(ctx->scope);
m.max_image_tokens = image_tokens(ctx->gen_max_pixels);
m.max_refs = reference_count(ctx->gen_max_refs);
if (m.max_image_tokens == 0) {
fprintf(stderr, "radiance: qwenimage21: --image-gen-max-pixels must fit a 32x32 image\n");
return RAD_E_INVAL;
}
RAD_ARCH_TRY(check_format(meta));
RAD_ARCH_TRY(geom_from(m.gt, meta, ctx, "bf16", RAD_BF16));
Names& nm = m.nm;
@@ -917,14 +935,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- the per-image state, a lane an image, and what the passes hand each other */
const int64_t C = rad_meta_geti(meta, "transformer.in_channels", 64);
const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens;
const int64_t lane_rows = (int64_t)kMaxLanes * m.max_image_tokens;
m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, C }, RAD_BUF_PERSIST);
m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, C }, RAD_BUF_PERSIST);
m.b_inp = decl_b(b, nm.f("lat_repaint"), RAD_BF16, { lane_rows, C }, RAD_BUF_PERSIST);
m.b_mask = decl_b(b, nm.f("lat_mask"), RAD_F32, { lane_rows, 1 }, RAD_BUF_PERSIST);
m.max_ref_rows = (int64_t)kMaxRefs * ref_tokens_max();
m.max_ref_rows = m.max_refs * ref_tokens_max();
m.b_reflat = decl_b(b, nm.f("ref_lat"), RAD_BF16, { m.max_ref_rows, C }, RAD_BUF_PERSIST);
m.b_encz = decl_b(b, nm.f("enc_lat"), RAD_BF16, { (int64_t)kMaxImageTokens, C });
m.b_encz = decl_b(b, nm.f("enc_lat"), RAD_BF16, { m.max_image_tokens, C });
m.C = C;
/* ---- in issue order: the tower, the language model, the encoder, the DiT, the decoder.
@@ -974,11 +992,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
d.size_multiple = 32;
d.pixel_channels = rad_meta_geti(meta, "vae.out_channels", 4);
d.slot_rows = 4;
d.max_tokens = kMaxImageTokens;
d.max_refs = kMaxRefs;
d.max_tokens = m.max_image_tokens;
d.max_refs = m.max_refs;
d.ref_area = kRefArea;
d.default_width = 2048;
d.default_height = 2048;
const int64_t side = (int64_t)(std::sqrt(std::min<int64_t>(m.max_image_tokens, 16384)) / 2) * 32;
d.default_width = side;
d.default_height = side;
d.default_steps = sig.empty() ? 40 : (int64_t)sig.size();
d.n_sigmas = (int32_t)sig.size();
d.sigmas = sig.empty() ? nullptr : sig.data();
@@ -1215,15 +1234,19 @@ static void step(RadCtx* c, const RadBatch* batch) {
const int64_t n = (int64_t)(ph / 16) * (pw / 16);
const RadOperand pcu = praw(G->px_cu + 2 * i, RAD_I32, 2);
if (i < n_ref) {
if (n > ref_tokens_max() || n > m.max_ref_rows - lat_row) {
rad_step_fail(c, "qwenimage21: reference pixels exceed the declared latent buffer");
return;
}
step_encode(c, m, px, ph, pw, pcu, m.b_reflat, lat_row);
lat_row += n;
} else {
step_encode(c, m, px, ph, pw, pcu, m.b_encz, 0);
RAD_ISSUE_N(c, m.op_lstore_lat, n, brows(m.b_encz, n),
praw(G->lane, RAD_I32, G->n_lane), brows(m.b_inp, kMaxLanes * (int64_t)kMaxImageTokens));
praw(G->lane, RAD_I32, G->n_lane), brows(m.b_inp, kMaxLanes * m.max_image_tokens));
RAD_ISSUE_N(c, m.op_lstore_mask, n, praw2(G->inp_mask, RAD_F32, n, 1),
praw(G->lane, RAD_I32, G->n_lane),
brows(m.b_mask, kMaxLanes * (int64_t)kMaxImageTokens));
brows(m.b_mask, kMaxLanes * m.max_image_tokens));
}
}
/* 4. the modulation at t = 0, which every conditioning row reads */
@@ -1254,7 +1277,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
const int64_t N = batch->n_tok, S = batch->n_seq;
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1);
const RadOperand lanes = praw(G->lane, RAD_I32, S);
const int64_t L = (int64_t)kMaxLanes * kMaxImageTokens;
const int64_t L = (int64_t)kMaxLanes * m.max_image_tokens;
step_temb(c, m, G->sigma, S);
RAD_ISSUE_N(c, m.op_randn, N, praw(G->flags, RAD_I32, S), praw(G->seed, RAD_U32, 2 * S),
lanes, cu, brows(m.b_state, L));
@@ -1275,7 +1298,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
case RAD_GEN_PASS_DECODE: {
const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W;
const rad_buf src = G->dec_preview ? m.b_prev : m.b_state;
RAD_ISSUE_N(c, m.op_dec_aff, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C),
RAD_ISSUE_N(c, m.op_dec_aff, n, brow_slice(src, (int64_t)G->dec_lane * m.max_image_tokens, n, C),
brows(m.b_decin, n));
const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2);
const int64_t npx = (int64_t)G->dec_height * G->dec_width, ch = m.dec_out.ch;
@@ -1309,12 +1332,21 @@ static void step(RadCtx* c, const RadBatch* batch) {
}
/* ================================================================== the probe */
/* The rows a pass carries (one image at the largest size with guidance, so two entries) and the
* vision patches of ten reference pictures at 1024 x 1024 of area. */
/* The denoiser can carry two copies of an image for guidance. With reduced output sizes
* also leave room for the reference conditioning and prompt, within the original row budget. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->gen_rows = 2 * (int64_t)kMaxImageTokens;
out->gen_patches = (int64_t)kMaxRefs * (kRefArea / 256) * 11 / 10;
const int64_t tokens = image_tokens(out->gen_max_pixels);
if (tokens == 0) return RAD_E_INVAL;
const int64_t refs = reference_count(out->gen_max_refs);
const int64_t conditioning_rows = std::min<int64_t>(
2 * kMaxImageTokens, refs * ref_tokens_max() + 1024);
out->gen_rows = std::max(2 * tokens, conditioning_rows);
const int64_t merge = rad_meta_geti(meta, "vision_config.spatial_merge_size", 2);
if (merge < 1 || merge > 16) return RAD_E_INVAL;
const int64_t group = merge * merge;
const int64_t patches = refs * (kRefArea / 256) * 11 / 10;
out->gen_patches = (patches + group - 1) / group * group;
return RAD_OK;
}
+44 -13
View File
@@ -1550,8 +1550,8 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
return RAD_E_INVAL;
}
/* References: a template with both of its slots, an item with one transcript before its one
* clip, and the clips' geometry; read whole by one branch's prompt (an unconditional branch
* would need references of its own). */
* clip, and the clips' geometry. Two branches may repeat the same reference prompt at
* guidance 1; reference CFG would need a separate unconditional frame map and is refused. */
if (d->tmpl_ref) {
auto once = [](const char* t, const char* k) {
const char* a = t ? std::strstr(t, k) : nullptr;
@@ -1566,16 +1566,36 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
"{input} once each, and ref_item {text} before its one {audio}", nm);
return RAD_E_INVAL;
}
if (d->branches != 1 || !d->prompt_whole || d->ref_rate <= 0 || d->ref_hop <= 0 ||
d->ref_max <= 0 || d->ref_max_samples < d->ref_hop) {
err(RAD_E_INVAL, "declare_audio_generator '%s': references are read by a model of one "
"branch from whole prompts, clips at a rate (%lld Hz) in frames of "
if (!d->prompt_whole || d->ref_rate <= 0 || d->ref_hop <= 0 ||
d->ref_max <= 0 || d->ref_max_samples < d->ref_hop ||
(d->branches != 1 && (!d->neg_tmpl || d->default_cfg != 1.0 ||
std::strstr(d->neg_tmpl, "{references}")))) {
err(RAD_E_INVAL, "declare_audio_generator '%s': references need whole prompts and "
"guidance 1 (two branches need a plain negative template); clips at "
"a rate (%lld Hz) in frames of "
"%lld samples, at most %d of them and %lld samples a request", nm,
(long long)d->ref_rate, (long long)d->ref_hop, (int)d->ref_max,
(long long)d->ref_max_samples);
return RAD_E_INVAL;
}
}
if (d->tmpl_ref_instruct || d->neg_tmpl_ref) {
auto once = [](const char* t, const char* key) {
const char* p = t ? std::strstr(t, key) : nullptr;
return p && !std::strstr(p + 1, key);
};
if (!d->tmpl_ref || !d->tmpl_ref_instruct || !d->neg_tmpl_ref || d->branches == 1 ||
!once(d->tmpl_ref_instruct, "{references}") ||
!once(d->tmpl_ref_instruct, "{input}") ||
!once(d->tmpl_ref_instruct, "{instructions}") ||
!once(d->neg_tmpl_ref, "{references}") || !once(d->neg_tmpl_ref, "{input}") ||
std::strstr(d->neg_tmpl_ref, "{instructions}")) {
err(RAD_E_INVAL, "declare_audio_generator '%s': reference direction needs paired "
"conditional/reference-only templates with one references/input "
"slot each and instructions only in the conditional template", nm);
return RAD_E_INVAL;
}
}
if (d->branches != 0 && d->branches != 1 && d->branches != 2) {
err(RAD_E_INVAL, "declare_audio_generator '%s': branches is %d; a request runs 1 sequence "
"or 2 (0 means 2)", nm, (int)d->branches);
@@ -1669,6 +1689,8 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
prog_.agen_str.tmpl_plain = d->tmpl_plain ? d->tmpl_plain : "";
prog_.agen_str.neg_tmpl = d->neg_tmpl ? d->neg_tmpl : "";
prog_.agen_str.tmpl_ref = d->tmpl_ref ? d->tmpl_ref : "";
prog_.agen_str.tmpl_ref_instruct = d->tmpl_ref_instruct ? d->tmpl_ref_instruct : "";
prog_.agen_str.neg_tmpl_ref = d->neg_tmpl_ref ? d->neg_tmpl_ref : "";
prog_.agen_str.ref_item = d->tmpl_ref && d->ref_item ? d->ref_item : "";
prog_.audio_gen = *d;
/* As for the image generator: the Program is moved after declare; strings live in agen_str. */
@@ -1677,6 +1699,8 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
prog_.audio_gen.tmpl_plain = nullptr;
prog_.audio_gen.neg_tmpl = nullptr;
prog_.audio_gen.tmpl_ref = nullptr;
prog_.audio_gen.tmpl_ref_instruct = nullptr;
prog_.audio_gen.neg_tmpl_ref = nullptr;
prog_.audio_gen.ref_item = nullptr;
/* Without references the clips' geometry is nothing: the driver stages none. */
if (!d->tmpl_ref) {
@@ -2038,9 +2062,9 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
if (d->kind == RAD_DRAFT_NONE) return RAD_OK; /* declaring nothing is declaring nothing */
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
if (d->kind != RAD_DRAFT_SERIAL && d->kind != RAD_DRAFT_BLOCK) {
err(RAD_E_INVAL, "declare_drafter '%s': kind %d is neither RAD_DRAFT_SERIAL nor "
"RAD_DRAFT_BLOCK", nm, d->kind);
const bool history = d->kind == RAD_DRAFT_HISTORY;
if (d->kind != RAD_DRAFT_SERIAL && d->kind != RAD_DRAFT_BLOCK && !history) {
err(RAD_E_INVAL, "declare_drafter '%s': unknown kind %d", nm, d->kind);
return RAD_E_INVAL;
}
if (prog_.drafter.kind != RAD_DRAFT_NONE) {
@@ -2050,9 +2074,16 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
prog_.drafter_name.c_str(), nm);
return RAD_E_STATE;
}
if (d->depth <= 0) {
err(RAD_E_INVAL, "declare_drafter '%s': depth %d. A drafter that proposes nothing is not "
"declared at all -- leave the call out.", nm, d->depth);
if (history && (d->depth != 0 || prog_.ctx.max_spec != 0 || d->proposal ||
d->proposal_pitch || d->block || d->window || !prog_.ctx.calib_dir ||
!*prog_.ctx.calib_dir || prog_.ctx.calib_tokens <= 0)) {
err(RAD_E_INVAL, "declare_drafter '%s': HISTORY requires calibration, max_spec 0 and "
"no proposal or block", nm);
return RAD_E_INVAL;
}
if (!history && d->depth <= 0) {
err(RAD_E_INVAL, "declare_drafter '%s': depth %d. A speculative drafter must propose "
"at least one token.", nm, d->depth);
return RAD_E_INVAL;
}
if (prog_.ctx.max_spec > 0 && d->depth != prog_.ctx.max_spec) {
@@ -2128,7 +2159,7 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
/* A block drafter's proposal row holds its whole block's tokens, and the engine reads row s
* at s * pitch (a short block fills only its front), so its pitch defaults to depth; a serial
* one writes a token a pass, at pitch 1 by default. */
if (prog_.drafter.proposal_pitch == 0)
if (!history && prog_.drafter.proposal_pitch == 0)
prog_.drafter.proposal_pitch = prog_.drafter.kind == RAD_DRAFT_BLOCK ? prog_.drafter.depth : 1;
return RAD_OK;
}
+6 -2
View File
@@ -253,7 +253,10 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
}
/* ---------------------------------------------------------------- the drafter (spec §10) */
if (p.drafter.kind != RAD_DRAFT_NONE) {
if (p.drafter.kind == RAD_DRAFT_HISTORY) {
s += fmt("---- drafter: '%s', RAD_DRAFT_HISTORY -- calibration pass, no proposals\n\n",
p.drafter_name.c_str());
} else if (p.drafter.kind != RAD_DRAFT_NONE) {
const bool blk = p.drafter.kind == RAD_DRAFT_BLOCK;
s += fmt("---- drafter: '%s', %s, %d token(s) a step\n",
p.drafter_name.c_str(),
@@ -729,7 +732,8 @@ std::string dump_graph_json(const Program& p, Registry* r) {
if (p.drafter.kind != RAD_DRAFT_NONE) {
json d;
d["name"] = p.drafter_name;
d["kind"] = p.drafter.kind == RAD_DRAFT_BLOCK ? "block" : "serial";
d["kind"] = p.drafter.kind == RAD_DRAFT_HISTORY ? "history"
: p.drafter.kind == RAD_DRAFT_BLOCK ? "block" : "serial";
d["depth"] = p.drafter.depth;
if (p.drafter.kind == RAD_DRAFT_BLOCK) {
d["window"] = p.drafter.window;
+25
View File
@@ -15,6 +15,7 @@
#include <cstring>
#include <map>
#include <mutex>
#include <set>
namespace rad {
@@ -481,6 +482,30 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
if (s < 0) {
RAD_ERR("%s: rad_arch_declare returned %s", lp.arch_plugin.c_str(), rad_strerror(s));
for (const auto& e : b.errors()) RAD_ERR(" %s", e.c_str());
/* A plugin that needs an op it declared, and finds it resolved to no kernel, returns a
* status and may say nothing more. The ops no library serves in either domain are the
* usual reason on a card whose kernel library covers fewer forms, so they are listed with
* the constraint that refused each: the device's line, which names the form the card
* lacks. */
const Program& p = b.program();
std::set<std::pair<int32_t, std::string>> no_host;
for (const Program::Miss& m : p.misses)
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.index, m.span);
std::vector<std::string> unserved;
for (const Program::Miss& m : p.misses) {
if (m.domain != RAD_DOMAIN_DEVICE || !no_host.count({ m.index, m.span })) continue;
const std::string line = m.line();
if (std::find(unserved.begin(), unserved.end(), line) == unserved.end())
unserved.push_back(line);
}
if (!unserved.empty()) {
const size_t shown = std::min<size_t>(unserved.size(), 16);
RAD_ERR(" %zu op form(s) it declared before stopping have no kernel in the loaded "
"libraries, on the card or on the host; a plugin that needs one of them stops "
"where it finds that%s:", unserved.size(),
shown < unserved.size() ? " (the first 16)" : "");
for (size_t i = 0; i < shown; ++i) RAD_ERR(" %s", unserved[i].c_str());
}
return s;
}
+455 -3
View File
@@ -4,6 +4,7 @@
* (spec §6).
*/
#include "rad_core.h"
#include "sched/draft_depth.h" /* the --draft-depth-load lists */
#include "kld.h"
#include "format/rope_override.h"
#include "sample/host_ref.h"
@@ -76,6 +77,12 @@ static const Flag g_flags[] = {
"of the chunk step's time, auto:SHARE in SHARE of it (0-4];\n"
"0 lets every step carry a chunk; served default auto:1\n"
"(0 under --deterministic, KL mode, generators)" },
{ "--mixed-step-target-ms", "N", "soft duration target in milliseconds for a mixed prefill/decode\n"
"step. The scheduler learns an aggregate prefill cap from\n"
"completed mixed steps; 0 (default) is off" },
{ "--prefill-room-gate", "MODE", "on: a fresh prefill starts only when its whole prompt plus one\n"
"decode position fits beside every runner; off (the default)\n"
"admits a prompt when its first chunk fits" },
{ "--preempt-wait-ms", "N", "how long a preempted prefill may wait for the whole-\n"
"recompute gate before reclaiming cache blocks and\n"
"preempting the lowest-priority running request; 0\n"
@@ -159,6 +166,10 @@ static const Flag g_flags[] = {
" disabled -- the default, also with no flag at all -- loads\n"
" nothing: no projection op is declared, and a request that\n"
" asks for the vector is refused" },
{ "--control-vector-variant", "NAME", "list MODEL:NAME, a name of this model whose\n"
" requests run with the control vector on; the model's\n"
" own name keeps --control-vector's default. Needs\n"
" --control-vector off or on" },
{ "--deterministic", nullptr, "pin placement to the plan the loader made, so the resident\n"
" set cannot change under the heat engine. The sampler is\n"
" already order-independent and needs no pinning; note that\n"
@@ -167,10 +178,33 @@ static const Flag g_flags[] = {
{ "--checkpoint-interval","N", "linear-attention state checkpoint interval, in tokens" },
{ "--prefill-span", "N", "checkpoint intervals one step may carry of a prefill alone\n"
" in its step, from the prompt's second interval on (default\n"
" 1); needs --max-num-batched-tokens of N intervals. Every\n"
" 1); needs --max-num-batched-tokens of N intervals. Prompts\n"
" prefilling side by side with nothing decoding take such\n"
" steps one at a time, the fewest tokens left first. Every\n"
" other step is planned at the budget less the extra\n"
" intervals, and the checkpoints inside a span are not\n"
" written" },
{ "--prefill-span-pass", "MODE", "piece (default) | step -- the routed (MoE) block's pass of a\n"
" spanned step: a pass an interval, or one pass over the\n"
" whole step where the model runs such a step serially\n"
" (Flash-Next at one or two ranks). Each expert's weight is\n"
" then read once for all the step's rows; the arena grows by\n"
" the expert planes' extra rows and the output differs from\n"
" piece passes at tie level. Needs --prefill-span above 1" },
{ "--prefill-tail-snapshot", "MODE", "on (default): a prompt's last chunk ends where the\n"
" next turn's linear-state snapshot goes (prefix resume\n"
" nearest), leaving its last tokens a step of their own (a\n"
" lone spanned prefill on a model that snapshots inside a step\n"
" takes it inside the chunk, no step more); off: the last chunk\n"
" runs to the prompt's end, one step fewer, and a next turn\n"
" resumes up to an interval earlier" },
{ "--prefill-span-first", "MODE", "off (default) | on -- whether a lone prefill may span from\n"
" its first token; on: the first interval rides the span (its\n"
" rows read QSA's selection, the same keys as the dense pass\n"
" below the exactness bound, summed in another order)" },
{ "--prefill-span-min", "N", "the shortest prompt, in tokens, a prefill spans for: auto\n"
" (default) is 8 intervals where routed experts are read from\n"
" host memory and 0 elsewhere; 0 spans every lone prefill" },
/* A total, not per sequence: the snapshot store is one pool of N slots
* (KVManager::set_checkpoint_store). */
{ "--checkpoint-slots", "N", "linear-state or sliding-window snapshots the server holds in\n"
@@ -209,6 +243,63 @@ static const Flag g_flags[] = {
" couples the target's draw to it: more accepted drafts on sampled\n"
" requests, the same output law, other tokens than off for a fixed\n"
" seed" },
{ "--draft-verify", "MODE", "token (default, alias rowwise) | block | traversal -- how a coupled draft chain is\n"
" verified: token decides each row on its own (maximal coupling);\n"
" block decides the whole chain at once (Block Verification, arXiv\n"
" 2403.10444; switches --draft-coupling on); traversal decides a\n"
" root-to-leaf path bottom-up (Traversal Verification, arXiv\n"
" 2505.12398; needs --draft-coupling on). The same output law in\n"
" every mode, more drafts accepted per step in block and traversal" },
{ "--draft-depth", "MODE", "fixed (default) | adaptive -- a coupled serial chain stops within\n"
" the step once the product of the head's probabilities along it falls\n"
" below --draft-depth-stop, and the next verify carries only the drafts\n"
" made (1 .. --draft-depth-max). Same output law (the rule reads the\n"
" draft's own laws only); switches --draft-coupling on (an explicit\n"
" off is refused) and needs --draft-window fixed (both choose the\n"
" depth, so they are not served together)" },
{ "--draft-depth-max", "N", "--draft-depth adaptive: the deepest chain (default 0 =\n"
"num-speculative-tokens)" },
{ "--draft-depth-min", "N", "--draft-depth adaptive: rounds that always run (default 1)" },
{ "--draft-depth-stop", "P", "--draft-depth adaptive: the chain goes on while its confidence\n"
"is at least P (default 0.85)" },
{ "--draft-depth-lag", "K", "--draft-depth adaptive: rounds the decision trails the chain,\n"
"0 or 1 (default 1: the host decides while the next round runs)" },
{ "--draft-depth-stat", "S", "--draft-depth adaptive: top (default, each round's largest\n"
"probability) | path (the probability of the token it drew)" },
{ "--draft-depth-load", "MODE", "off (default) | on -- --draft-depth adaptive with several sequences\n"
" in a step: draft round j only for the rows whose expected accepted\n"
" drafts pay their verify\n"
" rows, the kernel tile they open and the round, at the measured\n"
" throughput; fewer sequences than --draft-depth-load-from keep the\n"
" stop rule. Same output law" },
{ "--draft-depth-load-from", "N", "--draft-depth-load: the fewest drafting sequences of a step the\n"
"load-aware rule decides (default 5)" },
{ "--draft-depth-load-min", "N", "--draft-depth-load: rounds a load-aware step always runs (default 2)" },
{ "--draft-depth-load-late", "MODE", "on (default) | off -- --draft-depth-load: choose each row's verified\n"
"drafts again when the next verify is issued, from the laws read by then" },
{ "--draft-depth-load-calib", "MODE", "--draft-depth-load: online (default; acceptance by confidence,\n"
" throughput and row/round/tile prices follow the running server) |\n"
" static (the built-in or given tables only)" },
{ "--draft-depth-load-tok-ms", "LIST", "--draft-depth-load: tokens a millisecond by drafting sequences\n"
"1..8, comma-separated (a short list repeats its last; default built in)" },
{ "--draft-depth-load-row-ms", "LIST", "--draft-depth-load: a verify row's milliseconds, by drafting\n"
"sequences 1..8" },
{ "--draft-depth-load-round-ms", "LIST", "--draft-depth-load: a draft round's milliseconds, by drafting\n"
"sequences 1..8" },
{ "--draft-depth-load-jump-ms", "LIST", "--draft-depth-load: what a verify of more than 16, 32, 48, 64\n"
"rows costs on top, in milliseconds (four numbers)" },
{ "--draft-suffix", "MODE", "off (default) | on -- SuffixDecoding as a step selector on a serial head's chain: when the\n"
"sequence's last --draft-suffix-min-match tokens occurred earlier in\n"
"its own prompt ++ output, a host-built step verifies the earlier\n"
"continuation (a chain, up to --draft-suffix-max rows) instead of the\n"
"head's draft. Lossless; works beside the fixed chain, --draft-verify\n"
"traversal and --draft-depth adaptive, not --draft-verify block" },
{ "--draft-suffix-min-match", "L", "shortest suffix match that selects a suffix step (default 6)" },
{ "--draft-suffix-max", "N", "most rows of a suffix step (default 7; the verify window becomes\n"
"max(--num-speculative-tokens, N), the head still drafts its own)" },
{ "--draft-suffix-min-score", "D", "cut the suffix chain where its path score (the product of the\n"
"follower frequencies along it, SuffixDecoding's D) falls under D\n"
"(default 0.3)" },
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
{ "--host", "ADDR", "listen address" },
@@ -225,8 +316,9 @@ static const Flag g_flags[] = {
" never access; repeatable" },
{ "--served-model-name", "NAME", "the model id /v1/models lists and responses carry; default the container's name" },
{ "--mm-max-patches", "N", "patches one encoder pass carries, and so the largest image (a patch is 16x16\n"
"pixels). Default `auto`: 16384 when the container carries a vision tower. 0\n"
"serves text only and keeps the tower off the card" },
"pixels). Default `auto`: 16384 when the container carries a vision tower (0 in a build\n"
"without a media decoder, which would refuse every media part). 0 serves text\n"
"only and keeps the tower off the card" },
{ "--image-gen-max-pixels", "N", "an image generator's largest image, in pixels (1048576: 1024 x 1024).\n"
" Default: the model's. Its per-image buffers, and the activation\n"
" arena with them, are sized for it; larger requests are refused" },
@@ -336,6 +428,25 @@ static const Flag g_flags[] = {
{ "--kld-lora-sources", "PREFIX", "--kld-lora only for documents whose source starts with PREFIX; the\n"
" rest run as the base, in the same steps (a mixed batch)" },
{ "--diagnose", "DIR", "instead of serving, run a fixed workload on this engine and write\n"
" diagnose.json and diagnose.md to DIR: decode by prompt category,\n"
" a concurrency sweep, a prefill sweep with decode at each depth and\n"
" a prompt arriving into running streams -- step times, tokens a\n"
" step, draft acceptance, TTFT, emission intervals, jitter. Prompts\n"
" are salted so the prefix cache serves none of them" },
{ "--diagnose-tokens", "N", "tokens a --diagnose decode stream generates (default 256)" },
{ "--diagnose-runs", "N", "measured runs of every --diagnose point, after one unmeasured (default 3)" },
{ "--diagnose-concurrency", "LIST", "stream counts of the concurrency sweep, comma-separated (default\n"
" 1,2,4,8; counts above --max-num-seqs are skipped and reported)" },
{ "--diagnose-prefill", "LIST", "prompt lengths of the prefill sweep in tokens, comma-separated\n"
" (default 1024,4096,16384,65536; lengths the context cannot hold\n"
" are skipped and reported)" },
{ "--diagnose-corpus", "FILE", "JSONL of category prompts, one {\"category\", \"messages\" or \"prompt\",\n"
" \"max_tokens\"?} a line; default: a built-in set of code, reasoning,\n"
" prose, json, file_edit and summarization prompts" },
{ "--diagnose-baseline", "FILE", "an earlier diagnose.json of the same workload: compare every request's\n"
" tokens with it and fail the run on any difference (parity)" },
{ "--debug-graph", nullptr, "print the entire declared graph and exit-quality detail" },
{ "--debug-selection", nullptr, "print the selection table" },
{ "--debug-placement", nullptr, "print the placement plan" },
@@ -443,6 +554,25 @@ static bool parse_int(const char* flag, const char* v, int64_t lo, int64_t hi, i
return true;
}
/* A comma-separated list of whole numbers (--diagnose-concurrency, --diagnose-prefill). An empty
* element, a trailing comma or a value out of range refuses the list rather than dropping it. */
static bool parse_int_list(const char* flag, const char* v, int64_t lo, int64_t hi,
std::vector<int>* out) {
std::vector<int> got;
const char* p = v;
for (;;) {
const char* comma = std::strchr(p, ',');
const std::string one(p, comma ? (size_t)(comma - p) : std::strlen(p));
int64_t n = 0;
if (!parse_int(flag, one.c_str(), lo, hi, &n)) return false;
got.push_back((int)n);
if (!comma) break;
p = comma + 1;
}
*out = std::move(got);
return true;
}
/* Sampler defaults are checked against the request range (server::sampler_value_ok) at startup;
* an out-of-range default would 400 every request that omits the field. */
static bool sampler_num(const char* flag, const char* field, const char* v, double* out) {
@@ -507,6 +637,18 @@ static bool parse_template_kwargs(const char* v, std::map<std::string, std::stri
return true;
}
/* A name a request may give as `model`, by the rule a fleet applies to model ids and aliases
* (fleet::valid_name, in a file this one does not include): not empty, and no ':' (reserved for
* base:adapter), whitespace or control character. */
static bool plain_name(const char* s) {
if (!*s) return false;
for (; *s; ++s) {
const unsigned char ch = (unsigned char)*s;
if (ch == ':' || std::isspace(ch) || std::iscntrl(ch)) return false;
}
return true;
}
/* Returns 0 on success, 1 for --help (caller exits 0), negative on a bad argument. An unknown flag
* is an error, not a warning, since a mistyped budget flag changes the plan. */
int config_parse(int argc, char** argv, Config* c) {
@@ -589,6 +731,13 @@ int config_parse(int argc, char** argv, Config* c) {
}
else if (!parse_int(a.c_str(), v, 0, 64, &c->prefill_interleave)) return RAD_E_INVAL;
}
else if (S("--mixed-step-target-ms")) { if (!num(0, 60000, &c->mixed_step_target_ms)) return RAD_E_INVAL; }
else if (S("--prefill-room-gate")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "on")) c->prefill_room_gate = true;
else if (!std::strcmp(v, "off")) c->prefill_room_gate = false;
else { RAD_ERR("--prefill-room-gate takes on or off -- got '%s'", v); return RAD_E_INVAL; }
}
else if (S("--preempt-wait-ms")) { if (!num(0, INT64_MAX, &c->preempt_wait_ms)) return RAD_E_INVAL; }
else if (S("--max-num-seqs")) { if (!num(1, INT64_MAX, &c->max_seqs)) return RAD_E_INVAL; }
else if (S("--max-model-len")) { if (!num(0, INT64_MAX, &c->max_ctx)) return RAD_E_INVAL; }
@@ -764,9 +913,50 @@ int config_parse(int argc, char** argv, Config* c) {
}
c->control_vector = v;
}
else if (S("--control-vector-variant")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!plain_name(v)) {
RAD_ERR("--control-vector-variant takes a name with no ':' or whitespace -- "
"got '%s'", v);
return RAD_E_INVAL;
}
c->control_vector_variant = v;
}
else if (S("--deterministic")) c->deterministic = true;
else if (S("--checkpoint-interval")) { if (!num(0, INT64_MAX, &c->checkpoint_interval)) return RAD_E_INVAL; }
else if (S("--prefill-span")) { if (!num(1, INT32_MAX, &c->prefill_span)) return RAD_E_INVAL; }
else if (S("--prefill-span-pass")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "piece")) c->prefill_span_step = false;
else if (!std::strcmp(v, "step")) c->prefill_span_step = true;
else {
RAD_ERR("--prefill-span-pass takes piece or step, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--prefill-tail-snapshot")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "on")) c->prefill_tail_snapshot = true;
else if (!std::strcmp(v, "off")) c->prefill_tail_snapshot = false;
else {
RAD_ERR("--prefill-tail-snapshot takes on or off, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--prefill-span-first")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "on")) c->prefill_span_first = true;
else if (!std::strcmp(v, "off")) c->prefill_span_first = false;
else {
RAD_ERR("--prefill-span-first takes on or off, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--prefill-span-min")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "auto")) c->prefill_span_min = -1;
else if (!parse_int(a.c_str(), v, 0, INT64_MAX, &c->prefill_span_min)) return RAD_E_INVAL;
}
else if (S("--checkpoint-slots")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "auto")) {
@@ -836,6 +1026,107 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
}
else if (S("--draft-verify")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "token") || !std::strcmp(v, "rowwise")) {
c->draft_verify_block = false;
c->draft_verify_traversal = false;
}
else if (!std::strcmp(v, "block")) { c->draft_verify_block = true; c->draft_verify_traversal = false; }
else if (!std::strcmp(v, "traversal")) { c->draft_verify_block = false; c->draft_verify_traversal = true; }
else {
RAD_ERR("--draft-verify takes token (rowwise), block or traversal, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--draft-depth")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "fixed")) c->draft_depth_adaptive = false;
else if (!std::strcmp(v, "adaptive")) c->draft_depth_adaptive = true;
else {
RAD_ERR("--draft-depth takes fixed or adaptive, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--draft-depth-max")) { if (!num(0, 16, &c->draft_depth_max)) return RAD_E_INVAL; }
else if (S("--draft-depth-min")) { if (!num(1, 16, &c->draft_depth_min)) return RAD_E_INVAL; }
else if (S("--draft-depth-lag")) { if (!num(0, 1, &c->draft_depth_lag)) return RAD_E_INVAL; }
else if (S("--draft-depth-stop")) {
if (!(v = need(i))) return RAD_E_INVAL;
double d = 0;
if (!parse_num(a.c_str(), v, &d)) return RAD_E_INVAL;
if (!(d >= 0.0 && d <= 1.0)) {
RAD_ERR("--draft-depth-stop must be a probability in [0, 1], not '%s'", v);
return RAD_E_INVAL;
}
c->draft_depth_stop = d;
}
else if (S("--draft-depth-stat")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "top")) c->draft_depth_stat = 0;
else if (!std::strcmp(v, "path")) c->draft_depth_stat = 1;
else {
RAD_ERR("--draft-depth-stat takes top or path, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--draft-depth-load") || S("--draft-depth-load-late")) {
if (!(v = need(i))) return RAD_E_INVAL;
bool b = false;
if (!std::strcmp(v, "off")) b = false;
else if (!std::strcmp(v, "on")) b = true;
else { RAD_ERR("%s takes off or on, not '%s'", a.c_str(), v); return RAD_E_INVAL; }
(S("--draft-depth-load") ? c->draft_depth_load : c->draft_depth_load_late) = b;
}
else if (S("--draft-depth-load-from")) { if (!num(2, 64, &c->draft_depth_load_from)) return RAD_E_INVAL; }
else if (S("--draft-depth-load-min")) { if (!num(1, 16, &c->draft_depth_load_min)) return RAD_E_INVAL; }
else if (S("--draft-depth-load-calib")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "online")) c->draft_depth_load_online = true;
else if (!std::strcmp(v, "static")) c->draft_depth_load_online = false;
else {
RAD_ERR("--draft-depth-load-calib takes online or static, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--draft-depth-load-tok-ms") || S("--draft-depth-load-row-ms") ||
S("--draft-depth-load-round-ms") || S("--draft-depth-load-jump-ms")) {
if (!(v = need(i))) return RAD_E_INVAL;
const bool jump = S("--draft-depth-load-jump-ms");
double probe[DraftDepthCfg::kLoadSeqs];
const int cap = jump ? (int)DraftDepthCfg::kJumps : (int)DraftDepthCfg::kLoadSeqs;
/* a price may be zero (a tile that costs nothing); a rate may not */
if (*v && draft_depth_parse_list(v, probe, cap, jump ? 0.0 : 1e-6, 1000.0) < 1) {
RAD_ERR("%s takes 1..%d comma-separated %s numbers, not '%s'", a.c_str(), cap,
jump ? "non-negative" : "positive", v);
return RAD_E_INVAL;
}
(S("--draft-depth-load-tok-ms") ? c->draft_depth_load_tok_ms
: S("--draft-depth-load-row-ms") ? c->draft_depth_load_row_ms
: S("--draft-depth-load-round-ms") ? c->draft_depth_load_round_ms
: c->draft_depth_load_jump_ms) = v;
}
else if (S("--draft-suffix")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "off")) c->draft_suffix = false;
else if (!std::strcmp(v, "on")) c->draft_suffix = true;
else {
RAD_ERR("--draft-suffix takes off or on, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--draft-suffix-min-match")) { if (!num(1, 12, &c->draft_suffix_min_match)) return RAD_E_INVAL; }
else if (S("--draft-suffix-max")) { if (!num(1, 32, &c->draft_suffix_max)) return RAD_E_INVAL; }
else if (S("--draft-suffix-min-score")) {
if (!(v = need(i))) return RAD_E_INVAL;
char* end = nullptr;
const double d = std::strtod(v, &end);
if (end == v || *end || !(d >= 0.0 && d <= 1.0)) {
RAD_ERR("--draft-suffix-min-score takes a number in [0, 1], not '%s'", v);
return RAD_E_INVAL;
}
c->draft_suffix_min_score = (float)d;
}
else if (S("--draft-model")) {
/* Refused, not ignored: separate draft models are not supported (spec §10), and the
* drafter comes from the container (rad-convert --draft-model merges one in; an MTP
@@ -1090,6 +1381,29 @@ int config_parse(int argc, char** argv, Config* c) {
c->calib_layer_hi = hi;
}
else if (S("--kld-out")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_out = v; }
else if (S("--diagnose")) { if (!(v = need(i))) return RAD_E_INVAL; c->diagnose = v; }
else if (S("--diagnose-tokens")) {
if (!(v = need(i))) return RAD_E_INVAL;
int64_t n = 0;
if (!parse_int(a.c_str(), v, 2, 1 << 20, &n)) return RAD_E_INVAL;
c->diagnose_tokens = (int)n;
}
else if (S("--diagnose-runs")) {
if (!(v = need(i))) return RAD_E_INVAL;
int64_t n = 0;
if (!parse_int(a.c_str(), v, 1, 100, &n)) return RAD_E_INVAL;
c->diagnose_runs = (int)n;
}
else if (S("--diagnose-concurrency")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!parse_int_list(a.c_str(), v, 1, 4096, &c->diagnose_concurrency)) return RAD_E_INVAL;
}
else if (S("--diagnose-prefill")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!parse_int_list(a.c_str(), v, 16, 1 << 24, &c->diagnose_prefill)) return RAD_E_INVAL;
}
else if (S("--diagnose-corpus")) { if (!(v = need(i))) return RAD_E_INVAL; c->diagnose_corpus = v; }
else if (S("--diagnose-baseline")) { if (!(v = need(i))) return RAD_E_INVAL; c->diagnose_baseline = v; }
else if (S("--kld-lora")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_lora = v; }
else if (S("--kld-lora-sources")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_lora_sources = v; }
else if (S("--debug-graph")) { c->debug_graph = true; c->debug_selection = true; }
@@ -1198,6 +1512,21 @@ int config_parse(int argc, char** argv, Config* c) {
RAD_ERR("--calib-corpus records into --calib-dir; give one");
return RAD_E_INVAL;
}
if (!c->control_vector_variant.empty()) {
if (c->control_vector == "disabled") {
RAD_ERR("--control-vector-variant needs --control-vector off or on: with no vector "
"loaded, '%s' would have nothing to switch on",
c->control_vector_variant.c_str());
return RAD_E_INVAL;
}
/* An adapter is named the same way, `base:name`, so the two must differ. */
for (const auto& [name, dir] : c->lora.adapters)
if (name == c->control_vector_variant) {
RAD_ERR("--control-vector-variant '%s' is also a --lora adapter's name, so a "
"request naming it could mean either; rename one", name.c_str());
return RAD_E_INVAL;
}
}
if ((!c->calib_dir.empty() || c->calib_layer_hi) && !c->calib() && c->kld_record.empty()) {
RAD_ERR("--calib-dir and --calib-layers belong to a --calib-corpus or --kld-record run");
return RAD_E_INVAL;
@@ -1219,6 +1548,19 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
/* ONE MODE A RUN. Each replaces serving with its own driver, so two given together would have
* to pick one silently; --debug-graph returns before either runs. */
if (!c->diagnose_mode() && (!c->diagnose_corpus.empty() || !c->diagnose_baseline.empty())) {
RAD_ERR("--diagnose-corpus and --diagnose-baseline belong to the --diagnose workload; give "
"--diagnose DIR as well");
return RAD_E_INVAL;
}
if (c->diagnose_mode() && (c->kld() || c->calib() || c->debug_graph)) {
RAD_ERR("--diagnose runs its own workload; it cannot be combined with --kld-record, --kld-ref, "
"--calib-corpus or --debug-graph");
return RAD_E_INVAL;
}
/* Runtime LoRA: the slot flags need slots, the named adapters must fit them, and KL mode's
* adapter is one of them. */
{
@@ -1292,6 +1634,69 @@ int config_parse(int argc, char** argv, Config* c) {
RAD_ERR("--video-min-pixels is above --video-max-pixels"); return RAD_E_INVAL; }
if (c->video_min_frames && c->video_max_frames && *c->video_min_frames > *c->video_max_frames) {
RAD_ERR("--video-min-frames is above --video-max-frames"); return RAD_E_INVAL; }
/* --prefill-span-pass step and --prefill-span-min shape a span, so they need one. */
if (c->prefill_span_step && c->prefill_span <= 1) {
RAD_ERR("--prefill-span-pass step is the routed pass of a spanned step and needs "
"--prefill-span above 1");
return RAD_E_INVAL;
}
if (c->prefill_span_min >= 0 && c->prefill_span <= 1) {
RAD_ERR("--prefill-span-min is the shortest prompt a span is taken for and needs "
"--prefill-span above 1");
return RAD_E_INVAL;
}
/* --draft-depth adaptive reads the coupled chain's laws and chooses the chain's depth itself. */
if (c->draft_depth_adaptive) {
if (c->given.count("--draft-coupling") && !c->draft_coupling) {
RAD_ERR("--draft-depth adaptive needs the coupled drafting (--draft-coupling on): the "
"stop rule reads the law each draft was drawn from");
return RAD_E_INVAL;
}
if (c->draft_window == DraftWindow::Adaptive) {
RAD_ERR("--draft-depth adaptive and --draft-window adaptive both choose the chain's "
"depth; serve one of them");
return RAD_E_INVAL;
}
if (c->draft_verify_block) {
RAD_ERR("--draft-depth adaptive is verified token by token or by traversal "
"(--draft-verify token | traversal), not as a fixed block");
return RAD_E_INVAL;
}
if (c->draft_depth_min > 1 && c->draft_depth_max > 0 && c->draft_depth_min > c->draft_depth_max) {
RAD_ERR("--draft-depth-min is above --draft-depth-max");
return RAD_E_INVAL;
}
c->draft_coupling = true;
}
/* --draft-depth-load weighs the adaptive chain's rounds; its late choice reads each round's
* largest probability, the one statistic that is not the drawn token's own. */
if (c->draft_depth_load) {
if (!c->draft_depth_adaptive) {
RAD_ERR("--draft-depth-load on needs --draft-depth adaptive: it decides the adaptive "
"chain's rounds for a step of several sequences");
return RAD_E_INVAL;
}
if (c->draft_depth_stat != 0) {
RAD_ERR("--draft-depth-load on needs --draft-depth-stat top: its tables and the late "
"choice of the verify's rows read each round's largest probability");
return RAD_E_INVAL;
}
}
/* --draft-verify block verifies a linear chain with the coupled drafting's states, so it
* switches the coupling on; traversal needs it and says so rather than switching it on. */
if (c->draft_verify_block) {
if (c->given.count("--draft-coupling") && !c->draft_coupling) {
RAD_ERR("--draft-verify block needs the coupled drafting (--draft-coupling on); "
"--draft-coupling off contradicts it");
return RAD_E_INVAL;
}
c->draft_coupling = true;
}
if (c->draft_verify_traversal && !c->draft_coupling) {
RAD_ERR("--draft-verify traversal requires --draft-coupling on: the walk needs the draft's "
"law Q, which only a coupled draft carries");
return RAD_E_INVAL;
}
/* --host-pool-mib is what the model pins for its weights in all; Config::host_pool_mib is a
* rank's share of it, whichever of the two options came first. */
if (pool_all) c->host_pool_mib /= std::max(c->tp, 1);
@@ -1352,6 +1757,10 @@ const ShowRow kShow[] = {
return c.prefill_interleave > 0 ? num(c.prefill_interleave)
: c.prefill_interleave < 0 ? "auto:" + std::to_string(c.prefill_interleave_share)
: std::string("off"); } },
{ "--mixed-step-target-ms", [](const Config& c) {
return c.mixed_step_target_ms > 0 ? num(c.mixed_step_target_ms) : std::string("off"); } },
{ "--prefill-room-gate", [](const Config& c) {
return c.prefill_room_gate ? std::string("on") : std::string("off"); } },
{ "--preempt-wait-ms", [](const Config& c) { return num(c.preempt_wait_ms); } },
{ "--max-num-seqs", [](const Config& c) { return num(c.max_seqs); } },
{ "--max-model-len", [](const Config& c) {
@@ -1393,9 +1802,16 @@ const ShowRow kShow[] = {
return o.empty() ? std::string(c.lora.enabled() ? "the adapters' own" : "-") : o; } },
{ "--placement", [](const Config& c) { return c.placement; } },
{ "--control-vector", [](const Config& c) { return c.control_vector; } },
{ "--control-vector-variant", [](const Config& c) {
return or_none(c.control_vector_variant, "none: no variant listed"); } },
{ "--deterministic", [](const Config& c) { return onoff(c.deterministic); } },
{ "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } },
{ "--prefill-span", [](const Config& c) { return num(c.prefill_span); } },
{ "--prefill-span-pass", [](const Config& c) { return std::string(c.prefill_span_step ? "step" : "piece"); } },
{ "--prefill-tail-snapshot", [](const Config& c) { return onoff(c.prefill_tail_snapshot); } },
{ "--prefill-span-first", [](const Config& c) { return onoff(c.prefill_span_first); } },
{ "--prefill-span-min", [](const Config& c) {
return c.prefill_span_min < 0 ? std::string("auto") : num(c.prefill_span_min); } },
{ "--checkpoint-slots", [](const Config& c) {
return c.checkpoint_slots < 0 ? std::string("auto") : num(c.checkpoint_slots); } },
{ "--no-prefix-cache", [](const Config& c) {
@@ -1413,6 +1829,29 @@ const ShowRow kShow[] = {
return c.draft_short_from < 0 ? std::string("auto")
: c.draft_short_from > 0 ? num(c.draft_short_from) : std::string("0 (never)"); } },
{ "--draft-coupling", [](const Config& c) { return onoff(c.draft_coupling); } },
{ "--draft-verify", [](const Config& c) {
return std::string(c.draft_verify_block ? "block" : c.draft_verify_traversal ? "traversal" : "token"); } },
{ "--draft-depth", [](const Config& c) { return std::string(c.draft_depth_adaptive ? "adaptive" : "fixed"); } },
{ "--draft-depth-max", [](const Config& c) {
return c.draft_depth_max > 0 ? num(c.draft_depth_max) : std::string("auto"); } },
{ "--draft-depth-min", [](const Config& c) { return num(c.draft_depth_min); } },
{ "--draft-depth-stop", [](const Config& c) { return fnum(c.draft_depth_stop); } },
{ "--draft-depth-lag", [](const Config& c) { return num(c.draft_depth_lag); } },
{ "--draft-depth-stat", [](const Config& c) { return std::string(c.draft_depth_stat == 1 ? "path" : "top"); } },
{ "--draft-depth-load", [](const Config& c) { return onoff(c.draft_depth_load); } },
{ "--draft-depth-load-from", [](const Config& c) { return num(c.draft_depth_load_from); } },
{ "--draft-depth-load-min", [](const Config& c) { return num(c.draft_depth_load_min); } },
{ "--draft-depth-load-late", [](const Config& c) { return onoff(c.draft_depth_load_late); } },
{ "--draft-depth-load-calib", [](const Config& c) {
return std::string(c.draft_depth_load_online ? "online" : "static"); } },
{ "--draft-depth-load-tok-ms", [](const Config& c) { return or_none(c.draft_depth_load_tok_ms, "builtin"); } },
{ "--draft-depth-load-row-ms", [](const Config& c) { return or_none(c.draft_depth_load_row_ms, "builtin"); } },
{ "--draft-depth-load-round-ms", [](const Config& c) { return or_none(c.draft_depth_load_round_ms, "builtin"); } },
{ "--draft-depth-load-jump-ms", [](const Config& c) { return or_none(c.draft_depth_load_jump_ms, "builtin"); } },
{ "--draft-suffix", [](const Config& c) { return onoff(c.draft_suffix); } },
{ "--draft-suffix-min-match", [](const Config& c) { return num(c.draft_suffix_min_match); } },
{ "--draft-suffix-max", [](const Config& c) { return num(c.draft_suffix_max); } },
{ "--draft-suffix-min-score", [](const Config& c) { return fnum(c.draft_suffix_min_score); } },
{ "--draft-model", [](const Config&) { return std::string("not implemented (the container's own drafter)"); } },
{ "--host", [](const Config& c) { return c.host; } },
{ "--port", [](const Config& c) { return num(c.port); } },
@@ -1502,6 +1941,19 @@ const ShowRow kShow[] = {
{ "--kld-out", [](const Config& c) { return or_none(c.kld_out, "none"); } },
{ "--kld-lora", [](const Config& c) { return or_none(c.kld_lora, "none (the base)"); } },
{ "--kld-lora-sources", [](const Config& c) { return or_none(c.kld_lora_sources, "every document"); } },
{ "--diagnose", [](const Config& c) { return or_none(c.diagnose, "off (serve)"); } },
{ "--diagnose-tokens", [](const Config& c) { return num(c.diagnose_tokens); } },
{ "--diagnose-runs", [](const Config& c) { return num(c.diagnose_runs); } },
{ "--diagnose-concurrency", [](const Config& c) {
std::string s;
for (int n : c.diagnose_concurrency) s += (s.empty() ? "" : ",") + num(n);
return s; } },
{ "--diagnose-prefill", [](const Config& c) {
std::string s;
for (int n : c.diagnose_prefill) s += (s.empty() ? "" : ",") + num(n);
return s; } },
{ "--diagnose-corpus", [](const Config& c) { return or_none(c.diagnose_corpus, "the built-in set"); } },
{ "--diagnose-baseline", [](const Config& c) { return or_none(c.diagnose_baseline, "none"); } },
{ "--debug-graph", [](const Config& c) { return onoff(c.debug_graph); } },
{ "--debug-selection", [](const Config& c) { return onoff(c.debug_selection); } },
{ "--debug-placement", [](const Config& c) { return onoff(c.debug_placement); } },
+232 -21
View File
@@ -21,11 +21,15 @@
* an invalidation. A slot is rewritten one lap after it was last read, so a system-scope
* acquire is placed at least once per half lap; without it every kernel after the first lap
* reads its predecessor's arguments. Slots are 1 KiB so no argument fetch shares a cache line
* with the next slot;
* with the next slot. No fence makes a write through the BAR arrive: the card's host data
* path is flushed in front of every doorbell (host_writes_out);
* - host-written memory: the first dispatch after the host waits on any queue takes a
* system-scope acquire, since host writes for the next step follow such a wait;
* - copies touching host or peer memory carry the scope themselves, as do the barrier packets
* that implement events and synchronisation.
*
* A chained kernel that has lost its barrier bit may go without the acquire (see "the acquire of a
* chained launch"): it reads behind a wait in its own prologue, long after its packet's acquire.
*/
#include "device.h"
@@ -225,6 +229,9 @@ struct Dev {
bool has_vram = false;
uint32_t kfd_id = 0; /* the driver's gpu_id: its sysfs and ioctls name it so */
bool host_kargs = false; /* no large BAR: the argument ring lives in host memory */
/* The card's host data path flush register (HSA_AMD_AGENT_INFO_HDP_FLUSH), where the host
* writes arguments into VRAM; see host_writes_out. */
volatile uint32_t* hdp_flush = nullptr;
};
struct Global {
@@ -441,6 +448,18 @@ bool init_devices() {
RAD_INFO("device: card %d (%s) keeps kernel arguments in pinned host memory, as a "
"test asked", i, bus);
}
if (!g.dev[(size_t)i].host_kargs) {
hsa_amd_hdp_flush_t hdp{};
if (hsa_agent_get_info(g.dev[(size_t)i].agent,
(hsa_agent_info_t)HSA_AMD_AGENT_INFO_HDP_FLUSH,
&hdp) == HSA_STATUS_SUCCESS)
g.dev[(size_t)i].hdp_flush = hdp.HDP_MEM_FLUSH_CNTL;
if (!g.dev[(size_t)i].hdp_flush)
RAD_WARN("device: card %d (%s) gives no host data path flush register, so a kernel "
"may start before the arguments written for it through the BAR have "
"reached VRAM; chained launches keep the packet processor's acquire, "
"which leaves them the time they had", i, bus);
}
}
/* Without the handler a fault falls back to the runtime's own handling, which the
* memory-fault report below replaces; warn at startup. */
@@ -600,6 +619,7 @@ struct Stream {
hsa_queue_t* q = nullptr;
uint64_t mask = 0;
char* karg = nullptr; /* VRAM the CPU writes through the BAR, or host memory */
volatile uint32_t* hdp = nullptr; /* Dev::hdp_flush where `karg` is VRAM */
std::atomic<bool> busy{false};
uint64_t wr = 0; /* next packet index */
uint64_t rd = 0; /* last read index seen */
@@ -662,7 +682,15 @@ uint32_t g_queue_gen[kMaxQueues];
* card takes them over. A kept queue holds its context save area on the card, about 41 MiB on an
* R9700 (24 of them 0.99 GiB, measured). The queues of a card are destroyed at process exit, and
* where the caller answers for nothing computing on the card (a_stream_trim). Keyed by card and
* priority. */
* priority.
*
* Handed out oldest first. The firmware puts a card's queues on its pipes in the order they were
* created, alternating; an engine's two compute lanes on one pipe run ~50% slower in decode than on
* two (2x R9700 under MES, read from the driver's queue table: slow if and only if lane 0 and lane 1
* shared a pipe, 119 of 119 requests). Bring-up keeps queues in an order where the newest two share
* a pipe and the two oldest do not, so last-in first-out paired the lanes. Measured on jarvis with
* the stock plugins (27B with DFlash2, Gemma 4 31B with MTP, tp 2): the same step times either way,
* the second lane being nearly idle in decode there. */
std::mutex g_spare_mu;
std::vector<Stream*> g_spare[kMaxDevices][2];
@@ -943,6 +971,40 @@ void report_running(int card) {
}
}
int64_t stuck_ms();
std::atomic<bool> g_stuck_watch{false};
/* Started by a stall verdict, at most one at a time: ends the process once the verdict has stood
* for dev_stuck_exit_ms (`scheduler.stuck-exit`; 0 never), and ends itself when the queues move
* again. Its own thread, because the threads that noticed the stall are the ones parked in the
* wait. Without the exit a hung device left the process up for good: /health answered 503, a
* SIGTERM could not drain a thread blocked in the driver, and a restart policy had nothing to
* act on. */
void stuck_watch() {
for (;;) {
std::this_thread::sleep_for(std::chrono::seconds(1));
const int64_t ms = stuck_ms();
const int64_t limit = rad::dev_stuck_exit_ms.load(std::memory_order_relaxed);
/* The load phase is exempt (device.h): a verdict standing before the first engine
* finished bringup is a slow load, not a hang, and killing on it trades a patient
* start for a crash loop. The dumps and the log line still fire -- an operator
* watching a stuck load sees the queue state exactly as before. */
if (limit > 0 && ms >= limit && rad::dev_engine_ready.load(std::memory_order_acquire)) {
dump_queues("the device");
fatal("the device has advanced nothing for %lld s (the queue dumps above name the "
"packets it is stuck on); exiting so a restart can bring the server back",
(long long)(ms / 1000));
}
if (ms > 0) continue;
g_stuck_watch.store(false, std::memory_order_release);
/* A verdict that landed between the read above and the store has no watcher yet. */
if (!g_stuck_at.load(std::memory_order_acquire) ||
g_stuck_watch.exchange(true, std::memory_order_acq_rel))
return;
}
}
/* Stall detector for a spin loop. tick() reads the clock every 64k iterations, a few thousand
* times a second at most.
*
@@ -978,9 +1040,23 @@ struct Stall {
g_stuck_progress.store(p, std::memory_order_relaxed);
g_stuck_at.store(steady_ns() - (uint64_t)kStallMs * 1000000u, std::memory_order_release);
dump_queues(where);
RAD_ERR("device: nothing has advanced in the %u s since: the GPU is not running the "
"packet named above -- a hung kernel, or a queue the driver evicted and could "
"not restore (amdgpu cwsr_enable=0 is one cause)", kStallMs / 1000);
/* The line says what follows the verdict. Before the first engine has finished
* bring-up the exit is not armed: a stall standing during a load is taken for a slow
* load (device.h's dev_engine_ready). */
if (rad::dev_engine_ready.load(std::memory_order_acquire))
RAD_ERR("device: nothing has advanced in the %u s since: the GPU is not running the "
"packet named above -- a hung kernel, or a queue the driver evicted and could "
"not restore (amdgpu cwsr_enable=0 is one cause). The process exits once this "
"has stood for scheduler.stuck-exit (%lld s; 0 never)", kStallMs / 1000,
(long long)(rad::dev_stuck_exit_ms.load(std::memory_order_relaxed) / 1000));
else
RAD_ERR("device: nothing has advanced in the %u s since: the GPU is not running the "
"packet named above -- a hung kernel, or a queue the driver evicted and could "
"not restore (amdgpu cwsr_enable=0 is one cause). The engine is still in "
"bringup, so scheduler.stuck-exit is not armed yet: this verdict is reported, "
"not fatal, until the first engine has finished loading", kStallMs / 1000);
if (!g_stuck_watch.exchange(true, std::memory_order_acq_rel))
std::thread(stuck_watch).detach();
return;
}
sampled = true;
@@ -1045,10 +1121,39 @@ inline int reserve(Stream* s, uint64_t* out) {
return RAD_OK;
}
/* What the host wrote for the card, on its way before the packets that read it are announced.
*
* An argument slot in VRAM is written through the BAR: the bytes sit in the processor's
* write-combining buffers until a store fence, and behind the link in the card's host data path,
* which hands them on to memory in its own time unless it is told to flush. Nothing orders that
* against the doorbell. A kernel the card starts soon enough after its packet was announced
* reads the slot as the launch a lap of the ring before left it: first its chain record, which
* it obeys (an old target, so no wait) or does not accept (so it counts nothing and the chained
* launch behind it waits for good), then, behind its wait, its arguments.
*
* On an R9700 "soon enough" is a microsecond or two. The packet processor's acquire holds a
* launch 0.9 us and an ordered launch waits for the kernel in front, which is all that keeps
* such a launch from it; a chained launch whose packet goes without the acquire starts that much
* sooner behind its doorbell. Runs of fourteen 256 KiB card-side copies issued one by one that
* way: back to back, six runs in nine of 300 000 ended with a unit moved by another launch's
* arguments; with the host quiet for 50 us behind each doorbell the queue stalled in its first
* lap, four runs in four, on either card. With the flush below neither happened (fourteen runs
* and four), nor did it with the acquire on the packets, with plain launches, or with a 2 us
* pause in front of each doorbell.
*
* The register is the driver's (HSA_AMD_AGENT_INFO_HDP_FLUSH, the remapped page it gives a
* process for this), and the store travels the link behind the slot's bytes and in front of the
* doorbell's: the order the driver's own submissions use. It goes in front of every doorbell, a
* chained launch's or not: no launch was ordered against the write. */
inline void host_writes_out(Stream* s) {
_mm_sfence();
if (s->hdp) *s->hdp = 1;
}
inline void publish(Stream* s, uint64_t idx, uint16_t header, uint16_t setup) {
s->wr = idx + 1;
hsa_queue_store_write_index_relaxed(s->q, idx + 1);
_mm_sfence(); /* the argument slot, written before the header */
host_writes_out(s); /* the argument slot, in VRAM before the header */
__atomic_store_n(reinterpret_cast<uint32_t*>(
static_cast<hsa_kernel_dispatch_packet_t*>(s->q->base_address) +
(idx & s->mask)),
@@ -1088,6 +1193,9 @@ struct TapeRec {
uint8_t chain = 0;
/* A collective's launch (a_peer_launch). */
uint8_t peer = 0;
/* A chained kernel whose library acquires for it in the kernel (chain_bare): played without
* its barrier bit, its packet takes no acquire from the packet processor. */
uint8_t bare = 0;
};
struct Tape {
@@ -1108,12 +1216,13 @@ inline bool capturing() { return t_tape && t_tape_pause == 0; }
/* A dispatch just written at `p` on `s`, with its argument block `ka`. */
void tape_note_dispatch(Stream* s, const hsa_kernel_dispatch_packet_t* p, uint16_t setup,
const unsigned char* ka, uint32_t n, uint8_t fence, bool chain) {
const unsigned char* ka, uint32_t n, uint8_t fence, bool chain, bool bare) {
Tape* t = t_tape;
TapeRec r;
r.kind = kTapeDispatch;
r.fence = fence;
r.chain = chain ? 1 : 0;
r.bare = chain && bare ? 1 : 0;
r.peer = t_peer ? 1 : 0;
r.s = s;
r.pkt = *p;
@@ -1134,21 +1243,77 @@ inline uint16_t header(hsa_packet_type_t type, int acq, int rel, bool barrier =
(rel << HSA_PACKET_HEADER_SCRELEASE_FENCE_SCOPE));
}
/* Whether the packet at `idx` must acquire at system scope, and the bookkeeping if it does. */
inline int acquire_scope(Stream* s, uint64_t idx, bool forced) {
/* Whether the packet at `idx` must acquire at system scope, and the bookkeeping if it does.
* `*asked` says the acquire is one the argument ring's half lap, a host write or the caller asks
* for, at whichever scope it comes back, and not the agent scope every dispatch takes besides. */
inline int acquire_scope(Stream* s, uint64_t idx, bool forced, bool* asked) {
const uint64_t ep = G().host_epoch.load(std::memory_order_acquire);
const bool lap = (int64_t)idx - s->last_sys_acq >= (int64_t)(kQueuePackets / 2);
if (forced || lap || s->epoch != ep) {
*asked = forced || lap || s->epoch != ep;
if (*asked) {
s->last_sys_acq = (int64_t)idx;
s->epoch = ep;
/* The prefetch stream reads nothing the host writes; a system acquire there would only
* invalidate the L2 under the compute stream. */
if (s->agent_only && !forced) return HSA_FENCE_SCOPE_AGENT;
/* The prefetch stream reads no data the host writes, so a host write or epoch does not
* make it acquire at system scope (that would only invalidate the L2 under the compute
* stream). Its own kernel arguments are host-written into its ring like any stream's,
* though: after the ring laps, an agent-scope acquire leaves the slot's old line in the
* L2 and a launch could run with the previous lap's arguments. The half lap keeps the
* system acquire: one in 2048 prefetch launches. */
if (s->agent_only && !forced && !lap) return HSA_FENCE_SCOPE_AGENT;
return HSA_FENCE_SCOPE_SYSTEM;
}
return HSA_FENCE_SCOPE_AGENT;
}
/* The acquire of a chained launch.
*
* A packet's acquire runs when the packet processor launches the kernel. A chained kernel that has
* lost its barrier bit is launched ahead and reads nothing then: it reads behind the wait in its
* prologue, once the launches in front have written, and acquires there itself. The packet's
* acquire guards nothing it reads, and the packet processor launches nothing else while it runs
* one. Measured on an R9700, a chain of small dependent kernels issued behind a gate: 2.1 us a
* launch with the agent-scope acquire, 1.2 us without (system scope costs what agent scope does;
* the same hand-over inside one persistent kernel, with no launch between, 0.3 to 0.6 us). In a
* pass that is time on the path only where a dependent launch reaches the card after the kernel
* it waits for has ended: ~65 of a Qwen3.8-Flash-Next verify pass's 664 dependent launches, the
* delta net's update behind its two overlapped launches first among them.
*
* The acquire did one thing by the way, for every kernel on the card: it emptied the scalar data
* cache. No fence a compiler puts in a kernel does (an agent-scope acquire is a global_inv: the
* vector caches), and a load whose address every lane shares is often a scalar one: a row's
* scale, a routing count, the activation a head reads. A chained form that reads such a value
* where the launch in front wrote it finds what an earlier launch read from that address, unless
* a later packet's acquire happened to fall in between. With an acquire on every packet it nearly
* always had (one launch in 1800 read stale in a probe of 1024-block readers); without, 1797 in
* 1800 did, and the model's text changed. So the acquire goes only where every chained form the
* engine can launch empties that cache itself behind its wait (RadKernelChainFn saying 2,
* rad_dev_chain_unfenced; `s_dcache_inv` in r4d_chain.h and chain_kernel.h), which also closes
* the window the fenced packets leave.
*
* Everything else keeps its acquire or release: the release (dropping it as well measured
* nothing), a packet that keeps its bit, a plain kernel, every barrier packet, and every acquire
* acquire_scope asks for: the argument ring's half lap, the first dispatch after a host wait, a
* copy over the link. Those guard what the kernel reads of its own slot, its arguments and chain
* record, which the host wrote where some launch read a lap ago and which the L2 would still
* hold; they are kept at whichever scope they come. The prefetch stream keeps the acquire on
* every packet: nothing waits for its launches, so there is nothing to gain.
*
* The acquire did a second thing by the way: it held the launch until the slot the host had
* just written was in VRAM, which nothing else saw to (host_writes_out). Without the flush
* there, a bare chained launch stopped a server: a chained card-side copy on a card's second
* queue never finished, and the queue stood on it with 14 packets written behind. So a
* card whose arguments are in VRAM and that gives no flush register keeps the acquire on its
* chained launches. RADIANCE_AQL_CHAIN_FENCE=1 keeps it on every chained launch, to rule this
* out. */
inline bool chain_bare(const Stream* s) {
static const bool keep = [] {
const char* e = std::getenv("RADIANCE_AQL_CHAIN_FENCE");
return e && *e == '1';
}();
if (keep || s->agent_only || rad_dev_chain_unfenced() == 0) return false;
return s->hdp != nullptr || G().dev[(size_t)s->ord].host_kargs;
}
/* Collectives on a shared card.
*
* A chained kernel launched behind a running one holds its wave slots while it waits in its
@@ -1162,7 +1327,7 @@ inline int acquire_scope(Stream* s, uint64_t idx, bool forced) {
* once. Nothing advances from there: Qwen3.8-27B prefilling beside Gemma 4 12B decoding, both on
* the same two R9700, stopped within 12 s.
*
* So on a card that more than one multi-card engine has claimed (a_cards_claim), a chained packet
* So on a card that more than one engine has claimed (a_cards_claim), a chained packet
* keeps its barrier bit while a collective's packet may be running on its queue. Only the
* collectives' own blocks then wait on the card for another card; everything else waiting there
* waits for kernels that finish by themselves. An engine alone on its cards pays nothing. */
@@ -1266,20 +1431,27 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
const bool chain = k->chained && rad_dev_chain_enabled() && s->chain_ctr &&
n <= RAD_CHAIN_KARG_OFF;
if (k->chained) chain_record(s, slot, chain, s->chain_issued);
if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence, chain);
const bool bare = chain && chain_bare(s);
if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence, chain, bare);
/* Attach the ride after the tape copied the packet: a recorded packet carries no signal, and
* a play attaches whichever ride is pending then (PlayRun::put). */
if (s->ride.handle) {
p->completion_signal = s->ride;
s->ride.handle = 0;
}
const int acq = acquire_scope(s, idx, (fence & kFenceAcquireSystem) != 0);
bool asked = false;
const int acq = acquire_scope(s, idx, (fence & kFenceAcquireSystem) != 0, &asked);
const int rel = (fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT;
/* Behind another chained kernel a chained one waits in its prologue; a completion signal keeps
* the bit, since its completion must cover everything before it. */
const bool keep = !(chain && s->prev_chained && !s->plain_inflight && !p->completion_signal.handle &&
!(s->peer_inflight && card_shared(s)));
publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, keep), setup);
/* Without the bit, a kernel that acquires for itself takes none from the packet processor,
* unless the ring or the host asked for this one. */
publish(s, idx,
header(HSA_PACKET_TYPE_KERNEL_DISPATCH,
bare && !keep && !asked ? HSA_FENCE_SCOPE_NONE : acq, rel, keep),
setup);
s->chain_frontier = s->chain_issued;
s->frontier_open = !keep;
if (chain) s->chain_issued += blocks_of(p);
@@ -1324,6 +1496,9 @@ struct PlayRun {
void ring() {
if (!unrung) return;
/* The chained records' argument slots (put) are VRAM the packets read as soon as they
* are announced. */
host_writes_out(s);
hsa_queue_store_write_index_relaxed(s->q, next);
hsa_signal_store_relaxed(s->q->doorbell_signal, (hsa_signal_value_t)(next - 1));
unrung = 0;
@@ -1400,7 +1575,8 @@ struct PlayRun {
chain_record(s, slot, true, dependent ? s->chain_issued : s->chain_frontier);
}
}
const int acq = acquire_scope(s, idx, (r.fence & kFenceAcquireSystem) != 0);
bool asked = false;
const int acq = acquire_scope(s, idx, (r.fence & kFenceAcquireSystem) != 0, &asked);
int rel = (r.fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT;
if (rel < rel_min) rel = rel_min;
/* A dispatch carrying a record keeps the bit: its completion must cover everything before
@@ -1419,7 +1595,12 @@ struct PlayRun {
stamp->ordered = ordered;
stamp->chained = chain;
}
const uint16_t h = header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, ordered);
/* Without the bit, a kernel that acquires for itself takes none from the packet
* processor, unless the ring or the host asked for this one (see "the acquire of a
* chained launch"). */
const uint16_t h = header(HSA_PACKET_TYPE_KERNEL_DISPATCH,
chain && r.bare && !ordered && !asked ? HSA_FENCE_SCOPE_NONE : acq,
rel, ordered);
__atomic_store_n(reinterpret_cast<uint32_t*>(p), (uint32_t)h | ((uint32_t)r.pkt.setup << 16),
__ATOMIC_RELEASE);
foreign = false;
@@ -1696,7 +1877,7 @@ int a_stream_create(RadStream* out, int high_priority) {
{
std::lock_guard<std::mutex> lk(g_spare_mu);
auto& v = g_spare[ord][high_priority ? 1 : 0];
if (!v.empty()) { r = v.back(); v.pop_back(); }
if (!v.empty()) { r = v.front(); v.erase(v.begin()); }
}
if (r) {
/* Every packet it held has completed (a_stream_destroy drained it), so its counters
@@ -1747,6 +1928,7 @@ int a_stream_create(RadStream* out, int high_priority) {
return RAD_E_DEVICE;
}
s->karg = static_cast<char*>(ka);
s->hdp = d.host_kargs ? nullptr : d.hdp_flush;
s->chain_ctr = reinterpret_cast<uint64_t*>(s->karg + (size_t)(s->mask + 1) * kKargSlot);
*reinterpret_cast<volatile uint64_t*>(s->chain_ctr) = 0;
_mm_sfence();
@@ -4603,6 +4785,32 @@ bool ride_reusable(void* token) {
std::lock_guard<std::mutex> lk(pool().mu);
return reusable(g);
}
int chain_probe(void* stream, unsigned* x, unsigned* seen, unsigned pairs, unsigned blocks) {
if (!ours(stream) || !x || !seen) return RAD_E_INVAL;
for (unsigned i = 0; i < pairs; ++i)
if (rad_aql_probe_store(x, i + 1u, stream) < 0 ||
rad_aql_probe_load(x, seen + (size_t)i * blocks, blocks, stream) < 0)
return RAD_E_DEVICE;
return RAD_OK;
}
int chain_asks(void* stream, const void* src, void* dst, uint64_t bytes, unsigned* seen, unsigned n) {
Stream* s = ours(stream);
if (!s || !src || !dst || !seen || !s->chain_ctr || bytes == 0 || (bytes & 15)) return RAD_E_INVAL;
for (unsigned i = 0; i < n; ++i)
if (rad_aql_probe_ask(src, dst, bytes, seen, i + 1u,
reinterpret_cast<unsigned long long*>(s->chain_ctr), stream) < 0)
return RAD_E_DEVICE;
return RAD_OK;
}
int chain_marks(void* stream, unsigned* seen, unsigned n) {
if (!ours(stream) || !seen) return RAD_E_INVAL;
for (unsigned i = 0; i < n; ++i)
if (rad_aql_probe_mark(seen, i + 1u, stream) < 0) return RAD_E_DEVICE;
return RAD_OK;
}
} // namespace aql
size_t aql_code_registered(void) { return a_code_mark(); }
@@ -4913,8 +5121,11 @@ hipError_t hipPeekAtLastError(void) {
namespace rad {
namespace aql {
/* A build without the AQL backend hands out no ride. */
/* A build without the AQL backend hands out no ride and launches no chain. */
bool ride_reusable(void*) { return false; }
int chain_probe(void*, unsigned*, unsigned*, unsigned, unsigned) { return RAD_E_UNSUPPORTED; }
int chain_marks(void*, unsigned*, unsigned) { return RAD_E_UNSUPPORTED; }
int chain_asks(void*, const void*, void*, uint64_t, unsigned*, unsigned) { return RAD_E_UNSUPPORTED; }
} // namespace aql
} // namespace rad
+25
View File
@@ -72,6 +72,25 @@ void set_next_fence(uint8_t f);
/* Whether the signal behind a rad_ride token could be handed out again now (tests/device_test.cpp). */
bool ride_reusable(void* token);
/* `pairs` launches of two chained kernels onto `stream`, one behind the other: the first stores
* i + 1 over the 64 words at `x`; the second loads x[0] the way a kernel loads a value all its
* lanes share (a scalar load) and each of its `blocks` blocks stores what it saw, at
* seen[i * blocks + block]. Every reader must have seen the store in front of it
* (tests/device_test.cpp). RAD_E_UNSUPPORTED in a build without the backend. */
int chain_probe(void* stream, unsigned* x, unsigned* seen, unsigned pairs, unsigned blocks);
/* `n` chained launches onto `stream`, launch i storing i + 1 at seen[i]: each takes where to
* store from its own arguments, so a launch that read another's leaves a word unwritten
* (tests/device_test.cpp). RAD_E_UNSUPPORTED in a build without the backend. */
int chain_marks(void* stream, unsigned* seen, unsigned n);
/* `n` chained launches onto `stream`, each a card-side copy of `bytes` (a multiple of 16) from
* `src` to `dst` that also stores at seen[i] whether it found a chain record in its argument
* slot: i + 1 if every block did, that with the top bit set if one did not. A block that found
* none still counts, so the launches behind it are not left waiting (tests/device_test.cpp).
* RAD_E_UNSUPPORTED in a build without the backend. */
int chain_asks(void* stream, const void* src, void* dst, uint64_t bytes, unsigned* seen, unsigned n);
} // namespace aql
} // namespace rad
@@ -90,4 +109,10 @@ int rad_aql_blit_fill(void* dst, int value, uint64_t bytes, void* stream);
/* rad_memcpy_ranges_async's kernel: `prefix` a multiple of 16, both bases 16-byte aligned. */
int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix, const RadCopyRange* ranges,
int n, void* stream);
/* aql::chain_probe's two kernels, aql::chain_marks's one and aql::chain_asks's one. */
int rad_aql_probe_store(unsigned* x, unsigned v, void* stream);
int rad_aql_probe_load(const unsigned* x, unsigned* seen, unsigned blocks, void* stream);
int rad_aql_probe_mark(unsigned* seen, unsigned v, void* stream);
int rad_aql_probe_ask(const void* src, void* dst, uint64_t bytes, unsigned* seen, unsigned v,
unsigned long long* ctr, void* stream);
}
+69
View File
@@ -250,6 +250,75 @@ extern "C" int rad_aql_blit_ranges(void* dst, const void* src, uint64_t prefix,
return launched();
}
/* aql::chain_probe's pair (aql.h). The reader's load has one address for the whole wave and
* nothing in the kernel writes there, so the compiler makes it a scalar load: served from the
* scalar data cache, which the wait must have emptied (chain_kernel.h) for the kernel to see the
* store in front of it. */
namespace {
__global__ __launch_bounds__(64) void r4dchain_probe_store(unsigned* __restrict__ x, unsigned v) {
rad_chain_wait();
x[threadIdx.x] = v;
rad_chain_done();
}
__global__ __launch_bounds__(32) void r4dchain_probe_load(const unsigned* __restrict__ x,
unsigned* __restrict__ seen) {
rad_chain_wait();
const unsigned v = x[0];
if (threadIdx.x == 0) seen[blockIdx.x] = v;
rad_chain_done();
}
/* aql::chain_marks's kernel: where it stores comes from its arguments alone. */
__global__ __launch_bounds__(32) void r4dchain_probe_mark(unsigned* __restrict__ seen, unsigned v) {
rad_chain_wait();
if (threadIdx.x == 0) seen[v - 1u] = v;
rad_chain_done();
}
/* aql::chain_asks's kernel: a card-side copy like r4dchain_copy16 that says whether there was a
* chain record in its argument slot when it started. A block that found none counts nothing in
* rad_chain_done, so it counts by the address in its arguments instead and the launches behind
* it do not wait for it for good. */
__global__ __launch_bounds__(kThreads) void r4dchain_probe_ask(const u32x4* __restrict__ src,
u32x4* __restrict__ dst, uint64_t n,
unsigned* __restrict__ seen, unsigned v,
unsigned long long* __restrict__ ctr) {
const bool found = rad_chain_rec() != nullptr;
rad_chain_wait();
const uint64_t stride = (uint64_t)gridDim.x * kThreads;
for (uint64_t i = (uint64_t)blockIdx.x * kThreads + threadIdx.x; i < n; i += stride) dst[i] = src[i];
if (threadIdx.x == 0)
__hip_atomic_fetch_or(&seen[v - 1u], found ? v : (v | 0x80000000u), __ATOMIC_RELAXED,
__HIP_MEMORY_SCOPE_AGENT);
rad_chain_done();
if (!found && threadIdx.x == 0)
__hip_atomic_fetch_add(ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
}
} // namespace
extern "C" int rad_aql_probe_ask(const void* src, void* dst, uint64_t bytes, unsigned* seen, unsigned v,
unsigned long long* ctr, void* stream) {
const uint64_t n = bytes / 16;
hipLaunchKernelGGL(r4dchain_probe_ask, dim3(blocks_for(n, 4 * kThreads)), dim3(kThreads), 0,
(hipStream_t)stream, (const u32x4*)src, (u32x4*)dst, n, seen, v, ctr);
return launched();
}
extern "C" int rad_aql_probe_mark(unsigned* seen, unsigned v, void* stream) {
hipLaunchKernelGGL(r4dchain_probe_mark, dim3(1), dim3(32), 0, (hipStream_t)stream, seen, v);
return launched();
}
extern "C" int rad_aql_probe_store(unsigned* x, unsigned v, void* stream) {
hipLaunchKernelGGL(r4dchain_probe_store, dim3(1), dim3(64), 0, (hipStream_t)stream, x, v);
return launched();
}
extern "C" int rad_aql_probe_load(const unsigned* x, unsigned* seen, unsigned blocks, void* stream) {
if (blocks == 0) return 0;
hipLaunchKernelGGL(r4dchain_probe_load, dim3(blocks), dim3(32), 0, (hipStream_t)stream, x, seen);
return launched();
}
extern "C" int rad_aql_blit_fill(void* dst, int value, uint64_t bytes, void* stream) {
if (bytes == 0) return 0;
const hipStream_t s = (hipStream_t)stream;
+5
View File
@@ -37,6 +37,11 @@ __device__ __forceinline__ void rad_chain_wait() {
__builtin_amdgcn_s_sleep(1);
__syncthreads();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
/* The fence empties the vector caches. A load every lane shares may be a scalar one, and the
* scalar data cache still holds what a launch read from the address before the launch in front
* of this one wrote it: only the packet processor's acquire empties that cache, and it runs
* when the kernel is launched, before the launch in front has written. */
asm volatile("s_dcache_inv" ::: "memory");
}
__device__ __forceinline__ void rad_chain_done() {
+27 -3
View File
@@ -12,6 +12,7 @@
#include "rad_abi.h"
#include "rad_device.h"
#include <atomic>
#include <cstdint>
#include <map>
#include <functional>
@@ -42,8 +43,18 @@ extern "C" void rad_dev_host_wrote(void);
* lets a chained kernel (named r4dchain*) wait in its prologue instead of behind the barrier bit.
* Only on the AQL backend, whose queues keep the completion counter, and only where the model's
* plugin measured a gain (RadArchProbe::chain_pays): with its drafter decoding speculatively, or
* with and without one (rad_dev_chain_infer, from the engine before any row resolves). */
* with and without one (rad_dev_chain_infer, from the engine before any row resolves).
*
* rad_dev_chain_infer(2) says more: every chained form this engine can launch fences itself
* (RadKernelChainFn saying 2, abi/rad_abi.h). rad_dev_chain_unfenced then answers 1, and the
* backend issues a chained launch that has lost its barrier bit without the packet processor's
* acquire as well (aql.cpp, "the acquire of a chained launch"). */
extern "C" int rad_dev_chain_enabled(void);
/* VRAM the runtime keeps resident as queue scratch on `props`' card once a kernel with a private
* segment has run (0 on the host backend and on unified memory). Charged to the VRAM budget with
* the hardware queues. */
extern "C" int64_t rad_dev_resident_scratch_bytes(const RadDeviceProps* props);
extern "C" int rad_dev_chain_unfenced(void);
extern "C" void rad_dev_chain_infer(int pays);
/* One range of a ranged copy: `bytes` from source offset `src` to destination offset `dst`, all
@@ -96,8 +107,8 @@ extern "C" int rad_link_hold(RadStream s, int on);
/* The launches this thread issues between `on` 1 and `on` 0 are a collective's: their blocks wait
* for the other ranks' blocks of the same launch on another card. A recorded pass keeps the mark.
*
* rad_dev_cards_claim tells the backend which cards an engine's collectives run on (`on` 1, once
* per engine with more than one rank) and that the engine is gone (`on` 0). On a card more than one
* rad_dev_cards_claim tells the backend which cards an engine uses (`on` 1, once per engine)
* and that the engine is gone (`on` 0). On a card more than one
* engine has claimed, nothing may wait on the card behind a collective except the collective's own
* blocks (aql.cpp, "collectives on a shared card"). A claim that makes a card shared returns once
* everything issued before it on that card's streams has finished. */
@@ -447,6 +458,19 @@ std::string dev_dma_lane(int device);
* tell. */
int64_t dev_stuck_ms();
/* How long the device may be stuck (dev_stuck_ms) before the backend ends the process, in ms; 0
* never. Set from `scheduler.stuck-exit` before serving; a backend that can tell reads it when a
* stall is standing. A device that has advanced nothing for a minute is not coming back: the
* reported hangs stood for hours, and a stall that clears does so within seconds. */
extern std::atomic<int64_t> dev_stuck_exit_ms;
/* Whether at least one engine has finished bringup. The stuck-exit watchdog reads it: a stall
* verdict standing DURING load is a slow load -- a cold start faulting a mapped tier from disk
* advances none of the counters the verdict watches, and that is legitimate work, not a hang.
* A watchdog that fires there turns one patient start into a supervisor's crash loop. Nothing
* disarms: the phase the flag exempts is only the engine's first. */
extern std::atomic<bool> dev_engine_ready;
/* Longest run of dispatches a played tape leaves unordered. Of any kTapeOverlapRun + 1
* consecutive packets on a queue one carries the barrier bit, so a launched packet still proves
* that everything more than that many packets earlier has completed. Argument slots and tape
+26 -8
View File
@@ -874,6 +874,8 @@ std::string dev_pci_address(int device) {
if (!dev()->pci_address) return std::string();
return dev_string(64, [&](char* b, int n) { return dev()->pci_address(device, b, n); });
}
std::atomic<int64_t> dev_stuck_exit_ms{60000};
std::atomic<bool> dev_engine_ready{false};
int64_t dev_stuck_ms() {
const auto f = dev()->stuck_ms;
return f ? f() : 0;
@@ -932,26 +934,40 @@ int rad_event_sync(RadEvent e) {
}
void rad_dev_host_wrote(void) { dev()->host_wrote(); }
/* The VRAM the runtime keeps as queue scratch on `p`'s card once kernels with a private segment
* (spill, or a local array: step_advance's) have been dispatched: the runtime hands a queue
* scratch memory at the first such dispatch, and the card showed +114 MiB after the first
* speculative step and kept it, 150 MiB with a larger segment. Left out of the budget, it is
* taken from the margin: serving ran with 27-65 MiB of a card free. 5 MiB a CU (the R9700 reports
* 32), 160 MiB, over the measured. */
extern "C" int64_t rad_dev_resident_scratch_bytes(const RadDeviceProps* p) {
if (!p || p->is_host_backend || p->unified) return 0;
return (int64_t)p->n_cu * (5LL * 1024 * 1024);
}
/* Whether launches chain, by engine: rad_dev_chain_infer on a thread of an engine (EngineScope)
* records that engine's answer and rad_dev_chain_enabled on any of its threads reads it. A process
* serves several models, each with its own plugin's answer; a single answer for the process was
* the answer of whichever model started last. Owner 0 is a thread outside every engine (a tool, a
* test). Only where the backend chains: the AQL backend writes the record a chained form reads,
* while a HIP launch carries only the kernel's own arguments. */
* while a HIP launch carries only the kernel's own arguments. The answer is 2 where every chained
* form the engine can launch fences itself (RadKernelChainFn saying 2), which
* rad_dev_chain_unfenced reads. */
static std::mutex g_chain_mu;
static std::map<int, int> g_chain_pays; /* by owner */
static std::map<int, int> g_chain_pays; /* by owner: 0, 1, or 2 (their packets unacquired) */
static std::atomic<uint64_t> g_chain_gen{1};
void rad_dev_chain_infer(int pays) {
{
std::lock_guard<std::mutex> lk(g_chain_mu);
g_chain_pays[rad::engine_owner()] = pays ? 1 : 0;
g_chain_pays[rad::engine_owner()] = pays == 2 ? 2 : pays ? 1 : 0;
}
g_chain_gen.fetch_add(1, std::memory_order_release);
}
int rad_dev_chain_enabled(void) {
/* Asked on every launch: a thread keeps its engine's answer until some answer changes. */
/* The calling thread's engine's answer where the backend chains, else 0: asked on every launch,
* so a thread keeps it until some answer changes. */
static int chain_mode() {
thread_local uint64_t seen = 0;
thread_local int owner = -1, on = 0;
thread_local int owner = -1, mode = 0;
const uint64_t gen = g_chain_gen.load(std::memory_order_acquire);
const int o = rad::engine_owner();
if (seen != gen || owner != o) {
@@ -961,12 +977,14 @@ int rad_dev_chain_enabled(void) {
const auto it = g_chain_pays.find(o);
if (it != g_chain_pays.end()) pays = it->second;
}
on = pays && std::strcmp(rad::device_backend_name(), "aql") == 0 ? 1 : 0;
mode = pays && std::strcmp(rad::device_backend_name(), "aql") == 0 ? pays : 0;
seen = gen;
owner = o;
}
return on;
return mode;
}
int rad_dev_chain_enabled(void) { return chain_mode() != 0; }
int rad_dev_chain_unfenced(void) { return chain_mode() == 2; }
int rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
return dev()->event_elapsed_ms(a, b, out);
+16
View File
@@ -126,6 +126,22 @@ struct Facts {
* process reads them only for its own cards. Null reads them for every card. */
Facts collect(const std::string& root, const std::vector<std::string>* managed = nullptr);
/* A CARD'S STATE AT ONE MOMENT, for --diagnose to read before and after each run: a run that
* starts hotter, or under a different performance level, than the one it is compared with is
* measuring a different card. Read under the same root as collect(); unreadable fields stay unknown.
* The power-management files are answered by the SMU under its lock, so this is read between
* runs, never during one. */
struct CardSample {
std::string bdf;
int64_t edge_mc = -1, junction_mc = -1, mem_mc = -1; /* hwmon temperatures, millidegrees C */
int64_t power_uw = -1; /* power1_average, else power1_input */
std::string perf_level; /* power_dpm_force_performance_level: auto, high, profile_peak, ... */
std::string sclk_cur, mclk_cur; /* the DPM level marked current, as the driver lists it */
int busy_percent = -1;
};
std::vector<CardSample> sample_cards(const std::string& root, const std::vector<std::string>& bdfs);
/* Fills what only a system call answers for the live process: the memlock limit and whether
* io_uring is allowed (a container's seccomp profile may refuse it). */
void probe_process(HostFacts* h);
File diff suppressed because it is too large. Load diff
+279
View File
@@ -0,0 +1,279 @@
/* diagnose.h -- the --diagnose mode's arithmetic and its report.
*
* `radiance --diagnose DIR` starts the engine as it would to serve, then runs a fixed workload on
* itself instead of listening (core/engine_diagnose.cpp) and writes DIR/diagnose.json and
* DIR/diagnose.md. This file is the part with no device and no scheduler in it: the step record
* the scheduler keeps, the statistics a phase reduces to, and the report. The driver feeds it;
* tests/diagnose_test.cpp holds it to hand-computed numbers.
*
* WHY THE ENGINE MEASURES ITSELF. The numbers an operator wants -- milliseconds a decode step,
* tokens a step, how often a draft is taken, how long a prefill takes, how uneven the steps are --
* are all known inside the engine exactly, and outside it only through a client's clock and a
* stream that delivers a speculative step's tokens in one burst. A client measuring inter-token
* latency on a speculating engine is measuring the burst pattern; the engine knows the steps.
*
* WHAT A PHASE REPORTS, AND FROM WHERE.
* - SchedMetrics deltas taken while the engine is idle at the phase's edges: exact counts of
* steps by shape, tokens, drafts proposed and accepted, per draft position.
* - One StepRecord per step, written by the scheduler (Scheduler::step_finished): what the step
* carried and how long it took. From these: the distribution of decode step times, the
* interval between consecutive emissions (what a stream sees between token bursts), and the
* slowest steps against typical ones.
* - Each request's sink: admitted, first token, last token, tokens -- TTFT and stream rate.
* A quantity the run cannot measure is reported as absent with the reason, never as 0.
*/
#pragma once
#include "sched/metrics.h"
#include "util/json.h"
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
namespace diag {
struct Facts;
struct RunFacts;
struct Finding;
struct CardSample;
using json = Json;
/* ONE ENGINE STEP, as the scheduler commits it. Plain data, fixed size: the scheduler writes one
* per step under its own lock into a ring sized at init, so recording costs a store and no
* allocation on the step path. */
struct StepRecord {
int64_t step = 0; /* SchedMetrics::steps after this step: a run-wide ordinal */
int32_t phase = 0; /* RAD_PHASE_PREFILL / DECODE / MIXED of the step's plan */
int32_t n_seq = 0; /* sequences the step carried */
int32_t prefill_tok = 0; /* prompt tokens it computed */
int32_t decode_tok = 0; /* tokens it committed to decoding sequences, accepted drafts included */
int64_t ns = 0; /* inside the step, the clock SchedMetrics::step_ns charges */
int64_t end_ns = 0; /* steady clock when it was committed: emissions are spaced by these */
};
/* A FIXED-CAPACITY RING OF STEP RECORDS with a run-wide sequence number. The writer and every
* reader hold the scheduler's lock, so it needs no atomics of its own. A reader asks for what
* came after a sequence number it saved; if the ring has lapped since, the records it lost are
* counted, not invented. */
class StepRing {
public:
explicit StepRing(size_t capacity = 0) { reset(capacity); }
void reset(size_t capacity);
void push(const StepRecord& r) noexcept;
uint64_t count() const { return n_; } /* records ever pushed */
size_t capacity() const { return buf_.size(); }
/* Appends every record with sequence number >= `from` still in the ring to `out`; returns how
* many after `from` were overwritten before they could be read. */
uint64_t copy_since(uint64_t from, std::vector<StepRecord>* out) const;
private:
std::vector<StepRecord> buf_;
uint64_t n_ = 0;
};
/* ------------------------------------------------------------------ statistics */
/* Quantiles by nearest rank over a copy of the samples. `n == 0` means there were none, and every
* other field is then meaningless; the JSON form says null rather than 0. */
struct Quantiles {
int64_t n = 0;
double min = 0, p50 = 0, p90 = 0, p99 = 0, max = 0, mean = 0;
};
Quantiles quantiles(std::vector<double> v);
json to_json(const Quantiles& q);
/* What a request's sink recorded, on one steady-clock axis (Sink::t_start_ns + its offsets). -1
* where the sink never saw the event. */
struct RequestTiming {
int64_t start_ns = -1; /* the sink's construction: before submission */
int64_t admitted_ns = -1; /* the scheduler first gave it a step */
int64_t first_ns = -1; /* first token */
int64_t last_ns = -1; /* last token */
int64_t tokens = 0; /* produced */
int32_t prompt = 0; /* prompt tokens */
int32_t cached = 0; /* of those, served from the prefix cache */
int64_t drafted = 0;
int64_t accepted = 0;
bool ok = false; /* finished on length or stop, not on an error or a cancel */
bool stopped = false; /* finished on the model's own end of sequence, not on length */
std::vector<int32_t> output; /* the tokens it produced, for the parity comparison */
};
enum class PhaseKind { Decode, Prefill };
struct PhaseInput {
std::string name;
PhaseKind kind = PhaseKind::Decode;
int streams = 1;
int64_t wall_ns = 0;
SchedMetrics before, after;
std::vector<StepRecord> steps; /* the steps the phase ran, in order */
uint64_t steps_lost = 0; /* records the ring overwrote before they were read */
std::vector<RequestTiming> requests;
/* The serving cards' state before and after the run ({"start": [...], "end": [...]}, each
* card_samples_json), null when the driver read none. */
json cards;
};
/* The phase's section of the report. Every derived number names what it was derived from. */
json phase_report(const PhaseInput& in);
/* The slowest steps of one shape against the typical ones: the slowest `max(3, 1%)` decode steps
* with what they carried, and the median step beside them, so a reader can tell a step that was
* slow because it carried more from one that was slow carrying the same. */
json slow_steps(const std::vector<StepRecord>& steps, int phase);
/* DRAFT ACCEPTANCE BY POSITION, POOLED OVER A POINT'S RUNS: at each position the verifies that
* reached it and the share of those that took it, summed over the runs rather than a median of
* per-run rates, because a run reaches the deep positions only a few times. This is the curve an
* adaptive draft depth is tuned against. */
json pool_draft_positions(const std::vector<json>& runs);
/* THE RUNS OF ONE MEASUREMENT POINT, reduced to what a reader compares: for each headline number
* of phase_report, the median over the runs and the smallest and largest run. A run that has no
* value for a number does not count toward it; a number no run had is null. */
json summarize_runs(const std::vector<json>& runs);
/* The same over the numbers at the given JSON pointers, keyed by the pointer with '/' as '.'. */
json summarize_paths(const std::vector<json>& runs, const std::vector<std::string>& paths);
/* ------------------------------------------------------------------ reproducibility */
/* A headline number whose runs spread wider than this, as (max - min) / median, makes the point
* UNSTABLE in the report's stability section: the runs disagree by more than most changes a
* comparison is run to find. */
constexpr double kMaxSpreadPct = 5.0;
/* Runs of one report that start this many degrees apart (junction, else edge) began on cards in
* different thermal states. */
constexpr double kMaxStartTempSpreadC = 10.0;
/* The cards' samples as JSON: temperatures in degrees C, power in W, the performance level and the
* current DPM levels; an unknown field is null. */
json card_samples_json(const std::vector<CardSample>& samples);
/* WHAT THE RUN RAN ON, so two reports can be told comparable or not: the engine build, the host
* settings that move a step's time (CPU governor and energy preference, kernel, device runtime,
* THP, IOMMU mode) and the serving cards (rank >= 0) with their DPM ranges, power cap against its
* default, voltage offset, runtime power management and link. No path and no command line: the
* report is pasted into issues. `findings` are the startup report's (diag::check) and are listed
* with their fix. `fingerprint` hashes everything but the findings, whose text carries load-
* dependent numbers. */
json conditions_report(const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
/* The fields of two reports' `conditions` that differ, as {"field", "now", "baseline"} with the
* field as a JSON pointer; empty when they ran under the same conditions. */
json conditions_differences(const json& now, const json& base);
/* RUN-TO-RUN AGREEMENT. For each measured point the headline numbers -- aggregate and per-step
* decode rate for each category prompt (its `prompts_summary`; the category's own summary pools
* prompts that differ by design) and each concurrency point, TTFT and prefill rate for the prefill sweep, the arriving
* prompt's TTFT for interference -- whose spread_pct exceeds `max_spread_pct`. `verdict` is
* "stable", "UNSTABLE" or "not judged" (no point has two runs). */
json stability_report(const json& report, double max_spread_pct = kMaxSpreadPct);
/* THE CARDS ACROSS THE MEASURED RUNS: per card the start and end temperatures' range and the
* performance levels seen, from each run's `cards`. `warnings` names a start-temperature spread
* above kMaxStartTempSpreadC and a performance level that changed during the report. */
json thermal_report(const json& report);
/* A DECODE STALL: what a prompt arriving into running streams costs them. `from`..`to` is the
* window from the new request's admission to its first token; the report gives the longest gap
* between two emissions that overlaps it, against the median gap of the emissions before it. */
json interference_report(const std::vector<StepRecord>& steps, int64_t from_ns, int64_t to_ns);
/* ------------------------------------------------------------------ parity */
/* WHAT TWO RUNS OF THE SAME WORKLOAD PRODUCED, COMPARED TOKEN FOR TOKEN. With the same prompts and
* the same seed per request, a build whose logits are bit-identical samples identical tokens, at
* any temperature -- so every request of the categories, the concurrency sweep and the prefill
* sweep is a parity check of the paths it ran: long prefills, attention at depth, batched decode.
* The interference point is left out: when its running streams are cancelled depends on timing.
*
* `now` and `base` are whole reports. Points are matched by their key (category, streams,
* requested tokens), runs and requests by position. The result counts identical and differing
* requests and names, for each difference, the first token where they part; a point or run that
* only one side has is listed as missing rather than counted as either. Two reports of different
* workloads (workload.fingerprint) are refused with RAD_E_INVAL: their prompts differ. */
/* Beside the tokens it compares each matched point's draft acceptance: identical for
* bit-identical builds, and the first number to move when a build computes less accurately. The
* overall rate by a one-sided paired t test over the requests (same prompt and seed on both
* sides), the positions by the pooled two-proportion z divided by the square root of the
* dispersion the requests show; either as unlikely as z below -3 is a drop, listed in
* `acceptance_dropped`, and makes `acceptance_verdict` "DROPPED". */
int compare_outputs(const json& now, const json& base, json* out, std::string* why);
/* The part of a report's workload that decides which prompts and seeds it ran: equal fingerprints
* mean comparable outputs. */
std::string workload_fingerprint(const json& workload_params);
/* ------------------------------------------------------------------ workload */
/* ONE PROMPT OF THE CATEGORY WORKLOAD: OpenAI-style chat messages and the category they are
* reported under. `max_tokens` 0 means the run's --diagnose-tokens. */
struct CorpusEntry {
std::string category;
json messages;
int max_tokens = 0;
};
/* A small built-in corpus, a few prompts in each of the categories a chat deployment typically
* serves (code, reasoning, prose, json, file_edit, summarization), so a run without a corpus file
* still reports by category. Speculative decoding accepts very differently across these, which is
* why one decode number is not enough. */
std::vector<CorpusEntry> builtin_corpus();
/* Reads a corpus file: one JSON object a line, `{"category": "...", "messages": [...]}` or
* `{"category": "...", "prompt": "..."}`, optionally with "max_tokens". Blank lines and lines
* starting with '#' are skipped. Any other malformed line refuses the file, naming the line. */
int load_corpus(const std::string& path, std::vector<CorpusEntry>* out, std::string* why);
/* THE SAME MESSAGES MADE UNIQUE FROM THEIR FIRST CHARACTER. `tag` is put at the head of the first
* message's content, so no two requests of a run share a prefix longer than the chat template's
* own opening -- less than one cache block -- and the prefix cache cannot serve one from another.
* The tag is deterministic (a request counter), so two builds see the same prompts; a hit from a
* cache tier that outlived the process is caught by the driver's check of RequestTiming::cached. */
json salt_messages(const json& messages, const std::string& tag);
/* A deterministic document of about `chars` characters: numbered sections of fixed prose, every
* section different in its numbers, so a prefix cache cannot serve one run's text to the next
* when `salt` differs. Language-neutral enough to tokenise under any vocabulary. */
std::string synthetic_document(int64_t chars, uint32_t salt);
/* The decode prompts, one per stream: fixed instructions that ask for long prose, distinct per
* stream so eight streams are eight conversations and not one prompt eight times. */
std::string decode_prompt(int stream);
/* ------------------------------------------------------------------ report */
/* The environment the workload ran under: the NAMES of the variables in `env` (environ-shaped,
* null-terminated) that are on a fixed list of the engine's configuration knobs, sorted. Names
* only, never values: a value may be a path, a host name or a token, and the report is pasted into
* issues and committed beside a baseline (diag/diag.h's env_names states the same rule for the
* startup report).
*
* A fixed list, not a prefix: a prefix admits every suffix, so `RADIANCE_API_KEY_<anything>` is a
* name the report would print. A name the engine does not read as configuration is not reported. */
std::vector<std::string> env_allowlist(char* const* env);
/* The engine section of a report, built from the engine's /server_info object: the model's
* architecture, quantisation and shapes, and the cards it ran on. The object itself is not copied,
* because its `container` is the model's path and its control vector carries a file, and the report
* is pasted into issues: a path names a person's home directory and nothing a reader needs. */
json engine_report(const json& server_info);
/* The Markdown view of a report: one table each for the categories, the concurrency sweep, the
* prefill sweep and the interference point, from their `summary` sections plus the driver's
* header. It reads only the JSON, so it can be regenerated from a saved diagnose.json; the
* per-run detail stays in the JSON. It carries no path either: the header names the model by its
* architecture and quantisation (engine_report), never by where it is stored. */
std::string render_markdown(const json& report);
} /* namespace diag */
} /* namespace rad */
+42
View File
@@ -423,6 +423,48 @@ Facts collect(const std::string& root, const std::vector<std::string>* managed)
return f;
}
std::vector<CardSample> sample_cards(const std::string& root, const std::vector<std::string>& bdfs) {
/* The line the driver marks with '*', without the mark and the level's index: "2350Mhz". */
auto current = [](const std::string& path) {
std::istringstream in(slurp(path));
std::string l;
while (std::getline(in, l)) {
if (l.find('*') == std::string::npos) continue;
l.erase(std::remove(l.begin(), l.end(), '*'), l.end());
const size_t colon = l.find(':');
return trim(colon == std::string::npos ? l : l.substr(colon + 1));
}
return std::string();
};
std::vector<CardSample> out;
for (const std::string& bdf : bdfs) {
const std::string dev = root + "/sys/bus/pci/devices/" + bdf;
CardSample c;
c.bdf = bdf;
c.perf_level = line(dev + "/power_dpm_force_performance_level");
c.sclk_cur = current(dev + "/pp_dpm_sclk");
c.mclk_cur = current(dev + "/pp_dpm_mclk");
c.busy_percent = (int)num(dev + "/gpu_busy_percent", -1);
for (const std::string& h : list(dev + "/hwmon")) {
const std::string hp = dev + "/hwmon/" + h;
/* amdgpu labels its sensors; an unlabelled temp1 is the edge sensor. */
for (int t = 1; t <= 8; ++t) {
const std::string base = hp + "/temp" + std::to_string(t);
const int64_t v = num(base + "_input", -1);
if (v < 0) continue;
const std::string label = line(base + "_label");
if (label == "edge" || (label.empty() && t == 1)) c.edge_mc = v;
else if (label == "junction") c.junction_mc = v;
else if (label == "mem") c.mem_mc = v;
}
if (c.power_uw < 0) c.power_uw = num(hp + "/power1_average", -1);
if (c.power_uw < 0) c.power_uw = num(hp + "/power1_input", -1);
}
out.push_back(std::move(c));
}
return out;
}
void probe_process(HostFacts* h) {
struct rlimit rl{};
if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0)
+214 -24
View File
@@ -401,6 +401,7 @@ int Engine::park(int64_t drain_ms, const PageOut& req, PageResult* got, std::str
spare.push_back({ (const char*)r->ctx.arena_base() + fixed, top - fixed });
}
if (!spare.empty()) dev_page_discard(owner_, spare);
xflex_restore_.clear();
(void)xflex_settle();
if (cfg_.prefix_cache) (void)sched_.reset_prefix_cache();
const auto t2 = clk::now();
@@ -542,6 +543,7 @@ int64_t Engine::xflex_give(int64_t bytes) {
}
(void)rad_dev_set(ranks_[0]->device);
const int64_t left = xflex_settle();
xflex_restore_.recalled(cur, left);
xflex_retry_ns_ = rad_mono_ns() + 5000000000ull;
const int64_t got = std::max<int64_t>(cur - left, 0);
if (got > 0)
@@ -550,8 +552,10 @@ int64_t Engine::xflex_give(int64_t bytes) {
return got;
}
/* Every tenth of a second on the step loop. While the engine has been busy in the last five
* seconds, the slab grows a GiB at a time into memory the fleet says no model holds, and grows
/* Every tenth of a second on the step loop. While recently busy, or restoring backing a
* peer's recall removed, the slab grows a GiB at a time into memory the fleet says no model
* holds. Idle restoration stops at its previous watermark and never advertises eviction demand.
* The slab grows
* again only once the units fill what it already has, leaving no more than the turnover slots and
* half a step empty (an empty slot is VRAM nothing uses). A refusal is remembered, so the fleet
* can make room for it (expert_flex_wanted), and asked again a second later; a backing that fails
@@ -563,20 +567,27 @@ void Engine::xflex_tick(bool busy) {
if (now - xflex_ns_ < 100000000ull) return;
xflex_ns_ = now;
const int64_t cur = xflex_bytes_.load(std::memory_order_acquire);
if (cur >= xflex_cap_ || now - xflex_busy_ns_ > 5000000000ull) {
const bool idle_restore = now - xflex_busy_ns_ > 5000000000ull;
const int64_t restore_limit = xflex_restore_.limit(cur, xflex_cap_);
const int64_t limit = idle_restore ? restore_limit : xflex_cap_;
// Clear a previous busy demand even when retry or occupancy stops this attempt.
// Background restoration must not ask the fleet to evict an idle peer.
if (idle_restore) xflex_want_.store(0, std::memory_order_release);
if (cur >= limit) {
xflex_want_.store(0, std::memory_order_release);
return;
}
if (now < xflex_retry_ns_) return;
if (now < xflex_retry_ns_ || (idle_restore && !xflex_restore_.ready(now))) return;
const Mover& m0 = ranks_[0]->mover;
const int64_t g = std::max<int64_t>(VMem::granularity(), 1);
const int64_t step = std::min<int64_t>(((int64_t)1 << 30) / g * g, xflex_cap_ - cur);
const int64_t step = std::min<int64_t>(((int64_t)1 << 30) / g * g, limit - cur);
/* Still filling: what the loans offer and no unit holds, past the slots kept free for swaps. */
const int64_t kept = m0.turnover_bytes();
if (m0.flex_offered_bytes() - m0.flex_used_bytes() > kept + step / 2) return;
if (!broker_->flex_grow(rank_devices(), step)) {
xflex_want_.store(xflex_cap_ - cur, std::memory_order_release);
xflex_retry_ns_ = now + 1000000000ull;
xflex_want_.store(xflex_restore_.refused(now, idle_restore, xflex_cap_ - cur),
std::memory_order_release);
if (!idle_restore) xflex_retry_ns_ = now + 1000000000ull;
return;
}
struct Landed { VramBroker* b; ~Landed() { b->flex_done(); } } landed{ broker_ };
@@ -606,6 +617,10 @@ void Engine::xflex_tick(bool busy) {
(void)rad_dev_set(ranks_[0]->device);
xflex_bytes_.store(to, std::memory_order_release);
xflex_want_.store(0, std::memory_order_release);
(void)xflex_restore_.limit(to, xflex_cap_);
if (idle_restore && to >= restore_limit)
RAD_INFO("expert flex: restored previous %s of backing a card while idle; "
"cached expert fill continues", humanb(to).c_str());
if (to >= xflex_cap_ || cur == 0)
RAD_INFO("expert flex: the slab grows into memory no model holds: %s a card of up to %s",
humanb(to).c_str(), humanb(xflex_cap_).c_str());
@@ -757,6 +772,7 @@ Engine::Readback::~Readback() {
}
Engine::~Engine() {
depth_log_stats("final");
/* The control vector's per-rank direction copies. Uploaded at declare, outside any arena, so
* nothing else frees them; each rank's copy is freed with that rank's device bound, since the
* allocator is per device. */
@@ -880,6 +896,8 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
sc.rank = rank;
sc.world_size = cfg_.tp;
sc.draft_coupling = cfg_.draft_coupling;
sc.draft_verify_block = cfg_.draft_verify_block;
sc.draft_verify_traversal = cfg_.draft_verify_traversal;
RAD_TRY(smp.declare(b, sc));
/* Where the chain writes the sampled ids. The engine declares it because rad-kbench drives the
@@ -1017,6 +1035,9 @@ void Engine::tiering_dispatch(Rank& r, int step) {
* credited; the next unstaged step swaps on them. */
std::vector<Swap> swaps;
if (!r.stager.staged() && r.heat.step(&swaps) < 0) return;
/* What the turnover slots follow (MoverConfig::turnover_adaptive). A staged step proposes
* nothing and holds the turnover filled anyway (below), so it is not a quiet step. */
if (!r.stager.staged()) r.mover.swap_demand((int64_t)swaps.size());
for (const Swap& s : swaps) {
/* Contract: every proposed unit is busy until `issue` takes it or `abandon` returns it;
* a dropped proposal stays busy forever. */
@@ -1210,7 +1231,8 @@ int Engine::prepare_release(const RadBatch* b) {
* parked, so no allocation races the read. */
kvstream_step_runs(ranks_[0]->kv, b, sched_.step_seqs(b), &stage_runs_);
for (auto& rk : ranks_) kvstream_bound_live(&rk->ctx, stage_runs_);
return RAD_OK;
/* A checkpoint inside the step: every rank's Ctx copies into its stage (Ctx::set_ckpt_snap). */
return ckpt_stage_arm(b);
}
int Engine::issue_ahead(const RadBatch** out) {
@@ -1220,7 +1242,9 @@ int Engine::issue_ahead(const RadBatch** out) {
if (flex_pending_.load(std::memory_order_acquire) || quiet_pending_.load(std::memory_order_acquire))
return RAD_OK;
for (int i = 0; i < serial_rows_ && serial_done_ > 0; ++i)
sched_.expect_draft(serial_row_[(size_t)i].seq, serial_done_);
/* --draft-depth adaptive: the row's own chain (Engine::depth_row_nodes); else the rounds
* every row ran. */
sched_.expect_draft(serial_row_[(size_t)i].seq, depth_row_nodes(i));
for (int i = 0; i < block_rows_; ++i)
sched_.expect_draft(block_row_[(size_t)i].seq, block_steps_);
const RadBatch* nb = sched_.step_next();
@@ -1665,6 +1689,8 @@ int Engine::step_loop() {
* immediately for a kind that is not its own. */
st = block_drafting() ? finish_block_drafter(so) : finish_serial_drafter(so);
if (st < 0) return fail_loop(st);
/* --draft-depth-load: the step's time and tokens, for the rule's rate and prices. */
if (depth_load_on_) depth_step_note(b, so);
/* The step ends here, after its draft rounds, so step timing includes them
* (Scheduler::step_finished). */
sched_.step_finished();
@@ -1902,6 +1928,45 @@ int Engine::collect_pooled(const RadBatch* b, StepOut& so) {
return RAD_OK;
}
/* ------------------------------------------------------------------ the checkpoint stage */
/* After the KV carve, the snapshot store and Scheduler::init. Every rank carved a stage or none
* did (KVManager::plan_groups decides on the same config and plans). */
int Engine::ckpt_stage_open() {
bool staged = !ranks_.empty() && ck_store_.enabled();
for (auto& rk : ranks_) staged = staged && rk->kv.ckpt_stage() != nullptr;
if (!staged) return RAD_OK;
ranks_[0]->kv.ckpt_stage_layout(&ck_stage_off_, &ck_stage_lb_);
ckpt_inside_ = ckpt_snap_ok_;
sched_.set_ckpt_inside(ckpt_inside_);
RAD_INFO("checkpoint stage: %s a rank on the card; %s",
humanb(ranks_[0]->kv.ckpt_stage_bytes()).c_str(),
ckpt_inside_ ? "a prompt's tail snapshot is taken inside its last chunk"
: "every snapshot at a chunk's end");
return RAD_OK;
}
int Engine::ckpt_stage_arm(const RadBatch* b) {
if (ck_stage_off_.empty()) return RAD_OK;
const StepEntry* in = nullptr;
if (b && b->ckpt_cut > 0)
for (const StepEntry& e : sched_.plan().e)
if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && e.ckpt_tok + 1 < e.n_tokens) in = &e;
if (!in) {
for (auto& rk : ranks_) rk->ctx.set_ckpt_snap(nullptr, ckpt_slots_, ck_stage_off_, ck_stage_lb_);
return RAD_OK;
}
if (in->ckpt_tok + 1 != b->ckpt_cut || !state_slots_of(in->seq, &ckpt_slots_)) {
RAD_ERR("step %d: sequence %llu's checkpoint inside the step (row %d) is not the batch's "
"(%d), or its state slots are gone", b->step, (unsigned long long)in->seq,
(int)in->ckpt_tok, (int)b->ckpt_cut);
return RAD_E_STATE;
}
/* The step writes the stage; the last snapshot left it on the same stream (save_checkpoints). */
for (auto& rk : ranks_)
rk->ctx.set_ckpt_snap(rk->kv.ckpt_stage(), ckpt_slots_, ck_stage_off_, ck_stage_lb_);
return RAD_OK;
}
/* Snapshot after the step that produced the state. Linear state is what the chunk's last token
* leaves, so the chunker ended the chunk at the checkpoint and copy 0 holds exactly that state; a
* window snapshot is the window's rows behind the checkpoint, which may lie inside the chunk
@@ -1930,12 +1995,26 @@ int Engine::save_checkpoints() {
(unsigned long long)e.seq, (int)(e.ctx_len + e.ckpt_tok + 1));
return RAD_E_STATE;
}
for (auto& rk : ranks_) {
/* A checkpoint inside the step is in the stage already (rad_ckpt_snap) and goes
* to the host slot from there in one copy; one at the chunk's end is copied from
* the live slots. */
const bool inside = e.ckpt_tok + 1 < e.n_tokens && !ck_stage_off_.empty();
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
auto& rk = ranks_[ri];
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
const int s = rk->kv.checkpoint_save(ckpt_slots_.data(),
(int)ckpt_slots_.size(),
e.ckpt_slot, rk->ctx.stream(),
&ckpt_win_);
int s = RAD_OK;
if (!inside) {
s = rk->kv.checkpoint_save(ckpt_slots_.data(), (int)ckpt_slots_.size(),
e.ckpt_slot, rk->ctx.stream(), &ckpt_win_);
} else {
/* The layers the step did not snapshot (rad_ckpt_snap) are the ones it did
* not change: a drafter head's state, which moves only in the drafter's
* passes behind this copy. */
s = rk->kv.checkpoint_stage_rest(
ckpt_slots_.data(), (int)ckpt_slots_.size(), rk->ctx.stream(),
[&](size_t g, int64_t li) { return rk->ctx.ckpt_snapped(g, li); });
if (s >= 0) s = rk->kv.checkpoint_stage_out(e.ckpt_slot, rk->ctx.stream());
}
if (s < 0) {
RAD_ERR("rank %d could not snapshot sequence %llu into checkpoint slot "
"%d: %s", rk->index, (unsigned long long)e.seq,
@@ -1945,6 +2024,30 @@ int Engine::save_checkpoints() {
}
}
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
/* RADIANCE_DEBUG_CKPT_HASH=1: wait for the snapshot and log a digest of each
* rank's shard, to compare two builds' snapshots byte for byte. A debugging aid:
* it drains the streams. */
static const bool hash_on = [] {
const char* h = std::getenv("RADIANCE_DEBUG_CKPT_HASH");
return h && h[0] == '1';
}();
if (hash_on) {
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
auto& rk = ranks_[ri];
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
(void)rad_stream_sync(rk->ctx.stream());
const unsigned char* p = (const unsigned char*)rk->kv.checkpoint_ptr(e.ckpt_slot);
uint64_t h = 0xcbf29ce484222325ull;
const int64_t nb = rk->kv.checkpoint_bytes();
for (int64_t j = 0; p && j < nb; ++j) { h ^= p[j]; h *= 0x100000001b3ull; }
RAD_INFO("ckpt-hash seq=%llu pos=%lld rank=%zu inside=%d bytes=%lld %016llx",
(unsigned long long)e.seq,
(long long)(e.ctx_len + e.ckpt_tok + 1), ri,
(int)(e.ckpt_tok + 1 < e.n_tokens), (long long)nb,
(unsigned long long)h);
}
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
}
}
return RAD_OK;
});
@@ -1993,6 +2096,24 @@ int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so,
score_ids_.erase(std::unique(score_ids_.begin(), score_ids_.end()), score_ids_.end());
}
bool host_failed = false;
/* The step-wide sibling of the scheduler's kMaxScoredCandidates. That cap bounds one
* request's candidate list; this one bounds the step's union of them, which otherwise grows
* toward the whole vocabulary. The readback below is pinned host memory sized by the union and
* never shrinks, so a step is refused by its count before the allocation is tried: a
* gigabyte-scale pin that succeeds would stay pinned. The cap is sixteen requests at the
* per-request maximum; a scored request names a few dozen ids. A step past it is refused the
* way an allocation failure is: the scored requests cancel and the engine goes on. */
static const size_t kMaxScoredStepIds = 1u << 16;
if (score_only_ && score_ids_.size() > kMaxScoredStepIds) {
RAD_ERR("scored rows: the step names %zu candidate rows, over the step budget of %zu; "
"cancelling the scored requests, not the engine",
score_ids_.size(), kMaxScoredStepIds);
cancel.insert(cancel.end(), scored.begin(), scored.end());
score_rows_.clear();
score_only_ = false;
score_ids_.clear();
return RAD_OK;
}
int64_t failed_rows = 0;
for (auto& rk : ranks_) {
const int64_t width = rk->sampler.config().n_vocab_local;
@@ -2457,12 +2578,14 @@ void Engine::tier_tick() {
/* Release an entry once its host copy has landed, if the expert slab can use the blocks; a
* later turn restores it with a copy. Otherwise (no lending, or the loan already covers every
* slab slot) it stays in VRAM, and a request needing room takes it through trim. Snapshots
* are already in host memory. */
* are already in host memory. Stragglers with no host copy coming go too (PrefixCache::
* drop_clean): a few thousand such tokens near the top of the pool would otherwise hold the
* whole loan at zero until the server restarts. */
if (lending_) {
int64_t ceiling = 0;
for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV));
const auto lk = sched_.hold();
if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean();
if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean(ceiling);
}
/* ---- capacity ---------------------------------------------------------------------------- */
@@ -2813,9 +2936,13 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
* Qwen3.8-Flash-Next at TP2 (two R9700, 12 GiB host pool) the span loses to one-interval
* steps up to 12K tokens and wins from 18K, hence eight intervals. With every expert on
* the card there is no such cost and every lone prefill spans. */
sched_.set_span_min(stage_rows > 0 && arena_span_rows_ > 0
? 8 * std::max<int64_t>(geo_.checkpoint_interval, 0) : 0);
const int64_t span_auto = stage_rows > 0 && arena_span_rows_ > 0
? 8 * std::max<int64_t>(geo_.checkpoint_interval, 0) : 0;
/* --prefill-span-min N says it for the deployment: where the routed pass covers the whole
* spanned step (--prefill-span-pass step) the span pays from the second interval on. */
sched_.set_span_min(cfg_.prefill_span_min >= 0 ? cfg_.prefill_span_min : span_auto);
}
RAD_TRY(ckpt_stage_open());
for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get());
@@ -2840,11 +2967,14 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
stepped.store(true, std::memory_order_release);
});
if (cfg_.kld() || cfg_.calib()) {
if (cfg_.kld() || cfg_.calib() || cfg_.diagnose_mode()) {
print_startup_report(RAD_OK);
startup_watch_.reset();
}
int s = cfg_.kld() ? run_kld() : cfg_.calib() ? run_calib() : run_server();
int s = cfg_.diagnose_mode() ? run_diagnose()
: cfg_.kld() ? run_kld()
: cfg_.calib() ? run_calib()
: run_server();
startup_watch_.reset();
/* Stop the step loop before the server's storage is destroyed: Request::sink points into it,
@@ -3120,6 +3250,31 @@ std::string request_overrides(const Config& c) {
return out;
}
} /* namespace */
SamplingParams Engine::sampling_defaults() const {
return resolve_sampling_defaults(meta_, file_ != nullptr, cfg_);
}
/* A token the model's chat format writes as one of its call delimiters is a call boundary, not a
* turn's: a reply that closes a call with it must be able to write the next call and text after
* it. A checkpoint that also lists the token in generation_config.json's eos ids would end every
* tool-calling turn there, so the id leaves the vocabulary's end-of-generation set. This runs
* once the vocabulary and the plugins are both loaded (the reply format can be the architecture
* plugin's) and before anything reads the set: the scheduler and the cards' step state, which cut
* accepted drafts at it, the grammar index and the reply parser's terminators. */
int Engine::demote_call_delimiters() {
if (!vocab_own_ || vocab_own_->chat_template().empty()) return RAD_OK;
const std::vector<int32_t> dropped = vocab_own_->drop_named_eog(
server::ChatTemplateBridge::eog_call_markers(*vocab_own_,
rad_tools_chat_format(plugins_, meta_)));
if (dropped.empty()) return RAD_OK;
for (int32_t id : dropped)
RAD_WARN("vocab: token %d \"%s\" is listed as end-of-generation by the checkpoint's "
"generation_config.json and is one of this model's tool-call delimiters; a turn "
"does not end on it", id, vocab_->text(id).c_str());
return build_vocab_view();
}
/* The HTTP server over the engine. `/v1/completions`, `/v1/chat/completions`, `/v1/models`,
* `/metrics` and `/health` are live. `/v1/embeddings` answers 501 unless the program is an
* embedding program, and so do image, video and audio content parts unless the program declared an
@@ -3417,6 +3572,13 @@ int Engine::run_server() {
o.plugin_words = ranks_.empty() ? 0 : ranks_[0]->program.plugin_words;
o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name
: meta_.name && *meta_.name ? meta_.name : "radiance";
o.control_vector_variant = cfg_.control_vector_variant;
if (!o.control_vector_variant.empty() && o.control_vector_variant == o.model_id) {
RAD_ERR("--control-vector-variant '%s' is the served model's own name, so a request "
"naming it would run the default; rename it or give --served-model-name",
o.model_id.c_str());
return RAD_E_INVAL;
}
o.host = cfg_.host;
o.port = cfg_.port;
o.api_key = cfg_.api_key;
@@ -3561,6 +3723,31 @@ int Engine::run_server() {
return RAD_E_INVAL;
}
if (vc.family == mm::Family::Gemma4) {
/* A two-sided paged window is exact for image spans no longer than the window.
* Limit what the processor admits if a rank cannot run the long-span variant. */
if (encd.bidirectional) {
for (const auto& rank : ranks_) {
long long window = 0;
bool ahead = false;
for (const OpInfo& op : rank->program.ops) {
if (op.op == "attn_paged_ahead" || op.op == "attn_paged_qrow_ahead")
for (const Band& b : op.bands)
ahead = ahead || b.dom[RAD_DOMAIN_HOST] || b.dom[RAD_DOMAIN_DEVICE];
if (op.op == "attn_paged" || op.op == "attn_paged_qrow") {
long long causal = 1, w = 0;
if (op.base.get_i("causal", &causal) && causal == 0 &&
op.base.get_i("window", &w) && w > 0)
window = window > 0 ? std::min(window, w) : w;
}
}
if (!ahead && window > 0 && window < vc.max_patches / encd.merge)
vc.max_patches = window * encd.merge;
}
if (vc.max_patches < encd.max_patches)
RAD_INFO("media: image spans are limited to %lld soft tokens because the "
"loaded kernels cannot attend beyond the sliding window",
(long long)(vc.max_patches / encd.merge));
}
if (cfg_.image_min_pixels || cfg_.image_max_pixels || cfg_.video_min_pixels ||
cfg_.video_max_pixels || cfg_.video_min_frames) {
RAD_ERR("media: this model's processor sizes images and video frames by a token "
@@ -3640,10 +3827,11 @@ int Engine::run_server() {
}
if (vc.family == mm::Family::Gemma4 &&
(int64_t)std::max(vc.image_soft_tokens, vc.video_soft_tokens) * vc.merge * vc.merge >
encd.max_patches) {
RAD_ERR("media: an image of %d soft tokens or a video frame of %d is more patches than "
"one encoder pass holds (--mm-max-patches %lld)", vc.image_soft_tokens,
vc.video_soft_tokens, (long long)encd.max_patches);
vc.max_patches) {
RAD_ERR("media: an image of %d soft tokens or a video frame of %d exceeds this "
"deployment's limit of %lld soft tokens per segment; lower --image-tokens "
"or --video-max-frame-tokens", vc.image_soft_tokens, vc.video_soft_tokens,
(long long)(vc.max_patches / encd.merge));
return RAD_E_INVAL;
}
mm_proc = std::make_unique<mm::Processor>();
@@ -3951,6 +4139,8 @@ int Engine::run_server() {
in.branches = ad.branches == 1 ? 1 : 2;
in.input_special = ad.input_special != 0;
in.tmpl_ref = pg.agen_str.tmpl_ref;
in.tmpl_ref_instruct = pg.agen_str.tmpl_ref_instruct;
in.neg_tmpl_ref = pg.agen_str.neg_tmpl_ref;
in.ref_item = pg.agen_str.ref_item;
in.ref_rate = ad.ref_rate;
in.ref_hop = ad.ref_hop;
+98 -2
View File
@@ -29,6 +29,7 @@
#include "runtime/ctx.h" /* KVStageRun */
#include "sched/mem_iface.h"
#include "sched/scheduler.h"
#include "sched/draft_depth.h" /* --draft-depth adaptive: the stop rule */
#include "sample/vocab_view.h"
#include "runtime/rank_barrier.h"
#include "text/tokenizer.h"
@@ -38,9 +39,11 @@
#include "lora/adapter.h"
#include "lora/slots.h"
#include "fleet/broker.h"
#include "place/expert_restore.h"
#include <atomic>
#include <chrono>
#include <cstdio>
#include <condition_variable>
#include <functional>
#include <memory>
@@ -272,7 +275,7 @@ private:
/* The first of this engine's instance slots (RadBuildCtx::slot_base), held from load_plugins
* to the destructor (rad_engine_claim); -1 while none is held. */
int slot_base_ = -1;
bool cards_claimed_ = false; /* rad_dev_cards_claim, for an engine of more than one rank */
bool cards_claimed_ = false; /* rad_dev_cards_claim, balanced during teardown */
/* RadModelMeta holds bare char*, so the strings behind its key/value table must outlive
* every declare. */
@@ -419,6 +422,9 @@ private:
/* The text frontend, loaded from the container. The sampler's grammars walk `vocab_view_`,
* which references `vocab_` and must not outlive it. */
std::shared_ptr<const Vocab> vocab_;
/* `vocab_` itself, writable: bring-up takes call delimiters out of its end-of-generation set
* (demote_call_delimiters) before anything is built from the set. Not written after that. */
std::shared_ptr<Vocab> vocab_own_;
std::unique_ptr<VocabView> vocab_view_;
/* The container's second vocabulary (rad-convert --tokenizer2), which an image generator that
* declares `aux_tokens` reads its prompt through; null without one. */
@@ -487,10 +493,12 @@ private:
void flex_room_tick(uint64_t now_ns);
/* Expert flex (§6.7). Each rank's slab borrows from its own reserved range (Rank::xflex), the
* top `xflex_bytes_` of it backed; the ceiling is the loan that covers every slot carved there.
* xflex_tick grows it on the step loop while the engine is busy, a GiB at a time once the
* xflex_tick grows it while busy, or restores surrendered backing while idle, a GiB
* at a time once the
* slab has filled what it holds; xflex_give recalls and unbacks it, between steps. */
std::atomic<int64_t> xflex_bytes_{0};
std::atomic<int64_t> xflex_want_{0};
ExpertFlexRestore xflex_restore_; /* step-loop state, reset on park */
int64_t xflex_cap_ = 0;
int64_t xflex_claimed_ = 0; /* the claim's expert bytes a card */
uint64_t xflex_ns_ = 0, xflex_busy_ns_ = 0, xflex_retry_ns_ = 0;
@@ -540,6 +548,8 @@ private:
bool state_slots_of(uint64_t seq, std::vector<int32_t>* out) const;
int load_vocab();
int build_vocab_view();
int demote_call_delimiters();
int declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool sizing = false);
/* The build context for every declare of rank `rank` at `max_tok`; the real declare and the
* arena's sizing declares differ only in max_tok. */
@@ -668,6 +678,70 @@ private:
bool couple_evidence_ = false; /* the completed-verify line was written (once a process) */
bool couple_host_note_ = false; /* the host-domain counterpart was written (once) */
bool couple_malformed_note_ = false; /* a status -1 round was reported (once) */
int64_t couple_planes_ = 0; /* the rounds the state plane holds */
/* --draft-depth adaptive (sched/draft_depth.h, engine_draft.cpp): the chain of a step stops by
* the head's own laws, so its rounds are issued one decision at a time. After the pass of
* round r the engine copies that round's state rows to depth_rb_ and records depth_ev_[r - 1];
* the driver waits for the event of the round a decision needs, reads the statistic and issues
* the next round or ends the chain. depth_of_[i] is drafting row i's final depth, which
* expect_draft, set_draft and the coupling's bind all take in place of the rounds that ran. */
DraftDepthCfg depth_cfg_;
RadEvent depth_ev_[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
bool depth_issued_[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
RadMtpCoupleState* depth_rb_ = nullptr; /* pinned [rounds, couple_rows_] */
std::vector<DraftDepthRow> depth_row_;
std::vector<int32_t> depth_of_;
int depth_seen_ = 0; /* rounds observed this step */
static constexpr int64_t kDepthSpinUs = 3000; /* poll this long for a round, then block */
struct DepthStats {
uint64_t steps = 0, rows = 0, rounds = 0, drafts = 0, lawless = 0, waits = 0, blocked = 0;
uint64_t hist[RAD_MTP_COUPLE_MAX_ROUNDS + 1] = {};
double wait_us = 0;
uint64_t late = 0;
/* By the drafts a step made (d): the card's cycle from that step's first statistic to the
* next step's (its later rounds, the verify of d + 1 rows, the sampler, the next history
* pass), and what the verify of d drafts accepted. */
double cyc_us[RAD_MTP_COUPLE_MAX_ROUNDS + 1] = {};
uint64_t cyc_n[RAD_MTP_COUPLE_MAX_ROUNDS + 1] = {};
uint64_t acc[RAD_MTP_COUPLE_MAX_ROUNDS + 1] = {}, acc_n[RAD_MTP_COUPLE_MAX_ROUNDS + 1] = {};
} depth_stats_;
std::chrono::steady_clock::time_point depth_e1_{}; /* the last step's first statistic */
uint64_t depth_logged_ = 0; /* depth_stats_.rows at the last line */
int depth_last_ = 0; /* and the deepest chain that step made */
/* --draft-depth-load (sched/draft_depth.h): the load-aware rule and the late choice of the
* verify's rows, for a step that drafts for depth_cfg_.load_from sequences or more, and the
* online calibration of the tables they read. */
DraftDepthOnline depth_online_;
bool depth_online_on_ = false; /* --draft-depth-load-calib online */
int depth_other_rows_ = 0; /* the next verify's token rows that draft nothing */
bool depth_load_step_ = false; /* this step's chains were decided by the load-aware rule */
bool depth_load_on_ = false; /* --draft-depth-load on: the tables exist */
/* A chain between the step that drafted it and the verify that settles it, by card slot: what
* the online calibration counts once the accepted count is known. */
struct DepthPend {
uint64_t seq = 0;
int32_t depth = 0, rule = 0, n_s = 0; /* depth 0: nothing pending */
float s[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
};
std::vector<DepthPend> depth_pend_;
/* The step before this one, for the rule's rate and prices: when its passes ended, and whether
* it was a pure decode step of how many drafting rows. */
std::chrono::steady_clock::time_point depth_note_t_{};
int depth_note_step_ = -2, depth_note_rows_ = 0;
uint64_t depth_note_n_ = 0;
void depth_step_note(const RadBatch* b, const StepOut& so);
void depth_load_log(const char* when) const;
/* RADIANCE_DEBUG_CONC_LOG=<file>, diagnostics of the load-aware rule: one line a decode step (rows,
* rounds, each chain's depth and statistics, what the verify accepted) and one a refresh of
* the tables. */
std::FILE* depth_log_ = nullptr;
void depth_log_step(const RadBatch* b, const StepOut& so);
/* Drafting row i's depth after issue_serial_drafter: its own under the adaptive rule, else the
* rounds every row ran. */
int depth_row_nodes(int i) const;
int depth_readback_issue(int round, int n);
int depth_observe_upto(int round, int n, const StepOut& so);
void depth_log_stats(const char* when);
/* `rows` are serial_row_ or block_row_ (Scheduler::SerialRow / BlockRow). */
template <class Row> int stage_couple_draws(const Row* rows, int n);
int bind_couple(uint64_t seq, int i, int done, bool drafted, int32_t card);
@@ -707,6 +781,20 @@ private:
* the checkpoint save waits for its context pass (save_checkpoints). */
bool drafter_snap_ = false;
int save_checkpoints();
/* Checkpoints through the stage (KVManager::ckpt_stage).
*
* ckpt_snap_ok_: the plugin snapshots inside a step (RadArchProbe::ckpt_snap_ok); with a
* stage on every rank the scheduler then takes a prompt's tail snapshot inside its last chunk
* (Scheduler::set_ckpt_inside). Such a
* snapshot is the stage's one contiguous copy to the host slot rather than a pitched copy a
* group. */
bool ckpt_snap_ok_ = false;
bool ckpt_inside_ = false;
std::vector<int64_t> ck_stage_off_, ck_stage_lb_;
int ckpt_stage_open();
/* Before a step: a step with a checkpoint inside it arms every rank's Ctx
* (Ctx::set_ckpt_snap); every other step disarms them. */
int ckpt_stage_arm(const RadBatch* b);
/* A tree drafter (rad_drafter_tree), driven on the card only: ADV_BTAKE takes its parents,
* ADV_COMPACT moves the accepted path's K and V after the acceptance, and ADV_CTXTREE stages
* the context pass by that path. */
@@ -788,6 +876,10 @@ private:
std::vector<std::unique_ptr<server::Sink>>& sinks, bool fit_pool,
const char* tag, int every_s,
const std::function<void(size_t, double)>& progress, int* bad);
/* --diagnose (core/engine_diagnose.cpp), replacing run_server: runs a fixed workload on this
* engine -- decode by prompt category, a concurrency sweep, a prefill sweep, interference --
* and writes DIR/diagnose.json and DIR/diagnose.md instead of listening. */
int run_diagnose();
int score_rows(const RadBatch* b, const StepOut& so);
std::unique_ptr<Kld> kld_;
std::vector<float*> kld_host_;
@@ -800,6 +892,10 @@ private:
long long calib_tokens_ = 0;
/* The engine half of /server_info, as a JSON object. See the definition in engine.cpp. */
std::string engine_info() const;
/* The sampler a request that sends no settings runs with: the container's generation defaults
* with the operator's flags over them (resolve_sampling_defaults, engine.cpp). A mode that
* builds requests with no client -- --diagnose -- samples with what the server would. */
SamplingParams sampling_defaults() const;
/* ---- startup report inputs (engine_diag.cpp). `decisions_` holds each value startup resolved
* and why, recorded where it was resolved; the rest are facts only startup saw. */
+128 -25
View File
@@ -26,6 +26,7 @@
#include "mem/vram_budget.h"
#include "kvstream/bringup.h"
#include "kvstream/plan.h"
#include "mm/media.h"
#include "runtime/arena.h"
#include "runtime/kvbind.h"
#include "runtime/xprefetch.h"
@@ -1013,6 +1014,9 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
/* Under --prefill-span every step but a lone prefill is planned at the shared budget
* (Scheduler::step), so a wider step is one sequence; 0 without a span. */
bc.max_mixed_tok = cfg_.prefill_span > 1 ? std::min(max_tok, prefill_shared_tok(cfg_)) : 0;
/* --prefill-span-pass step: the routed block's pass is the whole spanned step where the plugin
* runs such a step serially. */
bc.span_pass_step = cfg_.prefill_span > 1 && cfg_.prefill_span_step ? 1 : 0;
/* --kv-resident in tokens, raised to kStreamFloorTokens as kvstream_ring_shape raises it: the
* arch declares kv_resolve's ring depth from this, and the kernel refuses a carve deeper than
* the declared table. */
@@ -1060,8 +1064,8 @@ int Engine::declare() {
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
}
/* --calib-corpus: every token of the corpus through prefill exactly once, so no prefix hit
* skips any and no drafter adds rows; the corpus is loaded here, before the plugins declare,
* because they are told its size. */
* skips any and no drafter adds rows. Load it before declaration so a plugin knows its size
* and can opt into a separate, proposal-free history pass (RAD_DRAFT_HISTORY). */
if (cfg_.calib()) {
if (cfg_.n_spec > 0) {
RAD_ERR("--num-speculative-tokens %d: a calibration run drafts nothing; leave it at "
@@ -1071,7 +1075,7 @@ int Engine::declare() {
cfg_.n_spec = 0;
cfg_.prefix_cache = false;
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
decide("--num-speculative-tokens", "0", "a calibration run records the trunk's rows only");
decide("--num-speculative-tokens", "0", "a calibration run does not propose draft tokens");
prefix_off_why_ = "a calibration run: a prefix hit would skip tokens the statistics must count";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
calib_ = std::make_unique<Kld>();
@@ -1266,7 +1270,14 @@ int Engine::declare() {
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
const bool always = pb.chain_pays == RAD_CHAIN_ALWAYS;
const bool pays = always || (cfg_.n_spec > 0 && pb.chain_pays != RAD_CHAIN_NONE);
rad_dev_chain_infer(pays);
/* Their packets go without the packet processor's acquire where every row that can chain
* acquires in the kernel for all it reads (RadKernelChainFn saying 2): one row that does
* not, from any library this engine loaded, keeps the acquire on all of them, since a
* queue's packets are not told apart by library. */
bool fenced = pays;
for (const KernelRow& row : reg_->rows())
if (row.chain && !row.chain_fenced) fenced = false;
rad_dev_chain_infer(pays ? (fenced ? 2 : 1) : 0);
const bool on = rad_dev_chain_enabled() != 0;
const char* why = on ? (always ? "the model's plugin measured a gain with them"
: "the model's plugin measured a gain with its "
@@ -1274,7 +1285,12 @@ int Engine::declare() {
: pays ? "the device backend does not chain"
: "no drafter whose plugin measured a gain with them decodes "
"speculatively";
RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why);
RAD_INFO("chained launches: %s -- %s%s", on ? "on" : "off", why,
!on ? ""
: rad_dev_chain_unfenced() ? "; their packets take no acquire from the packet processor"
: "; their packets keep the packet processor's acquire "
"(a row that chains does not acquire for its scalar "
"loads itself)");
decide("chained launches", on ? "on" : "off", why);
}
/* Trees: a block drafter's proposals verified as a tree, where the model's plugin measured a
@@ -1287,12 +1303,55 @@ int Engine::declare() {
/* A tree is verified only behind a step issued ahead (step_loop). The KL mode, which issues
* none, drafts nothing either (n_spec is 0 there by now), so this never runs under it. */
draft_tree_ = cfg_.n_spec > 0 && pb.tree_pays != 0;
ckpt_snap_ok_ = pb.ckpt_snap_ok != 0;
/* The checkpoint stage (KVManager::ckpt_stage), planned before any KV plan is made, where
* a tail snapshot can be taken inside the last chunk: the plugin cuts its step for it and
* a hit resumes at the nearest snapshot (the exact grid snapshots where a chunk starts). */
cfg_.ckpt_stage = ckpt_snap_ok_ && !cfg_.prefix_exact;
if (draft_tree_) {
const char* why = "the model's plugin measured a gain with them";
RAD_INFO("draft trees: asked -- %s", why);
decide("draft trees", "asked", why);
}
}
/* --draft-suffix: SuffixDecoding's selector (core/sched/suffix.h). A suffix step verifies up to
* `draft_suffix_max` rows of the sequence's own history while the head still drafts its own
* `n_spec` rounds, so the verify window every consumer of `n_spec` sees (buffers, rings, the
* scheduler's window) becomes the larger of the two and the head's rounds are kept apart in
* `n_spec_head`. A serial head's chain only: a block drafter's block is fixed. It works with
* the fixed chain, with --draft-depth adaptive (whose depth stays within the head's rounds)
* and with the traversal verify (a suffix row binds no coupled state, so it is a leaf of the
* walk); the block verify decides a head chain as a whole and is refused. */
cfg_.n_spec_head = 0;
if (cfg_.draft_suffix) {
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
const char* bad = nullptr;
if (cfg_.n_spec <= 0) bad = "speculation is off (this container carries no draft head)";
else if (draft_tree_) bad = "it needs the head's chain, not a block drafter's tree";
else if (pb.draft_depth_fixed) bad = "this drafter is a block drafter, not a serial head";
else if (cfg_.draft_window == DraftWindow::Adaptive)
bad = "it needs the fixed window (--draft-window fixed)";
else if (cfg_.draft_verify_block) bad = "it cannot be combined with --draft-verify block "
"(a suffix chain is no block; --draft-verify token | traversal)";
if (bad) {
RAD_ERR("--draft-suffix on: %s", bad);
return RAD_E_UNSUPPORTED;
}
const int window = std::max(cfg_.n_spec, cfg_.draft_suffix_max);
if (window > (int)RAD_SCHED_MAX_SPEC) {
RAD_ERR("--draft-suffix-max %d is past the largest verify window (%d)", cfg_.draft_suffix_max,
(int)RAD_SCHED_MAX_SPEC);
return RAD_E_INVAL;
}
cfg_.n_spec_head = cfg_.n_spec;
cfg_.n_spec = window;
RAD_INFO("draft suffix: on -- a host-built step verifies up to %d row(s) of the sequence's own "
"history when its last %d token(s) recur (path score >= %.2f); the head drafts %d "
"round(s), the verify window is %d", cfg_.draft_suffix_max, cfg_.draft_suffix_min_match,
(double)cfg_.draft_suffix_min_score, cfg_.n_spec_head, window);
decide("draft suffix", "on", "--draft-suffix on");
}
/* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio
* encoder (`radiance.encoder` names one) and the deployment is not text-only. */
if (cfg_.mm_audio_frames < 0) {
@@ -1315,18 +1374,32 @@ int Engine::declare() {
const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0 ||
rad_meta_geti(&meta_, "vision_config.image_size", 0) > 0;
cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0;
/* A build with no media decoder (RAD_WITH_FFMPEG) refuses every media part, so a tower it
* loaded could never run a pass: it would only hold card memory the routed experts are
* short of. Qwen3.8-Flash-Next at tp 2 on two R9700: 857 MiB a rank, about 800 expert
* units a rank that the routed GEMMs then read from the pinned pool over the link instead
* of from the card. An explicit --mm-max-patches still loads the tower. */
const bool undecodable = cfg_.mm_max_patches > 0 && !mm::decoder_available();
if (undecodable) cfg_.mm_max_patches = 0;
/* Whole output rows a pass: the plugin's merge, when it states one. */
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb, cfg_.image_gen_max_pixels, cfg_.image_gen_max_refs);
if (cfg_.mm_max_patches > 0 && pb.enc_merge > 1)
cfg_.mm_max_patches -= cfg_.mm_max_patches % pb.enc_merge;
if (cfg_.mm_max_patches == 0 && tower)
if (undecodable)
RAD_INFO("media: off -- the model carries a vision tower, but this build has no media "
"decoder (RAD_WITH_FFMPEG) and would refuse every media part, so the tower "
"is not loaded and its card memory goes to the experts and the cache; "
"--mm-max-patches N loads it all the same");
else if (cfg_.mm_max_patches == 0 && tower)
RAD_INFO("media: off -- the checkpoint has a vision tower but this container was "
"converted without its weights; convert again to serve images and video");
decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches),
cfg_.mm_max_patches > 0
? "the model carries a vision tower: 16384 patches is a 2048 x 2048 image, the "
"largest one encoder pass takes"
: undecodable ? "the model carries a vision tower, but this build has no media "
"decoder to feed it"
: tower ? "the checkpoint has a vision tower but this container was converted "
"without its weights"
: "the model carries no vision tower");
@@ -1531,7 +1604,13 @@ int Engine::declare() {
drafter_ = p0.drafter;
drafter_name_ = p0.drafter_name;
drafter_.name = drafter_name_.c_str();
if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{};
const bool calib_history = drafter_.kind == RAD_DRAFT_HISTORY;
if (calib_history && !cfg_.calib()) {
RAD_ERR("'%s' history calibration requires --calib-corpus; it cannot run with "
"--kld-record", drafter_.name);
return RAD_E_UNSUPPORTED;
}
if (cfg_.n_spec <= 0 && !calib_history) drafter_ = RadDrafterDecl{};
/* A tree drafter (rad_drafter_tree): its parents plane rides with the proposal. */
tree_ = drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0 && p0.drafter_tree;
tree_parents_ = tree_ ? p0.drafter_parents : 0;
@@ -1572,7 +1651,9 @@ int Engine::declare() {
"for the sequences the head declines", drafter_.name);
return RAD_E_INVAL;
}
if (drafter_.kind != RAD_DRAFT_NONE) {
if (calib_history) {
RAD_INFO("calib: '%s' history only; no draft proposals", drafter_.name);
} else if (drafter_.kind != RAD_DRAFT_NONE) {
/* A zero proposal handle means the sampler's token buffer: the head's logits go through
* the ordinary sampler chain. */
RAD_INFO("speculation: %s",
@@ -1753,6 +1834,7 @@ int Engine::plan() {
for (RadStream s : q) if (s) rad_stream_destroy(s);
}
f.n_queues = 2 + (r->program.scratch_regions > 1 ? 1 : 0);
f.queue_scratch = 0; /* set below, once props are read */
/* The weights' cost, split into the fixed floor and the elastic plane
* (weight_footprint in core/place/planner.h). Per rank, so already this card's share
* under TP. */
@@ -1773,6 +1855,7 @@ int Engine::plan() {
}
RadDeviceProps props{};
rad_dev_props(r->device, &props);
f.queue_scratch = rad_dev_resident_scratch_bytes(&props);
f.capacity = props.vram_bytes;
f.free = props.vram_free;
/* Unified memory: the pinned host pool is the same RAM as the card, so the
@@ -3551,8 +3634,11 @@ static int sweep_container(RadFile* file, std::vector<LoadRun>& runs,
return RAD_OK;
}();
/* Release the page cache of weights never read from the file again, leaving it to the mapped
* tier (e.g. a mapped n-gram table, read from its mapping for the process lifetime). */
/* Release the page cache of weights never read from the file again. The mapped tier's pages
* stay (RadFile::keep_cached, named where load_weights publishes a mapped weight): an n-gram
* table is gathered from its mapping on every step, and with its pages dropped the first long
* prefill after each load or restore faults them back from the drive (a 103 GiB table: 1460
* against 1998 tok/s on a 24k prompt). */
file->drop_blob_cache();
/* Drain before freeing: a sweep that failed part-way may have copies outstanding. */
for (int b = 0; b < kWin; ++b) pool->drain(b);
@@ -3683,6 +3769,8 @@ int Engine::load_weights() {
int64_t total = 0, n_loaded = 0, n_missing = 0;
/* Counted apart from `n_loaded`: mapped weights are published in place, not loaded. */
int64_t n_mapped = 0, mapped_bytes = 0;
/* Of the container's own bytes, what the mapped tier reads: left in the page cache. */
int64_t mapped_kept = 0;
/* Two phases. The walk decides which rank wants which bytes, where they land, and what is
* refused, without touching the disk; sweep_container then reads the container once in file
@@ -3703,6 +3791,9 @@ int Engine::load_weights() {
* aligned (rad_format.h), DirectFile's alignment, so stages take the no-bounce path. */
MoverConfig mc{};
mc.container_path = file_ ? cfg_.model : std::string();
/* The lent slots kept free for swaps follow the swaps asked for (mover.h): a rank that
* holds nearly all its experts gets the idle ones back as residents. */
mc.turnover_adaptive = true;
RAD_TRY(r->mover.init(r->program, r->plan, mc, &r->pools));
/* What the mover took, before the first copy. Its slabs are allocated in init, so the pool
* is as full as it will get; a load stopping with zero free is a placement failure, not
@@ -3870,6 +3961,7 @@ int Engine::load_weights() {
* for a row of a few hundred bytes. MADV_RANDOM is per range, so the rest of the
* container keeps sequential readahead. The effect shows only with a cold cache. */
posix_madvise(w.ptr, (size_t)n, POSIX_MADV_RANDOM);
if (file_) mapped_kept = file_->keep_cached(w.host_ptr, n);
r->mover.publish_mapped((rad_weight)i, w.ptr);
++n_mapped;
mapped_bytes += n;
@@ -4000,10 +4092,11 @@ int Engine::load_weights() {
/* Summed over ranks, which map the same file, so under TP the resident bytes are this
* divided by --tp; the message says so. */
RAD_INFO("load: %lld weight(s), %s, read in place from the container's mapping -- not "
"copied and charged to no pool%s", (long long)n_mapped,
humanb(mapped_bytes).c_str(),
"copied and charged to no pool%s; %s of the container stays page-cached for them",
(long long)n_mapped, humanb(mapped_bytes).c_str(),
cfg_.tp > 1 ? " (summed over ranks, which map the same file: the resident bytes "
"are that divided by --tp)" : "");
"are that divided by --tp)" : "",
humanb(mapped_kept).c_str());
return RAD_OK;
}
@@ -4703,6 +4796,7 @@ int Engine::start() {
if (vocab_ex) std::rethrow_exception(vocab_ex);
if (vocab_st < 0) return vocab_st;
if (plugins_st < 0) return plugins_st;
RAD_TRY(demote_call_delimiters());
{
/* The loaded libraries in selection order: as --kernels named them, or every library in
* the home. */
@@ -4725,15 +4819,14 @@ int Engine::start() {
r->device = devs[i];
ranks_.push_back(std::move(r));
}
/* Collectives run on these cards from here on; another engine's on the same cards must not be
* able to starve them of wave slots (rad_dev_cards_claim). */
if (cfg_.tp > 1) {
const int cs = rad_dev_cards_claim(devs.data(), cfg_.tp, 1);
if (cs < 0) {
RAD_ERR("device: the ranks' cards could not be claimed: %s", rad_strerror(cs));
return cs;
}
cards_claimed_ = true;
/* A single-rank engine can occupy wave slots on one of a peer engine's collective cards.
* Claim every engine's cards before it creates any work on them. The backend records the
* claim before draining outstanding work, so teardown also releases it on a drain failure. */
cards_claimed_ = true;
const int cs = rad_dev_cards_claim(devs.data(), cfg_.tp, 1);
if (cs < 0) {
RAD_ERR("device: the ranks' cards could not be claimed: %s", rad_strerror(cs));
return cs;
}
/* Peer access, measured before selection. Kernels that touch another card's memory constrain
@@ -5254,6 +5347,10 @@ int Engine::start() {
* restore reads it again (refill_weights). */
if (file_) dev_page_refilled(base);
}
/* Bringup done: everything this engine loads is loaded. From here the stuck-exit watchdog
* treats a device that advances nothing as a hang; before here it treats it as a slow load
* (device.h's dev_engine_ready). */
dev_engine_ready.store(true, std::memory_order_release);
return RAD_OK;
}
@@ -5346,6 +5443,7 @@ int Engine::load_vocab() {
auto v = std::make_shared<Vocab>();
RAD_TRY(v->load(std::move(vb)));
vocab_ = v;
vocab_own_ = v;
if (file_ && file_->aux_vocab()) {
VocabBuild ab;
RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), file_->aux_vocab().h, ab));
@@ -5355,13 +5453,18 @@ int Engine::load_vocab() {
RAD_INFO("vocab: a second vocabulary of %d tokens", aux_vocab_->n_tokens());
}
RAD_INFO("vocab: %d tokens, bos=%d eos=%d%s", vocab_->n_tokens(), vocab_->bos(), vocab_->eos(),
vocab_->chat_template().empty() ? ", no chat template" : "");
return build_vocab_view();
}
/* The sampler's view of the vocabulary and the grammar engine's index over it. The index sorts
* end-of-generation ids apart from text, so both are built again when that set changes. */
int Engine::build_vocab_view() {
auto view = std::make_unique<TokenView>();
RAD_TRY(view->init(vocab_));
vocab_view_ = std::move(view);
RAD_INFO("vocab: %d tokens, bos=%d eos=%d%s", vocab_->n_tokens(), vocab_->bos(), vocab_->eos(),
vocab_->chat_template().empty() ? ", no chat template" : "");
/* Build the grammar engine's vocabulary index now rather than on the first grammar request
* (nearly every tool-calling request has one), so admission pays only for its own grammar. */
GbnfVocabInfo gi;
+716
View File
@@ -0,0 +1,716 @@
/* engine_diagnose.cpp -- the --diagnose driver: a fixed workload the engine runs on itself in
* place of the HTTP server, and the report it writes. The arithmetic and the report format are
* core/diag/diagnose.h's; this file only drives the scheduler and collects what it needs.
*
* THE WORKLOAD IS A SERVING WORKLOAD. Prompts go through the model's chat template with the
* deployment's reasoning default, sampling is the server's default (the same resolve the HTTP
* path uses) with a fixed seed per request, and pipelining and drafting stay as configured -- so
* what is measured is the engine that serves, not a benchmark mode of it. No HTTP, no stop
* strings.
*
* NOTHING IS SERVED FROM THE PREFIX CACHE. Every prompt is salted at its head with a tag unique to
* the request (diag::salt_messages), the cache is emptied before every run, and every request's
* cached-token count is checked afterwards: a run the cache served any of is reported, and the
* report's verdict says the run is not a measurement. The cache itself stays on, so what it costs
* a request that misses -- lookups, publishing, checkpoints -- is measured as a server pays it.
*
* PARITY. The tag is a counter, not a clock, so two builds run the same workload on the same
* prompts with the same seeds, and every request's tokens are in the report. With
* --diagnose-baseline the run compares them with an earlier report token for token
* (diag::compare_outputs) and fails on any difference.
*
* Points, each run once unmeasured (first launches of a shape record passes and load code) and
* then --diagnose-runs times, every run from an idle engine:
* categories one stream a prompt of the corpus, ending on the model's EOS or max tokens
* concurrency N streams submitted together, for each N of --diagnose-concurrency;
* ignore_eos, so all N decode for the whole run
* prefill one prompt of each length of --diagnose-prefill, then a short decode at that
* depth
* interference streams decoding, then one prompt arriving: its TTFT under load and the gap it
* puts into the running streams
*/
#include "engine_priv.h"
#include "diag/diagnose.h"
#include "build/startup.h"
#include "device/device.h"
#include "place/xstats.h"
#include "server/adapters.h"
#include "server/sink.h"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <functional>
#include <fstream>
#include <memory>
#include <thread>
#include <vector>
extern char** environ;
namespace rad {
namespace {
using json = diag::json;
int64_t steady_ns() {
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
/* The environment knobs that change what is measured, so a report says what it was measured
* under: several are read once into statics and cannot be seen any other way. Names only, from the
* allowlist in diag/diagnose.cpp; a value may be a path, a host name or a token, and the report is
* pasted into issues and committed beside a baseline. */
json env_snapshot() { return diag::env_allowlist(environ); }
/* One request of a run. */
struct Job {
std::vector<int32_t> prompt;
int max_tokens = 0;
bool ignore_eos = true;
float temp = -1.0f; /* < 0: the server's default */
};
double loadavg1() {
FILE* f = std::fopen("/proc/loadavg", "r");
if (!f) return -1;
double v = -1;
if (std::fscanf(f, "%lf", &v) != 1) v = -1;
std::fclose(f);
return v;
}
} /* namespace */
int Engine::run_diagnose() {
namespace fs = std::filesystem;
std::error_code ec;
fs::create_directories(cfg_.diagnose, ec);
if (ec) {
RAD_ERR("diagnose: cannot create '%s': %s", cfg_.diagnose.c_str(), ec.message().c_str());
return RAD_E_IO;
}
json warnings = json::array();
json problems = json::array(); /* what makes the run not a measurement: the verdict */
auto warn = [&](const std::string& w) {
RAD_WARN("diagnose: %s", w.c_str());
warnings.push_back(w);
};
json not_measured = json::array({
"per-kernel device time, launch gaps and host joins: needs dispatch timestamps inside the "
"engine (docs/DIAGNOSE.md, step 3); rocprofv3 is not a substitute here",
"placement, expert streaming and link counters per phase (docs/DIAGNOSE.md, step 1b)",
"op correctness (repeat, oracle) over a step window (docs/DIAGNOSE.md, step 4)",
"the HTTP path, detokenisation and streaming to a client: a client-side benchmark measures "
"those, and the difference to these numbers is their cost",
});
/* ---- the conditions: what the run ran on, and the serving cards to sample between runs ----
* The startup report's machine reading and its findings, taken once before the workload; the
* cards' temperatures and performance level again around every run (diag::sample_cards), so a
* report shows when two runs, or two reports, were taken on cards in different states. */
const diag::Facts facts0 = hardware_facts(/*serving=*/true);
const diag::RunFacts rfacts = run_facts(false);
const std::vector<diag::Finding> findings = diag::check(facts0, rfacts);
std::vector<std::string> serving_bdfs;
for (const diag::CardFacts& c : facts0.cards)
if (c.rank >= 0) serving_bdfs.push_back(c.bdf);
for (const diag::Finding& x : findings)
if (x.level >= diag::Finding::Warn && x.id != "profile-ops" && x.id != "prefix-cache-off")
warn("machine: " + x.what + " (" + x.fix + ")"); /* those two the mode says below, in its terms */
/* What makes the numbers depend on more than the build and the machine. Notes, not problems:
* each is how the engine serves, and the fix makes it a different engine. */
json repro = json::array();
{
bool heat = false;
for (const auto& r : ranks_) heat = heat || r->heat.enabled();
if (heat)
repro.push_back("placement is dynamic: the heat engine moves experts as it sees routing, so the "
"resident set a run starts with depends on the runs before it; --deterministic "
"pins the loader's plan for an A/B comparison");
if (cfg_.prefill_interleave < 0)
repro.push_back("--prefill-interleave auto sizes the decode-only steps between prefill chunks by "
"how long a chunk step took, so a long prompt's step sequence depends on timing; "
"--prefill-interleave 0 or N fixes it");
const std::vector<diag::CardSample> s0 = diag::sample_cards("", serving_bdfs);
for (const diag::CardSample& c : s0)
if (c.perf_level == "auto")
repro.push_back("card " + c.bdf + ": performance level auto, so the firmware picks clocks by "
"load, temperature and power; a fixed level (profile_standard in "
"power_dpm_force_performance_level) holds them for a comparison, below "
"serving clocks");
if (cfg_.diagnose_runs < 5)
repro.push_back(std::to_string(cfg_.diagnose_runs) + " measured run(s) a point: a spread of so "
"few samples says little; --diagnose-runs 5 or more for a comparison");
}
/* ---- prompts: the chat template where the container has one, as the server renders it ---- */
server::TokenizerBridge tok(vocab_);
server::ChatTemplateBridge chat;
const RadChatFormat* fmt = rad_tools_chat_format(plugins_, meta_);
const bool use_chat = vocab_ && !vocab_->chat_template().empty() &&
chat.init(*vocab_, fmt, plugins_.arch_plugin) >= 0 && chat.ready();
if (!use_chat)
warn("no usable chat template: prompts are raw text, so draft acceptance and tokens a step "
"are not those of chat traffic");
/* A counter, the same in every process, so a baseline and a candidate see the same prompts.
* What the salt cannot cover is the tiers that outlive the process; the cached-token check
* after every run catches a hit and refuses the run (below). */
uint64_t salt_n = 0;
auto render = [&](const json& messages, std::vector<int32_t>* out) -> int {
char tag[64];
std::snprintf(tag, sizeof tag, "diagnose request %llu", (unsigned long long)++salt_n);
const json msgs = diag::salt_messages(messages, tag);
if (use_chat) {
server::ChatRenderOptions o;
const std::string& def = cfg_.reasoning_effort;
if (def == "none" || def == "minimal") o.enable_thinking = false;
else if (!def.empty()) o.template_kwargs.emplace("reasoning_effort", json(def).dump());
server::ChatRender r;
std::string why;
const int st = chat.apply(msgs, json::array(), o, &r, &why);
if (st < 0) {
RAD_ERR("diagnose: the chat template refused a workload prompt: %s", why.c_str());
return st;
}
*out = tok.encode(r.prompt, false, /*parse_special=*/true);
} else {
std::string text;
for (const json& m : msgs)
if (m["content"].is_string()) text += m["content"].get<std::string>() + "\n\n";
*out = tok.encode(text, true, /*parse_special=*/false);
}
if (out->empty()) {
RAD_ERR("diagnose: a workload prompt tokenised to nothing");
return RAD_E_STATE;
}
return RAD_OK;
};
auto user = [](const std::string& text) {
return json::array({ json{ { "role", "user" }, { "content", text } } });
};
const int64_t ctx_limit = cfg_.max_ctx > 0 ? (int64_t)cfg_.max_ctx : (int64_t)meta_.n_ctx_train;
const int dec_tokens = cfg_.diagnose_tokens;
const int runs = cfg_.diagnose_runs;
if (cfg_.profile_ops)
warn("--profile-ops is on: it turns recorded passes off and adds barriers, so every step time "
"here is of a different engine than the one that serves");
if (!cfg_.prefix_cache)
warn("--no-prefix-cache: requests do not pay the cache's lookups and publishing, which a "
"server with the cache on does");
const double load0 = loadavg1();
const unsigned ncpu = std::max(1u, std::thread::hardware_concurrency());
if (load0 > (double)ncpu / 4)
warn("the host is busy (load average " + std::to_string(load0) + " on " + std::to_string(ncpu) +
" CPUs): the scheduler's planning between steps competes with it, and emission gaps show that");
/* A prompt of about `want` tokens: a document to summarise, sized by a first render and
* scaled, because the template adds tokens of its own and a vocabulary's characters a token is
* not known in advance. */
auto sized_prompt = [&](int64_t want, uint32_t doc_salt, std::vector<int32_t>* out) -> int {
const std::string ask = "Summarise the document above in detail.";
int64_t chars = want * 4;
for (int pass = 0; pass < 4; ++pass) {
RAD_TRY(render(user(diag::synthetic_document(chars, doc_salt) + "\n\n" + ask), out));
const int64_t got = (int64_t)out->size();
if (got <= want && got >= want - std::max<int64_t>(8, want / 50)) return RAD_OK;
chars = std::max<int64_t>(16, (int64_t)((double)chars * (double)want / (double)got * 0.99));
}
if ((int64_t)out->size() > want) {
RAD_ERR("diagnose: could not fit a prefill prompt in %lld tokens", (long long)want);
return RAD_E_STATE;
}
return RAD_OK;
};
const SamplingParams sp0 = sampling_defaults();
uint64_t next_id = 1;
/* TEMPERATURE 1 FOR EVERY REQUEST, whatever the server's default: it is the temperature the
* model is served at, and draft acceptance -- what an adaptive draft depth is tuned on -- falls
* with temperature, so a greedy workload would tune it for traffic that never comes. top_k,
* top_p and min_p stay the server's. Parity does not need greedy: a fixed seed per request
* makes bit-identical logits sample identical tokens at any temperature. */
const float kTemp = 1.0f;
/* ---- one run: submit, wait, collect ----
* `late` is submitted once every request of `early` has produced `late_after` tokens; the
* early requests are cancelled once every late one has produced `late_after` tokens too, so a
* stream started only to be interfered with does not decode to its limit. */
auto run_set = [&](const std::string& name, diag::PhaseKind kind, const std::vector<Job>& early,
const std::vector<Job>& late, int late_after, diag::PhaseInput* in) -> int {
for (const auto* set : { &early, &late })
for (const Job& jb : *set)
if ((int64_t)jb.prompt.size() + jb.max_tokens > ctx_limit) {
RAD_ERR("diagnose: %s needs %zu + %d tokens of context and the engine serves %lld",
name.c_str(), jb.prompt.size(), jb.max_tokens, (long long)ctx_limit);
return RAD_E_INVAL;
}
sched_.reset_prefix_cache();
const std::vector<diag::CardSample> cards0 = diag::sample_cards("", serving_bdfs);
const SchedMetrics before = sched_.metrics();
const uint64_t seq0 = sched_.step_record_count();
std::vector<std::unique_ptr<server::Sink>> sinks;
auto submit = [&](const std::vector<Job>& jobs) -> int {
std::vector<std::unique_ptr<Request>> reqs;
for (const Job& jb : jobs) {
sinks.push_back(std::make_unique<server::Sink>((size_t)jb.max_tokens + 64));
auto r = std::make_unique<Request>();
r->id = next_id++;
r->prompt = jb.prompt;
r->max_tokens = jb.max_tokens;
r->ignore_eos = jb.ignore_eos;
r->sp = sp0;
if (jb.temp >= 0.0f) r->sp.temp = jb.temp;
r->sp.seed = 0x5eedull * 7919ull + r->id; /* fixed per request, so reruns sample alike */
r->sink = sinks.back().get();
sinks.back()->id = r->id;
reqs.push_back(std::move(r));
}
std::vector<int> rc(reqs.size(), RAD_OK);
/* All at once, under one hold of the queue: the streams are admitted into the same steps. */
sched_.add_all(reqs.data(), reqs.size(), rc.data());
for (int c : rc)
if (c < 0) {
RAD_ERR("diagnose: the scheduler refused a %s request: %s", name.c_str(), rad_strerror(c));
return c;
}
return RAD_OK;
};
auto produced_all = [&](size_t from, size_t to, int64_t n) {
for (size_t i = from; i < to; ++i)
if (!sinks[i]->done() && sinks[i]->n_produced() < n) return false;
return true;
};
auto wait_until = [&](const std::function<bool()>& ready) -> int {
while (!ready()) {
const int ls = loop_status_.load(std::memory_order_acquire);
if (ls < 0) return ls;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return RAD_OK;
};
const int64_t t0 = steady_ns();
RAD_TRY(submit(early));
const size_t n_early = sinks.size();
if (!late.empty()) {
RAD_TRY(wait_until([&] { return produced_all(0, n_early, late_after); }));
RAD_TRY(submit(late));
RAD_TRY(wait_until([&] { return produced_all(n_early, sinks.size(), late_after); }));
for (size_t i = 0; i < n_early; ++i)
if (!sinks[i]->done()) sched_.cancel(sinks[i]->id);
}
for (size_t first = 0;;) {
while (first < sinks.size() && sinks[first]->done()) ++first;
if (first == sinks.size()) break;
const int ls = loop_status_.load(std::memory_order_acquire);
if (ls < 0) return ls;
sinks[first]->wait(200);
}
/* A sink finishes before the step that produced its last token is charged to the
* counters, so wait for the scheduler to go idle and its step count to stop moving. */
for (uint64_t last = UINT64_MAX;;) {
const uint64_t c = sched_.step_record_count();
const SchedMetrics m = sched_.metrics();
if (c == last && m.running == 0 && m.queue_depth == 0) break;
last = c;
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
const std::vector<diag::CardSample> cards1 = diag::sample_cards("", serving_bdfs);
*in = diag::PhaseInput{};
if (!serving_bdfs.empty())
in->cards = { { "start", diag::card_samples_json(cards0) }, { "end", diag::card_samples_json(cards1) } };
in->name = name;
in->kind = kind;
in->streams = (int)sinks.size();
in->wall_ns = steady_ns() - t0;
in->before = before;
in->after = sched_.metrics();
in->steps_lost = sched_.step_records(seq0, &in->steps);
int bad = 0;
for (size_t i = 0; i < sinks.size(); ++i) {
const server::Sink& s = *sinks[i];
diag::RequestTiming t;
const int64_t base = s.t_start_ns();
t.start_ns = base;
t.admitted_ns = s.t_admitted_ns() >= 0 ? base + s.t_admitted_ns() : -1;
t.first_ns = s.t_first_token_ns() >= 0 ? base + s.t_first_token_ns() : -1;
t.last_ns = s.t_last_token_ns() >= 0 ? base + s.t_last_token_ns() : -1;
t.tokens = s.n_produced();
t.prompt = s.n_prompt();
t.cached = s.n_cached();
t.drafted = s.n_drafted();
t.accepted = s.n_draft_accepted();
{
std::vector<server::SinkToken> toks((size_t)std::max<int64_t>(s.n_produced(), 0) + 1);
const size_t got = sinks[i]->read(toks.data(), toks.size());
t.output.reserve(got);
for (size_t k = 0; k < got; ++k) t.output.push_back(toks[k].token);
}
const server::Finish f = s.finish_reason();
const bool cancelled_by_us = i < n_early && !late.empty() && f == server::Finish::Cancelled;
t.ok = f == server::Finish::Length || f == server::Finish::Stop || cancelled_by_us;
t.stopped = f == server::Finish::Stop;
if (!t.ok) {
RAD_ERR("diagnose: a %s request did not finish: %s", name.c_str(),
s.why() ? s.why() : rad_strerror(s.status()));
++bad;
}
in->requests.push_back(t);
sched_.reap(s.id);
}
int64_t cached = 0;
for (const auto& t : in->requests) cached += t.cached;
if (cached > 0)
problems.push_back(name + ": the prefix cache served " + std::to_string(cached) +
" prompt tokens, so this run measured a cache hit");
if (in->steps_lost > 0)
problems.push_back(name + ": " + std::to_string(in->steps_lost) +
" step records were overwritten before they were read");
RAD_INFO("diagnose: %s done in %.2f s", name.c_str(), (double)in->wall_ns / 1e9);
return bad ? RAD_E_STATE : RAD_OK;
};
/* A measured point: one unmeasured run, then `runs` measured ones. `make` builds a run's jobs
* fresh each time, so every run has its own salt. */
auto measure = [&](const std::string& name, diag::PhaseKind kind,
const std::function<int(bool warm, std::vector<Job>*)>& make,
std::vector<json>* out) -> int {
diag::PhaseInput in;
std::vector<Job> jobs;
RAD_TRY(make(true, &jobs));
RAD_TRY(run_set(name + "/warmup", kind, jobs, {}, 0, &in));
for (int r = 0; r < runs; ++r) {
jobs.clear();
RAD_TRY(make(false, &jobs));
RAD_TRY(run_set(name + "/" + std::to_string(r + 1), kind, jobs, {}, 0, &in));
out->push_back(diag::phase_report(in));
}
return RAD_OK;
};
/* ---- categories ---- */
std::vector<diag::CorpusEntry> corpus;
if (!cfg_.diagnose_corpus.empty()) {
std::string why;
if (diag::load_corpus(cfg_.diagnose_corpus, &corpus, &why) < 0) {
RAD_ERR("diagnose: %s", why.c_str());
return RAD_E_INVAL;
}
} else {
corpus = diag::builtin_corpus();
}
std::vector<std::string> cats;
for (const auto& e : corpus)
if (std::find(cats.begin(), cats.end(), e.category) == cats.end()) cats.push_back(e.category);
json categories = json::array();
for (const std::string& cat : cats) {
std::vector<const diag::CorpusEntry*> es;
for (const auto& e : corpus)
if (e.category == cat) es.push_back(&e);
std::vector<json> rs;
/* A category's summary pools its prompts; whether a number repeats is a question about one
* prompt's runs, so each prompt is summarised on its own as well (diag::stability_report). */
json per_prompt = json::array();
for (size_t k = 0; k < es.size(); ++k) {
const diag::CorpusEntry& e = *es[k];
const size_t from = rs.size();
const int mt = e.max_tokens > 0 ? e.max_tokens : dec_tokens;
RAD_TRY(measure("category " + cat + " #" + std::to_string(k + 1), diag::PhaseKind::Decode,
[&](bool warm, std::vector<Job>* jobs) -> int {
Job jb;
RAD_TRY(render(e.messages, &jb.prompt));
jb.max_tokens = warm ? std::min(mt, 32) : mt;
jb.ignore_eos = false; /* the model's own lengths: that is the category */
jb.temp = kTemp;
jobs->push_back(std::move(jb));
return RAD_OK;
},
&rs));
per_prompt.push_back({ { "prompt", (int64_t)k + 1 },
{ "summary", diag::summarize_runs(std::vector<json>(rs.begin() + (std::ptrdiff_t)from, rs.end())) } });
}
int64_t reqs = 0, stopped = 0;
for (const json& r : rs) {
reqs += r["requests"]["count"].get<int64_t>();
stopped += r["requests"]["stopped_on_eos"].get<int64_t>();
}
categories.push_back({ { "category", cat }, { "prompts", (int64_t)es.size() },
{ "requests", reqs }, { "stopped_on_eos", stopped },
{ "summary", diag::summarize_runs(rs) }, { "prompts_summary", per_prompt },
{ "draft_by_position", diag::pool_draft_positions(rs) }, { "runs", rs } });
}
/* ---- concurrency ---- */
json concurrency = json::array();
for (int n : cfg_.diagnose_concurrency) {
if (n > cfg_.max_seqs) {
warn("concurrency " + std::to_string(n) + " skipped: --max-num-seqs is " + std::to_string(cfg_.max_seqs));
continue;
}
std::vector<json> rs;
RAD_TRY(measure("concurrency " + std::to_string(n), diag::PhaseKind::Decode,
[&](bool warm, std::vector<Job>* jobs) -> int {
for (int s = 0; s < n; ++s) {
Job jb;
RAD_TRY(render(corpus[(size_t)s % corpus.size()].messages, &jb.prompt));
jb.max_tokens = warm ? std::min(dec_tokens, 32) : dec_tokens;
jb.ignore_eos = true; /* every stream decodes the whole run */
jb.temp = kTemp;
jobs->push_back(std::move(jb));
}
return RAD_OK;
},
&rs));
concurrency.push_back({ { "streams", n }, { "summary", diag::summarize_runs(rs) },
{ "draft_by_position", diag::pool_draft_positions(rs) }, { "runs", rs } });
}
/* ---- prefill ---- */
const int depth_tokens = std::min(dec_tokens, 64);
json prefill = json::array();
uint32_t doc_salt = 1;
for (int want : cfg_.diagnose_prefill) {
if ((int64_t)want + depth_tokens > ctx_limit) {
warn("prefill " + std::to_string(want) + " skipped: the engine serves " + std::to_string(ctx_limit) +
" tokens of context");
continue;
}
std::vector<json> rs;
int64_t got = 0;
RAD_TRY(measure("prefill " + std::to_string(want), diag::PhaseKind::Prefill,
[&](bool warm, std::vector<Job>* jobs) -> int {
Job jb;
RAD_TRY(sized_prompt(want, doc_salt++, &jb.prompt));
got = (int64_t)jb.prompt.size();
jb.max_tokens = warm ? 1 : depth_tokens;
jb.ignore_eos = true;
jb.temp = kTemp;
jobs->push_back(std::move(jb));
return RAD_OK;
},
&rs));
prefill.push_back({ { "requested_tokens", want }, { "prompt_tokens", got },
{ "summary", diag::summarize_runs(rs) }, { "runs", rs } });
}
/* ---- interference: a prompt arriving into running streams ---- */
json interference = nullptr;
{
const int streams = (int)std::min<int64_t>(4, cfg_.max_seqs - 1);
/* The arriving prompt: the longest measured prefill up to 16k, so its idle TTFT is known. */
const json* pick = nullptr;
for (const json& p : prefill)
if (p["requested_tokens"].get<int>() <= 16384) pick = &p;
if (!pick && !prefill.empty()) pick = &prefill[0];
if (streams < 1 || !pick) {
not_measured.push_back("a prompt arriving into running streams: needs --max-num-seqs of 2 or "
"more and a measured prefill length");
} else {
const int want = (*pick)["requested_tokens"].get<int>();
/* The running streams must outlast the arrival's prefill; they are cancelled once it has
* decoded a little, so their limit only has to be out of reach. */
const int run_tokens = (int)std::min<int64_t>(1 << 16, ctx_limit / 2);
const int after = 16;
std::vector<json> rs;
for (int r = -1; r < runs; ++r) {
std::vector<Job> early, late(1);
for (int s = 0; s < streams; ++s) {
Job jb;
RAD_TRY(render(corpus[(size_t)s % corpus.size()].messages, &jb.prompt));
jb.max_tokens = run_tokens;
jb.ignore_eos = true;
jb.temp = kTemp;
early.push_back(std::move(jb));
}
RAD_TRY(sized_prompt(want, doc_salt++, &late[0].prompt));
late[0].max_tokens = after;
late[0].ignore_eos = true;
late[0].temp = kTemp;
diag::PhaseInput in;
const std::string name = "interference/" + (r < 0 ? std::string("warmup") : std::to_string(r + 1));
RAD_TRY(run_set(name, diag::PhaseKind::Decode, early, late, after, &in));
if (r < 0) continue;
const diag::RequestTiming& a = in.requests.back();
json x;
x["arrival_ttft_ms"] = a.admitted_ns >= 0 && a.first_ns >= 0
? json(std::round((double)(a.first_ns - a.admitted_ns) / 1e3) / 1e3)
: json(nullptr);
/* The running streams' steps only: the arrival's own decode would fill the gap. */
x["interference"] = diag::interference_report(in.steps, a.admitted_ns, a.first_ns);
x["phase"] = diag::phase_report(in);
rs.push_back(x);
}
json idle = nullptr;
const json& ps = (*pick)["summary"];
if (ps.contains("requests.ttft_ms.p50") && ps["requests.ttft_ms.p50"].is_object())
idle = ps["requests.ttft_ms.p50"]["median"];
interference = { { "streams", streams }, { "prompt_tokens", (*pick)["prompt_tokens"] },
{ "idle_ttft_ms", idle },
{ "summary", diag::summarize_paths(rs, { "/arrival_ttft_ms",
"/interference/typical_gap_ms",
"/interference/longest_gap_ms",
"/interference/stall_ratio" }) },
{ "runs", rs } };
}
}
/* ---- the report ---- */
json rep;
{
/* The engine's /server_info is not spliced in: its container is the model's path and its
* control vector carries a file (diag::engine_report says what is kept). */
const json info = json::parse(engine_info(), nullptr, /*allow_exceptions=*/false);
json eng = info.is_object() ? diag::engine_report(info) : json::object();
eng["tp"] = cfg_.tp;
eng["backend"] = device_is_host() ? "host" : "device";
eng["plan"] = cfg_.deterministic ? "deterministic (static placement)" : "dynamic placement";
eng["max_num_seqs"] = cfg_.max_seqs;
eng["context"] = ctx_limit;
rep["engine"] = eng;
}
json w;
w["description"] = std::string(use_chat ? "chat-templated" : "raw-text") + " prompts, each salted at its head; " +
std::to_string(runs) + " measured run(s) a point after one unmeasured; categories from " +
(cfg_.diagnose_corpus.empty() ? std::string("the built-in corpus")
: std::string("the external corpus (its contents are in "
"workload.fingerprint)")) +
" up to " + std::to_string(dec_tokens) + " tokens, ending on EOS; concurrency streams " +
std::to_string(dec_tokens) + " tokens with ignore_eos; prefill then " +
std::to_string(depth_tokens) + " tokens of decode; temperature 1 with the server's "
"top_k/top_p/min_p and a fixed seed per request; prefix cache emptied before every run";
w["sampling"] = { { "temp", kTemp }, { "top_k", sp0.top_k }, { "top_p", sp0.top_p }, { "min_p", sp0.min_p } };
w["reasoning_effort"] = cfg_.reasoning_effort;
w["runs"] = runs;
w["tokens"] = dec_tokens;
{
/* What decides the prompts and the seeds: two reports with the same fingerprint ran the
* same requests in the same order. */
json fp;
json c = json::array();
for (const auto& e : corpus) c.push_back({ e.category, e.messages, e.max_tokens });
fp["corpus"] = c;
fp["tokens"] = dec_tokens;
fp["runs"] = runs;
fp["concurrency"] = cfg_.diagnose_concurrency;
fp["prefill"] = cfg_.diagnose_prefill;
fp["max_num_seqs"] = cfg_.max_seqs;
fp["context"] = ctx_limit;
fp["chat_template"] = use_chat;
fp["reasoning_effort"] = cfg_.reasoning_effort;
fp["sampling"] = w["sampling"];
w["fingerprint"] = diag::workload_fingerprint(fp);
}
rep["workload"] = w;
const double load1 = loadavg1();
if (load1 > (double)ncpu / 4)
warn("the host was busy at the end (load average " + std::to_string(load1) + " on " +
std::to_string(ncpu) + " CPUs)");
json envj;
envj["variables"] = env_snapshot();
envj["loadavg_start"] = load0;
envj["loadavg_end"] = load1;
envj["cpus"] = ncpu;
rep["environment"] = envj;
rep["conditions"] = diag::conditions_report(facts0, rfacts, findings);
{
const json measured = { { "categories", categories }, { "concurrency", concurrency },
{ "prefill", prefill }, { "interference", interference } };
rep["stability"] = diag::stability_report(measured);
for (const json& u : rep["stability"]["unstable"]) {
char b[256];
std::snprintf(b, sizeof b, "%s: %s spread %.1f%% over %s runs (median %s), above %.0f%%",
u["point"].get<std::string>().c_str(), u["metric"].get<std::string>().c_str(),
u["spread_pct"].get<double>(), u["runs"].dump().c_str(), u["median"].dump().c_str(),
diag::kMaxSpreadPct);
warn(b);
}
rep["thermal"] = diag::thermal_report(measured);
for (const json& w : rep["thermal"]["warnings"]) warn(w.get<std::string>());
}
rep["reproducibility"] = repro;
rep["verdict"] = problems.empty() ? std::string("valid") : std::string("NOT A MEASUREMENT -- see problems");
rep["problems"] = problems;
for (const auto& p : problems) warnings.push_back(p);
rep["warnings"] = warnings;
rep["categories"] = categories;
rep["concurrency"] = concurrency;
rep["prefill"] = prefill;
rep["interference"] = interference;
rep["not_measured"] = not_measured;
bool parity_ok = true;
if (!cfg_.diagnose_baseline.empty()) {
/* A baseline is a report another run wrote, possibly on another machine: it is read as
* a supplied file (a capped read and a bounded parse), and a baseline that is not shaped
* like a report is a refusal of the comparison, said in the report, with the run's own
* measurements kept. */
std::string why;
json cmp;
std::string base_text;
bool over = false, deep = false;
const bool base_read =
read_text_file(cfg_.diagnose_baseline, base_text, kMaxContainerFile) == RAD_OK;
const json base = base_read ? json::parse_container(base_text, &over, &deep) : json();
if (!base_read) {
why = "the baseline file cannot be read";
} else if (over || deep || base.is_discarded()) {
why = "the baseline file is not readable JSON";
} else {
int cmp_rc = RAD_E_FORMAT;
try {
cmp_rc = diag::compare_outputs(rep, base, &cmp, &why);
} catch (const json::exception& e) {
why = std::string("the baseline is not shaped like a report: ") + e.what();
cmp_rc = RAD_E_FORMAT;
}
if (cmp_rc == RAD_OK) {
cmp["baseline"] = "an earlier report";
rep["parity"] = cmp;
parity_ok = cmp["verdict"] == "identical" && cmp["acceptance_verdict"] == "no drop";
RAD_INFO("diagnose: parity %s, %lld of %lld requests identical; draft acceptance: %s",
cmp["verdict"].get<std::string>().c_str(),
(long long)cmp["identical"].get<int64_t>(),
(long long)cmp["compared"].get<int64_t>(),
cmp["acceptance_verdict"].get<std::string>().c_str());
}
}
if (!why.empty()) {
rep["parity"] = { { "baseline", "an earlier report" },
{ "verdict", "not compared: " + why } };
parity_ok = false;
RAD_ERR("diagnose: %s", why.c_str());
}
}
const fs::path dir(cfg_.diagnose);
/* Both reports go through the expert-stats writer's discipline (xstats.h): a temp file and a
* rename, the link not followed. A report dir is shared in practice -- /srv/reports, a peer's
* mount -- where a plain ofstream let a pre-created symlink make the run overwrite some other
* file, and a reader polling the dir saw half a report. */
if (const int rc = xs_write_atomic((dir / "diagnose.json").string(), rep.dump(2) + "\n")) {
RAD_ERR("diagnose: cannot write %s", (dir / "diagnose.json").c_str());
return rc;
}
if (const int rc =
xs_write_atomic((dir / "diagnose.md").string(), diag::render_markdown(rep))) {
RAD_ERR("diagnose: cannot write %s", (dir / "diagnose.md").c_str());
return rc;
}
RAD_INFO("diagnose: report in %s", (dir / "diagnose.md").c_str());
return problems.empty() && parity_ok ? RAD_OK : RAD_E_STATE;
}
} /* namespace rad */
+488 -8
View File
@@ -20,6 +20,7 @@
#include <string>
#include <vector>
namespace rad {
/* ------------------------------------------------------------------ the card's step state */
@@ -59,6 +60,11 @@ int Engine::step_state_init() {
* pinned staging beside them. A program without them is refused rather than served
* uncoupled. */
mtp_couple_ = cfg_.draft_coupling;
if (cfg_.draft_verify_traversal && !mtp_couple_) {
RAD_ERR("--draft-verify traversal requires --draft-coupling on: the walk needs the draft's "
"law Q, which only a coupled draft carries");
return RAD_E_INVAL;
}
if (mtp_couple_) {
/* Coupling is defined on a linear chain of drafts: a serial head's rounds, or a block
* drafter whose walk samples each position in turn (DFlash2, dflash_couple_propose), its
@@ -95,6 +101,7 @@ int Engine::step_state_init() {
return RAD_E_STATE;
}
couple_rows_ = sd.shape[1];
couple_planes_ = sd.shape[0];
/* One entry per card slot, indexed by StepEntry::card as slots_host_ is. */
couple_by_card_.assign((size_t)n_slot, RadMtpCoupleDraw{});
couple_draw_stage_ = static_cast<RadMtpCoupleDraw*>(
@@ -107,11 +114,104 @@ int Engine::step_state_init() {
RAD_INFO("DFlash coupled LIVE: %d position(s), x~Q along the candidate walk, maximal "
"coupling at the verify; fixed-seed tokens are NOT preserved", drafter_.depth);
else
RAD_INFO("MTP coupled LIVE: %d linear round(s), x~Q from the final reranked top8, "
RAD_INFO("MTP coupled LIVE: %d linear round(s), x~Q from the draft shortlist, "
"maximal coupling at the verify; fixed-seed tokens are NOT preserved",
drafter_.depth);
}
/* --draft-depth adaptive: the rule, the per-round readback of the chain's states and one host
* event a round. Refused wherever the chain it stops does not exist, rather than served fixed. */
depth_cfg_ = DraftDepthCfg{};
if (cfg_.draft_depth_adaptive) {
if (!mtp_couple_ || drafter_.kind != RAD_DRAFT_SERIAL) {
RAD_ERR("--draft-depth adaptive needs a coupled serial draft chain (--draft-coupling on, a "
"serial head); this deployment's drafter is '%s'",
drafter_.name ? drafter_.name : "(none)");
return RAD_E_INVAL;
}
/* --draft-window adaptive picks a window from the acceptance and the cost of the steps
* before (sched/draft.h); this rule picks the depth inside the step from the head's laws.
* Two controllers on one chain would fight over it. */
if (cfg_.draft_window == DraftWindow::Adaptive) {
RAD_ERR("--draft-depth adaptive and --draft-window adaptive both choose the chain's "
"depth; serve one of them");
return RAD_E_INVAL;
}
depth_cfg_.on = true;
depth_cfg_.max = (int)std::min<int64_t>(drafter_.depth, couple_planes_);
/* --draft-suffix widens the verify window (and the depth the plugin declares) past the head's
* own rounds: the chain never goes deeper than the head's num-speculative-tokens. */
if (cfg_.n_spec_head > 0) depth_cfg_.max = std::min(depth_cfg_.max, cfg_.n_spec_head);
if (cfg_.draft_depth_max > 0) depth_cfg_.max = std::min(depth_cfg_.max, cfg_.draft_depth_max);
depth_cfg_.max = std::min(depth_cfg_.max, (int)RAD_MTP_COUPLE_MAX_ROUNDS);
depth_cfg_.min = std::min(std::max(cfg_.draft_depth_min, 1), depth_cfg_.max);
depth_cfg_.lag = cfg_.draft_depth_lag;
depth_cfg_.stat = cfg_.draft_depth_stat;
depth_cfg_.stop = cfg_.draft_depth_stop;
depth_cfg_.lawless = std::min(3, depth_cfg_.max);
/* --draft-depth-load: the rule's tables (built in, or the configured lists) and the online
* calibration that keeps them. */
if (cfg_.draft_depth_load) {
draft_depth_load_defaults(&depth_cfg_);
depth_cfg_.load = true;
depth_load_on_ = true;
depth_cfg_.load_from = std::max(2, cfg_.draft_depth_load_from);
depth_cfg_.load_min = std::min(std::max(cfg_.draft_depth_load_min, 1), depth_cfg_.max);
depth_cfg_.late = cfg_.draft_depth_load_late;
depth_cfg_.late_lag = 1;
const int kN = DraftDepthCfg::kLoadSeqs, kJ = DraftDepthCfg::kJumps;
/* a list by drafting rows 1 .. 8; a short one repeats its last number */
auto by_rows = [&](const std::string& l, double* dst) {
double v[DraftDepthCfg::kLoadSeqs];
const int k = l.empty() ? 0 : draft_depth_parse_list(l.c_str(), v, kN, 0.0, 1000.0);
for (int i = 0; i < kN && k > 0; ++i) dst[1 + i] = v[std::min(i, k - 1)];
dst[0] = dst[1];
};
by_rows(cfg_.draft_depth_load_tok_ms, depth_cfg_.load_lam);
by_rows(cfg_.draft_depth_load_row_ms, depth_cfg_.load_row_ms);
by_rows(cfg_.draft_depth_load_round_ms, depth_cfg_.load_round_ms);
if (!cfg_.draft_depth_load_jump_ms.empty()) {
double v[DraftDepthCfg::kJumps] = {};
const int k = draft_depth_parse_list(cfg_.draft_depth_load_jump_ms.c_str(), v, kJ, 0.0, 1000.0);
for (int nn = 0; nn <= kN && k > 0; ++nn)
for (int j = 0; j < kJ; ++j) depth_cfg_.load_jump_ms[nn][j] = j < k ? v[j] : 0.0;
}
depth_online_on_ = cfg_.draft_depth_load_online;
draft_depth_online_begin(depth_cfg_, &depth_online_);
depth_pend_.assign((size_t)n_slot, DepthPend{});
if (const char* e = std::getenv("RADIANCE_DEBUG_CONC_LOG"); e && *e) {
depth_log_ = std::fopen(e, "w");
if (depth_log_) std::setvbuf(depth_log_, nullptr, _IOFBF, 1 << 20);
}
}
depth_rb_ = static_cast<RadMtpCoupleState*>(rad_dev_alloc(
(int64_t)RAD_MTP_COUPLE_MAX_ROUNDS * couple_rows_ * (int64_t)sizeof(RadMtpCoupleState),
RAD_MEM_HOST_PINNED));
if (!depth_rb_) return RAD_E_NOMEM;
for (RadEvent& e : depth_ev_)
RAD_TRY(rad_event_create_as(&e, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
depth_row_.assign((size_t)n_slot, DraftDepthRow{});
depth_of_.assign((size_t)n_slot, 0);
RAD_INFO("draft depth adaptive: 1..%d draft(s) a step, the chain goes on while the product of "
"the head's %s probabilities is >= %.3f (decided %d round(s) behind, %d round(s) "
"always run); a row with no law drafts %d",
depth_cfg_.max, depth_cfg_.stat == DRAFT_DEPTH_PATH ? "drawn-token" : "top",
depth_cfg_.stop, depth_cfg_.lag, depth_cfg_.min, depth_cfg_.lawless);
if (depth_cfg_.load)
RAD_INFO("draft depth load-aware: a step drafting for %d sequence(s) or more runs a round "
"for the rows whose expected accepted drafts pay their verify rows, the tile "
"they open and the round (%d round(s) always run; late choice of the verify's "
"rows %s); tables %s (at 8 sequences: %.3f tok/ms, a row %.3f ms, a round "
"%.3f ms, past %d/%d/%d/%d rows +%.2f/%.2f/%.2f/%.2f ms)",
depth_cfg_.load_from, depth_cfg_.load_min, depth_cfg_.late ? "on" : "off",
depth_online_on_ ? "calibrated online from these" : "static",
depth_cfg_.load_lam[8], depth_cfg_.load_row_ms[8], depth_cfg_.load_round_ms[8],
depth_cfg_.load_jump_at[0], depth_cfg_.load_jump_at[1], depth_cfg_.load_jump_at[2],
depth_cfg_.load_jump_at[3], depth_cfg_.load_jump_ms[8][0],
depth_cfg_.load_jump_ms[8][1], depth_cfg_.load_jump_ms[8][2],
depth_cfg_.load_jump_ms[8][3]);
}
RAD_TRY(rad_event_create_as(&step_end_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
RAD_TRY(rad_event_create_as(&tok_end_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
return RAD_OK;
@@ -131,6 +231,11 @@ void Engine::step_state_fini() {
if (couple_readback_) rad_dev_free(couple_readback_, RAD_MEM_HOST_PINNED);
couple_draw_stage_ = nullptr;
couple_readback_ = nullptr;
if (depth_rb_) rad_dev_free(depth_rb_, RAD_MEM_HOST_PINNED);
depth_rb_ = nullptr;
for (RadEvent& e : depth_ev_) { if (e) rad_event_destroy(e); e = nullptr; }
if (depth_log_) std::fclose(depth_log_);
depth_log_ = nullptr;
if (step_end_) rad_event_destroy(step_end_);
step_end_ = nullptr;
if (tok_end_) rad_event_destroy(tok_end_);
@@ -215,7 +320,7 @@ int Engine::tree_compact(int rows) {
const int64_t row = bits > 0 ? b->shape[3] * bits / 8 : 0;
int32_t layers = 0;
for (int32_t s : b->layer_slot) layers += s >= 0;
if (row <= 0 || row % 16 || (bits != 8 && bits != 16 && bits != 32) ||
if (row <= 0 || row % 4 || (bits != 8 && bits != 16 && bits != 32) ||
(b->bytes && (int64_t)layers * b->layer_stride > b->bytes)) {
RAD_ERR("speculation: KV group %zu's cache (%s, %lld-byte rows) is not one a tree's "
"acceptance can move", g, rad_dtype_name(b->dtype), (long long)row);
@@ -239,6 +344,248 @@ int Engine::tree_compact(int rows) {
return RAD_OK;
}
/* ------------------------------------------------------------------ --draft-depth adaptive
*
* The chain's depth is decided while it is drafted (sched/draft_depth.h), so the rounds cannot all
* be queued behind the step as a fixed chain's are: round j is issued once the statistic of round
* j - 1 - lag is known. That costs the host one tiny readback a round (the round's state rows of
* the drafting sequences, rank 0's copy; every rank holds the same) and a wait for it. With lag 1
* the card is running round j - 1 meanwhile, so nothing idles as long as the host answers within a
* round (about 0.5 ms; reading the row and issuing a recorded pass takes about 0.1 ms). The next
* verify is issued the same way, right after the chain's last decision, with exactly the rows the
* chain has (Engine::issue_ahead): each row count is its own recorded pass.
*
* The commit of the step in flight moves behind those decisions (the step loop collects after
* issue_ahead), so its tokens are streamed up to the chain's rounds later than with a fixed chain;
* the card is not held up by that. */
int Engine::depth_row_nodes(int i) const {
if (!depth_cfg_.on) return serial_done_;
if (i < 0 || (size_t)i >= depth_of_.size()) return 0;
return depth_of_[(size_t)i];
}
/* Behind the pass of round `round`: its state rows of the `n` drafting sequences to the host, and
* the event the driver waits on. */
int Engine::depth_readback_issue(int round, int n) {
if (round < 1 || round > (int)RAD_MTP_COUPLE_MAX_ROUNDS || round > (int)couple_planes_ || n <= 0)
return RAD_OK;
Rank& r0 = *ranks_[0];
const char* state = static_cast<const char*>(r0.ctx.buf_ptr(couple_state_buf_));
if (!state) return RAD_E_STATE;
const int64_t plane = couple_rows_ * (int64_t)sizeof(RadMtpCoupleState);
RAD_TRY(rad_memcpy_async(depth_rb_ + (int64_t)(round - 1) * couple_rows_,
state + (int64_t)(round - 1) * plane,
(int64_t)n * (int64_t)sizeof(RadMtpCoupleState), r0.ctx.stream()));
RAD_TRY(rad_event_record(depth_ev_[round - 1], r0.ctx.stream()));
depth_issued_[round - 1] = true;
return RAD_OK;
}
/* Waits for the statistics of every round up to `round` and feeds them to the rows. A round whose
* readback was never issued (its pass did not run) leaves the rows without a law. */
int Engine::depth_observe_upto(int round, int n, const StepOut& so) {
while (depth_seen_ < round) {
const int r = depth_seen_ + 1;
const bool have = r <= (int)RAD_MTP_COUPLE_MAX_ROUNDS && depth_issued_[r - 1];
if (have) {
RadEvent ev = depth_ev_[r - 1];
const auto t0 = std::chrono::steady_clock::now();
int q = rad_event_query(ev);
if (q < 0) return q;
if (q == 0) {
/* The ids' copy sits ahead of every draft pass: block for it (the trunk's whole
* forward pass may be in front), then poll, which answers within a microsecond of
* the card where an interrupt takes tens. */
if (so.early && depth_seen_ == 0) RAD_TRY(rad_event_sync(tok_end_));
const auto t1 = std::chrono::steady_clock::now();
bool blocked = false;
for (uint32_t spin = 0;; ++spin) {
q = rad_event_query(ev);
if (q != 0) break;
if ((spin & 255u) == 255u &&
std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t1)
.count() > (double)kDepthSpinUs) {
blocked = true;
break;
}
#if defined(__x86_64__) || defined(__i386__)
__builtin_ia32_pause();
#endif
}
if (q < 0) return q;
if (blocked) ++depth_stats_.blocked;
++depth_stats_.waits;
} else {
/* Already there: the host was behind the card by the time it asked. */
++depth_stats_.late;
}
/* The wait proper: what a host wait does to the fences of the dispatches that follow
* (the copy wrote host memory), and the block when the poll gave up. */
RAD_TRY(rad_event_sync(ev));
const auto t2 = std::chrono::steady_clock::now();
depth_stats_.wait_us += std::chrono::duration<double, std::micro>(t2 - t0).count();
/* The card's cycle by the last step's depth: the host waits for every step's first
* statistic, so two of them in a row are one cycle apart. A gap of 30 ms or more is
* no decode cycle (an idle engine, or the next request's prefill, in between). */
if (r == 1) {
const double us = std::chrono::duration<double, std::micro>(t2 - depth_e1_).count();
if (q == 1 && depth_last_ >= 1 && depth_last_ <= (int)RAD_MTP_COUPLE_MAX_ROUNDS &&
us > 0 && us < 30000.0) {
depth_stats_.cyc_us[depth_last_] += us;
++depth_stats_.cyc_n[depth_last_];
}
depth_e1_ = t2;
}
}
for (int i = 0; i < n; ++i) {
DraftDepthRow& row = depth_row_[(size_t)i];
double st = -1.0;
if (have && !row.lawless) {
const RadMtpCoupleState& cs = depth_rb_[(int64_t)(r - 1) * couple_rows_ + i];
/* this step's draw for this row, or a stale plane: no law */
if (!std::memcmp(&cs.draw, &couple_draw_stage_[(size_t)i], sizeof cs.draw))
st = draft_depth_stat(cs, r, depth_cfg_.stat);
}
draft_depth_observe(&row, r, st);
}
depth_seen_ = r;
}
return RAD_OK;
}
/* The adaptive chain's tuning line: the shares of each depth and what the host waits cost, then
* by the drafts a step made, the card's cycle and the drafts its verify accepted. Logged every
* 4096 drafting rows and at shutdown. */
void Engine::depth_log_stats(const char* when) {
const DepthStats& ds = depth_stats_;
if (!depth_cfg_.on || ds.rows == 0 || (depth_logged_ == ds.rows && !std::strcmp(when, "final"))) return;
depth_logged_ = ds.rows;
std::string h;
for (int d2 = 1; d2 <= depth_cfg_.max; ++d2)
h += fmt("%s%d:%.3f", d2 > 1 ? " " : "", d2, (double)ds.hist[d2] / (double)ds.rows);
RAD_INFO("draft depth adaptive (%s): %llu drafting step(s), drafts/row %.3f, rounds/step %.3f, "
"depth shares [%s], lawless rows %llu; host waits %llu (%.1f us each, %llu ended "
"blocked), statistics already there %llu",
when, (unsigned long long)ds.steps, (double)ds.drafts / (double)ds.rows,
(double)ds.rounds / (double)ds.steps, h.c_str(), (unsigned long long)ds.lawless,
(unsigned long long)ds.waits,
ds.waits + ds.late ? ds.wait_us / (double)(ds.waits + ds.late) : 0.0,
(unsigned long long)ds.blocked, (unsigned long long)ds.late);
std::string by;
for (int d2 = 1; d2 <= depth_cfg_.max; ++d2)
by += fmt("%s%d: %.0f us (%llu), %.3f accepted (%llu)", d2 > 1 ? "; " : "", d2,
ds.cyc_n[d2] ? ds.cyc_us[d2] / (double)ds.cyc_n[d2] : 0.0,
(unsigned long long)ds.cyc_n[d2],
ds.acc_n[d2] ? (double)ds.acc[d2] / (double)ds.acc_n[d2] : 0.0,
(unsigned long long)ds.acc_n[d2]);
RAD_INFO("draft depth adaptive (%s): by drafts made, the card's cycle and the drafts the "
"verify accepted -- %s", when, by.c_str());
if (depth_load_on_) depth_load_log(when);
}
/* --draft-depth-load, once a step, after its draft passes ended and its verify was committed:
* the step's milliseconds (since the step before it ended, when both were pure decode steps of the
* same drafting rows), its verify rows, rounds and tokens for the rule's rate and prices; every 64
* steps the tables again from what was measured. Between steps: the next step's chain is decided
* after this returns, from tables that nothing of that step went into (sched/draft_depth.h). */
void Engine::depth_step_note(const RadBatch* b, const StepOut& so) {
const auto now = std::chrono::steady_clock::now();
const StepPlan& plan = sched_.plan();
bool pure = b->phase == RAD_PHASE_DECODE;
int tokens = 0;
for (size_t i = 0; i < plan.e.size(); ++i) {
if (plan.e[i].is_prefill) pure = false;
if (i < so.first_row.size() && so.first_row[i] >= 0)
tokens += 1 + std::max(0, i < so.accepted.size() ? so.accepted[i] : 0);
}
const int n = serial_rows_;
if (depth_online_on_ && pure && n >= 1 && serial_done_ >= 1 && tokens > 0 &&
depth_note_step_ == b->step - 1 && depth_note_rows_ == n) {
const double ms = std::chrono::duration<double, std::milli>(now - depth_note_t_).count();
draft_depth_online_step(depth_cfg_, &depth_online_, n, (int)b->n_tok, serial_done_, ms, tokens);
}
depth_note_t_ = now;
depth_note_step_ = pure ? b->step : -2;
depth_note_rows_ = n;
if (depth_log_) depth_log_step(b, so);
if (depth_online_on_ && (++depth_note_n_ & 63u) == 0) {
draft_depth_online_refresh(&depth_cfg_, &depth_online_);
if ((depth_note_n_ & 32767u) == 0) depth_load_log("running");
if (depth_log_) {
/* K: the tables after a refresh, at the step's drafting rows */
const int nn = draft_depth_seqs(std::max(n, 1));
std::string k = fmt("K %d %d %.4f %.4f %.4f", b->step, nn, depth_cfg_.load_lam[nn],
depth_cfg_.load_row_ms[nn], depth_cfg_.load_round_ms[nn]);
for (int j = 0; j < DraftDepthCfg::kJumps; ++j) k += fmt(" %.3f", depth_cfg_.load_jump_ms[nn][j]);
for (int t = 0; t < 3; ++t)
for (int j = 2; j <= depth_cfg_.max && j <= DraftDepthCfg::kCalRounds; ++j) {
k += fmt(" | %d,%d", t, j);
for (int x = 0; x < draft_depth_knots(depth_cfg_); ++x)
k += fmt(" %.3f", depth_cfg_.cal_p[t][j][x]);
}
std::fprintf(depth_log_, "%s\n", k.c_str());
}
}
}
/* What the load-aware rule's tables hold now, by drafting rows that were measured. */
void Engine::depth_load_log(const char* when) const {
const DraftDepthOnline& o = depth_online_;
std::string t;
for (int n = 1; n <= DraftDepthCfg::kLoadSeqs; ++n) {
if (o.reg[n].n < 64 && o.lam[n].n < 32) continue;
t += fmt("%s%d seq: %.3f tok/ms, row %.3f ms, round %.3f ms, tiles +%.2f/%.2f/%.2f/%.2f ms "
"(%lld steps)", t.empty() ? "" : "; ", n, depth_cfg_.load_lam[n],
depth_cfg_.load_row_ms[n], depth_cfg_.load_round_ms[n], depth_cfg_.load_jump_ms[n][0],
depth_cfg_.load_jump_ms[n][1], depth_cfg_.load_jump_ms[n][2],
depth_cfg_.load_jump_ms[n][3], (long long)o.reg[n].n);
}
std::string c;
for (int j = 2; j <= depth_cfg_.max && j <= DraftDepthCfg::kCalRounds; ++j) {
c += fmt("%sdraft %d:", j > 2 ? "; " : "", j);
for (int x = 0; x < draft_depth_knots(depth_cfg_); ++x) c += fmt(" %.2f", depth_cfg_.cal_p[2][j][x]);
}
RAD_INFO("draft depth load-aware (%s): %s calibration, %lld chain(s) and %lld step(s) counted "
"(%lld stalled step(s) left out), %lld refresh(es); %s; acceptance by the confidence "
"that includes the draft's own law, at %.2f .. %.2f -- %s", when,
depth_online_on_ ? "online" : "static", (long long)o.chains, (long long)o.steps,
(long long)o.outliers, (long long)o.refreshes, t.empty() ? "no step count measured yet" : t.c_str(),
depth_cfg_.cal_x[0], depth_cfg_.cal_x[draft_depth_knots(depth_cfg_) - 1], c.c_str());
}
/* RADIANCE_DEBUG_CONC_LOG: the step just finished, one line.
* S step ns phase n_seq n_tok rounds drafting_rows load_step | entry;... | chain;...
* An entry is a sequence of the step's verify: seq,is_prefill,n_tokens,drafts verified,drafts
* accepted (-1: no token row),ctx_len. A chain is what a drafting row made behind the step, for
* the next verify: seq,depth,the rule's round,rounds that ran for it,lawless, then each of those
* rounds' top mass. Called after finish_serial_drafter, while plan() still describes the step. */
void Engine::depth_log_step(const RadBatch* b, const StepOut& so) {
const StepPlan& plan = sched_.plan();
std::string e, d;
for (size_t i = 0; i < plan.e.size(); ++i) {
const StepEntry& x = plan.e[i];
e += fmt("%s%llu,%d,%d,%d,%d,%d", i ? ";" : "", (unsigned long long)x.seq, (int)x.is_prefill,
(int)x.n_tokens, (int)x.n_spec,
i < so.accepted.size() && so.first_row[i] >= 0 ? (int)so.accepted[i] : -1,
(int)x.ctx_len);
}
for (int i = 0; i < serial_rows_ && serial_done_ > 0; ++i) {
const DraftDepthRow& row = depth_row_[(size_t)i];
const int ran = serial_done_;
d += fmt("%s%llu,%d,%d,%d,%d", i ? ";" : "", (unsigned long long)serial_row_[(size_t)i].seq,
depth_row_nodes(i), depth_load_step_ ? row.rule : 0, ran, (int)row.lawless);
if (mtp_couple_ && couple_readback_)
for (int r = 1; r <= ran && r <= (int)couple_planes_; ++r)
d += fmt(",%.4f", draft_depth_stat(couple_readback_[(int64_t)(r - 1) * couple_rows_ + i],
r, DRAFT_DEPTH_TOP));
}
const uint64_t ns = (uint64_t)std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
std::fprintf(depth_log_, "S %d %llu %d %lld %lld %d %d %d | %s | %s\n", b->step,
(unsigned long long)ns, (int)b->phase, (long long)b->n_seq, (long long)b->n_tok,
serial_done_, serial_rows_, (int)depth_load_step_, e.c_str(), d.c_str());
}
/* Issue the step's draft passes behind it, without waiting. After the trunk's ranks join: the
* acceptance on every rank, the sampled-id readback (before a round can overwrite them), the
* history pass and every round, then the final proposal into the slots and their readback.
@@ -248,8 +595,9 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
serial_rounds_ = 0;
serial_rows_ = 0;
serial_done_ = 0;
const bool history_only = drafter_.kind == RAD_DRAFT_HISTORY;
/* A step issued ahead continues from the card's acceptance, so run it even without drafts. */
if (!serial_drafting()) {
if (!serial_drafting() && !history_only) {
if (pipelining_) RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
return RAD_OK;
}
@@ -257,7 +605,11 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
RAD_TRY(collect_issue(so, /*fence=*/true));
int rounds = drafter_.depth;
/* serial_begin needs a pass budget even for history alone. The scheduler's speculative
* depth is still zero there, so it stages history rows but never reserves a proposal row. */
int rounds = history_only ? 1 : drafter_.depth;
/* --draft-depth-max below the head's declared depth: no round past it is ever asked for. */
if (depth_cfg_.on && rounds > depth_cfg_.max) rounds = depth_cfg_.max;
serial_row_.resize((size_t)cfg_.max_seqs);
/* `n` counts rows that can draft. It can be zero while the history pass still has work (a
* mid-prompt sequence has hidden states the head needs but no token to propose from). */
@@ -275,17 +627,59 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
static double a_batch = 0, a_samp = 0, a_rel = 0, a_iss = 0;
static long n_pass = 0;
/* --draft-depth adaptive: every row starts a chain; a greedy row (no draw) has no law. */
const bool adepth = depth_cfg_.on && n > 0;
depth_load_step_ = false;
if (adepth) {
depth_seen_ = 0;
for (bool& b : depth_issued_) b = false;
for (int i = 0; i < n; ++i) {
draft_depth_begin(depth_cfg_, &depth_row_[(size_t)i], couple_draw_stage_[(size_t)i].mode != 1);
depth_of_[(size_t)i] = 0;
}
/* --draft-depth-load: the next verify's rows beside the drafting sequences' (the plan's
* other token rows), and whether this step has the sequences for the load-aware rule. */
depth_other_rows_ = 0;
for (const StepEntry& pe : sched_.plan().e) depth_other_rows_ += pe.produces_token;
depth_other_rows_ = std::max(0, depth_other_rows_ - n);
depth_load_step_ = depth_cfg_.load && n >= depth_cfg_.load_from;
}
/* Pass 0, then rounds 2..rounds: round 1 has no pass of its own. */
for (int rd = 0; rd <= rounds; rd += rd == 0 ? 2 : 1) {
if (rd > 0 && n <= 0) break;
/* The adaptive chain: round rd runs only for a row whose confidence up to round
* rd - 1 - lag holds (sched/draft_depth.h); the pass runs while any row goes on. */
if (adepth && rd >= 2) {
const int need = draft_depth_need(depth_cfg_, rd);
if (need >= 1) RAD_TRY(depth_observe_upto(need, n, so));
bool any = false;
if (depth_load_step_)
any = draft_depth_go_load(depth_cfg_, depth_row_.data(), n, rd, depth_other_rows_);
else
for (int i = 0; i < n; ++i)
any = draft_depth_go(depth_cfg_, &depth_row_[(size_t)i], rd) || any;
if (!any) break;
}
const auto tA = std::chrono::steady_clock::now();
const RadBatch* db = sched_.serial_batch(rd, step);
if (!db) { if (rd == 0) continue; break; }
if (!db) {
if (history_only) {
RAD_ERR("'%s' calibration: missing history batch for step %d", drafter_.name, step);
return RAD_E_STATE;
}
if (rd == 0) continue;
break;
}
/* Pass 0 is the history pass, writing the head's own K and V (nothing else does). It is
* also draft round 1 for drafting rows, whose inputs are the last row of their history run
* (RadBatch::draft_out_ids), so it ends in the lm_head over those rows. Round r >= 2 embeds
* round r-1's proposal, which the advance takes from the proposal buffer on the card. */
const int drafted = rd == 0 ? (int)db->n_draft_out : n;
if (history_only && (n != 0 || drafted != 0 || rd != 0)) {
RAD_ERR("'%s' history-only calibration cannot reserve draft proposals", drafter_.name);
return RAD_E_STATE;
}
RAD_TRY(advance_all(rd == 0 ? ADV_HIST : ADV_ROUND, rd, rd > 0));
const auto tB = std::chrono::steady_clock::now();
@@ -330,8 +724,41 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
}
if (rd > 0) serial_done_ = rd;
else if (drafted > 0) serial_done_ = 1;
/* This round's states to the host, when a later round's decision reads them. */
/* The late choice reads every round but the last. */
if (adepth && serial_done_ == (rd > 0 ? rd : 1) &&
(serial_done_ <= draft_depth_need(depth_cfg_, rounds) ||
(depth_load_step_ && depth_cfg_.late)))
RAD_TRY(depth_readback_issue(serial_done_, n));
}
if (serial_done_ <= 0 || n <= 0) return RAD_OK;
/* The late choice (--draft-depth-load-late): every row's verified prefix again, from the
* rounds read by now and the wait for all but the last (it is still running, so the card is
* not held up as long as the wait and the next step's issue fit in it). */
if (adepth && depth_load_step_ && depth_cfg_.late && serial_done_ >= 2) {
const int upto = std::max(depth_seen_, serial_done_ - std::max(0, depth_cfg_.late_lag));
if (upto > depth_seen_) RAD_TRY(depth_observe_upto(upto, n, so));
draft_depth_select(depth_cfg_, depth_row_.data(), n, serial_done_, depth_other_rows_);
}
if (adepth) {
DepthStats& ds = depth_stats_;
++ds.steps;
ds.rounds += (uint64_t)serial_done_;
for (int i = 0; i < n; ++i) {
const DraftDepthRow& row = depth_row_[(size_t)i];
const int d = std::max(1, std::min(row.depth, serial_done_));
depth_of_[(size_t)i] = d;
++ds.rows;
ds.drafts += (uint64_t)d;
ds.lawless += row.lawless;
++ds.hist[std::min(d, (int)RAD_MTP_COUPLE_MAX_ROUNDS)];
}
depth_last_ = 0;
for (int i = 0; i < n; ++i) depth_last_ = std::max(depth_last_, (int)depth_of_[(size_t)i]);
if (ds.rows >= depth_logged_ + 4096) depth_log_stats("running");
} else {
depth_last_ = 0;
}
/* The last round's proposal into the slots, then rank 0's slots back to the host. Only the
* drafting rows: at depth 1 the last pass is the history pass, whose later rows only carried
@@ -356,7 +783,12 @@ int Engine::issue_serial_drafter(int step, StepOut& so) {
* set_draft, and move the history watermark. The card's acceptance positioned every draft pass,
* so a disagreement is a defect and the step is refused. */
int Engine::finish_serial_drafter(const StepOut& so) {
if (!serial_drafting() || serial_rounds_ <= 0) return RAD_OK;
if (serial_rounds_ <= 0) return RAD_OK;
if (drafter_.kind == RAD_DRAFT_HISTORY) {
sched_.serial_end(0); /* advance the history watermark, not the draft chain */
return RAD_OK;
}
if (!serial_drafting()) return RAD_OK;
const StepPlan& plan = sched_.plan();
if (serial_done_ > 0 && serial_rows_ > 0) {
for (size_t i = 0; i < plan.e.size(); ++i) {
@@ -372,7 +804,29 @@ int Engine::finish_serial_drafter(const StepOut& so) {
}
}
}
/* --draft-depth adaptive: what the verify of d drafts accepted, by d (the tuning line). */
if (depth_cfg_.on) {
for (size_t i = 0; i < plan.e.size(); ++i) {
const StepEntry& e = plan.e[i];
if (so.first_row[i] < 0 || e.n_spec <= 0 || e.n_spec > (int)RAD_MTP_COUPLE_MAX_ROUNDS ||
e.suffix || e.card < 0 || (size_t)e.card >= couple_by_card_.size())
continue;
const RadMtpCoupleDraw& d = couple_by_card_[(size_t)e.card];
if (d.seq != e.seq || d.mode != 1) continue;
/* --draft-depth-load: the chain this verify settled, with the confidences its
* decisions read, for the online calibration. */
if (depth_online_on_ && (size_t)e.card < depth_pend_.size()) {
const DepthPend& pd = depth_pend_[(size_t)e.card];
if (pd.depth > 0 && pd.seq == e.seq && pd.depth == e.n_spec)
draft_depth_online_chain(depth_cfg_, &depth_online_, pd.depth, pd.rule,
std::max(0, so.accepted[i]), pd.s, pd.n_s);
}
depth_stats_.acc[e.n_spec] += (uint64_t)std::max(0, so.accepted[i]);
++depth_stats_.acc_n[e.n_spec];
}
}
sched_.serial_end(serial_done_);
for (DepthPend& pd : depth_pend_) pd.depth = 0; /* settled above, or never verified */
if (serial_done_ <= 0 || serial_rows_ <= 0) return RAD_OK;
Rank& r0 = *ranks_[0];
@@ -388,9 +842,35 @@ int Engine::finish_serial_drafter(const StepOut& so) {
* cannot snapshot its state); the sampler would refuse the next step otherwise. */
if (!r0.sampler.allows_speculation(serial_row_[(size_t)i].seq)) continue;
const uint64_t seq = serial_row_[(size_t)i].seq;
const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)rounds], done);
/* Under --draft-depth adaptive the row's own chain: the drafts the step issued ahead was
* planned with (issue_ahead's expect_draft), a prefix of the rounds that ran. */
const int row_nodes = depth_cfg_.on ? depth_row_nodes(i) : done;
const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)rounds], row_nodes);
/* --draft-depth-load: the chain as the next verify will settle it -- its depth, the round
* the rule sent it to, and the statistics of the rounds that ran for it. */
if (depth_online_on_ && rc == RAD_OK && mtp_couple_ && couple_readback_ && row_nodes >= 1 &&
!depth_row_[(size_t)i].lawless) {
const int32_t card = serial_row_[(size_t)i].card;
if (card >= 0 && (size_t)card < depth_pend_.size()) {
DepthPend& pd = depth_pend_[(size_t)card];
pd.seq = seq;
pd.depth = row_nodes;
pd.rule = depth_load_step_ ? depth_row_[(size_t)i].rule : 0;
pd.n_s = 0;
const int ran = std::min(done, (int)std::min<int64_t>(RAD_MTP_COUPLE_MAX_ROUNDS, couple_planes_));
for (int r = 1; r <= ran; ++r) {
const RadMtpCoupleState& cs = couple_readback_[(int64_t)(r - 1) * couple_rows_ + i];
if (std::memcmp(&cs.draw, &couple_draw_stage_[(size_t)i], sizeof cs.draw)) break;
const double st = draft_depth_stat(cs, r, DRAFT_DEPTH_TOP);
if (st < 0.0) break;
pd.s[r - 1] = (float)st;
pd.n_s = r;
}
if (pd.n_s < row_nodes) pd.depth = 0; /* a round with no law: not counted */
}
}
if (mtp_couple_)
RAD_TRY(bind_couple(seq, i, done, rc == RAD_OK, serial_row_[(size_t)i].card));
RAD_TRY(bind_couple(seq, i, row_nodes, rc == RAD_OK, serial_row_[(size_t)i].card));
}
return RAD_OK;
}
+1
View File
@@ -113,4 +113,5 @@ struct TierPump {
* still hold the previous step's values when the step loop dumps. */
void dump_buffers(Ctx& ctx, int step, const char* phase = "");
} /* namespace rad */
+68 -4
View File
@@ -54,7 +54,7 @@ const Replaced kReplaced[] = {
const char* const kRepeatable[] = { "lora", "allow-host", "trusted-proxy" };
/* The fleet's own keys on a model. `defaults:` may carry every one but aliases (read_model_keys). */
const char* const kModelFleetKeys[] = { "aliases", "priority", "pin", "ttl", "flex", "park" };
const char* const kModelFleetKeys[] = { "aliases", "priority", "pin", "ttl", "flex", "park", "cards" };
const char* const kTopKeys[] = { "server", "cards", "memory", "scheduler", "defaults", "models", "groups" };
@@ -309,7 +309,7 @@ private:
if (level != "server" && (in(kServerKeys, key) || key == "log")) return key + " belongs under server:";
if (level != "memory" && level != "model" && in(kMemoryFlagKeys, key))
return key + " belongs under memory: or a model";
if (level != "memory" && (key == "host-mib" || key == "disk-tier"))
if (level != "memory" && (key == "host-mib" || key == "disk-tier" || key == "card-headroom-mib"))
return key + " belongs under memory:";
if (level != "model" && flags_.count(key))
return key + " is a per-model key; put it under the model or defaults:";
@@ -382,10 +382,27 @@ int Reader::read_memory(const Item& sec, FleetConfig* out) {
if (int s = scalar_text(it, &out->disk_tier); s < 0) return s;
continue;
}
if (k == "card-headroom-mib") {
if (!it.node.is_map())
return fail(it.node, it.path + " takes a map of card ordinal to MiB, as {0: 4096}");
std::vector<Item> cards;
if (int s = children(it.node, it.path, &cards); s < 0) return s;
for (const Item& c : cards) {
char* end = nullptr;
const long card = std::strtol(c.key.c_str(), &end, 10);
if (c.key.empty() || *end || card < 0 || card > 255)
return fail(c.node, c.path + ": a card is named by its ordinal, 0 or above");
int64_t mib = 0;
if (int s = integer(c, 0, INT64_MAX / (1 << 20), &mib); s < 0) return s;
out->card_headroom_mib[(int)card] = mib;
}
continue;
}
if (!in(kMemoryFlagKeys, k)) {
std::vector<std::string> valid = as_vector(kMemoryFlagKeys);
valid.push_back("host-mib");
valid.push_back("disk-tier");
valid.push_back("card-headroom-mib");
return refuse_key(it, "memory", "memory", valid);
}
if (int s = flag_args(it, &memory_args_); s < 0) return s;
@@ -403,10 +420,12 @@ int Reader::read_scheduler(const Item& sec, FleetConfig* out) {
if (k == "load-timeout") s = duration(it, &out->load_timeout_ms);
else if (k == "drain-timeout") s = duration(it, &out->drain_timeout_ms);
else if (k == "keepalive") s = duration(it, &out->keepalive_ms);
else if (k == "stuck-exit") s = duration(it, &out->stuck_exit_ms);
else if (k == "warm-up") s = boolean(it, &out->warm_up);
else {
return fail(it.node, "scheduler." + k + " is not a scheduler key" +
suggest(k, { "load-timeout", "drain-timeout", "keepalive", "warm-up" }));
suggest(k, { "load-timeout", "drain-timeout", "keepalive",
"stuck-exit", "warm-up" }));
}
if (s < 0) return s;
}
@@ -464,6 +483,9 @@ int Reader::read_model_keys(const Item& sec, bool is_defaults, std::vector<Item>
const std::string& k = it.key;
if (in(kModelFleetKeys, k)) {
if (is_defaults && k == "aliases") return fail(it.node, "aliases name one model; they cannot be a default");
if (is_defaults && k == "cards")
return fail(it.node, "cards under defaults would pin every model; the top-level "
"cards: names the cards the fleet uses");
continue;
}
std::string m = misplaced(k, "model");
@@ -493,6 +515,20 @@ int Reader::read_fleet_key(const Item& it, ModelEntry* e) {
return RAD_OK;
}
if (k == "pin") return boolean(it, &e->pin);
if (k == "cards") {
e->cards.clear();
if (scalar(it.node) && str(it.node.val()) == "all") return RAD_OK;
if (!it.node.is_seq() || it.node.num_children() == 0)
return fail(it.node, it.path + " takes all or a list of card indices");
for (Node c : it.node.children()) {
int64_t idx = 0;
if (int s = integer({ c, it.path, "cards" }, 0, 63, &idx); s < 0) return s;
if (std::find(e->cards.begin(), e->cards.end(), (int)idx) != e->cards.end())
return fail(c, "card " + std::to_string(idx) + " is listed twice");
e->cards.push_back((int)idx);
}
return RAD_OK;
}
if (k == "ttl") return duration(it, &e->ttl_ms);
if (k == "flex") {
std::vector<Item> parts;
@@ -688,6 +724,20 @@ int Reader::run(FleetConfig* out) {
out->models.push_back(std::move(e));
}
/* A model's own cards are among the fleet's and are enough for its ranks. */
for (const ModelEntry& e : out->models) {
if (e.cards.empty()) continue;
for (int c : e.cards)
if (!out->cards.empty() &&
std::find(out->cards.begin(), out->cards.end(), c) == out->cards.end())
return fail(doc, "models." + e.name + ".cards lists " + std::to_string(c) +
", which the top-level cards: leaves out");
if (std::max(e.cfg.tp, 1) > (int)e.cards.size())
return fail(doc, "models." + e.name + ": tp " + std::to_string(std::max(e.cfg.tp, 1)) +
" needs that many cards and its cards: lists " +
std::to_string(e.cards.size()));
}
std::map<std::pair<std::string, std::string>, Group::Kind> pairs;
for (const Group& g : out->groups) {
for (const std::string& m : g.members)
@@ -834,6 +884,7 @@ void print_reference(FILE* to) {
" load-timeout: DURATION how long a request waits for its model (default 120s)\n"
" drain-timeout: DURATION how long a model being evicted may finish requests (30s)\n"
" keepalive: DURATION SSE comment interval while a request waits (10s)\n"
" stuck-exit: DURATION a device stuck this long ends the process (60s; 0 never)\n"
" warm-up: true|false fill free VRAM, then host RAM, with models at start (true)\n"
"\ndefaults: any model key, merged under every model\n"
"\nmodels:\n"
@@ -841,6 +892,7 @@ void print_reference(FILE* to) {
" aliases: [NAME, ...] more ids for this model\n"
" priority: N higher keeps VRAM and takes flex from lower\n"
" pin: true|false never leaves VRAM\n"
" cards: all | [N, ...] the cards this model may be placed on (all)\n"
" ttl: DURATION park after this long without requests\n"
" flex: {kv: {min-tokens, max-tokens, weight}, experts: {min-mib, max-mib}}\n"
" park: {vram: none|statics|MIB, ram: required|allowed|never, restore: auto|full|live}\n");
@@ -949,7 +1001,19 @@ std::string yaml_from_args(int argc, char** argv) {
y += std::string(indent) + e.key + ": " + rad::Json::parse(e.vals[0]).dump() + "\n";
continue;
}
if (e.vals.size() == 1) { y += std::string(indent) + e.key + ": " + yaml_scalar(e.vals[0]) + "\n"; continue; }
if (e.vals.size() == 1) {
y += std::string(indent) + e.key + ": " + yaml_scalar(e.vals[0]);
/* A value an earlier release took and this one refuses is written as given, so
* the file says what the command line said, with what replaces it beside it. */
if (e.key == "kv-cache-dtype") {
if (e.vals[0] == "fp8_v4" || e.vals[0] == "k6_v4")
y += " # not served: i8 is the 8-bit cache, bf16 the other";
else if (e.vals[0] == "fp8")
y += " # served for few models: i8 is the 8-bit cache of the others";
}
y += "\n";
continue;
}
y += std::string(indent) + e.key + ":\n";
for (const std::string& v : e.vals) y += std::string(indent) + " - " + yaml_scalar(v) + "\n";
}
+10
View File
@@ -24,6 +24,7 @@
#include <cstdint>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
@@ -67,6 +68,9 @@ struct ModelEntry {
std::vector<std::string> aliases;
int priority = 0;
bool pin = false;
/* The cards this model may be placed on, in the file's order; empty means any of the
* fleet's. Not part of `args`: it decides where the engine runs, not how it is configured. */
std::vector<int> cards;
int64_t ttl_ms = 0; /* idle time before parking; 0 = never */
FlexSpec flex;
ParkSpec park;
@@ -99,11 +103,17 @@ struct FleetConfig {
/* memory: the per-card keys travel inside every model's flag list; these are the fleet's own. */
int64_t host_mib = 0; /* 0 = not set */
std::string disk_tier;
/* memory.card-headroom-mib: a card's own reserve, in MiB by card ordinal, in place of the
* gpu-headroom-mib every other card keeps (the card that drives a desktop). */
std::map<int, int64_t> card_headroom_mib;
/* scheduler: */
int64_t load_timeout_ms = 120000;
int64_t drain_timeout_ms = 30000;
int64_t keepalive_ms = 10000;
/* A device that has advanced nothing for this long ends the process, so a restart policy can
* bring the server back (dev_stuck_exit_ms); 0 never. */
int64_t stuck_exit_ms = 60000;
/* Once the listener is open and nothing waits, unpinned models load one at a time into free
* VRAM and park to host memory and the disk tier as later ones displace them, so a first
* request finds its model parked rather than cold (docs/MULTIMODEL.md §8.6). */
+177 -31
View File
@@ -142,6 +142,23 @@ double sysfs_number(const std::string& path) {
return f >> v ? v : -1;
}
/* A card's temperature in millidegrees: the sensor its driver labels `junction`, else temp1. amdgpu
* labels three, edge (temp1), junction and mem, and throttles on the junction, the hottest spot on
* the die: under a decode load an R9700 read 56 C at the edge and 75-77 C at the junction. A driver
* that labels none, or no junction, keeps temp1. -1 when neither can be read. */
double card_temp_mc(const std::string& hwmon) {
for (int i = 1; i <= 8; ++i) {
const std::string t = hwmon + "/temp" + std::to_string(i);
std::ifstream f(t + "_label");
std::string label;
if (!(f >> label)) continue;
if (label != "junction") continue;
if (const double mc = sysfs_number(t + "_input"); mc >= 0) return mc;
break;
}
return sysfs_number(hwmon + "/temp1_input");
}
/* What the driver reports of a card right now: busy share, power and temperature, on the routes of
* a dashboard being watched and nowhere on a request's path. A card that reports none adds none. */
void card_telemetry(int card, json& o) {
@@ -156,7 +173,7 @@ void card_telemetry(int card, json& o) {
double uw = sysfs_number(hp + "/power1_average");
if (uw < 0) uw = sysfs_number(hp + "/power1_input");
if (uw >= 0) o["power_w"] = uw / 1e6;
if (const double mc = sysfs_number(hp + "/temp1_input"); mc >= 0) o["temp_c"] = mc / 1000.0;
if (const double mc = card_temp_mc(hp); mc >= 0) o["temp_c"] = mc / 1000.0;
break;
}
}
@@ -270,10 +287,7 @@ private:
Model* m = nullptr;
int grant(const VramAsk& ask, int64_t* g, std::string* why) override { return f->grant(*m, ask, g, why); }
bool host_room(int64_t bytes) override {
if (!f->load_host_room(*m, bytes)) return false;
m->pools_held.fetch_add(bytes);
f->host_reserve_.fetch_add(bytes);
return true;
return f->load_host_room(*m, bytes, 0, /*reserve=*/true);
}
bool host_pools_room() override {
const int64_t own = m->pools_held.load();
@@ -428,7 +442,7 @@ private:
bool take_busy = false, int64_t own = 0, bool evict = true);
/* Parked models give back their snapshot stores, in `parked` order, until `need` is free. */
bool release_spares(const std::vector<Model*>& parked, int64_t need);
bool load_host_room(Model& m, int64_t need, int64_t own = 0);
bool load_host_room(Model& m, int64_t need, int64_t own = 0, bool reserve = false);
bool loading_beside(const Model& m);
bool alone_on_host(const Model& m);
int64_t host_held();
@@ -446,9 +460,14 @@ private:
void fail(Model& m, const std::string& why);
bool choose_cards(Model& m, const Config& cfg, std::vector<int>* out, std::string* why);
/* The cards `m` may be placed on: its own list (models.NAME.cards), else the fleet's. */
const std::vector<int>& cards_of(const Model& m) const {
return m.entry.cards.empty() ? cards_ : m.entry.cards;
}
std::vector<CardRoom> rooms();
/* The bytes a model may still claim on `card`: free past the headroom and what is pending. */
int64_t room_on(int card);
int64_t headroom_on(int card) const;
int64_t pending_on(int card);
/* rooms() covers `need` on every card in it, without anything leaving. */
bool fits_free(const std::map<int, int64_t>& need);
@@ -460,10 +479,16 @@ private:
std::string reload();
void stop_all();
void add_routes();
/* Whether `q`'s caller may reach the fleet's admin routes: everyone who pays the api key, or
* -- keyless -- the local operator on the three-leg rule (loopback, no foreign Origin, pinned
* Host). One predicate, read by add_routes' guard and the front's operator rule alike. */
bool operator_ok(const server::HttpRequest& q) const;
json status();
void history_loop();
json placement(const std::string& name);
std::string describe(const std::string& name);
/* Adapters a resident model serves from memory: the names /v1/models lists as its cards. */
std::vector<std::string> adapters_of(const std::string& name);
std::string metrics();
std::vector<std::string> group_partners(const std::string& name, Group::Kind kind) const;
void keep_partners(const Model& m, std::vector<Resident>* res) const;
@@ -502,6 +527,7 @@ private:
Fleet::Fleet(FleetConfig fc)
: fc_(std::move(fc)), front_(transport_options(fc_), fc_.keepalive_ms) {
dev_stuck_exit_ms.store(fc_.stuck_exit_ms, std::memory_order_relaxed);
bool any = false;
int64_t head = 0;
for (const ModelEntry& e : fc_.models) {
@@ -565,8 +591,15 @@ int64_t Fleet::pending_on(int card) {
return n;
}
/* What a card keeps free: its own reserve where memory.card-headroom-mib names it, else the
* headroom every card keeps. */
int64_t Fleet::headroom_on(int card) const {
const auto it = fc_.card_headroom_mib.find(card);
return it == fc_.card_headroom_mib.end() ? headroom_ : it->second * kMiB;
}
int64_t Fleet::room_on(int card) {
return std::max<int64_t>(free_on(card) - headroom_ - pending_on(card), 0);
return std::max<int64_t>(free_on(card) - headroom_on(card) - pending_on(card), 0);
}
std::vector<CardRoom> Fleet::rooms() {
@@ -690,27 +723,33 @@ std::vector<size_t> Fleet::exclusive_victims(const Model& m) {
bool Fleet::choose_cards(Model& m, const Config& cfg, std::vector<int>* out, std::string* why) {
const int tp = std::max(cfg.tp, 1);
if (tp > (int)cards_.size()) {
const std::vector<int>& may = cards_of(m);
if (tp > (int)may.size()) {
*why = "tp " + std::to_string(tp) + " needs " + std::to_string(tp) + " cards; " +
std::to_string(cards_.size()) + " are available";
std::to_string(may.size()) + " are available";
return false;
}
if (!use_broker()) {
out->assign(cards_.begin(), cards_.begin() + tp);
out->assign(may.begin(), may.begin() + tp);
return true;
}
/* The room plan and the fallback below see only the cards this model may use, so a model
* with its own list is never planned onto another card, whatever room that card has. */
std::vector<CardRoom> open;
for (const CardRoom& c : rooms())
if (std::find(may.begin(), may.end(), c.card) != may.end()) open.push_back(c);
const int64_t guess = first_guess(m.claim, cfg);
std::vector<Resident> res = residents(&m);
keep_partners(m, &res);
RoomPlan plan;
std::string w;
if (plan_room(rooms(), res, tp, guess, m.entry.priority, exclusive_victims(m), m.last_cards,
if (plan_room(open, res, tp, guess, m.entry.priority, exclusive_victims(m), m.last_cards,
nullptr, &plan, &w)) {
*out = plan.cards;
return true;
}
std::vector<std::pair<int64_t, int>> by;
for (const CardRoom& c : rooms()) {
for (const CardRoom& c : open) {
int64_t room = c.free;
for (const Resident& r : res)
if (!r.pin && !r.keep && r.priority <= m.entry.priority) room += r.gives(c.card);
@@ -733,9 +772,9 @@ int64_t Fleet::flex_room(const std::vector<int>& cards) {
for (auto& m : models_)
if (m->waiting.load(std::memory_order_acquire)) return 0;
}
const int64_t margin = headroom_ + 512 * kMiB;
int64_t room = INT64_MAX;
for (int c : cards) room = std::min(room, free_on(c) - margin - pending_on(c));
for (int c : cards)
room = std::min(room, free_on(c) - (headroom_on(c) + 512 * kMiB) - pending_on(c));
return room == INT64_MAX ? 0 : std::max<int64_t>(room, 0);
}
@@ -1402,11 +1441,21 @@ bool Fleet::alone_on_host(const Model& m) {
/* Room to pin `need` during a load. As in the load's first wait, beside another load in flight
* parked and idle models go only after ten seconds, once a load counted twice has passed. */
bool Fleet::load_host_room(Model& m, int64_t need, int64_t own) {
bool Fleet::load_host_room(Model& m, int64_t need, int64_t own, bool reserve) {
// A new pool must reserve the room in the same critical section that found it. A check
// of already reserved pools (own) does not count them a second time.
auto commit_reservation = [&] {
if (!reserve) return;
m.pools_held.fetch_add(need);
host_reserve_.fetch_add(need);
};
{
/* There already: a warm-up needs no budget for a pin that leaves the host its floor. */
std::lock_guard<std::recursive_mutex> room(room_mu_);
if (host_available() - host_reserve_.load() + own - kHostFloor >= need) return true;
if (host_available() - host_reserve_.load() + own - kHostFloor >= need) {
commit_reservation();
return true;
}
}
/* Before its grant a load holds a guess of VRAM, which what pins this memory may be waiting
* for (a parked model coming back): they would wait for each other. The guess goes while it
@@ -1428,8 +1477,12 @@ bool Fleet::load_host_room(Model& m, int64_t need, int64_t own) {
/* As in load_op: without a load in flight beside this one the figure is exact, and parked
* and idle models give their host memory at once. */
const bool exact = !warm && !loading_beside(m);
ok = make_host_room(need, &m, !warm, !warm && (exact || i >= 50),
!warm && (i >= 150 || (exact && i >= 10)), own);
{
std::lock_guard<std::recursive_mutex> room(room_mu_);
ok = make_host_room(need, &m, !warm, !warm && (exact || i >= 50),
!warm && (i >= 150 || (exact && i >= 10)), own);
if (ok) commit_reservation();
}
if (ok || i + 1 >= tries) break;
if (i == 0)
RAD_INFO("model %s: waiting for %s of host memory to pin (%s available, %s of it kept "
@@ -1666,6 +1719,9 @@ void Fleet::park_op(Model& m, const std::string& why) {
* copies of copies: make_host_room lets them go first. */
void Fleet::fill_op(Model& m) {
if (!m.engine || !m.parked) return;
// Size and reserve the fill together with parks and load reservations. The transfer itself
// runs without room_mu_: a slow drive must not hold up another model's room decision.
std::unique_lock<std::recursive_mutex> room_lock(room_mu_);
/* A GiB at a time: a restore asked for meanwhile waits for one batch at most. */
constexpr int64_t kBatch = (int64_t)1 << 30;
if (host_room() - kFillSlack - Engine::kRefillHost < kBatch) {
@@ -1683,8 +1739,20 @@ void Fleet::fill_op(Model& m) {
fill_wait_ns_.store(rad_mono_ns() + 5000000000ull);
return;
}
const int64_t budget = std::min(room, kBatch);
const int64_t reserved = budget + Engine::kRefillHost;
host_reserve_.fetch_add(reserved);
room_lock.unlock();
const auto t0 = std::chrono::steady_clock::now();
const int64_t n = m.engine->fill_host(std::min(room, kBatch));
int64_t n;
{
struct FillReservation {
std::atomic<int64_t>& total;
int64_t bytes;
~FillReservation() { total.fetch_sub(bytes); }
} hold{ host_reserve_, reserved };
n = m.engine->fill_host(budget);
}
if (n < 0) {
RAD_WARN("model %s: reading its parked copy into host memory failed: %s", m.entry.name.c_str(),
rad_dev_last_error());
@@ -1727,7 +1795,7 @@ void Fleet::restore_op(Model& m) {
std::string why;
/* A parked model comes back on its own cards. A fresh load could pick others, but needs as
* much room; it is worth it only where other cards exist, and only after a while. */
const bool elsewhere = (int)cards_.size() > (int)m.cards.size();
const bool elsewhere = (int)cards_of(m).size() > (int)m.cards.size();
std::unique_lock<std::recursive_mutex> room(room_mu_, std::defer_lock);
int rrc = RAD_OK;
bool yielded = false;
@@ -2256,6 +2324,15 @@ std::string Fleet::reload() {
if (a.host != b.host || a.port != b.port || a.api_key != b.api_key ||
a.http_threads != b.http_threads || a.cors != b.cors || nf.cards != fc_.cards)
return "server: and cards: changes need a restart";
for (const ModelEntry& e : nf.models)
for (int c : e.cards)
if (std::find(cards_.begin(), cards_.end(), c) == cards_.end())
return "models." + e.name + ": cards lists " + std::to_string(c) +
", which is not a usable card here";
for (const auto& [c, mib] : nf.card_headroom_mib)
if (std::find(cards_.begin(), cards_.end(), c) == cards_.end())
return "memory.card-headroom-mib names card " + std::to_string(c) +
", which is not a card this fleet uses";
if (nf.log_set) log_set_level(nf.log);
/* Work in flight finishes first. */
for (auto& m : models_) {
@@ -2288,7 +2365,7 @@ std::string Fleet::reload() {
RAD_INFO("model %s: added", e.name.c_str());
continue;
}
if (m->entry.args != e.args) {
if (m->entry.args != e.args || m->entry.cards != e.cards) {
unload(*m, fc_.drain_timeout_ms, "its configuration changed");
RAD_INFO("model %s: reconfigured", e.name.c_str());
std::lock_guard<std::mutex> lk(mu_);
@@ -2301,6 +2378,7 @@ std::string Fleet::reload() {
front_.update(e.name, e.aliases, nf.load_timeout_ms, required);
}
fc_ = std::move(nf);
dev_stuck_exit_ms.store(fc_.stuck_exit_ms, std::memory_order_relaxed);
for (const ModelEntry& e : fc_.models)
if (e.pin) demand(e.name);
RAD_INFO("reload: %s applied, %zu model(s)", fc_.path.c_str(), fc_.models.size());
@@ -2365,6 +2443,15 @@ std::string Fleet::describe(const std::string& name) {
return "{}";
}
/* The adapter names a resident model serves from memory. A parked or loading engine serves none
* through this name: nothing answers a request to a child while the parent is not open. */
std::vector<std::string> Fleet::adapters_of(const std::string& name) {
std::lock_guard<std::mutex> lk(mu_);
for (auto& mp : models_)
if (mp->entry.name == name && mp->resident && mp->engine) return mp->engine->lora_names();
return {};
}
/* What /admin/fleet says beyond describe(), which also feeds every /v1/models card: where the
* model's bytes are, its file and the policy it was configured with. */
json Fleet::placement(const std::string& name) {
@@ -2464,6 +2551,9 @@ void Fleet::history_loop() {
using clock = std::chrono::steady_clock;
auto next_row = clock::now();
std::set<std::string> open; /* the models that had a row since they last opened */
/* The adapter children sampled under each model's name, so that their series close with the
* model and a child no longer served is dropped. */
std::map<std::string, std::set<std::string>> kids;
while (!g_stop.load() && !front_.stopping()) {
const double t = std::chrono::duration<double>(std::chrono::system_clock::now().time_since_epoch()).count();
const bool watched = history_.watched(3.0);
@@ -2476,7 +2566,10 @@ void Fleet::history_loop() {
for (const std::string& n : front_.names()) {
const bool is_open = front_.activity(n).state == server::Front::State::Open;
if (!is_open) {
if (open.erase(n) || row) history_.model_closed(n);
if (open.erase(n) || row) {
history_.model_closed(n);
for (const std::string& c : kids[n]) history_.model_closed(c);
}
continue;
}
const bool first = !open.count(n);
@@ -2485,6 +2578,16 @@ void Fleet::history_loop() {
if (body.empty()) continue;
const json s = json::parse(body, nullptr, false);
if (!s.is_object()) continue;
/* status() lists each adapter of this model as a child; a child owns no engine, and
* the parent's stats are exactly what a request to the child runs on -- the same
* tokens, the same queue, the same seconds. Sample the child under its own name with
* the parent's body so the child's charts draw what its name actually drives. */
std::set<std::string> now;
for (const std::string& a : adapters_of(n)) now.insert(n + ":" + a);
for (const std::string& c : kids[n])
if (!now.count(c)) history_.forget(c);
for (const std::string& c : now) history_.model_sample(c, s, t, body);
kids[n] = std::move(now);
history_.model_sample(n, s, t, std::move(body));
open.insert(n);
}
@@ -2517,6 +2620,21 @@ json Fleet::status() {
if (j.contains("waiting_for") && a.state != server::Front::State::Open) j["state"] = "waiting";
if (const std::string caps = front_.capabilities(n); !caps.empty()) j["capabilities"] = json::parse(caps, nullptr, false);
models.push_back(j);
/* Runtime LoRA: an adapter is a model as far as choosing one goes, and /v1/models lists
* each as a child under `base:adapter` (server.cpp). The fleet view must say the same,
* or a view built on it is blind to what this machine answers to. A child owns nothing:
* no cards, no bytes, no policy of its own; its state and counters are the parent's,
* because the parent is what serves it. */
for (const std::string& a : adapters_of(n)) {
json ad;
ad["id"] = n + ":" + a;
ad["parent"] = n;
ad["adapter"] = true;
ad["state"] = j["state"];
ad["in_flight"] = j["in_flight"];
ad["waiting"] = j["waiting"];
models.push_back(std::move(ad));
}
}
json cards = json::array();
for (int c : cards_) {
@@ -2561,14 +2679,22 @@ json Fleet::status() {
{ "cards", cards }, { "groups", groups }, { "host", host }, { "warm_up", warm } };
}
bool Fleet::operator_ok(const server::HttpRequest& q) const {
const Config& c = fc_.models.front().cfg;
return !c.api_key.empty() || server::local_operator(q, c.host, c.allow_hosts);
}
void Fleet::add_routes() {
/* The fleet's own routes. Without a bearer key they answer loopback callers only, as the
* engine's other admin routes do. */
/* The fleet's own routes. Without a bearer key they answer the local operator only, on the
* very rule the engine's other admin routes apply: loopback socket, no foreign Origin, and a
* Host that names this box. The socket alone forges -- a rebinding page or a localhost proxy
* is loopback for any caller -- so all three legs are read here too (docs/GUIDE.md). */
auto guard = [this](const server::HttpRequest& q) -> std::optional<server::HttpResponse> {
if (!fc_.models.front().cfg.api_key.empty() || q.peer_is_loopback()) return std::nullopt;
if (operator_ok(q))
return std::nullopt;
return server::HttpResponse::json_body(
403, server::error_body(q.path, 403, "permission_error",
"the fleet's admin routes answer loopback callers only "
"the fleet's admin routes answer the local operator only "
"unless an api key is configured"));
};
auto ok = [](json j) { return server::HttpResponse::json_body(200, j.dump()); };
@@ -2584,7 +2710,8 @@ void Fleet::add_routes() {
* /admin/fleet's object as `live`. `since` (unix seconds) asks for what came after. Every byte
* comes from the sampler's last read, so a page that polls this reads nothing of the engine:
* it neither brings a model back nor costs a running one anything. A model's history is as
* open as its /stats, the fleet's as /admin/fleet. */
* open as its /stats, whose figures it repeats, and the fleet's as guarded as /admin/fleet:
* a browser the fleet view is refused to still draws the server's own model from it. */
front_.route("GET", "/history", [this, guard, ok](const server::HttpRequest& q) {
double since = 0;
if (auto it = q.query.find("since"); it != q.query.end()) since = std::strtod(it->second.c_str(), nullptr);
@@ -2756,12 +2883,28 @@ int Fleet::run() {
cards_.push_back(c);
}
}
for (const ModelEntry& e : fc_.models)
if (std::max(e.cfg.tp, 1) > (int)cards_.size()) {
RAD_ERR("models.%s: tp %d needs %d cards; %zu are available", e.name.c_str(), e.cfg.tp,
e.cfg.tp, cards_.size());
for (const auto& [c, mib] : fc_.card_headroom_mib) {
if (std::find(cards_.begin(), cards_.end(), c) == cards_.end()) {
RAD_ERR("%s: memory.card-headroom-mib names card %d, which is not a card this fleet "
"uses", fc_.path.c_str(), c);
return 2;
}
RAD_INFO("fleet: card %d keeps %lld MiB free (memory.card-headroom-mib)", c, (long long)mib);
}
for (const ModelEntry& e : fc_.models) {
for (int c : e.cards)
if (std::find(cards_.begin(), cards_.end(), c) == cards_.end()) {
RAD_ERR("models.%s: cards lists %d, which is not a usable card here",
e.name.c_str(), c);
return 2;
}
const size_t have = e.cards.empty() ? cards_.size() : e.cards.size();
if (std::max(e.cfg.tp, 1) > (int)have) {
RAD_ERR("models.%s: tp %d needs %d cards; %zu are available", e.name.c_str(), e.cfg.tp,
e.cfg.tp, have);
return 2;
}
}
/* Park files a process that died left in the disk tier: radiance-park-PID-N.bin (pageable
* chunks) and radiance-vmem-PID-N.bin (elastic ranges) of a PID that no longer runs. */
@@ -2800,6 +2943,9 @@ int Fleet::run() {
if (required) preload.push_back(e.name);
}
front_.set_demand([this](const std::string& n) { demand(n); });
/* The guarded routes wake models only for callers their own handlers would admit: the same
* operator_ok predicate add_routes' guard reads, keyed deployments always. */
front_.set_operator_rule([this](const server::HttpRequest& q) { return operator_ok(q); });
front_.set_describe([this](const std::string& n) { return describe(n); });
front_.set_metrics([this] { return metrics(); });
add_routes();
+298 -15
View File
@@ -2,6 +2,7 @@
#include "checkpoint.h"
#include "ggml_planes.h"
#include "rad_plugin.h"
#include "../rad_internal.h"
#include "util/json.h"
@@ -347,6 +348,7 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
* pass through in the free-form list. */
const std::string a = out->arch;
if (a == "hy_v3") out->arch = "hyv3";
if (a == "bailingmoe3") out->arch = "bailinghybrid";
auto gi = [&](const char* suffix, int64_t dflt) -> int64_t {
int64_t v = 0;
return g.get_i64(a + "." + suffix, &v) ? v : dflt;
@@ -443,6 +445,63 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
out->kv("attention_bias", "0");
out->kv("mlp_bias", "0");
}
if (a == "bailingmoe3") {
/* Ling 3.0 (the arch alias above): the release GGUF spells the family's keys
* bailingmoe3.*, and the plugin (arch/bailing_hybrid) reads them as the checkpoint's
* config.json names, so the reader re-spells them here and one plugin serves both
* formats. eps and rope_theta take the generic paths above. Four of the family's
* design choices the GGUF does not carry are Ling 3.0's, stated as constants. */
/* Bounds on the family gates too (see bailingmoe3_layouts): the layout rebuild's
* products -- heads * (nope + rope) rows, the fused kv's heads * 256 * latent -- are
* int64 products of these values handed to sized allocations, so the widths they are
* built from may not roam free. 128/64 is the shipped geometry. */
if (gi("kda.head_dim", 0) <= 0 || gi("kda.head_dim", 0) > 512 ||
gi("rope.dimension_count", 0) <= 0 || gi("rope.dimension_count", 0) > 256 ||
gi("attention.key_length_mla", 0) <= gi("rope.dimension_count", 0) ||
gi("attention.key_length_mla", 0) > 65536)
return RAD_E_FORMAT;
out->kv("num_attention_heads", fmt("%lld", (long long)m.n_head));
/* The typed head_dim the generic pass fell back to (the MLA query width) is not the
* KDA head the plugin asserts; rad-convert publishes the typed fields before the kv
* table, and lookups take the first row, so the typed field must carry the 128. */
out->m.head_dim = (int)gi("kda.head_dim", 0);
out->kv("head_dim", fmt("%lld", (long long)gi("kda.head_dim", 0)));
/* The GGUF's key_length_mla is the full query (nope + rotary); the plugin's
* qk_nope_head_dim is the rotary part subtracted. */
out->kv("qk_nope_head_dim",
fmt("%lld", (long long)(gi("attention.key_length_mla", 0) - gi("rope.dimension_count", 0))));
out->kv("qk_rope_head_dim", fmt("%lld", (long long)gi("rope.dimension_count", 0)));
out->kv("v_head_dim", fmt("%lld", (long long)gi("attention.value_length_mla", 0)));
out->kv("kv_lora_rank", fmt("%lld", (long long)gi("attention.kv_lora_rank", 0)));
out->kv("q_lora_rank", fmt("%lld", (long long)gi("attention.q_lora_rank", 0)));
out->kv("num_experts", fmt("%lld", (long long)m.n_expert));
out->kv("num_experts_per_tok", fmt("%lld", (long long)m.n_expert_used));
out->kv("n_group", fmt("%lld", (long long)gi("expert_group_count", 0)));
out->kv("topk_group", fmt("%lld", (long long)gi("expert_group_used_count", 0)));
out->kv("moe_intermediate_size", fmt("%lld", (long long)gi("expert_feed_forward_length", 0)));
out->kv("moe_shared_expert_intermediate_size",
fmt("%lld", (long long)gi("expert_shared_feed_forward_length", 0)));
out->kv("num_shared_experts", fmt("%lld", (long long)m.n_expert_shared));
out->kv("intermediate_size", fmt("%lld", (long long)m.n_ff));
out->kv("first_k_dense_replace", fmt("%lld", (long long)gi("leading_dense_block_count", 0)));
out->kv("short_conv_kernel_size", fmt("%lld", (long long)gi("ssm.conv_kernel", 0)));
out->kv("kda_lower_bound", fmt("%.17g", gf("kda.gate_lower_bound", 0.0)));
out->kv("routed_scaling_factor", fmt("%.17g", gf("expert_weights_scale", 1.0)));
out->kv("norm_topk_prob", fmt("%lld", (long long)gi("expert_weights_norm", 0)));
out->kv("kda_safe_gate", fmt("%lld", (long long)gi("kda.safe_gate", 0)));
out->kv("layer_group_size", "4");
out->kv("no_kda_lora", "1");
out->kv("rope_interleave", "1");
out->kv("gated_attention_proj_granularity_type", "head_wise");
out->kv("num_nextn_predict_layers", "0");
/* The plugin picks its checkpoint names from this: the GGUF spells the family's tensors
* blk. and ssm. names (and carries the layouts bailingmoe3_layouts rebuilds), the safetensors
* their config.json spellings. */
out->kv("gguf_source", "1");
std::string gating = "sigmoid";
g.get_str("bailingmoe3.expert_gating_func", &gating);
out->kv("score_function", gating);
}
/* Everything else, stringified, for the plugin. Arrays are summarised (small integer arrays
* spelled out); tokenizer keys are skipped, since the vocab has its own section. */
@@ -497,7 +556,9 @@ int Checkpoint::open_gguf(const std::string& path) {
index_.emplace(s.name, tensors_.size());
tensors_.push_back(std::move(s));
}
return meta_from_gguf(gguf_, &meta_);
RAD_TRY(meta_from_gguf(gguf_, &meta_));
if (meta_.arch == "bailinghybrid") RAD_TRY(bailingmoe3_layouts());
return RAD_OK;
}
int Checkpoint::add_shard(const std::string& p, const std::string& prefix,
@@ -538,6 +599,28 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix,
namespace {
/* Whether an index may name `f` as a shard. The index is data the checkpoint supplies, and its
* names are joined under the model directory and opened as the serving user, so a name must stay
* under that directory: relative, with no empty component, "." or "..". Subdirectories are legal.
* Only the name is screened. A shard that is a symbolic link is followed like any file the
* operator points the engine at: a Hugging Face cache snapshot is a directory of links into its
* blob store. */
bool shard_name_ok(const std::string& f) {
if (f.empty() || f.front() == '/') return false;
size_t i = 0;
while (i < f.size()) {
size_t j = f.find('/', i);
if (j == std::string::npos) j = f.size();
if (j == i) return false; /* empty component, "//" */
if (j - i == 2 && f.compare(i, 2, "..") == 0) return false;
if (j - i == 1 && f[i] == '.') return false;
i = j + 1;
}
return true;
}
static bool path_exists(const std::string& p) { std::ifstream f(p); return (bool)f; }
/* Every shard an index names, once each and in name order, or the one model.safetensors; `map`
* is the index's weight_map, empty without one. */
int shard_list(const std::string& dir, const std::string& index, bool index_given,
@@ -546,6 +629,13 @@ int shard_list(const std::string& dir, const std::string& index, bool index_give
if (s == RAD_OK) {
for (auto& [t, f] : *map)
if (std::find(out->begin(), out->end(), f) == out->end()) out->push_back(f);
for (const std::string& f : *out)
if (!shard_name_ok(f)) {
RAD_ERR("%s: the index names the shard '%s'; shards must live under the model "
"directory",
index.c_str(), log_sanitize(f).c_str());
return RAD_E_FORMAT;
}
std::sort(out->begin(), out->end());
for (auto& f : *out) f = dir + "/" + f;
return RAD_OK;
@@ -557,6 +647,7 @@ int shard_list(const std::string& dir, const std::string& index, bool index_give
} /* namespace */
/* A JSON file flattened under `prefix`; absent is not an error when `optional`. */
static int meta_merge_json_file(const std::string& path, const std::string& prefix, bool optional,
MetaOwn* out) {
@@ -577,8 +668,6 @@ static int meta_merge_json_file(const std::string& path, const std::string& pref
return RAD_OK;
}
static bool path_exists(const std::string& p) { std::ifstream f(p); return (bool)f; }
/* Whether an FP8 piece of `rows` rows has one scale for the whole tensor: a rank-0 scale
* (ModelOpt's) or a one-element [1] (compressed-tensors' tensor strategy). A [1, 1] scale is a
* block plane. */
@@ -1382,10 +1471,13 @@ void Checkpoint::detect_import() {
"; it is read in groups of 16";
if (algos.empty() && import_why_.empty())
import_why_ = "ModelOpt's quantization_config names no quant_algo";
/* W4A16_NVFP4 is the same NVFP4 weight with bf16 activations, which is what this reader
* serves either way: activations are quantised from their own values, never from a stored
* input scale. NVIDIA's Muse Glimmer release states it per layer beside FP8. */
for (const std::string& a : algos)
if (a != "NVFP4" && a != "FP8" && import_why_.empty())
import_why_ = "ModelOpt's quant_algo '" + a + "' is not one this reads; NVFP4 "
"and FP8 (per tensor), alone or per layer, are";
if (a != "NVFP4" && a != "W4A16_NVFP4" && a != "FP8" && import_why_.empty())
import_why_ = "ModelOpt's quant_algo '" + a + "' is not one this reads; NVFP4, "
"W4A16_NVFP4 and FP8 (per tensor), alone or per layer, are";
if (import_why_.empty()) import_ = Import::ModelOpt;
else import_why_ = "modelopt: " + import_why_;
} else if (qm == "paroquant") {
@@ -2970,9 +3062,17 @@ namespace {
/* ---------------------------------------------------------------- GGUF block types
*
* ggml block types decodable to f32. Their geometry lives in core/text; decoding lives here, where
* weights are read. Q4_K and Q6_K are the K-quants this HYV3 GGUF adapter needs. */
* weights are read. Q4_K, Q5_K and Q6_K are the K-quants the GGUF releases ship, IQ4_NL the
* non-linear 4-bit. */
enum { GGML_F32 = 0, GGML_F16 = 1, GGML_Q4_0 = 2, GGML_Q4_1 = 3, GGML_Q5_0 = 6, GGML_Q5_1 = 7,
GGML_Q8_0 = 8, GGML_Q4_K = 12, GGML_Q6_K = 14, GGML_BF16 = 30 };
GGML_Q8_0 = 8, GGML_Q4_K = 12, GGML_Q5_K = 13, GGML_Q6_K = 14, GGML_BF16 = 30,
GGML_IQ4_NL = 20 };
/* IQ4_NL's non-linear levels (llama.cpp's kvalues_iq4nl), one per 4-bit code. */
static const int8_t kIq4NlLevels[16] = {
-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113
};
int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
auto half = [&](const uint8_t* q) { uint16_t h; std::memcpy(&h, q, 2); return rad_f16_to_f32(h); };
@@ -3032,13 +3132,7 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
const uint8_t* qs = p + 16;
for (int j = 0; j < 8; ++j) {
uint32_t sc, mn;
if (j < 4) {
sc = scales[j] & 63u;
mn = scales[j + 4] & 63u;
} else {
sc = (scales[j + 4] & 15u) | ((uint32_t)(scales[j - 4] >> 6) << 4);
mn = (scales[j + 4] >> 4) | ((uint32_t)(scales[j] >> 6) << 4);
}
ggml_planes::k4_scale_min(j, scales, &sc, &mn);
const float ds = d * (float)sc, ms = dmin * (float)mn;
for (int l = 0; l < 32; ++l) {
const int v = j * 32 + l;
@@ -3049,7 +3143,33 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
}
}
return RAD_OK;
case GGML_Q5_K:
/* block: d, dmin, scales[12], qh[32], qs[128]. The fifth bit of value v is bit
* (v/64)*2 + (v%64)/32 of qh's byte (v/64)*32 + v%32. */
for (int64_t b = 0; b < n / 256; ++b, p += 176) {
const float d = half(p), dmin = half(p + 2);
const uint8_t* scales = p + 4;
const uint8_t* qh = p + 16;
const uint8_t* qs = p + 48;
for (int j = 0; j < 256; j += 64) {
const int hb = j / 64;
const uint32_t u1 = 1u << (2 * hb), u2 = 1u << (2 * hb + 1);
uint32_t sc1, m1, sc2, m2;
ggml_planes::k4_scale_min(j / 32, scales, &sc1, &m1);
ggml_planes::k4_scale_min(j / 32 + 1, scales, &sc2, &m2);
const float d1 = d * (float)sc1, m1f = dmin * (float)m1;
const float d2 = d * (float)sc2, m2f = dmin * (float)m2;
const uint8_t* ql = qs + (j / 2);
/* The 32 qh bytes are shared across all four 64-blocks; only the mask moves. */
for (int l = 0; l < 32; ++l)
dst[b * 256 + j + l] = d1 * (float)((ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0)) - m1f;
for (int l = 0; l < 32; ++l)
dst[b * 256 + j + 32 + l] = d2 * (float)((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - m2f;
}
}
return RAD_OK;
case GGML_Q6_K:
/* block: ql[128], qh[64], scales[16], d. */
for (int64_t b = 0; b < n / 256; ++b, p += 210) {
const uint8_t* ql = p;
const uint8_t* qh = p + 128;
@@ -3064,6 +3184,16 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) {
}
}
return RAD_OK;
case GGML_IQ4_NL:
for (int64_t b = 0; b < n / 32; ++b, p += 18) {
const float d = half(p);
const uint8_t* qs = p + 2;
for (int j = 0; j < 16; ++j) {
dst[b * 32 + j] = d * (float)kIq4NlLevels[qs[j] & 0x0F];
dst[b * 32 + j + 16] = d * (float)kIq4NlLevels[qs[j] >> 4];
}
}
return RAD_OK;
default:
return RAD_E_UNSUPPORTED;
}
@@ -3433,6 +3563,159 @@ int ckpt_import_form(CkptWeight* w, const ImportForm& f, std::string* why) {
return RAD_OK;
}
int Checkpoint::bailingmoe3_layouts() {
/* The release GGUF keeps layouts the plugin's names cannot spell through the row and slice
* maps. The MLA layers' latent projections are head-last: k_b [128, 512, heads] and
* v_b [512, 128, heads] (a 128-row k block and a 128-row v block a head), where the plugin
* reads one interleaved kv_b [heads * 2 * 128, 512] -- head h's k rows [2 * 128 * h,
* + 128), its v rows the next 128. The MoE layers' routed stacks are expert-last (gate and
* up [ff, emb, E], down [emb, ff, E]); the reader's fastest-first flip orients them, and
* the block's split-stacked source slices one expert off the flipped [E, ...] stack, so
* they stay where they are. Everything the flip already hands over in the plugin's
* orientation (the shared expert, the KDA and the norms) needs only a name, which the
* plugin takes from the gguf_source meta. */
const int64_t n_layer = meta_.m.n_layers;
const char* grp_s = meta_.get("layer_group_size");
const int64_t group = grp_s ? std::stoll(grp_s) : 4;
const char* dense_s = meta_.get("first_k_dense_replace");
const int64_t dense = dense_s ? std::stoll(dense_s) : 1;
const char* heads_s = meta_.get("num_attention_heads");
const int64_t heads = heads_s ? std::stoll(heads_s) : 16;
const char* latent_s = meta_.get("kv_lora_rank");
const int64_t latent = latent_s ? std::stoll(latent_s) : 512;
const char* ff_s = meta_.get("moe_intermediate_size");
const int64_t ff = ff_s ? std::stoll(ff_s) : 512;
/* The experts' third axis is the embedding width, not the dense feed-forward's. */
const int64_t emb = meta_.m.n_embd;
const char* nexp_s = meta_.get("num_experts");
const int64_t n_expert = nexp_s ? std::stoll(nexp_s) : 0;
/* Every loop below walks to n_layer on the open path, so the counts must be bounded HERE:
* a GGUF claiming 2^62 layers would spend centuries in name probes, never answering, never
* refusing -- a hostile container's hang, not a slow load. No real model of this family is
* near 4096 layers. And the MoE suffix loop starts at the dense prefix, so the prefix must
* lie inside the stack: negative opens a walk of twice the range, beyond the end is a
* container that means nothing by it. The head and rank caps are the same discipline one
* order down: the rebuild's products (heads * (nope + rope) rows, heads * 256 * latent
* bytes of fused kv) are computed in int64 and handed to vectors sized through size_t, and
* a product past that type's range truncates to a small allocation the copy then overruns.
* No family model is near 4096 heads or ranks; 256 rope dimensions is already
* far past what the rope kernel addresses. */
if (n_layer < 1 || n_layer > 4096 || dense < 0 || dense > n_layer ||
group < 2 || group > n_layer || heads < 1 || heads > 4096 ||
latent < 1 || latent > 4096 || ff < 1 || emb < 1)
return RAD_E_FORMAT;
/* Decode a whole source tensor to f32: a block type row by row, a plain one a copy. */
auto whole = [&](const SrcTensor* t, std::vector<float>& dst) -> int {
const int64_t n = t->numel();
dst.resize((size_t)n);
return piece_f32(*t, 0, n, dst.data());
};
auto add = [&](const std::string& name, std::vector<int64_t> shape,
std::vector<float>&& v) -> int {
if (index_.count(name)) return RAD_OK; /* the checkpoint already spells it */
SrcTensor s;
s.name = name;
s.rad_dtype = RAD_F32;
s.shape = std::move(shape);
s.owned = std::move(v);
s.data = s.owned.data();
s.bytes = (int64_t)(s.owned.size() * sizeof(float));
index_.emplace(s.name, tensors_.size());
tensors_.push_back(std::move(s));
return RAD_OK;
};
/* The exporter's ssm_a is exp(A_log) (llama.cpp's bailingmoe3 modify_tensors); the KDA
* kernel exponentiates internally, so the container wants the log values back. */
for (int64_t l = 0; l < n_layer; ++l) {
if ((l + 1) % group == 0) continue; /* the MLA layers carry no ssm_a */
const SrcTensor* sa = find(fmt("blk.%lld.ssm_a", (long long)l));
if (!sa) continue;
std::vector<float> a3, raw;
RAD_TRY(whole(sa, a3));
raw.resize(a3.size());
for (size_t i = 0; i < a3.size(); ++i)
raw[i] = std::logf(a3[i] > 0.0f ? a3[i] : 1.0f);
RAD_TRY(add(fmt("blk.%lld.ssm_a_raw", (long long)l), sa->shape, std::move(raw)));
}
for (int64_t l = 1; l < n_layer; ++l) {
if ((l + 1) % group) continue; /* the MLA layers */
const std::string kn = fmt("blk.%lld.attn_k_b.weight", (long long)l);
const std::string vn = fmt("blk.%lld.attn_v_b.weight", (long long)l);
const SrcTensor* k = find(kn);
const SrcTensor* v = find(vn);
if (!k || !v) continue;
if (k->shape.size() != 3 || v->shape.size() != 3 || k->shape[0] != heads ||
k->shape[1] != latent || k->shape[2] != 128 || v->shape[0] != heads ||
v->shape[1] != 128 || v->shape[2] != latent)
return RAD_E_SHAPE;
std::vector<float> k3, v3, fused;
RAD_TRY(whole(k, k3));
RAD_TRY(whole(v, v3));
fused.assign((size_t)(heads * (2 * 128) * latent), 0.0f);
for (int64_t h = 0; h < heads; ++h)
for (int64_t d = 0; d < 128; ++d) {
/* k_b's head block [latent, 128] transposed into the 128 k rows. */
for (int64_t l2 = 0; l2 < latent; ++l2)
fused[((h * 2 + 0) * 128 + d) * latent + l2] = k3[((h * latent + l2) * 128) + d];
/* v_b's head block [128, latent] already runs its v rows. */
std::memcpy(&fused[((h * 2 + 1) * 128 + d) * latent],
&v3[((h * 128 + d) * latent)], (size_t)latent * sizeof(float));
}
RAD_TRY(add(fmt("blk.%lld.attn_kv_b.weight", (long long)l),
{ heads * 2 * 128, latent }, std::move(fused)));
/* q_b is one [heads * (nope + rope), q_lora] matrix the plugin row-maps; a quantised
* source cannot be row-mapped, so split it into the plain nope and rope blocks. The
* per-head boundary comes from the meta the reader republished, so the split only runs
* when the geometry is the one the plugin will consume. */
const char* nps = meta_.get("qk_nope_head_dim"), *rps = meta_.get("qk_rope_head_dim");
const int64_t qn = nps ? std::stoll(nps) : 0, qr = rps ? std::stoll(rps) : 0;
const SrcTensor* qb = find(fmt("blk.%lld.attn_q_b.weight", (long long)l));
/* The row product is checked, not trusted: heads and the two rope widths arrive from
* the container, and a wrapped product that happened to equal the tensor's rows would
* run the split at the wrong per-head boundary. */
int64_t w = 0, qb_rows = 0;
if (qb && qb->shape.size() == 2 && qb->shape[1] > 0 && qn > 0 && qr > 0 &&
!__builtin_add_overflow(qn, qr, &w) && !__builtin_mul_overflow(heads, w, &qb_rows) &&
qb->shape[0] == qb_rows) {
const int64_t ql = qb->shape[1];
std::vector<float> q3, nblk, rblk;
RAD_TRY(whole(qb, q3));
nblk.assign((size_t)(heads * qn) * ql, 0.0f);
rblk.assign((size_t)(heads * qr) * ql, 0.0f);
for (int64_t h = 0; h < heads; ++h) {
std::memcpy(&nblk[(h * qn) * ql], &q3[(h * w) * ql], (size_t)(qn * ql) * sizeof(float));
std::memcpy(&rblk[(h * qr) * ql], &q3[(h * w + qn) * ql], (size_t)(qr * ql) * sizeof(float));
}
RAD_TRY(add(fmt("blk.%lld.attn_q_b_nope.weight", (long long)l), { heads * qn, ql }, std::move(nblk)));
RAD_TRY(add(fmt("blk.%lld.attn_q_b_rope.weight", (long long)l), { heads * qr, ql }, std::move(rblk)));
}
}
for (int64_t l = dense; l < n_layer; ++l) {
if (n_expert < 1) continue;
/* The routed stacks stay where they are: the block's split-stacked source
* (gate, up, down per expert, a dim-0 slice each) slices the reader's flipped
* [E, ff, emb] / [E, emb, ff] tensors directly. Only the shared expert needs
* re-spelling under the block's prefix: copies, the reader's flip already
* orienting them. */
const char* sh[3] = { "ffn_gate_shexp", "ffn_up_shexp", "ffn_down_shexp" };
const char* shd[3] = { "mlp.shared_experts.gate_proj.weight",
"mlp.shared_experts.up_proj.weight",
"mlp.shared_experts.down_proj.weight" };
for (int q = 0; q < 3; ++q) {
const SrcTensor* t = find(fmt("blk.%lld.%s.weight", (long long)l, sh[q]));
if (!t) continue;
std::vector<float> v;
RAD_TRY(whole(t, v));
RAD_TRY(add(fmt("blk.%lld.%s", (long long)l, shd[q]), t->shape, std::move(v)));
}
}
return RAD_OK;
}
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
std::string* why) {
auto refuse = [&](int rc, std::string m) {
+11
View File
@@ -49,6 +49,10 @@ struct SrcTensor {
std::vector<int64_t> shape; /* row-major */
const void* data = nullptr;
int64_t bytes = 0;
/* Owned payload for a derived tensor: a checkpoint's layout rebuilt at load time (the Ling
* GGUF's head-last k_b/v_b fused into the plugin's interleaved kv_b, its expert-last stacks
* regrouped per expert). When non-empty `data` points here and `rad_dtype` is RAD_F32. */
std::vector<float> owned;
/* GPTQ-packed (auto_gptq's layout, shared by AutoRound's `auto_round:auto_gptq` export):
* `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along K
* from the low bits up, unsigned with zero point 2^(bits-1). The tensor described is the
@@ -220,6 +224,13 @@ private:
int add_torch_files();
int open_gguf(const std::string& path);
void detect_import();
/* The Ling GGUF's layouts the plugin's names expect, rebuilt at load so the container's
* recipe never sees the source layout: the KDA layers' ssm_a (the exporter's exp(A_log))
* logged back to ssm_a_raw, the MLA layers' head-last k_b and v_b fused into one
* interleaved kv_b, the quantised q_b split into the plugin's nope and rope blocks, and
* the shared experts re-spelled under the block's mlp.shared_experts prefix. The routed
* stacks stay where the reader's fastest-first flip leaves them. */
int bailingmoe3_layouts();
enum Kind { None, Gguf, SafeT } kind_ = None;
std::string path_, dir_, tok_dir_, meta_dir_;
+62 -3
View File
@@ -71,13 +71,72 @@ int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const {
return RAD_OK;
}
bool rad_blob_range(const uint8_t* base, int64_t size, const void* p, int64_t n,
int64_t* off, int64_t* len) {
if (!base || size <= 0 || !p || n <= 0) return false;
const uintptr_t lo = (uintptr_t)base, a = (uintptr_t)p;
const uint64_t hi = (uint64_t)lo + (uint64_t)size, end = (uint64_t)a + (uint64_t)n;
if (a < lo || end > hi || end < (uint64_t)a) return false; /* outside, or wraps */
if (off) *off = (int64_t)(a - lo);
if (len) *len = n;
return true;
}
std::vector<std::pair<int64_t, int64_t>> rad_keep_complement(
int64_t tables, int64_t size, std::vector<std::pair<int64_t, int64_t>> keep) {
/* Clamp to the blob, drop empties, sort and merge: the caller may hand in one range per rank,
* and every rank publishes the same table. */
std::vector<std::pair<int64_t, int64_t>> k;
k.reserve(keep.size());
for (const auto& r : keep) {
const int64_t a = std::max(r.first, tables), b = std::min(r.first + r.second, size);
if (b > a) k.emplace_back(a, b);
}
std::sort(k.begin(), k.end());
size_t m = 0;
for (size_t i = 0; i < k.size(); ++i) {
if (m && k[i].first <= k[m - 1].second) k[m - 1].second = std::max(k[m - 1].second, k[i].second);
else k[m++] = k[i];
}
k.resize(m);
/* Whole pages only, so a page that holds kept bytes stays: a gap's start rounds up and its
* end rounds down (the blob's own end is the mapping's). */
const int64_t pg = 4096;
std::vector<std::pair<int64_t, int64_t>> out;
auto gap = [&](int64_t a, int64_t b) {
a = (a + pg - 1) / pg * pg;
if (b < size) b = b / pg * pg;
if (b > a) out.emplace_back(a, b - a); /* (offset, bytes), as `keep` is written */
};
int64_t cur = tables;
for (const auto& r : k) {
if (r.first > cur) gap(cur, r.first);
cur = std::max(cur, r.second);
}
if (cur < size) gap(cur, size);
return out;
}
int64_t RadFile::keep_cached(const void* p, int64_t n) {
int64_t off = 0, len = 0;
if (rad_blob_range(base_, size_, p, n, &off, &len) &&
std::find(keep_.begin(), keep_.end(), std::make_pair(off, len)) == keep_.end())
keep_.emplace_back(off, len);
int64_t kept = 0;
for (const auto& r : keep_) kept += r.second;
return kept;
}
void RadFile::drop_blob_cache() const {
if (!base_ || !hdr_ || fd_ < 0) return;
const int64_t tables = (int64_t)hdr_->data_off < size_ ? (int64_t)hdr_->data_off : size_;
if (tables >= size_) return;
/* Unmap first, then drop the cache: the kernel cannot drop a page still mapped here. */
::madvise(base_ + tables, (size_t)(size_ - tables), MADV_DONTNEED);
::posix_fadvise(fd_, (off_t)tables, (off_t)(size_ - tables), POSIX_FADV_DONTNEED);
/* Unmap first, then drop the cache: the kernel cannot drop a page still mapped here. Only the
* ranges that are not kept (keep_cached); with none kept this is the whole blob. */
for (const auto& r : rad_keep_complement(tables, size_, keep_)) {
::madvise(base_ + r.first, (size_t)r.second, MADV_DONTNEED);
::posix_fadvise(fd_, (off_t)r.first, (off_t)r.second, POSIX_FADV_DONTNEED);
}
}
/* Advisory, with no madvise: the load reads with pread and never maps these pages. The one region
+23 -1
View File
@@ -68,8 +68,14 @@ public:
/* Drop the blob from the page cache and this process's page tables, so a container larger
* than RAM does not leave the cache full of pages nothing will read. Only the blob: the tables
* are small and read constantly. Advisory; the kernel may decline. */
* are small and read constantly. The ranges named to keep_cached() are left alone, on whole
* pages. Advisory; the kernel may decline either way. */
void drop_blob_cache() const;
/* Names [p, p + n) as read through the mapping for the engine's life (the mapped tier: an
* n-gram table), so no drop_blob_cache() frees its pages: a gather from dropped pages starts
* cold, from the drive. An address outside the container is ignored (a copy in RAM, or a
* table read from its own file). Returns the bytes now kept. */
int64_t keep_cached(const void* p, int64_t n);
/* Drop one range of the blob behind a single forward cursor. A buffered front-to-back read of
* a container larger than RAM otherwise builds reclaim pressure that slows the read itself.
@@ -153,6 +159,7 @@ private:
std::string path_;
uint8_t* base_ = nullptr;
int64_t size_ = 0;
std::vector<std::pair<int64_t, int64_t>> keep_; /* keep_cached: (blob offset, bytes) */
int fd_ = -1;
const RadFileHeader* hdr_ = nullptr;
@@ -168,6 +175,21 @@ private:
std::unordered_map<std::string_view, int64_t> by_name_;
};
/* The blob range [*off, *off + *len) a pointer covers, when it lies wholly inside the container
* [base, base + size): what a load records for the mapped tier. False when the address is not in
* the blob (a copy in RAM under `ngram-placement: ram`, or a table read from its own file under
* `disk=DIR`), where keeping it would name bytes that belong to something else. */
bool rad_blob_range(const uint8_t* base, int64_t size, const void* p, int64_t n,
int64_t* off, int64_t* len);
/* The ranges of [tables, size) a page-cache drop must free when `keep` stays: the complement of
* the keep ranges as (offset, bytes), the same convention `keep` uses. Page-rounded the way the
* drop needs it -- a gap's start rounds up and its end down, so a page holding kept bytes is never
* dropped. Unsorted, overlapping and out-of-range input is merged and clamped; a keep list covering
* the whole blob gives no ranges. */
std::vector<std::pair<int64_t, int64_t>> rad_keep_complement(
int64_t tables, int64_t size, std::vector<std::pair<int64_t, int64_t>> keep);
/* ================================================================== writer */
/* Streaming writer: the blob is never held in RAM (a checkpoint may be 100 GB). The tables
* (strings, directory, planes, encodings, vocab, profile) are in memory; ~50k directory rows for a
+2
View File
@@ -71,6 +71,8 @@ struct AudioRequest {
std::vector<float> ref_audio;
std::vector<int32_t> ref_cu;
std::vector<int32_t> ref_frame;
/* Reference-direction guidance: the negative prompt's own map into the same clips. */
std::vector<int32_t> neg_ref_frame;
int64_t max_frames = 0; /* the most frames to make, >= 1 */
int32_t steps = 0; /* 0: the model's default */
float cfg = 0.0f; /* 0: the model's default */
+23 -3
View File
@@ -292,7 +292,10 @@ int AudioDriver::submit(std::unique_ptr<AudioRequest> r, std::string* why) {
if (r->cfg != 0.0f && !(r->cfg >= 1.0f)) return no("guidance_scale must be >= 1");
/* References: the clips the declaration allows, each a whole number of frames, and a frame
* for every row that names one. */
if (!r->ref_cu.empty() || !r->ref_frame.empty() || !r->ref_audio.empty()) {
if (!r->ref_cu.empty() || !r->ref_frame.empty() || !r->ref_audio.empty() ||
!r->neg_ref_frame.empty()) {
if (nb_ == 2 && r->cfg != 0.0f && r->cfg != 1.0f && r->neg_ref_frame.empty())
return no("voice cloning requires guidance_scale 1; reference CFG is not served");
const int64_t n_ref = (int64_t)r->ref_cu.size() - 1, hop = d.ref_hop;
bool ok = d.ref_max > 0 && n_ref >= 1 && n_ref <= d.ref_max && r->ref_cu[0] == 0 &&
r->ref_cu.back() == (int64_t)r->ref_audio.size() &&
@@ -303,6 +306,10 @@ int AudioDriver::submit(std::unique_ptr<AudioRequest> r, std::string* why) {
const int64_t frames = ok ? r->ref_cu.back() / hop : 0;
for (int64_t t = 0; ok && t < T; ++t)
ok = r->ref_frame[(size_t)t] >= -1 && r->ref_frame[(size_t)t] < frames;
if (ok && !r->neg_ref_frame.empty()) {
ok = nb_ == 2 && neg_own_ && (int64_t)r->neg_ref_frame.size() == Tn;
for (int32_t f : r->neg_ref_frame) ok = ok && f >= -1 && f < frames;
}
if (!ok)
return no(d.ref_max > 0 ? "the references do not fit this model: at most " +
std::to_string(d.ref_max) + " clips of whole frames, " +
@@ -707,12 +714,24 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
if (n_ref > 0) {
std::memcpy(hptr<float>(R_RAUD), q.ref_audio.data(), q.ref_audio.size() * 4);
std::memcpy(hptr<int32_t>(R_RCU), q.ref_cu.data(), q.ref_cu.size() * 4);
std::memcpy(hptr<int32_t>(R_RFRM), q.ref_frame.data() + p0, (size_t)cb[0] * 4);
reg_[R_RAUD].used = (int64_t)q.ref_audio.size() * 4;
reg_[R_RCU].used = (int64_t)q.ref_cu.size() * 4;
reg_[R_RFRM].used = cb[0] * 4;
h_rcu_ = q.ref_cu;
h_rfrm_.assign(q.ref_frame.begin() + p0, q.ref_frame.begin() + p0 + cb[0]);
/* At guidance 1 the driver runs the conditional prompt in both branches. Its audio
* rows must be duplicated too, not silently turned into text in the second branch. */
if (nb_ > 1) {
if (j.cfg == 1.0f)
h_rfrm_.insert(h_rfrm_.end(), q.ref_frame.begin() + p0,
q.ref_frame.begin() + p0 + cb[1]);
else if (!q.neg_ref_frame.empty())
h_rfrm_.insert(h_rfrm_.end(), q.neg_ref_frame.begin() + p0,
q.neg_ref_frame.begin() + p0 + cb[1]);
else
h_rfrm_.resize((size_t)rows, -1);
}
std::memcpy(hptr<int32_t>(R_RFRM), h_rfrm_.data(), h_rfrm_.size() * 4);
reg_[R_RFRM].used = (int64_t)h_rfrm_.size() * 4;
}
if (upload() < 0) return nullptr;
base_batches(rows, nb_, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch);
@@ -721,6 +740,7 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
for (size_t r = 0; r < ranks_.size(); ++r) {
out_[r].gen = RAD_GEN_PASS_PROMPT;
RadAudioGenBatch& A = aout_[r];
A.prompt_cu_h = cu;
A.n_lane = 1;
A.lane_h = h_lane_.data();
A.last_h = h_last_.data();
+6
View File
@@ -221,6 +221,12 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
" pixels");
const int64_t tokens = (int64_t)(r->width / d.latent_scale) * (r->height / d.latent_scale);
const int nb = r->has_neg ? 2 : 1;
// Guidance branches must run together. Waiting cannot make an undersized
// deployment schedulable; reject it without changing its memory budget.
if (nb > max_seqs_)
return no("this request needs " + std::to_string(nb) +
" simultaneous image branches (--max-num-seqs must be at least " +
std::to_string(nb) + ")");
if (tokens > d.max_tokens)
return no("the image is " + std::to_string(r->width) + "x" + std::to_string(r->height) +
"; the largest this model makes is " + std::to_string(d.max_tokens) +
+5 -1
View File
@@ -1264,7 +1264,11 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
for (size_t r = 0; r < ranks_.size(); ++r) {
const int ri = (int)r;
RadVideoGenBatch& V = vout_[(size_t)r];
V.enc_geom_d = dptr<int32_t>(ri, R_ENCG);
/* The encoder mixes device kernels with host-only k=1 convolutions and snake
* activations. Those host ops dereference their raw geometry operand directly;
* a rank's VRAM copy segfaults on discrete GPUs. The pinned staging table is
* readable by both execution sites and lives until this pass has completed. */
V.enc_geom_d = hptr<int32_t>(R_ENCG);
V.enc_kind = it.kind;
V.enc_slot = it.slot;
if (audio) {
+27 -12
View File
@@ -93,9 +93,16 @@ std::vector<GenFieldSource> gen_sampling_sources(const GenSampling& stated, cons
}
bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampling* out) {
Json j;
try { j = Json::parse(json_text); }
catch (const std::exception& e) { RAD_WARN("%s: %s; ignoring it", src, e.what()); return false; }
/* A model-repo file, and container metadata reaches here too. Read it with the container's
* bounds: a file that is refused never becomes a tree -- an unbounded read of a hostile one
* could overflow this process's stack on the way to the dump or destructor below. */
bool over = false, deep = false;
Json j = Json::parse_container(json_text, &over, &deep);
if (over || deep) {
RAD_WARN("%s: %s; ignoring it", src, Json::bound_why(over, deep));
return false;
}
if (j.is_discarded()) { RAD_WARN("%s: not valid JSON; ignoring it", src); return false; }
if (!j.is_object()) { RAD_WARN("%s: not a JSON object; ignoring it", src); return false; }
/* `do_sample: false` means greedy, and transformers then ignores every other sampler field,
@@ -178,12 +185,16 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli
}
bool gen_sampling_from_file(const std::string& path, bool required, GenSampling* out) {
std::ifstream f(path);
if (!f) {
std::string text;
const int rst = read_text_file(path, text, kMaxContainerFile);
if (rst == RAD_E_IO) {
if (required) RAD_ERR("%s: cannot be read", path.c_str());
return false;
}
std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
if (rst != RAD_OK) {
RAD_ERR("%s: larger than the 256 MiB a container file may be", path.c_str());
return false;
}
return gen_sampling_parse(text, path.c_str(), out);
}
@@ -204,13 +215,17 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
}
if (std::strcmp(k, "no_repeat_ngram_whitelist") == 0) {
/* Not a number: the container's metadata is string-valued, and the whitelist is a
* JSON array spelled as JSON text. */
try {
j[k] = Json::parse(v);
} catch (const std::exception& e) {
* JSON array spelled as JSON text. Bounded like every other container input. */
bool over = false, deep = false;
Json w = Json::parse_container(v, &over, &deep);
if (over || deep)
RAD_WARN("the container states generation.%s as \"%s\", which is not a JSON "
"array of ids (%s); ignoring it", k, v, e.what());
}
"array of ids (%s); ignoring it",
k, log_sanitize(v).c_str(), Json::bound_why(over, deep));
else if (!w.is_discarded()) j[k] = std::move(w);
else
RAD_WARN("the container states generation.%s as \"%s\", which is not a JSON "
"array of ids; ignoring it", k, log_sanitize(v).c_str());
continue;
}
if (std::strcmp(k, "suppress_tokens") == 0) {
+15 -3
View File
@@ -97,18 +97,30 @@ std::string hf_default_download_dir() {
std::string hf_served_path(const std::string& dir, std::string* why) {
std::vector<std::string> rad;
int64_t other_fmt = 0;
std::error_code ec;
for (const fs::directory_entry& e : fs::directory_iterator(dir, ec)) {
std::error_code fe;
if (e.is_regular_file(fe) && e.path().filename().string().ends_with(".rad"))
rad.push_back(e.path().filename().string());
if (!e.is_regular_file(fe)) continue;
const std::string name = e.path().filename().string();
if (name.ends_with(".rad")) rad.push_back(name);
/* A repo fetched with hfget holds its source weights beside anything the operator or a
* conversion added later; a container sitting among them is not self-appointing. */
else if (name.ends_with(".safetensors") || name.ends_with(".gguf")) ++other_fmt;
}
if (ec) {
*why = dir + ": " + ec.message();
return std::string();
}
if (rad.empty()) return dir;
if (rad.size() == 1) return dir + "/" + rad[0];
if (rad.size() == 1) {
if (other_fmt > 0) {
*why = dir + " holds the container " + rad[0] + " beside safetensors or gguf weights; " +
"pass the one to serve as --model " + dir + "/<file>";
return std::string();
}
return dir + "/" + rad[0];
}
std::string names;
for (size_t i = 0; i < rad.size(); ++i) names += (i ? ", " : "") + rad[i];
*why = dir + " holds " + std::to_string(rad.size()) + " containers (" + names +
+16 -1
View File
@@ -6,6 +6,7 @@
#include "runtime/wtab.h"
#include <algorithm>
#include <atomic>
#include <cstdlib>
namespace rad {
@@ -202,8 +203,10 @@ bool stage_src(Ctx* ctx, int group, const RadKVGroupBatch* kvb, int layer, Stage
if (end <= 0 || end > st->host_layer_stride) end = st->host_layer_stride;
o->src.clear(); o->dst.clear(); o->len.clear();
o->bytes = 0;
bool clamped = false;
auto add = [&](int64_t off, int64_t n) {
if (off >= end) return;
if (off >= end) { clamped = true; return; }
if (n > end - off) clamped = true;
n = std::min(n, end - off);
if (n <= 0) return;
o->src.push_back((uint64_t)(uintptr_t)(row + off));
@@ -214,6 +217,18 @@ bool stage_src(Ctx* ctx, int group, const RadKVGroupBatch* kvb, int layer, Stage
/* Only the step's ranges (stage.h, "Volume"); none set copies the row. */
if (b->stage_runs.empty()) add(0, end);
for (const KVStageRun& r : b->stage_runs) add(r.off, r.bytes);
if (clamped) {
/* Once, not per step: a run naming a block past the mirror row means pool and host
* layer disagree on the layout, and the bytes past the clamp silently never stage --
* attention then reads a row that is part copy and part stale. The clamp is the
* memory-safe answer; this is the promise that it is never a silent one. */
static std::atomic<bool> said{false};
if (log_once(said))
RAD_WARN("kvstream: group %d stage runs reach past the host layer's end (%lld of "
"%lld bytes): the stage drops what lies past it, and staged attention "
"reads stale bytes there (first of possibly many)",
group, (long long)end, (long long)st->host_layer_stride);
}
return o->bytes > 0;
}
+20 -8
View File
@@ -10,6 +10,7 @@
#include <cstdlib>
#include <cstring>
#include <map>
#include <limits>
#include <regex>
#include <thread>
#include <unordered_map>
@@ -133,16 +134,27 @@ void mm_tn(const float* A, const float* B, float* C, int64_t m, int64_t k, int64
void orth(float* Y, int64_t n, int64_t l) {
std::vector<double> col((size_t)n);
for (int64_t j = 0; j < l; ++j) {
double original_norm2 = 0.0;
for (int64_t r = 0; r < n; ++r) {
col[(size_t)r] = Y[r * l + j];
original_norm2 += col[(size_t)r] * col[(size_t)r];
}
// Keep both projection passes in double scratch. Rounding each subtraction
// to float can turn a dependent column's residue into a spurious basis vector.
for (int pass = 0; pass < 2; ++pass)
for (int64_t i = 0; i < j; ++i) {
double d = 0.0;
for (int64_t r = 0; r < n; ++r) d += (double)Y[r * l + i] * Y[r * l + j];
for (int64_t r = 0; r < n; ++r) Y[r * l + j] -= (float)(d * Y[r * l + i]);
double dot = 0.0;
for (int64_t r = 0; r < n; ++r) dot += Y[r * l + i] * col[(size_t)r];
for (int64_t r = 0; r < n; ++r) col[(size_t)r] -= dot * Y[r * l + i];
}
double nn = 0.0;
for (int64_t r = 0; r < n; ++r) nn += (double)Y[r * l + j] * Y[r * l + j];
const double inv = nn > 1e-30 ? 1.0 / std::sqrt(nn) : 0.0;
for (int64_t r = 0; r < n; ++r) Y[r * l + j] = (float)(Y[r * l + j] * inv);
double norm2 = 0.0;
for (const double value : col) norm2 += value * value;
// The tolerance follows the original column's scale and projection count,
// rather than the number of zero rows used to pad the matrix.
const double tolerance = std::numeric_limits<float>::epsilon() * std::max<int64_t>(1, j);
const double inverse = norm2 > original_norm2 * tolerance * tolerance
? 1.0 / std::sqrt(norm2) : 0.0;
for (int64_t r = 0; r < n; ++r) Y[r * l + j] = (float)(col[(size_t)r] * inverse);
}
}
@@ -532,7 +544,7 @@ void truncate(const Delta& d, int64_t r, std::vector<float>* B, std::vector<floa
mm_tn(d.B.data(), Y, t.data(), d.r, N, l);
mm_tn(d.A.data(), t.data(), X, K, d.r, l);
};
const int64_t l = std::min({ r + 8, N, K });
const int64_t l = std::min({ r + 8, N, K, d.rank_bound > 0 ? d.rank_bound : r + 8 });
/* A fixed sketch: the same adapter composes to the same bytes on every rank and every load. */
std::vector<float> Om((size_t)(K * l));
uint64_t st = 0x2545F4914F6CDD1Dull ^ (uint64_t)(N * 1315423911ull + K);
+22 -3
View File
@@ -616,7 +616,13 @@ bool op_is_site(const Program& prog, const OpInfo& op, rad_weight* b_out, std::s
return no(fmt("%s reads K=%lld against a weight of %lld columns (a widened, rotated "
"input)", op.op.c_str(), k, (long long)w.decl.shape[1]));
}
if (w.enc_known && w.enc.transform[0])
/* A quantised GEMM over a transformed weight is fed had_quant's rotated codes, so the adapter
* epilogue would multiply A against a transformed activation. A plain fp GEMM (gemm_nt,
* gemm_nt_bias) is fed what the architecture hands it: plain activations, with the kernel
* library's layout/relayout hooks presenting the planes in the plain basis at load (a plain
* kernel with no such hook is refused at declare by its own layout, RAD_E_DTYPE). A resolved
* plain GEMM over a transformed encoding is therefore basis-safe for the adapter epilogue. */
if ((gq || gqb) && w.enc_known && w.enc.transform[0])
return no(fmt("weight '%s' is stored in the '%.*s' transform basis, so its GEMM is fed a "
"transformed activation", w.name.c_str(), (int)RAD_ENC_STR, w.enc.transform));
return true;
@@ -631,6 +637,10 @@ int find_unsupported_uses(const Program& prog, const TargetSet& targets,
for (size_t i = 1; i < prog.ops.size(); ++i) {
const OpInfo& op = prog.ops[i];
if (op.weights.empty() || !op_live(op)) continue;
/* A prefetch only stages a weight's planes for the GEMMs that read them; the adapter's
* delta is applied at the site's expand op, so staging the base planes stays correct.
* A prefetch neither carries nor invalidates an adapter. */
if (op.op == "prefetch") continue;
rad_weight b = 0;
std::string why;
const bool site = op_is_site(prog, op, &b, &why);
@@ -804,9 +814,18 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
/* ---- the config */
const std::string cfg_path = dir + "/adapter_config.json";
std::string text;
if (!read_file(cfg_path, &text))
const int rst = read_text_file(cfg_path, text, kMaxContainerFile);
if (rst == RAD_E_FORMAT)
return fail(err, RAD_E_FORMAT,
cfg_path + ": larger than the 256 MiB a container file may be");
if (rst != RAD_OK)
return fail(err, RAD_E_IO, cfg_path + ": cannot read (a PEFT adapter directory has one)");
const ojson cfg = ojson::parse(text, nullptr, false);
/* Container-supplied like the generation config, so read with the container's bounds: a
* file past them is refused during the read, never grown into a tree to be walked. */
bool over = false, deep = false;
const ojson cfg = ojson::parse_container(text, &over, &deep);
if (over || deep)
return fail(err, RAD_E_FORMAT, cfg_path + ": " + ojson::bound_why(over, deep));
if (cfg.is_discarded() || !cfg.is_object())
return fail(err, RAD_E_FORMAT, cfg_path + ": not a JSON object");
auto truthy = [&](const char* k) {
+3 -3
View File
@@ -58,11 +58,11 @@ int main(int argc, char** argv) {
return 0;
}
/* An offline mode (KL scoring, calibration) or the graph dump runs one engine to its end and
* serves nothing; every other configuration is served by the fleet. */
/* An offline mode (KL scoring, calibration, the diagnose workload) or the graph dump runs one
* engine to its end and serves nothing; every other configuration is served by the fleet. */
bool offline = false;
for (const rad::fleet::ModelEntry& m : fleet.models)
offline |= m.cfg.kld() || m.cfg.calib() || m.cfg.debug_graph;
offline |= m.cfg.kld() || m.cfg.calib() || m.cfg.diagnose_mode() || m.cfg.debug_graph;
if (!offline) return rad::fleet::run(fleet);
if (fleet.models.size() != 1) {
RAD_ERR("%s: an offline mode or the graph dump runs one model; the file names %zu",
+91
View File
@@ -3,6 +3,7 @@
#include "kvstream/carve.h"
#include "kvstream/plan.h"
#include "device/device.h"
#include <algorithm>
#include <cmath>
@@ -303,6 +304,21 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
if (p.runtime_win && !p.zero)
fixed += align_up(max_seqs_ * p.ring_blocks_max() * p.bytes_per_block, RAD_ALIGN_UNIT);
/* The checkpoint stage (ckpt_stage): one snapshot of the linear state, where a lone spanned
* prefill may take its tail snapshot inside its last chunk (--prefill-span above 1,
* --prefill-tail-snapshot on), the engine snapshots into a prefix cache and the slot carries
* no window. */
stage_bytes_ = 0;
{
int64_t lin = 0;
for (const auto& p : plans_) if (p.stateful() && !p.zero) lin += p.bytes_per_state;
if (cfg.ckpt_stage && cfg.prefill_span > 1 && cfg.prefill_tail_snapshot &&
cfg.prefix_cache && cfg.checkpoint_slots != 0 && window_ck_bytes_ == 0 && lin > 0 &&
lin == checkpoint_bytes_)
stage_bytes_ = lin;
}
if (stage_bytes_ > 0) fixed += align_up(stage_bytes_, RAD_ALIGN_UNIT);
fixed_ = fixed;
ckpts_ = budget_ckpts;
return RAD_OK;
@@ -418,6 +434,8 @@ void KVManager::forget() {
live_.clear(); free_usable_.clear(); bucket_blocks_.clear(); held_hist_.clear();
chunk_blocks_.clear(); short_peak_.clear();
pool_ = nullptr;
stage_ = nullptr;
stage_off_ = 0;
clears_.clear();
seqs_.clear(); pending_.clear();
configured_ = false;
@@ -589,6 +607,15 @@ int KVManager::carve_into(Pool& kv_pool) {
p.pool_offset = off;
p.pool_bytes = bytes;
}
/* The checkpoint stage, after the groups (its bytes are in fixed_). */
if (stage_bytes_ > 0) {
stage_ = kv_pool.reserve("checkpoint stage", stage_bytes_, RAD_ALIGN_UNIT, &stage_off_);
if (!stage_) {
RAD_ERR("the checkpoint stage (%s) did not fit the KV pool",
humanb(stage_bytes_).c_str());
return RAD_E_NOMEM;
}
}
/* --checkpoint-slots does nothing on a model with no recurrent state; say so. */
if (ckpts_ > 0 && checkpoint_bytes_ <= 0)
RAD_WARN("--checkpoint-slots %lld ignored: this model declares no linear-attention state, "
@@ -672,6 +699,10 @@ int KVManager::carve_into(Pool& kv_pool) {
const int rc = lendable(p.index) ? 0 : pool_->commit(p.pool_offset, p.pool_bytes);
if (rc < 0) return rc;
}
if (stage_) {
const int rc = pool_->commit(stage_off_, stage_bytes_);
if (rc < 0) return rc;
}
if (const int rc = flex_span(flex_floor_loan_, carved + 1, true); rc < 0) {
RAD_ERR("KV pool: the card would not back the cache's floor of %s",
humanb(flex_backed_).c_str());
@@ -822,6 +853,22 @@ int64_t KVManager::total_blocks(int32_t g) const {
int64_t KVManager::live_blocks(int32_t g) const {
return (g >= 0 && g < (int32_t)live_.size()) ? live_[(size_t)g] : 0;
}
int64_t KVManager::live_blocks_at(int32_t g, int64_t tokens) const {
if (g < 0 || g >= (int32_t)plans_.size()) return 0;
return plans_[(size_t)g].n_blocks - lent_blocks((size_t)g, tokens);
}
int64_t KVManager::straggler_mark(int32_t g) const {
if (g < 0 || g >= (int32_t)plans_.size()) return 0;
const int64_t top = held_top((size_t)g), per = bucket_blocks_[(size_t)g];
const auto& h = held_hist_[(size_t)g];
int64_t mark = top, best = 0, held = 0;
for (int64_t b = (top + per - 1) / per; b-- > 0;) {
held += h[(size_t)b];
const int64_t gain = top - b * per - kStragglerCost * held;
if (gain > best) { best = gain; mark = b * per; }
}
return mark;
}
int64_t KVManager::held_top_blocks(int32_t g) const {
return (g >= 0 && g < (int32_t)plans_.size()) ? held_top((size_t)g) : 0;
}
@@ -1801,6 +1848,50 @@ int KVManager::checkpoint_restore(const int32_t* slots, int n, int32_t ck, RadSt
return checkpoint_copy(slots, n, ck, /*save=*/false, s, win);
}
void KVManager::ckpt_stage_layout(std::vector<int64_t>* off, std::vector<int64_t>* lb) const {
off->assign(plans_.size(), -1);
lb->assign(plans_.size(), 0);
int64_t at = 0;
for (size_t g = 0; g < plans_.size(); ++g) {
const KVGroupPlan& p = plans_[g];
if (!p.stateful()) continue;
(*off)[g] = at;
(*lb)[g] = p.layer_bytes_per_state();
at += p.layer_bytes_per_state() * p.n_layers;
}
}
int KVManager::checkpoint_stage_rest(const int32_t* slots, int n, RadStream s,
const std::function<bool(size_t, int64_t)>& skip) {
if (!stage_) return RAD_E_STATE;
if (!slots || n < (int)plans_.size()) return RAD_E_INVAL;
int64_t off = 0;
for (size_t g = 0; g < plans_.size(); ++g) {
const KVGroupPlan& p = plans_[g];
if (!p.stateful()) continue;
const int64_t nbytes = p.layer_bytes_per_state();
for (int64_t l = 0; l < p.n_layers; ++l) {
if (skip(g, l)) continue;
void* st = slots[g] >= 0 ? state_ptr((int32_t)g, (int32_t)l, slots[g]) : nullptr;
if (!st) return RAD_E_STATE;
RAD_TRY(rad_memcpy_async((char*)stage_ + off + l * nbytes, st, nbytes, s));
}
off += nbytes * p.n_layers;
}
return RAD_OK;
}
int KVManager::checkpoint_stage_out(int32_t ck, RadStream s) {
if (!stage_) return RAD_E_STATE;
if (!ck_store_ || !ck_store_->in_use(ck)) {
RAD_ERR("checkpoint stage: the store does not hold slot %d", (int)ck);
return RAD_E_INVAL;
}
char* dst = (char*)checkpoint_ptr(ck);
if (!dst) return RAD_E_INVAL;
return rad_memcpy_async(dst, stage_, stage_bytes_, s);
}
bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector<int32_t>* out) const {
out->clear();
const Seq* s = find(id);
+41
View File
@@ -508,6 +508,18 @@ public:
/* Blocks of a group the cache may hand out: the carve less the loan. */
int64_t live_blocks(int32_t group) const;
/* The same under a loan of `tokens`: the first block of the group that loan would take. A
* group that does not lend answers its whole carve. */
int64_t live_blocks_at(int32_t group, int64_t tokens) const;
/* Where a group's stragglers start. A loan reaches down only to the highest held block, so a
* few held blocks high in the pool keep everything between them and the dense part of the
* cache from the expert slab. Giving up the held blocks at or above a mark m extends what
* can be lent by (held top - m) blocks at the cost of the blocks held there; the mark is the
* m that gains the most over kStragglerCost times that cost, to a bucket of held_hist_. The
* held top itself when no m gains anything: a pool held densely up to its top has no
* stragglers, and the edge of a dense part is never one. Rank 0 only. */
int64_t straggler_mark(int32_t group) const;
static constexpr int64_t kStragglerCost = 16;
/* ---------------- flex (docs/MULTIMODEL.md §6) ----------------
*
@@ -615,6 +627,32 @@ public:
int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s,
const std::vector<int32_t>* win = nullptr);
/* ---------------- the checkpoint stage ----------------
*
* One snapshot of the linear state on the card, laid out as a checkpoint slot's linear section
* (checkpoint_copy's walk: group by group in plans() order, a layer after another), carved
* from the KV pool as a fixed cost. A checkpoint inside a step (RadBatch::ckpt_cut): the
* plugin copies each layer's state there between the recurrence's two pieces (rad_ckpt_snap,
* Ctx::set_ckpt_snap), since the live slot has moved on by the step's end; the engine then
* copies the layers the step left alone in (checkpoint_stage_rest) and the stage to the host
* slot in one copy (checkpoint_stage_out, Engine::save_checkpoints).
*
* Planned (plan_groups) where the engine snapshots linear state into a prefix cache and the
* slot has no window section, under Config::ckpt_stage (the plugin cuts its step at a tail
* snapshot and --prefix-resume is nearest); 0 bytes and a null stage otherwise, which keeps
* every checkpoint at a chunk's end. */
int64_t ckpt_stage_bytes() const { return stage_bytes_; }
void* ckpt_stage() const { return stage_; }
/* Per group (by index): the group's offset in the stage and its bytes a layer, -1 / 0 for a
* group with no state. */
void ckpt_stage_layout(std::vector<int64_t>* off, std::vector<int64_t>* lb) const;
/* The live slots' state of every stateful (group, layer) `skip` does not name into the stage,
* on `s`: the layers a step with a checkpoint inside it left alone. */
int checkpoint_stage_rest(const int32_t* state_slots, int n_slots, RadStream s,
const std::function<bool(size_t, int64_t)>& skip);
/* The stage into checkpoint slot `ck`, as one copy on `s`. */
int checkpoint_stage_out(int32_t ck, RadStream s);
/* ---------------- window snapshots (the sliding-window half of a prefix hit) ----------------
* A WINDOW group keeps only the blocks its window can still read, so the prefix cache's block
* lists do not describe it. A prompt extending a cached prefix at position P needs blocks
@@ -708,6 +746,9 @@ private:
int64_t ck_rank_off_ = 0;
int64_t checkpoint_bytes_ = 0;
int64_t window_ck_bytes_ = 0; /* the window section of checkpoint_bytes_ */
int64_t stage_bytes_ = 0; /* ckpt_stage_bytes */
void* stage_ = nullptr;
int64_t stage_off_ = 0; /* in the pool */
std::vector<StateClear> clears_; /* grabbed slots the engine must zero */
void* pool_base_ = nullptr;
BundleComparison bundling_;
+13 -2
View File
@@ -356,8 +356,10 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector<TierJob>* out) {
RAD_WARN("kv tiers: %lld entries (%lld tokens of context) got no host copy: the host "
"tier (--prefix-cache-mib, %s, %lld tokens) is full of context used more "
"recently or nearer the start of its conversation. They stay in VRAM only and "
"are prefilled again once VRAM gives them up; a larger --prefix-cache-mib holds "
"more. Counted in /sessions moved.held_back",
"are prefilled again once VRAM gives them up, which it does for a request that "
"needs the room, or where a few of them keep the expert loan from most of the "
"pool; a larger --prefix-cache-mib holds more. "
"Counted in /sessions moved.held_back",
(long long)held, (long long)(held * cfg_.block_tokens),
humanb(arena_.cap_bytes()).c_str(),
(long long)(arena_.capacity() * cfg_.block_tokens));
@@ -375,6 +377,15 @@ void IdleTiers::take_clean(std::vector<BlockHash>* out) {
clean_q_.clear();
}
bool IdleTiers::no_copy_coming(const BlockHash& key) const {
std::lock_guard lk(mu_);
auto it = recs_.find(key);
if (it == recs_.end()) return false;
const Rec& r = it->second;
if (r.pending || r.doomed || r.tier != KVTier::Device || r.host_slot >= 0) return false;
return !r.queued || (wb_stuck_ && arena_.full());
}
bool IdleTiers::droppable(const BlockHash& key) const {
std::lock_guard lk(mu_);
auto it = recs_.find(key);
+4
View File
@@ -156,6 +156,10 @@ public:
void take_clean(std::vector<BlockHash>* out);
/* Host copy landed and no job out: the blocks can leave VRAM at no cost. */
bool droppable(const BlockHash& key) const;
/* In VRAM only with no host copy coming: none made or on its way, and either none asked for
* (a full arena refused it, Stats::held_back) or the queue it waits in has stopped because
* the arena is full of entries worth more. */
bool no_copy_coming(const BlockHash& key) const;
/* The cache released the blocks; the record becomes a host record on the host list. Its
* snapshot stays in its store slot. */
void drop_commit(const BlockHash& key);
+50 -2
View File
@@ -796,12 +796,13 @@ int64_t PrefixCache::trim_sparing(int64_t n_entries,
return done;
}
int64_t PrefixCache::drop_clean() {
int64_t PrefixCache::drop_clean(int64_t loan_goal) {
if (!tiers_ || !kv_) return 0;
drop_scratch_.clear();
tiers_->take_clean(&drop_scratch_);
const uint64_t frees = kv_->seq_frees();
if (frees != frees_seen_ || released_) {
const bool recheck = frees != frees_seen_ || released_;
if (recheck) {
frees_seen_ = frees;
released_ = false;
for (const BlockHash& h : drop_wait_) {
@@ -830,6 +831,53 @@ int64_t PrefixCache::drop_clean() {
tiers_->drop_commit(h);
++n;
}
return n + drop_stragglers(loan_goal, recheck);
}
/* drop_clean's second half: resident entries with no host copy coming that are stragglers inside
* a loan of `loan_goal` tokens. One walk of the resident list, taken only while something is held
* above a group's mark, and then when a sequence has freed blocks (`recheck`) or the marks have
* moved since the last walk, a second or more ago. */
int64_t PrefixCache::drop_stragglers(int64_t loan_goal, bool recheck) {
if (loan_goal <= 0 || !tiers_->host_on()) return 0;
const size_t ng = entry_groups_.size();
strag_mark_.assign(2 * ng, 0);
bool any = false;
for (size_t k = 0; k < ng; ++k) {
const int32_t g = entry_groups_[k];
const int64_t top = kv_->held_top_blocks(g);
const int64_t mark = !kv_->lendable(g) ? INT64_MAX
: std::max(kv_->straggler_mark(g), kv_->live_blocks_at(g, loan_goal));
strag_mark_[k] = mark;
strag_mark_[ng + k] = top;
any = any || top > mark;
}
if (!any) return 0;
const uint64_t now = rad_mono_ns();
if (!recheck && (strag_mark_ == strag_seen_ || now - strag_ns_ < 1000000000ull)) return 0;
strag_seen_ = strag_mark_;
strag_ns_ = now;
int64_t n = 0;
for (auto it = lru_.begin(); it != lru_.end();) {
const BlockHash h = *it;
auto m = map_.find(h);
if (m == map_.end()) { ++it; continue; }
Entry& e = m->second;
bool above = false;
for (size_t k = 0; k < ng && k < e.blocks.size(); ++k)
above = above || e.blocks[k] >= strag_mark_[k];
if (!above || held_.count(h) > 0 || shared_with_live(e) || !tiers_->no_copy_coming(h)) {
++it;
continue;
}
release_blocks(e);
it = lru_.erase(it);
tiers_->forget(h);
map_.erase(m);
++stats_.evictions;
++n;
}
return n;
}
+16 -2
View File
@@ -306,8 +306,17 @@ public:
int64_t trim(int64_t n_entries);
/* Give up every VRAM copy that costs nothing to drop: host copy landed and no running sequence
* reading it. Used when the memory has a better use (the expert slab's loan). Entries still
* shared are retried after a sequence frees blocks. Returns how many entries left VRAM. */
int64_t drop_clean();
* shared are retried after a sequence frees blocks. Returns how many entries left VRAM.
*
* `loan_goal` is the loan the slab is short of, in tokens (0: none). An entry with no host
* copy coming (the host tier is full of context worth more) never becomes clean, and the
* loan reaches down only to the highest held block: a few such entries high in the pool keep
* the slab from everything below them for as long as the server runs. Where they are
* stragglers (KVManager::straggler_mark: giving them up lends at least sixteen blocks for
* each one lost) and stand inside `loan_goal`, they are forgotten, and their tokens are
* prefilled again if their conversation returns. Context that fills its part of the pool
* stays: there the cache is worth more than the loan it holds back. */
int64_t drop_clean(int64_t loan_goal = 0);
int64_t size() const { return (int64_t)map_.size(); }
/* Entries holding blocks in the pool, as opposed to only a copy off the card. */
int64_t resident() const { return (int64_t)lru_.size(); }
@@ -544,6 +553,11 @@ private:
* sequence-free count then. They are rechecked only once that count moves. */
std::vector<BlockHash> drop_wait_;
std::vector<BlockHash> drop_scratch_;
/* drop_stragglers: the marks and held tops it last walked the list for, and when. It walks
* again when a sequence frees blocks, or once they have moved and a second has passed. */
std::vector<int64_t> strag_mark_, strag_seen_;
uint64_t strag_ns_ = 0;
int64_t drop_stragglers(int64_t loan_goal, bool recheck);
uint64_t frees_seen_ = 0;
/* hold(): keys per waiting request, and holders per key. A release also triggers a recheck
* of drop_wait_. */
Loaded 100 of 448 files, more files were not shown because too many files have changed in this diff. Show more