Compare commits

...
95 Commits
Author SHA1 Message Date
Deadcode b068190326 radiance 1.6.0
- Qwen-Image 2.1 and 2.1 Turbo: text to image and image edits over OpenAI's images API,
  /v1/images/generations and /v1/images/edits. An edit takes up to ten pictures and an optional
  mask, outside which the picture comes back exactly as it was; `background: transparent`, png,
  jpeg and webp output, `n` pictures from one prompt, streamed previews (`partial_images`), and
  vLLM-Omni's seed, negative_prompt with true_cfg_scale, num_inference_steps, width and height.
  arch/qwenimage21 serves the diffusers pipeline directory, converted with
  data/recipes/qwen-image-2.1-fp8.recipe (block fp8) or qwen-image-2.1-bf16.recipe.
  deploy/compose/qwen-image-2.1.yaml and qwen-image-2.1-turbo.yaml serve the fp8 containers on
  two cards. Two R9700s make a 2048x2048 picture in 61 s at the base model's 40 steps and in
  13 s with Turbo (56 and 12 s with --tp-wire wht6), a 1024x1024 one in 6.0 and 2.6 s. The
  models are under Qwen's research license, which is non-commercial
- an image generator is a program kind of its own (core/gen): an architecture declares its
  conditioning, denoising and decoding passes, and the driver runs the schedule, the pictures of
  a batch and the conditioning cache. An image model's /v1/models entry is its generator's name
  (qwen-image-2.1, qwen-image-2.1-turbo), and its capabilities and startup banner list only the
  images endpoints
- the tiled prefill GEMMs run their tiles in groups of activation bands, 16 for fp8 and 8 for
  bf16, so an operand larger than the 64 MB cache is read once a group instead of once a band. A
  bf16 GEMM with more than 64 MB of weight runs up to twice as fast
- fixed: a second lane opened in the middle of a step started beside work lane 0 had not
  finished. Gemma 4 26B-A4B opens its lane that way, so its first step after startup could read
  rows not yet written
- startup no longer warns about --checkpoint-slots when it was not passed, nor about an expert
  floor on a model with no experts
- the image's FFmpeg writes png, jpeg and webp (libwebp)
- for out-of-tree plugins: RAD_ABI_VERSION is 16. The op vocabulary gains the image generator's
  ops (conv2d_nhwc, ln_mod, ln_mod_quant_fp8, flow_euler, attn_prefix_self and others; docs/OPS.md,
  "Image generation"), and all_reduce takes an optional `overlap`. Plugins built against 1.5.0
  must be rebuilt
2026-10-14 14:03:59 +02:00
Deadcode b93b531f63 radiance 1.5.0
- Gemma 4 31B (PRs #74, #75, #81, #86; sfjes, keptn42): sliding and global attention with their
  own kernels, the assistant head as a drafter that reads the trunk's cache, the vision tower, a
  fused w4a8 decode step, bf16 and compressed-tensors int4 checkpoints, and window snapshots so a
  prefix hit on a sliding-window model resumes instead of prefilling again.
  deploy/compose/gemma4-31b-w4a8.yaml serves keptn42's container on two cards
- ParoQuant (PRs #65, #66, #67; malic): Qwen3.8-27B checkpoints with learned Givens rotations,
  as int4, int5 and MXFP4, imported without re-quantising, the prefill's rotations on the matrix
  cores. deploy/compose/qwen3.8-27b-paro.yaml serves them on one card. A ParoQuant container made
  with the PR builds is refused: convert it again with --reuse <old container>
- Gemma 4 26B-A4B with z-lab's DFlash drafter (PR #88; Perire): arch/gemma4 serves Google's bf16
  checkpoint with the routed experts in block fp8 or bf16 (data/recipes/gemma4-26b-a4b-df*.recipe),
  and libr4d gains its windowed paged attention, the fused sandwich-norm joins, expert_scale and
  the sharded draft head's pair_argmax. A prefill chunk runs as two slices with its all-reduces
  beside the compute, bit-exact with the whole step. The 31B's global layers take the windowed
  attention too: an 11.5K-token prefill on two R9700s in 3.1 s instead of 4.9
- a startup that logs nothing for two minutes says where it waits (#89): the system call (a KFD
  request by name), the library that made it, and its stack, which addr2line resolves against the
  binary
- the prefix cache is kept in VRAM and host memory only (#70): the disk tier wrote every block and
  snapshot a prompt produced, and its copies never outlived the process. --prefix-cache-host-mib
  is renamed --prefix-cache-mib; --prefix-cache-dir and --prefix-cache-disk-mib are removed, and
  startup refuses all three with what replaced them. The compose files no longer mount /data, and
  .env no longer needs RADIANCE_STATE
- --prefix-cache-ttl S (default 3600, 0 never): a conversation no request has used for that long
  leaves the cache, whichever tier holds it; radiance:prefix_cache_expired_total counts them. A
  full host tier now drops its least recently used conversations
- --vision-tower-placement vram|ram (#84): ram keeps an encoder tower in pinned host memory and
  gives its VRAM to the KV cache, read over the link once an image
- timings carry ttft_ms and total_ms (#85): the server's own time from the request body's arrival
  to the first and the last token, queueing and tokenisation included
- a KV-cache recall that found a moved expert with nowhere to go stopped halfway and leaked the
  slots it had already freed: after it every recall failed, the cache stayed short until a
  restart, and requests failed with HTTP 500. A recall now waits for the slots it is owed and
  always finishes
- a tool result or tool-call arguments that are not JSON are no longer refused as nesting past
  1024 levels for their unmatched brackets (#90): only text that parses as JSON is held to the
  bound, since nothing else is parsed into a tree
- the host-pool refusal names the limit that applies to pinned memory (RAM less 1/64 and
  1.5 GiB), not ttm.pages_limit
- --embedding-placement auto, removed in 1.3.0, is refused with what replaced it
- for out-of-tree kernel libraries: gemm_nt_q gains two operands (pb1, pb2, the part bounds), and
  the loader requires identical op schemas, so a library built against 1.4.0 must be rebuilt. For
  architecture plugins, rad_op_declared(b, op) asks whether an op is in the loaded vocabulary
  without declaring it
2026-10-13 19:35:16 +02:00
AshlynandClaude Opus 5.5 c527863248 arch/gemma4: the dense arm on the second lane beside the routed arm, in a step that runs whole
The two feed-forward arms of a Gemma 4 MoE layer read the same normed residual and meet only at
the feed-forward join; issued one after the other, the dense arm's three launches -- gate_up,
act_mul, down, ~36 us under --profile-ops at a 26B-A4B decode step on 4x R9700 -- wait behind the
routed arm's ~120 every layer. At a few rows its GEMMs are latency-bound, nowhere near the
bandwidth the experts' GEMMs take.

In a step that runs whole -- every decode and verify step, and a prefill chunk too short to cut --
the dense arm now rides the second lane: issued behind a join from lane 0 (the attention join is
its producer), beside the routed arm on lane 0, and joined back before the feed-forward reduction
reads both. Its rows of the join buffer and the routed arm's are disjoint. No collective rides it,
so the reductions keep lane 0 here and lane 1 in a cut prefill chunk, and a step's collectives are
on one lane as before. h, gate_up, ffn and ff2 are named to rad_buf_concurrent. Off with the
overlap's switch, RADIANCE_GEMMA4_OVERLAP=0, which now keeps every step on one stream; a startup
note says which.

arch_test: a decode step issues the dense arm's three launches a layer on lane 1 and every
all-reduce on lane 0, two joins a layer, and nothing on the two lanes that touches a common
element unordered; a 4095-token chunk the same; the cut chunks keep lane 1 for their reductions
alone. GUIDE.md's switch and ARCHITECTURES.md say so.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 7a1ae22690 gemma4k, arch/gemma4: norm_add_norm_route -- the attention join writes the routed arm's inputs
The 26B-A4B's router reads rmsnorm(x) * w_r * hidden^-0.5 and its experts rmsnorm(x) * w_e,
quantised to E4M3 for the fp8 gate_up: an `rmsnorm` and an `rmsnorm_quant_fp8` a layer, each
reading back the x norm_add_norm has just written and taking the sum of squares it has just taken.
At decode that is 60 launches a step (8.3 and 7.8 us under --profile-ops on 4x R9700); at a
prefill, eleven passes of each a layer per 20K-token request.

norm_add_norm_route is norm_add_norm, then from the norm factor it already holds the router's row
by rmsnorm's expression, ((x * s) * w_r) * mult, and the experts' codes as rmsnorm_quant_fp8 writes
them: the bf16-rounded norm, a scale of amax * (1 / 448) a 128 columns (1 for an all-zero group),
the value times its reciprocal clamped to +-448, one v_cvt_pk_fp8_f32. Element i is thread i % 256
at slot i / 256, so a group is four waves at one slot -- a wave's max, then the four through LDS.
Its own name rather than optional operands on norm_add_norm: the codes need whole 128-column
groups, which the plain join does not, and the arch falls back cleanly where it does not resolve.
A device row and a host arm (one helper with norm_add_norm's), the schema, OPS.md.

arch/gemma4 asks for it on every layer whose gate_up is block fp8 -- the user's fp8gu container,
every layer -- and then issues neither op_rnorm nor op_enorm; it declares both still, and
norm_add_norm and the chain behind it, for where it does not resolve. The routed arm's two norm
gains are declared ahead of the attention join now, which names them. The overlap takes either
join. A startup note counts the layers that take it.

The same rounding as the chain, but for the order a sum of squares is added in, as every join here:
g4k_emu holds the kernel to a chain summed in its block order bit for bit -- x, y, the router's
row, every code and scale -- at the 26B-A4B's 2816 at four heights, at 128, 3072, 3200 and 6144,
and with an all-zero group; against the host arm, no code more than a step off. The emulator gains
v_cvt_pk_fp8_f32, through the project's saturating encoder. arch_test: with fp8 gate_up experts the
route op resolves on all six layers, a decode step issues it and no rmsnorm_quant_fp8 and one
rmsnorm fewer a layer; refused, norm_add_norm and both launches; a tp-4 prefill through the
overlap issues it a slice and keeps every reduction ordered.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 efff69be1d arch/gemma4: the drafter's residual add, norm and quantiser in one rmsnorm_quant_fp8 launch
Every input of a drafter layer was three launches after its all-reduce: `add` (x += h), `rmsnorm`
(x -> h) and `quant_act_fp8` (h -> hq | hs), ~8 us each under --profile-ops on 4x R9700 and a few
unprofiled, twice a layer -- thirty a draft pass, every decode step.

libr4d's `rmsnorm_quant_fp8` is that chain in one pass where it takes the residual operand (the
fused_add_rms_norm form): the norm of the bf16-rounded sum, the codes of the bf16-rounded norm,
which its row states is the chain's function. The drafter now issues it for both inputs of every
layer, the attention input of layer 0 with no residual -- x as the embedding left it -- and the
last layer's trailing add stays, ahead of the final norm, which no quantiser follows. Nineteen
launches fewer a draft pass. Where nothing serves the op the chain is declared and issued as
before. A draft is verified whatever it is, so this cannot change what is accepted.

arch_test: a draft pass issues ten rmsnorm_quant_fp8 and one add, the residual operand x and the
delta h past layer 0 and x alone at it; refused, the chain's ten adds and fifteen quantisers.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 34ee08ea5e arch/gemma4: a prefill chunk in two slices, the all-reduces on the second lane beside the compute
On gemma-4-26B-A4B at tp 4 on 4x R9700 the all-reduces were 47% of a 20K-token prefill under
--profile-ops (957 of 2020 ms): a layer reduces T x E after attention and both arms' 2T x E after
the feed-forward, at ~16.5 GB/s a rank on the link, against ~8 ms of compute a layer at the average
chunk. Run whole, the two take turns.

A chunk of two routed passes or more (4096 tokens) now runs as two slices, and every trunk
all-reduce rides the runtime's second lane (rad_lane) beside the other slice's compute: slice A's
attention reduction under slice B's output projection, slice B's under slice A's two arms, slice
A's feed-forward reduction under slice B's arms, and slice B's under the next layer's join and
projections of slice A. Attention runs whole -- it reads every row's keys. A model of the measured
times puts it at up to a quarter off an unprofiled prefill; --profile-ops syncs every op and cannot
show it.

The same bits as the whole step: the cut is a whole number of routed passes, so the routed arm
makes the passes the whole step makes, and both slices are at least one pass, above every row band
the sliced kernels have (the GEMM's 16 and 64, the reduction's one-shot edge) -- core's rule four
for the second lane. The slice's partials sit dense-then-routed in its own run of the join buffer,
so each slice's feed-forward reduction is one message.

The order: a reduction is issued on lane 1 behind a join from lane 0, its producer; lane 0 joins
lane 1 back before the consumer and before the next reduction is issued, since a join orders behind
everything its lane has issued. The embedding's reduction stays on lane 0, ahead of everything lane
1 is first joined behind, so the collectives keep one order on every rank. The two buffers reduced
in place are named to rad_buf_concurrent. Taken where the joins are fused, the wire is exact and
there is more than one rank; RADIANCE_GEMMA4_OVERLAP=0 runs every chunk whole, and the startup note
says which. A decode step never takes the lane.

routed() takes a run of rows and the join row its partial lands at; attention between the
projections and the output projection moves into attend(), which both paths issue.

arch_test records the lane of each issue and where each join sits, and a new test holds a 6-layer
26B-A4B with the DFlash taps, at tp 4: no two issues on different lanes that touch a common element
go unordered (taking every operand as read and written; dropping one wait makes it count six), lane
1 carries the trunk's 4 x 6 reductions at the slices' sizes and nothing else, the slices issue the
whole step's rows by op and its routed passes, a 4095-token chunk and a decode step stay on one
lane. GUIDE.md has the switch, ARCHITECTURES.md the paragraph.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 743b7e1a6a arch/gemma4: the DFlash head reads a block-fp8 copy of the table where the container holds one
The drafter's head was `gemm_nt` over the target's bf16 table -- 352 MiB a rank at tp 4, every draft
pass, 566 us of a 26B-A4B decode step under --profile-ops on 4x R9700: the widest read on the draft
path, and the "first thing to change once the model runs" its own comment named.

A container may now hold the table a second time as `dflash.draft_head.weight`, block fp8 -- one
checkpoint tensor, two logical weights, as rad_block_dflash2.h does it -- made by the recipe line

    dflash.draft_head.weight  rtn codes=fp8_e4m3 block=128x128 scale=bf16

which the three gemma4-26b-a4b -df recipes now carry. Where the copy is there, the head is
quant_act_fp8 over the gathered rows and gemm_nt_q over the copy at fp8a8: half the bytes, for 176
MiB a rank more. The copy is row-sharded exactly as the table, so a rank's rows are the same
vocabulary slice and row_topk's vocab_off, the all_gather and pair_argmax are unchanged. Drafts are
verified, so the coarser logits change what is proposed and never what is accepted --
draft_n_accepted says whether they propose worse; there is no rerank against the bf16 table yet.

Where the copy is not there -- every container converted before this, or one whose recipe made it
something other than block fp8 -- the head reads the bf16 table exactly as before. The decision is
the stored encoding's (weight_enc on the copy's name), and the copy's name map entry alone writes
nothing: rad-convert walks the declared weights. The startup note names the head in use. The
block-fp8 test moves to one helper, which the routed experts' encoding check now uses too.

arch_test: with the copy's encoding block fp8, the copy is declared and the head is gemm_nt_q over
it from the quantised rows; without, nothing is declared and the head is gemm_nt over the table;
a draft pass issues the head once either way. ARCHITECTURES.md says so.

Not yet run on the cards; it needs a container converted with the new recipe line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 73c3dc38be gemma4k, arch/gemma4: attn_paged_qrow -- q in the fused row only where gemma4k reads it
8772d5b handed the sliding layers' attn_paged q as a column slice of the fused [q|k|v] row. gemma4k
reads that; libr4d's paged attention reads q only dense and refuses the slice with RAD_E_STRIDE,
which stops the engine at the first step. Under attn_paged the first library in --kernels wins, so
the slice was only safe with gemma4k ahead of libr4d -- and the deploy script's default order
(libr4d,gemma4k,libavx) took the server down at layer 0's attention on both profile runs.

gemma4k now declares the same kernels a second time under attn_paged_qrow: attn_paged's schema
field for field, with q read at its own row pitch. Only gemma4k declares it, so it resolves there or
nowhere. The sliding layers ask for it once; where it resolves they read q in place (no lift), and
where it does not -- a hierarchy without gemma4k, or RADIANCE_GEMMA4_FUSE=0 -- q is lifted into a
dense block by a `cast` again and attn_paged reads that, which every attention library takes. The
lift's buffer is declared only then, since an unnamed buffer is live for the whole program. A miss
is the swa group's first op carrying a block_size, and answers rad_kv_block_size with the
RAD_KV_BLOCK it declares, as attn_paged would. No libref row, as the joins.

The kernel order still matters for speed -- gemma4k first is the order this model was measured with
(ARCHITECTURES.md) -- but no longer for whether the server runs. A startup note says which form
was taken.

arch_test: the slice reaches attn_paged_qrow and never attn_paged; refused, every sliding layer
lifts q for attn_paged; a decode step issues either form; and the three older gemma4 tests
count the sliding layers' attention under its new name. docs: OPS.md's row and paragraph (and a
line of the joins' text reflowed to the width, as one of gemma4.cpp's), ARCHITECTURES.md's kernel
paragraph, which now names expert_scale too, and GUIDE's FUSE row.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 e173365823 gemma4k: the sandwich joins issue every load first
A barrier is a fence, so a load written after a reduction waits for it. norm_add_norm fetched the
residual and both gains phase by phase, join_add_scale the residual, three or four gains and the
layer scalar, so each paid a global round trip per phase on top of its reductions: --profile-ops on
4x R9700 has them at 13.2 and 17.8 us a call at decode, 30 of each a step, where a launch that does
nothing costs ~7.

Now every operand of the row is in flight at once before the first reduction, the two arm norms
share one barrier pair (block_sum2: each value takes block_sum's butterfly and wave order), and a
thread holds 12 elements where the row fits -- n <= 3072, Gemma 4 26B's 2816 among them -- and
kMaxPer's 24 past that, instead of 24 always. The arithmetic is the same expressions in the same
order; a sum's terms past n were +0 and are gone.

g4k_emu: both joins at the edge between the two widths (3072, 3073), with and without the next
norm, bit for bit against the chain as every other case.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 76dd0019ac libr4d: logit_softcap spreads a row over blocks
One 256-thread block a row: at Gemma 4's tp 4 a row is a 65536-wide vocabulary shard and a step has
a decode's few rows, so a handful of blocks walked 256 elements a thread of tanhf each. --profile-ops
on 4x R9700: 82.7 us a decode step and 85.6 us for the prefill's single row, for 256 KiB of f32 a row
-- four times the drafter's row_topk over a row as wide (18.6 us).

Both legs now put a row on up to 64 blocks, eight elements a thread (32 blocks at 65536). Elementwise,
so no bit moves; libr4d's selftest and rad-kbench's libref comparison hold it as before.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 a378b41abb libr4d: the exact two-shot all-reduce takes every prefill-sized message
R4D_AR_TWOSHOT_WIDE_MAX_ELEMS was 20971520 -- a 4096-token chunk of a 5120-wide residual -- and the
band above it went back to the one-shot, which sends (ws-1)*N bytes a rank where the two-shot sends
2*(ws-1)/ws*N. At the default --max-num-batched-tokens 8192, Gemma 4 26B-A4B's attention reduce is
8192 x 2816 = 23M elements and its feed-forward reduce, which carries both branches for their own
post-norms, 46M: both over the bound, so every full prefill chunk went one-shot at twice the bytes.

--profile-ops on 4x R9700, tp 4, a 20489-token prefill (chunks of 8192, 8192, 4105) fits one link
rate across all of it: the attention reduces 16.8 ms the three calls (two one-shot, one two-shot)
and the feed-forward reduces ~37 ms (all one-shot), 1.6 s of the 2.7 s prefill. The same rate with
every call two-shot is ~9 and ~19 ms: about 0.8 s less a 20k prefill.

The bound guards the kernel's int word offsets and nothing else -- the scratch already holds a
full message per slot (r4d_ar_entry.hip build()), twice what the two-shot uses -- so it is now
2^28 elements, 2^26 words at fp32. The fold is the one-shot's, fp32 in ascending rank order, so
the band edge moves no bits. Fewer bands also means one scratch set less: the old 20971520 band
was its own instance, ~335 MiB a rank at tp 4.

plugin_test: a 16384-token chunk is two-shot to its end, and the one-shot still takes a message
past the bound. r4d_selftest's three-rank pattern walks a 46137344-element message, past the old
ceiling.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 0d95046f6f gemma4k, arch/gemma4: expert_scale -- per_expert_scale on the routing weights in one launch
Gemma 4 multiplies each renormalised routing weight by per_expert_scale of the expert it chose.
In the conventional vocabulary that is an `embed_lookup` of the [n_expert, 1] table by the ids
and a `mul` into the weights -- two launches a MoE layer, a few dozen elements each at decode
(--profile-ops: ~0.26 and ~0.22 ms a step across the 30 layers). gemma4k's `expert_scale` is the
pair as one kernel, ew = bf16(ew * w_e[id]), with an id outside the table reading 0 as
embed_lookup's missed row does: one product rounded once, so the pair's value bit for bit.

Like the joins it has no libref row on purpose, so arch/gemma4 falls back to the pair wherever
gemma4k is not loaded, and RADIANCE_GEMMA4_FUSE=0 turns it off with them. 30 launches a step the
fewer.

g4k_emu: device and host rows against the pair over 32 shapes -- top-k 1 and 8, pitched rows,
pads and one-past-the-end ids, rows past M untouched -- every element equal. arch_test: a decode
step scales in one launch, and in two with it refused. docs/OPS.md: the row and its paragraph;
GUIDE: what the switch now covers.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 29f981fd6c arch/gemma4: route a decode step in one launch -- libr4d's fused router, top-k and sort
At decode heights the router GEMM (128 x 2816), its top-k and the expert sort are each one small
workgroup's work behind a full dispatch: --profile-ops put the three at ~0.27, 0.29 and 0.24 ms a
step across the 30 MoE layers. libr4d already fuses them for the Qwen MoE blocks --
`router_topk_scatter` for the pair, `router_gemm_topk_scatter` with the GEMM in front -- and
documents both as byte-identical to the launches they replace, so the routing does not move.

arch/gemma4 now asks for them as rad_block_moe_fp8.h does: the pair up to the sort's
single-workgroup bound (1024 routing slots, 128 rows at top-8), the GEMM form up to the skinny
GEMM's decode band (64 rows), and the separate ops for a pass past either, declared regardless.
The per-expert scale and the experts' input norm sit between them in the issue order and read only
the ids and weights the fused op writes. Two launches a MoE layer the fewer at decode, 60 a step.

arch_test: a decode step routes with the fused op; refused, with the pair; both refused, with the
three separate ops -- and the per-expert scale and the gather run in every case.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 171dcee15b gemma4k, arch/gemma4: the feed-forward join writes the next layer's input norm
join_add_scale takes an optional gain `w_n` and output `y` (both or neither) and, given them,
writes y = rmsnorm(x) * w_n over the residual it has just stored -- the next layer's
input_layernorm, or the final norm after the last layer. Those norms read the x the join writes
and nothing else, so each was a launch of its own and a second read of the row; now it is a fourth
reduction in a block that already holds x in registers. On the 26B-A4B that is 30 launches a
forward pass the fewer (29 input norms and the final norm), at decode a step's worth of ~8 us
launches.

Rounding where the chain rounds: y is taken over the bf16 x the join stores, with libr4d's
expression, so g4k_emu holds it to the chain bit for bit (+next cases, decode to prefill heights,
odd widths and pitches) and to the host arm within a flipped rounding.

arch/gemma4 declares every layer's input-norm gain ahead of the layers so a join can name the
next one's; where a join resolves, the norm it replaces is neither declared nor issued, and where
it does not, the chain is as before. docs/OPS.md: the row and its paragraph. arch_test: fused,
the only x -> h rmsnorm is layer 0's and every join writes h; refused, all thirteen come back.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 3a48ee78de arch/gemma4: the sliding layers' attention reads q in the fused qkv row
The q lift -- a `cast` copying q out of the fused [q|k|v] projection into a dense block -- was
there because libr4d's paged attention reads q only dense. gemma4k's takes q at any row pitch
(its head_view, and g4k_emu's q-pitch-slice cases), and gemma4k serves all of Gemma 4's attention,
so the slice goes straight in: one launch and a [T, q] copy less on each of the 25 sliding layers,
every step. With libr4d ahead of gemma4k its attention refuses the slice by name (RAD_E_STRIDE)
rather than reading it wrong.

arch_test: no copy between projection and attention, and the attention reads `qkv_s`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 9967158d4a docs: gemma4 -- the architecture, its kernels, converting it, its two switches
ARCHITECTURES.md: a `gemma4` section in the file's form -- the 26B-A4B's geometry, the readings
that stay plausible when wrong (proportional rope is not a partial rotary, K is V, the router reads
the residual, per-arm post-norms, the bf16 embedding scale, the FULL sliding group, the drafter's
causality), tensor parallel, fp8 experts, which kernel library serves what, and what is not
declared. Its table gains the arch/gemma4 row, and the gemma4_bf16 row is corrected: that plugin
claims ("gemma4", "compressed-tensors"), not ("gemma4_bf16", "i4").

GUIDE.md: converting gemma-4-26B-A4B-it with its drafter, and RADIANCE_G4K_WMMA /
RADIANCE_GEMMA4_FUSE in the tooling table. IMPLEMENTATION.md: gemma4k/ in the layout.

KERNELS.md is rad-kbench's and is not edited here; it wants regenerating on a card with gemma4k
loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 753e9c598b data/recipes: gemma4-26b-a4b with DFlash -- fp8 gate_up, 768-padded fp8 experts, bf16 experts
The three containers arch/gemma4 has been served from, each with the usage header the in-tree
recipes carry:

- gemma4-26b-a4b-df: the routed experts' gate_up block fp8, their down bf16 (K = 704 is not
  whole 128-blocks), the drafter's linears block fp8. The measured container.
- gemma4-26b-a4b-df-pad768: both expert projections fp8, from a checkpoint whose experts were
  padded 704 -> 768 before conversion (zero rows of gate and up, zero columns of down: exact).
  The padding is described rather than shipped: the tool that did it is Python and stays out of
  the tree.
- gemma4-26b-a4b-df-bf16x: only the drafter quantised -- the bf16 reference for the KL mode.

The rules are the ones the containers were converted with; only the headers are new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 c2bd41fe95 arch/gemma4: Gemma 4 text with z-lab's DFlash drafter -- the 26B-A4B MoE and the dense sizes
Claims ("gemma4", ""): a container converted from Google's bf16 checkpoint, the recipe choosing
what is fp8. gemma4_bf16 keeps ("gemma4", "compressed-tensors"), the CT-INT4 dense release; the
two do not overlap. Serves gemma-4-26B-A4B-it (128 experts of 704, top 8) and the dense sizes
without per-layer embeddings, with a DFlash block-diffusion drafter merged at convert time.

The readings that stay plausible when wrong, each explained at its site:

- Proportional rope is not a partial rotary: the full layers rotate the first 64 frequency pairs
  of the 512-wide head at theta^(-2j/512), pair j = channels (j, j + 256), declared as full-width
  NeoX with the frequencies past pair 63 divided by 1e30 through the YaRN ramp `rope` carries.
- K is V on the full layers: V is the un-normed, un-rotated k projection, so its norm is issued
  before the key norm overwrites `k`.
- The router reads the residual through a gainless rmsnorm times its `scale` times hidden^-0.5,
  and per_expert_scale multiplies after the renormalised top-k.
- Two post-norms a layer's feed-forward, one an arm, each arm's partial reduced before its norm;
  both partials share one [2T, n_embd] buffer so one all-reduce carries them.
- The embedding scale is sqrt(hidden) rounded to bf16 (53.0, not 53.066).
- The sliding layers' KV group is RAD_KV_FULL with the window on the attention op: a WINDOW
  group is not prefix-cached, and on this tree a hit on one re-prefills; FULL keeps the hit.
- fp8 experts are two tables by parity, so a rank holds an even count; down at K = 704 cannot be
  fp8 (whole 128-blocks), hence the 768-padded recipe.
- The sharded draft head's merge is pair_argmax at R = 2 on the wire.
- The drafter's tap copy is declared at the end of the layer it taps, where it is issued. The
  buffer planner takes liveness from declaration order; declared once after the trunk, it let the
  plan share `dflash_src` with `moe_edn`, which every MoE layer writes, whenever the sizes
  allowed. At --max-num-seqs 16 they did, and on the cards DFlash accepted 2% of its drafts
  (97 tok/s against 135 with speculation off and 186 with the taps intact), the text fluent
  throughout.

The sandwich joins are asked for as norm_add_norm / join_add_scale (gemma4k) and declared as the
rmsnorm / add chain where nothing serves them; RADIANCE_GEMMA4_FUSE=0 asks for the chain. The
reply format is the shared one (arch/rad_gemma4_chat.h), so tool calls are parsed in the engine;
the plugin as measured declared reasoning only and left calls to an out-of-tree sidecar, so the
call path is untested on this plugin's containers.

arch_test: the MoE trunk declares both arms and six of each join; both KV groups FULL with the
window on the op; the full layers' rope over the whole head with the ramp at 63.5..64; with the
joins refused, the chain is declared and issued instead; both Gemma 4 plugins export one format;
with a DFlash drafter, `dflash_src` is live from the first tap layer (its range overlaps
`moe_edn`'s, so no plan can share them) and a step writes each tap once.

Measured on 4x R9700 at TP4 (gemma-4-26B-A4B-it + DFlash, gate_up experts block fp8), with
gemma4k and --draft-window adaptive: a story at T 1 177 tok/s, greedy thinking 572 tok/s, code at
T 0 319-334 tok/s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 368d0363eb arch: Gemma 4's reply format into arch/common, for both Gemma 4 plugins
Two plugins are about to serve Gemma 4 -- gemma4_bf16 the CT-INT4 dense release and arch/gemma4
the bf16 / fp8-expert containers -- and the reply format is the model's, not the weights': the
thought channel, and calls written as a name and one object in Gemma's dialect of JSON. One
declaration in the shared header library (installed as <arch/rad_gemma4_chat.h>), so the two
cannot drift apart and the reply-format tests read what both export.

The declaration moves unchanged, from gemma4_bf16::chat_format_decl() to
rad::arch::gemma4_chat_format(); chatparse_gemma4_test follows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 846e52148a tests: g4k_emu -- gemma4k's kernel source on the host, every GPU thread a fiber
gemma4k builds for gfx12 only and its two joins have no libref oracle, so nothing on a machine
without the card, and nothing in rad-kbench, would ever run its kernels. g4k_emu compiles the
.hip sources as host C++ against a HIP shim: every GPU thread a fiber, __syncthreads and every
cross-lane op a barrier (one not reached uniformly is reported as a deadlock), the WMMA operand
layouts gfx12's. Checked against a port of libref's ref_attn_paged (attention, fixed cases and a
random sweep over every compiled geometry), against the host rows (pair_argmax), and against the
unfused chain bit for bit (the joins).

Registered in CTest under the label g4k_emu, on x86-64 with a clang: the kernels use
ext_vector_type and the fiber switch is SysV inline assembly. Under a clang C++ compiler they are
ordinary targets. The docker image compiles host C++ with g++, so there g4k_emu/run.sh builds the
same tests with the HIP compiler, ROCm's own clang++, and runs them as one test -- so wherever
gemma4k is built, this runs, the image's host-test stage included. About 40 s at the default
40-case sweep (50 s through run.sh, which compiles too); `g4k_emu_attn sweep 200` is the long run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 833173cc04 gemma4k: Gemma 4's kernels beyond libr4d -- paged attention, pair_argmax, the sandwich joins
A kernel library beside libr4d, gfx12 only, and AHEAD of it for Gemma 4:
`--kernels gemma4k,libr4d,...`. Its own library rather than rows in libr4d: a smaller change,
its own gfx12 gating, and no churn in libr4d's row table; folding it in can follow.

- attn_paged at head_dim 256 and 512, gqa 1/2/4/8, bf16 or fp8 cache, any window, causal or not.
  One scalar kernel serves decode, verify and prefill, with a split-KV path whose merge is one
  wave a row (live pieces found by ballot, four at a time; a piece that saw no key writes only
  its max and sum); a WMMA prefill kernel takes a query of at least 64 rows and 32 a sequence on
  average -- Q and K bf16, P and V f16 (bf16 P measured 0.25% of the V range in error), the
  denominator summed from the rounded P. RADIANCE_G4K_WMMA=0 keeps every launch on the scalar
  kernel.
- pair_argmax, device and host, described as libref describes it so rad-kbench checks both.
- norm_add_norm and join_add_scale, ops of its own (docs/OPS.md, a new subsection): each one
  kernel for a post-norm / residual add / pre-norm chain, rounding where the chain rounds. libref
  has no row for them on purpose -- a reference row would resolve them where gemma4k is not
  loaded and the architecture would never fall back to the chain -- and no row declares
  `replaces`, since rad-kbench assembles a replaced chain from the fusing library's own rows.

WHY FIRST. libr4d on this tree also has rows at h256/gqa2 and h512/gqa8, Gemma 4's own
geometries, written for the dense 31B (which has no drafter) and not measured on the 26B-A4B or
under a DFlash verify; the hierarchy is absolute, so the first library takes them. These rows are
the ones every Gemma 4 number below was measured with. No other row overlaps libr4d's (the h256
gqa4/gqa8 rows take a window only), so putting this library first takes nothing else from it. The
softcap is libr4d's and libavx's `logit_softcap`.

Measured on 4x R9700, gemma-4-26B-A4B-it + z-lab DFlash, TP4: decode attention 3.234 -> 0.104 ms
a step on the full layers and 1.906 -> 0.722 on the sliding ones (the split-KV merge); a
20,489-token prefill 4.01 -> 2.83 s (the WMMA kernel); rad-kbench against libref 176/176. Not yet
run on the cards: the joins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 d0f6f332ff ops: pair_argmax in libref and libavx -- the sharded draft head's top-1, one id a row
A vocab-sharded draft head proposes each position's argmax: every rank takes its slice's top-R
as (id, value) pairs, an all_gather puts them side by side, and something picks the winner.
row_topk_merge does that with an R-wide answer; a block drafter wants ONE id a row, written
contiguously into the token buffer it verifies, and a rank cannot send R = 1 -- a
row-interleaved all_gather moves whole 16-byte words and a pair is 8 bytes. pair_argmax is the
merge at R = 1 over world_size * R pairs: largest value, ties to the lower id, a negative id a
pad, -1 and -inf for a row with nothing valid, `val` optional.

The Gemma 4 DFlash head is its caller (arch/gemma4, later in this series) and gemma4k its device
kernel. libref is the oracle and the schema's first declarer; libavx carries the host row,
because an op the placement puts on the host cannot run on a reference (avx_check holds libavx
to libref's vocabulary). Both scalar: n is sixteen pairs at TP8.

docs/OPS.md: the row and a paragraph beside row_topk_merge's. ref_test: ties to the lower id in
any slot, a pad carrying the row's largest value dropped, an all-pad row, all-negative values,
`idx` at a pitch of two with the slots between untouched, and `val` absent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 29bfe8f00c sched: --draft-window adaptive applies to block drafters
The adaptive window priced only a serial head's rounds and was refused for a
block drafter, on the grounds that the block is proposed in one pass. But
every verified draft is still a verify row, and on a MoE whose verify reads
the experts each row routes to, rows are not free (16 rows read ~10x the
experts one does). A block drafter now takes the same policy with its rounds
fixed: each sequence verifies the first min(D, its stop) of the block, its
stop from its own measured acceptance and D from the measured step times.
Prompt lookup alone keeps the fixed window and says so.

Speculation stays lossless: what is verified is a prefix of the proposal.

Measured on gemma-4-26B-A4B-it + z-lab DFlash (block 15), 4x R9700, TP4,
together with gemma4k's split-KV merge rewrite (landed in the same build, so
the two are not separated): story at T=1 95 -> 177 tok/s, greedy thinking
~360 -> 572 tok/s; code at T=0 319-334 tok/s (it verifies deep either way).

tests/sched_test.cpp: the block-drafter case now expects the policy on
(4 drafts verified while the estimate is the prior, 1 after 64 rejected
steps, draft_verify_depth[4] and [1] both counted); the prompt-lookup-only
and no-speculation cases are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 fb716830c2 oai: preserved_tokens on /v1/completions; find a text-tailed reasoning opener by its token
/v1/completions accepts llama-server's preserved_tokens: control tokens the
completion's text keeps rather than drops. A client that renders its own
template and parses its own reply (a tool-call sidecar) has no other way to
see a reply format built of control tokens. Bounded like the stop strings.

A thinking budget needs the reasoning block found by token. Gemma 4's opener
<|channel>thought is one control token followed by text; it is now found by
that first token (what a reply opening its own block writes first, and no
text can spell), with the text after it counted as reasoning. An opener with
a second control token in it is still refused, since its first token may open
something other than the reasoning. The refusal message says why.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 2381591823 tokenizer: end a Gemma 4 generation on <turn|> and <|tool_response>
Gemma 4 declares <eos> as its eos but ends a turn on <turn|>, and a
tool-calling turn on <|tool_response> (the opener of the result the caller
supplies, written after the model's last <tool_call|>). Neither was in
kEogNames, so every Gemma 4 reply ran to max_tokens. llama.cpp's loader
lists both for this vocabulary.

A vocabulary that has <|tool_response> as a control token also has </s> as
ordinary text (llama.cpp concludes the same); ending on it would cut a reply
that writes the HTML tag, so </s> is not an end-of-generation token there.

This branch already ends a generation on every id generation_config.json
names (c65fabe), which covers both tokens for a container that carries
`generation.eos_token_id`. The spellings here cover one that does not, and
the </s> rule is new either way: the eos list never names </s> for Gemma 4,
but kEogNames did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
AshlynandClaude Opus 5.5 c37f47cc78 libref, libavx: logit_softcap calls std::tanh on a float, not std::tanhf
std::tanhf is in <cmath> only from libstdc++ 14; against 13 (Ubuntu 24.04's) the host build stops
at libref and all four libavx levels. std::tanh's float overload is tanhf, so the arithmetic is
the same to the bit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:40:04 -05:00
Deadcode f6a9467cb5 Merge ParoQuant: PRs #65, #66 and #67 (malic), with fixes
Rotated Qwen3.8-27B checkpoints: ParoQuant MXFP4, int5 bit-plane and z-lab's int4 import (the givens
transform with parts, per-row scales, zero points), the w5a16/w4a16_asym decode GEMMs, the
w4a8i8/w5a8i8 prefill band, the givens_rotate kernel, and the dense per-group rotation
(givens_dense_quant: one 128x128 f16 matrix a part and group on the matrix cores) for the quantising
rotation in prefill. gemm_nt_q gains part bounds (pb1/pb2), an op-schema change an out-of-tree
kernel library has to follow.

Fixes on top: the dense matrices are a container table ("t.dense") that rad-convert composes in f64
from the pairs and angles, and the loader only moves its bits. A container converted before this is
refused at load, naming the re-convert (--reuse copies every unchanged weight). A gemm_nt_q row that
does not read part bounds refuses them instead of ignoring them. libavx implements givens_rotate and
givens_dense_quant.
2026-10-12 20:46:37 +02:00
Deadcode d10b64f9e5 gemma4 compose: prefill in 2048-token chunks
The 8192-token default makes a long prompt's step take about 5 s on Gemma 4 31B, holding every
running decode for that long. At TP2 on two R9700s, a 26K-token prefill: 1475-1477 tok/s at 2048
against 1456-1463 at 8192; decode step time equal at c1 and c4.
2026-10-12 20:46:37 +02:00
Deadcode 7c7f755931 Merge Gemma 4 31B: PRs #74, #75, #81 and #86 (sfjes, keptn42), with fixes
The gemma4_bf16 architecture (sliding and global attention, the proportional RoPE ladder, the
assistant head as a drafter that reads the trunk's cache, the vision tower), its w4a8 decode
junctions, the h512/gqa8 and h256/gqa2 attention kernels, compressed-tensors int4 import, multi-EOS
from generation_config, the call/reasoning reply format, a window group that keeps the keys a
prefill chunk still reads, and window snapshots in checkpoint slots so a prefix hit on a
sliding-window trunk resumes.

Fixes on top: the investigation switches and diagnostic blocks out of the served paths; int4 import
through the checkpoint import framework; attention_k_eq_v from the config; the fused junctions only
where every reader takes their pair; a shared-KV head binds no group of its own; the compose file
without HSA_ENABLE_IPC_MODE_LEGACY (TP2 fails with it on ROCm 10.1); a checkpoint carries a window
only where a hit resumes from it; the README says the linked container is keptn42's calibrated GPTQ
build and what the in-tree recipe gives.
2026-10-12 20:46:37 +02:00
Deadcode dc339b4cd2 radiance 1.4.0
- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and
  the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at
  decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against
  1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20%
- deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM
  (4096-token prefill steps, 4 sequences, a 301K-token cache)
- #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the
  requests decoding beside it and to new arrivals, instead of taking all of it (baKon)
- LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50)
- a startup report: every option with its value and where it came from, the hardware, and what
  on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only
  to the same machine)
- #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at
  once (exit status 70), instead of hanging or writing a core of tens of gigabytes
- #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of
  crashing at the first launch
- the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's
  libLLVM rebuilt so the same source compiles to the same kernels every time; a source build
  takes ROCm 10.1 or 7.2
- #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container,
  and hfget.sh runs under its busybox (baKon)
- --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an
  integrated GPU instead of stopping
2026-10-12 11:46:14 +02:00
keptn42 9a2747eaef checkpoint slots: startup and help name the window snapshots too 2026-10-12 09:05:31 +00:00
keptn42 e35052abfe sched: a prefix hit on a sliding-window model resumes from a snapshot of the window behind it
The prefix cache cannot index a windowed group, so every hit on a windowed
trunk re-prefilled the whole prompt (73620ef). Gemma 4 31B (50 of 60 layers
windowed at 1024) paid that on every chat and agent turn: 17-48 s to the
first token at 25-49k tokens.

A model with a window and no linear state now takes one checkpoint per
prompt, a block short of its end -- the next turn re-renders the last few
tokens -- if the prompt is --checkpoint-interval tokens or longer, and does
not split chunks at the interval. The prefix cache treats the window like
linear state: a hit is reusable at a checkpoint only. admit_one adopts the
full-attention blocks as before, seeds the windowed groups at the window's
floor, and the entry's restore fills them from the slot; anything else
re-prefills as before. A model with both linear state and a window keeps
refusing the hit.

Measured on Gemma 4 31B, TP 2, agent transcripts: a follow-up turn's first
token in 0.8-3.4 s instead of 17-48 s; greedy output byte-identical to a
cold prefill with the same chunk boundaries (32 turns, chains five hits
deep, thinking on and off).
2026-10-12 09:04:43 +00:00
keptn42 93389679e8 kv: a checkpoint slot carries the window behind it
A WINDOW group keeps only the blocks its window can still read, so no block
list from the prefix cache describes it. A checkpoint slot now carries, after
the linear state, window_blocks pages a WINDOW group (every layer, layer-major
rows): the window a query at the checkpoint reads, blocks
[max(0, P/B - (window_blocks - 1)), P/B) -- the floor recycle_window keeps.

window_rows() names those pages from the leader's table, padded per group, so
every rank copies its own shard with one vector (followers keep no sequence
tables); it answers false when the table no longer holds them. seed_window()
gives a sequence with an empty window table fresh blocks at that floor for a
restore to fill. checkpoint_save/restore take the rows; a model with no window
passes none.
2026-10-12 09:04:43 +00:00
keptn42 45109ebb45 Merge branch 'main' into gemma4-mtp 2026-10-12 02:38:12 +02:00
keptn42 ab4ae529f8 chat: a string the model leaves open ends at the call's close
Gemma 4 sometimes skips the <|"|> that closes a string and writes the
object's `}` and <tool_call|> straight after the text (measured on the
31B: the close delimiter at p=0.86, `}` at p=0.08). The object reader
only ended a dialect string at its own close, so the call's close, a
repeated close, an empty thought channel and the next call's opening
were read into the value -- up to the next call's <|"|>, which then
"closed" it.

Inside a string, the call's close now ends the string and the call when
the closers just before it close every open bracket of the object, as
vLLM's and HF's Gemma 4 parsers end a call at the first `}<tool_call|>`.
Those closers are the object's and leave the value, a repeated close
goes with them, and a quote or backtick just before them that leaves the
string with an odd count of its kind was the string's close in the wrong
spelling (seen with thinking on). The call's close inside a string that
does not close the object is text, as before.

A value opened with a plain `"` or `'` in a dialect with strings of its
own is read the way the model writes it there (measured: `'...'` for
nested arguments, `"..."` verbatim, or with only `\"` escaped): verbatim
but for an escaped quote, never with JSON's other escapes -- `\n` stays
the two characters, as in the JS source it came from. It ends at a quote
the object's syntax goes on after (a member, an element, the closers and
the call's close), or at <|"|>. Single-quoted values were read as bare
words before.

The object grammar admits such a value too. Refused, the model took the
next token the grammar allowed, a `-`, and every single-quoted string
came out as a number (-1, -2, ... at temperature 0).

Held bytes stay bounded (a 16-byte run, 32 bytes of lookahead).
2026-10-12 00:16:28 +00:00
keptn42 05033f3911 readme: the Gemma 4 31B container and its compose file
gemma4-31b-w4a8.rad on Hugging Face (keptn/gemma4-31b-w4a8): the bf16 checkpoint's trunk as GPTQ
int4 with int8 activations, the assistant head as MTP drafter, the vision tower. The compose file
carries the flags the model card's numbers were measured with.
2026-10-11 15:18:41 +00:00
keptn42 0895588b76 gemma4: the vision tower -- images and video through Gemma 4's own encoder
The 31B's tower (27 layers of 1152, 72-wide heads, a 2-D rotary over two 18-pair
neox blocks, 3x3 pooling, per-channel standardisation) declared beside the text
model when the container carries it and the deployment serves media; its rows
replace the placeholder embeddings after the lookup. qk_norm_rope's blocks mode
now runs at any head_dim and section size (a lane a pair outside the register
layout).
2026-10-11 02:51:18 +00:00
keptn42 191972eb75 gemma4: the w4a8 decode step through the fused norm/quant ops
Between two w4a8 blocks the stream ran five single-row dispatches
(post-norm, add, layer scalar, norm, quantiser), q, k and v quantised the
same norm output three times, the attention prologue was five more ops
and down's input two. Now every junction is one rmsnorm_quant_i8 (at two
ranks on the exact wire ar_rmsnorm_quant_i8, with the all-reduce in it),
q, k and v read one int8 pair, the prologue is qkv_norm_rope and down's
input gelu_mul_quant_i8. The trunk pass at k=3 goes from 1786 to 840
dispatches.

Byte-identical to the unfused step: greedy output equal at k=0 and k=3.
A kernel set without an op keeps that op's chain; RADIANCE_G4_FUSE=0
keeps every chain, for an A/B against the same build. arch_test checks
the issued op sequence fused, at two ranks, and with the ops refused.
2026-10-11 02:24:21 +00:00
keptn42 bdb50b2a9c gemma4: the trunk's lm_head is declared at its codes' dtype, like the assistant head's
bf16 as the checkpoint ships it; int8 or block fp8 where a recipe quantises
output.weight, served by the logits_gemm row for that encoding.
2026-10-11 02:23:48 +00:00
keptn42 e366777a0f gemma4: a bf16 checkpoint's plain weight names, and an int8 linear on the w4 grid
The plugin mapped only the CT-INT4 release's X.weight_packed. A bf16
checkpoint (Google's gemma-4-31B-it, every finetune of it) stores
X.weight; the name is now chosen from the checkpoint's own
quantization_config. A linear a recipe keeps at int8 on the same
128-column grid is served by gemm_nt_q at w8a8 with the activation
quantiser the w4a8 path already declares.

Recipe gemma4-31b-dense-bf16-w4a8 added: the CT recipe's grid and size
(int4, f16 scale a 128 columns) with the least-squares scale search. The
assistant head was trained against the bf16 trunk: served from this
container it accepts 0.71/0.62/0.63 of its k=3 drafts on prose, against
0.49/0.50/0.44 from the QAT container, at the same step time.
2026-10-11 02:23:48 +00:00
keptn42 d49d664381 libr4d: ar_rmsnorm_quant_i8 -- the two-rank exact all-reduce in front of rmsnorm_quant_i8
At two ranks the residual junction follows the row-parallel GEMM's
all-reduce. ar_rmsnorm_quant_i8 is that all-reduce (exact wire, the
ar_rmsnorm_quant_fp8 handshake) and rmsnorm_quant_i8 in one kernel, x
INOUT because it is the message. A deployment on the lossy wire keeps the
standalone all-reduce. Needs a peer rank, so the selftest skips it like
ar_rmsnorm_quant_fp8; byte identity is checked through a model run.
2026-10-11 02:23:39 +00:00
keptn42 0a4cf9b893 libr4d: gelu_mul_quant_i8 -- gelu(gate)*up and the w4a8 activation quantiser in one pass
The down projection of a GELU-gated feed-forward on a w4a8 grid is fed by
gelu_mul then quant_act_i8, two single-row dispatches at a decode batch.
gelu_mul_quant_i8 is the pair in one pass, byte-identical to it: the
product formed as gelu_mul_kernel forms it (tanh form, bf16 store), then
quant_act_i8's partition. The selftest compares it against the pair at
M 1/4/40.
2026-10-11 02:23:39 +00:00
keptn42 d90d90e43a libr4d: qkv_norm_rope -- q/k/v norms and both rotaries of separate projections in one dispatch
An attention block with separate q, k and v projections and per-head
norms (Gemma 4) runs five single-pass ops between the projections and the
cache store: rmsnorm_p on v (or on the raw k where v is k), rmsnorm over
the q heads, rmsnorm over the k heads, rope on q, rope on k.
qkv_norm_rope does them in one dispatch, one workgroup a (token, head).

Byte-identical to the five: the same norm widths r4d_act_threads picks
and rope's ladders, head included. The row is constrained to head_dim
256..512 in steps of 256; other shapes keep the five. The selftest
compares both of Gemma 4 31B's attention classes at M 1/4/40.
2026-10-11 02:23:39 +00:00
keptn42 dd6a7071a8 libr4d: rmsnorm_quant_i8 -- rmsnorm and the w4a8 activation quantiser in one pass
A w4a8 linear is fed by rmsnorm then quant_act_i8, two single-row
dispatches at a decode batch; in a sandwich-norm model (Gemma 2/3/4) the
residual junction in front adds a post-norm, the add and a layer scalar,
five dispatches at every junction. rmsnorm_quant_i8 is that chain in one
pass over the row, with the junction optional (w_post, scalar and the
residual operand).

Byte-identical to the chain it replaces: the same row partition
(r4d_act_threads) and a bf16 rounding wherever the chain stores. The
selftest compares it against the chain at three forms x M 1/8/40.
2026-10-11 02:23:39 +00:00
keptn42 8bde9f9c16 gemma4: the assistant head as a serial drafter that reads the trunk's cache
Google's Gemma 4 assistant (Gemma4AssistantForCausalLM), merged under
`draft.` by `rad-convert --draft-model`, declared when the container carries
it and the deployment speculates (max_spec > 0):

  x  = pre_projection(concat(E_trunk[tok] * sqrt(n_trunk), h_trunk))
  x  = 4 layers (3 sliding, 1 full): q-only attention over the TRUNK's cache,
       o_proj, plain-gain sandwich norms, GELU ffn, per-layer scalar
  hd = norm(x); logits = the head's own tied table (no soft-cap)
  h' = post_projection(hd), the next round's hidden state

h_trunk is the trunk's final-normed hidden state. Each head layer reads the
last trunk layer of its class (58 sliding, 59 full on the 31B), as vLLM wires
it. The head keeps no cache, so it is declared with rad_drafter_shared_kv:
one row a drafting sequence, every round at the committed position.

TP: q heads row-sharded with the trunk's kv heads; o_proj and down are
column-sharded and all-reduced before their post-norm; projections and norms
replicated; the lm_head vocab-sharded through the ordinary sampler chain.

Declare refuses a head whose kv geometry, window, rotary or vocabulary differs
from the trunk's, and use_ordered_embeddings (centroid masking). The probe
answers draft depth 3 for `--num-speculative-tokens auto`.

arch_test: no head without one or at max_spec 0; shapes, name maps, the
drafter declaration; the issue order of a history pass and a round; the
attention reading trunk layers 10/11 of the 12-layer fixture; TP2 reduces
before each post-norm; a history pass of the wrong shape is refused.
2026-10-10 19:15:05 +00:00
keptn42 997e1ae05f drafter: a serial head that keeps no cache of its own
rad_drafter_shared_kv(b, pos_offset), an additive builder export: the
declared SERIAL head reads the trunk's K and V and writes none (Gemma 4's
assistant head has a query projection and nothing else per layer). A
plugin that does not call it drafts exactly as before; RAD_ABI_VERSION is
untouched (same pattern as rad_kv_group_zero).

For such a head the serial driver changes in two places:

- No history is owed. The history pass carries round 1 only: one row a
  drafting sequence, at the committed position, with the token the trunk
  chose after it and the trunk's hidden state there. A sequence that does
  not draft gets no row; a step with nothing to draft runs no pass.
- Every round runs at that same position, over the same context. seqused
  ends at the committed position: past it, the trunk's cache holds the K
  and V of drafts the verify rejected, or nothing.

`pos_offset` (0 or 1) is where the rows sit for the rotary, relative to the
committed position; it moves nothing else.

Card side: ADV_HIST and ADV_ROUND take the shape from AdvanceArgs::shared_kv
and rot_shift, which the scheduler fills from the Program. Host side:
serial_begin/serial_batch stage one row and a constant ceiling.

Tests: build_test checks the export's refusals; sched_test stages one verify
step both ways (the old path pinned: five history rows, rounds stepping),
checks that a cacheless head runs no pass when nothing drafts, and runs the
card's advance rows directly for both shapes.
2026-10-10 16:29:34 +00:00
keptn42 d59e0bb003 gemma4: declare the reply format -- the thought channel and calls as one object
Gemma 4's template is one llama.cpp reads with a hand-written handler, so the template analysis
found no format in it: the server warned "this model's reply format cannot be described",
returned the thought channel as content and refused every request with tools (HTTP 400).

The plugin now states the format its tokenizer_config.json declares (`response_template`), in
gemma4_chat_format.h, exported through RAD_ARCH_CHAT_FORMAT:

  thinking    <|channel>thought\n ... <channel|>, reasoning_anywhere
  calls       <|tool_call>call:NAME{...}<tool_call|>, repeated, triggers on <|tool_call>
  the object  bare keys, strings between <|"|> and <|"|>, other values as JSON writes them

The template closes an empty channel in the generation prompt when thinking is off and opens one
after a tool response when it is on; RAD_CHAT_THINK_FROM_PROMPT reads both. llama.cpp's handler
records an extra thought channel after the answer and a lone <channel|>; reasoning_anywhere reads
the first as reasoning and drops the second, so neither reaches the content.

chatparse_gemma4_test, against the model's own template (tests/data/chat/gemma4) and llama.cpp's
Gemma 4 parser as the oracle (tests/legacy, which now takes a declared format): every reply the
template renders reads back as the message it rendered, byte for byte as llama.cpp reads it; the
shapes the model writes and the ways it leaves the format; thinking on, off, and after a tool
response; reasoning_format none; a conversation with role:tool results rendered into the open
turn and continued; every truncation, fuzzed replies and a 200 KB string under the streaming
contract; the call grammar against llama.cpp's on rendered calls, tool_choice required and a
response format; and the chat bridge serving it, with the decoder rendering <|"|>.
arch_test holds the export to the header.

End to end on the 31B QAT checkpoint, two R9700 at TP 2: 60 requests over greedy and
temperature 1.0 / top_k 64 / top_p 0.95, streaming and not, thinking on and off. Every request
with tools came back with finish_reason "tool_calls" and JSON arguments -- one call, two parallel
calls, integer and boolean arguments -- every follow-up with role:tool results as an answer with
finish_reason "stop", and no <|channel>, <channel|>, <|tool_call> or <|"|> reached any content or
reasoning_content. With thinking off the model writes <|channel>thought\n<channel|> itself
before its answer to a tool result; it is read as an empty thought.
2026-10-10 08:08:44 -07:00
keptn42 2c9ffc2888 vocab: every id the checkpoint's generation_config names as eos ends a generation
A checkpoint states the tokens a generation ends on in generation_config.json (eos_token_id, one
id or a list), and rad-convert already carries it into the container as
`generation.eos_token_id`. The vocabulary did not read it: it ended on eos, eot and a list of
known spellings. Gemma 4 names three, [1, 106, 50] -- <eos>, <turn|> and <|tool_response> -- and
the container's eos is only the first.

- <turn|> closes every turn. Without it a reply runs past its own end: a three-sentence answer
  stopped at max_tokens 400 after ~390 tokens of "---" lines instead of finish_reason "stop" at
  65 tokens.
- <|tool_response> is what the model writes after its calls, where it waits for the result.
  Greedy on the 31B QAT checkpoint (TP 2): after a finished call the next token is 50 with and
  without this change; without it generation goes on and writes the same call again until the
  token limit, with it the reply ends there (stop_type "eos", one token).

The engine reads `generation.eos_token_id` from the metadata before loading the vocabulary
(VocabBuild::eos_ids, not baked) and Vocab::load ends a generation on every id in range, logged
beside the spellings it adds.

text_test: ids in the list end a generation, an id naming no token is no id.
2026-10-10 08:08:44 -07:00
keptn42 dbd4e164b3 chat: a call written as its name and one object; reasoning that opens again later
The reply format described one call syntax, the tagged one: each argument in its own tags,
typed by the tool's schema. A call written as its name followed by ONE object holding the
arguments could not be described -- Gemma 4's `<|tool_call>call:NAME{key:<|"|>text<|"|>}<tool_call|>`
is one, and its tool requests were refused; JSON behind a name tag (`[TOOL_CALLS]NAME[ARGS]{...}`)
or inside a function tag is the same shape.

RadChatFormat grows at its end (no ABI bump; an older plugin reads the new fields as zero):

- args_form RAD_CHAT_ARGS_OBJECT: the arguments are one object after the name. name_suffix may
  be empty, and the name then ends at the object's `{`; call_end may be empty, and the object's
  own `}` ends the call. The arg_* fields are unused and must be empty.
- object_string_open / object_string_close: a string delimiter of the object's dialect besides
  JSON's `"`, between which the text is verbatim (Gemma 4: <|"|> twice).
- object_bare_keys: the dialect writes keys bare, `key:value`.
- reasoning_anywhere: a reasoning block may open again later in the reply (after the answer,
  between calls) and is read as reasoning there too; a close with no block open is dropped.

The streaming parser reads the object as it arrives and writes it as JSON as it reads: brackets
and separators as they come, a key once its `:` shows it is one, a string's bytes as they arrive
(the dialect's verbatim, JSON's with its escapes checked: an unknown escape is text, a lone
surrogate is U+FFFD), and a bare value as the tagged family writes a typed one -- held while it
could be a number or literal, else a string. Trailing and missing separators, a bracket of the
wrong kind, a key without value and an object cut off by the call's close are repaired locally
and reported as leaving the grammar; a closed call's arguments are JSON whatever was written.
The streaming contract holds: deltas are never revised, holds stay bounded.

The lazy grammar writes the object in its dialect (strings between the delimiters, bare keys,
JSON numbers and literals) and leaves the values to the model, as llama.cpp's own Gemma 4
grammar does: the schema converter speaks JSON, and the dialect is not JSON.

chat_format_check refuses what the parser could not read unambiguously, by name: tagged fields in
an object format, a dialect string opener that begins like a bare word, a call close that holds
object punctuation or cannot be told apart from the string opener, a reasoning marker that
overlaps a call opener in content.

chatparse_test: JSON behind a name tag and behind a function tag (strict, lenient, streamed every
way, grammar admits and refuses), reasoning_anywhere on and off, and the refusals.
2026-10-10 08:08:44 -07:00
keptn42 b9229091a9 gemma4: all-reduce before the post-norm
o_proj and down_proj are column-sharded, so under TP each rank holds a partial sum of the
projection. The post-attention and post-feedforward norms ran on those partials and the
all-reduce summed the normed halves: sum_r rmsnorm(p_r) instead of rmsnorm(sum_r p_r). HF and
vLLM (RowParallelLinear) reduce first. At TP 1 there is no all-reduce and nothing changes.
2026-10-10 08:08:43 -07:00
keptn42 cb5e812ccc attn prefill: a windowed CTA starts its KV walk at its own first row's window
The windowed prefill took the walk's first tile from the chunk's row 0, so every CTA of a long
chunk walked from the chunk's window start to its own causal limit. Tiles below the window of a
CTA's first row are masked for every row it holds, so starting there changes no value.
2026-10-10 08:08:43 -07:00
keptn42 c045ff85e9 rope: the head ladder rotates the whole head, as HF's proportional RoPE
ladder=head kept the rotary_dim-wide pairing: pair i = (i, i + rotary_dim/2). HF's proportional
RoPE (and vLLM's Gemma4RotaryEmbedding) rotates the whole head: inv_freq has head_dim/2 entries,
the first rotary_dim/2 of them 1 / theta^(2i/head_dim) and the rest zero, so pair i is
(i, i + head_dim/2). On Gemma 4's global layers (128 of 512) the old pairing turned channels
64..127 and left 256..319 alone.

rope in libr4d, libref and libavx now rotates the whole head under ladder=head, with the
frequencies past rotary_dim/2 at zero. The rotary ladder is unchanged. op_rope_ladder and the
r4d_selftest mirror check the HF pairing.
2026-10-10 08:08:43 -07:00
keptn42 921b02b60b kv: a window group keeps the keys a prefill chunk still reads
ensure() recycled a RAD_KV_WINDOW group against the end of the step, so a
prefill chunk lost the keys its first rows read (a 2185-token prompt kept
no window KV for positions 0..1151). Recycle below the step's first query
(keep_from = n_computed), size the caps for one extra chunk, and trim the
window when a prefill chunk is committed. The old test pinned the bug.

Found while debugging #75 (Gemma 4).
2026-10-10 08:08:43 -07:00
sfjes 77c266ce8f docs: catalog the gemma4 arch and its eight attention kernels
ARCHITECTURES.md gains the gemma4_bf16 row (two attention classes, CT-INT4
served form); KERNELS.md gains the h256/gqa2 and h512/gqa8 decode+prefill rows
(bf16kv + fp8kv legs) the arch selects.
2026-10-10 00:36:08 -07:00
sfjes 3259b4a8a2 arch: gemma4_bf16 plugin + w4a8 recipe + graph cases
Gemma 4 dense as two attention classes (sliding-window + proportional-RoPE
global, k_eq_v) over one GemmaRMSNorm stream with GELU ffn, two KV groups,
softcapped logits, tied scaled embedding. arch_test builds the full graph.
Env-gated residual-trace instrument in the arch (RADIANCE_TRACE_RESID, default
off). 21.7 GiB w4a16 QAT checkpoint serves coherent sampled output on the box.
2026-10-10 00:36:08 -07:00
sfjes 61cf8b7b1a engine: host-domain binding for weightless host-only ops
bind_ops falls back to the host domain when an op is host-only and carries no
weight tensors: a plugin declaring host-only math gets the same binding path as
device ops, with no model-specific quirk. Adds the R4D_DIAG kernel-selection
trace in plugin selection (default off).
2026-10-10 00:36:08 -07:00
sfjes 73bfc310aa format: CT-INT4 (QAT) checkpoint decode — _packed/_scale resolution, i4 affine planes
ckpt_rows_f32 resolves packed/scale tensor pairs and decodes i32-packed int4
rows to f32 planes. checkpoint_test cases added.
2026-10-10 00:36:08 -07:00
sfjes dd3310849a kernels: paged attention at h512/gqa8 and h256/gqa2, windowed prefill band
head 512 (gqa 8) — a head width the library had not compiled before — for the
global layers, head 256 (gqa 2) for sliding-window decode, plus the >=32-token
windowed prefill fix. Numeric selftests vs an inline port of ref_attn_paged
with negative control; env-gated attn-verify probes (R4D_VERIFY_ATTN, default
off) at the decode entries.
2026-10-10 00:36:08 -07:00
sfjes 8b825a941c rope + embed extensions: proportional-RoPE ladder, runtime embed scale (mult)
ladder param on rope/rope_table across ref/avx/r4d legs; embed_lookup gains its
runtime scale under the canonical registry name (mult). Default-preserving:
existing checkpoints replay unchanged (kbench rope fixture 44/44).
2026-10-10 00:36:08 -07:00
sfjes c37ce73d72 ops: rmsnorm_p, gelu_mul, logit_softcap, scale in lockstep across libref/libavx/libr4d + OPS.md rows
Elementwise ops with numeric selftest cases against the f64 oracle (both legs
of logit_softcap: bf16 and the f32 band the sampling chain carries). libr4d
gains env-gated verification probes alongside them (R4D_VERIFY_OFF
recompute-on-host checks; default off — instruments, not features).
2026-10-10 00:36:07 -07:00
sfjes 73620ef00e sched: a prefix hit on a windowed TRUNK re-prefills — reuse cannot cover a group the cache does not index
prefix.cpp indexes the RAD_KV_FULL groups and skips RAD_KV_WINDOW (its own
words: "a hit's blocks do not describe a cache whose floor moves" — the
blocks below the window are recycled). admit_one clamped a hit for the
linear/checkpoint cases; a model whose own attention includes a group the
cache skips — every windowed+full pair — passed every clamp, reused, and
adopted blocks covering the CACHED groups only. The windowed trunk layers
take used = ctx_len + n_tokens (batch.cpp) and read positions below
ctx_len this sequence never wrote; grab_block's min-heap (kv.cpp) hands
out the most recently freed blocks, i.e. the previous tenant's. The
sequence attends to the PREVIOUS REQUEST'S KV as its own prefix: fluent
text carrying the last request's content. Reproduced on a live server
with sequential prompts (A-B-C-A-B: the re-run of A reads C's prompt),
and it is why a windowed model with the prefix cache on cannot currently
serve more than one conversation at a time.

The fix is a second predicate next to the drafter floor, computed once
in init(): a paged group bound to a TRUNK layer (below meta.n_layers —
a drafter borrows from base_layer and above, per rad_bind_layer_kv) that
cached_groups() does not name. In admit_one, a hit with such a hole
reuses nothing: the prefix re-prefills (windowed prompts are small;
milliseconds). The drafter's own hole stays the refill design's —
HitCap ends the hit one drafter window before the prompt's end so the
tail-recompute covers the drafter's window while the trunk reuses the
rest (the e95d397 tests keep passing, all of them); no tail-recompute
can repair a trunk hole, which is why zero is the honest answer there.

sched_test gains an opt-in WINDOW group in the fixture (bound to a
trunk layer) and a_hit_on_a_model_with_a_windowed_group_reuses_nothing:
a deep, checkpoint-covered hit — legal under every other clamp — on a
cache indexing only the FULL group. Reuse lands at 0, nothing is
adopted, and attn_cached_tokens still reports the 304-token match: the
cache hit and the scheduler refused it. Disable the clamp and the hit
adopts 16 blocks of the seeded (previous tenant's) KV — n_computed 256,
the leak as shipped; that is the regression net.

Box: ctest lane + A-B-C-A-B battery green (evidence in the PR body).
2026-10-09 23:13:26 -07:00
sfjes f1d9afadfa sched: a prefix hit on a windowed TRUNK re-prefills — reuse cannot cover a group the cache does not index
prefix.cpp indexes the RAD_KV_FULL groups and skips RAD_KV_WINDOW (its own
words: "a hit's blocks do not describe a cache whose floor moves" — the
blocks below the window are recycled). admit_one clamped a hit for the
linear/checkpoint cases; a model whose own attention includes a group the
cache skips — every windowed+full pair — passed every clamp, reused, and
adopted blocks covering the CACHED groups only. The windowed trunk layers
take used = ctx_len + n_tokens (batch.cpp) and read positions below
ctx_len this sequence never wrote; grab_block's min-heap (kv.cpp) hands
out the most recently freed blocks, i.e. the previous tenant's. The
sequence attends to the PREVIOUS REQUEST'S KV as its own prefix: fluent
text carrying the last request's content. Reproduced on a live server
with sequential prompts (A-B-C-A-B: the re-run of A reads C's prompt),
and it is why a windowed model with the prefix cache on cannot currently
serve more than one conversation at a time.

The fix is a second predicate next to the drafter floor, computed once
in init(): a paged group bound to a TRUNK layer (below meta.n_layers —
a drafter borrows from base_layer and above, per rad_bind_layer_kv) that
cached_groups() does not name. In admit_one, a hit with such a hole
reuses nothing: the prefix re-prefills (windowed prompts are small;
milliseconds). The drafter's own hole stays the refill design's —
HitCap ends the hit one drafter window before the prompt's end so the
tail-recompute covers the drafter's window while the trunk reuses the
rest (the e95d397 tests keep passing, all of them); no tail-recompute
can repair a trunk hole, which is why zero is the honest answer there.

sched_test gains an opt-in WINDOW group in the fixture (bound to a
trunk layer) and a_hit_on_a_model_with_a_windowed_group_reuses_nothing:
a deep, checkpoint-covered hit — legal under every other clamp — on a
cache indexing only the FULL group. Reuse lands at 0, nothing is
adopted, and attn_cached_tokens still reports the 304-token match: the
cache hit and the scheduler refused it. Disable the clamp and the hit
adopts 16 blocks of the seeded (previous tenant's) KV — n_computed 256,
the leak as shipped; that is the regression net.

Box: ctest lane + A-B-C-A-B battery green (evidence in the PR body).
2026-10-09 18:47:09 -07:00
baKon d5b65cddc6 hfget: run under the image's busybox (df, xargs -I) (#71)
With curl and jq in the image, hfget.sh got further and stopped twice more,
both times on busybox, which is the only shell and coreutils the runtime
image has:

- `df -BG --output=avail` is GNU-only. Busybox printed its usage, $free came
  out empty, and every download "did not fit". Free space now comes from
  POSIX `df -Pk` (KiB), and the fit check compares bytes against KiB * 1024.
- Busybox `xargs -I` strips a line's leading blanks, and GNU's doesn't. A
  non-LFS file (config.json, tokenizer.json...) has an empty oid, so its line
  started with a tab and reached the child one field short. The size landed in
  oid and the path in size, so every small file failed its size check:
  "config.json is 721 bytes, listing says config.json". The list line is now
  <size><tab><oid><tab><path>. Size is never empty, so no line starts with a
  blank. The manifest format is unchanged, so an existing cache stays warm.

Tested in the image (busybox) and in ubuntu:24.04 with curl and jq (GNU):
fresh fetch, warm re-run, a truncated shard resumed and a deleted file
re-fetched (sha256 matches the hub's LFS oid), and the does-not-fit guard on a
1 MiB tmpfs.
2026-10-09 12:21:48 -05:00
baKon 4ab587a8a2 docker: ship curl, jq and a CA bundle, so --model can fetch an HF repo (#71)
`--model <repo id>` runs hfget.sh, which needs curl and jq, and curl needs a
CA bundle to reach huggingface.co over TLS. The runtime image is built FROM
scratch and had none of the three, so inside the container the fetch stopped
at "hfget: jq is required" (and with jq alone it would have stopped at curl,
then at the TLS handshake).

The rootfs stage now installs curl, jq and ca-certificates and copies the two
binaries and /etc/ssl/certs/ca-certificates.crt in. Their libraries go through
the same ldd closure, ELF-from-the-chroot check and licenses.sh as everything
else. They're installed in rootfs rather than build, so this doesn't
recompile the engine. The rootfs grows from 297 to 315 MB.
2026-10-09 12:16:15 -05:00
Malic Zilyas 32fa1a27ec libr4d: 5-/4-bit decode GEMM covers all row tiles in one block
cfg_for() pins MB = 1 across the decode band (M <= 64): right for the bf16
and MXFP4 skinny kernels, where the grid, not the weight, is the cost. The
w5a16 / w4a16_asym kernel is dequantise-bound, and one block per 16-row tile
unpacks every weight fragment once per tile, so two or three concurrent
streams (M = 16..48) paid the unpack two or three times: 104 us/call at one
stream, 190 us at three (profile-ops, PARO int5, 1.3.0).

Cover every row tile in one block (MB = ceil(M / 16), at most 4) unless a
tuned MB is pinned. The split-K bound is unchanged, so every output element
is still one wave's accumulation over the same K slices: output bits are
identical.

PARO int5, prod shape (175k / 3 seqs), BetterBench c3 aggregate t/s at
1 / 2 / 3 streams:  96 / 156 / 155  ->  92 / 169 / 170 (+9% / +10%);
same-source A/B on the dev build: c3 127 -> 166. Single-stream decode is
unchanged (that GEMM streams the weights at the memory roofline, ~620 GB/s).
Quality unchanged: ppl wiki 6.797 / code 1.533, GSM8K 100%, genchat 17/17
cold-verified, dia-mini v2 23/27, v3 15/15.

r4d_selftest gemm_w5a16_nt_m64: pass (incl. M = 40 with 3 parts, M = 64).
2026-10-09 12:30:15 +02:00
baKon 04405089cb sched: a long prefill leaves the rest of the step its room (--busy-prefill-chunk)
A prefill chunk took every token the step had left (plan_chunk(..., budget)). On a step budget of
a few thousand tokens and a prompt of a few hundred thousand, that is every step for a minute or
more, and for all of it a decode row behind the prefill in running_ got nothing (`want > budget`
-> break) and admission never ran (`while (... budget > 0)`). A mostly-cached turn that needed a
few hundred tokens waited for somebody else's whole prompt: on three ranks at
--max-num-batched-tokens 2048, a 94,529-token turn with 94,208 cached took 40.6 s to its first
token, which landed on the instant a 264,725-token cold prefill ahead of it ended (#61).

--busy-prefill-chunk auto (the default) holds a prefill chunk back only when work that would
otherwise get nothing is pending in the step: one row plus the draft window for each decode row
behind it, a share (an eighth of the budget, at least one quantum) for each prefill behind it and
for the next request waiting to start. The chunk never drops under the smallest step the prefill
stager overlaps -- under it every routed layer reads its pooled experts synchronously, the
-65 % prefill measured at a budget one token under the threshold. Where holding it back for a
waiting request or another prefill would leave a remainder under that floor before the checkpoint
boundary, the interval is split into two staged halves instead. Decode rows alone only take their
few tokens: the chunk ends a quantum short of the boundary and the next step finishes the
interval, the same pair of steps a prefill already runs when decode rows are planned ahead of it.
(Halving for decode rows too held a long prompt to half-interval chunks for as long as anything
decoded behind it, the larger cost.) Whatever the reserve was not used for (a refused admission, a
decode row that drafted less than its window) goes back to the chunk before the step is issued.
Admission shares the same way, so a cold prompt admitted with others queued behind it does not
take the whole step either; an embedding input still runs whole or not at all.

A prompt with nothing beside it, and rows already planned ahead of the prefill, are planned
exactly as before, so a lone request's steps -- and every greedy output -- are unchanged. `off`
restores the old loop including its break. `N` holds a chunk that shares the step to N tokens,
rows ahead included (the operator trading prefill speed for every other row's latency); startup
warns when N is under the stager's step.

The engine hands the scheduler the stager's smallest pass after init (PrefillStager::min_rows,
the largest over the ranks). radiance:engine_prefill_chunks_capped_total counts the chunks held
back. sched_test covers admission during a long prefill, a decode row behind one, off reproducing
the old plan, a lone prefill unchanged, an explicit N with rows ahead and behind, the share
handed back when nobody takes it, and the cap's arithmetic at a 2048-token step with the stager
at 1025, with and without a share in the reserve.
2026-10-09 00:28:03 -05:00
Malic Zilyas 9137948b95 ParoQuant dense: review fixes -- the matrices composed exactly, out checked, the stored form pinned
* r4d_rad_relayout_gdense composes in f64 (angles widened, cos/sin and products in double) and rounds to
  f16: the stored matrix is a derivation of the planes, the same bytes whichever libm computed it, as
  abi/rad_abi.h asks of a relayout.
* givens_dense_quant (libr4d and libref) refuses an `out` that does not name q's dtype instead of reading
  the quantiser off q alone.
* relayout_parity_test pins the dense stored form by hash, checks each matrix is orthogonal to f16
  accuracy and that a broken pairing is refused.
* r4d_givens_dense: static_assert that a thread stages one channel scale of the group; the selftest's
  givens_numeric takes one mode (rotate / dense fp8 / dense i8) instead of three flags; cGivensDense
  sits after the Hadamard constraint with its own comment.
2026-10-08 23:35:43 +02:00
Malic Zilyas d6b506fe4f ParoQuant dense: the gdense relayout checks the pairs with the givens pairs hook's gv_pairs_ok (a full pairing of each group, not only the range) 2026-10-08 23:35:43 +02:00
Malic Zilyas ec65b8cbeb ParoQuant: drop the sequential rotate-and-quantise ops (givens_quant_act_fp8 / givens_quant_act_i8g): givens_dense_quant replaces them; the rotate-only f16 kernel keeps its own file 2026-10-08 23:35:43 +02:00
Malic Zilyas c17f5fdc89 ParoQuant: dense per-group rotation (givens_dense_quant): composed 128x128 f16 matrices built at convert time, WMMA kernel with int8/fp8 epilogue; LinearFP8 uses it for the quantising rotation 2026-10-08 23:35:43 +02:00
Malic Zilyas a19cbcae85 ParoQuant int5/int4: review fixes -- docs, the w5 layout pinned and inverted, zero points checked, int4 import tested
* docs/OPS.md: the dtypes w5a16, w4a16_asym, w5a8i8, w4a8i8_asym, givens_quant_act_i8g, and which rows read pb1/pb2.
* r4d_gemm_w5a16_nt_m64: drop the unused two's-complement dequant copied from w4; the errors name this kernel.
* r4d_layout: r4d_rad_unrelayout_w5 (the inverse, wired to both w5 rows; the int4 rows take w4's); a zero point
  that is not a 4-/5-bit code is refused at load (the int8 prefill kernel reads five bits of it, the f16 one all).
* rad_fp8.h: one linear_is_givens predicate (table dtypes checked for both formats, the zero plane's u8 too);
  declare_rotation declares the tables and rot_stages only, decl_rot_op the op in front of each GEMM.
* tests: relayout_parity pins the w5 stored form and its refusal; checkpoint_test imports z-lab's int4 as a fused
  gate|up (two rotated parts); the selftest's asymmetric planes and part bounds come from one helper each.
* checkpoint: the ParoQuant refusal names both readable forms.
2026-10-08 23:35:43 +02:00
Malic Zilyas 3491aca6fe ParoQuant int5/int4: the review fixes of PR 1 carried to the 5-/4-bit path
* givens_rotate and givens_quant_act_i8g take the same checked `pairs` relayout as givens_quant_act_fp8.
* gemm_w4a8i8/w5a8i8_tiled: one re-tile slab for every part, as gemm_mxfp4a8_tiled (they share its
  scratch hook, which is one slab now).
* LinearFP8::decl_gemm_q: the one gemm_nt_q declaration, pb1/pb2 only with parts, for the MXFP4, the
  skinny 5-/4-bit and the int8 prefill GEMMs.
2026-10-08 23:35:43 +02:00
Malic Zilyas 6091039926 libr4d: int8 prefill band for ParoQuant int4/int5 (gemm_w4a8i8/w5a8i8 tiled, givens_quant_act_i8g); LinearFP8 uses it above 64 rows 2026-10-08 23:35:43 +02:00
Malic Zilyas cfe03f8ad8 qwen35_fp8: serve rotated 5-bit and 4-bit linears; keep the fp8 gated fold off them 2026-10-08 23:35:43 +02:00
Malic Zilyas 9e9fce3aca libr4d: w5a16 / w4a16_asym GEMM (5- and 4-bit asymmetric, any M, parts), givens_rotate kernel, layouts, selftest 2026-10-08 23:35:43 +02:00
Malic Zilyas ffa235bf0f libref: givens_rotate (the rotation without the quantiser, f16 out) 2026-10-08 23:35:43 +02:00
Malic Zilyas e45bb596f4 format: import ParoQuant int5-bitplane and z-lab's int4 (u5/u4 codes, f16 scale, u8 zero, givens tables) 2026-10-08 23:35:43 +02:00
Malic Zilyas 9af15f3a6e ParoQuant: check the givens pairs at load; one re-tile slab for every part; one bounds helper; one mxfp4 GEMM declaration
* libr4d: givens_quant_act_fp8 gets layout/relayout/unrelayout hooks for `pairs` -- stored as is,
  refused (RAD_E_FORMAT) when a stage is not a pairing of its own group of 128, which the kernel would
  index out of bounds. relayout_parity_test covers it.
* gemm_mxfp4a8_tiled: the parts run in order on one stream, so they share one re-tiled activation;
  the scratch is one slab again.
* mx_part_bounds: the pb1/pb2 clamping in one place (mx_parts, the decode scratch hook).
* LinearFP8: one gemm_nt_q declaration and one issue path for the plain and the rotated MXFP4 weight;
  pb1/pb2 still only on a weight with parts, so a one-part op keeps its tune-cache geometry.
2026-10-08 23:35:43 +02:00
Malic Zilyas 5681da471c qwen35_fp8: serve rotated MXFP4 linears (LinearFP8 rotates its input first); paro recipe
A rotated weight reads the producer's bf16 plane, rotates and quantises it into its own planes
(parts side by side) and runs the ordinary mxfp4a8 GEMM. Adds data/recipes/q38-27b-paro-mxfp4-df2.recipe
and the GUIDE entry.
2026-10-08 23:35:43 +02:00
Malic Zilyas 36e3b78c76 libr4d: givens_quant_act_fp8 kernel; mxfp4a8 GEMMs take parts as launches over windows
The rotate+scale+quantise kernel does a (part, group) per wave with the stages' tables prefetched.
The three MXFP4 GEMM rows learn row pitches (lda, ldws, ldc) and launch once per weight part; the
layout hook accepts the codes/exponent planes of a givens-encoded weight. r4d_selftest checks the
kernel against an f64 rotation and every GEMM row's parts against the planes' meaning.
2026-10-08 23:35:43 +02:00
Malic Zilyas 1213c05cd8 ops: givens_quant_act_fp8; gemm_nt_q pb1/pb2 for activation copies per weight part
libref implements both (and is the oracle); libavx refuses a call that names a part.
2026-10-08 23:35:43 +02:00
Malic Zilyas 3402acf82d format: import ParoQuant MXFP4 checkpoints (givens transform with parts, per-row fp8 scale)
quant_method paroquant_mxfp4 is Quark's MXFP4 planes in a rotated basis plus z-lab's learned
Givens rotations. rad-convert reads the codes and exponents byte for byte and builds the
encoding's givens tables (t.pairs/t.angle/t.scale) from pairs/theta/channel_scales; a fused
gate|up or qkv|z gets one set of tables a checkpoint tensor (new t.part table). The core decoder
undoes the per-part rotation. fp8 tensors with one f32 scale a row are read exactly.
2026-10-08 23:35:43 +02:00
Deadcode 89cee7ce41 radiance 1.3.0
- #47: llama-server's request fields, routes and sampler order, and /props (with baKon's model
  entry: max_model_len, root and capabilities on /v1/models, and /v1/models/:id)
- new APIs: Anthropic's Messages API (/v1/messages), OpenAI's Responses API (/v1/responses),
  llama-server's /completion and /infill, logprobs (OpenAI's logprobs and top_logprobs, up to
  20; llama-server's n_probs), OpenAI's legacy `functions`, and X-Api-Key beside the bearer key
- #4: --model takes a Hugging Face repo id (owner/name), fetched before startup into
  ~/.cache/radiance/hf or --download-dir and checked for changes at every start (redxherring)
- #46: --tp 3 --tp-wire wht6 serves -- a three-rank two-shot all-reduce with uneven shards and
  the tiered-int8 wire over it (baKon); scripts/cardclock.py names what holds each card's clock
  under load (baKon)
- CPU-only serving works again; --kernels names the kernel libraries to load; a model the
  loaded libraries cannot fully serve refuses at startup instead of failing its first request;
  --vram-kv-mib and --vram-weights-mib are gone (the split is automatic)
- --embedding-placement ram is the default, and `auto` is gone
- #40: Swift 1.5 recipes; rad-convert reads which shard holds a tensor from the index
- #53: the pinned host pool gets huge pages where shmem THP is off; #57: a crash on video with
  an odd frame width is fixed
2026-10-08 18:22:08 +02:00
redxherring 6a2ee986d6 serve: --help notes --model also takes an HF repo id 2026-10-08 17:47:27 +02:00
redxherring 7e796642e6 serve: --model takes an HF repo id, fetched to $RADIANCE_HOME/hf via hfget.sh
A non-path owner/name is downloaded before bring-up and the model path
rewritten to the cached dir, so a new user points --model at a repo link
instead of a pre-fetched checkpoint. hfget.sh now keys its re-run skip on
lfs.oid (sha256) for LFS files and size for the rest, recorded in a
.hfget-manifest, so a same-size weight update is caught and re-fetched
while a warm cache stays a no-rehash no-op.
2026-10-08 17:47:27 +02:00
baKon 9238b1f23d libr4d: --tp-wire wht6 at three ranks, the tiered-int8 wire over the uneven two-shot
--tp 3 --tp-wire wht6 had no kernel: the lossy rows were world_size 2 (rotated 6-bit) and 4
(tiered int8 over the two-shot). The tiered-int8 two-shot is already written over the world size,
and what kept it at four was the even split it shards by -- numel % (32 x ws) -- which a 2048-wide
row (64 groups) meets at three ranks one step in three.

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

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

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

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

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

No files matched your search

+1
View File
@@ -5,3 +5,4 @@ compile_commands.json
*.rad
/sync-jarvis.sh
__pycache__/
.cache/
+22 -7
View File
@@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21)
# VERSION is what /version reports and what a client checks compatibility against. It is NOT the
# ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because
# a plugin contract and a server release do not move together.
project(radiance VERSION 1.2.2 LANGUAGES C CXX)
project(radiance VERSION 1.6.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -18,10 +18,14 @@ endif()
# cache STRING.
set(RAD_WITH_HIP "AUTO" CACHE STRING "ON | OFF | AUTO -- build the HIP backend and device kernels")
set_property(CACHE RAD_WITH_HIP PROPERTY STRINGS ON OFF AUTO)
set(RAD_WITH_FFMPEG "AUTO" CACHE STRING "ON | OFF | AUTO -- decode image and video parts with libavformat/libavcodec/libswscale")
set(RAD_WITH_FFMPEG "AUTO" CACHE STRING "ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample")
set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO)
option(RAD_BUILD_TESTS "Build the test suite" ON)
option(RAD_ASAN "Build with AddressSanitizer" OFF)
# Whether the HIP compiler's VOPD pairing is repeatable. LLVM 24's is not unless it carries the
# fix the image builds (docker/llvm-vopd-pairing.patch); without this the build turns pairing off
# on LLVM 24, see rad_hip_repeatable in cmake/RadAddPlugin.cmake.
option(RAD_HIP_VOPD_REPEATABLE "The HIP compiler's VOPD pairing is repeatable (the image's LLVM 24 is)" OFF)
# ---------------------------------------------------------------- HIP detection
@@ -219,6 +223,14 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance)
endif()
# THE DOWNLOADER `radiance --model <owner/name>` RUNS (core/hf_model.cpp). The engine finds it at
# <bin>/../libexec/radiance/, so the build puts a copy at the same place under the build tree and
# a binary run from either tree finds it without a path to configure.
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
${CMAKE_BINARY_DIR}/libexec/radiance/hfget.sh COPYONLY)
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/radiance)
# rad_add_plugin() and rad_hipify() live in cmake/RadAddPlugin.cmake because the installed package
# config includes that same file: a third party building a plugin from their own repository needs
# the function, and a second copy of it in the package config would drift from this one. The file
@@ -316,22 +328,23 @@ endif()
find_package(Threads REQUIRED)
# ---------------------------------------------------------------- media decoding
# An image or video part of a chat request is decoded by libavformat/libavcodec and converted by
# libswscale (core/mm/media.cpp). Without them the engine builds and serves text, and refuses a
# An image, video or audio part of a request is decoded by libavformat/libavcodec and converted by
# libswscale or libswresample (core/mm/media.cpp). Without them the engine builds and serves text, and refuses a
# media part by name -- the same tri-state as HIP, because a machine that has the libraries should
# not silently build without them.
set(RAD_FFMPEG_FOUND OFF)
if(NOT RAD_WITH_FFMPEG STREQUAL "OFF")
find_package(PkgConfig QUIET)
if(PkgConfig_FOUND)
pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale)
pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale
libswresample)
endif()
if(RAD_FFMPEG_FOUND)
message(STATUS "radiance: media decoding via libavformat ${RAD_FFMPEG_libavformat_VERSION}")
elseif(RAD_WITH_FFMPEG STREQUAL "ON")
message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale were not found.")
message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale/libswresample were not found.")
else()
message(STATUS "radiance: no libavformat -- image and video input will be refused")
message(STATUS "radiance: no libavformat -- image, video and audio input will be refused")
endif()
endif()
@@ -446,3 +459,5 @@ install(FILES vendor/nlohmann/LICENSE.MIT
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME nlohmann-json.LICENSE)
install(FILES vendor/cpp-httplib/LICENSE
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME cpp-httplib.LICENSE)
install(FILES core/server/LICENSE.lfm
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME liquidai-d1.LICENSE)
+134 -29
View File
@@ -11,10 +11,17 @@
#
# Stages:
# ffmpeg FFmpeg built with only the demuxers core/mm/media.cpp admits and the decoders their
# streams need; the distribution's build brings ~200 packages of encoders, filters and
# display libraries the engine never calls
# build ROCm dev image + cmake/ninja/g++-14; configures, builds, installs to /stage
# test `ctest -LE gpu` on that build -- everything that does not need a card
# streams need (pictures, video, and audio with swresample), and the three encoders the
# images API writes (png, mjpeg, libwebp); the distribution's build brings ~200
# packages of encoders, filters and display libraries the engine never calls
# llvm ROCm's libLLVM rebuilt from ROCm's own llvm-project at the commit the image's clang
# reports, with docker/llvm-vopd-pairing.patch -- the fix that makes LLVM 24's device
# code repeatable from build to build (cmake/RadAddPlugin.cmake, rad_hip_repeatable)
# build ROCm dev image + cmake/ninja/g++-14; configures, builds, installs to /stage, every
# device source compiled by ROCm's clang from a shadow of the ROCm tree whose libLLVM
# is the llvm stage's
# test docker/llvm-check.sh, then `ctest -LE gpu` on that build -- everything that does not
# need a card
# rootfs the install tree stripped, and every library its binaries and plugins load, resolved
# by ldd, copied into one directory and checked from inside a chroot
# runtime FROM scratch + rootfs. This is the image that ships
@@ -31,9 +38,10 @@
# docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance
#
# The ROCm userspace in the image must be one the host's amdgpu kernel driver supports. It is
# pinned to the version the serving host runs; move both together.
# pinned to the version the serving host runs; move both together. From ROCm 10 on, the dev image
# is published only as the -full tag.
ARG ROCM_VERSION=7.2.4
ARG ROCM_VERSION=10.1.0-full
ARG UBUNTU_VERSION=24.04
ARG FFMPEG_VERSION=8.1.3
ARG FFMPEG_SHA256=7138d28c96d9d3e3af4ee3d8cad72741f8ffb40da90c1112235dea3ecd3178a3
@@ -46,24 +54,27 @@ ARG JOBS=
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
build-essential nasm pkg-config ca-certificates curl xz-utils zlib1g-dev libdav1d-dev \
libwebp-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /tmp
# The demuxers are media.cpp's kFormats whitelist, the only containers it opens. The decoders are
# what those containers carry: still images, H.264 and HEVC (MP4, MOV, HEIF), VP8 and VP9 (WebM,
# WebP), AV1 through dav1d (WebM, MP4, AVIF), MPEG-1/2/4, Theora and the FLV/H.263 family. JPEG XL
# is recognised and refused by name: its only decoder is libjxl's. No protocols: media.cpp reads
# from memory through its own I/O context.
# is recognised and refused by name: its only decoder is libjxl's. The encoders are an image
# model's output formats (media.cpp encode_image): png, jpeg as mjpeg, webp through libwebp. No
# protocols: media.cpp reads from memory through its own I/O context.
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
curl -fsSL "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" -o ffmpeg.tar.xz \
&& echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \
&& tar -xJf ffmpeg.tar.xz && cd "ffmpeg-${FFMPEG_VERSION}" \
&& ./configure --prefix=/opt/ffmpeg --enable-shared --disable-static --disable-debug \
--disable-programs --disable-doc --disable-network --disable-autodetect --disable-everything \
--disable-avdevice --disable-avfilter --disable-swresample \
--enable-zlib --enable-libdav1d \
--enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe \
--enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263 \
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl \
--disable-avdevice --disable-avfilter --enable-swresample \
--enable-zlib --enable-libdav1d --enable-libwebp \
--enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe,wav,w64,mp3,flac,aac,aiff \
--enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_alaw,pcm_mulaw,mp3float,mp2float,flac,vorbis,opus,aac \
--enable-encoder=png,mjpeg,libwebp \
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl,mpegaudio,flac,aac,vorbis,opus \
&& make -j"${JOBS:-$(nproc)}" \
&& make install \
&& mkdir -p /opt/ffmpeg/share/doc/ffmpeg \
@@ -73,6 +84,52 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
&& echo "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz, sha256 ${FFMPEG_SHA256}" \
> /opt/ffmpeg/share/doc/ffmpeg/SOURCE
# ------------------------------------------------------------------------------------------- llvm
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS llvm
ARG JOBS=
# THE ONE LIBRARY OF THE HIP COMPILER THAT CHANGES. clang, lld and the offload tools all load
# lib/llvm/lib/libLLVM.so, so this stage rebuilds that file and nothing else: the source is ROCm's
# llvm-project at exactly the commit `clang --version` names (a different commit refuses, as does
# a patch that no longer applies), configured as ROCm's lib/cmake/llvm/LLVMConfig.cmake says it
# was -- Release without assertions, AMDGPU;SPIRV;X86, every component in the dylib, no RTTI or
# exceptions, zlib and zstd from rocm_sysdeps -- and compiled by ROCm's own clang and lld. With
# VOPD pairing off it produces ROCm's code byte for byte; docker/llvm-check.sh holds the build
# stage to that. A sparse, depth-one fetch: llvm/, the cmake/, libc/ and third-party/ directories
# its configure reads, and none of its tests or documentation.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
git cmake ninja-build ca-certificates \
&& rm -rf /var/lib/apt/lists/*
COPY docker/llvm-vopd-pairing.patch /tmp/
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
set -e; L=/opt/rocm/lib/llvm; S=/opt/rocm/lib/rocm_sysdeps; \
rev=$($L/bin/clang --version | sed -n 's|.*ROCm/llvm-project.git \([0-9a-f]\{40\}\).*|\1|p'); \
[ -n "$rev" ] || { echo "llvm: no ROCm/llvm-project commit in: $($L/bin/clang --version | head -1)" >&2; exit 1; }; \
git init -q /llvm-project; cd /llvm-project; \
git remote add origin https://github.com/ROCm/llvm-project.git; \
git sparse-checkout set --no-cone '/*' '!/*/' /cmake/ /libc/ /llvm/ /third-party/ \
'!/llvm/test/' '!/llvm/unittests/' '!/llvm/docs/' '!/llvm/benchmarks/'; \
git fetch -q --depth 1 --filter=blob:none origin "$rev"; \
git checkout -q FETCH_HEAD; \
git apply /tmp/llvm-vopd-pairing.patch; \
cmake -G Ninja -S llvm -B /build-llvm -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=OFF \
-DLLVM_TARGETS_TO_BUILD="AMDGPU;SPIRV;X86" -DLLVM_BUILD_LLVM_DYLIB=ON -DLLVM_LINK_LLVM_DYLIB=ON \
-DLLVM_DYLIB_COMPONENTS=all -DLLVM_ENABLE_RTTI=OFF -DLLVM_ENABLE_EH=OFF -DLLVM_ENABLE_FFI=OFF \
-DLLVM_ENABLE_LIBXML2=OFF -DLLVM_ENABLE_LIBEDIT=OFF -DLLVM_ENABLE_CURL=OFF \
-DLLVM_ENABLE_HTTPLIB=OFF -DLLVM_ENABLE_TELEMETRY=ON -DLLVM_ENABLE_PLUGINS=ON \
-DLLVM_ENABLE_LIBPFM=OFF \
-DLLVM_ENABLE_ZLIB=FORCE_ON -DZLIB_INCLUDE_DIR=$S/include -DZLIB_LIBRARY=$S/lib/librocm_sysdeps_z.so.1 \
-DLLVM_ENABLE_ZSTD=FORCE_ON -Dzstd_INCLUDE_DIR=$S/include -Dzstd_LIBRARY=$S/lib/librocm_sysdeps_zstd.so.1 \
-DLLVM_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_BENCHMARKS=OFF -DLLVM_INCLUDE_EXAMPLES=OFF \
-DLLVM_INCLUDE_DOCS=OFF -DLLVM_BUILD_TOOLS=OFF -DLLVM_USE_LINKER=lld -DLLVM_PARALLEL_LINK_JOBS=2 \
-DCMAKE_C_COMPILER=$L/bin/clang -DCMAKE_CXX_COMPILER=$L/bin/clang++ > /tmp/llvm-configure.log 2>&1 \
|| { tail -40 /tmp/llvm-configure.log >&2; exit 1; }; \
ninja -C /build-llvm ${JOBS:+-j${JOBS}} LLVM > /tmp/llvm-build.log 2>&1 \
|| { grep -m20 -B2 -A8 'error' /tmp/llvm-build.log >&2; exit 1; }; \
so=$(basename $(readlink -f $L/lib/libLLVM.so)); \
mkdir -p /out; cp /build-llvm/lib/$so /out/; \
rm -rf /build-llvm /llvm-project
# ------------------------------------------------------------------------------------------ build
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build
ARG GPU_TARGETS=gfx1201
@@ -83,19 +140,49 @@ ARG JOBS=
# g++-14 rather than the image's default 13: its libstdc++ is the one hipcc then compiles the
# device-side translation units against too, and it is the runtime image's libstdc++ as well.
# gawk because tools/ops_doc_check.sh uses gensub, which Ubuntu's default awk (mawk) lacks.
# libdav1d7 is the runtime half of the AV1 decoder the ffmpeg stage linked; busybox-static goes
# into the runtime image.
# libdav1d7 and libwebp7 are the runtime halves of the AV1 decoder and the WebP encoder the ffmpeg
# stage linked; busybox-static goes into the runtime image.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
cmake ninja-build pkg-config g++-14 gawk libdav1d7 busybox-static \
cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 busybox-static \
&& rm -rf /var/lib/apt/lists/*
COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf && ldconfig
# ROCm's library directory is registered with the loader beside FFmpeg's because the ROCm 10 images
# register none, and the rootfs stage resolves every library the installed binaries load with ldd.
RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf \
&& echo /opt/rocm/lib > /etc/ld.so.conf.d/rocm.conf && ldconfig
ENV ROCM_PATH=/opt/rocm HIP_PATH=/opt/rocm CC=gcc-14 CXX=g++-14 \
PKG_CONFIG_PATH=/opt/ffmpeg/lib/pkgconfig
# THE HIP COMPILER: ROCm's clang, loading the llvm stage's libLLVM. ROCm's tools find their
# libraries through RPATHs relative to themselves -- $ORIGIN/../lib for libLLVM, which
# LD_LIBRARY_PATH cannot override, and $ORIGIN/../../rocm_sysdeps/lib and $ORIGIN/../../../lib,
# which leave lib/llvm -- so the compiler lives in a shadow of the whole ROCm tree at the same
# depth: /opt/rocm-repeatable, every entry a link back into /opt/rocm except lib/llvm/bin, which
# holds real copies of the executables, and lib/llvm/lib's libLLVM, which is the rebuilt one.
# Only compiling uses it. The build names /opt/rocm with --rocm-path, so the headers and device
# libraries are ROCm's and the runtime path clang records in a linked plugin is /opt/rocm/lib;
# without it clang takes the tree it sits in as ROCm, and a loader that follows that path from
# the HIP runtime to comgr reaches the rebuilt libLLVM, which lacks the libstdc++ symbols ROCm's
# GCC-built one re-exports for comgr. The rootfs stage refuses any library resolved through it.
COPY --from=llvm /out/ /tmp/llvm-out/
RUN set -e; R=/opt/rocm; D=/opt/rocm-repeatable; L=lib/llvm; \
so=$(basename $(readlink -f $R/$L/lib/libLLVM.so)); \
[ -f /tmp/llvm-out/$so ] || { echo "the llvm stage built no $so" >&2; exit 1; }; \
mkdir -p $D/$L/lib; \
for e in $R/*; do n=${e##*/}; [ $n = lib ] || ln -s $e $D/$n; done; \
for e in $R/lib/*; do n=${e##*/}; [ $n = llvm ] || ln -s $e $D/lib/$n; done; \
for e in $R/$L/*; do n=${e##*/}; [ $n = bin ] || [ $n = lib ] || ln -s $e $D/$L/$n; done; \
cp -a $R/$L/bin $D/$L/; \
for e in $R/$L/lib/*; do n=${e##*/}; \
if [ $n = $so ]; then mv /tmp/llvm-out/$so $D/$L/lib/; \
elif [ -L $e ] && [ "$(readlink $e)" = $so ]; then ln -s $so $D/$L/lib/$n; \
else ln -s $e $D/$L/lib/$n; fi; \
done; \
rm -rf /tmp/llvm-out
WORKDIR /src
COPY . .
@@ -108,6 +195,9 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
-DCMAKE_INSTALL_PREFIX=/opt/radiance \
-DRAD_WITH_HIP=ON -DRAD_WITH_FFMPEG=ON \
"-DRAD_GPU_TARGETS=${GPU_TARGETS}" \
-DCMAKE_HIP_COMPILER=/opt/rocm-repeatable/lib/llvm/bin/clang++ -DCMAKE_HIP_COMPILER_ROCM_ROOT=/opt/rocm \
-DCMAKE_HIP_FLAGS=--rocm-path=/opt/rocm \
-DRAD_HIP_VOPD_REPEATABLE=ON \
&& cmake --build /build ${JOBS:+-j${JOBS}} \
&& DESTDIR=/stage cmake --install /build \
&& mkdir -p /stage/opt/radiance/share/radiance/recipes \
@@ -126,41 +216,56 @@ FROM build AS test
# rebuilt against the installed package, libr4d included -- is the development tree's to run
# (tests/oot_plugins.sh): it re-does this stage's whole compile.
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
ctest --test-dir /build -LE 'gpu|oot' --output-on-failure \
bash /src/docker/llvm-check.sh /build \
&& ctest --test-dir /build -LE 'gpu|oot' --output-on-failure \
&& touch /build/host-tests-passed
# ----------------------------------------------------------------------------------------- rootfs
FROM build AS rootfs
# hfget.sh, which fetches the Hugging Face repo a --model id names, runs curl and jq, and curl needs
# a CA bundle to reach the hub over TLS. Installed in this stage, not in `build`, so adding them does
# not recompile the engine.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
curl jq ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# The marker makes this stage, and so the shipped image, depend on the test stage.
COPY --from=test /build/host-tests-passed /rootfs/opt/radiance/share/radiance/.host-tests-passed
# Every library the binaries and plugins load, plus comgr, which the HIP runtime opens at run time
# and cannot initialise a device without, goes into one directory the dynamic loader searches by
# default: no ld.so.cache, no LD_LIBRARY_PATH. libdrm_amdgpu names the card from amdgpu.ids. A
# static busybox provides the health check's wget and a shell for `docker exec`. docker/licenses.sh
# traces each of those files to its package and records its license and source in
# /usr/share/doc/THIRD-PARTY. Then every ELF file is resolved from inside the tree, so nothing can
# depend on a library the image lacks.
# default: no ld.so.cache, no LD_LIBRARY_PATH. ROCm's own libdrm_amdgpu carries the card name table
# compiled in, so no amdgpu.ids is copied. A static busybox provides the health check's wget and a
# shell for `docker exec`; curl, jq and the CA bundle are hfget.sh's, and the bundle is
# ca-certificates' Mozilla set, which is the directory named for it in the license list.
# docker/licenses.sh traces each of those files to its package and records its license and source
# in /usr/share/doc/THIRD-PARTY. Then every ELF file is resolved from inside the tree, so nothing
# can depend on a library the image lacks.
RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \
mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/usr/share/libdrm $R/data $R/tmp; \
mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/etc/ssl/certs $R/data $R/tmp; \
chmod 1777 $R/tmp; \
cp -a /stage/opt/radiance $R/opt/; \
elves=$(find $R/opt/radiance -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print); \
strip --strip-unneeded $elves; \
libs=$(for f in $elves /opt/rocm/lib/libamd_comgr.so.3; do ldd "$f"; done \
libs=$(for f in $elves /usr/bin/curl /usr/bin/jq /opt/rocm/lib/libamd_comgr.so.3; do ldd "$f"; done \
| awk '/=> \//{print $3} /^\t\/lib64\//{print $1}' | sort -u); \
if echo "$libs" | grep /opt/rocm-repeatable/; then \
echo "these resolve through the compiler's shadow ROCm tree, not /opt/rocm" >&2; exit 1; fi; \
for lib in $libs; do \
case "$lib" in */ld-linux-x86-64.so.2) cp -L "$lib" $R/lib64/ ;; *) cp -L "$lib" $L/ ;; esac; \
done; \
cp -L /opt/rocm/lib/libamd_comgr.so.3 $L/; \
cp /usr/share/libdrm/amdgpu.ids $R/usr/share/libdrm/; \
cp /bin/busybox $R/usr/bin/busybox; ln -s /usr/bin/busybox $R/bin/sh; \
sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 \
/usr/share/libdrm/amdgpu.ids /bin/busybox; \
for f in $(cd $R && find opt/radiance usr/lib -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print); do \
cp /usr/bin/curl /usr/bin/jq $R/usr/bin/; \
cp /etc/ssl/certs/ca-certificates.crt $R/etc/ssl/certs/; \
sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 /bin/busybox \
/usr/bin/curl /usr/bin/jq /usr/share/ca-certificates/mozilla; \
for f in $(cd $R && find opt/radiance usr/lib -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print) \
usr/bin/curl usr/bin/jq; do \
out=$(chroot $R /lib64/ld-linux-x86-64.so.2 --list "/$f" 2>&1) || { echo "$f: $out" >&2; exit 1; }; \
if echo "$out" | grep -q 'not found'; then echo "$f: $out" >&2; exit 1; fi; \
done; \
chroot $R /opt/radiance/bin/radiance --help > /dev/null; \
chroot $R /usr/bin/curl --version > /dev/null; chroot $R /usr/bin/jq --version > /dev/null; \
du -sh $R $L $R/opt/radiance
# ---------------------------------------------------------------------------------------- runtime
+31 -11
View File
@@ -1,18 +1,32 @@
radiance
Copyright 2026 Deadcode and the radiance contributors
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14
(the MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake
(the MXFP4 decode and prefill GEMMs and the MXFP4 linear, stop strings after the reasoning block,
and the draft refill on a prefix hit), goodman-b (four-rank tensor parallelism
for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the fused four-rank
writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard, the routed
GEMM's decode loads and run search, the gated residual's prefill read form and row groups, the
fused router launch, the adaptive draft window, the MoE prefill forms and the sorted operand's
decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000 (the n-gram
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14 (the
MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake (the
MXFP4 decode and prefill GEMMs, the MXFP4 linear and the DFlash2 drafter's MXFP4 linears, stop
strings after the reasoning block, and the draft refill on a prefix hit), goodman-b (four-rank
tensor parallelism for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the
fused four-rank writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard,
the routed GEMM's decode loads and run search, the gated residual's prefill read form and row
groups, the fused router launch, the adaptive draft window, the MoE prefill forms, the sorted
operand's decode kernel, 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), mechkbfan (the token embedding in the pinned host pool), Code000 (the n-gram
gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor parallelism,
serving any world size from the shipped container, the request log, an uneven world's per-rank
KV and weights split, and --rope-scaling) and hazyumps (static YaRN for the Qwen rotary paths).
serving any world size from the shipped container, the request log, an uneven world's per-rank KV
and weights split, --rope-scaling, the model entry's context length, root and capabilities, /props,
the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of the three-rank lossy-wire
crash, cardclock.py, --busy-prefill-chunk, and curl, jq and a CA bundle in the image with hfget.sh
under its busybox), hazyumps (static YaRN for the Qwen rotary paths), malic (ParoQuant: its MXFP4,
int5 and int4 checkpoints imported and served, the Givens rotation as stages and as dense per-group
matrices on the matrix cores, and the 5- and 4-bit asymmetric GEMMs), Perire (Gemma 4 26B-A4B with
z-lab's DFlash drafter: its plugin, its kernels in libr4d -- the windowed paged attention,
pair_argmax, the fused sandwich joins and expert_scale -- and the host emulator that tests them, the
prefill split into two slices with their all-reduces beside the compute, and the vocabulary-sharded
draft head), redxherring (--model taking a Hugging Face repo id), sfjes (Gemma 4 31B dense: its
plugin, its two attention classes and their kernels, and prefix reuse that leaves a windowed group
alone) and zivius (LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their
Codeberg PR 50).
This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each.
@@ -23,3 +37,9 @@ license text is in the file named beside each.
libquant/lq_ggml_*
nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
core/server/systemone.cpp carries text from Liquid AI's d1 (prompt.py and api.py in the
LiquidAI/d1-3B repository): the prompt it renders, its question blocks, the option codes and their
fallback codebook and the answer spellings, unchanged, in code rewritten in C++. That text is Liquid
AI, Inc.'s, under the LFM Open License v1.0, whose terms -- including its limit on commercial use --
apply to it; the license is in core/server/LICENSE.lfm.
+70 -13
View File
@@ -1,7 +1,8 @@
# radiance
An LLM inference server for AMD GPUs, in C++ and HIP, with an OpenAI-compatible HTTP API. Model
architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built
An LLM and image-generation inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks OpenAI's
chat, completions, Responses and images APIs, Anthropic's Messages API and llama-server's native one,
so their clients and SDKs work unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built
and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
The bundled device kernels (`libr4d`) target **AMD RDNA4** (`gfx1200`, `gfx1201`). The serve flags
@@ -21,8 +22,13 @@ If you wish to support the developement of the radiance engine you can do so [he
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` |
| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` |
| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` |
| Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` |
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` |
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` |
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
A container holds everything the server needs: the weights, the tokeniser, the chat template and
any drafter. Each download link's repository has the recipe and the exact command that made the
@@ -33,9 +39,30 @@ mkdir -p /srv/models/rad && cd /srv/models/rad
curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/minicpm5-2b-fp8.rad
```
The Gemma 4 container is keptn42's: GPTQ calibrated in transformers, with an int8 lm_head; its
repository has the recipe and the calibration step. To convert Google's bf16 checkpoint yourself,
`data/recipes/gemma4-31b-dense-bf16-w4a8.recipe` quantises without calibration (round-to-nearest
with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkpoint). On two R9700s
that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's,
and its drafts are accepted a little less often (0.46 against 0.50 of them on prose).
The ParoQuant containers keep the trunk exactly as the ParoQuant releases ship it, with the learned
Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, int5 from
`Launch80/Qwen3.8-27B-PARO-int5` and MXFP4 from `MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2`, each with
`data/recipes/q38-27b-paro-mxfp4-df2.recipe` and the DFlash2 drafter. A ParoQuant container made
before 1.5.0 is refused at startup. Convert it again and pass the old one as `--reuse` to copy every
tensor that did not change.
The Qwen-Image containers serve OpenAI's images API (`/v1/images/generations`, `/v1/images/edits`):
pictures from a prompt, and edits of up to ten pictures with an optional mask, 2048x2048 by default.
On two R9700s a 2048x2048 picture takes 61 s at the base model's 40 steps and 13 s with Turbo (56 and
12 s with `--tp-wire wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research
license, which is non-commercial.
## Run with Docker
The host needs Docker and an `amdgpu` driver that supports ROCm 7.2; it does not need ROCm. The
The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The
card needs Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The
image is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its
kernels built for `gfx1201`. Pull it, clone this repository for its compose files, then start a
model from one of them:
@@ -44,7 +71,7 @@ model from one of them:
docker pull stilldeadcode/radiance
git clone https://codeberg.org/StillDeadcode/radiance.git
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_STATE, RADIANCE_API_KEY, the GIDs
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_API_KEY, the GIDs
docker compose -f minicpm5-2b.yaml up -d # or any file from the table
docker compose -f minicpm5-2b.yaml logs -f
docker compose -f minicpm5-2b.yaml down
@@ -60,7 +87,8 @@ in the clone (it needs `docker buildx` and tests the build as it goes). Then set
## Build from source
You need Linux, git, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need
ROCm 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and build in it:
ROCm 10.1 or 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and
build in it:
```sh
git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance
@@ -70,13 +98,25 @@ cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # build for cards thi
cmake --install build --prefix /opt/radiance # optional; bin/, include/, share/radiance/
```
With ROCm 10.1 the build turns the compiler's VOPD pairing (dual-issue instruction pairs) off: its
LLVM 24 pairs in an order that follows heap addresses, so two builds of the same source can differ.
The Docker image builds its compiler with the fix and keeps the pairing, which is 1-3% faster on
the fp8 prefill GEMMs; a compiler that has the same fix is declared with
`-DRAD_HIP_VOPD_REPEATABLE=ON`. ROCm 7.2 is unaffected.
## Run without Docker
```sh
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an installed prefix finds its own
build/bin/radiance --model /srv/models/rad/minicpm5-2b-fp8.rad --port 8000 <flags>
build/bin/radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000 <flags>
```
`--model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
and `jq` into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere), serves the container it
holds, and checks it for changes at every start; a start that cannot reach the hub serves the copy
it has. The Docker image has neither tool, so with Docker download the file as shown above.
These are the flags each model is served with. They match its compose file, minus Flash-Next's
prefix-cache tiers:
@@ -89,6 +129,7 @@ prefix-cache tiers:
| Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` |
| MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` |
| Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` |
| Qwen-Image 2.1 and 2.1 Turbo | `--tp 2 --tp-wire wht6` |
Every model serves up to 32 sequences a step. Two rows keep 8, because on a hybrid model each
sequence holds its own recurrent state, and 32 of them take that memory from the attention cache
@@ -99,21 +140,22 @@ At `--tp 4` the gated residual's write carries the exact all-reduce, with the Mo
of it, on decode and verify steps; a prefill chunk runs the unfused chain. That chain's exact
all-reduce is one-shot up to 1 MiB a message and two-shot above that, which sends half the bytes
on a prefill chunk; both produce the same bits. The row above runs exact.
`--tp-wire wht6` at four ranks selects a different lossy wire, tiered int8 over the two-shot,
above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at
startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate against
`--tp 2` on the same cards has not been measured. The
`--tp-wire wht6` at three and four ranks selects a different lossy wire, tiered int8 over the
two-shot, above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6`
stops at startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate
against `--tp 2` on the same cards has not been measured. The
tiering flags are the tp2 recipe carried over. Above two ranks each rank still owns a **slice of
every expert's width** — each parity's 128-column blocks are cut contiguously over the ranks and the
odd block alternates with the parity, so every rank's share is whole blocks and every block has
exactly one owner — and the resident expert bytes per rank are smaller, so the elastic window is a
different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before
trusting it. **`--host-pool-mib` is pinned on every card**, so the row
above pins 4 × 12 GiB = 48 GiB, and the amdgpu driver caps pinned memory at `ttm.pages_limit`, half
of RAM by default: that row needs 96 GiB of RAM or a raised limit
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
above pins 4 × 12 GiB = 48 GiB of RAM that nothing else can use and the kernel cannot swap out. The
amdgpu driver caps what every process together pins at the machine's RAM less 1/64 and 1.5 GiB; the
pool is locked user memory, which `ttm.pages_limit` does not count. A 64 GiB machine serves
`flashnext-tp1.yaml` with 49 GiB pinned ([`docs/GUIDE.md`](docs/GUIDE.md) §7).
Add `--api-key KEY` to require `Authorization: Bearer KEY`. Add `--debug-graph` to print every op
Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). Add `--debug-graph` to print every op
and the kernel it resolved to, then exit without serving. Then:
```sh
@@ -121,6 +163,14 @@ curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \
-d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
```
An image model answers OpenAI's images API instead, with base64 pictures:
```sh
curl -s localhost:8000/v1/images/generations -H 'Content-Type: application/json' \
-d '{"prompt":"a lighthouse on a cliff at sunset, oil painting","size":"1024x1024"}' \
| python3 -c 'import sys,json,base64; open("out.png","wb").write(base64.b64decode(json.load(sys.stdin)["data"][0]["b64_json"]))'
```
`http://localhost:8000/` is the dashboard. [`docs/GUIDE.md`](docs/GUIDE.md) covers the API, memory
budgets, long context, speculative decoding and operating a server.
@@ -133,6 +183,13 @@ budgets, long context, speculative decoding and operating a server.
build/bin/rad-convert ~/models/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \
--recipe data/recipes/q38-27b-bf16.recipe
build/bin/rad-convert ~/models/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096
build/bin/rad-convert ~/models/google/gemma-4-31B-it -o gemma4-31b-w4a8.rad \
--recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \
--set quantization_config.quant_method=compressed-tensors \
--draft-model ~/models/google/gemma-4-31B-it-assistant
build/bin/rad-convert ~/models/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \
--recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \
--draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2
```
With Docker, use `docker run --rm -v ~/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`. In
+25 -3
View File
@@ -19,7 +19,7 @@ extern "C" {
* name, with both versions printed. An OPTIONAL export added beside the existing ones
* (rad_plugin_reference, say) is not a change of shape: a plugin without it is read as answering
* the default. */
#define RAD_ABI_VERSION 15u
#define RAD_ABI_VERSION 16u
/* ================================================================== plugin identity */
/* RAD_PLUGIN_QUANT is a quantiser plugin: rad_quant.h is its whole contract. */
@@ -95,7 +95,8 @@ typedef int (*RadInitFn) (const RadParam* p, int n_p, int rank, int world_
typedef void (*RadFiniFn) (void* instance);
/* The launch. Must not allocate and must not synchronise. Returns RAD_OK or negative; a negative
* return aborts the step and fails the requests in it, naming the kernel and the geometry. */
* return aborts the step and fails the requests in it, naming the kernel and the geometry. A launch
* handed `link_gate` may return RAD_LINK_ENDED instead of RAD_OK (rad_kernel_collective). */
typedef int (*RadLaunchFn) (const RadArgs* a, RadStream stream);
/* ================================================================== the described launch */
@@ -597,12 +598,33 @@ typedef void (*RadPluginCloseFn)(void);
* before it, which is always correct. The symbol name is `rad_kernel_concurrent`. */
typedef int (*RadKernelConcurrentFn)(int i);
/* Optional, and a promise about kernel `i` of rad_kernel_at: nonzero means it is a COLLECTIVE --
* its launches exchange data with the other ranks' cards, so the interconnect carries their bytes
* for as long as they run and the step waits on it. The engine then keeps its own bulk traffic on
* the same links (weights it streams onto the card while the card computes) out of their way for
* that time. A plugin that does not export the symbol, or answers 0, has only the conventional
* `all_reduce` op treated as one. The symbol name is `rad_kernel_collective`.
*
* 2 promises more: every launch of the kernel ends that time itself, as soon as the last byte the
* other ranks send this card for it has landed -- a kernel that reduces after the exchange has the
* link to spare for the rest of its run. The engine then hands each launch it holds the link for
* the parameter `link_gate`, the address of a 64-bit word in memory the kernel reaches at system
* scope; a launch without it holds nothing and has nothing to end. The kernel reads the word on
* the device as it starts -- not the host in the launch call, where the hold has not taken effect
* yet -- and, once those bytes have landed, takes one off it with a system-scope atomic if it was
* odd; an even word it leaves alone. A launch that did so returns RAD_LINK_ENDED; any other
* success is RAD_OK, and the engine then ends the hold behind the launch, so a path that does not
* know the word is always safe. */
typedef int (*RadKernelCollectiveFn)(int i);
#define RAD_LINK_ENDED 1
/* Optional: nonzero declares this kernel library a REFERENCE implementation -- written to be
* plainly correct rather than fast. Three things follow, for any library that says so and for no
* other, whatever it is called:
* - the loader ranks it below every unnamed kernel library, because a reference matches every
* op it declares and would otherwise answer for them ahead of the library serving the card
* (naming it in --kernels still puts it where it is named);
* (naming it in --kernels still puts it where it is named, and a --kernels list that does
* not name it leaves it out);
* - the engine refuses to serve a model with an op only a reference library implements, unless
* told to with --debug-accept-reference-kernels;
* - rad-kbench checks every other library against it.
+220 -2
View File
@@ -134,6 +134,15 @@ typedef struct RadBuildCtx {
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int64_t max_out_rows;
/* THE MOST FRAMES ONE AUDIO ENCODER PASS MAY CARRY, and 0 means this deployment serves no
* audio: the plugin declares no audio encoder. An audio encoder's `max_tok`, the way
* max_enc_patches is a vision tower's -- its activations are sized against it -- and it bounds
* the longest clip, since one clip is one segment. The engine takes it from
* RadArchProbe::audio_frames, which is the plugin's statement of its longest clip.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int64_t max_audio_frames;
} RadBuildCtx;
/* ================================================================== weights */
@@ -395,6 +404,13 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g);
* becomes one only if the plugin issues it. */
int rad_op_resolved(RadBuilder* b, rad_op h);
/* Does a loaded kernel library declare op `op` -- is it in the vocabulary at all? Declaring an op
* nobody declares is an error, because that is what a misspelt name looks like; an op that is
* declared and only resolved to no kernel is not (rad_op_resolved). A plugin asks this first for a
* fused op that only an optional library defines, and emits the chain when the answer is 0.
* Additive export. */
int rad_op_declared(RadBuilder* b, const char* op);
/* ================================================================== checkpoint name map */
/* The plugin owns the map from checkpoint tensor names to declared weight names, including
* convert-time fusions -- q/k/v into a single qkv, gate and up into gate_up. It is the only
@@ -443,6 +459,25 @@ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
* the first step. An embedding-only or encoder-only plugin declares none, deliberately. */
int rad_declare_logits(RadBuilder* b, rad_buf logits);
/* WHICH BUFFER HOLDS THIS STEP'S POOLED VECTORS: what an EMBEDDING model returns instead of logits,
* one row a sequence of the step -- row s is sequence s's whole input pooled into one vector,
* whatever pooling the model was trained with (a mean, the last token, a CLS row). The core reads
* rows [0, n_seq) back after the step and hands each to its request; it does not normalise them,
* because that is the API's choice and not the model's.
*
* DECLARING IT MAKES THE PROGRAM AN EMBEDDING PROGRAM, and that changes what a step is:
*
* - every sequence in a step is a WHOLE input. The scheduler never splits one across steps,
* because an encoder that attends both ways cannot be fed half of its input, and it refuses
* an input longer than one step's tokens rather than truncating it;
* - there is no sampler, no drafter and no prefix cache, and nothing is generated: a request
* ends at the step that carried it.
*
* f32, device, [>= max_seqs, dim]: `dim` is the vector's width and the extent the core reads. A
* Program declares this or logits, never both -- a model that both generates and embeds is two
* deployments. */
int rad_declare_pooled(RadBuilder* b, rad_buf pooled);
/* ================================================================== the drafter */
/* WHAT THE PLUGIN'S DRAFT HEAD IS, declared the same way and for the same reason the logits
@@ -518,6 +553,31 @@ typedef struct RadDrafterDecl {
int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
/* A SERIAL HEAD WITH NO CACHE OF ITS OWN. Every attention layer of it reads one of the TRUNK's
* layers' K and V and writes none -- Gemma 4's assistant head, whose layers have a query
* projection and nothing else, reads the last sliding and the last global trunk layer. Called
* once, after rad_declare_drafter, by a plugin whose serial head is that shape. Additive export: a
* plugin that does not call it drafts exactly as before, and RAD_ABI_VERSION does not move.
*
* What it changes in the serial driver, and each item follows from the head writing nothing:
*
* NO HISTORY IS OWED. A history pass exists to fill a head's own K and V, and there are none to
* fill. The pass carries round 1 alone: ONE row a drafting sequence, at the committed position,
* with the token the trunk chose after it and the trunk's hidden state there (out_ids). A
* sequence that does not draft gets no row, and a step with nothing to draft no pass.
*
* EVERY ROUND RUNS AT THAT SAME POSITION, OVER THE SAME CONTEXT. A head with a cache of its own
* steps one position a round and attends to what it wrote there. This one has nowhere to write,
* and the trunk's cache past the committed position holds the K and V of drafts the last verify
* REJECTED, or of nothing. So every round's `seqused` ends at the committed position, and what
* the head proposed travels forward in its hidden state and its next input token instead.
*
* `pos_offset` is where those rows sit for the rotary, as an offset from the committed position:
* 0 is the position of the trunk hidden state the head continues from, 1 the position of the token
* it embeds. It moves nothing else -- the context ends at the committed position either way -- and
* which one a checkpoint was trained with is the plugin's to know. */
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
/* ================================================================== the encoder */
/* A MEDIA ENCODER THE PLUGIN RUNS ON AN ENCODER PASS (RadBatch::enc), declared for the reason the
* logits buffer and the drafter are: the core drives the pass and reads its result, so it has to
@@ -531,17 +591,21 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
* the processor's (core/mm), which reads its geometry from the container: the two agree through
* `patch_dim` and `merge`, and the core refuses a program whose encoder disagrees with the
* processor about either. */
/* A PROGRAM DECLARES AT MOST TWO: one serving images and video, one serving audio. An audio
* encoder's "patch" is one feature frame (a mel row), its `merge` is frames per output row, and
* its `max_patches` is RadBuildCtx::max_audio_frames. RadBatch::enc names which one a pass runs. */
enum {
RAD_MM_IMAGE = 1u << 0,
RAD_MM_VIDEO = 1u << 1,
RAD_MM_AUDIO = 1u << 2,
};
typedef struct RadEncoderDecl {
const char* name; /* "vision" -- for messages */
uint32_t modalities; /* RAD_MM_* this encoder serves */
uint32_t modalities; /* RAD_MM_* this encoder serves: IMAGE|VIDEO, or AUDIO alone */
int64_t patch_dim; /* elements in one input patch row */
int64_t merge; /* input patches per output row */
int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches */
int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches (max_audio_frames) */
int64_t n_embd; /* the width of an output row, the model's embedding width */
/* [max_patches / merge, n_embd] bf16: where a pass leaves its rows. The core reads it after
* the pass and before any other pass runs, so the planner may share its bytes with buffers
@@ -551,6 +615,106 @@ typedef struct RadEncoderDecl {
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
/* ================================================================== the image generator */
/* A PROGRAM THAT MAKES IMAGES: a conditioning network that reads a prompt (and pictures), a
* denoiser that turns a latent from noise into an image's latent over a number of steps, and a
* decoder that turns the latent into pixels. Declared for the reason the logits buffer is: the
* core drives the passes, so it has to be told what it is driving, and only the plugin knows.
*
* DECLARING ONE MAKES THE PROGRAM A GENERATOR, and a generator is driven by passes rather than by
* token steps (RadBatch::gen):
*
* RAD_GEN_PASS_COND one conditioning sequence -- the prompt, and any reference pictures --
* encoded into the generator's KV group. Read once per request (twice
* with guidance: the negative prompt is a sequence of its own).
* RAD_GEN_PASS_DENOISE one step of every image in flight that the pass carries: each image's
* latent rows, read from and written back to the plugin's own state at the
* image's lane, against its conditioning's KV.
* RAD_GEN_PASS_DECODE one image's latent to pixels, in `image_out`, which the core reads back.
*
* A program declares this, logits or pooled vectors -- one of the three.
*
* WHAT IS HERE IS THE MODEL'S CONTRACT WITH A CLIENT: the prompt it was trained on, the sizes it
* makes, the schedule its sampler follows. The core turns a request into passes with it and
* nothing in the core names a model. */
enum { RAD_GEN_PASS_COND = 1, RAD_GEN_PASS_DENOISE = 2, RAD_GEN_PASS_DECODE = 3 };
/* HOW THE GENERATOR'S SEQUENCE IS LAID OUT, which the core builds from the conditioning prompt.
*
* JOINT_GRID the prompt's rows after `drop_prefix`, each media slot standing for `slot_rows`
* rows that a reference picture's latent tokens take in raster order, then the
* image being made. Rotary positions are three components: a text row counts up
* in all three; a picture of h x w tokens holds the count in the first, and its row
* and column, centred on zero (-(n - n/2) .. n/2 - 1), in the other two, after which
* the count moves on by max(h, w). Text rows attend causally, a picture's rows to
* each other both ways, every row to every row before it. */
enum { RAD_GEN_LAYOUT_JOINT_GRID = 1 };
typedef struct RadGeneratorDecl {
const char* name; /* "qwen-image" -- for messages */
int32_t layout; /* RAD_GEN_LAYOUT_* */
/* THE CONDITIONING PROMPT, as text the core tokenises. `{prompt}` is replaced by the user's
* prompt; in `tmpl_edit`, `{images}` by one `tmpl_image` for each reference picture, joined by
* `tmpl_image_sep`. In `tmpl_image`, `{n}` is the picture's 1-based number and `{image}` where
* the picture's own tokens go -- the run the media processor makes of it, its markers
* included. */
const char* tmpl_text;
const char* tmpl_edit;
const char* tmpl_image;
const char* tmpl_image_sep;
/* The tokens this text tokenises to at the start of the prompt are ENCODED but not handed to
* the generator: the conditioning starts after them (a fixed system turn, say). */
const char* drop_prefix;
/* A TRANSPARENT IMAGE, asked for in the words the model was trained on: `{prompt}` is the
* user's description. Empty when the model makes no alpha. */
const char* tmpl_transparent;
/* GEOMETRY. One latent token covers `latent_scale` x `latent_scale` pixels and holds
* `latent_channels` values; a side is a multiple of `size_multiple` pixels; an image has
* `pixel_channels` channels (4: RGBA). A media slot of the conditioning prompt -- one
* encoder output row -- stands for `slot_rows` rows of the generator's sequence. */
int64_t latent_channels;
int64_t latent_scale;
int64_t size_multiple;
int64_t pixel_channels;
int64_t slot_rows;
/* The largest image, in latent tokens: every buffer the plugin sized for one image. */
int64_t max_tokens;
/* Reference pictures: at most `max_refs` a request, each resized to `ref_area` pixels. */
int64_t max_refs;
int64_t ref_area;
/* The size a request that names none is made at. */
int64_t default_width, default_height;
/* THE SAMPLER: flow matching, an Euler step from sigma 1 towards 0.
* A FIXED SCHEDULE: `n_sigmas` values, the terminal 0 implied; a request may not change the
* step count. Otherwise `default_steps` sigmas from 1 to 1/steps, shifted:
* dyn_shift 0 sigma' = shift * s / (1 + (shift - 1) * s)
* dyn_shift 1 mu linear in the image's token count, 256 -> base_shift .. max_seq ->
* max_shift; shift_exp 1: exp(mu) / (exp(mu) + (1/s - 1)), 0: mu / (mu + ...)
* then, with shift_terminal > 0, stretched so the last sigma is shift_terminal. */
int64_t default_steps;
int32_t n_sigmas;
const double* sigmas;
double shift;
int32_t dyn_shift;
int32_t shift_exp;
double base_shift, max_shift;
int64_t base_seq, max_seq;
double shift_terminal;
/* Guidance a request gets when it names none; 1 is off. */
double default_cfg;
/* WHERE THINGS ARE. `max_lanes` images may be in flight at once, each in a lane of the
* plugin's own state; `image_out` is [max_tokens * latent_scale^2, pixel_channels] u8 on the
* device, row-major pixels of the image a decode pass made. */
int64_t max_lanes;
rad_buf image_out;
} RadGeneratorDecl;
int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d);
/* ================================================================== diagnostics */
/* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */
void rad_note(RadBuilder* b, const char* fmt, ...);
@@ -612,6 +776,26 @@ typedef struct RadArchProbe {
* function reads untouched. Zero -- what a plugin that never heard of it leaves -- means the
* core does not ask, and the activation arena is not lent. */
int shape_probe_ok;
/* THE ENCODER'S MERGE: input patches a output row (RadEncoderDecl::merge), when the plugin
* declares an encoder. A pass carries whole output rows, so the core rounds the pass size it
* picks itself (`--mm-max-patches auto`) down to a multiple of this; a size the operator
* names is the operator's, and a plugin refuses one that does not divide. 0 is no opinion. */
int64_t enc_merge;
/* THE LONGEST AUDIO CLIP THE PLUGIN'S AUDIO ENCODER TAKES, in feature frames (a whole
* number of its merge), when it declares one: the engine sizes the audio pass with it
* (RadBuildCtx::max_audio_frames). 0 is no audio. */
int64_t audio_frames;
/* AN IMAGE GENERATOR (rad_declare_generator), and the rows its largest pass carries: the
* engine sizes the step for it before declare -- a denoise pass carries an image's every
* latent row at once, twice with guidance -- and turns off what a generator has no use for.
* 0 is a program that generates text or embeds. */
int64_t gen_rows;
/* ...and the patches its conditioning pass encodes at most: every reference picture a request
* may carry, at the size the model resizes them to. The encoder's pass size (max_enc_patches). */
int64_t gen_patches;
} RadArchProbe;
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
@@ -636,6 +820,18 @@ int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
* UTF-8; NULL reads as "". The engine copies what it needs while loading, so static storage in
* the plugin is enough.
*
* The other family is a call written as a name and ONE object holding its arguments
* (args_form = RAD_CHAT_ARGS_OBJECT):
*
* [call_open] name_prefix NAME name_suffix { key: value, ... } [call_end] [call_close]
*
* The object is JSON, or a dialect of it: strings between object_string_open and
* object_string_close, their text verbatim, and keys written bare (object_bare_keys). Gemma 4 is
* "<|tool_call>" / "<tool_call|>", "call:" / "" / "", strings "<|\"|>" / "<|\"|>", bare keys --
* `<|tool_call>call:get_weather{city:<|"|>Paris<|"|>}<tool_call|>` -- and the reply's JSON
* arguments are that object respelled as JSON. The arg_* fields describe tagged arguments only
* and are empty in this family.
*
* THE STRUCT GROWS AT ITS END AND NEVER CHANGES IN THE MIDDLE. `struct_size` is
* sizeof(RadChatFormat) as the plugin was compiled; the engine reads only the fields that size
* covers and treats the rest as zero, so a plugin built against an older header keeps loading
@@ -657,6 +853,11 @@ enum {
RAD_CHAT_THINK_NEVER = 2 /* the model opens its own block, if any */
};
enum {
RAD_CHAT_ARGS_TAGGED = 0, /* each argument in its own tags: arg_prefix .. arg_value_suffix */
RAD_CHAT_ARGS_OBJECT = 1 /* one object after the name, in JSON or the object_* dialect */
};
typedef struct RadChatFormat {
uint32_t struct_size;
const char* name; /* for the startup log; NULL is the plugin's name */
@@ -696,6 +897,23 @@ typedef struct RadChatFormat {
* reply is read unconstrained. */
const char* const* triggers;
uint32_t n_triggers;
/* RAD_CHAT_ARGS_*: how a call's arguments are written. Zero is the tagged family above. With
* RAD_CHAT_ARGS_OBJECT, name_suffix may be empty -- the name then ends where the object
* begins -- and so may call_end, when the object's own closing brace ends the call. */
uint32_t args_form;
/* RAD_CHAT_ARGS_OBJECT: a string delimiter of the object's dialect besides JSON's `"`. What
* stands between the two is the string, verbatim -- the dialect has no escapes. NULL: the
* object writes JSON strings only. */
const char* object_string_open;
const char* object_string_close;
/* RAD_CHAT_ARGS_OBJECT: non-zero when the dialect writes a key bare, `key:value`. */
uint32_t object_bare_keys;
/* Non-zero: a reasoning block may open again LATER in the reply -- after its answer, between
* calls -- and is read as reasoning there as well, and a reasoning_close with no block open
* is not part of the answer. Zero: only a block the reply starts with is reasoning. */
uint32_t reasoning_anywhere;
} RadChatFormat;
/* Return the format, or NULL for "derive it from the chat template". Called once at startup. */
+39 -2
View File
@@ -73,6 +73,17 @@
* [S x cols] lists stage s's pairs as (pairs[s][2p], pairs[s][2p+1]), TABLE "t.angle"
* f32 [S x cols/2] their angles, and a row vector's pair (a, b) at angle t becomes
* (a cos t + b sin t, b cos t - a sin t). ParoQuant's scaled pairwise rotation.
* A weight whose row PARTS were rotated independently (a fused gate_up, a fused
* q|k|v: each projection has its own rotation) carries P parts: TABLE "t.part" i32
* [1 x P] holds the END ROW (exclusive) of each part, and the other tables stack the
* parts in order -- t.pairs and t.angle S rows a part (P*S rows), t.scale one row a
* part (P rows). Without "t.part" the weight is one part. The stages of a part are
* applied in table order, and a part's pairs address columns of the whole row.
* TABLE "t.dense" f16 [P * cols/128 x 128*128], where a weight carries it, is the same
* rotation composed: row p * (cols/128) + g holds part p's stages over the 128 columns
* of group g as one matrix, element j * 128 + i the output j for the unit input e_i,
* composed exactly (f64) and rounded to f16. It is stored because a kernel that
* applies the rotation as a matrix must not compute one at load (rad_abi.h).
*
* Pure C, header-only, like the rest of abi/.
*/
@@ -213,6 +224,15 @@ static inline int64_t rad_enc_fwht(const RadEncoding* e) {
return (int64_t)n;
}
/* The number of independently rotated row parts of a "givens" weight: the width of its "t.part"
* table, or 1 without one. 0 when the table is malformed. */
static inline int64_t rad_enc_givens_parts(const RadEncoding* e) {
const int i = rad_enc_find(e, "t.part");
if (i < 0) return 1;
return e->plane[i].kind == RAD_PLANE_TABLE && e->plane[i].extent[0] == 1 &&
e->plane[i].extent[1] >= 1 ? e->plane[i].extent[1] : 0;
}
/* Byte-for-byte equality, which is what two encodings agreeing means: the strings are
* zero-padded by construction, so there is nothing a memcmp could see that a reader cannot. */
static inline int rad_enc_equal(const RadEncoding* a, const RadEncoding* b) {
@@ -329,8 +349,25 @@ static inline int rad_enc_valid(const RadEncoding* e) {
if (!t[0]) return 1;
if (!strncmp(t, "fwht", 4)) return rad_enc_fwht(e) > 0;
if (!strcmp(t, "perm")) return rad_enc_find(e, "t.perm") > 0;
if (!strcmp(t, "givens"))
return rad_enc_find(e, "t.pairs") > 0 && rad_enc_find(e, "t.angle") > 0;
if (!strcmp(t, "givens")) {
const int ip = rad_enc_find(e, "t.pairs"), ia = rad_enc_find(e, "t.angle");
const int is = rad_enc_find(e, "t.scale");
const int64_t np = rad_enc_givens_parts(e);
if (ip <= 0 || ia <= 0 || np < 1) return 0;
if (e->plane[ip].kind != RAD_PLANE_TABLE || e->plane[ia].kind != RAD_PLANE_TABLE) return 0;
if (e->plane[ip].extent[0] % np || e->plane[ia].extent[0] != e->plane[ip].extent[0]) return 0;
if (e->plane[ia].extent[1] * 2 != e->plane[ip].extent[1]) return 0;
if (is > 0 && (e->plane[is].kind != RAD_PLANE_TABLE || e->plane[is].extent[0] != np ||
e->plane[is].extent[1] != e->plane[ip].extent[1])) return 0;
{
const int id = rad_enc_find(e, "t.dense");
if (id > 0 && (e->plane[id].kind != RAD_PLANE_TABLE || e->plane[id].dtype != RAD_F16 ||
e->plane[ip].extent[1] % 128 ||
e->plane[id].extent[0] != np * (e->plane[ip].extent[1] / 128) ||
e->plane[id].extent[1] != 128 * 128)) return 0;
}
return 1;
}
return 0;
}
+6 -1
View File
@@ -152,9 +152,14 @@ typedef struct RadVocabHeader {
int32_t bos, eos, eot, pad_id, unk, sep;
uint32_t add_bos, add_eos;
rad_stroff chat_template;
uint64_t reserved[4];
uint64_t flags; /* RAD_VOCAB_*; zero in a file written before the field existed */
uint64_t reserved[3];
} RadVocabHeader;
/* BPE: a pre-token that is already a vocabulary entry is emitted whole instead of merged
* (tokenizers' `ignore_merges`). LFM2's vocabulary sets it. */
enum { RAD_VOCAB_IGNORE_MERGES = 1u << 0 };
enum { RAD_TT_NORMAL = 1, RAD_TT_UNKNOWN = 2, RAD_TT_CONTROL = 3,
RAD_TT_USER_DEFINED = 4, RAD_TT_BYTE = 6 };
+49
View File
@@ -0,0 +1,49 @@
#ifndef RAD_PHILOX_H
#define RAD_PHILOX_H
/* Counter-based Gaussian noise, the one definition every kernel library computes it by, so an
* image's starting latent is a function of its seed and of nothing else: not the batch it shares a
* pass with, not the rank count, not the order its rows are visited in.
*
* Element e of a seed's stream is Philox4x32-10 at counter (e / 4, 0) keyed by the 64-bit seed,
* its four words made uniform in (0, 1) as ((w >> 8) + 0.5) * 2^-24 and paired by Box-Muller --
* words 0 and 1 give elements 4g and 4g+1 (r cos t, r sin t), words 2 and 3 give 4g+2 and 4g+3.
* f32 throughout. A library's libm may differ from another's in the last place of log, cos and
* sin, so two libraries agree to a tolerance and each agrees with itself exactly. */
#include <stdint.h>
#include <math.h>
#if defined(__HIPCC__)
#define RAD_PHILOX_HD __host__ __device__ __forceinline__
#else
#define RAD_PHILOX_HD static inline
#endif
RAD_PHILOX_HD void rad_philox4x32_10(uint32_t c[4], uint32_t k0, uint32_t k1) {
const uint32_t M0 = 0xD2511F53u, M1 = 0xCD9E8D57u, W0 = 0x9E3779B9u, W1 = 0xBB67AE85u;
for (int r = 0; r < 10; ++r) {
const uint64_t p0 = (uint64_t)M0 * c[0], p1 = (uint64_t)M1 * c[2];
const uint32_t hi0 = (uint32_t)(p0 >> 32), lo0 = (uint32_t)p0;
const uint32_t hi1 = (uint32_t)(p1 >> 32), lo1 = (uint32_t)p1;
const uint32_t n0 = hi1 ^ c[1] ^ k0, n2 = hi0 ^ c[3] ^ k1;
c[0] = n0; c[1] = lo1; c[2] = n2; c[3] = lo0;
k0 += W0;
k1 += W1;
}
}
/* Element `e` of the standard-normal stream of `seed`. */
RAD_PHILOX_HD float rad_philox_normal(uint64_t seed, uint64_t e) {
const uint64_t g = e >> 2;
uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), 0u, 0u };
rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32));
const int j = (int)(e & 3u);
const uint32_t wa = c[(j >> 1) * 2], wb = c[(j >> 1) * 2 + 1];
const float ua = ((float)(wa >> 8) + 0.5f) * (1.0f / 16777216.0f);
const float ub = ((float)(wb >> 8) + 0.5f) * (1.0f / 16777216.0f);
const float r = sqrtf(-2.0f * logf(ua));
const float t = 6.28318530717958647692f * ub;
return (j & 1) ? r * sinf(t) : r * cosf(t);
}
#endif /* RAD_PHILOX_H */
+133 -4
View File
@@ -206,10 +206,16 @@ typedef struct RadBatch {
const int32_t* mm_rows; /* [n_mm_rows] device: index into this pass's tokens */
const void* mm_embd; /* [n_mm_rows, n_embd] bf16 device */
/* THE ENCODER PASS. Non-zero `enc` runs the plugin's declared encoder (rad_declare_encoder)
* and nothing else: no token rows, no KV, no logits. Its input is a list of patches, already
* resized, normalised and cut by the processor, and its output is the encoder's declared
* `out` buffer, one row per `merge` patches, which the core reads back after the pass.
/* THE ENCODER PASS. Non-zero `enc` runs a declared encoder (rad_declare_encoder) and nothing
* else: no token rows, no KV, no logits. It is that encoder's `modalities` -- RAD_MM_AUDIO
* for an audio encoder, the image/video mask for the other -- so a program that declared two
* knows which to run. Its input is a list of patches, already resized, normalised and cut by
* the processor, and its output is the encoder's declared `out` buffer, one row per `merge`
* patches, which the core reads back after the pass.
*
* An AUDIO pass's patches are feature frames and its coordinates are 1-D: plane 0 the frame's
* index in its clip, plane 1 whether the frame is real (1) or the zero padding that makes the
* clip whole output rows (0), plane 2 the clip's real frames and plane 3 its staged ones.
*
* Patches are grouped into SEGMENTS -- one per image, and one per temporal group of a video
* -- and attention runs within a segment. `enc_coord` gives each patch its place in its
@@ -223,8 +229,95 @@ typedef struct RadBatch {
int64_t enc_n_seg;
const int32_t* enc_cu; /* [enc_n_seg + 1] device: segment boundaries in patches */
int32_t enc_max_seg; /* host: the longest segment, which bands the attention */
/* ================================================ image generation */
/* A GENERATOR PASS (rad_declare_generator): RAD_GEN_PASS_*, and `gen_b` what it carries. 0 on
* every step of a program that declared no generator. */
int32_t gen;
const struct RadGenBatch* gen_b;
} RadBatch;
/* WHAT A GENERATOR PASS CARRIES beside the step batch's own fields, which keep their meanings:
*
* COND ONE sequence. `token_ids`, `positions` and `rope_pos` are its conditioning prompt, the
* encoder's input (`enc_*`) is the prompt's reference pictures and `mm_rows` the prompt
* rows the encoder's output rows replace, as on any media step. What is here lays out
* the generator's sequence over those rows and writes it into the KV group.
* DENOISE one entry per (image, conditioning): `cu_seqlens` bounds each entry's latent rows,
* and the KV group's `block_table` and `seqused` name its conditioning's sequence.
* DECODE one image.
*
* Every pointer is device memory unless the name ends in _h. */
typedef struct RadGenBatch {
/* ---- COND */
int64_t rows; /* the generator's rows for this sequence */
/* Where each row comes from: >= 0 the prompt row of that index (the conditioning network's
* output there), < 0 the reference latent row -(1 + src). [rows] */
const int32_t* src;
/* Rotary positions, three components a row. On a COND pass they are laid out SEGMENT BY
* SEGMENT: segment s's [3, length] component-major block starts at element 3 * seg_h[s], so a
* segment's positions are one dense operand. On a DENOISE pass, [3, n_tok] component-major,
* the latent rows'. */
const int32_t* rope;
/* The sequence in SEGMENTS: rows [seg_h[s], seg_h[s+1]), each a picture (`seg_bidi_h` 1, its
* rows attend to each other both ways) or a run of text (0, causal). A segment is never split
* and attends to every segment before it. `seg` is the same offsets on the device; `seg_cu`
* is [n_seg, 2], segment s's own cu_seqlens {0, length}, and `seg_start` [n_seg] its first
* row -- the keys before it, which is its `seqused` when it is run on its own. */
int64_t n_seg;
const int32_t* seg;
const int32_t* seg_h;
const int32_t* seg_bidi_h;
const int32_t* seg_cu;
const int32_t* seg_start;
/* [rows] the KV slot each row is stored at. */
const int32_t* slot_mapping;
/* PIXELS the decoder's encoder takes: `n_px` blocks of `px` [*, pixel_channels] bf16 in
* [-1, 1], block b at pixel px_h[3b], px_h[3b+1] high and px_h[3b+2] wide. The reference
* pictures, in prompt order, and -- with `inpaint` -- a last block that is no reference but
* the picture being repainted, at the size being made: its latents go to the lanes below. */
int64_t n_px;
const void* px;
const int32_t* px_h;
/* [n_px, 2] each block's own cu_seqlens over its latent tokens: {0, (h / scale) (w / scale)}. */
const int32_t* px_cu;
int32_t inpaint;
/* [image tokens] f32: 1 where the image is repainted, 0 where the picture is kept. */
const float* inp_mask;
/* The lanes this conditioning's images run in, which take the repainted picture's latents. */
int64_t n_lane;
const int32_t* lane_h;
/* ---- DENOISE, one value per entry ([n_seq]); on a COND pass `sigma` is one 0, the time
* the conditioning is modulated at */
const float* sigma; /* where the entry's latent is */
const float* sigma_next; /* where this step takes it */
const float* cfg; /* guidance: v = neg + cfg * (pos - neg); 1 without a pair */
/* The entry holding this image's NEGATIVE conditioning, or -1 for none; -2 marks an entry
* that IS one, whose rows serve another entry's step and whose lane it does not move. */
const int32_t* pair;
const int32_t* lane; /* the plugin's lane the image's latent lives in */
const int32_t* lane_dh; /* ... the same, host */
/* RAD_GEN_F_*. */
const int32_t* flags;
/* [n_seq, 2] the image's noise seed, low word first. */
const uint32_t* seed;
/* ---- DECODE */
int32_t dec_lane;
int32_t dec_height, dec_width; /* pixels */
int32_t dec_preview; /* the lane's preview latent, not its state */
} RadGenBatch;
/* An entry's flags on a DENOISE pass. */
enum {
RAD_GEN_F_FIRST = 1, /* the image's first step: its latent is the noise its seed draws */
RAD_GEN_F_INPAINT = 2, /* repaint: after the step, the kept region goes back to the picture,
* noised to sigma_next with the image's own noise */
RAD_GEN_F_PREVIEW = 4 /* write the step's estimate of the clean latent to the lane's preview */
};
/* ================================================================== operands */
/* RAD_OPK_KV names a KV group's pool rather than a buffer: attention and kv_store take the cache
* as an operand, and RadKVGroupBatch carries the slot mapping and the block table but not the
@@ -370,6 +463,42 @@ int rad_route_report(RadCtx* c, int layer, const RadRouting* r);
* `n_expert` -- the router then writes its own buffer and reports that. */
int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert);
/* THE NEXT-LAYER EXPERT PREFETCH, at decode. A routed layer names the next routed layer at its router
* input; the core applies that layer's router to this layer's input rows, takes the experts the next
* layer is likeliest to route that sit in the pinned host pool, and copies them onto the card while
* the rest of this layer runs. Just before the next layer's routed GEMMs it points their weight-table
* entries at the copies, where the copies have landed and the entries still name the pool slots they
* were made from. It changes no result: a copy holds the bytes of its slot. It is on where the
* placement keeps experts in a pinned pool and the device backend can spare a DMA engine for it, and
* a pass of more than 16 rows makes no prediction; the three calls are no-ops otherwise.
*
* `parts` names, for each of the next layer's experts, the weights its unit is made of (at most four,
* e.g. the gate-up matrix and its scales and the down matrix and its scales), as the routed GEMMs
* read them through weight tables; 0 where an expert has fewer or none. An expert is prefetched only
* where each of its weights is in exactly one table and all of them sit in one pool slot. The arrays
* must outlive the context; the core reads the routing counts only to rank and count, never to choose
* an expert's bytes. `layer` is the next layer's index as rad_route_report and
* rad_expert_prefetch_step name it; `router` is its router, [n_expert, n_embd] bf16. */
typedef struct RadPrefetchNext {
int layer;
rad_weight router;
int64_t n_expert, top_k;
int64_t n_parts;
const rad_weight* parts; /* [n_expert * n_parts] */
const int32_t* count_at; /* [n_expert]: where the expert's count is in the layer's routing
counts (rad_route_counts), -1 for nowhere; null when at its index */
} RadPrefetchNext;
/* At this layer's router input: `h` rows [r0, r0 + rows) of n_embd bf16, read in place on another
* stream -- the block must not overwrite them before this layer's routed GEMMs. */
int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows,
int64_t n_embd);
/* After this layer's routed down GEMM: the copies cross the link from here, under the next layer's
* attention rather than under this layer's own streamed experts. */
int rad_expert_prefetch_mark(RadCtx* c);
/* Ahead of `layer`'s routed GEMMs, on every routed layer of every pass. */
int rad_expert_prefetch_step(RadCtx* c, int layer);
/* A weight's pointer, for the rare op that genuinely needs one (a plugin-private kernel invoked
* outside the op vocabulary). Waits on the mover. Using this forfeits nothing except the ability
* to move that weight while the pointer is live, so it is legal only within one issue. */
+2 -1
View File
@@ -44,7 +44,8 @@ enum {
RAD_SP_PENALTY = 1 << 1, /* any of rep / freq / pres is non-identity */
RAD_SP_MASK = 1 << 2, /* a grammar is constraining this sequence this step */
RAD_SP_XTC = 1 << 3,
RAD_SP_DRY = 1 << 4
RAD_SP_DRY = 1 << 4,
RAD_SP_LOGPROBS = 1 << 5 /* `sample_logprobs` summarises this row's raw logits */
};
/* One row per sampled position. Laid out so the 8-byte fields are aligned and the struct has no
+19
View File
@@ -168,6 +168,11 @@ struct AttnGatedFP8 {
bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* The pass's K and V into the cache and nothing else: no query, no attention, no output. What a
* pass that only leaves the layer's state behind asks for -- the MTP head's history pass over
* a prompt chunk with no row that drafts. The keys are the ones step() stores: the same
* projection, norm, rotation and store. */
void store_kv(RadCtx* c, const RadBatch* batch) const;
};
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -470,6 +475,20 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
return RAD_OK;
}
inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (!ext_in) nq_h.step(c, T);
if (op_fill) return; /* the attention-zero rank holds no heads to store */
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_kv_store,
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
}
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
+78 -79
View File
@@ -65,8 +65,10 @@
* The head reads the 2-BIT copy of the lm_head, exactly as the MTP head does and for exactly the
* reason rad_block_mtp_fp8.h gives at op_dlogits: a draft is a proposal, the target verifies every
* one of them with its own untouched head, and speculative decoding is distribution-preserving --
* so a coarser draft costs acceptance and cannot change a token the model emits. Here it also buys
* something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
* so a coarser draft costs acceptance and cannot change a token the model emits. Its candidates
* are then rescored against the target's own head where that head is fp8 or int8 (op_drerank), so
* the coarseness costs only which candidates are proposed, not how they are ranked. The 2-bit head
* also buys something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
* global without an all-gather and the selector's codebooks can be indexed directly.
*
* ============================== THE NORMS ARE PLAIN ==============================
@@ -230,10 +232,11 @@ struct Dflash2 {
/* model-scope weights.
*
* THE SIX LINEARS ARE FP8 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares each as
* block fp8 and the recipe makes it so -- and the reason is bytes: the drafter is read WHOLE on
* every decode step, which makes it one of the largest single items in the decode budget
* after the trunk's own GEMMs.
* THE SIX LINEARS ARE FP8 OR MXFP4 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares
* each as block fp8 or OCP-MXFP4, whichever the recipe made it -- and the reason is bytes: the
* drafter is read WHOLE on every decode step, which makes it one of the largest single items in
* the decode budget after the trunk's own GEMMs. On Qwen3.8-27B at depth 7, MXFP4 rounded to
* nearest accepts ~1% fewer tokens a step than fp8 and takes ~1.5 ms off a ~34 ms step.
* Nothing it computes can change an emitted token, because every draft is verified against the
* trunk exactly; the only thing quantising it can move is acceptance. */
DenseFP8 w_fc{};
@@ -284,6 +287,14 @@ struct Dflash2 {
/* head and selector */
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
rad_op op_drerank = 0; /* the candidates rescored against the target's head */
/* THE TARGET'S lm_head, set by the plugin before declare when its plane is one logit_rerank
* reads (fp8 or int8 rows); 0 leaves the coarse head's own scores as the candidates'. */
rad_weight w_lm = 0;
/* How many candidates the coarse head proposes for the rerank: logit_rerank's and row_topk's
* ceiling. Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
static constexpr int64_t kRerankR = 32;
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
rad_op op_hp = 0, op_sel = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
@@ -471,8 +482,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.q}, {w.attn});
/* ---------------------------------------------------------------- the context pass */
/* EVERY LINEAR HERE IS `fp8a8`, and every activation that feeds one gets a `quant_act_fp8` in
* front of it. The weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
/* EVERY LINEAR HERE IS `fp8a8` -- or `mxfp4a8` where the recipe made the drafter 4-bit; DenseFP8
* reads which off the container and declares the GEMM (`gemm()`), and either one reads the
* same E4M3 pair -- and every activation that feeds one gets a `quant_act_fp8` in
* front of it. The fp8 weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
* why), and there is no `fp8a16` band anywhere in this block: that kernel is M <= 1, and
* neither pass here ever runs at one row -- a context pass is a committed chunk and a query
* pass is `block` rows by construction.
@@ -489,12 +502,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
RAD_INT("K", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_fc.w, w_fc.s)),
{w.srcq, w.srcs}, {w.c});
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
/* IN PLACE. Safe for any implementation that computes a row's scale before writing the row,
* which none can avoid doing; the per-head q/k norms below run in place for the same reason. */
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
@@ -515,18 +523,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
/* TWO OPS OF THE SAME SHAPE, one per weight. An op's declared weight list is what gives a
* weight its prefetch interval and its residency class, so two weights want two ops even
* where one would issue both. */
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.cq, w.cs}, {w.ck});
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.cq, w.cs}, {w.cv});
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
@@ -603,24 +601,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_acp[i])),
{w.h}, {w.coef});
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
{w.h2q, w.h2s}, {w.q});
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
{w.h2q, w.h2s}, {w.k});
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
{w.h2q, w.h2s}, {w.v});
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h2q, w.h2s}, {w.q});
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h2q, w.h2s}, {w.k});
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.h2q, w.h2s}, {w.v});
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
@@ -633,12 +616,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.k});
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
{w.atq, w.ats}, {w.h});
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h});
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
@@ -650,12 +628,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fcp[i])),
{w.h}, {w.coef});
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
{w.h2q, w.h2s}, {w.gate_up});
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
/* THE SAME FOLD THE TRUNK'S MLP HAS, over the same weights and into the same activation;
* rad_block_mlp_fp8.h declares it beside the pair for the same reason. Unfused, a layer
* runs gate_up -> silu_mul -> quant, which is two extra launches and two extra passes over
@@ -667,7 +640,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* because M > 64 is a refusal in the kernel and not a slower path. */
{
const int64_t hi = qrows < 64 ? qrows : 64;
if (hi > 0) {
if (hi > 0 && !w_gu[i].mx) { /* the fold is an fp8a8 tile; an MXFP4 gate_up takes the pair */
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd),
@@ -678,12 +651,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
if (op_gug[i]) gated_rows = hi;
}
}
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
{w.ffq, w.ffs}, {w.h});
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
}
/* The convolutions. `block_size` is the QUERY BLOCK -- the mask that kills the shifted tap at
@@ -789,31 +757,56 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
* replicated, so that graph is the one it always was -- an optional parameter present with
* the value 0 is not the same declaration as an absent one. */
const bool rerank = w_lm && (dh_shard || g.world <= 1); /* see op_drerank below */
if (!rerank) top_w = cfg.sel_topk;
op_dtopk = dh_shard
? rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("R", cfg.sel_topk), RAD_INT("vocab_off", g.vocab_off),
RAD_INT("R", top_w), RAD_INT("vocab_off", g.vocab_off),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary, w.dpair})
: rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("R", cfg.sel_topk), RAD_STR("dtype", g.dtype)),
RAD_INT("R", top_w), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary});
/* THE CANDIDATES ARE RESCORED EXACTLY when the target's head can be read row by row. The
* coarse head proposes its top kRerankR, `logit_rerank` scores those against the target's own
* fp8 head and re-sorts them, and the selector reads the best sel_topk of that order -- the
* candidate set and the unary logits the drafter was trained against, at kRerankR rows of the
* weight a draft row instead of a second, finer copy of the head. On Qwen3.8-27B the 2-bit
* head's own top-1 matches the exact head's on 76% of draft rows and the rescored one on all of
* them; served at depth 7 that is the 4-bit head's speed at half its bytes (330 MiB).
*
* Sharded, each rank rescores only ids it owns (row_topk reports this rank's slice), and the
* gather and merge below then rank exact values. A replicated draft head above one rank
* proposes ids another rank owns, so it keeps its own scores. */
if (rerank) {
op_drerank = RAD_OP(b, "logit_rerank",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
RAD_INT("n_vocab", head_rows(g)), RAD_INT("n_embd", g.n_embd),
RAD_INT("vocab_off", g.vocab_off), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_lm));
if (!op_drerank) return RAD_E_INVAL;
rad_buf rd[2] = { w.sel_h, w.cand };
rad_buf wr[3] = { w.cand, w.unary, w.dpair };
rad_op_reads (b, op_drerank, rd, 2);
rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
}
if (dh_shard) {
/* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side --
* `row_topk_merge` reads one row at one row stride, the same reason the sampler's own
* candidate gather carries `row`. */
op_dgather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * cfg.sel_topk * 2),
RAD_INT("numel", srows * top_w * 2),
RAD_STR("dtype", "f32"),
RAD_INT("row", cfg.sel_topk * 2)),
RAD_INT("row", top_w * 2)),
RAD_NOWEIGHTS),
{w.dpair}, {w.dgath});
op_dmerge = rw(b, RAD_OP(b, "row_topk_merge",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", cfg.sel_topk),
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
@@ -851,16 +844,16 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
* rows. */
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.c, T), RAD_NONE, RAD_NONE);
brows(w.c, T), RAD_NONE, w_fc.bref());
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
@@ -898,11 +891,11 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv,
brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
@@ -919,7 +912,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
brows(w.attn, T));
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
/* BEFORE the closing convolution, not after. The convolution is linear in its input and
* its coefficients come from the replicated pre-attention norm, so either order is the
* same arithmetic -- and reducing first keeps the residual stream's contract ("what the
@@ -941,13 +934,12 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_NONE);
} else {
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
RAD_NONE);
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE, w_gu[i].bref());
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
@@ -980,15 +972,22 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
if (op_dmerge) {
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
brows(w.dpair, S));
if (op_drerank)
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.cand, S),
brows(w.cand, S), brows(w.unary, S), brows(w.dpair, S));
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
RAD_ISSUE_N(c, op_dmerge, S, brows(w.dgath, S), brows(w.cand, S), brows(w.unary, S));
} else {
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
RAD_NONE);
if (op_drerank)
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.cand, S),
brows(w.cand, S), brows(w.unary, S), RAD_NONE);
}
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
RAD_ISSUE_N(c, op_sel, batch->n_seq, brows(w.cand, S), brows(w.unary, S), brows(w.hp, S),
RAD_ISSUE_N(c, op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
brows(w.tokens, batch->n_seq));
}
+3 -1
View File
@@ -275,7 +275,9 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
* all of q, all of k and a third of v, a well-formed wrong model. */
RAD_ARCH_TRY(in.declare(b, nm, g, nm.f("blk.%d.ssm_inz", l), conv_dim + v_dim, g.n_embd,
RAD_SHARD_ROW, grp_layer(l), { s.in_qkv, s.in_z }, w.h, w.in.x, 0,
{ cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() }));
{ cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() }, 0, 0,
/* a rotated weight was rotated per CHECKPOINT tensor: q|k|v, then z */
{ 2 * cfg.k_dim() + cfg.v_dim(), cfg.v_dim() }));
if (cfg.uneven()) {
/* THIS RANK'S HEADS OF EACH PART, in the container's rows: q and k by K head, v and z by
* V head. The scale plane of a row shard has the same rows (its blocks run along K). */
+4 -2
View File
@@ -90,6 +90,8 @@ struct MlpFP8 {
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;
/* The block over the first `T` rows of its buffers (MoeFP8::step_rows says who asks). */
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
/* One row slice of the whole block; `rows <= 0` means the rest of the step. */
void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
};
@@ -123,10 +125,10 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
/* The fold, over the same weights and into the same activation the pair writes. Not
* RAD_ARCH_TRY: a plugin without the row is the ordinary case and the pair still runs. It
* multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold -- and neither
* has an MXFP4 one: libr4d's gated fold is an fp8a8 tile, and the pair serves it. */
* has an MXFP4 one: libr4d's gated fold is an fp8a8 tile, and the pair serves it (a rotated 5-bit one neither). */
{
const int64_t hi = g.max_tok < 64 ? g.max_tok : 64;
if (hi > 0 && !gate_up.bf16 && !gate_up.mx) {
if (hi > 0 && !gate_up.bf16 && !gate_up.mx && !gate_up.paro5) {
op_gated = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", gate_up.N),
RAD_INT("K", gate_up.K),
+49 -1
View File
@@ -387,6 +387,16 @@ struct MoeFP8 {
* `pff`, and down into the same `edn` rows the quantised down left zero. */
std::vector<int64_t> prot;
const char* prot_list = nullptr;
/* THE NEXT-LAYER EXPERT PREFETCH (rad_expert_prefetch). `xp_next` is the next routed layer, which
* this one predicts for at its router input -- the architecture links them once every layer is
* declared. `xp` is what this layer is to the one before it: its router, and each of the model's
* experts' unit -- the four handles its place's tables hold, and its place in the routing counts.
* Quantised experts only: a bf16 layer and the protected experts are not described, and a layer
* with no description is predicted for by nobody. */
const MoeFP8* xp_next = nullptr;
RadPrefetchNext xp{};
std::vector<rad_weight> xp_parts;
std::vector<int32_t> xp_count_at;
int64_t n_reg = 0;
/* How many weight-table classes the quantised GEMMs take: 2 by parity (`moe_gemm_q`), or 4 by
* number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4). */
@@ -461,6 +471,10 @@ struct MoeFP8 {
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;
/* The block over the first `T` rows of its buffers, which a pass that runs it for fewer rows
* than its batch has asks for: the MTP head's history pass, which reads the head's output only
* at its drafting rows. */
void step_rows(RadCtx* c, int64_t T) const;
/* One pass of at most `c.rows` tokens. */
void pass(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
void shared_up(RadCtx* c, int64_t T, int64_t r0, int64_t rows, bool gate_done = false) const;
@@ -1469,6 +1483,29 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h.x}, {w.x});
/* The layer as the prefetch sees it, by the model's expert number -- what the router ranks. */
if (!c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) {
const int64_t na = c.n_expert_all;
xp_parts.assign((size_t)(na * 4), 0);
xp_count_at.assign((size_t)na, -1);
for (int64_t s = 0; s < n_reg; ++s) {
const int64_t e = c.expert_base + reg[(size_t)s];
if (e < 0 || e >= na) continue;
xp_parts[(size_t)(e * 4 + 0)] = w_gu[(size_t)s];
xp_parts[(size_t)(e * 4 + 1)] = w_gus[(size_t)s];
xp_parts[(size_t)(e * 4 + 2)] = w_dn[(size_t)s];
xp_parts[(size_t)(e * 4 + 3)] = w_dns[(size_t)s];
xp_count_at[(size_t)e] = (int32_t)s;
}
xp.layer = layer;
xp.router = w_router;
xp.n_expert = na;
xp.top_k = c.top_k;
xp.n_parts = 4;
xp.parts = xp_parts.data();
xp.count_at = xp_count_at.data();
}
return RAD_OK;
}
@@ -1516,6 +1553,10 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
* sharing pool (see declare), so issuing it ahead of its declared position moves no byte. */
/* THE ROUTED ARM. */
/* THE NEXT ROUTED LAYER'S PREDICTION, from this router's input, read in place behind the router
* on the compute stream (rad_expert_prefetch). A failure there costs the prediction, nothing else. */
if (xp_next && xp_next->xp.n_parts > 0)
(void)rad_expert_prefetch(c_, &xp_next->xp, w.h.x, r0, rows, g.n_embd);
/* THE COUNTS GO STRAIGHT INTO THE CORE'S ROW for this layer when it keeps one, so the
* report at the end of step() hands them over with no copy -- otherwise a card-local blit
* a routed layer, a whole dependent dispatch for a kilobyte. */
@@ -1564,6 +1605,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
* 2 * i + q, and each parity is its own pair of table operands; at four classes expert
* 4 * i + q, class q holding ceil((n_reg - q) / 4). */
const int64_t n4[4] = { (n_reg + 3) / 4, (n_reg + 2) / 4, (n_reg + 1) / 4, n_reg / 4 };
/* The layer before predicted for this one: its copies go into the tables here, where they landed. */
(void)rad_expert_prefetch_step(c_, layer);
if (c.expert_bf16)
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),
@@ -1608,6 +1651,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
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));
/* This layer's streamed experts are read: the next one's copies cross the link from here. */
(void)rad_expert_prefetch_mark(c_);
/* THE PROTECTED EXPERTS, over the trailing run of the offsets: their sorted rows are the
* ones the quantised down GEMM above zeroed as past its live count, and the down GEMM
* here writes them -- after it, which the shared `edn` orders. */
@@ -1733,7 +1778,10 @@ inline void MoeFP8::calib_experts_pass(RadCtx* c_, int64_t slots) const {
}
inline void MoeFP8::step(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
step_rows(c_, batch->n_tok);
}
inline void MoeFP8::step_rows(RadCtx* c_, int64_t T) const {
for (int64_t r0 = 0; r0 < T; r0 += c.rows) {
const int64_t n = (T - r0 < c.rows) ? (T - r0) : c.rows;
pass(c_, T, r0, n);
+39 -32
View File
@@ -288,6 +288,24 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
{w.c}, {w.x});
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn));
/* DRAFT ROUND 1'S ROWS OUT OF A HISTORY PASS (RadBatch::draft_out_ids), one a drafting
* sequence in round order, to the front of the residual stream `x` -- before the feed-forward,
* which then runs over those rows alone. Through `hout`, which is dead from the fc's read to
* the norm's write, because a gather in place could overwrite a row another sequence has yet to
* read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
RAD_ARCH_TRY(mlp.declare(b, nm, g, l, w.mlp, src.mlp));
op_norm = rw(b, RAD_OP(b, "rmsnorm",
@@ -297,22 +315,6 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
RAD_WEIGHTS(w_norm)),
{w.x}, {w.hout});
/* DRAFT ROUND 1'S ROWS OUT OF A HISTORY PASS (RadBatch::draft_out_ids), one a drafting
* sequence in round order, to the front of `hout` -- where the lm_head reads a round's rows
* and round 2 reads its input. Through `x`, which is dead once the norm has read it, because a
* gather in place could overwrite a row another sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* The trunk's lm_head, over the head's hidden state. Banded at the logits buffer's own extent
* rather than at `rows`: it runs over one row a drafting sequence. */
op_logits = rw(b, RAD_OP(b, "logits_gemm",
@@ -435,27 +437,32 @@ 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 THAT DRAFTS NOTHING ONLY LEAVES K AND V BEHIND, and they come from the
* block's input. The query, the attention, its output, the feed-forward, the norm and the
* lm_head compute the head's output, which only a drafting row reads -- and every prefill
* chunk but a prompt's last drafts nothing. `n_draft_out` is the batch's and the same on every
* rank, so a collective skipped here is skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) {
attn.store_kv(c, batch);
return;
}
attn.step(c, batch);
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave K and V behind, and the
* attention above has stored them. The feed-forward, the norm and the lm_head compute the
* head's output, which only a drafting row reads -- and every prefill chunk but a prompt's
* last drafts nothing. `n_draft_out` is the batch's and the same on every rank, so a
* collective the feed-forward would run is skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) return;
mlp.step(c, batch);
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.hout, T));
/* A history pass that drafts brings round 1's rows to the front first. */
int64_t L = T; /* the rows the lm_head runs over */
/* A HISTORY PASS THAT DRAFTS GOES ON WITH ITS DRAFTING ROWS ALONE. They are round 1, and
* nothing reads the head's output at any other row: the feed-forward, the norm and the lm_head
* would run over a whole prompt chunk for a handful of rows. So round 1's rows come to the
* front of `x` first, and everything after runs as a pass of those rows. */
int64_t L = T; /* the rows the stream goes on with */
if (r < 0) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hout), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.x, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.x, L), brows(w.hout, L));
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.x), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hout, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.hout, L), brows(w.x, L));
}
mlp.step_rows(c, L);
RAD_ISSUE(c, op_norm, brows(w.x, L), RAD_W(w_norm), brows(w.hout, L));
if (q2) {
/* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
* whole: there is no row slice of it that means anything. */
+46 -34
View File
@@ -292,6 +292,22 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
false, false, kArNone, hc_attn.op_ar_write != 0));
if (src.qsa.qk_proj)
RAD_ARCH_TRY(qsa.declare(b, nm, g, l, src.qsa, w.qsa, w.attn.h, qsa_bk));
/* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids), before the
* feed-forward, which then runs over them alone: gathered into `hin`, one row a drafting
* sequence in round order, and copied back to the front of `hw`. Two ops and not one because a
* gather in place could overwrite a row another sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hin}, {w.hw});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* The rotated expert input rides in this read, as it does on the trunk. */
HyperConn::Config mcfg = hc;
HyperConn::Wire mwire{w.hw, w.x, w.inj};
@@ -321,21 +337,6 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
/* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids): gathered into the
* carry, one row a drafting sequence in round order, and copied back to the front of `hw` for
* the mixer. Two ops and not one because a gather in place could overwrite a row another
* sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hin}, {w.hw});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* ---- the head's own mixer: the connection with no write half, which collapses its wide
* stream to the one hidden state the lm_head reads. No fp8 twin -- that input is bf16. */
@@ -523,40 +524,51 @@ 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(c, T, 0, T);
/* A HISTORY PASS THAT DRAFTS NOTHING ONLY LEAVES THE HEAD'S STATE BEHIND: the K and V of its
* rows and the indexer's block keys and tail, all of which come from the block's input. The
* query, the indexer's scores and selection, the attention, its output and everything after
* compute the head's stream, which only a drafting row reads. Every prefill chunk but a
* prompt's last is such a pass. `n_draft_out` is the batch's and the same on every rank, so
* the collectives skipped here are skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) {
qsa.store(c, attn.w.h, batch);
attn.store_kv(c, batch);
return;
}
/* THE INDEXER RUNS FIRST, because the attention reads its selection. It can: this block's
* input is normed and quantised by the connection above, so `w.h` is already what it will be
* when the attention runs. */
qsa.step(c, attn.w.h, batch);
attn.step(c, batch);
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave the head's state behind --
* the K and V the attention just stored and the indexer's block keys and tail -- and both are
* written above. Everything below computes the head's stream, which only a drafting row
* reads: the experts, the two connections around them and the lm_head. Every prefill chunk
* but a prompt's last is such a pass, so on those the head costs its attention alone.
* `n_draft_out` is the batch's and the same on every rank, so the collectives skipped here
* are skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) return;
hc_attn.write(c, T, 0, T);
hc_mlp.read(c, T, 0, T);
mlp.step(c, batch);
hc_mlp.write(c, T, 0, T);
/* THE CARRY, and only where a round after this one will read it. The last round of a group
* is followed by a trunk step. A history pass that drafts takes round 1's rows out of its own
* -- into the carry, and back to the front of `hw` for the mixer below. */
int64_t L = T; /* the rows the lm_head runs over */
/* A HISTORY PASS THAT DRAFTS GOES ON WITH ITS DRAFTING ROWS ALONE. They are round 1, and
* nothing reads the head's stream at any other row: the experts, their connection and the
* lm_head would run over a whole prompt chunk for a handful of rows. So round 1's rows come out
* of `hw` first -- gathered into `hin` and copied back to its front, two ops because a gather
* in place could overwrite a row another sequence has yet to read -- and everything after runs
* as a pass of those rows. */
int64_t L = T; /* the rows the stream goes on with */
if (r < 0) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hin, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
} else if (r < depth) {
RAD_ISSUE_N(c, op_carry, T, brows(w.hw, T), brows(w.hin, T));
}
hc_mlp.read(c, L, 0, L);
mlp.step_rows(c, L);
hc_mlp.write(c, L, 0, L);
/* THE CARRY, and only where a round after this one will read it. The last round of a group
* is followed by a trunk step; a history pass is round 1, followed by round 2 when the
* deployment drafts deeper. */
if (r < 0 ? depth > 1 : r < depth)
RAD_ISSUE_N(c, op_carry, L, brows(w.hw, L), brows(w.hin, L));
mixer.read(c, L, 0, L);
if (q2) {
/* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
+72 -8
View File
@@ -14,8 +14,11 @@
* x += fc2(gelu_tanh(fc1(LN2(x))))
* out = fc2'(gelu(fc1'(LN(x) viewed [P/merge^2, merge^2 * width]))) the patch merger
*
* which is transformers' Qwen3_5VisionModel with no deepstack taps (the checkpoints this tree
* serves list none, and one that did would be refused at declare). Every linear layer is
* which is transformers' Qwen3_5VisionModel. Qwen3-VL's DEEPSTACK taps -- the residual stream
* after named blocks, each through a merger of its own whose norm is taken AFTER the 2x2 view
* (over merge^2 * width), into rows added to the language model's hidden state after its first
* layers -- are declared only for a plugin that asks (declare's `deepstack`); one that does not is
* refused a tower with taps rather than served without them. Every linear layer is
* `gemm_nt_bias` with its activation and residual in the epilogue, each rounded where the
* reference's separate tensors are.
*
@@ -35,6 +38,7 @@
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
@@ -61,6 +65,16 @@ struct VisionTower {
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_mh = 0, b_mf = 0, b_out = 0;
char sec[48] = {};
/* DEEPSTACK: tap t is the residual stream after block `ds_layer[t]`, merged into `b_ds[t]`
* ([P / merge^2, n_embd], one row a merged token, in the order `b_out` holds them). */
enum { MAX_DS = 4 };
int n_ds = 0;
int ds_layer[MAX_DS] = {};
rad_weight ds_nw[MAX_DS] = {}, ds_nb[MAX_DS] = {}, ds_1w[MAX_DS] = {}, ds_1b[MAX_DS] = {};
rad_weight ds_2w[MAX_DS] = {}, ds_2b[MAX_DS] = {};
rad_op ds_ln[MAX_DS] = {}, ds_1[MAX_DS] = {}, ds_2[MAX_DS] = {};
rad_buf b_ds[MAX_DS] = {};
/* Is there a tower to declare: the container carries one and the deployment asked for media.
* `why` is set when the container carries one this block cannot serve. */
static bool present(const RadModelMeta* m) {
@@ -68,12 +82,12 @@ struct VisionTower {
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group);
int64_t model_embd, int first_group, bool deepstack = false);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
Names& nm, int64_t model_embd, int first_group) {
Names& nm, int64_t model_embd, int first_group, bool deepstack) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
@@ -105,14 +119,27 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
return RAD_E_INVAL;
}
/* DEEPSTACK -- tower layers feeding the language model's early layers directly -- is a second
* input path this block does not carry. Refused by name rather than dropped. */
* input path, and a plugin that does not consume it is refused the tower by name rather than
* served without it. */
const char* ds = rad_meta_gets(m, "vision_config.deepstack_visual_indexes", "");
for (const char* q = ds; q && *q; ++q)
if (*q >= '0' && *q <= '9') {
n_ds = 0;
for (const char* q = ds; q && *q;) {
if (*q < '0' || *q > '9') { ++q; continue; }
char* e = nullptr;
const long v = std::strtol(q, &e, 10);
q = e;
if (!deepstack) {
fprintf(stderr, "radiance: this vision tower has deepstack taps (%s), which this plugin "
"does not serve\n", ds);
return RAD_E_UNSUPPORTED;
}
if (n_ds >= MAX_DS || v < 0 || v >= depth) {
fprintf(stderr, "radiance: deepstack taps '%s' do not fit a %lld-block tower\n", ds,
(long long)depth);
return RAD_E_INVAL;
}
ds_layer[n_ds++] = (int)v;
}
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu_pytorch_tanh");
if (std::strcmp(act, "gelu_pytorch_tanh") && std::strcmp(act, "gelu")) {
fprintf(stderr, "radiance: vision_config.hidden_act '%s' is not served\n", act);
@@ -182,6 +209,17 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
m2_b = bw(nm.f("v.merger.fc2.bias"), nm.ckpt("model.visual.merger.linear_fc2.bias"), RAD_BF16, { n_embd }, grp_model());
if (!w_patch || !b_patch || !w_pos || !mn_w || !mn_b || !m1_w || !m1_b || !m2_w || !m2_b)
return RAD_E_INVAL;
for (int t = 0; t < n_ds; ++t) {
const char* pre = "model.visual.deepstack_merger_list";
ds_nw[t] = bw(nm.f("v.ds.%d.norm.weight", t), nm.ckpt("%s.%d.norm.weight", pre, t), RAD_BF16, { mm * width }, grp_model());
ds_nb[t] = bw(nm.f("v.ds.%d.norm.bias", t), nm.ckpt("%s.%d.norm.bias", pre, t), RAD_BF16, { mm * width }, grp_model());
ds_1w[t] = bw(nm.f("v.ds.%d.fc1.weight", t), nm.ckpt("%s.%d.linear_fc1.weight", pre, t), RAD_BF16, { mm * width, mm * width }, grp_model());
ds_1b[t] = bw(nm.f("v.ds.%d.fc1.bias", t), nm.ckpt("%s.%d.linear_fc1.bias", pre, t), RAD_BF16, { mm * width }, grp_model());
ds_2w[t] = bw(nm.f("v.ds.%d.fc2.weight", t), nm.ckpt("%s.%d.linear_fc2.weight", pre, t), RAD_BF16, { n_embd, mm * width }, grp_model());
ds_2b[t] = bw(nm.f("v.ds.%d.fc2.bias", t), nm.ckpt("%s.%d.linear_fc2.bias", pre, t), RAD_BF16, { n_embd }, grp_model());
if (!ds_nw[t] || !ds_nb[t] || !ds_1w[t] || !ds_1b[t] || !ds_2w[t] || !ds_2b[t])
return RAD_E_INVAL;
}
/* ---- activations. `mh` is the merger's input, declared at the MERGED width: the norm writes
* it as P rows of `width` and the first merger layer reads it as P/mm rows of mm * width,
@@ -244,6 +282,22 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
op_mln = rw(b, lnorm(P, mn_w, mn_b), { b_x }, { b_mh });
op_m1 = rw(b, gemm(R, mm * width, mm * width, "gelu", m1_w, m1_b), { b_mh }, { b_mf });
op_m2 = rw(b, gemm(R, n_embd, mm * width, "none", m2_w, m2_b), { b_mf }, { b_out });
/* A deepstack merger normalises AFTER the view, over a merged row: the same bytes as P rows of
* `width`, read as R rows of merge^2 * width. Its ops are declared here, after the tower, and
* issued between its blocks; their working planes are consumed before the next block runs.
* Each tap's OUTPUT is not -- it waits for the language model while the remaining blocks
* overwrite the tower's planes -- so it is PERSIST, outside the planner's sharing. */
for (int t = 0; t < n_ds; ++t) {
b_ds[t] = decl_b(b, nm.f("v.ds.%d.out", t), RAD_BF16, { R, n_embd }, RAD_BUF_PERSIST);
if (!b_ds[t]) return RAD_E_INVAL;
ds_ln[t] = rw(b, RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", mm * width),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(ds_nw[t], ds_nb[t])),
{ b_x }, { b_mh });
ds_1[t] = rw(b, gemm(R, mm * width, mm * width, "gelu", ds_1w[t], ds_1b[t]), { b_mh }, { b_mf });
ds_2[t] = rw(b, gemm(R, n_embd, mm * width, "none", ds_2w[t], ds_2b[t]), { b_mf }, { b_ds[t] });
}
if (!ctx->shape_probe) {
RadEncoderDecl e{};
@@ -282,7 +336,8 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
for (const Layer& l : L) {
for (size_t li = 0; li < L.size(); ++li) {
const Layer& l = L[li];
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
brows(b_qkv, Pn));
@@ -297,6 +352,15 @@ inline void VisionTower::step(RadCtx* c, const RadBatch* batch) const {
brows(b_ff, Pn));
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
brows(b_x, Pn), brows(b_x, Pn));
for (int t = 0; t < n_ds; ++t) {
if (ds_layer[t] != (int)li) continue;
RAD_ISSUE_N(c, ds_ln[t], Rn, brows(b_x, Pn), RAD_W(ds_nw[t]), RAD_W(ds_nb[t]),
brows(b_mh, Rn));
RAD_ISSUE_N(c, ds_1[t], Rn, brows(b_mh, Rn), RAD_W(ds_1w[t]), RAD_W(ds_1b[t]), RAD_NONE,
brows(b_mf, Rn));
RAD_ISSUE_N(c, ds_2[t], Rn, brows(b_mf, Rn), RAD_W(ds_2w[t]), RAD_W(ds_2b[t]), RAD_NONE,
brows(b_ds[t], Rn));
}
}
/* The merger norm writes P rows of `width` into a buffer declared at the merged width: the
* same bytes the next layer reads as P/mm rows. */
+360 -15
View File
@@ -58,6 +58,7 @@
#include <cstdlib>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
@@ -690,6 +691,28 @@ struct LinearFP8 {
* feeds an MXFP4 linear unchanged. Read off the weight's encoding like `bf16` and `i8`. */
bool mx = false;
rad_weight wref = 0;
/* ...ROTATED (ParoQuant), a variant of `mx`: the same GEMM over an activation that
* `givens_dense_quant` made from the input's bf16 plane -- the channel scale, the rotation (a
* dense per-group matrix) and the E4M3 quantiser in one pass, once for each rotated PART of a fused projection
* (gate|up, qkv|z: each piece was rotated on its own) -- into this linear's own code and
* scale planes, `parts` copies side by side. The tables are views of the weight's own planes.
* The GEMM takes the parts' row bounds as `pb1`/`pb2` and meets copy p with part p's rows. */
bool paro = false;
/* ...AND ITS 5-BIT SIBLING: the same rotation, to f16 (`rot_q` is then the f16 plane and there is no
* `rot_s`), then gemm_nt_q at w5a16 over a weight of u5 codes, an f16 scale and a zero point. */
bool paro5 = false;
/* ...AND ITS PREFILL BAND (z-lab's int4 and the int5): above `rot_split` rows the f16 skinny kernel is
* bound by the slow f16 matrix instruction, so a second chain runs there -- the same rotation to
* int8 with a scale a (row, 128) into `rot_q2`/`rot_s2`, then the int8 tiled GEMM
* (`w4a8i8_asym` / `w5a8i8`), both reading the SAME weight views. At or below the split the f16 chain
* above runs. */
int64_t rot_split = 0;
rad_buf rot_q2 = 0, rot_s2 = 0;
rad_op op_rot2 = 0, op2 = 0;
rad_weight rot_pairs = 0, rot_angle = 0, rot_scale = 0, rot_dense = 0;
rad_buf rot_q = 0, rot_s = 0;
rad_op op_rot = 0;
int64_t rot_parts = 1, rot_stages = 0;
/* What probe() read: the weight is int8. Lets a model learn its trunk's format from one linear
* before it declares the activation buffers that format decides (ActFP8::declare_qs's `i8`). */
bool probed_i8 = false;
@@ -728,12 +751,39 @@ struct LinearFP8 {
/* `span_lo`/`span_hi`, when hi is set, is this rank's uneven slice of the split dimension in
* the model's units -- rows of each row part for RAD_SHARD_ROW, columns for RAD_SHARD_COL --
* and n_out / n_in is already its width; see rad_weight_shard_span. Whole scale blocks. */
/* `rot_parts`: the rows of each independently rotated part of a ROTATED weight,
* which `row_parts` is when the pieces and the shard parts are the same cut -- gate|up -- and
* is not when they are not: the delta net's qkv|z is four shard parts and two rotated ones. */
int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp,
std::initializer_list<const char*> src,
const ActFP8& a, rad_buf y, int64_t max_rows = 0,
std::initializer_list<int64_t> row_parts = {},
int64_t span_lo = 0, int64_t span_hi = 0);
int64_t span_lo = 0, int64_t span_hi = 0,
std::initializer_list<int64_t> rot_part_rows = {});
/* THE ROTATION OF A ROTATED WEIGHT: its parts and stages (`rot_parts`, `rot_stages`) and its
* channel scale as a view of the weight's own plane. `cut` is the rows of each rotated part; the
* GEMM's part bounds come back in pb1 and pb2. */
int declare_rotation(RadBuilder* b, Names& nm, const char* base, const char* wn,
const RadEncoding& enc, int64_t N, int64_t K, RadWeightGroup grp,
const std::vector<int64_t>& cut, int64_t* pb1, int64_t* pb2);
/* THE SEQUENTIAL NETWORK (decode: a few rows, where one network a row is cheap): the pairs and
* angles as views, and givens_rotate over them to f16, for M in [lo, hi]. */
int decl_seq_tables(RadBuilder* b, Names& nm, const char* base, const char* wn, RadWeightGroup grp);
rad_op decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, int64_t lo, int64_t hi,
std::initializer_list<rad_buf> outs) const;
/* THE DENSE ROTATION (rot_dense, decl_dense): givens_dense_quant to `out` ("fp8" or "i8") codes
* and a scale, for M in [lo, hi]. */
rad_op decl_dense_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* out, int64_t lo,
int64_t hi, std::initializer_list<rad_buf> outs) const;
/* gemm_nt_q over this weight, M in [lo, hi]. `pb1`/`pb2` go only to a weight with rotated
* parts, so a one-part op keeps the plain op's geometry -- the key the tune cache is read by. */
rad_op decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int64_t group, const char* dtype,
int64_t pb1, int64_t pb2, std::initializer_list<rad_weight> wts,
std::initializer_list<rad_buf> reads, rad_buf y) const;
rad_weight decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc,
int64_t K,
RadWeightGroup grp);
void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0,
int64_t rows = 0) const;
/* A SPAN PER STACKED ROW PART (rad_weight_shard_span_parts), in the weight's rows; the scale
@@ -797,6 +847,35 @@ inline bool linear_is_mxfp4(const RadEncoding& e) {
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
}
/* A ROTATED weight (ParoQuant): an affine encoding stored in the basis a "givens" transform names,
* with the rotation's tables as planes of their own -- int32 column pairs, f32 angles, f32 channel
* scales, and for a fused projection one set a part. The GEMM reads the codes as stored; the
* activation in front of it is rotated first. */
inline bool linear_is_givens(const RadEncoding& e) {
if (!rad_enc_is(&e, "affine") || std::strncmp(e.transform, "givens", RAD_ENC_STR) != 0) return false;
if (!rad_enc_valid(&e)) return false;
const RadEncPlane *pr = rad_enc_plane(&e, "t.pairs"), *an = rad_enc_plane(&e, "t.angle"),
*rs = rad_enc_plane(&e, "t.scale");
return pr && an && rs && pr->dtype == RAD_I32 && an->dtype == RAD_F32 && rs->dtype == RAD_F32;
}
/* ...whose codes and E8M0 exponents are OCP-MXFP4's: read as the plain MXFP4 weight. */
inline bool linear_is_paro_mxfp4(const RadEncoding& e) {
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
return linear_is_givens(e) && e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[1] == 1 && sc &&
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
}
/* ...whose codes are ParoQuant's int5 (u5) or z-lab's int4 (u4), asymmetric: an f16 scale and a u8
* zero point a 128 of K. Read by gemm_nt_q at w5a16 / w4a16_asym over an f16 activation, and at
* w5a8i8 / w4a8i8_asym over an int8 one. */
inline bool linear_is_paro_w5(const RadEncoding& e) {
const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *zp = rad_enc_plane(&e, "zero");
return linear_is_givens(e) && (e.plane[0].dtype == RAD_U5 || e.plane[0].dtype == RAD_U4) && sc &&
zp && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK &&
zp->dtype == RAD_U8 && zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK;
}
inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* base,
std::initializer_list<const char*> src) {
if (src.size() == 0) return RAD_E_INVAL;
@@ -808,16 +887,116 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
enc.plane[0].dtype == RAD_BF16;
probed_i8 = known && linear_is_w8(enc);
reads_x = g.w_bf16 || plain || probed_i8;
/* A ROTATED weight rotates the bf16 plane itself: its quantiser is not the producer's. */
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc));
reads_x = g.w_bf16 || plain || probed_i8 || rotated;
return RAD_OK;
}
inline rad_op LinearFP8::decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int64_t group,
const char* dtype, int64_t pb1, int64_t pb2,
std::initializer_list<rad_weight> wts,
std::initializer_list<rad_buf> reads, rad_buf y) const {
const RadParam ps[] = { RAD_RANGE("M", lo, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", group), RAD_STR("dtype", dtype),
RAD_INT("pb1", pb1), RAD_INT("pb2", pb2) };
const int n_ps = (int)(sizeof ps / sizeof ps[0]) - (rot_parts > 1 ? 0 : 2);
return rw(b, rad_decl_op(b, "gemm_nt_q", ps, n_ps, wts.begin(), (int)wts.size()), reads, { y });
}
inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const char* base, const char* wn,
const RadEncoding& enc, int64_t N, int64_t K,
RadWeightGroup grp, const std::vector<int64_t>& cut_in,
int64_t* pb1, int64_t* pb2) {
/* THE PARTS, in rows, and the tables as weights of their own. The container records how many
* parts there are and not where they end -- a declaration has no plane bytes -- so the block
* says: `rot_part_rows`, or its row parts when those are the cut. */
const int64_t P = rad_enc_givens_parts(&enc);
const RadEncPlane* tp = rad_enc_plane(&enc, "t.pairs");
if (P < 1 || !tp || tp->extent[0] % P || tp->extent[1] != K) {
fprintf(stderr, "radiance: '%s' has rotation tables that do not fit %lld columns\n",
wn, (long long)K);
return RAD_E_SHAPE;
}
const int64_t S = tp->extent[0] / P;
std::vector<int64_t> cut = cut_in;
if (cut.empty() && P == 1) cut.push_back(N);
int64_t sum = 0;
for (int64_t p : cut) sum += p;
if ((int64_t)cut.size() != P || sum != N || P > 3) {
fprintf(stderr, "radiance: '%s' was rotated as %lld part(s) and is declared as %zu "
"rotated part(s) of %lld rows; the GEMM meets up to three copies "
"of the activation\n", wn, (long long)P, cut.size(), (long long)sum);
return RAD_E_SHAPE;
}
for (int64_t i = 0; i + 1 < P; ++i) if (cut[(size_t)i] % 128) {
fprintf(stderr, "radiance: '%s' rotation part of %lld rows is not whole 128s\n",
wn, (long long)cut[(size_t)i]);
return RAD_E_SHAPE;
}
rot_parts = P;
rot_stages = S;
*pb1 = P > 1 ? cut[0] : 0;
*pb2 = P > 2 ? cut[0] + cut[1] : 0;
rot_scale = decl_view(b, nm.f("%s.rot_scale", base), wn, "t.scale", RAD_F32,
{ P, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
return rot_scale ? RAD_OK : RAD_E_INVAL;
}
inline int LinearFP8::decl_seq_tables(RadBuilder* b, Names& nm, const char* base, const char* wn,
RadWeightGroup grp) {
const int64_t PS = rot_parts * rot_stages;
rot_pairs = decl_view(b, nm.f("%s.rot_pairs", base), wn, "t.pairs", RAD_I32,
{ PS, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
rot_angle = decl_view(b, nm.f("%s.rot_angle", base), wn, "t.angle", RAD_F32,
{ PS, K / 2 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
return rot_pairs && rot_angle ? RAD_OK : RAD_E_INVAL;
}
inline rad_op LinearFP8::decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, int64_t lo,
int64_t hi, std::initializer_list<rad_buf> outs) const {
return rw(b, RAD_OP(b, "givens_rotate",
RAD_PARAMS(RAD_RANGE("M", lo, hi), RAD_INT("n", K), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", g.dtype), RAD_INT("stages", rot_stages),
RAD_INT("parts", rot_parts)),
RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)),
{ a.x }, outs);
}
inline rad_op LinearFP8::decl_dense_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* out,
int64_t lo, int64_t hi, std::initializer_list<rad_buf> outs) const {
return rw(b, RAD_OP(b, "givens_dense_quant",
RAD_PARAMS(RAD_RANGE("M", lo, hi), RAD_INT("n", K), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", g.dtype), RAD_INT("parts", rot_parts),
RAD_STR("out", out)),
RAD_WEIGHTS(rot_dense, rot_scale)),
{ a.x }, outs);
}
/* The dense rotation matrices of a rotated weight: a view of its "t.dense" table, f16 [P * K/128, 128*128],
* which rad-convert composes from the givens tables (abi/rad_encoding.h). A container written before the
* table existed carries only the pairs and angles; it is refused here, naming the reconvert, rather than
* served through a matrix the kernel library would have to compute. */
inline rad_weight LinearFP8::decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn,
const RadEncoding& enc, int64_t K, RadWeightGroup grp) {
if (!rad_enc_plane(&enc, "t.dense")) {
fprintf(stderr, "radiance: '%s' carries its rotation as pairs and angles only, and the dense "
"quantiser reads it composed (a \"t.dense\" table); convert it again with this "
"rad-convert -- --reuse <this container> copies every other weight\n", wn);
return 0;
}
return decl_view(b, nm.f("%s.rot_dense", base), wn, "t.dense", RAD_F16,
{ rot_parts * (K / RAD_FP8_BLOCK), RAD_FP8_BLOCK * RAD_FP8_BLOCK },
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
}
inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp,
std::initializer_list<const char*> src,
const ActFP8& a, rad_buf y, int64_t max_rows,
std::initializer_list<int64_t> row_parts,
int64_t span_lo, int64_t span_hi) {
int64_t span_lo, int64_t span_hi,
std::initializer_list<int64_t> rot_part_rows) {
N = n_out;
K = n_in;
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
@@ -929,6 +1108,68 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL;
}
/* ---- A ROTATED 5-BIT OR ASYMMETRIC 4-BIT WEIGHT (ParoQuant int5; z-lab's int4): its input's
* bf16 plane rotated into this linear's own f16 planes, then the w5a16 GEMM. Two views of one
* stored weight: the codes, and the (scale, zero) pair as `b_scale`. */
paro5 = known && linear_is_paro_w5(enc);
if (paro5) {
const int bits = enc.plane[0].dtype == RAD_U4 ? 4 : 5;
if (!a.x) {
fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight, rotated from its input's "
"bf16 plane, and its input has none\n", wn, bits);
return RAD_E_DTYPE;
}
if (g.world > 1 || span_hi > 0) {
fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight; its rotation is not cut by "
"a tensor-parallel shard (world %d)\n", wn, bits, g.world);
return RAD_E_UNSUPPORTED;
}
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld; a %d-bit weight takes rows in 16s and K "
"in whole 128s\n", base, (long long)N, (long long)K, bits);
return RAD_E_INVAL;
}
std::vector<int64_t> cut;
for (int64_t p : rot_part_rows) cut.push_back(p);
if (cut.empty()) for (int64_t p : row_parts) cut.push_back(p);
int64_t pb1 = 0, pb2 = 0;
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
const bool bits5 = enc.plane[0].dtype == RAD_U5;
const int64_t kSplit = 64; /* the skinny kernel's M ceiling */
const bool band = hi > kSplit;
const int64_t f16_hi = band ? kSplit : hi; /* the f16 chain's rows */
RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2));
RAD_ARCH_TRY(decl_seq_tables(b, nm, base, wn, grp));
const int64_t P = rot_parts;
rot_q = decl_b(b, nm.f("%s.rot_y", base), RAD_F16, { f16_hi, P * K });
if (!rot_q) return RAD_E_INVAL;
op_rot = decl_rot_op(b, g, a, 1, f16_hi, { rot_q });
if (!op_rot) return RAD_E_INVAL;
w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, RAD_ACCESS_PER_TOKEN,
shard, grp);
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K },
RAD_ACCESS_PER_TOKEN, shard, grp);
if (!w || !ws) return RAD_E_INVAL;
op = decl_gemm_q(b, 1, f16_hi, RAD_FP8_BLOCK, bits5 ? "w5a16" : "w4a16_asym",
pb1, pb2, { w, ws }, { rot_q }, y);
if (!op) return RAD_E_INVAL;
if (band) {
/* THE PREFILL BAND: rows above the skinny kernel's ceiling rotate to int8 and meet the int8
* tiled GEMM. Declared over the tables and weight views already made above. */
rot_split = kSplit;
rot_q2 = decl_b(b, nm.f("%s.rot_q2", base), RAD_I8, { hi, P * K });
rot_s2 = decl_b(b, nm.f("%s.rot_s2", base), RAD_F32, { hi, P * (K / RAD_FP8_BLOCK) });
if (!rot_q2 || !rot_s2) return RAD_E_INVAL;
rot_dense = decl_dense(b, nm, base, wn, enc, K, grp);
if (!rot_dense) return RAD_E_INVAL;
op_rot2 = decl_dense_op(b, g, a, "i8", kSplit + 1, hi, { rot_q2, rot_s2 });
op2 = decl_gemm_q(b, kSplit + 1, hi, RAD_FP8_BLOCK, bits5 ? "w5a8i8" : "w4a8i8_asym",
pb1, pb2, { w, ws }, { rot_q2, rot_s2 }, y);
if (!op_rot2 || !op2) return RAD_E_INVAL;
}
return RAD_OK;
}
/* An E4M3 weight reads the E4M3 pair, and an input the model feeds at int8 codes has none --
* a container whose trunk mixes the two formats, which the model's one probe did not see. */
if (a.q8_fed) {
@@ -941,9 +1182,24 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
* the exponent plane as `b_scale`, and the same plane again as `b_ref`. Every view takes the
* weight's row parts as they are -- the exponent grid is one row tall -- and a column slice in
* whole 128s, which is the ACTIVATION's scale block and so the stricter of the two. */
mx = known && linear_is_mxfp4(enc);
paro = known && linear_is_paro_mxfp4(enc);
mx = known && (linear_is_mxfp4(enc) || paro);
if (mx) {
if (!a.q || !a.s) {
if (paro) {
/* THE ROTATION OF A ROTATED WEIGHT IS THE ACTIVATION'S, so this linear needs the input's
* bf16 plane (probe() set reads_x; the producer wrote it) and quantises it itself. */
if (!a.x) {
fprintf(stderr, "radiance: '%s' is a rotated MXFP4 weight, rotated and quantised "
"from its input's bf16 plane, and its input has none\n", wn);
return RAD_E_DTYPE;
}
if (g.world > 1 || span_hi > 0) {
fprintf(stderr, "radiance: '%s' is a rotated MXFP4 weight; its rotation is per "
"projection and is not cut by a tensor-parallel shard (world %d)\n",
wn, g.world);
return RAD_E_UNSUPPORTED;
}
} else if (!a.q || !a.s) {
fprintf(stderr, "radiance: '%s' is an MXFP4 weight read against its input's E4M3 "
"pair, and its input has none\n", wn);
return RAD_E_DTYPE;
@@ -966,6 +1222,21 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
}
parts[np++] = p;
}
int64_t pb1 = 0, pb2 = 0;
if (paro) {
std::vector<int64_t> cut;
for (int64_t p : rot_part_rows) cut.push_back(p);
if (cut.empty()) for (int64_t p : row_parts) cut.push_back(p);
RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2));
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { rows, rot_parts * K });
rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32, { rows, rot_parts * (K / RAD_FP8_BLOCK) });
if (!rot_q || !rot_s) return RAD_E_INVAL;
rot_dense = decl_dense(b, nm, base, wn, enc, K, grp);
if (!rot_dense) return RAD_E_INVAL;
op_rot = decl_dense_op(b, g, a, "fp8", 1, rows, { rot_q, rot_s });
if (!op_rot) return RAD_E_INVAL;
}
const char* sn = nm.f("%s.scale", base);
const char* rn = nm.f("%s.ref", base);
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, RAD_ACCESS_PER_TOKEN,
@@ -989,12 +1260,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, lo, hi));
RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi));
}
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
op = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
RAD_WEIGHTS(w, ws, wref)),
{ a.q, a.s }, { y });
/* ONE GEMM for both: a rotated weight reads its own rotated pair, a plain one the producer's. */
op = decl_gemm_q(b, 1, max_rows > 0 ? max_rows : g.max_tok, RAD_MX_GROUP, "mxfp4a8", pb1, pb2,
{ w, ws, wref }, { paro ? rot_q : a.q, paro ? rot_s : a.s }, y);
return op ? RAD_OK : RAD_E_INVAL;
}
@@ -1096,9 +1364,33 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (paro5 && rot_split && rows > rot_split) {
RAD_ISSUE_N(c, op_rot2, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_dense),
RAD_W(rot_scale), brow_slice(rot_q2, r0, rows, rot_parts * K),
brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)));
RAD_ISSUE_N(c, op2, rows, brow_slice(rot_q2, r0, rows, rot_parts * K),
brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)),
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (paro5) {
RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs),
RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q, r0, rows, rot_parts * K));
RAD_ISSUE_N(c, op, rows, brow_slice(rot_q, r0, rows, rot_parts * K), RAD_NONE,
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (mx) {
RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
/* A rotated weight rotates its input first, into its own codes, `rot_parts` copies side
* by side (one for a plain weight, which reads the producer's). */
const rad_buf aq = paro ? rot_q : a.q, as = paro ? rot_s : a.s;
const int64_t ak = rot_parts * K;
if (paro)
RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_dense),
RAD_W(rot_scale), brow_slice(aq, r0, rows, ak),
brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK));
RAD_ISSUE_N(c, op, rows, brow_slice(aq, r0, rows, ak),
brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK),
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref));
return;
}
@@ -1127,11 +1419,35 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
*/
struct DenseFP8 {
rad_weight w = 0, s = 0;
/* OR AN OCP-MXFP4 WEIGHT, when that is what the container holds for it (a recipe's `codes=
* fp4_e2m1 group=32 scale=e8m0`): e2m1 codes, the E8M0 plane, and that plane again as the
* per-row reference -- LinearFP8's mx branch, without the GEMM. A block that declares its own
* GEMM over a DenseFP8 asks `gemm()` for it and passes `bref()` as the op's last operand, so
* one block serves either format against the same E4M3 activation pair. */
rad_weight ref = 0;
bool mx = false;
int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
int access, int shard, RadWeightGroup grp,
std::initializer_list<const char*> src,
std::initializer_list<int64_t> row_parts = {});
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. */
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes) const {
if (mx)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
RAD_WEIGHTS(w, s, ref)),
reads, writes);
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
RAD_WEIGHTS(w, s)),
reads, writes);
}
/* The op's trailing `b_ref` operand: the reference view for MXFP4, absent for fp8. */
RadOperand bref() const { return mx ? RAD_W(ref) : RAD_NONE; }
};
inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
@@ -1139,6 +1455,36 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
std::initializer_list<const char*> src,
std::initializer_list<int64_t> row_parts) {
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
/* ---- OCP-MXFP4, read off the encoding the name map resolves to. The exponent grid is one row
* tall, so a part needs only whole 16-row tiles; K takes whole 128s because the E4M3 activation
* in front carries a scale per (row, 128). */
{
const char* wn = nm.f("%s.weight", base);
RAD_ARCH_TRY(map_linear(b, wn, src));
RadEncoding enc{};
mx = weight_enc(b, wn, &enc) && linear_is_mxfp4(enc);
if (mx) {
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows "
"in 16s and K in whole %d-column activation scale blocks.\n",
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
int64_t p[RAD_MAX_ROW_PARTS] = {0};
int np = 0;
for (int64_t q : row_parts) {
if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL;
p[np++] = q;
}
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, shard, grp, p, np);
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, p, np);
ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, p, np);
return w && s && ref ? RAD_OK : RAD_E_INVAL;
}
}
if (N % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank, which is not a whole number of "
"%dx%d scale blocks. A block-scaled fp8 weight cannot be split inside a "
@@ -1163,8 +1509,7 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
}
const char* wn = nm.f("%s.weight", base);
const char* sn = nm.f("%s.scale", base);
RAD_ARCH_TRY(map_linear(b, wn, src));
const char* sn = nm.f("%s.scale", base); /* the name map was made above */
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, wp, np);
s = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, access, shard,
grp, sp, np);
+64
View File
@@ -0,0 +1,64 @@
/* rad_gemma4_chat.h -- how Gemma 4 spells a turn: its reasoning and its tool calls, as data.
*
* The chat template is one llama.cpp reads with a hand-written handler, so the template analysis
* finds nothing in it, and the engine would serve the model with no reasoning split and refuse
* every request that sends tools. The model's own tokenizer_config.json states the format instead
* (`response_template`), and this is that statement in the engine's terms:
*
* thinking <|channel>thought\n ... <channel|>
* tool calls <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3,flag:true}<tool_call|>, repeated
* the object unquoted keys, strings between <|"|> and <|"|> with their text verbatim, every
* other value as JSON writes it
* the turn ends at <turn|>; after its calls the model writes <|tool_response> and stops
* (generation_config.json names it beside <eos> and <turn|>)
*
* llama.cpp's handler records two habits of the model beyond that: an extra thought channel after
* the answer, and a lone <channel|>. `reasoning_anywhere` reads the first as reasoning and drops
* the second, so neither reaches the content.
*
* Here rather than in one plugin because two plugins serve Gemma 4 -- arch/gemma4 (bf16 and fp8
* experts) and arch/gemma4_bf16 (the CT-INT4 dense release) -- and the format is the model's, not
* the weights'. One declaration, so the two cannot drift apart, and so the reply-format tests read
* the declaration the plugins export rather than a copy of it. */
#pragma once
#include "rad_builder.h"
namespace rad {
namespace arch {
inline const RadChatFormat* gemma4_chat_format() {
static const char* const kBreaks[] = { "<|tool_call>" };
static const char* const kTriggers[] = { "<|tool_call>" };
static const RadChatFormat f = [] {
RadChatFormat c{};
c.struct_size = (uint32_t)sizeof(RadChatFormat);
c.name = "plugin:gemma4";
c.reasoning_open = "<|channel>thought\n";
c.reasoning_close = "<channel|>";
/* A call that starts inside an unclosed thought ends it there. */
c.reasoning_breaks = kBreaks;
c.n_reasoning_breaks = 1;
/* Thinking off, the template closes an empty channel in the generation prompt; on, the
* model opens its own -- or, after a tool response, the prompt has opened it. */
c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
c.reasoning_anywhere = 1;
c.call_open = "<|tool_call>";
c.call_close = "<tool_call|>";
c.name_prefix = "call:";
c.name_suffix = ""; /* the name ends at the object's `{` */
c.call_end = ""; /* and the object's `}` ends the call */
c.args_form = RAD_CHAT_ARGS_OBJECT;
c.object_string_open = "<|\"|>";
c.object_string_close = "<|\"|>";
c.object_bare_keys = 1;
c.triggers = kTriggers;
c.n_triggers = 1;
return c;
}();
return &f;
}
} /* namespace arch */
} /* namespace rad */
+51 -28
View File
@@ -154,6 +154,11 @@ 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);
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
/* The block keys and the tail of the pass's rows and nothing else: no query, no score, no
* selection. What a pass that only leaves the layer's state behind asks for (see
* AttnGatedFP8::store_kv); the stores are the ones step() makes. */
void store(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
bool store_keys(RadCtx* c, const RadBatch* batch) const;
};
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -314,38 +319,16 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
return RAD_OK;
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
/* THE KEYS A PASS LEAVES BEHIND: the block keys of the blocks its rows complete and the tail of
* raw keys after them, out of the projection's raw-key head. False when the step carries no batch
* for the indexer's groups. */
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t qw = c.heads * c.head_dim;
const int64_t nw = (c.heads + 1) * c.head_dim;
const int64_t koff = qw; /* the raw-key head, after the query heads */
proj.step(c_, in, w.qk, T);
/* ONE LAUNCH OR `heads` + 1. The fused form takes the projection WHOLE -- the kernel picks
* head `h` out of it at the operand's own row pitch, so the strided view the unfused norm
* needs is not taken at all -- and it writes the query heads contiguous and rotated, which is
* what the pair below leaves behind. `n_head` 0 is the k-only form: no q_gate, no q_w, no
* q_out, and the ninth operand (`gate_out`) is absent as it is everywhere else.
*
* `T <= qprep_rows` IS THE TABLE'S BOUND and declare() says why it is correctness. */
if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
RAD_ISSUE_N(c_, op_qprep, T,
RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_NONE, RAD_W(w_qn),
RAD_NONE, brows(w.q, T), RAD_NONE);
} else {
for (int64_t h = 0; h < c.heads; ++h)
RAD_ISSUE_N(c_, op_norm, T,
bcol_at(w.qk, 0, nw, h * c.head_dim, c.head_dim, T), RAD_W(w_qn),
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
}
const int64_t koff = c.heads * c.head_dim; /* the raw-key head, after the query heads */
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
const RadKVGroupBatch* tlb = kv_batch(batch, c.kv_tail);
if (!bkb || !atb || !tlb) return;
if (!bkb || !tlb) return false;
/* COLUMN 0 OF THE STATE ROW IS THE COMMITTED SLOT. The row is wider than one whenever the
* deployment speculates -- the manager gives every linear group a second copy then, because
* the kernel that needed one asked for it -- and this op wants the committed slot in every
@@ -389,6 +372,46 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw));
return true;
}
inline void QsaIndexer::store(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
proj.step(c_, in, w.qk, batch->n_tok);
(void)store_keys(c_, batch);
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t qw = c.heads * c.head_dim;
const int64_t nw = (c.heads + 1) * c.head_dim;
proj.step(c_, in, w.qk, T);
/* ONE LAUNCH OR `heads` + 1. The fused form takes the projection WHOLE -- the kernel picks
* head `h` out of it at the operand's own row pitch, so the strided view the unfused norm
* needs is not taken at all -- and it writes the query heads contiguous and rotated, which is
* what the pair below leaves behind. `n_head` 0 is the k-only form: no q_gate, no q_w, no
* q_out, and the ninth operand (`gate_out`) is absent as it is everywhere else.
*
* `T <= qprep_rows` IS THE TABLE'S BOUND and declare() says why it is correctness. */
if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
RAD_ISSUE_N(c_, op_qprep, T,
RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_NONE, RAD_W(w_qn),
RAD_NONE, brows(w.q, T), RAD_NONE);
} else {
for (int64_t h = 0; h < c.heads; ++h)
RAD_ISSUE_N(c_, op_norm, T,
bcol_at(w.qk, 0, nw, h * c.head_dim, c.head_dim, T), RAD_W(w_qn),
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
}
/* The keys first: the selection below reads the blocks they complete. */
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
if (!atb || !store_keys(c_, batch)) return;
/* SCORE AND SELECT OVER EVERY QUERY IN THE STEP. A selection does not have to be per-SEQUENCE
* even though a block table is: both ops take `cu`, the block table stays the sequence's, and
+11
View File
@@ -0,0 +1,11 @@
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
# radiance (`cmake -S arch/embgemma2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(embgemma2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(embgemma2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/embgemma2.cpp)
File diff suppressed because it is too large. Load diff
+14
View File
@@ -0,0 +1,14 @@
# gemma4 -- the architecture plugin for Gemma 4's text model (Gemma4ForConditionalGeneration /
# Gemma4ForCausalLM; the 26B-A4B MoE and the dense sizes without per-layer embeddings), with a
# z-lab DFlash drafter merged at convert time.
#
# Built inside radiance's tree (arch/ discovers it) or on its own against an installed radiance:
# cmake -S arch/gemma4 -B build-gemma4 -DCMAKE_PREFIX_PATH=/opt/radiance && cmake --build build-gemma4
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(gemma4 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(gemma4 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma4.cpp)
File diff suppressed because it is too large. Load diff
+686
View File
@@ -0,0 +1,686 @@
/* gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4.
*
* ============================== WHAT IT IS ==============================
*
* rad_block_dflash2.h WITHOUT THE TWO THINGS DFLASH2 ADDED: the per-layer dynamic convolutions
* around attention and the feed-forward, and the candidate selector that walks a path through the
* block. What is left is the original DFlash: a small Qwen3-shaped transformer that denoises one
* anchor token plus `block - 1` mask tokens in ONE forward and reads every position's argmax off
* the TARGET's lm_head.
*
* context pass, one row a committed token:
* c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids)))
* for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v)
*
* query pass, `block` rows a sequence:
* x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below
* for each layer:
* h = input_layernorm(x)
* q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store
* x += o_proj(attention(q, cache)) sliding layers CAUSAL over a 2048 window,
* the full layer NON-causal over everything
* x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x)
* x = norm(x)
* over the mask rows: logits = lm_head(x) [the TARGET's]; draft = argmax
*
* ============================== THE THREE GEMMA-SPECIFIC FACTS ==============================
*
* They are vLLM PR #41703's, and each one costs acceptance and nothing else when it is wrong --
* every draft is verified against the trunk, so the model's output never depends on any of them.
*
* THE EMBEDDING IS SCALED. Gemma multiplies its token embedding by sqrt(hidden_size), stored as a
* bf16 (53.0 at 2816), and the drafter was trained reading the target's embedding module, which
* applies it. `embed_lookup`'s `mult` carries it.
*
* THE SLIDING LAYERS ARE CAUSAL AND THE FULL LAYER IS NOT. The checkpoint's `layer_types` names
* four sliding layers and one full one; the PR's own test pins `causal True` on the sliding
* layers and `False` on the full one. So this block declares TWO attention ops and issues the
* one each layer's type names.
*
* THE LOGITS ARE SOFT-CAPPED, and that is ignored on purpose: the draft is an argmax, and
* cap * tanh(x / cap) is strictly increasing, so it cannot move one.
*
* ============================== THE HEAD ==============================
*
* The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma
* ties it to the embedding, so it is the same weight the trunk's `embed_lookup` and `logits_gemm`
* read: no extra bytes are stored. It is vocab-sharded with the trunk, so the top-1 runs over this
* rank's slice and the ranks' candidates are merged exactly (`row_topk` at R = 2 -> `all_gather` ->
* `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR).
*
* Reading the bf16 head every draft pass is the expensive way to do it -- 262144 x 2816 x 2 bytes
* over the ranks, 566 us of a 26B-A4B decode step at tp 4 (--profile-ops, 4x R9700), the widest
* read on the draft path. So where the CONTAINER holds a block-fp8 copy of the table under a name
* of its own -- `dflash.draft_head.weight`, one checkpoint tensor and two logical weights, as
* rad_block_dflash2.h does it, made by a recipe line
*
* dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
*
* -- the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, and the argmax is taken over
* its coarser logits. Every draft is still verified, so the copy can change what is proposed and
* never what is accepted; draft_n_accepted is what says whether it proposes worse. A container
* without it, or with it in any other encoding, reads the bf16 table as before. The copy costs
* half the table's bytes again, 176 MiB a rank at tp 4. No rerank against the bf16 table yet:
* DFlash2's needs the target's head in fp8 or int8, which a tied Gemma head is not.
*
* ============================== THE LINEARS ARE FP8 ==============================
*
* The same as DFlash2 and for the same reason -- the drafter is read whole on every decode step --
* so the container must be converted with a recipe that makes the six linears block fp8 (or
* MXFP4). declare() refuses a bf16 one by name rather than letting the loader fail on a view.
*/
#ifndef GEMMA4_DFLASH_H
#define GEMMA4_DFLASH_H
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <cstdio>
#include <cstring>
namespace gemma4 {
using namespace rad::arch;
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale a 128x128 block, no
* transform -- a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`. */
inline bool block_fp8_128(const RadEncoding& e) {
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 &&
sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK;
}
struct Dflash1 {
enum { MAX_LAYERS = 8 };
struct Config {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* query rows a sequence: the anchor plus block - 1 masks */
int64_t window = 0; /* the sliding layers' window; 0 for none */
int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */
double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */
int64_t steps() const { return block - 1; }
};
struct Wire {
/* the context pass */
rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | e4m3 | f32 */
rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */
rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */
/* the query pass */
rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */
rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */
rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */
rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */
/* the head, one row a draft position */
rad_buf sel_h = 0; /* [srows, n_embd] */
rad_buf selq = 0, sels = 0; /* [srows, n_embd] e4m3 | f32, the fp8 head's */
rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */
rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */
rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */
rad_buf tokens = 0; /* [srows, 1] i32: THE DRAFT, pitch `steps` */
};
Geom g{}; /* the drafter's geometry */
Config cfg{};
Wire w{};
int first_layer = 0;
int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0;
rad_kvgroup kv = 0;
bool sharded = false;
DenseFP8 w_fc{};
rad_weight w_hnorm = 0, w_norm = 0;
rad_weight w_tok = 0; /* the TARGET's table: embedding AND head */
DenseFP8 w_dh{}; /* its block-fp8 copy, the head where it is stored */
bool fp8_head = false;
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{};
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {};
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0;
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
/* THE RESIDUAL ADD, THE NORM AND THE QUANTISER IN ONE LAUNCH where `rmsnorm_quant_fp8` is
* served (libr4d): op_anq[i] the attention input's -- layer 0's with no add, x as the
* embedding left it -- and op_fnq[i] the feed-forward input's. Zero where it is not, and the
* `add` / `rmsnorm` / `quant_act_fp8` chain is issued instead. */
rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {};
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0;
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0;
/* CANDIDATES A RANK CONTRIBUTES under a sharded head. The draft needs one, but the gather moves
* whole 16-byte words a row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is refused at
* launch ("shape this kernel does not serve") -- the bound rad_block_mtp_hc.h states. Two pairs
* are one word; `pair_argmax` reduces the world * 2 of them to the global top-1. */
static constexpr int64_t kTopR = 2;
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
rad_kvgroup group, rad_weight tok_embd, const char* ck, const Wire& wire,
const char* tok_src);
void context(RadCtx* c, const RadBatch* batch) const;
void step(RadCtx* c, const RadBatch* batch) const;
private:
int64_t q_dim() const { return g.n_head * g.head_dim; }
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
/* The six linears must be what the recipe made them. DenseFP8 declares E4M3 (or MXFP4) views
* whatever the container holds, and the loader's complaint about a bf16 weight read through an
* fp8 view names the view, not the missing recipe. */
static int need_quantised(RadBuilder* b, const char* wn) {
RadEncoding e{};
if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */
const uint32_t dt = e.plane[0].dtype;
if (dt == RAD_F8E4M3 || dt == RAD_FP4E2M1) return RAD_OK;
fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its six linears "
"are served block fp8 (or MXFP4): convert with a recipe that names them, "
"e.g. `dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 "
"scale=bf16` and the same for fc, attn_k/v/output, ffn_gate_up and "
"ffn_down.\n", wn, rad_dtype_name(dt));
return RAD_E_DTYPE;
}
};
/* ------------------------------------------------------------------------------ declare */
inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
int base_layer, rad_kvgroup group, rad_weight tok_embd,
const char* ck, const Wire& wire, const char* tok_src) {
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
if (!ck || !w_tok || !tok_src) return RAD_E_INVAL;
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most "
"%d\n", (long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL;
const int64_t qd = q_dim(), kvd = kv_dim();
crows = g.max_tok;
qrows = g.max_seqs * cfg.block;
if (qrows > g.max_tok) qrows = g.max_tok;
srows = g.max_seqs * cfg.steps();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
sharded = head_sharded(g);
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
{ nm.ckpt("%s.fc.weight", ck) }));
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
/* ---------------------------------------------------------------- per-layer weights */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const RadWeightGroup gl = grp_layer(first_layer + i);
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i),
nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i),
nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i)));
w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
/* The declared names are rad_block_dflash2.h's, deliberately: the recipe that quantises a
* DFlash2 drafter's linears names exactly these, so one recipe serves both drafters. */
RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl,
{ nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff,
g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i),
nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) },
{ g.n_ff, g.n_ff }));
RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl,
{ nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
for (const char* s : { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up",
"ffn_down" })
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, s)));
}
/* ---------------------------------------------------------------- attention: two kinds
* Declared before either kv_store: `block_size` is read back off the resolved kernel. Both
* read the one KV group, so whichever resolves first answers for it. */
auto attn = [&](int causal, int64_t window) {
return rw(b, RAD_OP(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", causal),
RAD_INT("window", window), RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
};
bool any_full = false, any_swa = false;
for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true;
if (any_swa) op_attn_swa = attn(1, cfg.window);
if (any_full) op_attn_full = attn(0, 0);
/* ---------------------------------------------------------------- the context pass */
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.c});
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.c}, {w.cq, w.cs});
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.ck}, {w.ck});
}
op_crope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.ck}, {w.ck});
op_cstore = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.ck, w.cv}, {});
/* ---------------------------------------------------------------- the query pass */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{w.x}, {w.x});
op_qh = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h}, {w.hq, w.hs});
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn}, {w.atq, w.ats});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.ffn}, {w.ffq, w.ffs});
/* x's norm under `gain`, quantised into hq|hs, in one launch; with `add` the fused_add_rms_norm
* form, x += h first. The row is the chain's function exactly -- the norm of the bf16-rounded
* sum, the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp) -- and a draft is verified
* whatever it is. */
auto norm_quant = [&](rad_weight gain, bool add) -> rad_op {
const rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)),
RAD_WEIGHTS(gain));
return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs});
};
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_anorm[i])),
{w.x}, {w.h});
op_anq[i] = norm_quant(w_anorm[i], l > 0);
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q});
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k});
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v});
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_qn[i])),
{w.q}, {w.q});
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.k});
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h});
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fnorm[i])),
{w.x}, {w.h});
op_fnq[i] = norm_quant(w_fnorm[i], true);
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up});
/* The gate_up|silu|quant fold where it resolves, the pair where it does not --
* rad_block_dflash2.h's rule, band included. */
{
const int64_t hi = qrows < 64 ? qrows : 64;
if (hi > 0 && !w_gu[i].mx) {
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
{w.hq, w.hs}, {w.ffq, w.ffs});
if (op_gug[i]) gated_rows = hi;
}
}
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
}
op_qrope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.q}, {w.q});
op_krope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.k}, {w.k});
op_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.k, w.v}, {});
op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ffn});
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{w.h}, {w.h});
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h}, {w.x});
op_final = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
/* ---------------------------------------------------------------- the head
* The MASK rows -- offsets 1..block-1 of each block; the core names them through out_ids --
* gathered contiguous, projected onto THIS RANK's slice of the target's vocabulary, and the
* argmax taken. Sharded, each rank's best kTopR are reported as global ids with their logits,
* all-gathered, and reduced to the global top-1 by `pair_argmax`, ties to the lower id -- exact,
* since the global winner is its own shard's first. */
op_gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h}, {w.sel_h});
/* THE FP8 COPY, where the container holds one (see the top of this file). The name map comes
* first -- it is how the encoding is looked up -- and a map whose weight is never declared is
* written by nothing: rad-convert walks the declared weights. The copy is row-sharded exactly
* as the table is, so this rank's rows are the same vocabulary slice and `vocab_off` holds. */
const char* dhn = nm.f("dflash.draft_head.weight");
RAD_ARCH_TRY(map_copy(b, dhn, tok_src));
RadEncoding he{};
fp8_head = weight_enc(b, dhn, &he) && block_fp8_128(he);
if (fp8_head) {
if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: gemma4: the fp8 draft head is %lldx%lld a rank, which "
"is not whole %d-row scale blocks\n",
(long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE;
w_dh.w = decl_view(b, dhn, nullptr, "codes", RAD_F8E4M3, { g.n_vocab, g.n_embd },
RAD_ACCESS_PER_TOKEN, shard, grp_model());
w_dh.s = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16,
{ fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN,
shard, grp_model());
if (!w_dh.w || !w_dh.s) return RAD_E_INVAL;
w.selq = decl_b(b, nm.f("df_selq"), RAD_F8E4M3, {srows, g.n_embd});
w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, {srows, fp8_blocks(g.n_embd)});
op_qsel = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.selq, w.sels});
op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog});
} else {
op_head = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_tok)),
{w.sel_h}, {w.dlog});
}
if (sharded) {
op_topk = rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary, w.dpair});
/* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side. */
op_dgather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"),
RAD_INT("row", kTopR * 2)),
RAD_NOWEIGHTS),
{w.dpair}, {w.dgath});
op_pick = rw(b, RAD_OP(b, "pair_argmax",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{w.dgath}, {w.tokens});
if (!op_pick) {
fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the "
"device, and no loaded kernel library serves it there\n");
return RAD_E_UNSUPPORTED;
}
} else {
op_topk = rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("R", 1), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.tokens, w.unary});
}
return RAD_OK;
}
/* ------------------------------------------------------------------------------ the context pass */
inline void Dflash1::context(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
brows(w.c, T), RAD_NONE, w_fc.bref());
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T), praw(slot, RAD_I32, T),
kv_cache(kv, first_layer + i));
}
}
/* ------------------------------------------------------------------------------ the query pass */
inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (T <= 0) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T));
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa;
/* The attention input, with the last layer's residual add where one launch takes both. */
if (op_anq[i]) {
RAD_ISSUE_N(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T),
l > 0 ? brows(w.x, T) : RAD_NONE, RAD_W(w_anorm[i]), brows(w.hq, T),
brows(w.hs, T), RAD_NONE);
} else {
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
}
RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_vp[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
kv_cache(kv, first_layer + i));
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
brows(w.q, T), kv_cache(kv, first_layer + i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T));
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
if (op_fnq[i]) {
RAD_ISSUE_N(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), RAD_W(w_fnorm[i]),
brows(w.hq, T), brows(w.hs, T), RAD_NONE);
} else {
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T));
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
}
if (op_gug[i] && T <= gated_rows) {
RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T),
RAD_NONE);
} else {
RAD_ISSUE_N(c, op_gu[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
w_gu[i].bref());
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
/* the residual add, unless the next layer's input norm takes it */
if (l + 1 == g.n_layer || !op_anq[i + 1])
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T));
}
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
const int64_t S = batch->n_out;
if (S <= 0) return;
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
if (fp8_head) {
RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S));
RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w),
RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref());
} else {
RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S));
}
if (sharded) {
RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
brows(w.dpair, S));
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE);
} else {
RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S),
RAD_NONE);
}
}
} /* namespace gemma4 */
#endif /* GEMMA4_DFLASH_H */
+11
View File
@@ -0,0 +1,11 @@
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
# radiance (`cmake -S arch/gemma4_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(gemma4_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(gemma4_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma4_bf16.cpp)
File diff suppressed because it is too large. Load diff
+321
View File
@@ -0,0 +1,321 @@
/* gemma4_vision.h -- the vision tower of Gemma 4's large dense models (31B), for gemma4_bf16.
*
* The same tower family embgemma2 serves (transformers' Gemma4VisionModel), at the 31B's size and
* with the two parts that model leaves out:
*
* a patch is 16 x 16 x 3, staged by the core's Gemma 4 processor as 2 * (u / 255) - 1 in bf16,
* (y, x, channel); patch embedding a [width, 768] linear plus a learned row for the patch's
* column and one for its row ([2, 10240, width] table)
* 27 layers of width 1152: sandwich norms (gain w, not 1 + w), q/k RMS-normed with a gain and v
* without one, a 2-D rotary over two 36-channel neox blocks a 72-wide head -- x (the column)
* over the first, y over the second, each block at theta^(-j / 18) (rope_type "default"; the
* embedding model spells the same rotary "axial") -- bidirectional attention within an image at
* scale 1, a gated gelu-tanh MLP
* pooling: the mean of each 3 x 3 window times sqrt(width) (the processor lays a window's nine
* patches out consecutively, raster order of windows, as the reference's position pooling)
* STANDARDISATION (vision_config.standardize): (z - std_bias) * std_scale per channel. The
* reference does it in f32 because a few channels carry ~5e4 with a bias that cancels them;
* here z is the pooler's bf16 row, so those channels keep bf16's spacing at their magnitude
* (about 1e-2 after the scale -- measured against the reference, see vision.md). The bias row
* is made on the card: fill(-1) times std_bias, added to z; then times std_scale.
* the multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. Its rows
* replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the
* image rows are not scaled).
*
* Every rank runs the whole tower (engine_mm.cpp), so its weights are replicated (RAD_SHARD_NONE)
* and each rank writes the rows into its own copy of the embedding stream. */
#pragma once
namespace gemma4_bf16 {
using namespace rad::arch;
struct Vision {
struct Layer {
rad_weight in_norm = 0, qkv = 0, q_norm = 0, k_norm = 0, o = 0, post_attn = 0;
rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0;
rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0;
};
bool on = false, standardize = false;
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
int64_t npos = 0, n_embd = 0;
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
rad_op op_patch = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0, op_pool = 0, op_norm = 0;
rad_op op_out = 0, op_sfill = 0, op_sbias = 0, op_sadd = 0, op_sscale = 0;
rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_px = 0,
b_py = 0, b_pool = 0, b_sb = 0, b_pn = 0, b_out = 0;
std::vector<Layer> L;
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
return t && !std::strcmp(t, "gemma4_vision");
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
hd = rad_meta_geti(m, "vision_config.head_dim", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
pool = rad_meta_geti(m, "vision_config.pooling_kernel_size", 0);
npos = rad_meta_geti(m, "vision_config.position_embedding_size", 0);
const int64_t depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
const int64_t patch = rad_meta_geti(m, "vision_config.patch_size", 0);
const int64_t kvh = rad_meta_geti(m, "vision_config.num_key_value_heads", heads);
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
const double theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 0.0);
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "");
const char* act = rad_meta_gets(m, "vision_config.hidden_activation", "");
standardize = rad_meta_geti(m, "vision_config.standardize", 0) != 0;
if (width <= 0 || heads <= 0 || hd <= 0 || ff <= 0 || pool <= 0 || npos <= 0 ||
depth <= 0 || patch <= 0 || !(theta > 0) || heads * hd != width || kvh != heads ||
hd % 4) {
fprintf(stderr, "radiance: gemma4_bf16: the container's vision_config is incomplete or "
"not the shape this plugin serves (hidden %lld, heads %lld x %lld, kv "
"%lld, ff %lld, pooling %lld, layers %lld)\n", (long long)width,
(long long)heads, (long long)hd, (long long)kvh, (long long)ff,
(long long)pool, (long long)depth);
return RAD_E_INVAL;
}
if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
(std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
std::strcmp(act, "gelu_pytorch_tanh")) {
fprintf(stderr, "radiance: gemma4_bf16: this vision tower uses clipped linears, a '%s' "
"rotary or a '%s' activation, which this plugin does not serve\n",
rt, act);
return RAD_E_UNSUPPORTED;
}
n_embd = model_embd;
patch_dim = 3 * patch * patch;
const int64_t kk = pool * pool;
P = ctx->max_enc_patches;
if (P % kk) P -= P % kk;
R = P / kk;
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
const char* V = "model.vision_tower";
RAD_ARCH_TRY(map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.patch_embedder.input_proj.weight", V)));
RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_x.weight"),
nm.ckpt("%s.patch_embedder.position_embedding_table", V), 0));
RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_y.weight"),
nm.ckpt("%s.patch_embedder.position_embedding_table", V), 1));
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight")));
w_in = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
if (standardize) {
RAD_ARCH_TRY(map_copy(b, nm.f("v.std_bias"), nm.ckpt("%s.std_bias", V)));
RAD_ARCH_TRY(map_copy(b, nm.f("v.std_scale"), nm.ckpt("%s.std_scale", V)));
w_sbias = decl_w(b, nm.f("v.std_bias"), RAD_BF16, {width}, A, N, grp_model());
w_sscale = decl_w(b, nm.f("v.std_scale"), RAD_BF16, {width}, A, N, grp_model());
}
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const long long li = (long long)i;
const RadWeightGroup g = grp_layer(first_group + (int)i);
auto src = [&](const char* s) { return nm.ckpt("%s.encoder.layers.%lld.%s", V, li, s); };
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.in_norm", li), src("input_layernorm.weight")));
RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.qkv", li),
{src("self_attn.q_proj.linear.weight"),
src("self_attn.k_proj.linear.weight"),
src("self_attn.v_proj.linear.weight")}));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.q_norm", li), src("self_attn.q_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.k_norm", li), src("self_attn.k_norm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.o", li), src("self_attn.o_proj.linear.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_attn", li), src("post_attention_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.pre_ff", li), src("pre_feedforward_layernorm.weight")));
RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.gate_up", li),
{src("mlp.gate_proj.linear.weight"),
src("mlp.up_proj.linear.weight")}));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.down", li), src("mlp.down_proj.linear.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_ff", li), src("post_feedforward_layernorm.weight")));
l.in_norm = decl_w(b, nm.f("v.blk.%lld.in_norm", li), RAD_BF16, {width}, A, N, g);
l.qkv = decl_w(b, nm.f("v.blk.%lld.qkv", li), RAD_BF16, {3 * width, width}, A, N, g);
l.q_norm = decl_w(b, nm.f("v.blk.%lld.q_norm", li), RAD_BF16, {hd}, A, N, g);
l.k_norm = decl_w(b, nm.f("v.blk.%lld.k_norm", li), RAD_BF16, {hd}, A, N, g);
l.o = decl_w(b, nm.f("v.blk.%lld.o", li), RAD_BF16, {width, width}, A, N, g);
l.post_attn = decl_w(b, nm.f("v.blk.%lld.post_attn", li), RAD_BF16, {width}, A, N, g);
l.pre_ff = decl_w(b, nm.f("v.blk.%lld.pre_ff", li), RAD_BF16, {width}, A, N, g);
l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g);
l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g);
l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g);
}
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width});
b_o = decl_b(b, nm.f("v.o"), RAD_BF16, {P, width});
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, {P, 3 * width});
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, {P, width});
b_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, {P, 2 * ff});
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, {P, ff});
b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width});
b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width});
b_pool = decl_b(b, nm.f("v.pool"), RAD_BF16, {R, width});
b_sb = decl_b(b, nm.f("v.sb"), RAD_BF16, {R, width});
b_pn = decl_b(b, nm.f("v.pn"), RAD_BF16, {R, width});
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {R, n_embd});
auto rms = [&](int64_t rows, rad_weight w) {
if (!w)
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight w) {
return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn),
RAD_INT("K", K), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto add = [&](int64_t rows) {
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
auto lookup = [&](rad_weight w) {
return RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
RAD_WEIGHTS(w));
};
auto gain = [&](rad_weight w) {
return RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
RAD_STR("dtype", "bf16"), RAD_INT("scalar", 0)),
RAD_WEIGHTS(w));
};
op_patch = rw(b, gemm(P, width, patch_dim, w_in), {}, {b_x});
op_px = rw(b, lookup(w_px), {}, {b_px});
op_py = rw(b, lookup(w_py), {}, {b_py});
op_padd = rw(b, add(P), {b_px, b_py}, {b_px});
op_add = rw(b, add(P), {b_x, b_px}, {b_x});
/* Two neox blocks of hd / 4 pairs, x (staged plane 1, the column) then y (plane 0). */
char sec[48];
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
for (Layer& l : L) {
l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h});
l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv});
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
RAD_F64("theta", theta), RAD_F64("eps", eps),
RAD_STR("mode", "blocks"), RAD_INT("v_norm", 1),
RAD_STR("sections", sec), RAD_STR("comps", "1 0")),
RAD_WEIGHTS(l.q_norm, l.k_norm)),
{b_qkv}, {b_qkv});
l.op_attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"), RAD_F64("scale", 1.0),
RAD_INT("max_seqlen", P), RAD_INT("window", 0)),
RAD_NOWEIGHTS),
{b_qkv}, {b_att});
l.op_o = rw(b, gemm(P, width, width, l.o), {b_att}, {b_o});
l.op_pa = rw(b, rms(P, l.post_attn), {b_o}, {b_o});
l.op_add1 = rw(b, add(P), {b_x, b_o}, {b_x});
l.op_pf = rw(b, rms(P, l.pre_ff), {b_x}, {b_h});
l.op_gu = rw(b, gemm(P, 2 * ff, width, l.gate_up), {b_h}, {b_gu});
l.op_act = rw(b, RAD_OP(b, "act_mul",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff),
RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_gu}, {b_ff});
l.op_down = rw(b, gemm(P, width, ff, l.down), {b_ff}, {b_o});
l.op_pff = rw(b, rms(P, l.post_ff), {b_o}, {b_o});
l.op_add2 = rw(b, add(P), {b_x, b_o}, {b_x});
}
op_pool = rw(b, RAD_OP(b, "pool_rows",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("k", kk), RAD_F64("mult", std::sqrt((double)width)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{b_x}, {b_pool});
if (standardize) {
op_sfill = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
RAD_STR("dtype", "bf16"), RAD_F64("value", -1.0)),
RAD_NOWEIGHTS),
{}, {b_sb});
op_sbias = rw(b, gain(w_sbias), {b_sb}, {b_sb});
op_sadd = rw(b, add(R), {b_pool, b_sb}, {b_pool});
op_sscale = rw(b, gain(w_sscale), {b_pool}, {b_pool});
}
op_norm = rw(b, rms(R, 0), {b_pool}, {b_pn});
op_out = rw(b, gemm(R, n_embd, width, w_proj), {b_pn}, {b_out});
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
e.patch_dim = patch_dim;
e.merge = kk;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"pooled %lldx%lld%s; %lld patches a pass -> %lld rows of %lld",
(long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff,
(long long)patch, (long long)pool, (long long)pool,
standardize ? ", standardised" : "", (long long)P, (long long)R,
(long long)n_embd);
on = true;
return RAD_OK;
}
void step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg, kk = pool * pool;
if (!on || Pn <= 0 || Pn > P || Pn % kk || S <= 0) {
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, "
"more patches than it was declared for, or not whole pooling windows");
return;
}
const int64_t Rn = Pn / kk;
const int32_t* crd = batch->enc_coord;
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand rc = praw2(crd, RAD_I32, 2, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_in), brows(b_x, Pn));
RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn));
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn));
RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn));
RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn),
brows(b_ff, Pn));
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn));
RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
}
RAD_ISSUE_N(c, op_pool, Pn, brows(b_x, Pn), brows(b_pool, Rn));
if (standardize) {
RAD_ISSUE_N(c, op_sfill, Rn, brows(b_sb, Rn));
RAD_ISSUE_N(c, op_sbias, Rn, brows(b_sb, Rn), RAD_W(w_sbias), brows(b_sb, Rn));
RAD_ISSUE_N(c, op_sadd, Rn, brows(b_pool, Rn), brows(b_sb, Rn), brows(b_pool, Rn));
RAD_ISSUE_N(c, op_sscale, Rn, brows(b_pool, Rn), RAD_W(w_sscale), brows(b_pool, Rn));
}
RAD_ISSUE_N(c, op_norm, Rn, brows(b_pool, Rn), RAD_NONE, brows(b_pn, Rn));
RAD_ISSUE_N(c, op_out, Rn, brows(b_pn, Rn), RAD_W(w_proj), brows(b_out, Rn));
}
};
} /* namespace gemma4_bf16 */
+10
View File
@@ -0,0 +1,10 @@
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
# radiance (`cmake -S arch/lfm2_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(lfm2_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(lfm2_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/lfm2_bf16.cpp)
+489
View File
@@ -0,0 +1,489 @@
/* lfm2_bf16 -- LiquidAI's LFM2 and LFM2-VL, bf16 weights and activations, one rank.
*
* ============================== THE SHAPE ==============================
*
* A hybrid of two layer kinds, in the order the checkpoint's `layer_types` lists them -- d1-3B's
* schedule is irregular (attention at 2, 5, 9, 13, ...), so it is read, never 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, NeoX rotary over the whole head
*
* each followed by a SwiGLU feed-forward (w1 the gate, w3 the up, w2 the down). Every norm is a
* plain RMSNorm -- `x_hat * w`, not Gemma's `1 + w` -- and the final one is `embedding_norm`. At
* d1-3B: 30 layers (10 attention), hidden 2048, 32 heads over 8 at head_dim 64, ffn 10752,
* vocabulary 128000 with the lm_head TIED to the embedding, conv width 3.
*
* LFM2-VL nests the same text model under `model.language_model` and adds a SigLIP2 tower and a
* projector (siglip2.h), declared when the container carries their weights and the deployment
* asked for media; the projector's rows replace the image placeholders' embeddings, which rotate
* at their token positions like any other token. A text-only LFM2 checkpoint keeps the text model
* under `model`. Which one this is is read off the config (a VL checkpoint has a `text_config`),
* not off the model's name.
*
* ============================== WHAT IT DOES NOT SERVE ==============================
*
* Tensor parallelism: one rank. A 3B model has no need of a second card, and the vocabulary
* shard, the head split and the all-reduces would be code no deployment runs. A drafter, MoE
* (LFM2-8B-A1B), conv bias, or a checkpoint without the rotary: each is refused by name.
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_mlp.h>
#include <arch/rad_block_vit.h>
#include "siglip2.h"
#include <sstream>
#include <string>
#include <vector>
namespace lfm2_bf16 {
using namespace rad::arch;
struct Layer {
bool attention = false;
MlpBF16 mlp;
rad_weight w_norm = 0, w_in = 0, w_out = 0;
/* conv */
rad_weight w_conv = 0;
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
/* attention: w_in is q, these are k, v and the two head norms */
rad_weight w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0;
rad_op op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
rad_op op_store = 0, op_attn = 0;
/* both */
rad_op op_norm = 0, op_in = 0, op_out = 0, op_add = 0;
};
struct Model {
Names nm{""};
Geom g{};
int64_t width = 0; /* conv_L_cache: the convolution's taps */
rad_kvgroup kv_attn = 0, kv_conv = 0;
rad_buf b_x = 0, b_h = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0;
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate_up = 0, b_ffn = 0;
rad_buf b_hout = 0, b_logits = 0;
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
std::vector<Layer> layers;
/* LFM2-VL's images: the tower and the scatter of its rows over the embeddings. */
bool media = false;
Siglip2 vit{};
MediaRows mrows{};
};
static Model g_model[MAX_RANKS];
/* A text_config key first, then the top level: a VL checkpoint nests the text model's settings
* and a text checkpoint does not. */
static const char* text_key(const RadModelMeta* m, const char* key) {
const std::string nested = std::string("text_config.") + key;
const char* v = rad_meta_gets(m, nested.c_str(), nullptr);
return v ? v : rad_meta_gets(m, key, nullptr);
}
static int64_t text_int(const RadModelMeta* m, const char* key, int64_t dflt) {
const char* v = text_key(m, key);
return v ? std::strtoll(v, nullptr, 10) : dflt;
}
static bool text_bool(const RadModelMeta* m, const char* key, bool dflt) {
const char* v = text_key(m, key);
if (!v) return dflt;
return std::strcmp(v, "true") == 0 || std::strcmp(v, "1") == 0;
}
/* `layer_types`, one word a layer. The container flattens the list space-separated. */
static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Layer>* out) {
const char* s = text_key(m, "layer_types");
if (!s || !*s) {
fprintf(stderr, "radiance: lfm2: the container has no layer_types; this family's schedule "
"is irregular and is not derived\n");
return RAD_E_FORMAT;
}
std::istringstream in(s);
std::string kind;
while (in >> kind) {
if (kind != "conv" && kind != "full_attention") {
fprintf(stderr, "radiance: lfm2: layer_types[%zu] is '%s'; this plugin knows 'conv' "
"and 'full_attention'\n", out->size(), kind.c_str());
return RAD_E_UNSUPPORTED;
}
Layer l;
l.attention = kind == "full_attention";
out->push_back(l);
}
if ((int64_t)out->size() != n_layer) {
fprintf(stderr, "radiance: lfm2: layer_types names %zu layers and the model has %lld\n",
out->size(), (long long)n_layer);
return RAD_E_FORMAT;
}
return RAD_OK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: lfm2_bf16 serves one rank; run it with --tp 1\n");
return RAD_E_UNSUPPORTED;
}
if (meta->n_expert > 0 || text_bool(meta, "conv_bias", false) ||
!text_bool(meta, "block_use_swiglu", true) || !text_bool(meta, "use_pos_enc", true)) {
fprintf(stderr, "radiance: lfm2_bf16 serves the dense SwiGLU model with rotary "
"attention and bias-free convolutions; this checkpoint is not that\n");
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
Names& nm = m.nm;
/* The FFN width as stated, unless the config asks for LFM2's sizing rule (the 1.2B and
* smaller releases): two thirds of it, times the multiplier, rounded up to `multiple_of`. */
RadModelMeta dims = *meta;
if (text_bool(meta, "block_auto_adjust_ff_dim", false)) {
int64_t ff = 2 * dims.n_ff / 3;
if (const char* mult = text_key(meta, "block_ffn_dim_multiplier")) {
const int64_t of = text_int(meta, "block_multiple_of", 256);
const double f = std::strtod(mult, nullptr);
if (!(f > 0.0) || of <= 0) return RAD_E_FORMAT;
ff = (int64_t)(f * (double)ff);
ff = of * ((ff + of - 1) / of);
}
dims.n_ff = ff;
}
RAD_ARCH_TRY(geom_from(m.g, &dims, ctx, "bf16", RAD_BF16));
Geom& g = m.g;
RAD_ARCH_TRY(yarn_from(g, meta, "", g.head_dim));
RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &m.layers));
m.width = text_int(meta, "conv_L_cache", 0);
if (m.width < 2 || m.width > 8) {
fprintf(stderr, "radiance: lfm2: conv_L_cache %lld is outside the 2..8 the convolution "
"kernels serve\n", (long long)m.width);
return RAD_E_UNSUPPORTED;
}
const char* pre = rad_meta_gets(meta, "text_config.num_hidden_layers", nullptr)
? "model.language_model" : "model";
/* ---- the two state groups: paged KV for the attention layers, and a rolling window of the
* convolution's last width-1 inputs (plus the speculative slack the manager adds) for the
* conv layers. The conv group's channels are n_head_kv * head_dim: one "head" of n_embd. */
RadKVGroupDecl fd{};
fd.kind = RAD_KV_FULL;
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
fd.n_head_kv = g.n_head_kv;
fd.head_dim = g.head_dim;
m.kv_attn = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
g.kv_dtype = rad_dtype_name(fd.dtype);
RadKVGroupDecl cd{};
cd.kind = RAD_KV_CONV;
cd.dtype = RAD_BF16;
cd.n_head_kv = 1;
cd.head_dim = g.n_embd;
cd.conv_width = m.width;
m.kv_conv = rad_decl_kv_group(b, nm.f("kv_conv"), &cd);
if (!m.kv_attn || !m.kv_conv) return RAD_E_INVAL;
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_bcx = decl_b(b, nm.f("conv_bcx"), RAD_BF16, {g.max_tok, 3 * g.n_embd});
m.b_conv_in = decl_b(b, nm.f("conv_in"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_conv_out = decl_b(b, nm.f("conv_out"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_q = decl_b(b, nm.f("attn_q"), RAD_BF16, {g.max_tok, g.q_dim()});
m.b_k = decl_b(b, nm.f("attn_k"), RAD_BF16, {g.max_tok, g.kv_dim()});
m.b_v = decl_b(b, nm.f("attn_v"), RAD_BF16, {g.max_tok, g.kv_dim()});
m.b_attn = decl_b(b, nm.f("attn_out"), RAD_BF16, {g.max_tok, g.q_dim()});
m.b_gate_up = decl_b(b, nm.f("gate_up"), RAD_BF16, {g.max_tok, 2 * g.n_ff});
m.b_ffn = decl_b(b, nm.f("ffn"), RAD_BF16, {g.max_tok, g.n_ff});
m.b_hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
/* ---- the vocabulary edges. The lm_head is tied in every release so far, and declared as a
* weight of its own anyway: the embedding lives in host memory (--embedding-placement) and the
* head on the card, and a kernel may ask the head for a layout the lookup does not read. */
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.embedding_norm.weight", pre)));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("%s.embed_tokens.weight", pre)));
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.w_lm_head = decl_w(b, nm.f("output.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.w_tok)),
{}, {m.b_x});
/* The encoder's rows, over the lookup: one rank, so nothing is reduced after it. */
m.media = Siglip2::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
MlpBF16::Wire mw{};
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
auto gemm = [&](int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) {
return rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w)),
{in}, {out});
};
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out) {
return rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w)),
{in}, {out});
};
auto layer_w = [&](const char* name, int l, std::initializer_list<int64_t> shape,
uint32_t dtype) {
return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
};
for (int l = 0; l < (int)m.layers.size(); ++l) {
Layer& L = m.layers[(size_t)l];
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),
nm.ckpt("%s.layers.%d.operator_norm.weight", pre, l)));
L.w_norm = layer_w("blk.%d.attn_norm.weight", l, {g.n_embd}, RAD_F32);
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
if (L.attention) {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_attn));
const char* a = "%s.layers.%d.self_attn.%s";
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), nm.ckpt(a, pre, l, "q_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), nm.ckpt(a, pre, l, "k_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), nm.ckpt(a, pre, l, "v_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l),
nm.ckpt(a, pre, l, "q_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l),
nm.ckpt(a, pre, l, "k_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l),
nm.ckpt(a, pre, l, "out_proj.weight")));
L.w_in = layer_w("blk.%d.attn_q.weight", l, {g.q_dim(), g.n_embd}, RAD_BF16);
L.w_k = layer_w("blk.%d.attn_k.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
L.w_v = layer_w("blk.%d.attn_v.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
L.w_q_norm = layer_w("blk.%d.attn_q_norm.weight", l, {g.head_dim}, RAD_F32);
L.w_k_norm = layer_w("blk.%d.attn_k_norm.weight", l, {g.head_dim}, RAD_F32);
L.w_out = layer_w("blk.%d.attn_output.weight", l, {g.n_embd, g.q_dim()}, RAD_BF16);
L.op_in = gemm(g.q_dim(), g.n_embd, L.w_in, m.b_h, m.b_q);
L.op_k = gemm(g.kv_dim(), g.n_embd, L.w_k, m.b_h, m.b_k);
L.op_v = gemm(g.kv_dim(), g.n_embd, L.w_v, m.b_h, m.b_v);
/* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
* T * heads such rows. */
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q);
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k);
L.op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim,
"neox"), {m.b_q}, {m.b_q});
L.op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
"neox"), {m.b_k}, {m.b_k});
/* attn_paged before kv_store: the cache's block size is read off the resolved
* attention kernel. */
L.op_attn = rw(b, RAD_OP(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa()),
RAD_INT("causal", 1), RAD_INT("window", 0),
RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs),
RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{m.b_q}, {m.b_attn});
L.op_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, m.kv_attn)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{m.b_k, m.b_v}, {});
L.op_out = gemm(g.n_embd, g.q_dim(), L.w_out, m.b_attn, m.b_h);
} else {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv));
const char* c = "%s.layers.%d.conv.%s";
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_in.weight", l), nm.ckpt(c, pre, l, "in_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_out.weight", l), nm.ckpt(c, pre, l, "out_proj.weight")));
L.w_in = layer_w("blk.%d.conv_in.weight", l, {3 * g.n_embd, g.n_embd}, RAD_BF16);
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
* convert, as the gated delta net's conv1d is. */
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
L.w_out = layer_w("blk.%d.conv_out.weight", l, {g.n_embd, g.n_embd}, RAD_BF16);
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
L.op_in = gemm(3 * g.n_embd, g.n_embd, L.w_in, m.b_h, m.b_bcx);
L.op_gate_in = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_bcx}, {m.b_conv_in});
L.op_conv = rw(b, RAD_OP(b, "causal_conv1d",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(L.w_conv)),
{m.b_conv_in}, {m.b_conv_out});
L.op_gate_out = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_bcx, m.b_conv_out}, {m.b_conv_out});
L.op_out = gemm(g.n_embd, g.n_embd, L.w_out, m.b_conv_out, m.b_h);
}
L.op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_x, m.b_h}, {m.b_x});
MlpBF16::Src ms{};
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
ms.gate = nm.ckpt("%s.layers.%d.feed_forward.w1.weight", pre, l);
ms.up = nm.ckpt("%s.layers.%d.feed_forward.w3.weight", pre, l);
ms.down = nm.ckpt("%s.layers.%d.feed_forward.w2.weight", pre, l);
RAD_ARCH_TRY(L.mlp.declare(b, nm, g, l, mw, ms));
}
/* The final norm runs on the gathered rows only: it is per token, and those are the rows the
* lm_head reads. */
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_x}, {m.b_hout});
m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, m.b_hout);
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.w_lm_head)),
{m.b_hout}, {m.b_logits});
/* THE VISION TOWER, LAST, so its activations share the arena with every buffer above. */
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
int64_t n_attn = 0;
for (const Layer& L : m.layers) n_attn += L.attention ? 1 : 0;
rad_note(b, "lfm2: %lld layers, %lld attention + %lld short convolution of width %lld; "
"%lld heads over %lld at head_dim %lld, ffn %lld, vocab %lld",
(long long)g.n_layer, (long long)n_attn, (long long)(g.n_layer - n_attn),
(long long)m.width, (long long)g.n_head, (long long)g.n_head_kv,
(long long)g.head_dim, (long long)g.n_ff, (long long)g.n_vocab);
return RAD_OK;
}
/* THE CONVOLUTION IS ISSUED ONCE PER HALF OF THE STEP, as the PLE's and the gated delta net's
* are: the decode rows [0, D) with `num_accepted`, which leaves 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 tokens behind it has a
* history. The per-sequence arrays of the prefill half move to `+ D`; the token operands stay at
* their base, because the kernel reads rows at the absolute offsets in `cu`. */
static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch* batch, int l) {
const int64_t T = batch->n_tok, S = batch->n_seq;
const RadKVGroupBatch* cv = kv_batch(batch, m.kv_conv);
const int32_t* idx = cv ? cv->state_index : nullptr;
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
const int64_t P = S - D;
if (D > 0)
RAD_ISSUE_N(c, L.op_conv, DT,
brows(m.b_conv_in, DT), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
praw(batch->cu_seqlens, RAD_I32, D + 1), praw(idx, RAD_I32, D),
praw(batch->ctx_lens, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
brows(m.b_conv_out, DT));
if (P > 0)
RAD_ISSUE_N(c, L.op_conv, T,
brows(m.b_conv_in, T), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
praw(batch->cu_seqlens + D, RAD_I32, P + 1),
praw(idx ? idx + D : nullptr, RAD_I32, P),
praw(batch->ctx_lens + D, RAD_I32, P), RAD_NONE,
brows(m.b_conv_out, T));
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Geom& g = m.g;
if (batch->draft_pass || batch->spec_parent ||
(!m.media && (batch->enc || batch->n_mm_rows > 0))) {
rad_step_fail(c, "lfm2_bf16: this step asks for an encoder, a draft pass or media rows, "
"and the program declares none of them");
return;
}
/* AN ENCODER PASS RUNS THE VISION TOWER AND NOTHING ELSE (RadBatch::enc). */
if (batch->enc) {
m.vit.step(c, batch);
return;
}
const int64_t T = batch->n_tok, n = g.n_embd;
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
m.mrows.step(c, batch, m.b_x, T);
for (int l = 0; l < (int)m.layers.size(); ++l) {
const Layer& L = m.layers[(size_t)l];
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
if (L.attention) {
const RadKVGroupBatch* kv = kv_batch(batch, m.kv_attn);
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_q, T));
RAD_ISSUE(c, L.op_k, brows(m.b_h, T), RAD_W(L.w_k), brows(m.b_k, T));
RAD_ISSUE(c, L.op_v, brows(m.b_h, T), RAD_W(L.w_v), brows(m.b_v, T));
RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm),
brows(m.b_q, T));
RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm),
brows(m.b_k, T));
RAD_ISSUE(c, L.op_rope_q, brows(m.b_q, T), rope_pos1(batch, T));
RAD_ISSUE(c, L.op_rope_k, brows(m.b_k, T), rope_pos1(batch, T));
RAD_ISSUE(c, L.op_store, brows(m.b_k, T), brows(m.b_v, T),
praw(kv ? kv->slot_mapping : nullptr, RAD_I32, T), kv_cache(m.kv_attn, l));
RAD_ISSUE_N(c, L.op_attn, batch->max_q_len,
brows(m.b_q, T), kv_cache(m.kv_attn, l),
praw2(kv ? kv->block_table : nullptr, RAD_I32, batch->n_seq,
kv ? kv->block_table_pitch : 0),
praw(kv ? kv->seqused : nullptr, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(m.b_attn, T));
RAD_ISSUE(c, L.op_out, brows(m.b_attn, T), RAD_W(L.w_out), brows(m.b_h, T));
} else {
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_bcx, T));
RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T),
brows(m.b_conv_in, T));
conv_step(m, L, c, batch, l);
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
brows(m.b_conv_out, T));
RAD_ISSUE(c, L.op_out, brows(m.b_conv_out, T), RAD_W(L.w_out), brows(m.b_h, T));
}
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
L.mlp.step(c, batch);
}
/* The lm_head runs on the rows the sampler asked for and on nothing else; a prefill chunk
* that finishes no sequence issues none of it. */
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_x, T),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_out_norm), brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
}
}
} /* namespace lfm2_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.1.0",
"LiquidAI LFM2 / LFM2-VL, bf16: short gated convolutions and GQA attention in the "
"checkpoint's own schedule, one rank; LFM2-VL's SigLIP2 tower for images")
#endif
+329
View File
@@ -0,0 +1,329 @@
/* siglip2.h -- LFM2-VL's image encoder: the SigLIP2 NaFlex tower and the projector after it.
*
* WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
*
* x = patches @ Wp^T + bp the patch embedding, a linear layer over a patch
* row (y, x, channel)
* x += pos_table resampled to each segment's grid torch's antialiased half-pixel bilinear
* (grid_embed_aa), rounded before the add
* depth times:
* x += out(attn(qkv(LN1(x)))) full attention within a segment (one tile or the
* thumbnail), no rotary
* x += fc2(gelu_tanh(fc1(LN2(x))))
* y = post_LN(x)
* out = l2(gelu(l1([LN](y viewed [P/merge^2, merge^2 * width])))) the projector
*
* which is transformers' Siglip2VisionModel (no pooling head) followed by Lfm2VlMultiModalProjector.
* The projector's pixel unshuffle is a VIEW here: the processor stores each segment's patches in
* merge-block order (core/mm/processor.cpp, image_lfm2), so a block's merge^2 patches are
* consecutive rows, dy then dx -- the order the unshuffle concatenates them in. The tower itself
* does not care about the order: attention within a segment is permutation-equivariant and every
* other layer is per patch, and the position table is resampled at each patch's own (row, column).
*
* q, k and v are one fused weight, concatenated at convert (map_concat), so a layer is one QKV
* GEMM; the attention reads the three as column slices.
*
* Replicated, per-request weights and pass-sized activations, as arch/common/rad_block_vit.h's
* tower: see the notes there.
*/
#ifndef LFM2_SIGLIP2_H
#define LFM2_SIGLIP2_H
#include <arch/rad_arch.h>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace lfm2_bf16 {
using namespace rad::arch;
struct Siglip2 {
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, merge = 0, side = 0;
int64_t head_dim = 0, patch_dim = 0, proj_hidden = 0, n_embd = 0, P = 0;
float eps = 1e-6f;
bool proj_norm = false, on = false;
struct Layer {
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0;
rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
rad_weight up_w = 0, up_b = 0, down_w = 0, down_b = 0;
rad_op ln1 = 0, qkv = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
};
std::vector<Layer> L;
rad_weight w_patch = 0, b_patch = 0, w_pos = 0, pn_w = 0, pn_b = 0;
rad_weight mn_w = 0, mn_b = 0, m1_w = 0, m1_b = 0, m2_w = 0, m2_b = 0;
rad_op op_patch = 0, op_pos = 0, op_post = 0, op_mln = 0, op_m1 = 0, op_m2 = 0;
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_mh = 0, b_mn = 0, b_mf = 0;
rad_buf b_out = 0;
/* A tower to declare: the container is an LFM2-VL one, whose vision_config is SigLIP2's. */
static bool present(const RadModelMeta* m) {
return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "siglip2_vision_model") &&
rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
}
/* Input patches an output row: the projector's unshuffle. */
static int64_t merge_of(const RadModelMeta* m) {
const int64_t d = rad_meta_geti(m, "downsample_factor", 0);
return d * d;
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int Siglip2::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
Names& nm, int64_t model_embd, int first_group) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
eps = (float)rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-6);
const int64_t chans = rad_meta_geti(m, "vision_config.num_channels", 3);
const int64_t npos = rad_meta_geti(m, "vision_config.num_patches", 0);
merge = rad_meta_geti(m, "downsample_factor", 0);
proj_hidden = rad_meta_geti(m, "projector_hidden_size", 0);
n_embd = model_embd;
side = (int64_t)std::llround(std::sqrt((double)npos));
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || merge <= 0 ||
proj_hidden <= 0 || side <= 0 || side * side != npos || width % heads || chans != 3) {
fprintf(stderr, "radiance: lfm2: the container's SigLIP2 vision_config is incomplete or "
"inconsistent (layers %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
"positions %lld, channels %lld; downsample_factor %lld, projector %lld)\n",
(long long)depth, (long long)width, (long long)heads, (long long)ff,
(long long)patch, (long long)npos, (long long)chans, (long long)merge,
(long long)proj_hidden);
return RAD_E_INVAL;
}
/* The pooling head is SigLIP2's contrastive readout; LFM2-VL reads the patch rows, and a
* checkpoint that ships a head would load weights nothing runs. Refused by name. */
if (rad_meta_geti(m, "vision_config.vision_use_head", 0) != 0 ||
!std::strcmp(rad_meta_gets(m, "vision_config.vision_use_head", ""), "true")) {
fprintf(stderr, "radiance: lfm2: this SigLIP2 tower has a pooling head, which LFM2-VL does "
"not read and this plugin does not serve\n");
return RAD_E_UNSUPPORTED;
}
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu_pytorch_tanh");
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
if (std::strcmp(act, "gelu_pytorch_tanh") || std::strcmp(pact, "gelu")) {
fprintf(stderr, "radiance: lfm2: the tower's activation '%s' and the projector's '%s' are "
"not gelu_pytorch_tanh and gelu, which is what this plugin serves\n",
act, pact);
return RAD_E_UNSUPPORTED;
}
const char* pb = rad_meta_gets(m, "projector_bias", "true");
if (std::strcmp(pb, "true") && std::strcmp(pb, "1")) {
fprintf(stderr, "radiance: lfm2: a projector without biases is not served\n");
return RAD_E_UNSUPPORTED;
}
proj_norm = !std::strcmp(rad_meta_gets(m, "projector_use_layernorm", "true"), "true") ||
!std::strcmp(rad_meta_gets(m, "projector_use_layernorm", "true"), "1");
head_dim = width / heads;
patch_dim = chans * patch * patch;
const int64_t mm = merge * merge, mw = mm * width;
P = ctx->max_enc_patches;
/* The longest segment attention sees: a tile or the largest thumbnail, which the processor
* keeps within max_num_patches. A bound that picks the attention kernel's block height, so it
* is the real one in a sizing declare too. */
const int64_t seg = rad_meta_geti(m, "processor.image_processor.max_num_patches",
rad_meta_geti(m, "max_num_patches", P));
const int64_t max_seg = std::min<int64_t>(P, seg);
if (ctx->shape_probe) {
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
P = std::max<int64_t>(mm, r / mm * mm);
}
if (P % mm) return RAD_E_SHAPE;
const int64_t R = P / mm;
const int ACC = RAD_ACCESS_PER_REQUEST;
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
RadWeightGroup g) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
};
const char* tw = "model.vision_tower.vision_model.";
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("%sembeddings.patch_embedding.weight", tw),
{ width, patch_dim }, grp_model());
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("%sembeddings.patch_embedding.bias", tw),
{ width }, grp_model());
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%sembeddings.position_embedding.weight", tw),
{ npos, width }, grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const RadWeightGroup g = grp_layer(first_group + (int)i);
const int li = (int)i;
const char* e = "%sencoder.layers.%d.%s";
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt(e, tw, li, "layer_norm1.weight"), { width }, g);
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt(e, tw, li, "layer_norm1.bias"), { width }, g);
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt(e, tw, li, "layer_norm2.weight"), { width }, g);
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt(e, tw, li, "layer_norm2.bias"), { width }, g);
/* q, k, v fused at convert: one GEMM a layer. */
const char* qw = nm.f("v.blk.%d.qkv.weight", li);
const char* qb = nm.f("v.blk.%d.qkv.bias", li);
if (map_concat(b, qw, { nm.ckpt(e, tw, li, "self_attn.q_proj.weight"),
nm.ckpt(e, tw, li, "self_attn.k_proj.weight"),
nm.ckpt(e, tw, li, "self_attn.v_proj.weight") }) < 0 ||
map_concat(b, qb, { nm.ckpt(e, tw, li, "self_attn.q_proj.bias"),
nm.ckpt(e, tw, li, "self_attn.k_proj.bias"),
nm.ckpt(e, tw, li, "self_attn.v_proj.bias") }) < 0)
return RAD_E_INVAL;
l.qkv_w = decl_w(b, qw, RAD_BF16, { 3 * width, width }, ACC, RAD_SHARD_NONE, g);
l.qkv_b = decl_w(b, qb, RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g);
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt(e, tw, li, "self_attn.out_proj.weight"), { width, width }, g);
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt(e, tw, li, "self_attn.out_proj.bias"), { width }, g);
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt(e, tw, li, "mlp.fc1.weight"), { ff, width }, g);
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt(e, tw, li, "mlp.fc1.bias"), { ff }, g);
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt(e, tw, li, "mlp.fc2.weight"), { width, ff }, g);
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt(e, tw, li, "mlp.fc2.bias"), { width }, g);
if (!l.n1w || !l.n1b || !l.n2w || !l.n2b || !l.qkv_w || !l.qkv_b || !l.out_w ||
!l.out_b || !l.up_w || !l.up_b || !l.down_w || !l.down_b)
return RAD_E_INVAL;
}
pn_w = bw(nm.f("v.post_norm.weight"), nm.ckpt("%spost_layernorm.weight", tw), { width }, grp_model());
pn_b = bw(nm.f("v.post_norm.bias"), nm.ckpt("%spost_layernorm.bias", tw), { width }, grp_model());
const char* pj = "model.multi_modal_projector.";
if (proj_norm) {
mn_w = bw(nm.f("v.proj.norm.weight"), nm.ckpt("%slayer_norm.weight", pj), { mw }, grp_model());
mn_b = bw(nm.f("v.proj.norm.bias"), nm.ckpt("%slayer_norm.bias", pj), { mw }, grp_model());
if (!mn_w || !mn_b) return RAD_E_INVAL;
}
m1_w = bw(nm.f("v.proj.fc1.weight"), nm.ckpt("%slinear_1.weight", pj), { proj_hidden, mw }, grp_model());
m1_b = bw(nm.f("v.proj.fc1.bias"), nm.ckpt("%slinear_1.bias", pj), { proj_hidden }, grp_model());
m2_w = bw(nm.f("v.proj.fc2.weight"), nm.ckpt("%slinear_2.weight", pj), { n_embd, proj_hidden }, grp_model());
m2_b = bw(nm.f("v.proj.fc2.bias"), nm.ckpt("%slinear_2.bias", pj), { n_embd }, grp_model());
if (!w_patch || !b_patch || !w_pos || !pn_w || !pn_b || !m1_w || !m1_b || !m2_w || !m2_b)
return RAD_E_INVAL;
/* ---- activations. `mh` is the post-norm's output declared at the MERGED width: the norm
* writes P rows of `width` and the projector reads P/mm rows of mm * width, the same bytes. */
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mw });
if (proj_norm) b_mn = decl_b(b, nm.f("v.mn"), RAD_BF16, { R, mw });
b_mf = decl_b(b, nm.f("v.mf"), RAD_BF16, { R, proj_hidden });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_qkv || !b_att || !b_ff || !b_mh || (proj_norm && !b_mn) || !b_mf ||
!b_out)
return RAD_E_INVAL;
auto gemm = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
rad_weight bias) -> rad_op {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
RAD_WEIGHTS(w, bias));
};
auto lnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_weight bias) -> rad_op {
return RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
op_patch = rw(b, gemm(P, width, patch_dim, "none", w_patch, b_patch), {}, { b_x });
op_pos = rw(b, RAD_OP(b, "grid_embed_aa",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("side", side), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_pos)),
{ b_x }, { b_x });
for (Layer& l : L) {
l.ln1 = rw(b, lnorm(P, width, l.n1w, l.n1b), { b_x }, { b_h });
l.qkv = rw(b, gemm(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
RAD_INT("max_seqlen", max_seg)),
RAD_NOWEIGHTS),
{ b_qkv }, { b_att });
l.proj = rw(b, gemm(P, width, width, "none", l.out_w, l.out_b), { b_att, b_x }, { b_x });
l.ln2 = rw(b, lnorm(P, width, l.n2w, l.n2b), { b_x }, { b_h });
l.up = rw(b, gemm(P, ff, width, "gelu_tanh", l.up_w, l.up_b), { b_h }, { b_ff });
l.down = rw(b, gemm(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_x }, { b_x });
}
op_post = rw(b, lnorm(P, width, pn_w, pn_b), { b_x }, { b_mh });
if (proj_norm) op_mln = rw(b, lnorm(R, mw, mn_w, mn_b), { b_mh }, { b_mn });
op_m1 = rw(b, gemm(R, proj_hidden, mw, "gelu", m1_w, m1_b), { proj_norm ? b_mn : b_mh }, { b_mf });
op_m2 = rw(b, gemm(R, n_embd, proj_hidden, "none", m2_w, m2_b), { b_mf }, { b_out });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE;
e.patch_dim = patch_dim;
e.merge = mm;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "SigLIP2 tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"%lld x %lld position table; projector %lld -> %lld -> %lld%s; %lld patches a "
"pass -> %lld rows",
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
(long long)ff, (long long)patch, (long long)side, (long long)side,
(long long)mw, (long long)proj_hidden, (long long)n_embd,
proj_norm ? " behind a layer norm" : "", (long long)P, (long long)R);
}
on = true;
return RAD_OK;
}
inline void Siglip2::step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
const int64_t mm = merge * merge, Rn = Pn / mm;
if (!on || batch->enc != RAD_MM_IMAGE || Pn <= 0 || Pn > P || Pn % mm || S <= 0) {
rad_step_fail(c, "lfm2: an encoder pass this program's SigLIP2 tower cannot serve: no "
"tower, not images, more patches than it was declared for, or not whole "
"merged rows");
return;
}
/* The patches, their coordinates -- a dense [4, P] of row, column, segment height and width,
* which is what the position resample reads -- and the segment boundaries. */
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
brows(b_qkv, Pn));
RAD_ISSUE_N(c, l.attn, Pn,
bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
brows(b_x, Pn), brows(b_x, Pn));
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_x, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
brows(b_ff, Pn));
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
brows(b_x, Pn), brows(b_x, Pn));
}
/* The post-norm writes Pn rows of `width` into a buffer declared at the merged width: the
* same bytes the projector reads as Pn/mm rows -- the pixel unshuffle. */
RAD_ISSUE_N(c, op_post, Pn, brows(b_x, Pn), RAD_W(pn_w), RAD_W(pn_b), brows(b_mh, Rn));
if (proj_norm)
RAD_ISSUE_N(c, op_mln, Rn, brows(b_mh, Rn), RAD_W(mn_w), RAD_W(mn_b), brows(b_mn, Rn));
RAD_ISSUE_N(c, op_m1, Rn, brows(proj_norm ? b_mn : b_mh, Rn), RAD_W(m1_w), RAD_W(m1_b),
RAD_NONE, brows(b_mf, Rn));
RAD_ISSUE_N(c, op_m2, Rn, brows(b_mf, Rn), RAD_W(m2_w), RAD_W(m2_b), RAD_NONE,
brows(b_out, Rn));
}
} /* namespace lfm2_bf16 */
#endif /* LFM2_SIGLIP2_H */
+20 -5
View File
@@ -493,13 +493,24 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
* vocab-sharded, asked here rather than re-derived, because a buffer that disagreed with the
* op declared over it is a read past its end. */
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)});
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, dc.sel_topk});
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, dc.sel_topk});
/* THE CANDIDATES ARE RESCORED against the target's head when logit_rerank can read its plane
* (fp8 or int8 rows) and every candidate a rank proposes is one it owns -- the rule the block
* applies; the planes are then kRerankR wide and the selector reads the first sel_topk. */
{
const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16);
if ((hd == RAD_F8E4M3 || hd == RAD_I8) && (Dflash2::head_sharded(dg) || dg.world <= 1)) {
m.df.w_lm = m.w_lm_head;
m.df.top_w = Dflash2::kRerankR;
}
}
const int64_t tw = m.df.w_lm ? m.df.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});
/* The vocab-parallel candidate exchange, and only when there is one: this rank's top-R as
* (int32 id, float value) pairs and the all-gathered world_size * R of them. */
if (Dflash2::head_sharded(dg)) {
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, dc.sel_topk, 2});
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * dc.sel_topk, 2});
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});
}
/* NAMED, because the engine reads the draft out of it by name: a DFlash2 pass proposes through
* the selector and never through the sampler's token buffer. */
@@ -678,7 +689,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* the 16 attention layers pay it, because the 48 delta-net layers carry fixed-size state
* instead. At eight sequences of 16k that is 4.3 GB of read traffic a step, which is most of
* what depth costs at that concurrency, and halving the width halves it. It also halves what a
* sequence costs in --vram-kv-mib, which is context and batch size as well as time.
* sequence costs in the KV pool, which is context and batch size as well as time.
*
* IT IS OFF BY DEFAULT ON A QUALITY ARGUMENT, not as a precaution. Greedy continuations from a
* long prompt agree between bf16 and fp8 for the first few hundred tokens and then diverge,
@@ -1086,6 +1097,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, mlp_fold, mlp_add,
mlp_ar_in, mlp_ar_out));
}
#if QWEN35_MOE
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
for (int64_t l = 0; l + 1 < m.n_main; ++l) m.layers[(size_t)l].mlp.xp_next = &m.layers[(size_t)l + 1].mlp;
#endif
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),
+3
View File
@@ -1232,6 +1232,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
}
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
for (size_t l = 0; l + 1 < m.layers.size(); ++l) m.layers[l].mlp.xp_next = &m.layers[l + 1].mlp;
/* ---- the 97th connection. No write half, no fp8 twin: it produces the one hidden state the
* lm_head reads, as a bf16 input. Its `hc_norm` is what a pre-norm model calls the
* final norm -- this checkpoint has no `model.language_model.norm.weight` at all. */
+11
View File
@@ -0,0 +1,11 @@
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
# radiance (`cmake -S arch/qwenimage21 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(qwenimage21 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwenimage21 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwenimage21.cpp)
File diff suppressed because it is too large. Load diff
+22
View File
@@ -32,6 +32,8 @@
# the tree, where a plugin installs beside the engine under the same prefix;
# radiance-config.cmake sets it to the found installation's home, so a plugin
# built out of tree installs where that engine's loader scans.
# RAD_HIP_VOPD_REPEATABLE ON when the HIP compiler's VOPD pairing is repeatable; unset is OFF,
# which turns the pairing off on LLVM 24 (rad_hip_repeatable, below).
# For CMAKE_INSTALL_DATADIR, below. Idempotent, and included here rather than left to the includer
# because this file is what needs it: a consumer project has no reason to have included it, and the
@@ -154,6 +156,25 @@ function(rad_add_plugin name kind)
endif()
endfunction()
# REPEATABLE DEVICE CODE ON LLVM 24. ROCm 10.1's clang (AMD clang 24) does not compile the same
# source to the same code twice. Its post-RA scheduler pairs VALU instructions for dual issue
# (VOPD), and the pairing pass (GCNVOPDUtils.cpp) caches each load's transitive load dependencies;
# fusing a pair adds edges behind that cache, and which entries were cached before a fusion
# follows the iteration order of a pointer-keyed set -- heap addresses. So every compile can pair
# differently: r4d_hc_bf16.hip came out with a different .text on each of three builds, a kernel's
# speed depends on which build it came from, and no comparison between two builds can be trusted.
# LLVM 22 (ROCm 7.2) pairs without that cache and is repeatable.
#
# The image builds its compiler's libLLVM with the cache dropped after every fusion
# (docker/llvm-vopd-pairing.patch) and says so with RAD_HIP_VOPD_REPEATABLE=ON. Any other LLVM 24
# has the pairing turned off: repeatable, at a price -- 1.4 to 3.5% on the fp8 prefill tiles.
function(rad_hip_repeatable tgt)
if(CMAKE_HIP_COMPILER_ID STREQUAL "Clang" AND CMAKE_HIP_COMPILER_VERSION VERSION_GREATER_EQUAL 24
AND NOT RAD_HIP_VOPD_REPEATABLE)
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:-mllvm=-amdgpu-enable-vopd=false>)
endif()
endfunction()
# Mark a target's device sources as HIP and pin the architecture. -ffp-contract=off is mandatory
# for any quantised cross-rank op: two ranks see the two dequantised products in the opposite order
# and contracting either into an FMA makes them disagree by ~1 ULP, which breaks the
@@ -196,6 +217,7 @@ function(rad_hipify tgt)
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:--no-offload-compress>)
target_link_options(${tgt} PRIVATE $<$<LINK_LANGUAGE:HIP>:--no-offload-compress>)
target_link_libraries(${tgt} PRIVATE ${RAD_HIP_RUNTIME})
rad_hip_repeatable(${tgt})
endfunction()
# Narrow RAD_GPU_TARGETS to the architectures ONE kernel library actually serves. A library states
+14 -1
View File
@@ -3,7 +3,7 @@
#
# Sources are globbed per subdirectory with CONFIGURE_DEPENDS so that adding a file to a component
# does not mean editing a file another component owns. Re-run cmake if a new file does not appear.
set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm)
set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag gen)
set(RAD_CORE_SRC "")
foreach(d ${RAD_CORE_DIRS})
@@ -40,6 +40,15 @@ endif()
if(RAD_HIP_FOUND)
target_compile_definitions(rad_core PUBLIC RAD_HAVE_HIP=1)
target_link_libraries(rad_core PUBLIC ${RAD_HIP_RUNTIME} ${RAD_HSA_RUNTIME})
# AN EXECUTABLE RUNS THE ROCm IT WAS BUILT AGAINST. The runtime is linked by its full path, but the
# HIP driver reports that directory among its implicit link directories, so CMake writes no RPATH
# for it: the engine, the tools and the tests loaded whichever libamdhip64.so.7 the system's loader
# cache names, and a tree built against a second ROCm beside /opt/rocm ran /opt/rocm's runtime
# under its own kernels. A linker flag and not CMake's RPATH, because install rewrites CMake's, and
# rewriting it beside the entry ROCm 10's clang gives a shared library left an empty element -- the
# current directory -- in the installed plugin.
get_filename_component(RAD_HIP_LIBDIR "${RAD_HIP_RUNTIME}" DIRECTORY)
target_link_options(rad_core INTERFACE "LINKER:-rpath,${RAD_HIP_LIBDIR}")
# THE AQL BACKEND'S OWN KERNELS: the copies and fills it dispatches for rad_memcpy_async and
# rad_memset_async.
target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/device/aql_blit.hip)
@@ -50,6 +59,9 @@ if(RAD_HIP_FOUND)
# WEIGHT-TABLE ENTRIES WRITTEN IN STREAM ORDER, their values carried in the arguments (runtime/wtab.h).
target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/runtime/wtab.hip)
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/runtime/wtab.hip PROPERTIES LANGUAGE HIP)
# THE NEXT-LAYER EXPERT PREFETCH's prediction, plan and table patches (runtime/xprefetch.h).
target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/runtime/xprefetch.hip)
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/runtime/xprefetch.hip PROPERTIES LANGUAGE HIP)
# THE CORE'S OWN KERNELS ARE BUILT FOR EVERY AMD GPU FAMILY, not only for the cards this build
# targets. They are what every copy and fill on a card runs, so an engine without a code object
# for a card cannot start on it -- whatever kernel plugin is installed for that card, and a plugin
@@ -60,6 +72,7 @@ if(RAD_HIP_FOUND)
gfx9-generic gfx9-4-generic gfx10-1-generic gfx10-3-generic gfx11-generic gfx12-generic)
list(REMOVE_DUPLICATES RAD_CORE_GPU_TARGETS)
set_target_properties(rad_core PROPERTIES HIP_ARCHITECTURES "${RAD_CORE_GPU_TARGETS}")
rad_hip_repeatable(rad_core)
# EVERY EXECUTABLE THAT LINKS THE CORE EXPORTS THE HIP ENTRY POINTS THE BACKEND DEFINES. A kernel
# plugin is dlopen'ed and its hipLaunchKernel binds to the first definition in the global scope,
# which is the executable's only if the executable exports it. Without this a plugin would launch
+4
View File
@@ -130,10 +130,14 @@ public:
rad_op decl_op (const char* op, const RadParam* p, int n_p,
const rad_weight* w, int n_w);
int op_resolved (rad_op h) const;
int op_declared (const char* op) const;
int decl_name_map(const RadNameMap* m);
int declare_logits(rad_buf b);
int declare_pooled(rad_buf b);
int declare_drafter(const RadDrafterDecl* d);
int drafter_shared_kv(int pos_offset);
int declare_encoder(const RadEncoderDecl* d);
int declare_generator(const RadGeneratorDecl* d);
void note_v (const char* f, va_list ap);
/* The buffer operands of an op.
+267 -29
View File
@@ -10,6 +10,7 @@
* and have fusion be a selection rather than a compiler pass (spec §2.3).
*/
#include "rad_build.h"
#include "../device/device.h"
#include <algorithm>
#include <climits>
@@ -45,6 +46,26 @@ std::string Program::Miss::line() const {
why.c_str());
}
std::vector<const Program::Miss*> Program::device_holes(bool host_backend) const {
/* By INSTANCE, because bands are: two declarations of one op can differ in geometry and in
* whether they carry a weight, and only the instance that missed decides whether the planner
* can move it to the host. */
std::set<std::pair<int32_t, std::string>> no_host;
for (const Miss& m : misses)
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.index, m.span);
std::vector<const Miss*> out;
for (const Miss& m : misses) {
if (m.domain == RAD_DOMAIN_HOST) continue;
const bool host_kernel = no_host.count(std::make_pair(m.index, m.span)) == 0;
/* An instance with no weight has nothing the planner places, so nothing moves it. */
const bool weightless = m.index > 0 && (size_t)m.index < ops.size() &&
ops[(size_t)m.index].weights.empty();
if (host_kernel && (host_backend || !weightless)) continue;
out.push_back(&m);
}
return out;
}
const char* bld_access_name(int a) {
switch (a) {
case RAD_ACCESS_PER_TOKEN: return "per-token";
@@ -565,7 +586,7 @@ void Builder::resolve_bands(OpInfo& oi) {
* reports the list whole (spec §3.1). */
prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span,
b.miss[d].empty() ? "no kernel matched" : b.miss[d],
d });
d, oi.index });
continue;
}
@@ -616,7 +637,7 @@ void Builder::finish_instances() {
r.geom.str().c_str(), rad_strerror(s));
b.miss[d] = fmt("init() refused the instance: %s", rad_strerror(s));
prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span,
b.miss[d], d });
b.miss[d], d, oi.index });
r = Resolved{};
}
}
@@ -814,6 +835,10 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
return resolved ? h : RAD_NULL_HANDLE;
}
int Builder::op_declared(const char* op) const {
return op && reg_.schema(op) ? 1 : 0;
}
int Builder::op_resolved(rad_op h) const {
if (h == 0 || h >= prog_.ops.size()) return 0;
const OpInfo& o = prog_.ops[h];
@@ -1036,10 +1061,60 @@ int Builder::declare_logits(rad_buf b) {
prog_.buffers[prog_.logits_buf].name.c_str(), prog_.buffers[b].name.c_str());
return RAD_E_STATE;
}
if (prog_.pooled_buf != RAD_NULL_HANDLE) {
err(RAD_E_STATE, "declare_logits: this program already declared '%s' as its pooled "
"output; a program generates or embeds, not both",
prog_.buffers[prog_.pooled_buf].name.c_str());
return RAD_E_STATE;
}
if (prog_.generator.layout != 0) {
err(RAD_E_STATE, "declare_logits: this program already declared the image generator '%s'",
prog_.gen_str.name.c_str());
return RAD_E_STATE;
}
prog_.logits_buf = b;
return RAD_OK;
}
/* The embedding program's output (rad_declare_pooled). Checked here for the logits buffer's
* reasons, and for shape: the core reads `n_seq` f32 rows of it from the device after every step,
* so a buffer narrower than a step's sequences, or in another dtype or domain, is refused now
* rather than read past or misread at the first request. */
int Builder::declare_pooled(rad_buf b) {
if (finished_) { err(RAD_E_STATE, "declare_pooled after declare finished"); return RAD_E_STATE; }
if (b == RAD_NULL_HANDLE || (size_t)b >= prog_.buffers.size()) {
err(RAD_E_INVAL, "declare_pooled: %u is not a declared buffer", (unsigned)b);
return RAD_E_INVAL;
}
if (prog_.pooled_buf != RAD_NULL_HANDLE && prog_.pooled_buf != b) {
err(RAD_E_STATE, "declare_pooled: '%s' was already named as the pooled output; '%s' is a "
"second one", prog_.buffers[prog_.pooled_buf].name.c_str(),
prog_.buffers[b].name.c_str());
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE) {
err(RAD_E_STATE, "declare_pooled: this program already declared '%s' as its logits; a "
"program generates or embeds, not both",
prog_.buffers[prog_.logits_buf].name.c_str());
return RAD_E_STATE;
}
if (prog_.generator.layout != 0) {
err(RAD_E_STATE, "declare_pooled: this program already declared the image generator '%s'",
prog_.gen_str.name.c_str());
return RAD_E_STATE;
}
const RadBufDecl& d = prog_.buffers[b].decl;
if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 ||
d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) {
err(RAD_E_INVAL, "declare_pooled: '%s' must be a device f32 buffer of [>= %lld, dim] -- "
"one row a sequence of the step",
prog_.buffers[b].name.c_str(), (long long)prog_.ctx.max_seqs);
return RAD_E_INVAL;
}
prog_.pooled_buf = b;
return RAD_OK;
}
/* WHAT THE ENCODER IS. Checked here, at declare, for the drafter's reason: an encoder is exercised
* only when a request carries media, so a declaration the engine cannot drive would otherwise
@@ -1054,30 +1129,36 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
if (!d) { err(RAD_E_INVAL, "declare_encoder: null declaration"); return RAD_E_INVAL; }
if (d->modalities == 0) return RAD_OK; /* declaring nothing is declaring nothing */
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
if (prog_.encoder.modalities != 0) {
err(RAD_E_STATE, "declare_encoder: '%s' already declared this program's encoder; '%s' is "
"a second one", prog_.encoder_name.c_str(), nm);
return RAD_E_STATE;
}
if ((d->modalities & ~(uint32_t)(RAD_MM_IMAGE | RAD_MM_VIDEO)) != 0) {
/* One vision encoder (images and video) and one audio encoder, each at most once. */
const bool audio = d->modalities == RAD_MM_AUDIO;
if (!audio && (d->modalities & ~(uint32_t)(RAD_MM_IMAGE | RAD_MM_VIDEO)) != 0) {
err(RAD_E_INVAL, "declare_encoder '%s': modalities 0x%x names a kind this engine has no "
"processor for", nm, (unsigned)d->modalities);
"processor for (an audio encoder serves audio alone)", nm,
(unsigned)d->modalities);
return RAD_E_INVAL;
}
RadEncoderDecl& slot = audio ? prog_.audio_encoder : prog_.encoder;
std::string& slot_name = audio ? prog_.audio_encoder_name : prog_.encoder_name;
if (slot.modalities != 0) {
err(RAD_E_STATE, "declare_encoder: '%s' already declared this program's %s encoder; '%s' "
"is a second one", slot_name.c_str(), audio ? "audio" : "image and video",
nm);
return RAD_E_STATE;
}
const int64_t want = audio ? prog_.ctx.max_audio_frames : prog_.ctx.max_enc_patches;
if (d->patch_dim <= 0 || d->merge <= 0 || d->n_embd <= 0) {
err(RAD_E_INVAL, "declare_encoder '%s': patch_dim %lld, merge %lld, n_embd %lld -- all "
"three must be positive", nm, (long long)d->patch_dim,
(long long)d->merge, (long long)d->n_embd);
return RAD_E_INVAL;
}
if (d->max_patches <= 0 || d->max_patches != prog_.ctx.max_enc_patches ||
d->max_patches % d->merge != 0) {
if (d->max_patches <= 0 || d->max_patches != want || d->max_patches % d->merge != 0) {
err(RAD_E_INVAL, "declare_encoder '%s': max_patches %lld, but this program was declared "
"with max_enc_patches %lld and a merge of %lld. The plugin sized its "
"activations with max_enc_patches and the core stages up to that many "
"patches a pass; they cannot differ, and a pass's patches must divide into "
"whole output rows.", nm, (long long)d->max_patches,
(long long)prog_.ctx.max_enc_patches, (long long)d->merge);
"with %s %lld and a merge of %lld. The plugin sized its activations with "
"that and the core stages up to that many patches a pass; they cannot "
"differ, and a pass's patches must divide into whole output rows.", nm,
(long long)d->max_patches, audio ? "max_audio_frames" : "max_enc_patches",
(long long)want, (long long)d->merge);
return RAD_E_INVAL;
}
if (d->out == RAD_NULL_HANDLE || (size_t)d->out >= prog_.buffers.size()) {
@@ -1096,9 +1177,108 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
(long long)d->n_embd);
return RAD_E_INVAL;
}
prog_.encoder = *d;
prog_.encoder_name = nm;
prog_.encoder.name = nullptr; /* the plugin's storage; encoder_name is the copy */
slot = *d;
slot_name = nm;
slot.name = nullptr; /* the plugin's storage; the name is the copy */
return RAD_OK;
}
/* WHAT THE GENERATOR IS. Checked whole here: a generator's every request runs all three of its
* passes, so a declaration the core cannot drive fails the first request rather than a rare one,
* and the first request is the wrong place to learn that the plugin sized its image buffer for a
* smaller picture than it says it makes. The strings are copied: the plugin's storage is not the
* Program's, and the Program outlives a declare. */
int Builder::declare_generator(const RadGeneratorDecl* d) {
if (finished_) { err(RAD_E_STATE, "declare_generator after declare finished"); return RAD_E_STATE; }
if (!d) { err(RAD_E_INVAL, "declare_generator: null declaration"); return RAD_E_INVAL; }
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
if (prog_.generator.layout != 0) {
err(RAD_E_STATE, "declare_generator: '%s' was already declared; '%s' is a second one",
prog_.gen_str.name.c_str(), nm);
return RAD_E_STATE;
}
if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE) {
err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program "
"generates text, embeds or makes images -- one of the three", nm,
prog_.logits_buf != RAD_NULL_HANDLE ? "logits" : "a pooled output");
return RAD_E_STATE;
}
if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID) {
err(RAD_E_INVAL, "declare_generator '%s': layout %d is not one this engine builds", nm,
(int)d->layout);
return RAD_E_INVAL;
}
auto has = [](const char* t, const char* what) { return t && std::strstr(t, what); };
if (!has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") ||
!has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) {
err(RAD_E_INVAL, "declare_generator '%s': tmpl_text needs {prompt}, tmpl_edit {images} and "
"{prompt}, and tmpl_image {image}, where the picture's tokens go", nm);
return RAD_E_INVAL;
}
if (d->latent_channels <= 0 || d->latent_scale <= 0 || d->size_multiple <= 0 ||
d->size_multiple % d->latent_scale != 0 || d->pixel_channels <= 0 ||
d->pixel_channels > 4 || d->slot_rows <= 0 || d->max_tokens <= 0 || d->max_refs < 0 ||
d->ref_area <= 0 || d->default_width <= 0 || d->default_height <= 0 ||
d->default_width % d->size_multiple != 0 || d->default_height % d->size_multiple != 0 ||
(d->default_width / d->latent_scale) * (d->default_height / d->latent_scale) > d->max_tokens ||
d->max_lanes <= 0) {
err(RAD_E_INVAL, "declare_generator '%s': a geometry field is out of range (latent %lld x "
"%lld px, multiple %lld, %lld channels, slot rows %lld, max %lld tokens, "
"default %lldx%lld, %lld lanes)", nm, (long long)d->latent_channels,
(long long)d->latent_scale, (long long)d->size_multiple, (long long)d->pixel_channels,
(long long)d->slot_rows, (long long)d->max_tokens, (long long)d->default_width,
(long long)d->default_height, (long long)d->max_lanes);
return RAD_E_INVAL;
}
if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) ||
(d->n_sigmas == 0 && d->default_steps <= 0) || !(d->default_cfg >= 1.0) ||
(d->dyn_shift && (d->max_seq <= d->base_seq || d->base_seq <= 0)) ||
(!d->dyn_shift && !(d->shift > 0)) || d->shift_terminal < 0 || d->shift_terminal >= 1) {
err(RAD_E_INVAL, "declare_generator '%s': the sampler is incomplete (%d fixed sigmas, %lld "
"default steps, shift %g, dynamic %d over %lld..%lld, terminal %g, "
"guidance %g)", nm, (int)d->n_sigmas, (long long)d->default_steps,
d->shift, (int)d->dyn_shift, (long long)d->base_seq, (long long)d->max_seq,
d->shift_terminal, d->default_cfg);
return RAD_E_INVAL;
}
for (int i = 0; i < d->n_sigmas; ++i)
if (!(d->sigmas[i] > 0.0 && d->sigmas[i] <= 1.0) ||
(i > 0 && !(d->sigmas[i] < d->sigmas[i - 1]))) {
err(RAD_E_INVAL, "declare_generator '%s': fixed sigma %d (%g) is not in (0, 1] below "
"the one before it", nm, i, d->sigmas[i]);
return RAD_E_INVAL;
}
if (d->image_out == RAD_NULL_HANDLE || (size_t)d->image_out >= prog_.buffers.size()) {
err(RAD_E_INVAL, "declare_generator '%s': image_out %u is not a declared buffer", nm,
(unsigned)d->image_out);
return RAD_E_INVAL;
}
const RadBufDecl& ob = prog_.buffers[d->image_out].decl;
int64_t numel = 1;
for (uint32_t i = 0; i < ob.rank; ++i) numel *= ob.shape[i];
const int64_t px = d->max_tokens * d->latent_scale * d->latent_scale;
if (ob.dtype != RAD_U8 || ob.domain != RAD_DOMAIN_DEVICE || numel < px * d->pixel_channels) {
err(RAD_E_INVAL, "declare_generator '%s': image_out '%s' must be a device u8 buffer of at "
"least %lld x %lld -- the largest image", nm,
prog_.buffers[d->image_out].name.c_str(), (long long)px, (long long)d->pixel_channels);
return RAD_E_INVAL;
}
Program::GenStrings& g = prog_.gen_str;
g.name = nm;
g.tmpl_text = d->tmpl_text;
g.tmpl_edit = d->tmpl_edit;
g.tmpl_image = d->tmpl_image;
g.tmpl_image_sep = d->tmpl_image_sep ? d->tmpl_image_sep : "";
g.drop_prefix = d->drop_prefix ? d->drop_prefix : "";
g.tmpl_transparent = d->tmpl_transparent ? d->tmpl_transparent : "";
g.sigmas.assign(d->sigmas, d->sigmas + d->n_sigmas);
prog_.generator = *d;
/* The Program is moved after declare, and a pointer into a moved string is a pointer into the
* old one's storage: nothing here may be read through the decl, only through gen_str. */
RadGeneratorDecl& c = prog_.generator;
c.name = c.tmpl_text = c.tmpl_edit = c.tmpl_image = c.tmpl_image_sep = nullptr;
c.drop_prefix = c.tmpl_transparent = nullptr;
c.sigmas = nullptr;
return RAD_OK;
}
@@ -1205,6 +1385,32 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
return RAD_OK;
}
/* A SERIAL HEAD THAT READS THE TRUNK'S CACHE AND KEEPS NONE (rad_builder.h). Checked here for the
* reason declare_drafter checks everything: the driver only reaches the head once a request
* speculates, and a head staged the wrong way round costs acceptance and says nothing. */
int Builder::drafter_shared_kv(int pos_offset) {
if (finished_) {
err(RAD_E_STATE, "drafter_shared_kv after declare finished");
return RAD_E_STATE;
}
if (prog_.drafter.kind != RAD_DRAFT_SERIAL) {
err(RAD_E_STATE, "drafter_shared_kv: %s. Only a SERIAL head runs round after round at one "
"position; declare it with rad_declare_drafter first.",
prog_.drafter.kind == RAD_DRAFT_NONE ? "no drafter is declared"
: "the declared drafter is a BLOCK drafter");
return RAD_E_STATE;
}
if (pos_offset != 0 && pos_offset != 1) {
err(RAD_E_INVAL, "drafter_shared_kv '%s': pos_offset %d. The rows sit at the committed "
"position (0) or one past it (1); nothing else names a position the head "
"was trained at.", prog_.drafter_name.c_str(), pos_offset);
return RAD_E_INVAL;
}
prog_.drafter_shared_kv = true;
prog_.drafter_pos_offset = pos_offset;
return RAD_OK;
}
void Builder::note_v(const char* f, va_list ap) {
char msg[1024];
vsnprintf(msg, sizeof msg, f ? f : "", ap);
@@ -1455,6 +1661,8 @@ void Builder::finish_kv_groups() {
default: break;
}
std::sort(gi.layers.begin(), gi.layers.end());
gi.drafter = prog_.meta.n_layers > 0 && !gi.layers.empty() &&
gi.layers.front() >= prog_.meta.n_layers;
/* A group nothing is bound to is a group the block manager cannot size: how many state
* instances a sequence owns is the layer count, and assuming one would make the page size
@@ -1526,6 +1734,8 @@ void Builder::finish_buffer_liveness() {
* empty and nothing that shared with logits before is prevented from doing so. The
* undeclared-use guard in core/runtime/issue.cpp is what refuses the untruthful version. */
if ((rad_buf)i == prog_.logits_buf && last_op > b.last_use) b.last_use = last_op;
/* The pooled output for the same reason: the engine reads it after the last op. */
if ((rad_buf)i == prog_.pooled_buf && last_op > b.last_use) b.last_use = last_op;
}
}
@@ -1559,6 +1769,19 @@ int Builder::finish() {
finish_weight_uses();
finish_layouts();
finish_kv_groups();
/* A HEAD DECLARED TO KEEP NO CACHE OF ITS OWN (rad_drafter_shared_kv) is given no history pass:
* the scheduler owes it none. A KV group bound at one of its layers -- meta.n_layers and above
* are the drafter's -- would then be read without anything ever having written it. */
if (prog_.drafter_shared_kv)
for (size_t g = 1; g < prog_.kv_groups.size(); ++g)
for (int l : prog_.kv_groups[g].layers)
if (l >= prog_.meta.n_layers) {
err(RAD_E_STATE, "drafter '%s' keeps no cache of its own (rad_drafter_shared_kv) "
"and its layer %d is bound to KV group '%s', which no pass "
"would ever write", prog_.drafter_name.c_str(), l,
prog_.kv_groups[g].name.c_str());
break;
}
finish_buffer_liveness();
int s = plan_buffers(prog_, &bufrep_);
@@ -1573,16 +1796,11 @@ int Builder::finish() {
* SPLIT BY DOMAIN, because the two counts mean different things and one total means
* neither. Every caller of this that is not the engine -- rad-check, rad-tune, rad-convert
* -- reads this line and nothing else, so it has to say which kind it found. */
/* A device miss whose op resolved on the HOST for the same band is not a hole -- the
* planner runs it there (engine_bringup.cpp's miss_report says the same thing at more
* length). Counting it as a device miss makes a deliberately host-only op open every run
* with a warning that names a hole there is not. */
std::set<std::pair<std::string, std::string>> no_host;
for (const Program::Miss& m : prog_.misses)
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span);
size_t dev = 0;
for (const Program::Miss& m : prog_.misses)
if (m.domain != RAD_DOMAIN_HOST && no_host.count(std::make_pair(m.op, m.span))) ++dev;
/* A device miss a host kernel stands in for is not a hole -- the planner runs it there
* (Program::device_holes has the rule, engine_bringup.cpp's miss_report the longer
* account). Counting it as a device miss makes a deliberately host-only op open every
* run with a warning that names a hole there is not. */
const size_t dev = prog_.device_holes(device_is_host()).size();
/* A host-only miss set is not a warning at all -- see the report in engine_bringup.cpp --
* so it does not get warned about here either. The device count is the one that means
* something to a tool reading this line and nothing else. */
@@ -1644,6 +1862,11 @@ int rad_op_resolved(RadBuilder* b, rad_op h) {
return B(b)->op_resolved(h);
}
int rad_op_declared(RadBuilder* b, const char* op) {
if (!b) return 0;
return B(b)->op_declared(op);
}
/* Proposed additions to rad_builder.h -- defined here so the mechanism exists and core-side
* callers (rad-convert, the tests) can use it. A C plugin cannot until the declarations
* move into the frozen header. */
@@ -1688,16 +1911,31 @@ int rad_declare_logits(RadBuilder* b, rad_buf logits) {
return B(b)->declare_logits(logits);
}
int rad_declare_pooled(RadBuilder* b, rad_buf pooled) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_pooled(pooled);
}
int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_drafter(d);
}
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) {
if (!b) return RAD_E_INVAL;
return B(b)->drafter_shared_kv(pos_offset);
}
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_encoder(d);
}
int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) {
if (!b) return RAD_E_INVAL;
return B(b)->declare_generator(d);
}
void rad_note(RadBuilder* b, const char* f, ...) {
if (!b) return;
va_list ap;
+4
View File
@@ -289,6 +289,10 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
"%d, drafter window %lld\n",
(long long)p.drafter.block, p.drafter.depth,
(int)p.drafter.mask_token, (long long)p.drafter.window);
if (p.drafter_shared_kv)
s += fmt(" cache none of its own: it reads the trunk's, owes no history, and "
"every round runs at the committed position%s\n",
p.drafter_pos_offset ? " (rotated one past it)" : "");
s += "\n";
}
+16 -4
View File
@@ -19,10 +19,20 @@ namespace rad {
/* One Registry for the life of the process. A Resolved, a Band and a KernelRow all point into a
* plugin's static tables, and the Program outlives the call that built it, so the registry cannot
* be a local. registry.h says the same thing about the engine. */
* be a local. registry.h says the same thing about the engine.
*
* NEVER DESTROYED, because exit destroys in the wrong order for it. A function-local static is
* constructed before the first plugin is loaded, so its destructor runs AFTER every plugin's own
* static destructors -- and closing from there calls each instance's fini into plugin state that
* no longer exists. libr4d's router keeps its per-device counter blocks in a global map; fini
* looked up and erased a node of the destroyed map, a double free that glibc reported as
* "corrupted size vs. prev_size" or "free(): invalid pointer" on whichever exit the heap layout
* exposed it. A caller that needs the finis to run closes the registry itself while the plugins
* are alive, as Engine's shutdown does; at exit the process is ending and what the instances
* hold goes with it. */
Registry& rad_tools_registry() {
static Registry r;
return r;
static Registry* r = new Registry();
return *r;
}
/* ------------------------------------------------------------------ the reference-kernel gate */
@@ -376,7 +386,9 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
* the same resolution as the plugin's. A sampler op that does not resolve is deliberately NOT
* a declare failure -- a deployment that never sends `typical_p` does not need a typical
* kernel -- so this returning negative means something structural, not a miss. */
if (also) {
/* NOT FOR AN EMBEDDING PROGRAM (rad_declare_pooled) OR AN IMAGE GENERATOR: neither samples a
* token, so a sampler chain in it would be ops and buffers no step ever issues. */
if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_generator()) {
/* THE WIDTH THE PLUGIN ACTUALLY DECLARED, handed over rather than re-derived. The sampler
* needs to know how much vocabulary THIS RANK produces, and the one place that is a fact
* is the logits buffer the plugin just named. Computing it a second time from n_vocab and
+314 -35
View File
@@ -9,6 +9,7 @@
#include "format/rope_override.h"
#include "sample/host_ref.h"
#include "server/oai.h"
#include "diag/diag.h"
#include <nlohmann/json.hpp>
@@ -39,35 +40,42 @@ static const std::string g_draft_window_help =
draft_window_name(kDraftWindowDefault);
static const Flag g_flags[] = {
{ "--model", "PATH", "the .rad container, or a checkpoint served as it stands" },
{ "--model", "PATH", "the .rad container, a checkpoint served as it stands, or a\n"
"Hugging Face repo id (owner/name), fetched before startup" },
{ "--download-dir", "DIR", "where a repo id is fetched to; default\n"
"$XDG_CACHE_HOME/radiance/hf, else ~/.cache/radiance/hf" },
{ "--radiance-home", "DIRS", "where kernels/, architectures/ and quantizers/ live; several\n"
"homes separated by ':' are searched in order, the first winning" },
{ "--kernels", "LIST", "kernel plugin hierarchy, comma-separated, first wins" },
{ "--kernels", "LIST", "the kernel libraries to use, comma-separated, first wins; unnamed ones are not loaded. Default: every library found" },
{ "--tp", "N", "tensor-parallel ranks" },
{ "--tp-wire", "MODE", "cross-rank all-reduce payload: exact (default) or wht6, a\n"
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 4,\n"
"none at 8" },
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 3\n"
"and 4, none at 8" },
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" },
{ "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n"
"asks the driver, on requires peer access and stops without\n"
"it, off exchanges through pinned host memory" },
{ "--max-num-batched-tokens", "N", "the largest token count one step may carry" },
{ "--busy-prefill-chunk", "MODE", "a prefill chunk's share of a step that has other work: auto\n"
"(default) leaves decode rows and new requests their room,\n"
"off takes the whole step, N holds the chunk to N tokens" },
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
"keys, no reconvert (docs/YARN.md); none: off" },
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
{ "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" },
{ "--vram-kv-mib", "N", "the paged KV pool; 0 derives it from the card" },
{ "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" },
{ "--host-pool-mib", "N", "pinned host tier" },
{ "--embedding-placement", "WHERE", "auto (default) | vram | ram: where the token embedding lives. ram\n"
" keeps it in the pinned host pool, read over the link in place;\n"
" auto keeps it on the card unless the KV cache could then not\n"
" hold one --max-model-len sequence. disk is refused: the lookup\n"
" writes the card's activations, which no host read can reach" },
{ "--embedding-placement", "WHERE", "ram (default) | vram: where the token embedding lives. ram\n"
" pins it in host memory beside --host-pool-mib, read over the\n"
" link in place; by default a model whose output head reads the\n"
" table, or a host without the memory, keeps it on the card" },
{ "--vision-tower-placement", "WHERE", "vram (default) | ram: where the encoder towers live (the\n"
" vision tower; the audio encoder too). ram pins them in host\n"
" memory beside --host-pool-mib, read over the link once an\n"
" image, and gives their VRAM to the KV cache" },
{ "--ngram-placement", "WHERE", "auto (default) | vram | ram | disk: where an n-gram\n"
" embedding table lives (Qwen3.8-Flash-Next: 47.7 GiB).\n"
" vram puts all of it on every card; ram copies it into\n"
@@ -78,15 +86,13 @@ static const Flag g_flags[] = {
{ "--weights-disk-tier", nullptr, "read weights that fit neither VRAM nor the host pool from the\n"
" container on disk (O_DIRECT); a routed expert is read a layer\n"
" at a time, so a step is paced by the drive" },
{ "--prefix-cache-host-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n"
{ "--prefix-cache-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n"
" so their VRAM can go to experts and a return restores\n"
" instead of re-prefilling. 0 is off. Part of it holds\n"
" linear-state snapshots on a hybrid model; startup says how many" },
{ "--prefix-cache-dir", "DIR", "where the disk tier keeps them. Not --weights-disk-tier, which is\n"
" about WEIGHTS" },
{ "--prefix-cache-disk-mib", "N", "and copy them on to disk under --prefix-cache-dir, up to N MiB,\n"
" so a full host tier gives slots up for nothing. Holds\n"
" conversation content unencrypted. 0 is off" },
" instead of re-prefilling. A full tier drops its least\n"
" recently used entries. 0 is off" },
{ "--prefix-cache-ttl", "S", "seconds a cached conversation no request uses is kept, in VRAM\n"
" or host memory (default 3600). 0 keeps it until the memory\n"
" is wanted" },
{ "--placement", "MODE", "all_vram | layer_offload | expert_tiered | auto" },
{ "--deterministic", nullptr, "pin placement to the plan the loader made, so the resident\n"
@@ -100,7 +106,8 @@ static const Flag g_flags[] = {
* 2 for the whole server rather than 2 x --max-num-seqs. At the default 8 slots and
* 8 sequences that is one snapshot a sequence, which is what an append-only chat wants --
* the next turn's hit lands at the end of the last one. */
{ "--checkpoint-slots", "N", "linear-state snapshots retained IN TOTAL (not "
{ "--checkpoint-slots", "N", "linear-state or sliding-window snapshots "
"retained IN TOTAL (not "
"per sequence), in pinned host memory; compare "
"against --max-num-seqs" },
{ "--no-prefix-cache", nullptr, "disable prefix caching" },
@@ -192,7 +199,10 @@ static const Flag g_flags[] = {
{ "--video-fps", "F", "frames sampled per second of video" },
{ "--video-min-frames", "N", "the fewest frames sampled from a video" },
{ "--video-max-frames", "N", "the most frames sampled from a video" },
{ "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap" },
{ "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap (a token\n"
" budget processor -- Gemma 4's -- takes 70, 140, 280, 560 or 1120)" },
{ "--image-tokens", "N", "a token-budget processor's image budget (Gemma 4: 70, 140, 280, 560, 1120;\n"
" default the container's); a request's `image_tokens` overrides it" },
{ "--max-source-pixels", "N", "the largest image or video frame the decoder accepts, before any resize\n"
" (default 67108864). The media flags above default to what the container\n"
" states, and do nothing for a model that takes no media" },
@@ -223,10 +233,19 @@ static const Flag g_flags[] = {
void config_usage(const char* argv0) {
fprintf(stderr, "usage: %s --model FILE [options]\n\n", argv0);
/* A help text's continuation lines start under its first line, whatever indentation the
* string itself carries. */
for (const Flag& f : g_flags) {
char left[64];
snprintf(left, sizeof left, "%s%s%s", f.name, f.arg ? " " : "", f.arg ? f.arg : "");
fprintf(stderr, " %-32s %s\n", left, f.help);
std::string help;
for (const char* p = f.help; *p; ++p) {
help += *p;
if (*p != '\n') continue;
help.append(35, ' ');
while (p[1] == ' ') ++p;
}
fprintf(stderr, " %-32s %s\n", left, help.c_str());
}
fprintf(stderr,
"\nEvery pool is budgeted explicitly. The trade between KV blocks and resident weights\n"
@@ -373,6 +392,7 @@ int config_parse(int argc, char** argv, Config* c) {
else if (S("-v")) log_set_level(Log::Debug);
else if (S("-vv")) log_set_level(Log::Trace);
else if (S("--model")) { if (!(v = need(i))) return RAD_E_INVAL; c->model = v; }
else if (S("--download-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->download_dir = v; }
else if (S("--radiance-home")) { if (!(v = need(i))) return RAD_E_INVAL; c->radiance_home = v; }
else if (S("--kernels")) { if (!(v = need(i))) return RAD_E_INVAL; c->kernel_hierarchy = split_commas(v); }
else if (S("--tp")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp = atoi(v); }
@@ -391,6 +411,18 @@ int config_parse(int argc, char** argv, Config* c) {
}
else if (S("--tp-wire-min-kb")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp_wire_min_kb = atoll(v); }
else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); }
else if (S("--busy-prefill-chunk")) {
if (!(v = need(i))) return RAD_E_INVAL;
char* end = nullptr;
const long long n = std::strtoll(v, &end, 10);
if (!std::strcmp(v, "auto")) c->busy_prefill_chunk = -1;
else if (!std::strcmp(v, "off")) c->busy_prefill_chunk = 0;
else if (end && end != v && *end == '\0' && n > 0) c->busy_prefill_chunk = n;
else {
RAD_ERR("--busy-prefill-chunk takes auto, off or a positive token count, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--max-num-seqs")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); }
else if (S("--max-model-len")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_ctx = atoll(v); }
else if (S("--rope-scaling")) {
@@ -405,8 +437,16 @@ int config_parse(int argc, char** argv, Config* c) {
}
c->rope_scaling = v;
}
else if (S("--vram-weights-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_weights_mib = atoll(v); }
else if (S("--vram-kv-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_kv_mib = atoll(v); }
/* THE TWO POOLS ARE THE BUDGET RESOLVER'S, always (core/mem/vram_budget.h). A launch
* line that tries to size them is told which flags move the split, rather than "unknown
* option". */
else if (S("--vram-weights-mib") || S("--vram-kv-mib")) {
RAD_ERR("%s was removed: the card is split between the weights and the cache from what "
"the model needs. --gpu-headroom-mib takes card space away, --max-model-len and "
"--max-num-seqs bound the cache, and --host-pool-mib decides which experts stay "
"on the card", a.c_str());
return RAD_E_INVAL;
}
/* --gpu-headroom takes the short name too: it is the flag an operator reaches for and
* "-mib" is the unit, which every other size flag in this list also spells out. Both
* parse to the same field. */
@@ -425,16 +465,55 @@ int config_parse(int argc, char** argv, Config* c) {
const bool emb = S("--embedding-placement");
if (!(v = need(i))) return RAD_E_INVAL;
TablePlacement p;
if (!parse_table_placement(v, &p)) {
/* The embedding has two tiers: its lookup writes activations the card reads, which a
* host kernel reading the container cannot reach, so there is no disk -- and with
* ram the default wherever it can be honoured, nothing left for auto to choose. */
if (emb && (!parse_table_placement(v, &p) ||
(p != TablePlacement::Ram && p != TablePlacement::Vram))) {
if (parse_table_placement(v, &p) && p == TablePlacement::Auto)
RAD_ERR("--embedding-placement auto was removed in 1.3.0: ram, the default, "
"holds the table in pinned host memory, and vram keeps it on the card. "
"Drop the flag or name one of the two");
else
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
return RAD_E_INVAL;
}
if (!emb && !parse_table_placement(v, &p)) {
RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v);
return RAD_E_INVAL;
}
(emb ? c->embedding_placement : c->ngram_placement) = p;
if (emb) c->embedding_placement_given = true;
}
else if (S("--vision-tower-placement")) {
if (!(v = need(i))) return RAD_E_INVAL;
TablePlacement p;
/* Two tiers, for the embedding's reason: an encoder writes activations the card reads. */
if (!parse_table_placement(v, &p) || (p != TablePlacement::Ram && p != TablePlacement::Vram)) {
RAD_ERR("--vision-tower-placement takes vram or ram, not '%s'", v);
return RAD_E_INVAL;
}
c->tower_placement = p;
}
else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; }
else if (S("--prefix-cache-host-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_host_mib = atoll(v); }
else if (S("--prefix-cache-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_dir = v; }
else if (S("--prefix-cache-disk-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_disk_mib = atoll(v); }
else if (S("--prefix-cache-mib")) { if (!(v = need(i)) ||
!parse_int(a.c_str(), v, 0, INT32_MAX, &c->prefix_cache_mib))
return RAD_E_INVAL; }
else if (S("--prefix-cache-ttl")) { if (!(v = need(i)) ||
!parse_int(a.c_str(), v, 0, INT32_MAX, &c->prefix_cache_ttl))
return RAD_E_INVAL; }
/* THE PREFIX CACHE KEEPS NOTHING ON A DRIVE: a tier there wore it at the rate the server
* prefills, and its copies never outlived the process. The old size flags are told what
* replaced them rather than "unknown option". */
else if (S("--prefix-cache-host-mib")) {
RAD_ERR("--prefix-cache-host-mib was renamed: use --prefix-cache-mib");
return RAD_E_INVAL;
}
else if (S("--prefix-cache-dir") || S("--prefix-cache-disk-mib")) {
RAD_ERR("%s was removed: the prefix cache is kept in VRAM and host memory only "
"(--prefix-cache-mib), and --prefix-cache-ttl says how long", a.c_str());
return RAD_E_INVAL;
}
else if (S("--placement")) { if (!(v = need(i))) return RAD_E_INVAL; c->placement = v; }
else if (S("--deterministic")) c->deterministic = true;
else if (S("--checkpoint-interval")) { if (!(v = need(i))) return RAD_E_INVAL; c->checkpoint_interval = atoll(v); }
@@ -681,6 +760,12 @@ int config_parse(int argc, char** argv, Config* c) {
if (!(d > 0.0)) { RAD_ERR("--video-fps must be > 0, not '%s'", v); return RAD_E_INVAL; }
c->video_fps = d;
}
else if (S("--image-tokens")) {
if (!(v = need(i))) return RAD_E_INVAL;
int64_t n = 0;
if (!parse_int(a.c_str(), v, 1, INT32_MAX, &n)) return RAD_E_INVAL;
c->image_tokens = (int32_t)n;
}
else if (S("--video-min-frames") || S("--video-max-frames") || S("--video-max-frame-tokens")) {
if (!(v = need(i))) return RAD_E_INVAL;
int64_t n = 0;
@@ -704,11 +789,16 @@ int config_parse(int argc, char** argv, Config* c) {
RAD_ERR("unknown option '%s'", a.c_str());
return RAD_E_INVAL;
}
/* WHERE EACH OPTION CAME FROM, for the startup report (core/diag/diag.h): every branch
* above that returned refused the option, so reaching here is the option taken. Under the
* table's spelling, so an alias reports as the option it is. */
c->given[S("--gpu-headroom") ? "--gpu-headroom-mib" : a] = "command line";
}
if (c->radiance_home.empty()) {
const char* h = getenv("RADIANCE_HOME");
c->radiance_home = h ? h : RAD_DEFAULT_HOME;
if (h) c->given["--radiance-home"] = "environment (RADIANCE_HOME)";
}
if (c->kernel_hierarchy.empty()) {
/* RADIANCE_KERNELS, ahead of the built-in default.
@@ -718,7 +808,10 @@ int config_parse(int argc, char** argv, Config* c) {
* plugin with rad-kbench or rad-tune has no way to serve with it short of editing every
* launcher's command line. Same spelling, same separator. */
const char* e = getenv("RADIANCE_KERNELS");
if (e && *e) c->kernel_hierarchy = split_commas(e);
if (e && *e) {
c->kernel_hierarchy = split_commas(e);
c->given["--kernels"] = "environment (RADIANCE_KERNELS)";
}
}
/* AND THERE IS NO BUILT-IN DEFAULT, deliberately. Naming a library here -- the RDNA4 one, say
* -- would make the core carry the name of one card's kernels, and on any other machine that
@@ -726,12 +819,12 @@ int config_parse(int argc, char** argv, Config* c) {
* rank the one that IS installed behind the reference implementation, which matches every op
* and would answer for all of them.
*
* An empty hierarchy is not "no order". The loader orders what it finds: everything named by
* --kernels or RADIANCE_KERNELS first, then every other plugin, then the reference library
* last by construction because it matches anything (core/plugin/loader.cpp). So dropping a
* kernel library into $RADIANCE_HOME/kernels is enough to be used, on any card, with no
* configuration -- and naming one ahead of another is what settles a tie between two that
* both serve an op. */
* An empty hierarchy is not "no order". The loader loads everything it finds and orders it,
* the reference library last by construction because it matches anything
* (core/plugin/loader.cpp). So dropping a kernel library into $RADIANCE_HOME/kernels is
* enough to be used, on any card, with no configuration. A list names the libraries to use:
* only those load, in its order, so naming one ahead of another settles a tie between two that
* both serve an op and leaving one out keeps it out. */
if (c->model.empty()) {
RAD_ERR("--model is required");
return RAD_E_INVAL;
@@ -799,4 +892,190 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_OK;
}
/* ------------------------------------------------------------------ the startup report's rows */
namespace {
std::string onoff(bool b) { return b ? "on" : "off"; }
std::string num(int64_t v) { return std::to_string(v); }
std::string or_none(const std::string& s, const char* none) { return s.empty() ? std::string(none) : s; }
std::string fnum(double v) {
char b[48];
snprintf(b, sizeof b, "%g", v);
return b;
}
template <class T>
std::string opt(const std::optional<T>& v, const char* unset) {
if (!v) return unset;
if constexpr (std::is_floating_point_v<T>) return fnum((double)*v);
else return std::to_string(*v);
}
std::string joined(const std::map<std::string, std::string>& m, const char* sep) {
std::string s;
for (const auto& [k, v] : m) s += (s.empty() ? "" : ",") + k + sep + v;
return s.empty() ? "none" : s;
}
using Show = std::string (*)(const Config&);
struct ShowRow { const char* flag; Show show; };
/* HOW EACH OPTION'S VALUE IS SHOWN, one entry an option of the table above, under the same
* spelling. config_rows walks the TABLE, so an option missing here still appears in the report --
* as "(not shown)" -- and diag_test fails naming it. A sentinel a field uses for "resolved at
* startup" (-1, 0, empty) is shown as what it means; the engine's decisions replace it with the
* value it resolved to. */
const ShowRow kShow[] = {
{ "--model", [](const Config& c) { return c.model; } },
{ "--download-dir", [](const Config& c) { return or_none(c.download_dir, "the XDG cache (~/.cache/radiance/hf)"); } },
{ "--radiance-home", [](const Config& c) { return c.radiance_home; } },
{ "--kernels", [](const Config& c) {
std::string s;
for (const std::string& k : c.kernel_hierarchy) s += (s.empty() ? "" : ",") + k;
return or_none(s, "every library found"); } },
{ "--tp", [](const Config& c) { return num(c.tp); } },
{ "--tp-wire", [](const Config& c) { return std::string(c.tp_wire_exact ? "exact" : "wht6"); } },
{ "--tp-wire-min-kb", [](const Config& c) { return num(c.tp_wire_min_kb); } },
{ "--p2p", [](const Config& c) {
return std::string(c.p2p == RAD_P2P_ON ? "on" : c.p2p == RAD_P2P_OFF ? "off" : "auto"); } },
{ "--max-num-batched-tokens", [](const Config& c) { return num(c.max_tok); } },
{ "--busy-prefill-chunk", [](const Config& c) {
return c.busy_prefill_chunk < 0 ? std::string("auto")
: c.busy_prefill_chunk == 0 ? std::string("off") : num(c.busy_prefill_chunk); } },
{ "--max-num-seqs", [](const Config& c) { return num(c.max_seqs); } },
{ "--max-model-len", [](const Config& c) {
return c.max_ctx ? num(c.max_ctx) : std::string("0 (the model's training context)"); } },
{ "--rope-scaling", [](const Config& c) { return or_none(c.rope_scaling, "the checkpoint's own"); } },
{ "--gpu-headroom-mib", [](const Config& c) { return num(c.gpu_headroom_mib); } },
{ "--kv-cache-dtype", [](const Config& c) { return c.kv_cache_dtype; } },
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } },
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
{ "--ngram-placement", [](const Config& c) { return std::string(table_placement_name(c.ngram_placement)); } },
{ "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } },
{ "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } },
{ "--prefix-cache-mib", [](const Config& c) {
return c.prefix_cache_mib ? num(c.prefix_cache_mib) : std::string("0 (off)"); } },
{ "--prefix-cache-ttl", [](const Config& c) {
return c.prefix_cache_ttl ? num(c.prefix_cache_ttl) + " s" : std::string("0 (never)"); } },
{ "--placement", [](const Config& c) { return c.placement; } },
{ "--deterministic", [](const Config& c) { return onoff(c.deterministic); } },
{ "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } },
{ "--checkpoint-slots", [](const Config& c) { return num(c.checkpoint_slots); } },
{ "--no-prefix-cache", [](const Config& c) {
return std::string(c.prefix_cache ? "not given: prefix caching on" : "prefix caching off"); } },
{ "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } },
{ "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } },
{ "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } },
{ "--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); } },
/* A SECRET IS NOT A VALUE. Whether one is set is what a reader of the log needs. */
{ "--api-key", [](const Config& c) { return std::string(c.api_key.empty() ? "not set" : "set"); } },
{ "--served-model-name", [](const Config& c) { return or_none(c.served_model_name, "the container's name"); } },
{ "--mm-max-patches", [](const Config& c) { return c.mm_max_patches < 0 ? std::string("auto") : num(c.mm_max_patches); } },
{ "--generation-config", [](const Config& c) { return or_none(c.generation_config, "none"); } },
{ "--override-chat-template", [](const Config& c) { return or_none(c.override_chat_template, "none (the container's)"); } },
{ "--temp", [](const Config& c) { return c.sample_temp < 0 ? std::string("unset") : fnum(c.sample_temp); } },
{ "--top-k", [](const Config& c) { return c.sample_top_k < 0 ? std::string("unset") : num(c.sample_top_k); } },
{ "--top-p", [](const Config& c) { return c.sample_top_p < 0 ? std::string("unset") : fnum(c.sample_top_p); } },
{ "--min-p", [](const Config& c) { return c.sample_min_p < 0 ? std::string("unset") : fnum(c.sample_min_p); } },
{ "--reasoning-effort", [](const Config& c) { return or_none(c.reasoning_effort, "the template's default"); } },
{ "--reasoning-effort-map", [](const Config& c) { return joined(c.reasoning_effort_map, "="); } },
{ "--thinking-token-budget", [](const Config& c) {
return c.thinking_token_budget < 0 ? std::string("none") : num(c.thinking_token_budget); } },
{ "--typical-p", [](const Config& c) { return opt(c.sample_typical_p, "the request default"); } },
{ "--presence-penalty", [](const Config& c) { return opt(c.sample_pres_penalty, "the request default"); } },
{ "--frequency-penalty", [](const Config& c) { return opt(c.sample_freq_penalty, "the request default"); } },
{ "--repetition-penalty", [](const Config& c) { return opt(c.sample_rep_penalty, "the request default"); } },
{ "--repeat-last-n", [](const Config& c) { return opt(c.sample_penalty_last_n, "the request default"); } },
{ "--dry-multiplier", [](const Config& c) { return opt(c.sample_dry_multiplier, "the request default"); } },
{ "--dry-base", [](const Config& c) { return opt(c.sample_dry_base, "the request default"); } },
{ "--dry-allowed-length", [](const Config& c) { return opt(c.sample_dry_allowed_length, "the request default"); } },
{ "--dry-penalty-last-n", [](const Config& c) { return opt(c.sample_dry_penalty_last_n, "the request default"); } },
{ "--dry-sequence-breakers", [](const Config& c) {
/* Replaced, not thrown on, like every dump in the report: the strings reach Config from
* outside the engine, and a serialiser that throws would end a startup that is otherwise
* sound over one line of its log. */
return c.sample_dry_seq_breakers
? nlohmann::json(*c.sample_dry_seq_breakers)
.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace)
: std::string("the request default"); } },
{ "--xtc-probability", [](const Config& c) { return opt(c.sample_xtc_probability, "the request default"); } },
{ "--xtc-threshold", [](const Config& c) { return opt(c.sample_xtc_threshold, "the request default"); } },
{ "--default-max-tokens", [](const Config& c) {
return c.default_max_tokens > 0 ? num(c.default_max_tokens)
: std::string("auto (what the context leaves after the prompt)"); } },
{ "--max-tokens-cap", [](const Config& c) { return c.max_tokens_cap > 0 ? num(c.max_tokens_cap) : std::string("none"); } },
{ "--max-n", [](const Config& c) {
return c.max_n > 0 ? num(c.max_n)
: std::string("auto (the larger of 8 and --max-num-seqs)"); } },
{ "--max-queued-requests", [](const Config& c) {
return c.max_queued_requests > 0 ? num(c.max_queued_requests)
: std::string("auto (8 x --max-num-seqs)"); } },
{ "--max-stop-strings", [](const Config& c) { return num(c.max_stop_strings); } },
{ "--max-stop-bytes", [](const Config& c) { return num(c.max_stop_bytes); } },
{ "--chat-template-kwargs", [](const Config& c) { return joined(c.chat_template_kwargs, "="); } },
{ "--reasoning-format", [](const Config& c) { return c.reasoning_format; } },
{ "--http-threads", [](const Config& c) {
return c.http_threads > 0 ? num(c.http_threads)
: std::string("auto (one a hardware thread, at least 4)"); } },
{ "--read-timeout", [](const Config& c) { return num(c.http_read_timeout_s) + " s"; } },
{ "--write-timeout", [](const Config& c) { return num(c.http_write_timeout_s) + " s"; } },
{ "--keep-alive-timeout", [](const Config& c) { return num(c.http_keep_alive_timeout_s) + " s"; } },
{ "--max-body-mib", [](const Config& c) { return num(c.http_max_body_mib); } },
{ "--retry-after", [](const Config& c) { return num(c.retry_after_s) + " s"; } },
{ "--no-cors", [](const Config& c) {
return std::string(c.cors ? "not given: CORS headers sent" : "no CORS headers"); } },
{ "--image-min-pixels", [](const Config& c) { return opt(c.image_min_pixels, "the container's"); } },
{ "--image-max-pixels", [](const Config& c) { return opt(c.image_max_pixels, "the container's"); } },
{ "--video-min-pixels", [](const Config& c) { return opt(c.video_min_pixels, "the container's"); } },
{ "--video-max-pixels", [](const Config& c) { return opt(c.video_max_pixels, "the container's"); } },
{ "--video-fps", [](const Config& c) { return opt(c.video_fps, "the container's"); } },
{ "--video-min-frames", [](const Config& c) { return opt(c.video_min_frames, "the container's"); } },
{ "--video-max-frames", [](const Config& c) { return opt(c.video_max_frames, "the container's"); } },
{ "--video-max-frame-tokens", [](const Config& c) { return opt(c.video_max_frame_tokens, "the container's"); } },
{ "--image-tokens", [](const Config& c) { return opt(c.image_tokens, "the container's"); } },
{ "--max-source-pixels", [](const Config& c) { return opt(c.max_source_pixels, "67108864"); } },
{ "--kld-record", [](const Config& c) { return or_none(c.kld_record, "none"); } },
{ "--kld-ref", [](const Config& c) { return or_none(c.kld_ref, "none"); } },
{ "--kld-corpus", [](const Config& c) { return or_none(c.kld_corpus, "none"); } },
{ "--kld-out", [](const Config& c) { return or_none(c.kld_out, "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); } },
{ "--debug-accept-reference-kernels", [](const Config& c) { return onoff(c.accept_reference_kernels); } },
{ "--profile-ops", [](const Config& c) { return onoff(c.profile_ops); } },
{ "--live", [](const Config& c) { return onoff(c.live_view); } },
{ "-v", [](const Config& c) { return onoff(c.given.count("-v") > 0); } },
{ "-vv", [](const Config& c) { return onoff(c.given.count("-vv") > 0); } },
};
} /* namespace */
namespace diag {
std::vector<ConfigRow> config_rows(const Config& c) {
std::vector<ConfigRow> out;
for (const Flag& f : g_flags) {
/* --help asks for this text and serves nothing; it is not a setting. */
if (!std::strcmp(f.name, "--help")) continue;
ConfigRow r;
r.flag = f.name;
r.value = "(not shown)";
for (const ShowRow& s : kShow)
if (!std::strcmp(s.flag, f.name)) { r.value = s.show(c); break; }
auto g = c.given.find(f.name);
r.source = g != c.given.end() ? g->second : "default";
out.push_back(std::move(r));
}
return out;
}
std::vector<std::string> config_option_names() {
std::vector<std::string> out;
for (const Flag& f : g_flags)
if (std::strcmp(f.name, "--help")) out.push_back(f.name);
return out;
}
} /* namespace diag */
} /* namespace rad */
+1040 -13
View File
File diff suppressed because it is too large. Load diff
+112
View File
@@ -58,6 +58,79 @@ struct RadCopyRange {
extern "C" int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, RadStream s);
/* ONE COPY OF A LIST: `bytes` from `src` to `dst`, both absolute addresses. */
struct RadCopySeg {
const void* src;
void* dst;
int64_t bytes;
};
/* MANY UNRELATED COPIES, IN LIST ORDER ON THE STREAM, on the card's DMA engine where the backend
* has one. The list is read at the call, so it need not outlive it; the bytes it names do, like
* any copy's. A backend without a DMA engine copies the segments one by one, in order. An empty
* list puts nothing on the stream, and readies what the backend's first list on that stream's card
* would otherwise set up, so a caller can take that cost at bring-up.
*
* It exists for bulk copies across the link while the card computes -- the prefill stager's,
* a layer's pooled experts a call. A copy as a kernel holds a compute unit's slot for as long as
* the link takes, and waits for one to free up at every launch: beside kernels that keep every unit
* busy, 1.3 MB copies from pinned host memory ran at 2.3 GB/s as kernels and at 28.7 GB/s -- the
* link -- on the DMA engine, which cost those kernels nothing (aql.cpp, "the DMA lane").
*
* RAD_COPY_YIELD makes the list give way to the card's collectives: it waits, between pieces of
* about a megabyte, while a stream of that card holds the link (rad_link_hold). */
#define RAD_COPY_YIELD 1u
extern "C" int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream s);
/* THE CARD'S LINK, HELD BY A STREAM FOR WHAT IT ISSUES BETWEEN TWO CALLS: `on` 1 at the point in
* `s` where traffic the step waits on starts to cross the card's link -- a collective -- and 0
* where it ends, or 2 where the work in between ended the hold itself (rad_link_gate). Lists issued
* RAD_COPY_YIELD for that card stop between pieces while it is held. The holds of one card
* alternate, on then off, in the order they are issued across all its streams: they never nest or
* overlap. And the holding stream must not wait, between the two
* calls, on anything behind a yielding list -- the list would wait for the hold to end, and the
* hold for the list. A backend without a DMA engine holds nothing.
*
* WHY: a card's inbound link carries a collective's peer bytes and the stager's copies alike, and
* the DMA engine takes its share at the link's full rate. A 4 MB all-reduce message that crosses in
* 165 us on its own took 301 us beside a layer's copies, and the step waits on every one; the
* copies have the rest of the layer to finish in. */
extern "C" int rad_link_hold(RadStream s, int on);
/* THE WORD THE HOLD IS KEPT IN, for a launch that ends its own: a 64-bit word in memory every
* engine and kernel of the card reaches, odd while the link is held. rad_link_hold(s, 2) after a
* launch that was handed this address records that the launch released the hold itself, by taking
* one off the word -- once, and only if it found it odd -- as soon as the bytes it waited for had
* landed. Null where the backend holds nothing. */
extern "C" void* rad_link_gate(RadStream s);
/* THE EXPERT PREFETCH'S DEVICE HALF (core/runtime/xprefetch.cpp). A backend that cannot make a
* dispatch complete a signal, or has no DMA engine to spare for it, leaves these out:
* rad_xp_supported is then 0 and the prefetch is off.
*
* A RIDE is a signal the next dispatch issued on a stream completes -- that dispatch keeps its
* ordering bit, so the signal stands for everything before it on the stream -- in place of a
* barrier packet of its own between two kernels. rad_ride_wait puts a barrier on another stream
* that waits for it and gives the signal back behind that barrier; a ride the DMA engine polls
* instead goes back with rad_ride_release once nothing can poll it: at once (`after` null) when the
* list that polled it has finished, else once `after` is `packets` dispatches further on, which is
* long after the ridden dispatch has completed it.
*
* rad_xp_list hands the card's prefetch DMA queue a list: wait for `mark` (a ride, or null), copy
* the `n` ranges, then write `done_val` to `done` (pinned host memory, or null). rad_xp_behind is how
* many lists the queue has been handed and not yet finished. The prefetch's ring is uncached device
* memory (rad_dev_alloc_uncached): the engine writes it and kernels read it, and no cache may hold
* what a slot held before. */
extern "C" int rad_xp_supported(int device);
extern "C" int rad_xp_stream_create(RadStream* out);
extern "C" int rad_ride(RadStream s, void** token);
extern "C" int rad_ride_wait(RadStream s, void* token);
extern "C" void rad_ride_release(void* token, RadStream after, int64_t packets);
extern "C" int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst,
const uint64_t* bytes, uint32_t* done, uint32_t done_val);
extern "C" int64_t rad_xp_behind(int device);
extern "C" void* rad_dev_alloc_uncached(int64_t bytes);
extern "C" void rad_dev_free_uncached(void* p);
namespace rad {
/* A recorded pass, owned by the backend that recorded it. See DeviceBackend::tape_begin. */
@@ -128,6 +201,9 @@ struct DeviceBackend {
int (*memset_async)(void* dst, int value, int64_t bytes, RadStream s);
int (*memcpy_ranges_async)(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, RadStream s);
int (*memcpy_list_async)(const RadCopySeg* segs, int n, unsigned flags, RadStream s);
int (*link_hold)(RadStream s, int on);
void* (*link_gate)(RadStream s);
/* ---- recorded passes. A backend with none leaves these null, and the run phase then issues
* every pass; see Ctx::run_step for what a tape is for and when one is kept.
@@ -228,6 +304,32 @@ struct DeviceBackend {
* the backend cannot say. Asked, not enabled: rad_dev_enable_peer is the call that maps the
* memory. Null on a backend whose devices share one address space, which answers 1. */
int (*peer_access)(int self, int peer);
/* ---- the card's PCI address, "0000:03:00.0", into `out`; RAD_E_UNSUPPORTED from a backend
* whose devices are not PCI devices. It is what joins the runtime's device index to the
* kernel's description of the same card -- its link, its power limits, its IOMMU group -- in
* the startup report (core/diag/diag.h). */
int (*pci_address)(int device, char* out, int cap);
/* ---- the device runtime's name and version, "HIP 7.2.25403", into `out`. Null on a backend
* with no runtime behind it. */
int (*runtime_version)(char* out, int cap);
/* ---- what carries the engine's copy lists for `device` (rad_memcpy_list_async), into `out`:
* the card's DMA engine on a queue of the process's own, or why not. Null on a backend that
* copies every list segment by segment. */
int (*dma_lane)(int device, char* out, int cap);
/* ---- the expert prefetch's device half: see rad_xp_supported. Last in the table, so a backend
* listing its entries in order leaves them null. */
int (*xp_supported)(int device);
int (*xp_stream_create)(RadStream* out);
int (*ride)(RadStream s, void** token);
int (*ride_wait)(RadStream s, void* token);
void (*ride_release)(void* token, RadStream after, int64_t packets);
int (*xp_list)(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst,
const uint64_t* bytes, uint32_t* done, uint32_t done_val);
int64_t (*xp_behind)(int device);
void* (*alloc_uncached)(int64_t bytes);
void (*free_uncached)(void* p);
};
@@ -260,6 +362,12 @@ int dev_code_runs(size_t from, size_t to, int device, std::string* why);
/* The current backend's DeviceBackend::integrated. */
bool dev_integrated(int device);
/* The current backend's DeviceBackend::pci_address and runtime_version, "" where it has none. */
std::string dev_pci_address(int device);
std::string dev_runtime_version();
/* The current backend's DeviceBackend::dma_lane, "" where it has none. */
std::string dev_dma_lane(int device);
/* THE 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 packet having been launched
* still proves that everything more than that many packets before it has completed -- which is
@@ -376,6 +484,10 @@ const DeviceBackend* hip_backend_if_present(void);
const DeviceBackend* aql_backend_if_present(void);
/* Bytes copied to or from pageable host memory so far: every such copy is a host wait. */
int64_t aql_pageable_bytes(void);
/* The fat binaries registered so far, counted whichever backend runs: the registration hooks are
* this build's own exported symbols and see every dlopen'ed kernel plugin's device code, card or
* no card. The host backend's code_mark in a HIP build. */
size_t aql_code_registered(void);
#endif
/* ------------------------------------------------------------------ the error slot */
+1 -3
View File
@@ -181,9 +181,7 @@ int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) {
/* ------------------------------------------------------------------ write */
/* The store is written to as well as read: the SSD prefix-cache tier (core/mem/sstier.cpp)
* publishes blocks, and the SSD weight tier is populated once at load. Both write whole aligned
* slots, so this has the same shape as read_at -- one fast path, and a read-modify-write for
/* The same shape as read_at -- one fast path for whole aligned blocks, and a read-modify-write for
* anything that does not cover a whole block. */
int DirectFile::write_at(const void* src, int64_t off, int64_t bytes) {
if (fd_ < 0) return RAD_E_STATE;
+5 -5
View File
@@ -30,11 +30,11 @@ enum {
/* Open buffered when the filesystem refuses O_DIRECT, instead of failing the open.
*
* Off by default, and that default is the point. The weight tier and the prefix cache are
* sized in gigabytes and read in megabyte runs; a silent buffered fallback turns both into a
* page-cache pump that is three times slower and looks like nothing at all in a profile. An
* operator who pointed --prefix-cache-dir at tmpfs wants to be told, not accommodated. The flag is
* for tests, which have to run on whatever /tmp happens to be. */
* Off by default, and that default is the point. The weight tier is sized in gigabytes and
* read in megabyte runs; a silent buffered fallback turns it into a page-cache pump that is
* three times slower and looks like nothing at all in a profile. An operator whose container
* sits on tmpfs wants to be told, not accommodated. The flag is for tests, which have to run
* on whatever /tmp happens to be. */
RAD_DIO_ALLOW_BUFFERED = 16,
};
+119 -1
View File
@@ -67,16 +67,52 @@ static std::string device_inventory(const DeviceBackend* b) {
return s;
}
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
/* COMPUTE WAVE SAVE/RESTORE OFF IS A GPU HANG WAITING FOR AN EVICTION. The driver evicts a
* process's queues whenever host memory the card maps is moved or reclaimed under memory pressure,
* and a serve with a host pool or a host KV tier maps gigabytes of it. With
* amdgpu.cwsr_enable=0 it cannot preempt a running queue and waits for it to drain, which a queue
* a serve keeps fed never does: the queue stops inside whatever kernel it was running, MES fails
* REMOVE_QUEUE, and the driver resets the card. Said at startup because nothing later can tell
* that hang from a kernel bug -- and said here, as the backend comes up, and not only in the
* startup report: a hang during the load ends the process before the report prints, and the
* tools that bring a backend up (rad-kbench, rad-tune) print no report at all. */
static void warn_cwsr_off() {
FILE* f = std::fopen("/sys/module/amdgpu/parameters/cwsr_enable", "r");
if (!f) return;
int v = -1;
const int got = std::fscanf(f, "%d", &v);
std::fclose(f);
if (got == 1 && v == 0)
RAD_WARN("device: amdgpu cwsr_enable is 0, so the driver cannot preempt a running queue: "
"any queue eviction (host memory the card maps, moved under memory pressure) waits "
"for a queue a serve never lets drain, and ends in a GPU hang and reset. Set "
"amdgpu.cwsr_enable=1 (module option, then rebuild the initramfs and reboot)");
}
/* THE HOST BACKEND IN A BUILD THAT HAS HIP STILL COUNTS THE GPU CODE PLUGINS BRING. The
* registration hooks are this build's own exported symbols and see every dlopen'ed kernel
* library's fat binaries, card or no card, so the plugin loader can bracket each dlopen and know
* which library brought device code. An engine serving here leaves that library's device rows out
* of selection (Registry::set_no_device_code); a tool that only selects keeps them. */
static DeviceBackend g_host_beside_hip;
#endif
static const DeviceBackend* select_backend() {
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
if (const DeviceBackend* b = aql_backend_if_present()) {
RAD_INFO("device: AQL backend, %d device(s) [%s]", b->count(),
device_inventory(b).c_str());
warn_cwsr_off();
return b;
}
RAD_INFO("device: built with HIP but no device is visible -- using the host backend");
#endif
g_host_beside_hip = *host_backend();
g_host_beside_hip.code_mark = aql_code_registered;
const DeviceBackend* b = &g_host_beside_hip;
#else
const DeviceBackend* b = host_backend();
#endif
RAD_INFO("device: host backend, %d device(s) [%s]", b->count(), device_inventory(b).c_str());
return b;
}
@@ -501,6 +537,39 @@ int tape_set_overlap(RadTape t, int i, bool on) {
return dev()->tape_set_overlap ? dev()->tape_set_overlap(t, i, on ? 1 : 0) : RAD_E_UNSUPPORTED;
}
bool dev_integrated(int device) { return dev()->integrated && dev()->integrated(device) > 0; }
/* A FAILURE ANSWERED HERE, as "", is not one for the next reader of rad_dev_last_error: that
* reader is reporting a failure of its own and would name this one instead. The slot is put back
* as the call found it. */
std::string dev_pci_address(int device) {
char buf[64] = { 0 };
if (!dev()->pci_address) return std::string();
const std::string before = t_last_error;
if (dev()->pci_address(device, buf, (int)sizeof buf) < 0) {
t_last_error = before;
return std::string();
}
return buf;
}
std::string dev_dma_lane(int device) {
char buf[256] = { 0 };
if (!dev()->dma_lane) return std::string();
const std::string before = t_last_error;
if (dev()->dma_lane(device, buf, (int)sizeof buf) < 0) {
t_last_error = before;
return std::string();
}
return buf;
}
std::string dev_runtime_version() {
char buf[128] = { 0 };
if (!dev()->runtime_version) return std::string();
const std::string before = t_last_error;
if (dev()->runtime_version(buf, (int)sizeof buf) < 0) {
t_last_error = before;
return std::string();
}
return buf;
}
int dev_peer_access(int self, int peer) {
if (self == peer) return 1;
return dev()->peer_access ? dev()->peer_access(self, peer) : 1;
@@ -555,6 +624,55 @@ int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, RadStream s) {
return dev()->memcpy_ranges_async(dst, src, prefix, ranges, n, s);
}
int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream s) {
if (const auto f = dev()->memcpy_list_async) return f(segs, n, flags, s);
for (int i = 0; i < n; ++i) RAD_TRY(dev()->memcpy_async(segs[i].dst, segs[i].src, segs[i].bytes, s));
return RAD_OK;
}
int rad_link_hold(RadStream s, int on) {
if (const auto f = dev()->link_hold) return f(s, on);
return RAD_OK;
}
void* rad_link_gate(RadStream s) {
if (const auto f = dev()->link_gate) return f(s);
return nullptr;
}
int rad_xp_supported(int device) {
const auto* d = dev();
return d->xp_supported && d->xp_stream_create && d->ride && d->ride_wait && d->ride_release && d->xp_list &&
d->xp_behind && d->alloc_uncached && d->free_uncached && d->xp_supported(device);
}
int rad_xp_stream_create(RadStream* out) {
if (const auto f = dev()->xp_stream_create) return f(out);
return RAD_E_UNSUPPORTED;
}
int rad_ride(RadStream s, void** token) {
if (const auto f = dev()->ride) return f(s, token);
return RAD_E_UNSUPPORTED;
}
int rad_ride_wait(RadStream s, void* token) {
if (const auto f = dev()->ride_wait) return f(s, token);
return RAD_E_UNSUPPORTED;
}
void rad_ride_release(void* token, RadStream after, int64_t packets) {
if (const auto f = dev()->ride_release) f(token, after, packets);
}
int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes,
uint32_t* done, uint32_t done_val) {
if (const auto f = dev()->xp_list) return f(device, mark, n, src, dst, bytes, done, done_val);
return RAD_E_UNSUPPORTED;
}
int64_t rad_xp_behind(int device) {
if (const auto f = dev()->xp_behind) return f(device);
return 0;
}
void* rad_dev_alloc_uncached(int64_t bytes) {
if (const auto f = dev()->alloc_uncached) return f(bytes);
return nullptr;
}
void rad_dev_free_uncached(void* p) {
if (const auto f = dev()->free_uncached) f(p);
}
/* Cleared by reading it, per the header. Never null: a caller printing "%s" on a path where
* nothing failed should get an empty line, not a segfault. */
+27 -1
View File
@@ -258,6 +258,30 @@ int d_peer_access(int self, int peer) {
return can ? 1 : 0;
}
/* The runtime's bus id, rewritten in the kernel's spelling (lower case, four-digit domain) so it
* names the same directory under /sys/bus/pci/devices. */
int d_pci_address(int device, char* out, int cap) {
if (!out || cap <= 0) return RAD_E_INVAL;
char bus[64] = { 0 };
HIP_TRY(hipDeviceGetPCIBusId(bus, (int)sizeof bus, device));
unsigned dom = 0, b = 0, d = 0, f = 0;
if (std::sscanf(bus, "%x:%x:%x.%x", &dom, &b, &d, &f) != 4) {
device_set_error("hipDeviceGetPCIBusId(%d): '%s' is not a PCI address", device, bus);
return RAD_E_IO;
}
std::snprintf(out, (size_t)cap, "%04x:%02x:%02x.%x", dom, b, d, f);
return RAD_OK;
}
/* HIP_VERSION's encoding: major * 10^7 + minor * 10^5 + patch. */
int d_runtime_version(char* out, int cap) {
if (!out || cap <= 0) return RAD_E_INVAL;
int v = 0;
HIP_TRY(hipRuntimeGetVersion(&v));
std::snprintf(out, (size_t)cap, "HIP %d.%d.%d", v / 10000000, (v / 100000) % 100, v % 100000);
return RAD_OK;
}
int d_enable_peer(int self, int peer) {
if (self == peer) return RAD_OK;
int can = 0;
@@ -360,7 +384,7 @@ const DeviceBackend g_hip = {
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr,
nullptr,
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
/* Recorded passes: likewise the AQL backend's. */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
@@ -373,6 +397,8 @@ const DeviceBackend g_hip = {
nullptr, nullptr,
d_integrated,
d_peer_access,
d_pci_address,
d_runtime_version,
};
} /* namespace */
+14
View File
@@ -663,6 +663,18 @@ int h_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadC
return stream_push((HostStream*)st, t);
}
/* A copy a segment, queued in list order: this stream has no dispatch to save, and a task holds
* no list, so the list is read here, at the call, as the device backend reads it. */
int h_memcpy_list_async(const RadCopySeg* segs, int n, unsigned, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_list_async"));
if (n < 0 || (n > 0 && !segs)) {
device_set_error("rad_memcpy_list_async: %d segments at %p", n, (const void*)segs);
return RAD_E_INVAL;
}
for (int i = 0; i < n; ++i) RAD_TRY(h_memcpy_async(segs[i].dst, segs[i].src, segs[i].bytes, st));
return RAD_OK;
}
int h_memset_async(void* dst, int value, int64_t bytes, RadStream st) {
RAD_TRY(check_stream(st, "rad_memset_async"));
if (bytes == 0) return RAD_OK;
@@ -775,6 +787,8 @@ const DeviceBackend g_host = {
h_event_query, h_event_sync, h_event_elapsed_ms,
h_host_wrote,
h_memcpy_async, h_memcpy_2d_async, h_memset_async, h_memcpy_ranges_async,
h_memcpy_list_async,
nullptr, nullptr, /* no DMA engine, so no link to hold */
/* No recorded passes: a host stream runs its work as it is issued, so there is no queue to
* write a recording into, and every pass is issued. */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
+446
View File
@@ -0,0 +1,446 @@
/* checks.cpp -- what in the configuration or on the machine costs speed or correctness, and what to
* do about it.
*
* EACH CHECK IS A FUNCTION OF THE FACTS AND NOTHING ELSE: no file is read here and no device is
* asked, so every one of them is tested by handing it a machine described in a struct. A check
* says what it saw with the numbers, why that matters, and the change that addresses it -- a
* warning without a fix is a worry handed to the reader.
*
* WARN is a cost or a risk the operator should act on; NOTE is a setting that is a trade-off or
* worth knowing when reading a benchmark. A finding that depends on load (a parked link) is only
* raised when the card was busy when the facts were read: at startup the cards are idle and a
* PCIe link at rest parks at its lowest speed, which is the power management doing its job.
*/
#include "diag/diag.h"
#include "rad_internal.h"
#include <algorithm>
#include <cstdlib>
#include <map>
#include <set>
namespace rad {
namespace diag {
namespace {
constexpr int64_t kGiB = (int64_t)1 << 30;
constexpr int64_t kMiB = (int64_t)1 << 20;
/* A card this busy when its link was read is under load, so a link below its maximum is not the
* idle parking every PCIe link does. */
constexpr int kBusyPercent = 30;
void add(std::vector<Finding>* out, Finding::Level lv, const char* id, std::string what,
std::string why, std::string fix) {
Finding f;
f.level = lv;
f.id = id;
f.what = std::move(what);
f.why = std::move(why);
f.fix = std::move(fix);
out->push_back(std::move(f));
}
std::vector<const CardFacts*> served(const Facts& f) {
std::vector<const CardFacts*> out;
for (const CardFacts& c : f.cards)
if (c.rank >= 0) out.push_back(&c);
std::sort(out.begin(), out.end(),
[](const CardFacts* a, const CardFacts* b) { return a->rank < b->rank; });
return out;
}
/* WHETHER THE SERVING CARDS' DMA IS TRANSLATED, from their own IOMMU groups where the kernel
* says, and from the machine's mode where it does not. */
bool translated(const Facts& f) {
bool any = false, dma = false;
for (const CardFacts* c : served(f)) {
if (c->iommu_type.empty()) continue;
any = true;
if (c->iommu_type != "identity") dma = true;
}
return any ? dma : f.host.iommu == "translated";
}
/* A GPU the engine could serve on: an amdgpu device with VRAM of its own worth the name. An
* integrated GPU's carve-out of a few hundred MiB is not one; an APU set up with tens of GiB is. */
bool servable_gpu(const CardFacts& c) {
return c.vendor == "0x1002" && c.driver == "amdgpu" && c.vram_total >= ((int64_t)4 << 30);
}
std::string card_name(const CardFacts& c) {
return c.rank >= 0 ? fmt("card %s (rank %d)", c.bdf.c_str(), c.rank) : "card " + c.bdf;
}
std::string hop_link(const PciHop& h, bool cur) {
const std::string& s = cur ? h.cur_speed : h.max_speed;
const int w = cur ? h.cur_width : h.max_width;
std::string sp = s;
const size_t p = sp.find(" PCIe");
if (p != std::string::npos) sp.erase(p);
return w > 0 ? fmt("%s x%d", sp.c_str(), w) : sp;
}
/* ---- the link ------------------------------------------------------------------------------ */
/* A HOP BELOW ITS OWN MAXIMUM WHILE THE CARD IS BUSY: the SMU's link power management stuck a
* level down, or a link that retrained narrower. The card's own endpoint can read full speed
* while the root port above it runs at half (a card with a switch on it), so every hop is read. */
void check_link_under_load(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->busy_percent < kBusyPercent) continue;
for (const PciHop& h : c->chain) {
const double cur = link_gts(h.cur_speed), mx = link_gts(h.max_speed);
const bool slow = cur > 0 && mx > 0 && cur < mx;
const bool narrow = h.cur_width > 0 && h.max_width > 0 && h.cur_width < h.max_width;
if (!slow && !narrow) continue;
add(out, Finding::Warn, "link-below-max",
fmt("%s: the PCIe link at %s runs %s of its %s while the card is %d%% busy",
card_name(*c).c_str(), h.bdf.c_str(), hop_link(h, true).c_str(),
hop_link(h, false).c_str(), c->busy_percent),
"every copy between host memory and the card -- experts streamed from the host "
"pool, the all-reduce through host memory, the embedding read in place -- and "
"every kernel launch's packet fetch cross this link, so the card serves at the "
"slower link's rate and a tensor-parallel step waits for it",
"a link stuck one level down after long uptime has been cleared by a reboot; "
"check that it recovers under load (GET /diagnostics during a long prefill), and "
"reseat or move the card if it trains narrow");
break;
}
if (c->dpm_pcie_cur >= 0 && c->dpm_pcie_cur + 1 < (int)c->dpm_pcie.size())
add(out, Finding::Warn, "link-dpm-below-top",
fmt("%s: the card's PCIe power level is %s, not its top level %s, while it is "
"%d%% busy", card_name(*c).c_str(), c->dpm_pcie[(size_t)c->dpm_pcie_cur].c_str(),
c->dpm_pcie.back().c_str(), c->busy_percent),
"the SMU picks the link's speed from this table; a level below the top under load "
"is half the host bandwidth or less",
"a reboot has cleared a level stuck after long uptime; pp_dpm_pcie can pin a level "
"(echo 2 | sudo tee /sys/class/drm/CARD/device/pp_dpm_pcie with "
"power_dpm_force_performance_level manual), with the server stopped");
}
}
/* A LINK THAT CANNOT REACH THE CARD'S SPEED, whatever the load: a hop whose own maximum is below
* the card's -- a slot one generation older, a riser, a lane split. Not a fault, and often the
* board's design; worth knowing when two machines measure differently. */
void check_link_capped(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->chain.size() < 2) continue;
const PciHop& ep = c->chain.back();
const double card = link_gts(ep.max_speed);
for (size_t i = 0; i + 1 < c->chain.size(); ++i) {
const PciHop& h = c->chain[i];
const double mx = link_gts(h.max_speed);
const bool slower = mx > 0 && card > 0 && mx < card;
const bool narrower = h.max_width > 0 && ep.max_width > 0 && h.max_width < ep.max_width;
if (!slower && !narrower) continue;
add(out, Finding::Note, "link-capped",
fmt("%s: the card's link is %s at most, and %s above it is %s at most",
card_name(*c).c_str(), hop_link(ep, false).c_str(), h.bdf.c_str(),
hop_link(h, false).c_str()),
"the host side of the link bounds what the card can move to and from host memory: "
"streamed experts, the host pool and the all-reduce when it goes through host memory",
"a slot with the card's full width and speed (the board manual says which slots "
"share lanes), or no riser; nothing to do if the board has no faster slot");
break;
}
}
}
/* ---- the cards against each other ----------------------------------------------------------- */
/* A TENSOR-PARALLEL STEP ENDS WHEN ITS SLOWEST RANK DOES, so cards set up differently serve at
* the slower one's pace, and a difference in a setting nobody remembers making is the usual
* reason one card is the slow one. */
void check_cards_differ(const Facts& f, std::vector<Finding>* out) {
const auto cs = served(f);
if (cs.size() < 2) return;
std::vector<std::string> diffs;
auto field = [&](const char* what, auto get, auto show) {
std::map<std::string, std::vector<std::string>> by;
for (const CardFacts* c : cs) by[show(get(*c))].push_back(c->bdf);
if (by.size() < 2) return;
std::string d = std::string(what) + ":";
for (const auto& [v, bdfs] : by) {
d += " " + v + " on";
for (const std::string& b : bdfs) d += " " + b;
d += ";";
}
d.pop_back();
diffs.push_back(d);
};
auto str = [](const std::string& s) { return s.empty() ? std::string("unknown") : s; };
field("root port link", [](const CardFacts& c) {
return c.chain.empty() ? std::string() : hop_link(c.chain.front(), false); }, str);
field("power cap", [](const CardFacts& c) { return c.power_cap_uw; },
[](int64_t uw) { return uw < 0 ? std::string("unknown") : fmt("%lld W", (long long)(uw / 1000000)); });
field("voltage offset", [](const CardFacts& c) { return c.vddgfx_offset; }, str);
field("top PCIe power level", [](const CardFacts& c) {
return c.dpm_pcie.empty() ? std::string() : c.dpm_pcie.back(); }, str);
field("runtime power management", [](const CardFacts& c) { return c.runtime_control; }, str);
field("target", [](const CardFacts& c) { return c.gfx; }, str);
if (diffs.empty()) return;
std::string what = "the cards serving this model are not set up alike -- ";
for (size_t i = 0; i < diffs.size(); ++i) what += (i ? "; " : "") + diffs[i];
add(out, Finding::Warn, "cards-differ", what,
"a tensor-parallel step waits for its slowest rank in every all-reduce, so the whole "
"server runs at the pace of the card with the lower limit or the slower link",
"make the settings match (the power cap and voltage offset are per card under "
"/sys/class/drm/cardN/device; set them with the server stopped)");
}
/* A CAP LOWERED BELOW THE CARD'S OWN DEFAULT. The default, not the maximum, is the yardstick: a
* stock card ships below the most its board allows (300 W of 330 W on an R9700), and a finding on
* every stock card is one nobody reads. A cap someone lowered -- or one a reset left at a value a
* tool set before it -- is the one that changes what the card does under load. */
void check_power_cap(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->power_cap_uw <= 0 || c->power_cap_default_uw <= 0) continue;
if (c->power_cap_uw >= c->power_cap_default_uw) continue;
add(out, Finding::Note, "power-cap-below-default",
fmt("%s: the power cap is %lld W, below the card's default of %lld W",
card_name(*c).c_str(), (long long)(c->power_cap_uw / 1000000),
(long long)(c->power_cap_default_uw / 1000000)),
"under a sustained load the power cap is what sets the clock on these cards "
"(scripts/cardclock.py shows which limit binds)",
fmt("echo %lld | sudo tee /sys/class/drm/%s/device/hwmon/hwmon*/power1_cap restores "
"the default, with the server stopped; nothing to do if the cap was lowered on "
"purpose", (long long)c->power_cap_default_uw,
c->drm.empty() ? "cardN" : c->drm.c_str()));
}
}
void check_small_bar(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->vram_visible <= 0 || c->vram_total <= 0) continue;
if (c->vram_visible * 10 >= c->vram_total * 9) continue;
add(out, Finding::Warn, "small-bar",
fmt("%s: the host and the other cards see %s of its %s of VRAM", card_name(*c).c_str(),
humanb(c->vram_visible).c_str(), humanb(c->vram_total).c_str()),
"without Resizable BAR a peer can address only a window of the card's memory, which "
"limits peer-to-peer collectives and copies into VRAM from the host",
"enable Resizable BAR (\"Re-Size BAR Support\" and \"Above 4G Decoding\") in the "
"firmware setup");
}
}
/* AN OVERDRIVE SETTING AND RUNTIME SUSPEND. The driver holds the offset and uploads it again
* whenever the card resumes from runtime suspend; on RDNA4 that upload has been seen to fail in
* the kernel log ("Failed to upload customized OD settings") at every resume. Whether the
* firmware still holds the offset afterwards is not readable here, and a card that lost it runs a
* lower clock at the same power cap. Keeping the card out of runtime suspend keeps the question
* from arising. */
void check_od_runtime_pm(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->vddgfx_offset.empty() || c->vddgfx_offset == "0 mV") continue;
if (c->runtime_control != "auto") continue;
add(out, Finding::Note, "od-runtime-suspend",
fmt("%s: a voltage offset of %s is set and the card runtime-suspends when idle "
"(power/control auto)", card_name(*c).c_str(), c->vddgfx_offset.c_str()),
"the driver re-uploads overdrive settings on every resume and can fail to (\"Failed "
"to upload customized OD settings\" in the kernel log); a card that resumed without "
"its offset clocks lower at the same power cap, and in a tensor-parallel world sets "
"the pace for every card",
fmt("echo on | sudo tee /sys/bus/pci/devices/%s/power/control keeps it resumed; check "
"`journalctl -k | grep -i overdrive` for failed uploads", c->bdf.c_str()));
}
}
/* ---- the host ------------------------------------------------------------------------------- */
void check_cwsr(const Facts& f, std::vector<Finding>* out) {
if (f.host.cwsr_enable != 0) return;
add(out, Finding::Warn, "cwsr-off", "amdgpu cwsr_enable is 0",
"the driver cannot preempt a running queue: any queue eviction (host memory the card maps, "
"moved under memory pressure) waits for a queue a serve never lets drain, and ends in a "
"GPU hang and reset",
"amdgpu.cwsr_enable=1 as a module option, then rebuild the initramfs and reboot");
}
void check_huge_pages(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
if (f.host.thp_enabled != "never") return;
if (r.host_pool_mib <= 0 && r.pinned_bytes < kGiB) return;
const bool tr = translated(f);
add(out, tr ? Finding::Warn : Finding::Note, "thp-never",
"transparent huge pages are off (/sys/kernel/mm/transparent_hugepage/enabled is never), so "
"every pinned range is 4 KiB pages",
tr ? "with an IOMMU translating the cards' reads each page is a translation of its "
"own; a host pool streamed at 4 KiB pages measured 10-21% slower prefill"
: "with the IOMMU in passthrough the page size has not measured slower; it "
"matters as soon as the IOMMU translates",
"echo madvise | sudo tee /sys/kernel/mm/transparent_hugepage/enabled (or "
"transparent_hugepage=madvise on the kernel command line)");
}
void check_iommu(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
if (!translated(f)) return;
if (r.host_weight_bytes <= 0 && r.host_pool_mib <= 0 && r.tp < 2) return;
std::string groups;
for (const CardFacts* c : served(f))
if (!c->iommu_type.empty()) groups += (groups.empty() ? "" : ", ") + c->bdf + " " + c->iommu_type;
add(out, Finding::Note, "iommu-translated",
"the IOMMU translates the cards' DMA (" + (groups.empty() ? f.host.iommu_why : groups) + ")",
"every read a card makes of host memory -- the host pool, the embedding in RAM, the "
"all-reduce through host memory -- goes through an IOMMU translation; with huge pages that "
"is cheap, at 4 KiB pages it measured 10-21% prefill",
std::string("iommu=pt on the kernel command line (amd_iommu=pt / intel_iommu=pt), if "
"nothing on the machine needs DMA isolation; otherwise keep transparent huge "
"pages at madvise or always") +
(r.tp > 1 ? "; with more than one card, check that peer access survives the change "
"(--p2p on refuses to start without it): iommu=pt removed it on an Intel "
"VT-d host (GUIDE §7.2)"
: ""));
}
void check_memory(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
const HostFacts& h = f.host;
if (h.mem_available >= 0 && h.mem_total > 0 &&
(h.mem_available < 2 * kGiB || h.mem_available * 20 < h.mem_total))
add(out, Finding::Warn, "memory-low",
fmt("%s of %s of RAM is available after startup", humanb(h.mem_available).c_str(),
humanb(h.mem_total).c_str()),
"the page cache is what a container read in place and the n-gram rows read from disk "
"come through; with it starved every step waits on the drive, and the kernel starts "
"reclaiming and swapping",
"lower --host-pool-mib or --prefix-cache-mib, or stop what else holds memory");
if (h.swap_total > 0 && h.swap_free >= 0 && h.swap_total - h.swap_free > 256 * kMiB)
add(out, Finding::Note, "swap-in-use",
fmt("%s of swap is in use", humanb(h.swap_total - h.swap_free).c_str()),
"a host thread that faults on a swapped page stalls the step it is part of",
"free memory, or turn swap off on a machine that only serves");
if (h.cgroup_mem_limit > 0 && h.mem_total > 0 && h.cgroup_mem_limit < h.mem_total &&
r.pinned_bytes > 0 && r.pinned_bytes * 10 > h.cgroup_mem_limit * 8)
add(out, Finding::Warn, "cgroup-limit",
fmt("the container's memory limit is %s and the process pins %s",
humanb(h.cgroup_mem_limit).c_str(), humanb(r.pinned_bytes).c_str()),
"pinned memory counts against the limit and cannot be reclaimed; what is left is all "
"the page cache and the process's own allocations get before the OOM killer",
"raise the container's memory limit or lower the pools");
}
void check_memlock(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
if (f.host.memlock_soft == -2 || f.host.memlock_soft < 0) return;
if (r.locked_bytes > 0 || r.ngram_placement != "disk") return;
add(out, Finding::Note, "memlock-limited",
fmt("RLIMIT_MEMLOCK is %s and the n-gram table is read from the container on disk",
humanb(f.host.memlock_soft).c_str()),
"a locked copy of the table in RAM is one of the faster tiers, and the memlock limit is "
"one of the things that keeps --ngram-placement auto off it",
"Docker: ulimits memlock -1 (--ulimit memlock=-1); systemd: LimitMEMLOCK=infinity");
}
void check_cpu(const Facts& f, std::vector<Finding>* out) {
const HostFacts& h = f.host;
if (h.cpu_governor.empty() || h.cpu_governor == "performance") return;
if (h.cpu_governor == "powersave" && h.cpu_epp == "performance") return;
if (h.cpu_governor == "schedutil") return;
add(out, Finding::Note, "cpu-governor",
fmt("the CPU governor is %s%s", h.cpu_governor.c_str(),
h.cpu_epp.empty() ? "" : (" with energy preference " + h.cpu_epp).c_str()),
"the host side of a step -- scheduling, sampling, the n-gram gather, launch bookkeeping -- "
"is single-threaded per rank, and a core that ramps slowly shows as host gap between steps",
"cpupower frequency-set -g performance, or echo performance | sudo tee "
"/sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference");
}
/* ---- the engine ----------------------------------------------------------------------------- */
void check_engine(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
std::string gpus;
for (const CardFacts& c : f.cards)
if (servable_gpu(c))
gpus += (gpus.empty() ? "" : ", ") + c.bdf + (c.gfx.empty() ? "" : " " + c.gfx);
if (r.host_backend && !gpus.empty())
add(out, Finding::Warn, "host-backend",
"the engine serves on the CPU although this machine has an AMD GPU (" + gpus + ")",
r.device_build ? "the device runtime found no card it could use, so every op runs on the host"
: "this build has no device runtime (built without HIP), so every op runs "
"on the host",
r.device_build
? "the device lines at the top of the log say why: /dev/kfd and /dev/dri must be "
"passed to a container with the render and video groups, ROCm must support the "
"card, and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES must not hide it"
: "build with ROCm (RAD_WITH_HIP=ON, hipcc on the PATH), or run the image");
for (const std::string& why : r.ignored)
add(out, Finding::Note, "device-ignored", "a device was left out: " + why,
"a rank placed on a slower or different card would set the pace of every step",
"ROCR_VISIBLE_DEVICES names the cards to use explicitly");
if (r.tp > 1 && r.p2p == 0 && !r.p2p_forced_off)
add(out, Finding::Note, "p2p-off",
"the cards cannot reach each other's memory directly" +
(r.p2p_blocked.empty() ? std::string() : " (" + r.p2p_blocked + ")"),
"the collectives exchange through pinned host memory, which crosses each card's link "
"twice",
"peer access needs Resizable BAR and the cards under one root complex; whether the "
"IOMMU's mode allows it depends on the platform -- iommu=pt removed it on an Intel "
"VT-d host (GUIDE §7.2) -- so check `--p2p on`, which refuses to start without it, "
"before and after changing the mode");
if (r.tp > 1 && r.tp_wire_lossy)
add(out, Finding::Note, "tp-wire-lossy",
fmt("--tp-wire wht6: all-reduce messages from %lld KiB up carry a quantised payload",
(long long)r.tp_wire_min_kb),
"faster prefill, but the model does not compute the exact function; two runs on "
"different world sizes are not comparable token for token",
"--tp-wire exact when exactness matters more than prefill speed");
/* Only when the operator turned it off: where the engine did (the KL mode, an embedding
* model) there is no cache to have, and the configuration line says why. */
if (!r.prefix_cache && r.prefix_cache_off_why.empty())
add(out, Finding::Note, "prefix-cache-off", "prefix caching is off (--no-prefix-cache)",
"every request prefills its whole prompt, including the conversation it shares with "
"the turn before",
"drop --no-prefix-cache");
if (r.host_weight_bytes > 0)
add(out, Finding::Note, "experts-from-host",
fmt("%s of weights a rank live in the pinned host pool and cross PCIe when they are "
"used", humanb(r.host_weight_bytes).c_str()),
"a prefill step streams every routed layer's pooled experts onto the card, so its speed "
"is bounded by the link; decode reads the ones it routes to",
"more VRAM for the experts: a shorter --max-model-len or fewer --max-num-seqs, "
"--embedding-placement ram, --kv-cache-dtype fp8, or more cards (--tp)");
if (r.file_weight_bytes > 0)
add(out, Finding::Warn, "weights-from-disk",
fmt("%s of weights a rank are read from the container on disk as they are needed",
humanb(r.file_weight_bytes).c_str()),
"a step that needs them is paced by the drive",
"a larger --host-pool-mib (if RAM allows) or more VRAM for the weights");
if (r.reference_kernels)
add(out, Finding::Warn, "reference-kernels",
"--debug-accept-reference-kernels: ops may run on the reference implementation",
"the reference library is an oracle, orders of magnitude slower than a device kernel",
"install a kernel library for this card and drop the flag");
if (r.profile_ops)
add(out, Finding::Warn, "profile-ops",
"--profile-ops times every op, which restores synchronisations",
"the run is slower and its numbers are not comparable against an unprofiled one",
"drop --profile-ops for anything measured");
}
} /* namespace */
std::vector<Finding> check(const Facts& f, const RunFacts& r) {
std::vector<Finding> out;
check_engine(f, r, &out);
check_link_under_load(f, &out);
check_cards_differ(f, &out);
check_link_capped(f, &out);
check_small_bar(f, &out);
check_power_cap(f, &out);
check_od_runtime_pm(f, &out);
check_cwsr(f, &out);
check_memory(f, r, &out);
check_huge_pages(f, r, &out);
check_iommu(f, r, &out);
check_memlock(f, r, &out);
check_cpu(f, &out);
/* Warnings first, each group in the order above: what to act on before what to know. */
std::stable_sort(out.begin(), out.end(),
[](const Finding& a, const Finding& b) { return a.level > b.level; });
return out;
}
double link_gts(const std::string& speed) {
return speed.empty() ? 0.0 : std::strtod(speed.c_str(), nullptr);
}
} /* namespace diag */
} /* namespace rad */
+215
View File
@@ -0,0 +1,215 @@
/* diag.h -- the startup report: what was configured, what it runs on, and what looks wrong.
*
* WHY ONE REPORT AND NOT THE LINES ALREADY IN THE LOG. Every decision startup makes is said
* somewhere on the way up, in the order it was made, between a hundred other lines. A log a user
* pastes into an issue is read by someone who has to find the line about the embedding, the one
* about the VRAM split and the one about the card's link, and cannot find the line that was never
* printed because the value was a default. The report puts all of it in one block at the end of
* startup: every option the command line takes with the value in force and where it came from,
* the machine as the kernel describes it, and a list of the things on it that cost speed or
* correctness with what to do about each.
*
* THREE PARTS, each built from data rather than from a list kept beside the code:
*
* CONFIGURATION every row of the option table (core/config.cpp), so an option added there
* appears here without anyone remembering to; a value startup resolved carries
* the reason it was resolved that way (Decision).
* HARDWARE read from /proc and /sys under a ROOT, so a test can hand the collector a
* directory tree of its own and a container built FROM scratch -- no shell, no
* lspci, no rocm-smi -- reads the same files the host does.
* FINDINGS each a small function over the two above (checks.cpp), unit-testable without
* a card.
*
* Unknown is a value. A field that could not be read is reported as unknown rather than left out:
* a report that silently drops a line reads as a machine that does not have the thing.
*/
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
struct Config;
namespace diag {
/* ------------------------------------------------------------------ decisions */
/* ONE VALUE STARTUP RESOLVED, and why. `key` is the option it resolves (`--placement`) when there
* is one, so the configuration table can show it on that option's row, or a topic of its own
* (`vram split`) for what no single option states. Recording the same key again replaces the
* earlier answer: a later stage that revises a choice (the n-gram copy that could not be made)
* is the answer in force. */
struct Decision {
std::string key;
std::string value;
std::string why;
};
void decide(std::vector<Decision>* list, const std::string& key, const std::string& value,
const std::string& why);
/* ------------------------------------------------------------------ the configuration table */
/* One option as the report shows it: the value in force, where it came from (`default`, `command
* line`, an environment variable, or `auto` for a value startup derived), and the reason when
* startup derived it. */
struct ConfigRow {
std::string flag;
std::string value;
std::string source;
std::string why;
};
/* Every option in the command line's table (core/config.cpp), in its order, with the value `c`
* holds and its source from Config::given. Secrets are not values: --api-key is "set" or "not
* set". */
std::vector<ConfigRow> config_rows(const Config& c);
/* The options the table holds, for a test that every one reaches the report. */
std::vector<std::string> config_option_names();
/* ------------------------------------------------------------------ hardware */
/* One PCIe link on the way from the root port to a card. Speeds are the kernel's strings
* ("32.0 GT/s PCIe"), widths lanes; -1 / "" where the file is absent, as it is on a bridge
* internal to a card's own switch on some boards. */
struct PciHop {
std::string bdf;
std::string cur_speed, max_speed;
int cur_width = -1, max_width = -1;
};
struct CardFacts {
std::string bdf; /* 0000:03:00.0 */
std::string vendor, pci_device; /* 0x1002, 0x7551 */
std::string driver; /* the bound kernel driver, "" for none */
std::string drm; /* card1, "" when the driver made no DRM node */
std::string gfx; /* gfx1201, from the KFD topology; "" when unknown */
int simd = -1; /* SIMDs the KFD topology reports */
int numa_node = -1;
int64_t vram_total = -1, vram_visible = -1; /* the BAR the host and the peers see */
int busy_percent = -1;
std::string runtime_status; /* active | suspended, "" when unknown */
std::string runtime_control; /* auto | on */
std::string iommu_type; /* the card's IOMMU group: identity, DMA, DMA-FQ */
std::vector<PciHop> chain; /* root port first, the card's own link last */
std::vector<std::string> dpm_pcie; /* the SMU's link levels, as listed */
int dpm_pcie_cur = -1; /* the level marked current, -1 unknown */
std::string sclk, mclk; /* "500-2350 MHz", the lowest and highest DPM level */
int64_t power_cap_uw = -1, power_cap_default_uw = -1, power_cap_max_uw = -1;
std::string vddgfx_offset; /* "-75 mV" from pp_od_clk_voltage, "" when unknown */
bool integrated = false; /* the KFD topology's node has no local memory of its own */
/* What the engine knows and the kernel does not: filled by the engine for its own cards. */
std::string name; /* the runtime's product name */
int rank = -1; /* the tensor-parallel rank it serves, -1 none */
int device = -1; /* the backend's device index, -1 none */
std::string dma; /* what carries its copy lists (dev_dma_lane), "" unknown */
};
struct HostFacts {
std::string cpu_model;
int cores = -1, threads = -1;
int64_t mem_total = -1, mem_available = -1, swap_total = -1, swap_free = -1;
std::string kernel, distro;
std::string container; /* "docker", "podman", "" for none seen */
int64_t cgroup_mem_limit = -1; /* bytes; -2 is "max", -1 unknown */
int64_t memlock_soft = -1; /* bytes; -2 is unlimited, -1 unknown */
std::string thp_enabled, thp_defrag, thp_shmem; /* the selected word of each */
std::string iommu; /* passthrough | translated | off | unknown */
std::string iommu_why; /* what that was read from */
std::string cmdline; /* the boot parameters that bear on a card, space separated */
int64_t ttm_pages_limit = -1; /* pages; TTM's limit on the system memory it allocates */
int64_t page_size = 4096;
int cwsr_enable = -1;
std::string io_uring; /* available | refused (why) | unknown */
std::string cpu_governor, cpu_epp, cpu_driver;
std::string runtime; /* the device runtime's version, "" for none */
};
struct Facts {
HostFacts host;
std::vector<CardFacts> cards; /* every display-class PCI device, in address order */
};
/* Reads /proc and /sys under `root` ("" is the live system). Never fails: what cannot be read is
* left unknown.
*
* `managed`, when given, names the cards (by PCI address) whose power-management files are read
* -- the DPM tables, the overdrive block, the busy percentage and the hwmon power limits; every
* other card is described from its PCI and memory files alone. The driver answers those files
* from the card's SMU under its power-management lock, and wakes a card that was runtime-
* suspended to do it, so a server reading the machine again while it serves reads them for the
* cards it serves on and no others. Null reads them for every card. */
Facts collect(const std::string& root, const std::vector<std::string>* managed = nullptr);
/* What only a system call answers, filled for the live process: the memlock limit and whether
* io_uring is allowed here (a container's seccomp profile refuses it). */
void probe_process(HostFacts* h);
/* The names of the variables in `env` (an environ-shaped, null-terminated array) that start with
* `prefix`, sorted. Names only: a value can be a path, a host name or a token, and the report is
* written to be pasted into an issue. */
std::vector<std::string> env_names(char* const* env, const char* prefix);
/* ------------------------------------------------------------------ what the engine did */
struct RunFacts {
std::string version; /* the engine's, for the report's first line */
bool device_build = true; /* built with a device runtime (HIP) */
int tp = 1;
bool host_backend = false;
bool failed = false; /* startup stopped; the report is what it got to */
int p2p = -1; /* 1 peer to peer, 0 through host memory, -1 n/a */
bool p2p_forced_off = false; /* --p2p off */
std::string p2p_blocked; /* the pairs the driver refused */
std::vector<std::string> ignored; /* devices left out, each with the reason */
bool tp_wire_lossy = false;
int64_t tp_wire_min_kb = 0;
bool prefix_cache = true;
/* Why the engine turned prefix caching off itself (the KL mode, an embedding model); "" when
* it is on or the operator turned it off. */
std::string prefix_cache_off_why;
int64_t host_pool_mib = 0; /* a rank, as configured */
int64_t pinned_bytes = -1; /* every pinned host allocation the process made */
int64_t host_weight_bytes = 0; /* weights a rank reads from the pinned host pool */
int64_t file_weight_bytes = 0; /* and from the container on disk */
int64_t locked_bytes = 0; /* memory locked for a host gather (an n-gram copy) */
std::string ngram_placement; /* where an n-gram table went, "" for a model without one */
bool reference_kernels = false;
bool profile_ops = false;
bool deterministic = false;
/* The RADIANCE_* variables set in the environment, by name (env_names). The option table
* covers what the command line takes; these change behaviour beside it -- the log level, a
* pinned tuning, an instrument left on -- and a report of every setting in force names them. */
std::vector<std::string> environment;
};
/* ------------------------------------------------------------------ findings */
struct Finding {
enum Level { Note = 0, Warn = 1 };
Level level = Note;
std::string id; /* stable, for a test or a grep: "link-below-max" */
std::string what; /* what was seen, with the numbers */
std::string why; /* what it costs */
std::string fix; /* what to do: a flag, a setting, a command */
};
std::vector<Finding> check(const Facts& f, const RunFacts& r);
/* ------------------------------------------------------------------ the report */
std::string render(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
/* The same, as a JSON object in text: {"configuration", "derived", "hardware", "findings"}. */
std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
/* Merges the decisions into the option rows: a decision whose key is an option's flag supplies
* that row's value and reason (and `auto` as its source when the option was not given). The
* decisions no row took are returned in `derived`, in the order they were made. */
void merge(std::vector<ConfigRow>* rows, const std::vector<Decision>& decisions,
std::vector<Decision>* derived);
/* "32.0 GT/s PCIe" -> 32.0; 0 when it does not parse. */
double link_gts(const std::string& speed);
} /* namespace diag */
} /* namespace rad */
+296
View File
@@ -0,0 +1,296 @@
/* report.cpp -- the startup report, as text for the log and as JSON for /diagnostics.
*
* ONE LAYOUT FOR A READER WHO DID NOT RUN THE SERVER: every option on its own line with the value
* in force and where it came from, the reason under any value startup derived, the machine in a
* few dense lines and a block a card, and the findings last with what to do about each. The text
* and the JSON are rendered from the same structs, so neither can say something the other does
* not.
*/
#include "diag/diag.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
namespace rad {
namespace diag {
void decide(std::vector<Decision>* list, const std::string& key, const std::string& value,
const std::string& why) {
for (Decision& d : *list)
if (d.key == key) { d.value = value; d.why = why; return; }
list->push_back({ key, value, why });
}
void merge(std::vector<ConfigRow>* rows, const std::vector<Decision>& decisions,
std::vector<Decision>* derived) {
derived->clear();
for (const Decision& d : decisions) {
auto it = std::find_if(rows->begin(), rows->end(),
[&](const ConfigRow& r) { return r.flag == d.key; });
if (it == rows->end()) { derived->push_back(d); continue; }
it->value = d.value;
it->why = d.why;
if (it->source == "default") it->source = "auto";
}
}
namespace {
std::string or_unknown(const std::string& s) { return s.empty() ? "unknown" : s; }
std::string bytes_or_unknown(int64_t b) { return b < 0 ? "unknown" : humanb(b); }
/* Continuation lines of a multi-line value, indented under the column they belong to. */
void indented(std::string* out, const std::string& text, int indent) {
size_t at = 0;
while (at <= text.size()) {
size_t nl = text.find('\n', at);
if (nl == std::string::npos) nl = text.size();
const std::string l = text.substr(at, nl - at);
if (!l.empty()) *out += std::string((size_t)indent, ' ') + l + "\n";
at = nl + 1;
}
}
std::string short_bdf(const std::string& b) {
return b.rfind("0000:", 0) == 0 ? b.substr(5) : b;
}
std::string link(const std::string& speed, int width) {
std::string s = speed;
const size_t p = s.find(" PCIe");
if (p != std::string::npos) s.erase(p);
if (s.empty()) s = "?";
return width > 0 ? fmt("%s x%d", s.c_str(), width) : s;
}
std::string watts(int64_t uw) { return uw < 0 ? std::string("unknown") : fmt("%lld W", (long long)(uw / 1000000)); }
std::string host_lines(const HostFacts& h, const RunFacts& r) {
std::string o;
o += fmt(" host %s | %s cores, %s threads | RAM %s, %s available | swap %s\n",
or_unknown(h.cpu_model).c_str(),
h.cores > 0 ? std::to_string(h.cores).c_str() : "?",
h.threads > 0 ? std::to_string(h.threads).c_str() : "?",
bytes_or_unknown(h.mem_total).c_str(), bytes_or_unknown(h.mem_available).c_str(),
h.swap_total == 0 ? "none"
: h.swap_total < 0 ? "unknown"
: fmt("%s, %s used", humanb(h.swap_total).c_str(),
humanb(h.swap_total - std::max<int64_t>(h.swap_free, 0)).c_str()).c_str());
o += fmt(" system kernel %s | %s | %s | cgroup memory %s | memlock %s\n",
or_unknown(h.kernel).c_str(), or_unknown(h.distro).c_str(),
h.container.empty() ? "no container seen" : ("in a " + h.container + " container").c_str(),
h.cgroup_mem_limit == -2 ? "unlimited" : bytes_or_unknown(h.cgroup_mem_limit).c_str(),
h.memlock_soft == -2 ? "unlimited" : bytes_or_unknown(h.memlock_soft).c_str());
o += fmt(" memory huge pages %s (defrag %s, shmem %s) | ttm.pages_limit %s "
"| pinned by this process %s\n",
or_unknown(h.thp_enabled).c_str(), or_unknown(h.thp_defrag).c_str(),
or_unknown(h.thp_shmem).c_str(),
h.ttm_pages_limit > 0 ? humanb(h.ttm_pages_limit * h.page_size).c_str() : "unknown",
bytes_or_unknown(r.pinned_bytes).c_str());
o += fmt(" iommu %s (%s)\n", or_unknown(h.iommu).c_str(), or_unknown(h.iommu_why).c_str());
o += fmt(" amdgpu cwsr_enable %s | boot parameters: %s\n",
h.cwsr_enable < 0 ? "unknown" : std::to_string(h.cwsr_enable).c_str(),
h.cmdline.empty() ? "none that bear on a card" : h.cmdline.c_str());
o += fmt(" cpu governor %s%s%s | io_uring %s\n", or_unknown(h.cpu_governor).c_str(),
h.cpu_epp.empty() ? "" : (", energy preference " + h.cpu_epp).c_str(),
h.cpu_driver.empty() ? "" : (" (" + h.cpu_driver + ")").c_str(),
or_unknown(h.io_uring).c_str());
o += fmt(" runtime %s | backend %s\n",
h.runtime.empty() ? "no device runtime" : h.runtime.c_str(),
r.host_backend ? "host (CPU)" : "device");
return o;
}
std::string card_lines(const CardFacts& c) {
std::string o;
std::string who = c.rank >= 0 ? fmt("rank %d (device %d)", c.rank, c.device)
: c.device >= 0 ? fmt("device %d, not serving", c.device) : "not serving";
o += fmt(" card %s %s %s%s%s %s VRAM",
c.bdf.c_str(), who.c_str(), c.gfx.empty() ? (c.vendor + ":" + c.pci_device).c_str() : c.gfx.c_str(),
c.name.empty() ? "" : " ", c.name.empty() ? "" : ("\"" + c.name + "\"").c_str(),
bytes_or_unknown(c.vram_total).c_str());
if (c.vram_visible > 0 && c.vram_visible != c.vram_total)
o += fmt(" (BAR %s)", humanb(c.vram_visible).c_str());
o += fmt(" NUMA %d driver %s%s%s\n", c.numa_node, or_unknown(c.driver).c_str(),
c.drm.empty() ? "" : " ", c.drm.c_str());
std::string chain;
for (const PciHop& h : c.chain)
chain += fmt("%s%s %s (max %s)", chain.empty() ? "" : " -> ", short_bdf(h.bdf).c_str(),
link(h.cur_speed, h.cur_width).c_str(), link(h.max_speed, h.max_width).c_str());
o += fmt(" link %s [read at %s%% busy%s]\n", chain.empty() ? "unknown" : chain.c_str(),
c.busy_percent < 0 ? "?" : std::to_string(c.busy_percent).c_str(),
c.busy_percent >= 0 && c.busy_percent < 30 ? ": a link at rest parks below its maximum" : "");
if (!c.dpm_pcie.empty()) {
std::string t;
for (size_t i = 0; i < c.dpm_pcie.size(); ++i)
t += fmt("%s%s%s", i ? " | " : "", (int)i == c.dpm_pcie_cur ? "*" : "", c.dpm_pcie[i].c_str());
o += " pcie " + t + "\n";
}
if (!c.dma.empty()) o += " dma " + c.dma + "\n";
o += fmt(" power cap %s (default %s, max %s) | voltage offset %s | sclk %s | mclk %s | "
"runtime pm %s (control %s) | iommu group %s\n",
watts(c.power_cap_uw).c_str(), watts(c.power_cap_default_uw).c_str(),
watts(c.power_cap_max_uw).c_str(), or_unknown(c.vddgfx_offset).c_str(),
or_unknown(c.sclk).c_str(), or_unknown(c.mclk).c_str(),
or_unknown(c.runtime_status).c_str(), or_unknown(c.runtime_control).c_str(),
c.iommu_type.empty() ? "none" : c.iommu_type.c_str());
return o;
}
} /* namespace */
std::string render(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings) {
std::string o;
o += "STARTUP REPORT" + (r.version.empty() ? std::string() : " -- radiance " + r.version) +
(r.failed ? " -- STARTUP STOPPED; this is what it had resolved when it did\n" : "\n");
o += "CONFIGURATION -- every option, the value in force, and where it came from\n";
size_t w = 0;
for (const ConfigRow& c : config) w = std::max(w, c.flag.size());
w = std::min<size_t>(w + 2, 34);
for (const ConfigRow& c : config) {
const std::string v = c.value.empty() ? "\"\"" : c.value;
const std::string first = v.substr(0, v.find('\n'));
std::string l = fmt(" %-*s %s", (int)w, c.flag.c_str(), first.c_str());
const size_t col = 2 + w + 1 + 44;
l += l.size() < col ? std::string(col - l.size(), ' ') : std::string(" ");
o += l + "[" + c.source + "]\n";
if (first.size() != v.size()) indented(&o, v.substr(first.size() + 1), (int)(3 + w));
if (!c.why.empty()) indented(&o, c.why, (int)(5 + w));
}
o += "ENVIRONMENT -- the RADIANCE_* variables set, by name; their values are not shown\n";
if (r.environment.empty()) o += " none\n";
for (const std::string& n : r.environment) o += " " + n + "\n";
if (!derived.empty()) {
o += "DERIVED -- what startup worked out that no single option states\n";
for (const Decision& d : derived) {
o += fmt(" %-*s %s\n", (int)w, d.key.c_str(), d.value.c_str());
if (!d.why.empty()) indented(&o, d.why, (int)(5 + w));
}
}
o += "HARDWARE\n";
o += host_lines(f.host, r);
for (const CardFacts& c : f.cards) o += card_lines(c);
if (f.cards.empty()) o += " no display-class PCI device is visible\n";
int nw = 0, nn = 0;
for (const Finding& x : findings) (x.level == Finding::Warn ? nw : nn)++;
o += fmt("FINDINGS -- %d warning%s, %d note%s\n", nw, nw == 1 ? "" : "s", nn, nn == 1 ? "" : "s");
if (findings.empty()) o += " nothing found that costs speed or correctness\n";
for (const Finding& x : findings) {
o += fmt(" %s %s: %s\n", x.level == Finding::Warn ? "WARN" : "note", x.id.c_str(),
x.what.c_str());
o += " why: " + x.why + "\n";
o += " fix: " + x.fix + "\n";
}
return o;
}
std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings) {
using J = nlohmann::ordered_json;
J o;
o["startup_failed"] = r.failed;
J cfg = J::array();
for (const ConfigRow& c : config) {
J e;
e["option"] = c.flag;
e["value"] = c.value;
e["source"] = c.source;
if (!c.why.empty()) e["why"] = c.why;
cfg.push_back(std::move(e));
}
o["configuration"] = std::move(cfg);
o["environment"] = r.environment;
J der = J::array();
for (const Decision& d : derived) der.push_back({ { "topic", d.key }, { "value", d.value }, { "why", d.why } });
o["derived"] = std::move(der);
const HostFacts& h = f.host;
J host;
host["cpu"] = h.cpu_model;
host["cores"] = h.cores;
host["threads"] = h.threads;
host["mem_total"] = h.mem_total;
host["mem_available"] = h.mem_available;
host["swap_total"] = h.swap_total;
host["swap_free"] = h.swap_free;
host["kernel"] = h.kernel;
host["distro"] = h.distro;
host["container"] = h.container;
host["cgroup_mem_limit"] = h.cgroup_mem_limit;
host["memlock"] = h.memlock_soft;
host["thp"] = { { "enabled", h.thp_enabled }, { "defrag", h.thp_defrag },
{ "shmem_enabled", h.thp_shmem } };
host["iommu"] = { { "mode", h.iommu }, { "why", h.iommu_why } };
host["boot_parameters"] = h.cmdline;
host["ttm_pages_limit"] = h.ttm_pages_limit;
host["page_size"] = h.page_size;
host["cwsr_enable"] = h.cwsr_enable;
host["io_uring"] = h.io_uring;
host["cpu_governor"] = h.cpu_governor;
host["cpu_epp"] = h.cpu_epp;
host["cpu_driver"] = h.cpu_driver;
host["runtime"] = h.runtime;
J cards = J::array();
for (const CardFacts& c : f.cards) {
J e;
e["bdf"] = c.bdf;
e["rank"] = c.rank;
e["device"] = c.device;
e["name"] = c.name;
e["vendor"] = c.vendor;
e["pci_device"] = c.pci_device;
e["gfx"] = c.gfx;
e["simd"] = c.simd;
e["driver"] = c.driver;
e["drm"] = c.drm;
e["numa_node"] = c.numa_node;
e["vram_total"] = c.vram_total;
e["vram_visible"] = c.vram_visible;
e["busy_percent"] = c.busy_percent;
e["runtime_status"] = c.runtime_status;
e["runtime_control"] = c.runtime_control;
e["iommu_group_type"] = c.iommu_type;
e["dma"] = c.dma;
J chain = J::array();
for (const PciHop& hp : c.chain)
chain.push_back({ { "bdf", hp.bdf }, { "speed", hp.cur_speed }, { "width", hp.cur_width },
{ "max_speed", hp.max_speed }, { "max_width", hp.max_width } });
e["link_chain"] = std::move(chain);
e["pcie_dpm"] = c.dpm_pcie;
e["pcie_dpm_current"] = c.dpm_pcie_cur;
e["sclk"] = c.sclk;
e["mclk"] = c.mclk;
e["power_cap_uw"] = c.power_cap_uw;
e["power_cap_default_uw"] = c.power_cap_default_uw;
e["power_cap_max_uw"] = c.power_cap_max_uw;
e["vddgfx_offset"] = c.vddgfx_offset;
cards.push_back(std::move(e));
}
J run;
run["version"] = r.version;
run["device_build"] = r.device_build;
run["tp"] = r.tp;
run["host_backend"] = r.host_backend;
run["p2p"] = r.p2p;
run["p2p_blocked"] = r.p2p_blocked;
run["ignored_devices"] = r.ignored;
run["pinned_bytes"] = r.pinned_bytes;
run["host_weight_bytes"] = r.host_weight_bytes;
run["file_weight_bytes"] = r.file_weight_bytes;
o["hardware"] = { { "host", std::move(host) }, { "cards", std::move(cards) }, { "run", std::move(run) } };
J fs = J::array();
for (const Finding& x : findings)
fs.push_back({ { "level", x.level == Finding::Warn ? "warn" : "note" }, { "id", x.id },
{ "what", x.what }, { "why", x.why }, { "fix", x.fix } });
o["findings"] = std::move(fs);
/* REPLACE, NOT THROW, on bytes that are not UTF-8. Values here come from the operator and the
* filesystem -- a --model path, a boot parameter, a product name -- and none of them is
* promised to be UTF-8; the strict default would make the whole answer an exception. */
return o.dump(-1, ' ', false, J::error_handler_t::replace);
}
} /* namespace diag */
} /* namespace rad */
+473
View File
@@ -0,0 +1,473 @@
/* sysinfo.cpp -- the machine, as /proc and /sys describe it.
*
* EVERY READ IS A FILE UNDER A ROOT. No tool is run and no library beyond the C++ runtime is
* asked: the production image is built FROM scratch and has no shell, no lspci and no rocm-smi,
* and a test hands the collector a directory tree of its own to stand for a machine with two cards
* behind a switch, a parked link, or an IOMMU that translates. What a file does not say is left
* unknown, never guessed.
*/
#include "diag/diag.h"
#include "rad_internal.h"
#include <cerrno>
#include <cctype>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <map>
#include <set>
#include <sstream>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <unistd.h>
namespace rad {
namespace diag {
namespace fs = std::filesystem;
namespace {
std::string slurp(const std::string& path) {
std::ifstream f(path);
if (!f) return std::string();
std::stringstream ss;
ss << f.rdbuf();
return ss.str();
}
std::string trim(std::string s) {
while (!s.empty() && (s.back() == '\n' || s.back() == ' ' || s.back() == '\t' || s.back() == '\r'))
s.pop_back();
size_t i = 0;
while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
return s.substr(i);
}
/* The first line of a sysfs attribute, trimmed; "" when it cannot be read. */
std::string line(const std::string& path) {
const std::string s = slurp(path);
const size_t nl = s.find('\n');
return trim(nl == std::string::npos ? s : s.substr(0, nl));
}
int64_t num(const std::string& path, int64_t dflt = -1) {
const std::string s = line(path);
if (s.empty()) return dflt;
char* end = nullptr;
const long long v = std::strtoll(s.c_str(), &end, 0);
return end && end != s.c_str() ? (int64_t)v : dflt;
}
/* The bracketed word of a sysfs choice list: "always [madvise] never" -> "madvise". */
std::string selected(const std::string& path) {
const std::string s = line(path);
const size_t a = s.find('['), b = s.find(']');
if (a == std::string::npos || b == std::string::npos || b < a) return s;
return s.substr(a + 1, b - a - 1);
}
bool exists(const std::string& p) {
std::error_code ec;
return fs::exists(p, ec);
}
std::vector<std::string> list(const std::string& dir) {
std::vector<std::string> out;
std::error_code ec;
for (fs::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec))
out.push_back(it->path().filename().string());
std::sort(out.begin(), out.end());
return out;
}
bool is_bdf(const std::string& s) {
unsigned d, b, dv, f;
char tail;
return s.size() == 12 && std::sscanf(s.c_str(), "%4x:%2x:%2x.%1x%c", &d, &b, &dv, &f, &tail) == 4;
}
/* "0x7551" from a sysfs id file, which the kernel writes with its prefix. */
std::string hexid(const std::string& path) { return line(path); }
/* The lowest and highest level of a pp_dpm_* table, "500-2350 MHz"; the levels are listed in
* order, one a line, as "N: 2350Mhz *". */
std::string dpm_range(const std::string& path) {
std::istringstream in(slurp(path));
std::string l;
long lo = -1, hi = -1;
while (std::getline(in, l)) {
const size_t c = l.find(':');
const char* p = l.c_str() + (c == std::string::npos ? 0 : c + 1);
long v = std::strtol(p, nullptr, 10);
if (v <= 0) continue;
if (lo < 0 || v < lo) lo = v;
if (v > hi) hi = v;
}
if (lo < 0) return std::string();
return fmt("%ld-%ld MHz", lo, hi);
}
/* `pm`: whether the power-management files are read as well (collect's `managed`). */
void read_card(const std::string& root, const std::string& bdf, bool pm, CardFacts* c) {
const std::string dev = root + "/sys/bus/pci/devices/" + bdf;
c->bdf = bdf;
c->vendor = hexid(dev + "/vendor");
c->pci_device = hexid(dev + "/device");
{
std::error_code ec;
const fs::path drv = fs::read_symlink(dev + "/driver", ec);
if (!ec) c->driver = drv.filename().string();
}
c->numa_node = (int)num(dev + "/numa_node", -1);
c->runtime_status = line(dev + "/power/runtime_status");
c->runtime_control = line(dev + "/power/control");
c->iommu_type = line(dev + "/iommu_group/type");
for (const std::string& d : list(dev + "/drm"))
if (d.rfind("card", 0) == 0 && d.size() > 4 && std::isdigit((unsigned char)d[4])) c->drm = d;
/* THE WHOLE PATH TO THE ROOT PORT, not the card's own link alone. A card with a switch on it
* reports its own endpoint link at full speed whatever the slot does upstream: a root port
* parked one speed down shows only at the root port (and in the card's DPM table). */
std::error_code ec;
const fs::path real = fs::canonical(dev, ec);
if (!ec) {
for (const fs::path& part : real) {
const std::string p = part.string();
if (!is_bdf(p)) continue;
const std::string hd = root + "/sys/bus/pci/devices/" + p;
PciHop h;
h.bdf = p;
h.cur_speed = line(hd + "/current_link_speed");
h.max_speed = line(hd + "/max_link_speed");
h.cur_width = (int)num(hd + "/current_link_width", -1);
h.max_width = (int)num(hd + "/max_link_width", -1);
c->chain.push_back(h);
}
}
if (c->chain.empty()) {
PciHop h;
h.bdf = bdf;
h.cur_speed = line(dev + "/current_link_speed");
h.max_speed = line(dev + "/max_link_speed");
h.cur_width = (int)num(dev + "/current_link_width", -1);
h.max_width = (int)num(dev + "/max_link_width", -1);
c->chain.push_back(h);
}
c->vram_total = num(dev + "/mem_info_vram_total", -1);
c->vram_visible = num(dev + "/mem_info_vis_vram_total", -1);
if (!pm) return;
c->busy_percent = (int)num(dev + "/gpu_busy_percent", -1);
{
std::istringstream in(slurp(dev + "/pp_dpm_pcie"));
std::string l;
while (std::getline(in, l)) {
l = trim(l);
if (l.empty()) continue;
if (l.find('*') != std::string::npos) c->dpm_pcie_cur = (int)c->dpm_pcie.size();
l.erase(std::remove(l.begin(), l.end(), '*'), l.end());
c->dpm_pcie.push_back(trim(l));
}
}
c->sclk = dpm_range(dev + "/pp_dpm_sclk");
c->mclk = dpm_range(dev + "/pp_dpm_mclk");
for (const std::string& h : list(dev + "/hwmon")) {
const std::string hp = dev + "/hwmon/" + h;
if (!exists(hp + "/power1_cap")) continue;
c->power_cap_uw = num(hp + "/power1_cap", -1);
c->power_cap_default_uw = num(hp + "/power1_cap_default", -1);
c->power_cap_max_uw = num(hp + "/power1_cap_max", -1);
break;
}
{
/* "OD_VDDGFX_OFFSET:\n-75mV": the offset the driver holds for the card, which is the one
* it uploads; whether the firmware took it is not in this file. */
const std::string od = slurp(dev + "/pp_od_clk_voltage");
const size_t at = od.find("OD_VDDGFX_OFFSET:");
if (at != std::string::npos) {
const char* p = od.c_str() + at + std::strlen("OD_VDDGFX_OFFSET:");
char* end = nullptr;
const long v = std::strtol(p, &end, 10);
if (end && end != p) c->vddgfx_offset = fmt("%ld mV", v);
}
}
}
/* The KFD topology knows what the PCI files do not: each GPU node's target and SIMD count, keyed
* by its PCI location -- `location_id` is (bus << 8) | (device << 3) | function. */
void read_kfd(const std::string& root, std::vector<CardFacts>* cards) {
const std::string nodes = root + "/sys/class/kfd/kfd/topology/nodes";
for (const std::string& n : list(nodes)) {
/* A LINE AT A TIME, and only the four keys this needs parsed: the file holds values no
* signed 64-bit integer takes (unique_id is a full 64-bit hash), and a stream extraction
* that meets one fails and stops reading every key after it. */
std::istringstream in(slurp(nodes + "/" + n + "/properties"));
std::string l;
long long loc = -1, dom = 0, gfx = 0, simd = -1;
while (std::getline(in, l)) {
const size_t sp = l.find_first_of(" \t");
if (sp == std::string::npos) continue;
const std::string k = l.substr(0, sp);
long long* into = k == "location_id" ? &loc
: k == "domain" ? &dom
: k == "gfx_target_version" ? &gfx
: k == "simd_count" ? &simd
: nullptr;
if (!into) continue;
const char* p = l.c_str() + sp + 1;
char* end = nullptr;
errno = 0;
const long long v = std::strtoll(p, &end, 10);
if (end != p && errno == 0) *into = v;
}
if (gfx <= 0 || loc < 0) continue;
const std::string bdf = fmt("%04llx:%02llx:%02llx.%llx", dom, (loc >> 8) & 0xff,
(loc >> 3) & 0x1f, loc & 7);
for (CardFacts& c : *cards) {
if (c.bdf != bdf) continue;
c.gfx = fmt("gfx%lld%llx%llx", gfx / 10000, (gfx / 100) % 100, gfx % 100);
c.simd = (int)simd;
}
}
}
/* Of two memory limits in HostFacts' encoding (bytes, -2 unlimited, -1 unknown), the one that
* binds: the smaller number, else unlimited over unknown. */
int64_t tighter(int64_t a, int64_t b) {
if (a >= 0 && b >= 0) return std::min(a, b);
if (a >= 0 || b >= 0) return std::max(a, b);
return a == -2 || b == -2 ? -2 : -1;
}
/* THE TIGHTEST MEMORY LIMIT FROM A CGROUP UP TO THE MOUNT'S ROOT. A limit binds every cgroup
* below it, so the process's own group can say "max" while the systemd slice or the container's
* group above it holds the limit that counts. `rel` is the path /proc/self/cgroup names, under
* `mount`; every level on the way up is read, the mount's root included -- inside a container's
* cgroup namespace that root is the container's own group. */
int64_t cgroup_limit(const std::string& mount, std::string rel, const char* file) {
int64_t lim = -1;
while (!rel.empty() && rel.back() == '/') rel.pop_back();
for (;;) {
const std::string v = line(mount + rel + "/" + file);
if (v == "max") {
lim = tighter(lim, -2);
} else if (!v.empty()) {
char* end = nullptr;
errno = 0;
const long long n = std::strtoll(v.c_str(), &end, 10);
/* Version 1 writes "no limit" as the largest page-aligned number below 2^63. */
if (end != v.c_str() && errno == 0 && n >= 0)
lim = tighter(lim, n >= ((long long)1 << 62) ? -2 : (int64_t)n);
}
if (rel.empty()) break;
const size_t up = rel.rfind('/');
rel.erase(up == std::string::npos ? 0 : up);
}
return lim;
}
void read_host(const std::string& root, HostFacts* h) {
{
std::istringstream in(slurp(root + "/proc/cpuinfo"));
std::string l;
std::set<std::pair<std::string, std::string>> cores;
std::string phys;
int threads = 0;
while (std::getline(in, l)) {
const size_t c = l.find(':');
if (c == std::string::npos) continue;
const std::string k = trim(l.substr(0, c)), v = trim(l.substr(c + 1));
if (k == "processor") ++threads;
else if (k == "model name" && h->cpu_model.empty()) h->cpu_model = v;
else if (k == "physical id") phys = v;
else if (k == "core id") cores.insert({ phys, v });
}
if (threads > 0) h->threads = threads;
if (!cores.empty()) h->cores = (int)cores.size();
}
{
std::istringstream in(slurp(root + "/proc/meminfo"));
std::string k;
long long v;
std::string unit;
while (in >> k >> v) {
std::getline(in, unit);
const int64_t b = (int64_t)v * 1024;
if (k == "MemTotal:") h->mem_total = b;
else if (k == "MemAvailable:") h->mem_available = b;
else if (k == "SwapTotal:") h->swap_total = b;
else if (k == "SwapFree:") h->swap_free = b;
}
}
h->kernel = line(root + "/proc/sys/kernel/osrelease");
{
std::istringstream in(slurp(root + "/etc/os-release"));
std::string l;
while (std::getline(in, l))
if (l.rfind("PRETTY_NAME=", 0) == 0) {
h->distro = l.substr(12);
if (h->distro.size() >= 2 && h->distro.front() == '"') h->distro = h->distro.substr(1, h->distro.size() - 2);
}
}
if (exists(root + "/.dockerenv")) h->container = "docker";
else if (exists(root + "/run/.containerenv")) h->container = "podman";
else {
const std::string cg = slurp(root + "/proc/1/cgroup");
if (cg.find("docker") != std::string::npos) h->container = "docker";
else if (cg.find("kubepods") != std::string::npos) h->container = "kubernetes";
else if (cg.find("containerd") != std::string::npos) h->container = "containerd";
}
{
/* THE PROCESS'S OWN CGROUP, which inside a container is "/" under its namespace, and
* every one above it: cgroup_limit says why. Version 2 is the "0::" line; version 1's
* memory controller is the ":memory:" one, where "unlimited" is a number near 2^63. */
std::istringstream in(slurp(root + "/proc/self/cgroup"));
std::string l;
int64_t lim = -1;
while (std::getline(in, l)) {
int64_t v = -1;
if (l.rfind("0::", 0) == 0)
v = cgroup_limit(root + "/sys/fs/cgroup", l.substr(3), "memory.max");
else if (l.find(":memory:") != std::string::npos)
v = cgroup_limit(root + "/sys/fs/cgroup/memory", l.substr(l.find(":memory:") + 8),
"memory.limit_in_bytes");
lim = tighter(lim, v);
}
h->cgroup_mem_limit = lim;
}
const std::string thp = root + "/sys/kernel/mm/transparent_hugepage";
h->thp_enabled = selected(thp + "/enabled");
h->thp_defrag = selected(thp + "/defrag");
h->thp_shmem = selected(thp + "/shmem_enabled");
{
std::istringstream in(line(root + "/proc/cmdline"));
std::string t;
static const char* const kKeep[] = { "iommu", "amd_iommu", "intel_iommu", "amdgpu.", "ttm.",
"transparent_hugepage", "hugepages", "pcie_aspm",
"pci=", "default_hugepagesz" };
while (in >> t)
for (const char* k : kKeep)
if (t.rfind(k, 0) == 0) { h->cmdline += (h->cmdline.empty() ? "" : " ") + t; break; }
}
{
/* PASSTHROUGH OR TRANSLATED, from what decides it for the cards: their IOMMU groups' type
* (identity is passthrough) is the kernel's own answer; the boot parameters and the
* presence of an IOMMU are what is left when a card has no group. */
const bool any_iommu = !list(root + "/sys/class/iommu").empty();
const bool groups = !list(root + "/sys/kernel/iommu_groups").empty();
const std::string cl = " " + h->cmdline + " ";
if (!any_iommu && !groups) {
h->iommu = "off";
h->iommu_why = "no IOMMU is registered (/sys/class/iommu is empty)";
} else if (cl.find(" iommu=pt ") != std::string::npos ||
cl.find(" amd_iommu=pt ") != std::string::npos ||
cl.find(" intel_iommu=pt ") != std::string::npos) {
h->iommu = "passthrough";
h->iommu_why = "iommu=pt on the kernel command line";
} else if (cl.find("iommu=off") != std::string::npos) {
h->iommu = "off";
h->iommu_why = "the kernel command line turns it off";
} else {
h->iommu = "unknown";
h->iommu_why = "an IOMMU is present; its mode is read from the cards' groups below";
}
}
{
int64_t lim = num(root + "/sys/module/ttm/parameters/pages_limit", -1);
/* 0 IS THE DRIVER'S DEFAULT, which is half of RAM. */
if (lim == 0 && h->mem_total > 0) lim = h->mem_total / 2 / h->page_size;
h->ttm_pages_limit = lim;
}
h->cwsr_enable = (int)num(root + "/sys/module/amdgpu/parameters/cwsr_enable", -1);
{
const int64_t d = num(root + "/proc/sys/kernel/io_uring_disabled", -1);
h->io_uring = d == 0 ? "available" : d == 1 ? "restricted to a group (io_uring_disabled 1)"
: d == 2 ? "refused (io_uring_disabled 2)" : "unknown";
}
const std::string cpu = root + "/sys/devices/system/cpu/cpu0/cpufreq";
h->cpu_governor = line(cpu + "/scaling_governor");
h->cpu_epp = line(cpu + "/energy_performance_preference");
h->cpu_driver = line(cpu + "/scaling_driver");
}
} /* namespace */
Facts collect(const std::string& root, const std::vector<std::string>* managed) {
Facts f;
if (root.empty()) {
const long ps = sysconf(_SC_PAGE_SIZE);
if (ps > 0) f.host.page_size = ps;
}
read_host(root, &f.host);
/* EVERY DISPLAY-CLASS DEVICE, the engine's or not: an integrated GPU beside the cards, or a
* card the engine was told not to use, is part of the answer to "what is in this machine". */
for (const std::string& d : list(root + "/sys/bus/pci/devices")) {
const std::string cls = line(root + "/sys/bus/pci/devices/" + d + "/class");
if (cls.rfind("0x03", 0) != 0) continue;
const bool pm =
!managed || std::find(managed->begin(), managed->end(), d) != managed->end();
CardFacts c;
read_card(root, d, pm, &c);
f.cards.push_back(std::move(c));
}
read_kfd(root, &f.cards);
/* THE IOMMU'S MODE AS THE CARDS SEE IT, which beats the command line where both exist: each
* card's group says identity (passthrough) or DMA / DMA-FQ (translated), and a machine can
* hold both -- an integrated GPU left identity-mapped beside a translated discrete card. */
if (f.host.iommu == "unknown") {
std::map<std::string, std::string> by;
for (const CardFacts& c : f.cards)
if (!c.iommu_type.empty()) by[c.iommu_type] += (by[c.iommu_type].empty() ? "" : ", ") + c.bdf;
if (by.size() == 1) {
const bool id = by.begin()->first == "identity";
f.host.iommu = id ? "passthrough" : "translated";
f.host.iommu_why = "the display devices' IOMMU groups are of type " + by.begin()->first;
} else if (by.size() > 1) {
f.host.iommu = "mixed";
f.host.iommu_why.clear();
for (const auto& [t, bdfs] : by)
f.host.iommu_why += (f.host.iommu_why.empty() ? "" : "; ") + t + " for " + bdfs;
}
}
return f;
}
void probe_process(HostFacts* h) {
struct rlimit rl{};
if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0)
h->memlock_soft = rl.rlim_cur == RLIM_INFINITY ? -2 : (int64_t)rl.rlim_cur;
#ifdef SYS_io_uring_setup
/* ASKED, NOT INFERRED: a seccomp profile (Docker's default) refuses the call whatever the
* sysctl says, and the answer is the error the call returns. One entry, closed at once. */
struct { uint32_t sq_entries, cq_entries, flags, sq_thread_cpu, sq_thread_idle, features,
wq_fd, resv[3]; uint64_t sq_off[5]; uint64_t cq_off[5]; } p{};
static_assert(sizeof(p) == 120, "io_uring_params is 120 bytes");
const long fd = syscall(SYS_io_uring_setup, 1, &p);
if (fd >= 0) {
close((int)fd);
h->io_uring = "available";
} else {
h->io_uring = fmt("refused (%s)", std::strerror(errno));
}
#endif
}
std::vector<std::string> env_names(char* const* env, const char* prefix) {
std::vector<std::string> out;
const size_t n = std::strlen(prefix);
for (char* const* e = env; e && *e; ++e) {
if (std::strncmp(*e, prefix, n) != 0) continue;
const char* eq = std::strchr(*e, '=');
out.emplace_back(*e, eq ? (size_t)(eq - *e) : std::strlen(*e));
}
std::sort(out.begin(), out.end());
return out;
}
} /* namespace diag */
} /* namespace rad */
+587 -198
View File
File diff suppressed because it is too large. Load diff
+95 -26
View File
@@ -22,6 +22,7 @@
#pragma once
#include "rad_core.h"
#include "build/startup.h"
#include "diag/diag.h"
#include "mem/hostarena.h"
#include "sched/mem_iface.h"
#include "sched/scheduler.h"
@@ -40,8 +41,8 @@
namespace rad {
class SSDTier;
class Kld;
namespace gen { class Driver; }
struct TierPump;
struct TierJob;
struct StepSlot;
@@ -70,6 +71,20 @@ public:
const Program& program() const;
const Config& config() const { return cfg_; }
/* THE STARTUP REPORT (core/diag/diag.h): every option with the value in force and its source,
* the machine, and what on it costs speed or correctness. serve() prints it before it starts
* listening with `status` RAD_OK; main prints it with the error start() or serve() stopped
* with, so a log of a server that never came up still says what it was running on and what
* it had decided -- and ends with that error again on an E line, because the report's lines
* now follow the one that said it and a reader of the log's tail would see only them. */
void print_startup_report(int status);
/* The same, as JSON, with the hardware read again -- a card's link and clock are only
* meaningful under load, and /diagnostics is how they are read while a request runs. The
* reading is reused for a second, and covers the power-management files of the serving
* cards only (hardware_facts). */
std::string diagnostics_json() const;
bool startup_report_printed() const { return report_printed_; }
private:
/* One thread per tensor-parallel rank, each owning one device. No IPC, no shared-memory
* handshake, no serialisation between ranks -- which is most of what a Python engine spends
@@ -77,18 +92,7 @@ private:
* shared BY POINTER rather than broadcast (spec §1). */
struct Rank;
std::vector<std::unique_ptr<Rank>> ranks_;
/* THE DISK HALF OF THE IDLE TIERS. One store for the engine, not one per rank: it is
* keyed by a chained hash of TOKENS, which every rank computes identically, and a
* per-rank store would write the same key several times over. Off unless
* --prefix-cache-disk-mib and a directory are both given; it holds conversation content
* unencrypted and says so at startup.
*
* unique_ptr because engine.h is included by main.cpp and the tools, and SSDTier
* drags in the O_DIRECT device layer that none of them want to compile against. */
std::unique_ptr<SSDTier> kv_disk_;
/* THE TIERS' WORK IN FLIGHT: the copy to host memory the transfer streams are running and the
* disk batch the IO thread is writing. Declared after kv_disk_ so it goes first -- the thread
* writes into that store. */
/* THE TIERS' WORK IN FLIGHT: the copy to host memory the transfer streams are running. */
std::unique_ptr<TierPump> pump_;
std::vector<std::thread> rank_threads_;
@@ -131,11 +135,11 @@ private:
int apply_rope_scaling();
int declare();
int plan();
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
* (engine_bringup.cpp says how auto chooses). */
/* --embedding-placement, --vision-tower-placement and --ngram-placement, resolved into Config
* before the card is split (engine_bringup.cpp says how auto chooses). */
int resolve_table_placement(const std::vector<VramFacts>& facts,
const std::vector<int64_t>& emb_bytes,
const std::vector<int64_t>& floor_emb_ram, int64_t kv_floor,
const std::vector<int64_t>& tower_bytes, int64_t kv_floor,
int64_t ngram_bytes, bool ngram_device, bool ngram_host);
/* --ngram-placement ram: the copy of the container's [src, src + n), file offset `foff`, made
* once and shared by every rank -- locked for the host gather, or pinned for a device kernel
@@ -167,6 +171,9 @@ private:
std::vector<int32_t> token; /* [n_seq] */
std::vector<int32_t> accepted; /* [n_seq] */
std::vector<uint8_t> eos; /* [n_seq] */
/* [n_rows] each sampled row's logprobs, for the rows of requests that asked for them;
* empty on a step with none. */
std::vector<TokenLogprobs> lp;
};
/* The text frontend, loaded out of the container. `vocab_view_` is what the sampler's
@@ -216,6 +223,14 @@ private:
* the device cannot reach until the whole forward pass has run, and that pass is the time the
* walk hides inside. This is a one-shot gate per step, reset while the ranks are parked at the
* release, so there is no window in which a rank can read a stale ready flag. */
/* THIS STEP'S SCORED ROWS (Request::token_scores): a logits row and the result it fills.
* Written by the scheduler thread while the ranks are parked, read by them during the step,
* consumed by collect_step. */
std::vector<std::pair<int32_t, TokenScores*>> score_rows_;
int stage_scored_rows(const StepPlan& plan, const StepOut& so);
int issue_scored_rows(Rank& r);
int collect_scored_rows();
std::mutex build_mu_;
std::condition_variable build_cv_;
bool build_ready_ = false;
@@ -224,6 +239,7 @@ private:
/* Scratch for the checkpoint copies: the state slots of one sequence, reused so the step path
* does not allocate. See state_slots_of. */
std::vector<int32_t> ckpt_slots_;
std::vector<int32_t> ckpt_win_; /* KVManager::window_rows, same reuse */
bool state_slots_of(uint64_t seq, std::vector<int32_t>* out) const;
int load_vocab();
@@ -238,6 +254,7 @@ private:
* wait left until after them. */
int collect_issue(const RadBatch* b, StepOut& so);
int collect_step(const RadBatch* b, StepOut& so);
int row_logprobs(StepOut& so, int32_t row, int32_t token);
/* WHERE THE STEP ENDS ON THE CARD: after its last draft pass and the copies the host reads,
* and before the step issued ahead of it. collect_step waits for this and not for the
* stream, so the card runs the next step while the host commits this one. */
@@ -269,6 +286,20 @@ private:
~Readback();
};
Readback readback_;
/* AN EMBEDDING PROGRAM (rad_declare_pooled): no sampler, and a step's answer is the pooled
* buffer's first n_seq rows rather than sampled ids. `pooled_host_` is their pinned landing
* place, [max_seqs, pooled_dim_] f32; collect_pooled copies them there behind the step and
* hands each row to its request's sink after the step's one wait. */
bool embedding_ = false;
int64_t pooled_dim_ = 0;
float* pooled_host_ = nullptr;
int collect_pooled_issue(const RadBatch* b, StepOut& so);
int collect_pooled(const RadBatch* b, StepOut& so);
/* AN IMAGE GENERATOR (rad_declare_generator): the driver that turns its requests into passes
* and the loop that runs them, in place of the scheduler and the step loop (engine_gen.cpp).
* Null for every other program. */
std::unique_ptr<gen::Driver> gen_;
int gen_loop();
bool serial_drafting() const;
int advance_all(int mode, int round, bool from_proposal, int rows = -1);
int issue_serial_drafter(int step, const RadBatch* b, StepOut& so);
@@ -316,20 +347,15 @@ private:
/* The terminal ids drain_completed() took, reused so a steady state allocates nothing. */
std::vector<uint64_t> done_;
/* THE TIERS' SIDE OF THE LOOP, every iteration: collect a copy that has landed, hand the next
* one out, collect and hand out the disk work. Nothing in it waits on the device or on a file,
* and the scheduler's lock is held only around the bookkeeping. */
* one out, and make room in a full arena. Nothing in it waits on the device, and the
* scheduler's lock is held only around the bookkeeping. */
void tier_tick();
bool submit_fetch(uint64_t tag, std::vector<TierJob>&& jobs);
/* A MARK ON EVERY RANK'S STREAMS, for the disk thread to wait on before it touches a slot:
* the transfer streams' when `transfer`, the compute streams' when `compute`, in that order,
* one a rank each; `st` is the first failure to make one. destroy_fences gives them back on
* their own cards. */
std::vector<RadEvent> rank_fences(bool transfer, bool compute, int* st = nullptr);
void destroy_fences(std::vector<RadEvent>& f);
/* --prefix-cache-ttl, once a second, with or without the tiers (PrefixCache::expire). */
void expire_tick(uint64_t now_ns);
uint64_t expire_last_ns_ = 0;
/* Every host copy that is waiting, issued and landed now. Under the scheduler's lock, from an
* eviction that would otherwise erase what the copies cover. True when any landed. */
bool flush_copies();
uint64_t tier_last_ns_ = 0;
/* THE LOAN: what the KV cache is not using, lent to every rank's expert slab at the addresses
* the cache already owns (KVManager, the loan block). Here rather than inside the scheduler
* because it spans both sides -- rank 0's cache decides how much, and every rank's mover
@@ -372,6 +398,49 @@ private:
/* The engine half of /server_info, as a JSON object. See the definition in engine.cpp. */
std::string engine_info() const;
/* ---- what the startup report says about the run (engine_diag.cpp). `decisions_` holds each
* value startup resolved and why, recorded where it was resolved; the rest are the facts a
* check needs that only startup saw. */
std::vector<diag::Decision> decisions_;
void decide(const std::string& key, const std::string& value, const std::string& why) {
diag::decide(&decisions_, key, value, why);
}
std::string devnote_; /* the devices usable_devices left out, and why */
int p2p_measured_ = -1; /* 1 peer to peer, 0 through host memory, -1 not asked */
std::string p2p_blocked_;
bool has_ngram_ = false; /* the model carries an n-gram table */
std::string prefix_off_why_; /* why the engine itself turned prefix caching off, or "" */
std::vector<std::string> env_set_; /* the RADIANCE_* names set when the engine was made */
bool report_printed_ = false;
/* THE RUNTIME'S DEVICES, ASKED ONCE, in start() beside usable_devices, which reads every
* device's properties anyway. A report printed after start() failed -- possibly after a device
* fault -- then makes no runtime call at all, and /diagnostics, on an HTTP thread, makes none
* either: a runtime call there can wait on a lock the launch path holds
* (DeviceBackend::vram_used says the same of the dashboard). What only the runtime knows --
* each device's PCI address, its name, whether it is integrated, and the runtime's version --
* is kept from that one reading. */
struct DevId { int device = -1; std::string bdf, name; bool integrated = false; };
std::vector<DevId> dev_ids_;
std::string runtime_version_;
void identify_devices(const std::vector<std::string>& names);
/* WHAT ONLY A SYSTEM CALL ANSWERS (diag::probe_process), asked once when the report is first
* printed: the memlock limit cannot change under a running process, and the io_uring probe is
* a syscall that /diagnostics has no reason to repeat on every request. */
bool probed_ = false;
int64_t memlock_soft_ = -1;
std::string io_uring_;
/* THE MACHINE AS /diagnostics LAST READ IT, kept for kDiagReuseNs. The card files are answered
* by the SMU under the driver's power-management lock, so a client polling the endpoint must
* not turn into a stream of SMU requests beside the serving process; a second's staleness is
* nothing to a reading of links and clocks. */
mutable std::mutex diag_mu_;
mutable diag::Facts diag_facts_;
mutable uint64_t diag_read_ns_ = 0;
/* `serving`: read the power-management files of the cards the ranks serve on only
* (diag::collect's `managed`), which is how a running server reads them. */
diag::Facts hardware_facts(bool serving) const;
diag::RunFacts run_facts(bool failed) const;
/* One dispatch of the tiering seam: retire what landed, credit last step's routing and issue
* what the heat engine proposes. A member because Rank is private, and a no-op on a static
* plan. See the long note at the definition for why a step is the unit. */
+464 -306
View File
File diff suppressed because it is too large. Load diff
+158
View File
@@ -0,0 +1,158 @@
/* engine_diag.cpp -- the startup report's engine half: the facts only a started engine has, joined
* to the machine's (core/diag/diag.h).
*
* THE CARDS ARE JOINED BY PCI ADDRESS. The runtime numbers its devices its own way -- a visible-
* device mask renumbers them, an integrated GPU may come first -- and the kernel describes them by
* bus address; the backend's pci_address is the one key both sides agree on.
*/
#include "engine_priv.h"
#include "device/device.h"
#include <algorithm>
namespace rad {
namespace {
/* How long /diagnostics reuses a reading of the machine. */
constexpr uint64_t kDiagReuseNs = 1000000000ull;
} /* namespace */
void Engine::identify_devices(const std::vector<std::string>& names) {
dev_ids_.clear();
runtime_version_ = dev_runtime_version();
for (int d = 0; d < (int)names.size(); ++d) {
DevId id;
id.device = d;
id.bdf = dev_pci_address(d);
if (id.bdf.empty()) continue;
id.name = names[(size_t)d];
id.integrated = dev_integrated(d);
dev_ids_.push_back(std::move(id));
}
}
diag::Facts Engine::hardware_facts(bool serving) const {
std::vector<std::string> mine;
for (const DevId& id : dev_ids_)
for (const auto& r : ranks_)
if (r->device == id.device) mine.push_back(id.bdf);
diag::Facts f = diag::collect("", serving ? &mine : nullptr);
f.host.runtime = runtime_version_;
if (probed_) {
f.host.memlock_soft = memlock_soft_;
f.host.io_uring = io_uring_;
}
for (const DevId& id : dev_ids_)
for (diag::CardFacts& c : f.cards) {
if (c.bdf != id.bdf) continue;
c.name = id.name;
c.device = id.device;
c.integrated = id.integrated;
for (const auto& r : ranks_)
if (r->device == id.device) c.rank = r->index;
if (c.rank >= 0) c.dma = dev_dma_lane(id.device);
}
return f;
}
diag::RunFacts Engine::run_facts(bool failed) const {
diag::RunFacts r;
r.version = RAD_VERSION;
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
r.device_build = true;
#else
r.device_build = false;
#endif
r.tp = cfg_.tp;
r.host_backend = device_is_host();
r.failed = failed;
r.p2p = cfg_.tp > 1 ? p2p_measured_ : -1;
r.p2p_forced_off = cfg_.p2p == RAD_P2P_OFF;
r.p2p_blocked = p2p_blocked_;
if (!devnote_.empty()) r.ignored.push_back(devnote_);
r.tp_wire_lossy = !cfg_.tp_wire_exact;
r.tp_wire_min_kb = cfg_.tp_wire_min_kb;
r.prefix_cache = cfg_.prefix_cache;
r.prefix_cache_off_why = prefix_off_why_;
r.host_pool_mib = cfg_.host_pool_mib;
{
int64_t pinned = 0, mapped = 0, n = 0;
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, &n);
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, &n);
r.pinned_bytes = pinned + mapped;
}
/* THE MOST ANY RANK READS FROM THE HOST: the ranks step together, so the one that streams most
* is the one each step waits for. The embedding the placement flag put in host memory is read
* a few rows a step, the encoder towers once an image, and neither is what this counts. */
for (const auto& rk : ranks_) {
const Plan& p = rk->plan;
const int64_t host = p.totals.bytes[(int)Tier::HostPinned] +
p.totals.bytes[(int)Tier::HostPageable] - p.forced_host_used;
r.host_weight_bytes = std::max(r.host_weight_bytes, std::max<int64_t>(host, 0));
r.file_weight_bytes = std::max(r.file_weight_bytes, p.totals.bytes[(int)Tier::SSD]);
}
for (const TableCopy& t : table_copies_) r.locked_bytes += (int64_t)t.bytes;
r.ngram_placement = has_ngram_ ? table_placement_name(cfg_.ngram_resolved) : "";
r.reference_kernels = cfg_.accept_reference_kernels;
r.profile_ops = cfg_.profile_ops;
r.deterministic = cfg_.deterministic;
r.environment = env_set_;
return r;
}
void Engine::print_startup_report(int status) {
report_printed_ = true;
if (!probed_) {
diag::HostFacts h;
diag::probe_process(&h);
memlock_soft_ = h.memlock_soft;
io_uring_ = h.io_uring;
probed_ = true;
}
std::vector<diag::ConfigRow> rows = diag::config_rows(cfg_);
std::vector<diag::Decision> derived;
diag::merge(&rows, decisions_, &derived);
const diag::Facts f = hardware_facts(false);
const diag::RunFacts r = run_facts(status < 0);
const std::vector<diag::Finding> found = diag::check(f, r);
/* A LINE A LOG CALL: the logger formats into a fixed buffer, and one line each keeps every line
* of the report on the same level tag a grep for the startup reads. */
const std::string text = diag::render(rows, derived, f, r, found);
size_t at = 0;
while (at < text.size()) {
size_t nl = text.find('\n', at);
if (nl == std::string::npos) nl = text.size();
RAD_INFO("%s", text.substr(at, nl - at).c_str());
at = nl + 1;
}
/* AND EACH WARNING ON A W LINE OF ITS OWN, because the warnings are what a reader filtering a
* production log for W and E lines is looking for. */
for (const diag::Finding& x : found)
if (x.level == diag::Finding::Warn)
RAD_WARN("startup report: %s: %s. Fix: %s", x.id.c_str(), x.what.c_str(), x.fix.c_str());
/* THE FAILURE LAST. The line that said what stopped startup is above the report now, and
* `docker logs --tail` or a terminal's last screen shows only what is below it. */
if (status < 0)
RAD_ERR("startup stopped: %s (the reason is said above the startup report)",
rad_strerror(status));
}
std::string Engine::diagnostics_json() const {
std::vector<diag::ConfigRow> rows = diag::config_rows(cfg_);
std::vector<diag::Decision> derived;
diag::merge(&rows, decisions_, &derived);
diag::Facts f;
{
std::lock_guard<std::mutex> lk(diag_mu_);
const uint64_t now = rad_mono_ns();
if (diag_read_ns_ == 0 || now - diag_read_ns_ >= kDiagReuseNs) {
diag_facts_ = hardware_facts(true);
diag_read_ns_ = now;
}
f = diag_facts_;
}
const diag::RunFacts r = run_facts(false);
return diag::to_json(rows, derived, f, r, diag::check(f, r));
}
} /* namespace rad */
+72
View File
@@ -0,0 +1,72 @@
/* engine_gen.cpp -- the image generator's loop: the driver's passes (core/gen/driver.h) run on the
* ranks the way the step loop runs token steps, one at a time and each drained before the next.
*
* WHY EACH PASS IS DRAINED. A generator pass is tens to thousands of milliseconds of device work,
* and what decides the next one -- which image finished, which preview a step marked -- is the
* driver's bookkeeping of the pass just run, not anything the card computes. Waiting for the card
* between passes costs the few microseconds the host takes to build the next one; issuing ahead
* would need a second staging region and a commit protocol, for nothing a client could measure.
*/
#include "engine_priv.h"
#include "gen/driver.h"
#include <chrono>
#include <thread>
namespace rad {
int Engine::gen_loop() {
if (rad_dev_set(ranks_[0]->device) < 0)
RAD_ERR("image generator loop: could not bind rank 0's device");
int step = 0, idle = 0;
const rad_buf img = ranks_[0]->program.generator.image_out;
while (!stopping_.load(std::memory_order_acquire)) {
const RadBatch* b = gen_->next(step);
if (!b) {
step_batch_.store(nullptr, std::memory_order_release);
if (idle < 200) ++idle;
std::this_thread::sleep_for(std::chrono::microseconds(idle * 50));
continue;
}
idle = 0;
if (const int ps = prepare_release(b); ps < 0) {
gen_->shutdown("the engine stopped on an error and is not serving", ps);
return fail_loop(ps);
}
issue_what_.store(kIssueModel, std::memory_order_release);
step_batch_.store(b, std::memory_order_release);
barrier_->arrive_and_wait(); /* release the ranks */
barrier_->arrive_and_wait(); /* wait for them */
int st = step_status_.load(std::memory_order_acquire);
if (st < 0) {
RAD_ERR("generator pass %d failed: %s -- the engine cannot continue", step,
rad_strerror(st));
gen_->shutdown("the engine stopped on an error and is not serving", st);
return fail_loop(st);
}
/* A DECODE PASS'S IMAGE, behind it on rank 0's stream: every rank decodes the same pixels. */
if (const int64_t n = gen_->decode_bytes(); n > 0) {
const void* src = ranks_[0]->ctx.buf_ptr(img);
if (!src) {
RAD_ERR("the generator's image buffer was declared but never planned");
gen_->shutdown("the engine stopped on an error and is not serving", RAD_E_STATE);
return fail_loop(RAD_E_STATE);
}
st = rad_memcpy_async(gen_->host_image(), src, n, ranks_[0]->ctx.stream());
}
for (auto& rk : ranks_)
if (st >= 0) st = rad_stream_sync(rk->ctx.stream());
if (st < 0) {
RAD_ERR("generator pass %d: the device failed: %s", step, rad_strerror(st));
gen_->shutdown("the engine stopped on an error and is not serving", st);
return fail_loop(st);
}
if ((int)log_level() >= (int)Log::Trace)
dump_buffers(ranks_[0]->ctx, step, std::getenv("RADIANCE_DUMP_BUF"));
gen_->done();
++step;
}
return RAD_OK;
}
} /* namespace rad */
+87 -61
View File
@@ -11,6 +11,9 @@
* inside one; the processor has already kept every segment within a pass. Several items share a
* pass when they fit, which is what a request with a handful of small pictures wants.
*
* AN AUDIO CLIP IS ONE SEGMENT OF THE AUDIO ENCODER, whose passes are separate from the vision
* tower's: a program declares one of each at most, and an item goes to the one its kind names.
*
* EVERY RANK RUNS THE WHOLE TOWER on its own card from its own copy of the patches. The rows are
* needed on every rank anyway -- each rank embeds every token -- and running it everywhere costs the
* encoder's compute once per card instead of a transfer of its output between them.
@@ -29,16 +32,6 @@ int Engine::run_encodes() {
sched_.take_encodes(&items);
if (items.empty()) return RAD_OK;
const RadEncoderDecl& enc = ranks_[0]->program.encoder;
const int64_t max_p = sched_.encoder_patches();
const int64_t n_embd = enc.n_embd;
Rank& r0 = *ranks_[0];
void* out = r0.ctx.buf_ptr(enc.out);
if (!out) {
RAD_ERR("encoder '%s': its output buffer was declared but never planned",
ranks_[0]->program.encoder_name.c_str());
return RAD_E_STATE;
}
/* A DIAGNOSTIC: RADIANCE_DEBUG_MM_DUMP=<dir> writes each item's patches (`.pix.bf16`, the
* processor's output in merge-block order) and its rows (`.bf16`) there as raw bf16, named by
* its content key -- the tower's input and output, for comparison against a reference encoder
@@ -56,65 +49,98 @@ int Engine::run_encodes() {
}
};
Rank& r0 = *ranks_[0];
const Program& prog = r0.program;
for (auto& ip : items) {
if (ip->encoded) continue;
ip->embd.assign((size_t)(ip->n_rows() * n_embd), 0);
const RadEncoderDecl& e = ip->kind == mm::Kind::Audio ? prog.audio_encoder : prog.encoder;
ip->embd.assign((size_t)(ip->n_rows() * e.n_embd), 0);
if (dump_dir && *dump_dir) dump(*ip, ".pix.bf16", ip->pixels.data(), ip->pixels.size());
}
size_t i = 0;
int32_t seg = 0;
while (i < items.size()) {
std::vector<BatchBuilder::EncoderPart> parts;
int64_t np = 0;
while (i < items.size()) {
mm::Item& it = *items[i];
if (it.encoded) { ++i; seg = 0; continue; }
const int64_t seg_p = (int64_t)it.grid_h * it.grid_w;
if (seg_p > max_p) {
RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld",
(long long)seg_p, (long long)max_p);
/* THE PASSES, ENCODER BY ENCODER: an audio clip goes through the audio encoder and a picture
* or a video through the other, each with its own pass size and output buffer. */
for (int which = 0; which < 2; ++which) {
const bool audio = which == 1;
const RadEncoderDecl& enc = audio ? prog.audio_encoder : prog.encoder;
const std::string& enc_name = audio ? prog.audio_encoder_name : prog.encoder_name;
std::vector<mm::Item*> mine;
for (auto& ip : items)
if (!ip->encoded && (ip->kind == mm::Kind::Audio) == audio) mine.push_back(ip.get());
if (mine.empty()) continue;
if (enc.modalities == 0) {
RAD_ERR("encoder: a %s item reached the encoder and this program declares no %s "
"encoder", audio ? "audio" : "picture", audio ? "audio" : "image");
return RAD_E_STATE;
}
const int64_t max_p = enc.max_patches;
const int64_t n_embd = enc.n_embd;
size_t i = 0;
int32_t seg = 0;
while (i < mine.size()) {
std::vector<BatchBuilder::EncoderPart> parts;
int64_t np = 0;
while (i < mine.size()) {
mm::Item& it = *mine[i];
const int32_t first = seg;
for (; seg < it.n_seg; ++seg) {
const int64_t seg_p = it.patch_at(seg + 1) - it.patch_at(seg);
if (seg_p > max_p) {
RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld",
(long long)seg_p, (long long)max_p);
return RAD_E_STATE;
}
if (np + seg_p > max_p) break;
np += seg_p;
}
if (seg == first) break;
parts.push_back({ &it, first, seg - first });
if (seg == it.n_seg) { ++i; seg = 0; }
}
if (parts.empty()) break;
const RadBatch* b = sched_.build_encoder(parts, enc_step_++, enc);
if (!b) return RAD_E_STATE;
RAD_TRY(prepare_release(b));
/* THE OUTPUT'S ADDRESS IS THE PASS'S LEVEL'S, read after prepare_release: a pass runs
* at the arena's full plan (Engine::arena_step), and a buffer sits at another offset
* in every level. An address taken at the level the last step left would read some
* other buffer, or memory lent to the expert slab, in place of the rows. */
void* out = r0.ctx.buf_ptr(enc.out);
if (!out) {
RAD_ERR("encoder '%s': its output buffer was declared but never planned",
enc_name.c_str());
return RAD_E_STATE;
}
const int64_t room = (max_p - np) / seg_p;
const int32_t can = (int32_t)std::min<int64_t>(it.n_seg - seg, room);
if (can <= 0) break;
parts.push_back({ &it, seg, can });
np += (int64_t)can * seg_p;
seg += can;
if (seg == it.n_seg) { ++i; seg = 0; }
/* kIssueModel: the pass and nothing behind it -- no sampler, and no tiering tick,
* which belongs to steps. */
issue_what_.store(kIssueModel, std::memory_order_release);
step_batch_.store(b, std::memory_order_release);
barrier_->arrive_and_wait();
barrier_->arrive_and_wait();
const int st = step_status_.load(std::memory_order_acquire);
if (st < 0) {
RAD_ERR("encoder pass failed: %s -- the engine cannot continue", rad_strerror(st));
return st;
}
/* The rows, in pass order: each part's segments are consecutive rows of its item. */
int64_t row = 0;
for (const BatchBuilder::EncoderPart& p : parts) {
mm::Item& it = *const_cast<mm::Item*>(p.item);
const int64_t first = it.row_at(p.seg0);
const int64_t rows = it.row_at(p.seg0 + p.n_seg) - first;
const int64_t bytes = rows * n_embd * (int64_t)sizeof(uint16_t);
RAD_TRY(rad_memcpy_async(it.embd.data() + first * n_embd,
static_cast<const char*>(out) +
row * n_embd * (int64_t)sizeof(uint16_t),
bytes, r0.ctx.stream()));
row += rows;
}
/* Every rank's stream, not only rank 0's: the next pass rewrites the staging every
* rank's copy reads, and the arena every rank's tower wrote. */
for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream()));
}
if (parts.empty()) break;
const RadBatch* b = sched_.build_encoder(parts, enc_step_++);
if (!b) return RAD_E_STATE;
RAD_TRY(prepare_release(b));
/* kIssueModel: the pass and nothing behind it -- no sampler, and no tiering tick, which
* belongs to steps. */
issue_what_.store(kIssueModel, std::memory_order_release);
step_batch_.store(b, std::memory_order_release);
barrier_->arrive_and_wait();
barrier_->arrive_and_wait();
const int st = step_status_.load(std::memory_order_acquire);
if (st < 0) {
RAD_ERR("encoder pass failed: %s -- the engine cannot continue", rad_strerror(st));
return st;
}
/* The rows, in pass order: each part's segments are consecutive rows of its item. */
int64_t row = 0;
for (const BatchBuilder::EncoderPart& p : parts) {
mm::Item& it = *const_cast<mm::Item*>(p.item);
const int64_t rows = (int64_t)p.n_seg * it.seg_rows;
const int64_t bytes = rows * n_embd * (int64_t)sizeof(uint16_t);
RAD_TRY(rad_memcpy_async(it.embd.data() + (int64_t)p.seg0 * it.seg_rows * n_embd,
static_cast<const char*>(out) +
row * n_embd * (int64_t)sizeof(uint16_t),
bytes, r0.ctx.stream()));
row += rows;
}
/* Every rank's stream, not only rank 0's: the next pass rewrites the staging every rank's
* copy reads, and the arena every rank's tower wrote. */
for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream()));
}
for (auto& ip : items) {
+10 -10
View File
@@ -17,7 +17,6 @@
#include "mem/kv.h"
#include "mem/prefix.h"
#include "mem/kvtier.h"
#include "mem/sstier.h"
#include "runtime/tierexec.h"
#include "build/rad_build.h"
#include "place/heat.h"
@@ -58,15 +57,16 @@ struct Engine::Rank {
* Without the split, a placement engine starved of evidence reads exactly like a model whose
* layers are idle. */
uint64_t heat_credited = 0, heat_idle = 0;
/* Trunk steps in a row whose pass the prefill stager did not arm (Engine::tiering_dispatch). */
int unstaged_steps = 0;
Residency residency;
KVManager kv;
PrefixCache prefix;
/* THE IDLE SESSION TIERS (spec 7.3). Rank 0 owns the policy and the session index,
* because they describe CONVERSATIONS and a conversation is not sharded -- but the
* transfer is per rank, since each rank holds its own shard of every KV block and
* has its own pool to gather out of. The disk store is rank 0's alone for the same
* reason the policy is: one store, keyed by a hash of tokens every rank agrees on.
* Both are inert unless the operator gave a tier a size. */
* has its own pool to gather out of. Both are inert unless --prefix-cache-mib gave the
* host tier a size. */
IdleTiers tiers;
TierExec tierx;
/* The activation arena's smaller levels, smallest step first (Engine::probe_arena_levels). */
@@ -84,6 +84,10 @@ struct Engine::Rank {
StagerChain stagers;
Ctx ctx;
Sampler sampler; /* one per rank: each samples its own vocab shard (spec §9) */
/* THE SCORED ROWS' LOGITS (Request::token_scores), this rank's vocabulary shard of each,
* copied into pinned memory ahead of the sampler. Grown to the most rows a step has scored. */
float* score_host = nullptr;
int64_t score_rows_cap = 0;
rad_buf tok_buf = 0; /* where the chain writes the sampled ids */
/* THE CARD'S STEP STATE (sched/advance.h): one StepSlot a scheduler slot, and the
* end-of-generation ids acceptance stops at, sorted. Every rank keeps its own and computes the
@@ -95,16 +99,12 @@ struct Engine::Rank {
/* THE TIERS' WORK IN FLIGHT (Engine::tier_tick). One copy batch out on every rank's transfer
* stream at a time, with each rank's answer kept until all of them have one -- a rank that has
* landed must not be asked again and forget it failed -- and one disk batch out on the IO thread. */
* landed must not be asked again and forget it failed. */
struct TierPump {
std::vector<TierJob> copy;
std::vector<int> copy_st; /* per rank: 0 in flight, 1 landed, negative failed */
TierIO io;
int64_t max_copy = 0;
int slow_budget = 0;
/* The requests a read off disk is out for (IdleTiers::plan_fetch). Asked again while their
* read is out, they wait without walking their prompt; the read's collection lets them go. */
std::vector<uint64_t> waiting;
int slow_budget = 0; /* capacity drops one plan may make */
};
/* THE BUFFER PROBE (engine_probe.cpp). Declared here because three files call it: the step
+6 -5
View File
@@ -114,9 +114,10 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
* WHY THAT IS ENOUGH FOR A KL DIVERGENCE, with no log-sum-exp anywhere. Renormalised over a
* fixed candidate set S, p~_i = exp(l_i) / sum_{j in S} exp(l_j) -- the partition function
* over the WHOLE vocabulary cancels, in both engines independently. So a top-K KLD against
* another engine's top-K logprobs needs only these logits. An OpenAI `logprobs` FIELD would
* need the normaliser, and `supports_logprobs` is false; this is a probe, and it says so by
* being an environment variable at -vv rather than a response field. */
* another engine's top-K logprobs needs only these logits. The OpenAI `logprobs` field carries
* the normaliser (sample_logprobs) and only the RAW distribution's top 20; this reads the
* plane the pick drew from, which is a probe, and it says so by being an environment variable
* at -vv rather than a response field. */
static const int head = [] {
const char* s = std::getenv("RADIANCE_DUMP_HEAD");
const long v = (s && *s) ? std::strtol(s, nullptr, 10) : 0;
@@ -156,8 +157,8 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
* writing different code -- so the question a LOSSY LEVER asks ("how much worse, if at all")
* needs an instrument of its own.
*
* WHY THIS SHAPE AND NOT A PERPLEXITY. The server returns no logprobs (`supports_logprobs` is
* never set, so it refuses them) and a served prefill produces logits only at the rows
* WHY THIS SHAPE AND NOT A PERPLEXITY. The server's logprobs are the generated positions'
* only -- never the prompt's -- and a served prefill produces logits only at the rows
* `out_ids` names; the teacher-forced scoring pass is the KL mode's (core/kld.h), which runs in
* place of the server. What a serving engine offers: send N distinct prompts at max_tokens = 1,
* and every build under comparison sees IDENTICAL inputs at one row each. The top of that row,
+639 -36
View File
@@ -5,6 +5,7 @@
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <fstream>
@@ -76,6 +77,7 @@ static void flatten_json(const nlohmann::json& j, const std::string& prefix, Met
if (e.is_number_integer()) s += fmt("%lld", (long long)e.get<int64_t>());
else if (e.is_number()) s += fmt("%.17g", e.get<double>());
else if (e.is_string()) s += e.get<std::string>();
else if (e.is_boolean()) s += e.get<bool>() ? "1" : "0";
else { ok = false; break; }
}
if (ok) out->kv(key, s);
@@ -148,9 +150,15 @@ int meta_merge_generation_config(const std::string& dir, MetaOwn* out) {
* `size.shortest_edge` means two different things in the two files. Absent is not an error: a
* text model has neither. */
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out) {
/* processor_config.json is the newer single file: one object a sub-processor
* (`image_processor`, `video_processor`, `feature_extractor`) beside the processor's own keys
* -- EmbeddingGemma 2's image budget and its audio token rate are only there. */
static const struct { const char* file; const char* prefix; } kFiles[] = {
{ "preprocessor_config.json", "preprocessor" },
{ "video_preprocessor_config.json", "video_preprocessor" },
{ "processor_config.json", "processor" },
/* sentence-transformers' own: an embedding model's named prompts and its default. */
{ "config_sentence_transformers.json", "sentence_transformers" },
};
for (const auto& f : kFiles) {
const std::string path = dir + "/" + f.file;
@@ -228,6 +236,10 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
if (const char* mt = gs("model_type")) {
out->arch.clear();
for (const char* p = mt; *p; ++p) if (*p != '_') out->arch += *p;
/* LFM2-VL is LFM2 with a vision tower, and unlike Qwen's VL releases it names the wrapper
* rather than the text model. One plugin serves both, the way one serves a Qwen3.5 with
* or without its tower; `model_type` itself stays in the free-form keys. */
if (out->arch == "lfm2vl") out->arch = "lfm2";
}
if (const char* nm = gs("_name_or_path")) out->name = nm;
@@ -251,25 +263,30 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
m.n_expert = gi("num_experts", gi("num_local_experts", 0));
m.n_expert_used = gi("num_experts_per_tok", 0);
m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
m.rms_eps = (float)gf("rms_norm_eps", 1e-6);
m.rms_eps = (float)gf("rms_norm_eps", gf("norm_eps", 1e-6)); /* LFM2: norm_eps */
m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
/* The rotary's scaling stays in the free-form keys with its type beside it; the architecture
* reads both (arch/common/rad_arch.h, yarn_from). A factor copied here without its type would
* be a linear position divide for llama3, longrope or YaRN. */
m.rope_scale = 1.0f;
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
* rather than by a flag. */
if (const char* qm = gs("quantization_config.quant_method")) {
out->quant = qm;
if (const char* fm = gs("quantization_config.fmt")) { out->quant += "_"; out->quant += fm; }
}
out->quant = quant_descriptor(*out);
out->finish();
return RAD_OK;
}
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
* rather than by a flag. */
std::string quant_descriptor(const MetaOwn& m) {
std::string q;
if (const char* qm = m.get("quantization_config.quant_method")) {
q = qm;
if (const char* fm = m.get("quantization_config.fmt")) { q += "_"; q += fm; }
}
return q;
}
int meta_from_gguf(GgufFile& g, MetaOwn* out) {
if (!g.get_str("general.architecture", &out->arch)) {
RAD_ERR("the GGUF has no general.architecture, so no architecture plugin can be chosen");
@@ -408,10 +425,24 @@ int Checkpoint::open_gguf(const std::string& path) {
return meta_from_gguf(gguf_, &meta_);
}
int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
int Checkpoint::add_shard(const std::string& p, const std::string& prefix,
const std::unordered_map<std::string, std::string>* owner) {
shards_.push_back(std::make_unique<SafeTensorsFile>());
RAD_TRY(shards_.back()->open(p));
const std::string file = p.substr(p.find_last_of('/') + 1);
for (const auto& t : shards_.back()->tensors()) {
/* THE INDEX SAYS WHICH SHARD A TENSOR IS READ FROM. A directory that merges two
* checkpoints -- a finetune's changed tensors in its own shards beside links to the base
* model's -- holds some names in two shards, and only the index tells the copies apart. */
if (owner) {
auto it = owner->find(t.name);
if (it != owner->end() && it->second != file) continue;
}
if (index_.count(prefix + t.name)) {
RAD_ERR("%s: '%s' is also in %s, and no index entry says which copy to read", p.c_str(),
t.name.c_str(), shards_[index_shard_[prefix + t.name]]->path().c_str());
return RAD_E_FORMAT;
}
if (t.dtype == RAD_DT_INVALID) {
RAD_ERR("%s: '%s' has dtype %s, which has no RAD equivalent", p.c_str(),
t.name.c_str(), t.dtype_str.c_str());
@@ -423,6 +454,7 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
s.shape = t.shape; /* safetensors is already row-major */
s.data = t.data;
s.bytes = (int64_t)t.bytes;
index_shard_.emplace(s.name, shards_.size() - 1);
index_.emplace(s.name, tensors_.size());
tensors_.push_back(std::move(s));
}
@@ -431,13 +463,13 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
namespace {
/* Every shard an index names, once each and in name order, or the one model.safetensors. */
/* 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,
std::vector<std::string>* out) {
std::unordered_map<std::string, std::string> map;
const int s = st_load_index(index, &map);
std::vector<std::string>* out, std::unordered_map<std::string, std::string>* map) {
const int s = st_load_index(index, map);
if (s == RAD_OK) {
for (auto& [t, f] : map)
for (auto& [t, f] : *map)
if (std::find(out->begin(), out->end(), f) == out->end()) out->push_back(f);
std::sort(out->begin(), out->end());
for (auto& f : *out) f = dir + "/" + f;
@@ -450,20 +482,113 @@ 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) {
std::ifstream f(path);
if (!f) {
if (optional) return RAD_OK;
RAD_ERR("%s: cannot read it", path.c_str());
return RAD_E_NOTFOUND;
}
nlohmann::json j;
try { f >> j; }
catch (const std::exception& e) { RAD_ERR("%s: %s", path.c_str(), e.what()); return RAD_E_FORMAT; }
if (!j.is_object()) {
RAD_ERR("%s: not a JSON object", path.c_str());
return RAD_E_FORMAT;
}
flatten_json(j, prefix, out);
return RAD_OK;
}
static bool path_exists(const std::string& p) { std::ifstream f(p); return (bool)f; }
/* A DIFFUSERS PIPELINE: model_index.json at the top and one folder a component, each with its own
* config and weights. It is read as ONE checkpoint, because the components are one model to the
* architecture plugin that serves them:
*
* text_encoder/ its config.json is the container's model config -- the typed dimensions and
* the bare keys -- and its tensors keep their names;
* transformer/ tensors under `transformer.`, config.json under `transformer.` keys;
* vae/ tensors under `vae.`, config.json under `vae.` keys;
* scheduler/ scheduler_config.json under `scheduler.` keys;
* processor/ (or tokenizer/) the tokenizer, the chat template and the preprocessor configs.
*
* model_index.json itself goes under `pipeline.` keys, and its `_class_name` names the
* architecture: `QwenImage21Pipeline` is `qwenimage21`. A component folder may be a link to
* another pipeline's (a distilled release sharing its base's text encoder). */
int Checkpoint::open_diffusers() {
kind_ = SafeT;
RAD_TRY(meta_merge_json_file(dir_ + "/model_index.json", "pipeline", false, &meta_));
const std::string te = dir_ + "/text_encoder";
if (path_exists(te + "/config.json")) {
std::vector<std::string> shards;
std::unordered_map<std::string, std::string> owner;
RAD_TRY(shard_list(te, te + "/model.safetensors.index.json", false, &shards, &owner));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner));
RAD_TRY(meta_from_config_json(te, &meta_));
RAD_TRY(meta_merge_generation_config(te, &meta_));
}
for (const char* comp : { "transformer", "vae" }) {
const std::string d = dir_ + "/" + comp;
if (!path_exists(d + "/config.json")) continue;
const std::string idx = d + "/diffusion_pytorch_model.safetensors.index.json";
std::vector<std::string> shards;
std::unordered_map<std::string, std::string> owner;
if (path_exists(idx)) {
RAD_TRY(shard_list(d, idx, true, &shards, &owner));
} else {
shards.push_back(d + "/diffusion_pytorch_model.safetensors");
}
for (const auto& sh : shards)
RAD_TRY(add_shard(sh, std::string(comp) + ".", owner.empty() ? nullptr : &owner));
RAD_TRY(meta_merge_json_file(d + "/config.json", comp, false, &meta_));
}
RAD_TRY(meta_merge_json_file(dir_ + "/scheduler/scheduler_config.json", "scheduler", true,
&meta_));
for (const char* sub : { "processor", "tokenizer" }) {
const std::string d = dir_ + "/" + sub;
if (!path_exists(d + "/tokenizer.json")) continue;
tok_dir_ = d;
RAD_TRY(meta_merge_preprocessor_configs(d, &meta_));
break;
}
/* The architecture is the pipeline's, whatever the text encoder calls itself. */
if (const char* cn = meta_.get("pipeline._class_name")) {
std::string a = cn;
const std::string suf = "Pipeline";
if (a.size() > suf.size() && a.compare(a.size() - suf.size(), suf.size(), suf) == 0)
a.resize(a.size() - suf.size());
for (char& ch : a) ch = (char)std::tolower((unsigned char)ch);
meta_.arch = a;
}
if (tensors_.empty()) {
RAD_ERR("%s: a diffusers pipeline with no component weights", dir_.c_str());
return RAD_E_NOTFOUND;
}
meta_.finish();
return RAD_OK;
}
int Checkpoint::open_safetensors(const std::string& path) {
kind_ = SafeT;
/* One shard, an index, or the directory holding either: one namespace whichever it is. */
std::vector<std::string> shards;
std::unordered_map<std::string, std::string> owner;
const bool is_index = path.size() > 10 && path.compare(path.size() - 10, 10, "index.json") == 0;
const bool is_file = path.size() > 12 &&
path.compare(path.size() - 12, 12, ".safetensors") == 0;
if (!is_file && !is_index && path_exists(dir_ + "/model_index.json") &&
!path_exists(dir_ + "/config.json"))
return open_diffusers();
if (is_file) {
shards.push_back(path);
} else {
RAD_TRY(shard_list(dir_, is_index ? path : dir_ + "/model.safetensors.index.json",
is_index, &shards));
is_index, &shards, &owner));
}
for (const auto& sh : shards) RAD_TRY(add_shard(sh));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner));
RAD_TRY(meta_from_config_json(dir_, &meta_));
RAD_TRY(meta_merge_generation_config(dir_, &meta_));
@@ -516,6 +641,64 @@ void Checkpoint::detect_import() {
else
import_why_ = "Quark's weight scheme here is not MXFP4 (fp4, per_group 32, e8m0 scales) "
"throughout, which is the one this reads";
} else if (qm == "compressed-tensors") {
/* COMPRESSED-TENSORS' PACK-QUANTIZED INT4, symmetric and grouped -- Google's Gemma 4 QAT
* release (w4a16-ct) is one. Every config group must say so: a zero point, act-order, a
* dynamic or activation scheme would each change what a code means. */
std::vector<std::string> groups;
const std::string cg = "quantization_config.config_groups.";
for (const std::string& k : meta_.keys)
if (k.rfind(cg, 0) == 0) {
const std::string g = k.substr(cg.size(), k.find('.', cg.size()) - cg.size());
if (std::find(groups.begin(), groups.end(), g) == groups.end()) groups.push_back(g);
}
std::string why;
int64_t group = 0;
if (qc("format") != "pack-quantized")
why = "its format is '" + qc("format") + "', and pack-quantized is the one this reads";
if (groups.empty() && why.empty()) why = "its quantization_config names no config group";
for (const std::string& g : groups) {
if (!why.empty()) break;
const std::string w = "config_groups." + g + ".weights.";
const std::string gs = qc(w + "group_size");
const long long gn = gs.empty() ? 0 : std::atoll(gs.c_str());
if (qc("config_groups." + g + ".format") != "pack-quantized" ||
qc(w + "num_bits") != "4" || qc(w + "type") != "int" || qc(w + "symmetric") != "1" ||
qc(w + "strategy") != "group" || qc(w + "dynamic") != "0" || gn <= 0 ||
!qc(w + "actorder").empty() || any_under("config_groups." + g + ".input_activations."))
why = "config group '" + g + "' is not symmetric 4-bit int weights in groups, packed, "
"with no act-order and unquantised activations, which is the one this reads";
else if (group && gn != group)
why = "its config groups state different group sizes";
else
group = gn;
}
if (why.empty()) {
import_ = Import::CtInt4;
ct_group_ = group;
} else {
import_why_ = "compressed-tensors: " + why;
}
} else if (qm == "paroquant") {
/* z-lab's ParoQuant at integer widths, in the "int5-bitplane" packing: AWQ nibbles of the
* low four bits plus a bit plane for the fifth, group 128, asymmetric, with the learned
* rotations beside. Other widths and packings are not read. */
if (qc("format") == "int5-bitplane" && qc("bits") == "5" && qc("group_size") == "128")
import_ = Import::ParoI5;
else if (qc("format").empty() && qc("bits") == "4" && qc("group_size") == "128")
import_ = Import::ParoI4; /* z-lab's own release: AWQ-packed int4, asymmetric */
else
import_why_ = "ParoQuant here is neither the int5-bitplane format (5-bit codes) nor z-lab's "
"AWQ-packed int4, in groups of 128, which are the ones this reads";
} else if (qm == "paroquant_mxfp4") {
/* QUARK'S MXFP4 PLANES IN A ROTATED BASIS: e2m1 codes, an e8m0 exponent a 32 of K, and per
* projection the learned Givens rotations (`pairs`, `theta`) and channel scales in groups
* of 128 -- z-lab's ParoQuant, retrained for the MXFP4 grid. */
if (qc("format") == "mxfp4" && qc("mxfp4_block") == "32" && qc("group_size") == "128")
import_ = Import::ParoMx;
else
import_why_ = "ParoQuant's MXFP4 here is not format mxfp4 with 32-element blocks and "
"rotation groups of 128, which is the one this reads";
}
/* THE TOOL'S DESCRIPTION IS KEPT, UNDER ANOTHER NAME. A plugin reads quantization_config as
* the statement of the format it serves (qwen35_fp8 checks quant_method is "fp8"), and an
@@ -539,7 +722,51 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
return RAD_OK;
}
if (import_ == Import::QuarkMx) {
if (import_ == Import::ParoI5 || import_ == Import::ParoI4) {
const bool i5 = import_ == Import::ParoI5;
/* PARO int5: `X.weight` is X.qweight/.qweight_hi (codes), X.scales (f16 [G, N]) and
* X.qzeros/.qzeros_hi (zero points). The view carries the logical [N, K] u5 matrix; the
* planes are re-laid row by row by ckpt_plane_rows. */
const std::string suffix = ".weight";
if (name.size() <= suffix.size() ||
name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
return RAD_E_NOTFOUND;
const std::string base = name.substr(0, name.size() - suffix.size());
const SrcTensor* qw = find(base + ".qweight");
if (!qw) return RAD_E_NOTFOUND;
const SrcTensor* hi = i5 ? find(base + ".qweight_hi") : nullptr;
const SrcTensor* sc = find(base + ".scales");
const SrcTensor* qz = find(base + ".qzeros");
const SrcTensor* qzh = i5 ? find(base + ".qzeros_hi") : nullptr;
if ((i5 && (!hi || !qzh)) || !sc || !qz || qw->rad_dtype != RAD_I32 ||
qz->rad_dtype != RAD_I32 || sc->rad_dtype != RAD_F16 || qw->shape.size() != 2 ||
qz->shape.size() != 2 || sc->shape.size() != 2 ||
(i5 && (hi->rad_dtype != RAD_I32 || qzh->rad_dtype != RAD_I32 ||
hi->shape.size() != 2 || qzh->shape.size() != 2)))
return refuse(RAD_E_FORMAT, "'" + qw->name + "' lacks an int32 " +
(i5 ? "qweight_hi, qzeros_hi, " : "") +
"qzeros and an f16 scales beside it");
const int64_t K = qw->shape[0], N = qw->shape[1] * 8, G = sc->shape[0];
if (N % 32 || K % 128 || G * 128 != K || sc->shape[1] != N || qz->shape[0] != G ||
qz->shape[1] != N / 8 ||
(i5 && (hi->shape[0] != K || hi->shape[1] != N / 32 || qzh->shape[0] != G ||
qzh->shape[1] != N / 32)))
return refuse(RAD_E_SHAPE, "'" + qw->name + "' planes do not fit a [" +
std::to_string(N) + ", " + std::to_string(K) + "] weight");
SrcTensor c = *qw;
c.name = name;
c.rad_dtype = i5 ? RAD_U5 : RAD_U4;
c.shape = { N, K };
c.pbits = i5 ? 5 : 4;
c.aux[0] = hi; c.aux[1] = qz; c.aux[2] = qzh;
sliced_.push_back(std::move(c));
*codes = &sliced_.back();
*scale = sc;
imported_[name] = { *codes, *scale };
return RAD_OK;
}
if (import_ == Import::QuarkMx || import_ == Import::ParoMx) {
/* QUARK'S MXFP4 IS THE ENCODING AS IT STANDS: two codes a byte, element 2j in the low
* nibble, and one biased exponent a 32 of K -- `fp4_e2m1*e8m0[1x32]`. A view renames the
* dtypes and the logical width; no byte moves. Its excluded layers are plain tensors. */
@@ -563,6 +790,53 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
return RAD_OK;
}
if (import_ == Import::CtInt4) {
/* CT-INT4: `X.weight` is shipped as X.weight_packed (i32 [N, K/8], eight codes a word from
* the low bits, unsigned about 8) and X.weight_scale ([N, K/group]). The words are the
* logical [N, K] code matrix in row order already; only the offset is left for the
* relayout. A layer the config ignores is an ordinary X.weight. */
const std::string suffix = ".weight";
if (name.size() <= suffix.size() ||
name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
return RAD_E_NOTFOUND;
const SrcTensor* pk = find(name + "_packed");
if (!pk) return RAD_E_NOTFOUND;
const SrcTensor* sc = find(name + "_scale");
const std::string what = "'" + pk->name + "'";
if (pk->rad_dtype != RAD_I32 || pk->shape.size() != 2)
return refuse(RAD_E_FORMAT, what + " is not an int32 [N, K/8] matrix");
if (find(name + "_zero_point"))
return refuse(RAD_E_UNSUPPORTED, what + " has a zero point beside it, which a symmetric "
"config does not; an asymmetric weight is not read");
const int64_t N = pk->shape[0], K = pk->shape[1] * 8;
if (K % ct_group_)
return refuse(RAD_E_SHAPE, what + " has " + std::to_string(K) + " columns, not whole "
"groups of " + std::to_string(ct_group_));
if (!sc || sc->shape.size() != 2 || sc->shape[0] != N || sc->shape[1] != K / ct_group_ ||
(sc->rad_dtype != RAD_F16 && sc->rad_dtype != RAD_BF16 && sc->rad_dtype != RAD_F32))
return refuse(RAD_E_FORMAT, what + " has no float [" + std::to_string(N) + ", " +
std::to_string(K / ct_group_) + "] '" + name +
"_scale' beside it");
if (const SrcTensor* ws = find(name + "_shape")) {
int64_t dims[2] = { 0, 0 };
for (int i = 0; i < 2 && i < (int)ws->numel(); ++i)
dims[i] = (int64_t)rad_load_f32(ws->data, ws->rad_dtype, i);
if (ws->numel() != 2 || dims[0] != N || dims[1] != K)
return refuse(RAD_E_SHAPE, "'" + ws->name + "' does not state the [" +
std::to_string(N) + ", " + std::to_string(K) +
"] its codes hold");
}
SrcTensor c = *pk;
c.rad_dtype = RAD_I4;
c.shape = { N, K };
c.ct_group = ct_group_;
sliced_.push_back(std::move(c));
*codes = &sliced_.back();
*scale = sc;
imported_[name] = { *codes, *scale };
return RAD_OK;
}
/* GPTQ-PACKED: `X.weight` is shipped as X.qweight, X.scales, X.qzeros and, optionally,
* X.g_idx. The width is read off the tensors rather than quantization_config, because a
* release may mix widths -- int4 experts beside int8 projections -- and say so only per layer. */
@@ -663,8 +937,9 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
? prefix
: prefix.substr(0, prefix.size() - 1), &meta_));
std::vector<std::string> shards;
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix));
std::unordered_map<std::string, std::string> owner;
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards, &owner));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix, owner.empty() ? nullptr : &owner));
meta_.finish();
return RAD_OK;
}
@@ -733,7 +1008,7 @@ std::string ckpt_tensor_of(const SrcTensor& t) {
bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>& names,
std::unordered_set<std::string>* hit) {
bool any = false;
for (const auto* list : { &w.pieces, &w.scales })
for (const auto* list : { &w.pieces, &w.scales, &w.pq_pairs, &w.pq_theta, &w.pq_scale })
for (const SrcTensor* t : *list) {
if (!t) continue;
const std::string n = ckpt_tensor_of(*t);
@@ -745,6 +1020,121 @@ bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>&
return any;
}
namespace {
/* The ROTATION GROUP of a ParoQuant checkpoint: pairs address columns within a group of 128. */
constexpr int64_t kParoGroup = 128;
/* "model.layers.0.mlp.down_proj.weight" -> "model.layers.0.mlp.down_proj" */
std::string paro_base(const SrcTensor& piece) {
std::string n = ckpt_tensor_of(piece);
const std::string suffix = ".weight";
return n.size() > suffix.size() && n.compare(n.size() - suffix.size(), suffix.size(), suffix) == 0
? n.substr(0, n.size() - suffix.size()) : n;
}
} /* namespace */
/* ONE (PART, GROUP)'S STAGES COMPOSED INTO ITS DENSE MATRIX: out[j * 128 + i] is output j of the
* stages fed the unit vector e_i, applied in table order (stage 0 first) as a' = a cos t + b sin t,
* b' = b cos t - a sin t -- libref's loop. In f64 throughout (the f32 angles widened, cos, sin and
* every product in double), so the error (~1e-15) is far below an f16 step and the bytes are the
* exact composition rounded to f16 by way of f32, whichever libm or summation order computed it. */
void paro_compose_dense(int64_t S, const int32_t* ia, const int32_t* ib, const float* th,
uint16_t* out) {
constexpr int64_t G = kParoGroup, H = kParoGroup / 2;
std::vector<double> cs((size_t)(S * H)), sn((size_t)(S * H)), v((size_t)G);
for (int64_t o = 0; o < S * H; ++o) {
cs[(size_t)o] = std::cos((double)th[o]);
sn[(size_t)o] = std::sin((double)th[o]);
}
for (int64_t i = 0; i < G; ++i) {
std::fill(v.begin(), v.end(), 0.0);
v[(size_t)i] = 1.0;
for (int64_t o = 0; o < S * H; ++o) {
const double va = v[(size_t)ia[o]], vb = v[(size_t)ib[o]];
v[(size_t)ia[o]] = va * cs[(size_t)o] + vb * sn[(size_t)o];
v[(size_t)ib[o]] = vb * cs[(size_t)o] - va * sn[(size_t)o];
}
for (int64_t j = 0; j < G; ++j) out[j * G + i] = rad_f32_to_f16((float)v[(size_t)j]);
}
}
namespace {
/* PARTS: EACH PIECE OF A ROTATED WEIGHT HAS ITS OWN ROTATION. A fused gate_up or q|k|v is several
* checkpoint projections, each learned with its own pairs, angles and channel scales, so the
* fused weight is one row PART per piece (abi/rad_encoding.h, "givens"). Gives the encoding its
* four tables -- t.pairs and t.angle stage-major per part, t.scale a row per part, t.part the end
* row of each -- and refuses a rotation that is not what the kernels read: a pair that leaves its
* group of 128, or a stage that does not use every column of a group exactly once. */
int paro_attach(Checkpoint& ck, CkptWeight* out, std::string* why) {
auto refuse = [&](std::string m) {
if (why) *why = std::move(m);
return (int)RAD_E_FORMAT;
};
const int64_t K = out->cols, P = (int64_t)out->pieces.size();
if (K % kParoGroup) return refuse("'" + out->name + "' has " + std::to_string(K) +
" columns, which is not whole rotation groups of 128");
int64_t S = 0;
out->pq_pairs.clear(); out->pq_theta.clear(); out->pq_scale.clear();
for (const SrcTensor* piece : out->pieces) {
const std::string base = paro_base(*piece);
const SrcTensor* pr = ck.find(base + ".pairs");
const SrcTensor* th = ck.find(base + ".theta");
const SrcTensor* cs = ck.find(base + ".channel_scales");
if (!pr || !th || !cs)
return refuse("'" + piece->name + "' is a ParoQuant MXFP4 weight and '" + base +
"' lacks its pairs, theta or channel_scales");
if (pr->rad_dtype != RAD_I16 || th->rad_dtype != RAD_F16 || cs->rad_dtype != RAD_F16 ||
pr->shape.size() != 2 || th->shape.size() != 2 || cs->shape.size() != 2 ||
pr->shape[1] != K || th->shape[0] != pr->shape[0] || th->shape[1] != K / 2 ||
cs->shape[0] != 1 || cs->shape[1] != K || pr->shape[0] < 1)
return refuse("'" + base + "' pairs/theta/channel_scales do not fit a " +
std::to_string(K) + "-column weight (int16 [S, K], f16 [S, K/2], f16 [1, K])");
if (S == 0) S = pr->shape[0];
if (pr->shape[0] != S)
return refuse("the pieces of '" + out->name + "' have different numbers of rotation stages");
/* every stage is a perfect matching of each group's 128 columns */
const int16_t* pv = (const int16_t*)pr->data;
for (int64_t st = 0; st < S; ++st)
for (int64_t g = 0; g < K / kParoGroup; ++g) {
bool seen[kParoGroup] = {};
for (int64_t i = 0; i < kParoGroup; ++i) {
const int v = pv[st * K + g * kParoGroup + i];
if (v < 0 || v >= kParoGroup || seen[v])
return refuse("'" + pr->name + "' stage " + std::to_string(st) + " group " +
std::to_string(g) + " is not a pairing of its 128 columns");
seen[v] = true;
}
}
out->pq_pairs.push_back(pr);
out->pq_theta.push_back(th);
out->pq_scale.push_back(cs);
}
RadEncoding& e = out->enc;
rad_enc_copy_str(e.transform, "givens");
rad_enc_add_table(&e, "t.pairs", RAD_I32, P * S, K);
rad_enc_add_table(&e, "t.angle", RAD_F32, P * S, K / 2);
rad_enc_add_table(&e, "t.scale", RAD_F32, P, K);
if (P > 1) rad_enc_add_table(&e, "t.part", RAD_I32, 1, P);
/* THE DENSE MATRICES, composed here and stored: the prefill quantiser (givens_dense_quant) applies a
* (part, group)'s stages as one 128 x 128 matrix, and a matrix is a number a kernel library must
* not choose at load (abi/rad_abi.h, weight layout) -- the pairs and angles stay for the stage-wise
* rotation the 16-bit GEMMs read. */
if (rad_enc_add_table(&e, "t.dense", RAD_F16, P * K / kParoGroup, kParoGroup * kParoGroup) < 0)
return refuse("'" + out->name + "' has more planes than an encoding holds");
if (!rad_enc_valid(&e)) return refuse("the rotation tables of '" + out->name + "' are malformed");
out->imported = true;
out->paro = true;
out->trivial = false;
out->why = "it is ParoQuant MXFP4, which rad-convert imports with its rotation tables -- "
"serve the container it writes";
return RAD_OK;
}
} /* namespace */
int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional,
CkptWeight* out, std::string* why) {
auto refuse = [&](int rc, std::string m) {
@@ -780,6 +1170,14 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
for (const Src1& s1 : srcs) {
const SrcTensor* st = ck.find(s1.name);
const SrcTensor* sc = st ? ck.find(scale_name(s1.name)) : nullptr;
/* ParoQuant's fp8 heads and embedding carry ONE f32 SCALE A ROW (`X.weight_scale`, [N]),
* not a block plane: Quark's `_scale` naming for a per-channel weight. */
if (st && !sc && ck.imports() == Checkpoint::Import::ParoMx &&
(st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2) && st->shape.size() == 2) {
const SrcTensor* pr = ck.find(std::string(s1.name) + "_scale");
if (pr && pr->rad_dtype == RAD_F32 && pr->shape.size() == 1 && pr->shape[0] == st->shape[0])
sc = pr;
}
/* A WEIGHT THE CHECKPOINT SHIPS IN AN IMPORTED FORM is read through that form's views. */
{
const SrcTensor *ic = nullptr, *is = nullptr;
@@ -823,23 +1221,30 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
" holds none of them");
}
/* THE LOGICAL SHAPE: the pieces joined along concat_dim, every other extent agreeing. */
/* THE LOGICAL SHAPE: the pieces joined along concat_dim, every other extent agreeing. A
* rank-0 tensor is one element and is read as shape [1]: safetensors stores a scalar
* parameter (Gemma 4's clipped-linear bounds) with an empty shape. */
const SrcTensor& p0 = *out->pieces[0];
const int d = out->concat_dim;
if (p0.shape.empty() || p0.shape.size() > RAD_MAX_RANK || d < 0 || d >= (int)p0.shape.size())
auto shape_of = [](const SrcTensor& t) {
return t.shape.empty() ? std::vector<int64_t>{ 1 } : t.shape;
};
const std::vector<int64_t> s0 = shape_of(p0);
if (s0.size() > RAD_MAX_RANK || d < 0 || d >= (int)s0.size())
return refuse(RAD_E_SHAPE, "'" + p0.name + "' cannot be joined along dim " +
std::to_string(d));
out->rank = (uint32_t)p0.shape.size();
for (uint32_t i = 0; i < out->rank; ++i) out->shape[i] = p0.shape[i];
out->rank = (uint32_t)s0.size();
for (uint32_t i = 0; i < out->rank; ++i) out->shape[i] = s0[i];
for (size_t k = 1; k < out->pieces.size(); ++k) {
const SrcTensor& pk = *out->pieces[k];
bool fits = pk.shape.size() == p0.shape.size();
const std::vector<int64_t> sk = shape_of(pk);
bool fits = sk.size() == s0.size();
for (uint32_t i = 0; fits && i < out->rank; ++i)
if ((int)i != d && pk.shape[i] != p0.shape[i]) fits = false;
if ((int)i != d && sk[i] != s0[i]) fits = false;
if (!fits)
return refuse(RAD_E_SHAPE, "'" + pk.name + "' and '" + p0.name +
"' do not join along dim " + std::to_string(d));
out->shape[d] += pk.shape[(size_t)d];
out->shape[d] += sk[(size_t)d];
}
rad_enc_view(out->rank, out->shape, &out->rows, &out->cols);
@@ -855,6 +1260,25 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
} else if (!same) {
out->why = "its pieces are stored in different dtypes";
} else if (p0.pbits) {
/* PARO int5-bitplane: u5 codes, an f16 scale and a u8 zero point a 128 of K, then the
* rotation tables. Joined only along rows (gate|up), as every imported form is. */
bool fits = d == 0 || out->pieces.size() == 1;
for (const SrcTensor* pk : out->pieces) fits = fits && pk->pbits == p0.pbits;
if (!fits) {
out->why = "its int5 pieces are joined along a column, across their groups";
} else {
rad_enc_clear(&out->enc);
rad_enc_copy_str(out->enc.scheme, "affine");
rad_enc_add_plane(&out->enc, "codes", p0.pbits == 5 ? RAD_U5 : RAD_U4, 1, 1);
rad_enc_add_plane(&out->enc, "scale", RAD_F16, 1, 128);
rad_enc_add_plane(&out->enc, "zero", RAD_U8, 1, 128);
const int rc = paro_attach(ck, out, why);
if (rc != RAD_OK) return rc;
out->why = std::string("it is ParoQuant int") + (p0.pbits == 5 ? "5" : "4") +
", which rad-convert imports with its zero points and rotation tables -- "
"serve the container it writes";
}
} else if (p0.gptq_bits) {
/* GPTQ-PACKED, IMPORTED: one width and one group throughout, joined only along rows --
* a column join would put two pieces' groups in one scale block. */
@@ -888,6 +1312,10 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
rad_enc_copy_str(out->enc.scheme, "affine");
rad_enc_add_plane(&out->enc, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(&out->enc, "scale", RAD_E8M0, 1, 32);
if (ck.imports() == Checkpoint::Import::ParoMx) {
const int rc = paro_attach(ck, out, why);
if (rc != RAD_OK) return rc;
}
}
} else if ((dt == RAD_F8E4M3 || dt == RAD_F8E5M2) && scaled) {
/* BLOCK-SCALED FP8, byte for byte: the codes and the scale plane are the planes of
@@ -909,7 +1337,10 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
const int64_t want_r = (r + br - 1) / br, want_c = (c + bc - 1) / bc;
int64_t sr = 0, scl = 0;
rad_enc_view((uint32_t)sk.shape.size(), sk.shape.data(), &sr, &scl);
if (sk.rad_dtype != sdt || sr != want_r || scl != want_c) {
const bool per_row = sk.shape.size() == 1; /* one scale a row; see above */
if (per_row && sk.shape[0] == r && sk.rad_dtype == sdt) {
/* fits */
} else if (per_row || sk.rad_dtype != sdt || sr != want_r || scl != want_c) {
out->trivial = false;
out->why = "'" + sk.name + "' is not the [" + std::to_string(want_r) + ", " +
std::to_string(want_c) + "] " + std::to_string(br) + "x" +
@@ -924,7 +1355,30 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
rad_enc_clear(&out->enc);
rad_enc_copy_str(out->enc.scheme, "affine");
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
rad_enc_add_plane(&out->enc, "scale", sdt, br, bc);
if (out->scales[0]->shape.size() == 1) rad_enc_add_plane(&out->enc, "scale", sdt, 1, 0);
else rad_enc_add_plane(&out->enc, "scale", sdt, br, bc);
}
} else if (p0.ct_group) {
/* CT-INT4, IMPORTED: one group throughout and joined only along rows, as GPTQ's. The codes
* become signed i4 (the offset flipped out at relayout) and the scale is the plane as
* shipped, one a group of K. A kernel reads that group or a recipe re-quantises it. */
out->imported = true;
for (size_t k = 1; k < out->pieces.size() && out->imported; ++k)
if (out->pieces[k]->ct_group != p0.ct_group ||
out->scales[k]->rad_dtype != out->scales[0]->rad_dtype) {
out->imported = false;
out->why = "its CT-INT4 pieces differ in group or scale dtype";
}
if (out->imported && d != 0 && out->pieces.size() > 1) {
out->imported = false;
out->why = "its CT-INT4 pieces are joined along a column, across their groups";
}
if (out->imported) {
rad_enc_clear(&out->enc);
rad_enc_copy_str(out->enc.scheme, "affine");
rad_enc_add_plane(&out->enc, "codes", RAD_I4, 1, 1);
rad_enc_add_plane(&out->enc, "scale", out->scales[0]->rad_dtype, 1, p0.ct_group);
out->why = "it is CT-INT4, which rad-convert imports -- serve the container it writes";
}
} else if (!unscaled) {
out->why = "some of its pieces carry a scale plane and some do not";
@@ -1038,6 +1492,18 @@ struct Joined {
/* `n` elements of a stored-dtype piece from element `e`, as f32. */
int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
if (t.ct_group) {
/* the signed code: element (row, k) of the logical [N, K] matrix is nibble k % 8 of word
* [row, k / 8], less 8 */
const int64_t K = t.shape[1];
for (int64_t i = 0; i < n; ++i) {
const int64_t row = (e + i) / K, k = (e + i) % K;
uint32_t w;
std::memcpy(&w, (const uint8_t*)t.data + (row * (K / 8) + k / 8) * 4, 4);
out[i] = (float)((int)((w >> ((k % 8) * 4)) & 0xFu) - 8);
}
return RAD_OK;
}
if (t.gptq_bits) {
/* the signed code: element (row, k) of the logical [N, K] matrix is field k % (32/bits)
* of word [k / (32/bits), row], less its zero point */
@@ -1092,6 +1558,11 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
return rc;
};
if (r0 < 0 || nr < 0 || r0 + nr > w.rows) return refuse(RAD_E_SHAPE, "rows out of range");
/* A ROTATED WEIGHT's codes are in the rotated basis; its f32 value would be the unrotated one,
* which only a decoder over the container's tables computes. Nothing quantises it again. */
if (w.paro)
return refuse(RAD_E_UNSUPPORTED, "'" + w.name + "' is a ParoQuant weight, stored rotated; "
"it is kept as it is and has no f32 view here");
Joined j;
j.init(w.pieces, w.concat_dim);
/* the runs come in order, so the cursor is the elements already written */
@@ -1109,8 +1580,8 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
: "?")
: std::string(rad_dtype_name(w.pieces[0]->rad_dtype))) +
")");
/* A GPTQ-PACKED CODE TIMES ITS GROUP'S SCALE, the scale read as shipped: the scale tensor is
* [groups, N], so row r's scales are a column of it. */
/* AN IMPORTED CODE TIMES ITS GROUP'S SCALE, the scale read as shipped: GPTQ's scale tensor is
* [groups, N], so row r's scales are a column of it; CT-INT4's is [N, groups], a row. */
if (w.imported) {
int64_t base = 0;
for (size_t k = 0; k < w.pieces.size(); ++k) {
@@ -1119,8 +1590,10 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
const int64_t pr = pk.shape[0];
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r)
for (int64_t c = 0; c < w.cols; ++c)
out[(r - r0) * w.cols + c] *=
rad_load_f32(sk.data, sk.rad_dtype, (c / pk.gptq_group) * pr + (r - base));
out[(r - r0) * w.cols + c] *= rad_load_f32(
sk.data, sk.rad_dtype,
pk.ct_group ? (r - base) * (w.cols / pk.ct_group) + c / pk.ct_group
: (c / pk.gptq_group) * pr + (r - base));
base += pr;
}
return RAD_OK;
@@ -1130,13 +1603,15 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
* are that piece's. */
if (!w.scales.empty() && w.scales[0]) {
const int64_t br = w.enc.n_planes > 1 ? w.enc.plane[1].block[0] : 128;
const int64_t bc = w.enc.n_planes > 1 ? w.enc.plane[1].block[1] : 128;
/* a block extent of 0 is the whole extent: a scale a row, one column of scales */
const int64_t bc0 = w.enc.n_planes > 1 ? w.enc.plane[1].block[1] : 128;
int64_t base = 0;
for (size_t k = 0; k < w.pieces.size(); ++k) {
const SrcTensor& pk = *w.pieces[k];
const SrcTensor& sk = *w.scales[k];
int64_t pr = 0, pc = 0;
rad_enc_view((uint32_t)pk.shape.size(), pk.shape.data(), &pr, &pc);
const int64_t bc = bc0 > 0 ? bc0 : pc;
const int64_t sc = (pc + bc - 1) / bc;
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r)
for (int64_t c = 0; c < w.cols; ++c)
@@ -1163,7 +1638,116 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
const uint32_t dt = w.enc.plane[k].dtype;
const int64_t eb = rad_dtype_bits(dt) / 8;
uint8_t* o = (uint8_t*)dst;
if (w.imported) {
if (w.paro && w.pieces[0]->pbits && k <= 2) {
/* PARO int5-bitplane, RE-LAID a row of the logical [N, K] matrix at a time. The checkpoint
* packs along N: qweight [K, N/8] holds eight low nibbles per word in AWQ order (word
* column c of a group of eight sits in nibble j, ORDER[j] == c), and qweight_hi [K, N/32]
* the fifth bit of 32 columns, bit n % 32. The zero points are the same two packings over
* [G, N]. */
auto nib = [](int c) { return c % 2 == 0 ? c / 2 : 4 + c / 2; }; /* AWQ order */
auto u32 = [](const SrcTensor& t, int64_t i) {
uint32_t v;
std::memcpy(&v, (const uint8_t*)t.data + i * 4, 4);
return v;
};
int64_t base = 0;
for (size_t pi = 0; pi < w.pieces.size(); ++pi) {
const SrcTensor* pc = w.pieces[pi];
const int64_t Np = pc->shape[0], K = pc->shape[1], G = K / 128;
const SrcTensor *hip = pc->aux[0], *qzp = pc->aux[1], *qzhp = pc->aux[2];
const SrcTensor& sc = *w.scales[pi];
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + Np); ++r) {
const int64_t n = r - base;
const int cn = (int)(n % 8);
if (k == 0) {
const int pb = pc->pbits;
const int64_t rb = (K * pb + 7) / 8;
std::memset(o, 0, (size_t)rb);
for (int64_t kk = 0; kk < K; ++kk) {
const uint32_t lo = (u32(*pc, kk * (Np / 8) + n / 8) >> (4 * nib(cn))) & 15u;
const uint32_t h = pb == 5 ? (u32(*hip, kk * (Np / 32) + n / 32) >> (n % 32)) & 1u : 0u;
const uint32_t code = lo | (h << 4);
const int64_t bit = kk * pb;
const uint32_t sh = (uint32_t)(bit & 7);
const uint32_t v = code << sh;
o[bit >> 3] |= (uint8_t)(v & 0xFFu);
if (sh + pb > 8) o[(bit >> 3) + 1] |= (uint8_t)(v >> 8);
}
o += rb;
} else if (k == 1) {
for (int64_t g = 0; g < G; ++g) {
std::memcpy(o, (const uint8_t*)sc.data + (g * Np + n) * 2, 2);
o += 2;
}
} else {
for (int64_t g = 0; g < G; ++g) {
const uint32_t lo = (u32(*qzp, g * (Np / 8) + n / 8) >> (4 * nib(cn))) & 15u;
const uint32_t h = pc->pbits == 5 ? (u32(*qzhp, g * (Np / 32) + n / 32) >> (n % 32)) & 1u : 0u;
*o++ = (uint8_t)(lo | (h << 4));
}
}
}
base += Np;
}
return RAD_OK;
}
if (w.paro && std::strncmp(w.enc.plane[k].role, "t.", 2) == 0) {
/* A ROTATION TABLE, built from the checkpoint's own tensors a row at a time: the pairs
* from group-local to whole-row columns, the angles widened, the channel scale inverted
* (the checkpoint multiplies the activation by it; the encoding's t.scale is the factor
* the stored row was MULTIPLIED by, so the activation is divided), the part ends. */
const RadEncPlane& pl = w.enc.plane[k];
const int64_t P = (int64_t)w.pieces.size(), S = w.pq_pairs[0]->shape[0], K = w.cols;
const std::string role = pl.role;
for (int64_t r = r0; r < r0 + nr; ++r) {
if (role == "t.pairs") {
const int16_t* pv = (const int16_t*)w.pq_pairs[(size_t)(r / S)]->data + (r % S) * K;
int32_t* d = (int32_t*)o;
for (int64_t c = 0; c < K; ++c)
d[c] = (int32_t)((c / kParoGroup) * kParoGroup + pv[c]);
o += K * 4;
} else if (role == "t.angle") {
const SrcTensor& th = *w.pq_theta[(size_t)(r / S)];
float* d = (float*)o;
for (int64_t c = 0; c < K / 2; ++c)
d[c] = rad_load_f32(th.data, th.rad_dtype, (r % S) * (K / 2) + c);
o += K / 2 * 4;
} else if (role == "t.scale") {
const SrcTensor& cs = *w.pq_scale[(size_t)r];
float* d = (float*)o;
for (int64_t c = 0; c < K; ++c) d[c] = 1.0f / rad_load_f32(cs.data, cs.rad_dtype, c);
o += K * 4;
} else if (role == "t.part") {
int32_t* d = (int32_t*)o;
int64_t end = 0;
for (int64_t q = 0; q < P; ++q) {
end += w.pieces[(size_t)q]->shape[0];
d[q] = (int32_t)end;
}
o += P * 4;
} else if (role == "t.dense") {
/* row r is part r / (K/128), group r % (K/128): its stages, group-local, composed */
const int64_t nkb = K / kParoGroup, H = kParoGroup / 2, q = r / nkb, g = r % nkb;
const int16_t* pv = (const int16_t*)w.pq_pairs[(size_t)q]->data;
const SrcTensor& th = *w.pq_theta[(size_t)q];
std::vector<int32_t> ia((size_t)(S * H)), ib((size_t)(S * H));
std::vector<float> an((size_t)(S * H));
for (int64_t st = 0; st < S; ++st)
for (int64_t j = 0; j < H; ++j) {
const int64_t at = st * H + j;
ia[(size_t)at] = pv[st * K + g * kParoGroup + 2 * j];
ib[(size_t)at] = pv[st * K + g * kParoGroup + 2 * j + 1];
an[(size_t)at] = rad_load_f32(th.data, th.rad_dtype, st * (K / 2) + g * H + j);
}
paro_compose_dense(S, ia.data(), ib.data(), an.data(), (uint16_t*)o);
o += kParoGroup * kParoGroup * 2;
} else {
return refuse(RAD_E_STATE, "plane '" + role + "' of a ParoQuant weight is not a table");
}
}
return RAD_OK;
}
if (w.imported && !w.paro) {
/* GPTQ-PACKED, RE-LAID: a row of codes is a column of the qweight, its words' bytes in
* order -- two codes a byte for int4, low nibble first, as the encoding packs them -- each
* offset to signed by flipping the top bit of every field; a row of scales is a column of
@@ -1173,6 +1757,24 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
const SrcTensor& c = *w.pieces[p];
const SrcTensor& s = *w.scales[p];
const int64_t N = c.shape[0], K = c.shape[1];
if (c.ct_group) {
/* CT-INT4, RE-LAID: a row of codes is a row of the packed words, already two codes
* a byte low nibble first, each offset to signed by flipping its top bit; a row of
* scales is a row of the scale tensor, as shipped. */
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) {
const int64_t n = r - base;
if (k == 0) {
const uint8_t* q = (const uint8_t*)c.data + n * (K / 2);
for (int64_t i = 0; i < K / 2; ++i) *o++ = q[i] ^ 0x88;
} else {
const int64_t g = K / c.ct_group, sb = rad_dtype_bits(s.rad_dtype) / 8;
std::memcpy(o, (const uint8_t*)s.data + n * g * sb, (size_t)(g * sb));
o += g * sb;
}
}
base += N;
continue;
}
const uint8_t flip = c.gptq_bits == 4 ? 0x88 : 0x80;
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) {
const int64_t n = r - base;
@@ -1214,6 +1816,7 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
for (const SrcTensor* s : src) {
int64_t sr = 0, scl = 0;
rad_enc_view((uint32_t)s->shape.size(), s->shape.data(), &sr, &scl);
if (s->shape.size() == 1) { sr = s->shape[0]; scl = 1; } /* one scale a row */
const int64_t lo = std::max(r0, base), hi = std::min(r0 + nr, base + sr);
if (hi > lo) {
std::memcpy(o, (const uint8_t*)s->data + (lo - base) * scl * eb,
+40 -4
View File
@@ -56,6 +56,18 @@ struct SrcTensor {
* the K columns one row of its scale tensor covers. 0 for any other tensor. */
int32_t gptq_bits = 0;
int64_t gptq_group = 0;
/* CT-INT4 (compressed-tensors' pack-quantized int4, symmetric): `data` is X.weight_packed's
* int32 words [N, K / 8], eight codes a word along K from the low bits up, stored unsigned with
* the zero point 8. The tensor this describes is the logical [N, K] code matrix, `rad_dtype`
* RAD_I4; `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for
* any other tensor. */
int64_t ct_group = 0;
/* ParoQuant's int5-bitplane (Import::ParoI5): `data` is the AWQ-packed low nibbles qweight
* [K, N/8] and the tensor described is the logical [N, K] u5 code matrix; `aux` are the fifth-bit
* plane qweight_hi [K, N/32], and the zero points qzeros [G, N/8] and qzeros_hi [G, N/32].
* z-lab's int4 (Import::ParoI4) is the same without the fifth-bit planes (aux[0], aux[2] null). */
int pbits = 0; /* 5 for int5-bitplane, 4 for z-lab's plain AWQ-packed int4; 0 otherwise */
const SrcTensor* aux[3] = { nullptr, nullptr, nullptr };
int64_t numel() const {
int64_t n = 1;
@@ -84,6 +96,8 @@ struct MetaOwn {
};
int meta_from_config_json(const std::string& dir, MetaOwn* out);
/* quantization_config's quant_method and fmt as the plugin descriptor ("fp8_e4m3"), "" without. */
std::string quant_descriptor(const MetaOwn& m);
int meta_merge_config_json(const std::string& dir, const std::string& prefix, MetaOwn* out);
int meta_merge_generation_config(const std::string& dir, MetaOwn* out);
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out);
@@ -111,6 +125,9 @@ public:
GgufFile& gguf() { return gguf_; }
const std::string& path() const { return path_; }
const std::string& dir() const { return dir_; } /* where config.json and tokenizer.json sit */
/* Where tokenizer.json, tokenizer_config.json and the chat template sit: dir() for a model
* repository, the `processor/` (or `tokenizer/`) folder of a diffusers pipeline. */
const std::string& tok_dir() const { return tok_dir_.empty() ? dir_ : tok_dir_; }
MetaOwn& meta() { return meta_; }
const MetaOwn& meta() const { return meta_; }
@@ -126,11 +143,12 @@ public:
/* THE CHECKPOINT'S QUANTISATION, IMPORTED WEIGHT BY WEIGHT, or None. Read from
* quantization_config at open: AutoRound's `auto_round:auto_gptq` export and GPTQ's own (v1,
* the zero point stored less one) are Gptq; Quark's MXFP4 (fp4 weights, per_group 32, e8m0
* scales, no per-layer overrides) is QuarkMx. A quantisation of one of those tools in a form
* scales, no per-layer overrides) is QuarkMx; ParoQuant's MXFP4 (`paroquant_mxfp4`: Quark's
* codes and exponents in a ROTATED basis, with the rotations beside them) is ParoMx. A quantisation of one of those tools in a form
* this does not read stays None, with the reason in import_refusal(). */
/* Its quantization_config keys are then renamed `imported_quantization_config.*`: they
* describe the tool, not a served format, and a plugin reads the latter there. */
enum class Import { None, Gptq, QuarkMx };
enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4 };
Import imports() const { return import_; }
const std::string& import_refusal() const { return import_why_; }
@@ -142,22 +160,28 @@ public:
std::string* why);
private:
int add_shard(const std::string& p, const std::string& prefix = "");
/* `owner`, when the checkpoint has an index, is its weight_map: a tensor the index places in
* another shard is not read from this one. */
int add_shard(const std::string& p, const std::string& prefix = "",
const std::unordered_map<std::string, std::string>* owner = nullptr);
int open_safetensors(const std::string& path);
int open_diffusers();
int open_gguf(const std::string& path);
void detect_import();
enum Kind { None, Gguf, SafeT } kind_ = None;
std::string path_, dir_;
std::string path_, dir_, tok_dir_;
GgufFile gguf_;
MetaOwn meta_;
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
std::vector<SrcTensor> tensors_;
std::unordered_map<std::string, size_t> index_;
std::unordered_map<std::string, size_t> index_shard_; /* name -> shards_ position */
std::deque<SrcTensor> sliced_; /* views; a deque never moves what it holds */
int64_t fp8_br_ = 128, fp8_bc_ = 128;
Import import_ = Import::None;
std::string import_why_;
int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */
/* import_piece's answers by name, so a weight resolved twice reads one pair of views. */
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
};
@@ -180,6 +204,13 @@ struct CkptWeight {
* Not trivial -- the rounding means the numbers are not served as shipped -- so the loader
* refuses one and rad-convert keeps it in `enc`, as it keeps a trivial weight. */
bool imported = false;
/* PAROQUANT MXFP4, IMPORTED (Import::ParoMx): `imported` too, so the loader refuses it and
* rad-convert writes it plane by plane through ckpt_plane_rows. Planes 0 and 1 are Quark's
* codes and exponents byte for byte; the rest are the "givens" transform's tables, built here
* from `pq_pairs`/`pq_theta`/`pq_scale`, one set per piece (a piece is a row PART: gate and up,
* or q, k and v, each rotated on its own). */
bool paro = false;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale;
RadEncoding enc{};
std::string why;
};
@@ -199,6 +230,11 @@ std::string ckpt_tensor_of(const SrcTensor& t);
bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>& names,
std::unordered_set<std::string>* hit = nullptr);
/* One (part, group) of a ParoQuant rotation as its dense matrix: `S` stages of 64 pairs, the pair's two
* group-local columns `ia`/`ib` and angle `th`, stage-major; out[j * 128 + i] (f16) is output j for the
* unit vector e_i. It is the "givens" encoding's "t.dense" table, row for row. */
void paro_compose_dense(int64_t S, const int32_t* ia, const int32_t* ib, const float* th, uint16_t* out);
/* Logical rows [r0, r0 + nr) of `w` as f32 [nr, cols], whatever the pieces are stored as: a
* plain float widened, FP8 times its block scale, a GGUF block type dequantised. */
int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::string* why);
+62 -14
View File
@@ -102,31 +102,77 @@ Rd plane(const EncodedView& v, int idx) {
return r;
}
/* Undo a "givens" transform on one row in place: w = v . G_S^T ... G_1^T . D^-1. */
int givens_inverse(const EncodedView& v, float* row, std::string* why) {
/* The tables of one row part of a "givens" weight, read once: the cosine and sine of every angle
* and the pairs as indices, so undoing a row is arithmetic and not a table walk. A decode asks for
* the part its row falls in, and rows of one part follow each other. */
struct GivensPart {
int64_t part = -1;
int64_t S = 0;
std::vector<int32_t> pair; /* [S][K] */
std::vector<double> cs, sn; /* [S][K/2] */
std::vector<float> scale; /* [K], empty without t.scale */
};
int givens_part(const EncodedView& v, int64_t r, GivensPart* g, std::string* why) {
const Rd pairs = plane(v, rad_enc_find(&v.enc, "t.pairs"));
const Rd angle = plane(v, rad_enc_find(&v.enc, "t.angle"));
const Rd scale = plane(v, rad_enc_find(&v.enc, "t.scale"));
const int64_t S = pairs.v->rows, K = v.cols;
if (pairs.v->cols != K || angle.v->rows != S || angle.v->cols != K / 2 || (K & 1) ||
(scale && (scale.v->rows != 1 || scale.v->cols != K))) {
const Rd bound = plane(v, rad_enc_find(&v.enc, "t.part"));
const int64_t K = v.cols, P = rad_enc_givens_parts(&v.enc);
if (P < 1 || pairs.v->rows % P || pairs.v->cols != K || angle.v->rows != pairs.v->rows ||
angle.v->cols != K / 2 || (K & 1) ||
(scale && (scale.v->rows != P || scale.v->cols != K))) {
if (why) *why = fmt("a givens transform's tables do not fit a %lld-column row", K);
return RAD_E_SHAPE;
}
for (int64_t s = S - 1; s >= 0; --s)
for (int64_t p = 0; p < K / 2; ++p) {
const int64_t a = (int64_t)pairs.at(s, 2 * p), b = (int64_t)pairs.at(s, 2 * p + 1);
if (a < 0 || a >= K || b < 0 || b >= K || a == b) {
if (why) *why = fmt("givens stage %lld pairs columns %lld and %lld", s, a, b);
int64_t part = 0;
while (bound && part + 1 < P && r >= (int64_t)bound.at(0, part)) ++part;
if (g->part == part) return RAD_OK;
g->part = part;
g->S = pairs.v->rows / P;
g->pair.assign((size_t)(g->S * K), 0);
g->cs.assign((size_t)(g->S * K / 2), 0.0);
g->sn.assign((size_t)(g->S * K / 2), 0.0);
for (int64_t s = 0; s < g->S; ++s) {
for (int64_t k = 0; k < K; ++k) {
const int64_t c = (int64_t)pairs.at(part * g->S + s, k);
if (c < 0 || c >= K) {
if (why) *why = fmt("givens stage %lld names column %lld", s, c);
return RAD_E_SHAPE;
}
const double t = angle.at(s, p), c = std::cos(t), sn = std::sin(t);
g->pair[(size_t)(s * K + k)] = (int32_t)c;
}
for (int64_t p = 0; p < K / 2; ++p) {
const double t = angle.at(part * g->S + s, p);
g->cs[(size_t)(s * K / 2 + p)] = std::cos(t);
g->sn[(size_t)(s * K / 2 + p)] = std::sin(t);
}
}
g->scale.clear();
if (scale) {
g->scale.resize((size_t)K);
for (int64_t k = 0; k < K; ++k) g->scale[(size_t)k] = scale.at(part, k);
}
return RAD_OK;
}
/* Undo a "givens" transform on one row in place: w = v . G_S^T ... G_1^T . D^-1, with the tables
* of the row part `g` holds. */
int givens_inverse(const GivensPart& g, int64_t K, float* row, std::string* why) {
for (int64_t s = g.S - 1; s >= 0; --s)
for (int64_t p = 0; p < K / 2; ++p) {
const int64_t a = g.pair[(size_t)(s * K + 2 * p)], b = g.pair[(size_t)(s * K + 2 * p + 1)];
if (a == b) {
if (why) *why = fmt("givens stage %lld pairs column %lld with itself", s, a);
return RAD_E_SHAPE;
}
const double c = g.cs[(size_t)(s * K / 2 + p)], sn = g.sn[(size_t)(s * K / 2 + p)];
const double x = row[a], y = row[b];
row[a] = (float)(c * x - sn * y);
row[b] = (float)(sn * x + c * y);
}
if (scale)
for (int64_t k = 0; k < K; ++k) row[k] /= scale.at(0, k);
if (!g.scale.empty())
for (int64_t k = 0; k < K; ++k) row[k] /= g.scale[(size_t)k];
return RAD_OK;
}
@@ -219,6 +265,7 @@ int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out, s
return RAD_E_SHAPE;
}
std::vector<float> tmp(perm ? (size_t)v.cols : 0);
GivensPart gv;
/* THE COMMON FORM, A ROW AT A TIME: codes with no codebook, sign, zero or minimum and at most
* one scale level -- int4 experts, fp8 rows, a fixed-scale table. The element walk below
* resolves every element's dtype and its scale's index through a switch and two divisions,
@@ -288,7 +335,8 @@ int enc_decode_rows(const EncodedView& v, int64_t row0, int64_t n, float* out, s
}
std::memcpy(o, tmp.data(), (size_t)v.cols * sizeof(float));
} else if (giv) {
const int st = givens_inverse(v, o, why);
int st = givens_part(v, r, &gv, why);
if (st == RAD_OK) st = givens_inverse(gv, v.cols, o, why);
if (st != RAD_OK) return st;
}
}
+916
View File
@@ -0,0 +1,916 @@
/* driver.cpp -- the image generator's pass driver (driver.h). */
#include "driver.h"
#include "sched/mem_iface.h"
#include <algorithm>
#include <cmath>
#include <cstring>
namespace rad {
namespace gen {
namespace {
constexpr int64_t kAlign = 256;
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
/* A reference picture's latent tokens at most: its area, a little over for the rounding of its
* sides to the size multiple. */
int64_t ref_tokens_max(const RadGeneratorDecl& d) {
const int64_t s2 = d.latent_scale * d.latent_scale;
return (d.ref_area + s2 - 1) / s2 * 11 / 10 + 64;
}
struct Sizes {
int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0;
};
Sizes sizes_of(const Program& prog, int64_t block_size) {
const RadGeneratorDecl& d = prog.generator;
Sizes z;
z.T = prog.ctx.max_tok;
z.S = prog.ctx.max_seqs;
z.EP = prog.encoder.modalities ? prog.ctx.max_enc_patches : 0;
z.PD = prog.encoder.modalities ? prog.encoder.patch_dim : 0;
z.R = d.max_refs;
z.P = z.T + z.R * ref_tokens_max(d);
const int64_t s2 = d.latent_scale * d.latent_scale;
z.PX = z.R * (ref_tokens_max(d) * s2) + d.max_tokens * s2;
z.NT = d.max_tokens;
z.NB = block_size > 0 ? (z.P + block_size - 1) / block_size : 0;
return z;
}
/* The regions, in order, and the total. One function for both the allocation and the budget's
* count of it, so the two cannot disagree. */
int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
const int64_t I = 4, H = 2;
const int64_t rope_rows = std::max(z.P, z.T);
const int64_t want[][2] = {
{ 0, z.T * I }, /* R_TOK */
{ 0, z.T * I }, /* R_POS */
{ 0, 3 * z.T * I }, /* R_ROPE */
{ 0, (z.S + 1) * I }, /* R_CU */
{ 0, z.T * I }, /* R_MMROW */
{ 0, z.EP * z.PD * H }, /* R_ENCPIX */
{ 0, 4 * z.EP * I }, /* R_ENCCRD */
{ 0, (z.R + 2) * I }, /* R_ENCCU */
{ 0, z.P * I }, /* R_SRC */
{ 0, 3 * rope_rows * I }, /* R_GROPE */
{ 0, (12 * z.R + 24) * I }, /* R_SEG: offsets, {0, length} and start a segment, {0, tokens} a picture */
{ 0, z.P * I }, /* R_SLOT */
{ 0, z.PX * pixel_ch * H }, /* R_PX */
{ 0, z.NT * 4 }, /* R_MASK */
{ 0, z.S * 4 }, /* R_SIG */
{ 0, z.S * 4 }, /* R_SIGN */
{ 0, z.S * 4 }, /* R_CFG */
{ 0, z.S * I }, /* R_PAIR */
{ 0, z.S * I }, /* R_LANE */
{ 0, z.S * I }, /* R_FLAGS */
{ 0, 2 * z.S * 4 }, /* R_SEED */
{ 0, z.S * z.NB * I }, /* R_BT */
{ 0, z.S * I }, /* R_USED */
};
int64_t off = 0;
for (int r = 0; r < n; ++r) {
bytes[r][0] = off;
bytes[r][1] = want[r][1];
off = align_up(off + want[r][1]);
}
return off;
}
} /* namespace */
int64_t Driver::device_bytes(const Program& prog, const Config& cfg) {
(void)cfg;
if (!prog.is_generator() || prog.kv_groups.size() < 2) return 0;
const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size);
int64_t b[R_N][2];
return carve(z, prog.generator.pixel_channels, b, R_N);
}
int Driver::init(const Program& prog, const Config& cfg, IKVManager* kv,
const std::vector<RankIO>& ranks) {
(void)cfg;
fini();
if (!prog.is_generator()) return RAD_E_STATE;
decl_ = prog.generator;
fixed_ = prog.gen_str.sigmas;
kv_ = kv;
ranks_ = ranks;
/* ONE KV GROUP, PAGED: the conditioning's keys and values. A generator with no conditioning
* cache, or two, is not a shape this driver stages. Group handles start at 1 -- the program's
* group 0 is the null handle -- and the KV manager and a batch both index by handle. */
if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
prog.kv_groups[1].block_size <= 0) {
RAD_ERR("image generator: the program declares %zu KV group(s); the driver stages exactly "
"one full-attention group, the conditioning's", prog.kv_groups.size() - 1);
return RAD_E_UNSUPPORTED;
}
kv_group_ = 1;
block_size_ = prog.kv_groups[1].block_size;
const Sizes z = sizes_of(prog, block_size_);
max_tok_ = z.T;
max_seqs_ = z.S;
max_enc_ = z.EP;
patch_dim_ = z.PD;
max_rows_ = z.P;
max_px_ = z.PX;
max_blocks_ = z.NB;
int64_t b[R_N][2];
bytes_ = carve(z, decl_.pixel_channels, b, R_N);
for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; }
host_ = static_cast<char*>(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED));
img_bytes_ = decl_.max_tokens * decl_.latent_scale * decl_.latent_scale * decl_.pixel_channels;
img_host_ = rad_dev_alloc(img_bytes_, RAD_MEM_HOST_PINNED);
if (!host_ || !img_host_) {
RAD_ERR("image generator: no pinned host memory for the pass staging (%lld + %lld bytes)",
(long long)bytes_, (long long)img_bytes_);
return RAD_E_NOMEM;
}
std::memset(host_, 0, (size_t)bytes_);
dev_.assign(ranks_.size(), nullptr);
for (size_t r = 0; r < ranks_.size(); ++r) {
RAD_TRY(rad_dev_set(ranks_[r].device));
dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE);
if (!dev_[r]) {
RAD_ERR("image generator: rank %zu has no room for the pass staging (%lld bytes)", r,
(long long)bytes_);
return RAD_E_NOMEM;
}
}
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device));
out_.assign(ranks_.size(), RadBatch{});
gout_.assign(ranks_.size(), RadGenBatch{});
kout_.assign(ranks_.size(), RadKVGroupBatch{});
lanes_.assign((size_t)decl_.max_lanes, Lane{});
free_lanes_.clear();
for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i);
return RAD_OK;
}
void Driver::fini() {
for (size_t r = 0; r < dev_.size(); ++r)
if (dev_[r]) {
if (r < ranks_.size()) rad_dev_set(ranks_[r].device);
rad_dev_free(dev_[r], RAD_MEM_DEVICE);
}
dev_.clear();
if (!ranks_.empty()) rad_dev_set(ranks_[0].device);
if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED);
if (img_host_) rad_dev_free(img_host_, RAD_MEM_HOST_PINNED);
host_ = nullptr;
img_host_ = nullptr;
}
/* ================================================================== requests */
int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
if (!r || !r->ticket) return RAD_E_INVAL;
const RadGeneratorDecl& d = decl_;
auto no = [&](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
if (r->width <= 0 || r->height <= 0 || r->width % d.size_multiple || r->height % d.size_multiple)
return no("the size must be whole multiples of " + std::to_string(d.size_multiple) +
" 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;
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) +
" latent tokens (" + std::to_string(d.max_tokens * d.latent_scale * d.latent_scale) +
" pixels)");
if (tokens * nb > max_tok_)
return no("an image of this size with guidance needs " + std::to_string(tokens * nb) +
" rows a step and a step carries " + std::to_string(max_tok_) +
" (--max-num-batched-tokens)");
if (r->n < 1 || r->n > d.max_lanes)
return no("n must be 1.." + std::to_string(d.max_lanes));
if ((int64_t)r->refs.size() > d.max_refs)
return no("at most " + std::to_string(d.max_refs) + " pictures a request");
for (const Branch* b : { &r->pos, &r->neg }) {
if (b == &r->neg && !r->has_neg) continue;
if ((int64_t)b->tokens.size() > max_tok_)
return no("the prompt is " + std::to_string(b->tokens.size()) + " tokens with its "
"pictures; a conditioning pass carries " + std::to_string(max_tok_));
int64_t np = 0;
if (b->media)
for (const mm::Placed& p : b->media->items) np += p.item ? p.item->n_patch : 0;
if (np > max_enc_)
return no("the pictures are " + std::to_string(np) + " patches together and a "
"conditioning pass encodes " + std::to_string(max_enc_) +
" (--mm-max-patches)");
}
int64_t px = 0;
for (const Pixels& p : r->refs) px += (int64_t)p.w * p.h;
if (r->inpaint) px += (int64_t)r->inp_src.w * r->inp_src.h;
if (px > max_px_) return no("the pictures are larger than the staging holds");
if (r->inpaint && ((int64_t)r->inp_mask.size() != tokens || r->inp_src.w != r->width ||
r->inp_src.h != r->height))
return no("the mask's picture is not at the size being made");
if (r->previews < 0 || r->previews > 3) return no("partial_images must be 0..3");
r->ticket->t_submit_ns = (int64_t)rad_mono_ns();
std::lock_guard<std::mutex> lk(mu_);
if (closed_) {
if (why) *why = closed_why_;
return closed_status_;
}
auto j = std::make_unique<Job>();
j->id = next_id_++;
j->n_branch = nb;
j->tokens = tokens;
j->h_lat = (int32_t)(r->height / d.latent_scale);
j->w_lat = (int32_t)(r->width / d.latent_scale);
j->req = std::move(r);
jobs_.push_back(std::move(j));
return RAD_OK;
}
void Driver::shutdown(const char* why, int status) {
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
closed_why_ = why ? why : "the engine stopped";
closed_status_ = status;
for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_);
}
int64_t Driver::queued() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (!j->admitted) ++n;
return n;
}
int64_t Driver::running() const {
std::lock_guard<std::mutex> lk(mu_);
int64_t n = 0;
for (const auto& j : jobs_) if (j->admitted) ++n;
return n;
}
bool Driver::busy() const {
std::lock_guard<std::mutex> lk(mu_);
return !jobs_.empty();
}
Driver::Job* Driver::job_locked(uint64_t id) {
for (auto& j : jobs_) if (j->id == id) return j.get();
return nullptr;
}
void Driver::release_locked(Job& j) {
for (int b = 0; b < 2; ++b)
if (j.cond[b].have_kv) {
kv_->free_sequence(j.cond[b].seq);
j.cond[b].have_kv = false;
}
for (int32_t l : j.lanes) {
lanes_[(size_t)l] = Lane{};
free_lanes_.push_back(l);
}
j.lanes.clear();
}
void Driver::fail_locked(Job& j, int status, const std::string& why) {
j.failed = true;
j.req->ticket->finish(status, why);
}
/* IN ORDER, AND A REQUEST THAT DOES NOT FIT STOPS THE ONES BEHIND IT. */
int Driver::admit_locked() {
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted || j.failed) continue;
Request& r = *j.req;
if ((int64_t)free_lanes_.size() < r.n) break;
/* The sequences, once: their length is what the KV has to hold. */
if (j.cond[0].lay.rows == 0) {
j.ref_hw.clear();
for (const Pixels& p : r.refs)
j.ref_hw.push_back({ (int32_t)(p.h / decl_.latent_scale),
(int32_t)(p.w / decl_.latent_scale) });
for (int b = 0; b < j.n_branch; ++b) {
std::string why;
const int s = build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw,
&j.cond[b].lay, &why);
if (s < 0) { fail_locked(j, s, why); break; }
if (j.cond[b].lay.rows > max_rows_) {
fail_locked(j, RAD_E_INVAL, "the conditioning is " +
std::to_string(j.cond[b].lay.rows) + " rows; the driver stages " +
std::to_string(max_rows_));
break;
}
}
if (j.failed) continue;
}
bool ok = true;
for (int b = 0; b < j.n_branch && ok; ++b) {
Cond& c = j.cond[b];
if (c.have_kv) continue;
if (!kv_->can_ever_fit(c.lay.rows)) {
fail_locked(j, RAD_E_INVAL, "the conditioning's " + std::to_string(c.lay.rows) +
" rows do not fit the KV cache even when it is empty");
ok = false;
break;
}
c.seq = ((uint64_t)1 << 62) | next_seq_++;
if (kv_->add_sequence(c.seq) < 0) { ok = false; break; }
const int s = kv_->ensure(c.seq, c.lay.rows);
if (s < 0) {
kv_->free_sequence(c.seq);
ok = false;
break;
}
c.have_kv = true;
}
if (j.failed) continue;
if (!ok) {
/* The KV is short now: give back what this one took and wait. */
for (int b = 0; b < 2; ++b)
if (j.cond[b].have_kv) { kv_->free_sequence(j.cond[b].seq); j.cond[b].have_kv = false; }
break;
}
j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens);
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
for (int b = 0; b < j.n_branch; ++b) {
Cond& c = j.cond[b];
c.rope_img.assign((size_t)(3 * j.tokens), 0);
image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens);
}
for (int32_t i = 0; i < r.n; ++i) {
const int32_t l = free_lanes_.back();
free_lanes_.pop_back();
Lane& ln = lanes_[(size_t)l];
ln = Lane{};
ln.job = 0;
ln.job_id = j.id;
ln.index = i;
ln.seed = r.seed + (uint64_t)i;
for (int32_t k = 1; k <= r.previews; ++k) {
const int32_t at = (int32_t)((int64_t)n_steps * k / (r.previews + 1));
if (at >= 1 && at < n_steps &&
(ln.preview_at.empty() || ln.preview_at.back() != at))
ln.preview_at.push_back(at);
}
j.lanes.push_back(l);
}
r.ticket->steps = n_steps;
int64_t in_tok = (int64_t)r.pos.tokens.size();
if (r.has_neg) in_tok += (int64_t)r.neg.tokens.size();
r.ticket->in_tokens = in_tok;
r.ticket->out_tokens = j.tokens * r.n;
j.admitted = true;
}
return RAD_OK;
}
/* ================================================================== staging */
int Driver::upload() {
for (size_t r = 0; r < ranks_.size(); ++r)
for (int g = 0; g < R_N; ++g) {
if (reg_[g].used <= 0) continue;
RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off,
reg_[g].used, ranks_[r].stream));
}
return RAD_OK;
}
void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int step) {
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = out_[r];
RadGenBatch& G = gout_[r];
RadKVGroupBatch& K = kout_[r];
const int ri = (int)r;
B.step = step;
B.phase = RAD_PHASE_PREFILL;
B.n_tok = n_tok;
B.n_seq = n_seq;
B.max_q_len = max_q;
B.token_ids = dptr<int32_t>(ri, R_TOK);
B.positions = dptr<int32_t>(ri, R_POS);
B.cu_seqlens = dptr<int32_t>(ri, R_CU);
B.q_lens = nullptr;
B.ctx_lens = nullptr;
B.n_seq_decode = 0;
B.n_tok_decode = 0;
B.max_q_len_prefill = max_q;
K.group = (rad_kvgroup)kv_group_;
K.slot_mapping = reg_[R_SLOT].used > 0 ? dptr<int32_t>(ri, R_SLOT) : nullptr;
K.block_table = dptr<int32_t>(ri, R_BT);
K.seqused = dptr<int32_t>(ri, R_USED);
K.block_size = block_size_;
K.max_blocks = max_blocks_;
B.n_kv_groups = 1;
B.kv = &K;
B.gen_b = &G;
G.src = dptr<int32_t>(ri, R_SRC);
G.rope = dptr<int32_t>(ri, R_GROPE);
G.seg = dptr<int32_t>(ri, R_SEG);
G.seg_h = hptr<int32_t>(R_SEG);
G.slot_mapping = dptr<int32_t>(ri, R_SLOT);
G.px = dptr<uint16_t>(ri, R_PX);
G.inp_mask = dptr<float>(ri, R_MASK);
G.sigma = dptr<float>(ri, R_SIG);
G.sigma_next = dptr<float>(ri, R_SIGN);
G.cfg = dptr<float>(ri, R_CFG);
G.pair = dptr<int32_t>(ri, R_PAIR);
G.lane = dptr<int32_t>(ri, R_LANE);
G.lane_dh = hptr<int32_t>(R_LANE);
G.flags = dptr<int32_t>(ri, R_FLAGS);
G.seed = dptr<uint32_t>(ri, R_SEED);
}
}
/* ================================================================== the passes */
const RadBatch* Driver::next(int step) {
std::lock_guard<std::mutex> lk(mu_);
pass_ = Pass{};
dec_bytes_ = 0;
if (closed_) return nullptr;
/* What finished, failed or was given up on since the last pass leaves now: its KV and lanes
* go back before anything is admitted. Nothing is in flight -- next() runs between passes. */
for (auto it = jobs_.begin(); it != jobs_.end();) {
Job& j = **it;
const bool gone = j.failed || j.req->ticket->cancel.load(std::memory_order_acquire) ||
(j.admitted && j.images_done >= j.req->n);
if (!gone) { ++it; continue; }
if (j.req->ticket->cancel.load(std::memory_order_acquire) && !j.failed &&
j.images_done < j.req->n)
j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled");
release_locked(j);
it = jobs_.erase(it);
}
admit_locked();
/* 1. A decode an image is owed. */
for (int32_t l = 0; l < (int32_t)lanes_.size(); ++l) {
Lane& ln = lanes_[(size_t)l];
if (ln.job < 0 || ln.finished) continue;
if (ln.preview_due) return build_decode(l, true, step);
if (ln.final_due) return build_decode(l, false, step);
}
/* 2. A conditioning an admitted request is owed. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed) continue;
for (int b = 0; b < j.n_branch; ++b)
if (!j.cond[b].encoded) return build_cond(j, b, step);
}
/* 3. A denoise step over what is in flight, oldest request first. */
std::vector<int32_t> take;
int64_t rows = 0, entries = 0;
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed) continue;
bool ready = true;
for (int b = 0; b < j.n_branch; ++b) ready = ready && j.cond[b].encoded;
if (!ready) continue;
const int32_t n_steps = (int32_t)j.sigmas.size() - 1;
for (int32_t l : j.lanes) {
const Lane& ln = lanes_[(size_t)l];
if (ln.finished || ln.final_due || ln.preview_due || ln.step >= n_steps) continue;
const int64_t need = j.tokens * j.n_branch;
if (rows + need > max_tok_ || entries + j.n_branch > max_seqs_) break;
rows += need;
entries += j.n_branch;
take.push_back(l);
}
}
if (take.empty()) return nullptr;
return build_denoise(take, step);
}
const RadBatch* Driver::batch_for(int rank) const {
if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr;
return &out_[(size_t)rank];
}
const RadBatch* Driver::build_cond(Job& j, int branch, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const Request& r = *j.req;
const Branch& br = branch ? r.neg : r.pos;
const Cond& c = j.cond[branch];
const int64_t T = (int64_t)br.tokens.size(), P = c.lay.rows;
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* rope = hptr<int32_t>(R_ROPE);
std::memcpy(tok, br.tokens.data(), (size_t)T * 4);
for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i;
for (int64_t i = 0; i < T; ++i) {
int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i };
if (br.media) br.media->rope.at(i, p3);
rope[i] = p3[0];
rope[T + i] = p3[1];
rope[2 * T + i] = p3[2];
}
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)T;
reg_[R_TOK].used = reg_[R_POS].used = T * 4;
reg_[R_ROPE].used = 3 * T * 4;
reg_[R_CU].used = 2 * 4;
/* The pictures, for the conditioning network's encoder: every item's patches in prompt order,
* one segment an item, and the prompt rows the encoder's output rows replace. */
int64_t n_patch = 0, n_seg = 0, n_mm = 0;
int32_t max_seg = 0;
if (br.media) {
uint16_t* pix = hptr<uint16_t>(R_ENCPIX);
int32_t* crd = hptr<int32_t>(R_ENCCRD);
int32_t* ecu = hptr<int32_t>(R_ENCCU);
int64_t total = 0;
for (const mm::Placed& p : br.media->items) total += p.item->n_patch;
std::vector<int64_t> row0;
int64_t rows_at = 0;
ecu[0] = 0;
std::vector<int32_t> tmp;
for (const mm::Placed& p : br.media->items) {
const mm::Item& it = *p.item;
std::memcpy(pix + n_patch * patch_dim_, it.pixels.data(),
(size_t)(it.n_patch * patch_dim_) * 2);
tmp.resize((size_t)(4 * it.n_patch));
it.coords(0, it.n_patch, tmp.data());
for (int cc = 0; cc < 4; ++cc)
std::memcpy(crd + cc * total + n_patch, tmp.data() + cc * it.n_patch,
(size_t)it.n_patch * 4);
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t a = it.patch_at(s), e = it.patch_at(s + 1);
ecu[n_seg + 1] = (int32_t)(n_patch + e);
max_seg = std::max<int32_t>(max_seg, (int32_t)(e - a));
++n_seg;
}
row0.push_back(rows_at);
rows_at += it.n_rows();
n_patch += it.n_patch;
}
int32_t* mmr = hptr<int32_t>(R_MMROW);
for (const mm::RopeLayout::Run& run : br.media->rope.runs) {
const int64_t base = row0[(size_t)run.item] + run.row0;
(void)base;
for (int32_t k = 0; k < run.n; ++k) mmr[n_mm++] = run.tok + k;
}
reg_[R_ENCPIX].used = n_patch * patch_dim_ * 2;
reg_[R_ENCCRD].used = 4 * total * 4;
reg_[R_ENCCU].used = (n_seg + 1) * 4;
reg_[R_MMROW].used = n_mm * 4;
}
/* The generator's sequence, which the plugin runs a segment at a time: each segment's rotary
* positions as one dense [3, length] block, its own {0, length} and its first row. */
std::memcpy(hptr<int32_t>(R_SRC), c.lay.src.data(), (size_t)P * 4);
const int64_t nsg = (int64_t)c.lay.bidi.size();
int32_t* grope = hptr<int32_t>(R_GROPE);
int32_t* segp = hptr<int32_t>(R_SEG);
std::memcpy(segp, c.lay.seg.data(), (size_t)(nsg + 1) * 4);
for (int64_t s = 0; s < nsg; ++s) {
const int32_t a = c.lay.seg[(size_t)s], len = c.lay.seg[(size_t)s + 1] - a;
for (int cc = 0; cc < 3; ++cc)
std::memcpy(grope + 3 * (int64_t)a + cc * (int64_t)len,
&c.lay.rope[(size_t)(cc * P + a)], (size_t)len * 4);
segp[nsg + 1 + 2 * s] = 0;
segp[nsg + 1 + 2 * s + 1] = len;
segp[nsg + 1 + 2 * nsg + s] = a;
}
reg_[R_SRC].used = P * 4;
reg_[R_GROPE].used = 3 * P * 4;
reg_[R_SEG].used = (4 * nsg + 1) * 4;
const std::vector<int32_t>& bt = kv_->block_table(c.seq, kv_group_);
int32_t* slot = hptr<int32_t>(R_SLOT);
for (int64_t p = 0; p < P; ++p) {
const int64_t bi = p / block_size_;
slot[p] = bi < (int64_t)bt.size() ? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_)
: -1;
}
reg_[R_SLOT].used = P * 4;
int32_t* btab = hptr<int32_t>(R_BT);
for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i];
reg_[R_BT].used = (int64_t)bt.size() * 4;
hptr<int32_t>(R_USED)[0] = (int32_t)P;
reg_[R_USED].used = 4;
/* The pictures again, for the generator's own encoder, and with a mask the picture being
* repainted -- only the positive conditioning's pass writes the lanes. */
const int64_t ch = decl_.pixel_channels;
uint16_t* px = hptr<uint16_t>(R_PX);
std::vector<int32_t> pxh;
int64_t at = 0;
for (const Pixels& p : r.refs) {
std::memcpy(px + at * ch, p.bf16.data(), (size_t)((int64_t)p.w * p.h * ch) * 2);
pxh.insert(pxh.end(), { (int32_t)at, p.h, p.w });
at += (int64_t)p.w * p.h;
}
const bool inp = r.inpaint && branch == 0;
if (inp) {
const Pixels& p = r.inp_src;
std::memcpy(px + at * ch, p.bf16.data(), (size_t)((int64_t)p.w * p.h * ch) * 2);
pxh.insert(pxh.end(), { (int32_t)at, p.h, p.w });
at += (int64_t)p.w * p.h;
std::memcpy(hptr<float>(R_MASK), r.inp_mask.data(), r.inp_mask.size() * 4);
reg_[R_MASK].used = (int64_t)r.inp_mask.size() * 4;
}
reg_[R_PX].used = at * ch * 2;
/* Each picture's latent tokens as a cu pair, after the segments' arrays. */
const int64_t npx = (int64_t)pxh.size() / 3;
int32_t* pxcu = hptr<int32_t>(R_SEG) + 4 * nsg + 1;
for (int64_t b = 0; b < npx; ++b) {
pxcu[2 * b] = 0;
pxcu[2 * b + 1] = (pxh[(size_t)(3 * b + 1)] / (int32_t)decl_.latent_scale) *
(pxh[(size_t)(3 * b + 2)] / (int32_t)decl_.latent_scale);
}
reg_[R_SEG].used = (4 * nsg + 1 + 2 * npx) * 4;
/* The conditioning is modulated at t = 0. */
hptr<float>(R_SIG)[0] = 0.0f;
reg_[R_SIG].used = 4;
/* The host arrays the plugin reads on the host: the segments' kinds, the pixel blocks and the
* lanes. Kept here, in the driver, for the life of the pass. */
host_bidi_ = c.lay.bidi;
host_px_ = pxh;
host_lanes_ = inp ? j.lanes : std::vector<int32_t>{};
/* ...and the lanes on the device too: the repainted picture's latent and mask are copied into
* each of them by an op. */
if (!host_lanes_.empty()) {
std::memcpy(hptr<int32_t>(R_LANE), host_lanes_.data(), host_lanes_.size() * 4);
reg_[R_LANE].used = (int64_t)host_lanes_.size() * 4;
}
if (upload() < 0) return nullptr;
finish_batches(T, 1, (int32_t)T, step);
for (size_t rr = 0; rr < ranks_.size(); ++rr) {
RadBatch& B = out_[rr];
RadGenBatch& G = gout_[rr];
const int ri = (int)rr;
B.max_ctx_len = (int32_t)P;
B.rope_pos = dptr<int32_t>(ri, R_ROPE);
B.rope_mixed = br.media ? 1 : 0;
B.n_mm_rows = n_mm;
B.mm_rows = n_mm ? dptr<int32_t>(ri, R_MMROW) : nullptr;
B.mm_embd = nullptr;
B.enc = 0;
B.enc_n_patch = n_patch;
B.enc_pixels = n_patch ? dptr<uint16_t>(ri, R_ENCPIX) : nullptr;
B.enc_coord = n_patch ? dptr<int32_t>(ri, R_ENCCRD) : nullptr;
B.enc_n_seg = n_seg;
B.enc_cu = n_seg ? dptr<int32_t>(ri, R_ENCCU) : nullptr;
B.enc_max_seg = max_seg;
B.gen = RAD_GEN_PASS_COND;
kout_[rr].block_table_pitch = (int64_t)bt.size();
G = RadGenBatch{};
G.rows = P;
G.src = dptr<int32_t>(ri, R_SRC);
G.rope = dptr<int32_t>(ri, R_GROPE);
G.n_seg = nsg;
G.seg = dptr<int32_t>(ri, R_SEG);
G.seg_h = hptr<int32_t>(R_SEG);
G.seg_bidi_h = host_bidi_.data();
G.seg_cu = dptr<int32_t>(ri, R_SEG) + nsg + 1;
G.seg_start = dptr<int32_t>(ri, R_SEG) + nsg + 1 + 2 * nsg;
G.slot_mapping = dptr<int32_t>(ri, R_SLOT);
G.n_px = (int64_t)pxh.size() / 3;
G.px = at ? dptr<uint16_t>(ri, R_PX) : nullptr;
G.px_h = host_px_.data();
G.px_cu = dptr<int32_t>(ri, R_SEG) + 4 * nsg + 1;
G.sigma = dptr<float>(ri, R_SIG);
G.inpaint = inp ? 1 : 0;
G.inp_mask = inp ? dptr<float>(ri, R_MASK) : nullptr;
G.n_lane = (int64_t)host_lanes_.size();
G.lane_h = host_lanes_.data();
G.lane = G.n_lane ? dptr<int32_t>(ri, R_LANE) : nullptr;
}
pass_.kind = RAD_GEN_PASS_COND;
pass_.job = j.id;
pass_.branch = branch;
return &out_[0];
}
const RadBatch* Driver::build_denoise(const std::vector<int32_t>& take, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
/* Two passes over the images: the entries and their rows, then the per-entry arrays. */
struct E { const Job* j; int32_t lane; int branch; };
std::vector<E> es;
for (int32_t l : take) {
const Job* j = nullptr;
for (auto& jp : jobs_) if (jp->id == lanes_[(size_t)l].job_id) { j = jp.get(); break; }
if (!j) continue;
for (int b = 0; b < j->n_branch; ++b) es.push_back({ j, l, b });
}
const int64_t S = (int64_t)es.size();
int64_t n_tok = 0;
int32_t max_q = 0, max_ctx = 0;
int64_t pitch = 1;
for (const E& e : es) {
n_tok += e.j->tokens;
max_q = std::max<int32_t>(max_q, (int32_t)e.j->tokens);
max_ctx = std::max<int32_t>(max_ctx, (int32_t)e.j->cond[e.branch].lay.rows);
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq, kv_group_).size());
}
int32_t* cu = hptr<int32_t>(R_CU);
int32_t* pos = hptr<int32_t>(R_POS);
int32_t* tok = hptr<int32_t>(R_TOK);
int32_t* grope = hptr<int32_t>(R_GROPE);
float* sig = hptr<float>(R_SIG);
float* sign = hptr<float>(R_SIGN);
float* cfg = hptr<float>(R_CFG);
int32_t* pair = hptr<int32_t>(R_PAIR);
int32_t* lane = hptr<int32_t>(R_LANE);
int32_t* flags = hptr<int32_t>(R_FLAGS);
uint32_t* seed = hptr<uint32_t>(R_SEED);
int32_t* btab = hptr<int32_t>(R_BT);
int32_t* used = hptr<int32_t>(R_USED);
int64_t row = 0;
cu[0] = 0;
pass_.lanes.clear();
pass_.marks.clear();
for (int64_t i = 0; i < S; ++i) {
const E& e = es[(size_t)i];
const Job& j = *e.j;
const Lane& ln = lanes_[(size_t)e.lane];
const Cond& c = j.cond[e.branch];
const int64_t N = j.tokens;
for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; }
for (int cc = 0; cc < 3; ++cc)
std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4);
row += N;
cu[i + 1] = (int32_t)row;
sig[i] = j.sigmas[(size_t)ln.step];
sign[i] = j.sigmas[(size_t)ln.step + 1];
const bool neg = e.branch == 1;
cfg[i] = neg ? 0.0f : (j.n_branch > 1 ? j.req->cfg : 1.0f);
pair[i] = neg ? -2 : (j.n_branch > 1 ? (int32_t)(i + 1) : -1);
lane[i] = e.lane;
int32_t f = 0;
bool mark = false;
if (!neg) {
if (ln.step == 0) f |= RAD_GEN_F_FIRST;
if (j.req->inpaint) f |= RAD_GEN_F_INPAINT;
if (ln.previews_done < (int32_t)ln.preview_at.size() &&
ln.step + 1 == ln.preview_at[(size_t)ln.previews_done]) {
f |= RAD_GEN_F_PREVIEW;
mark = true;
}
pass_.lanes.push_back(e.lane);
pass_.marks.push_back(mark ? 1 : 0);
}
flags[i] = f;
seed[2 * i] = (uint32_t)(ln.seed & 0xffffffffu);
seed[2 * i + 1] = (uint32_t)(ln.seed >> 32);
const std::vector<int32_t>& bt = kv_->block_table(c.seq, kv_group_);
for (int64_t b = 0; b < pitch; ++b)
btab[i * pitch + b] = b < (int64_t)bt.size() ? bt[(size_t)b] : -1;
used[i] = (int32_t)c.lay.rows;
}
reg_[R_CU].used = (S + 1) * 4;
reg_[R_POS].used = reg_[R_TOK].used = n_tok * 4;
reg_[R_GROPE].used = 3 * n_tok * 4;
reg_[R_SIG].used = reg_[R_SIGN].used = reg_[R_CFG].used = S * 4;
reg_[R_PAIR].used = reg_[R_LANE].used = reg_[R_FLAGS].used = S * 4;
reg_[R_SEED].used = 2 * S * 4;
reg_[R_BT].used = S * pitch * 4;
reg_[R_USED].used = S * 4;
if (upload() < 0) return nullptr;
finish_batches(n_tok, S, max_q, step);
for (size_t rr = 0; rr < ranks_.size(); ++rr) {
RadBatch& B = out_[rr];
const int ri = (int)rr;
B.max_ctx_len = max_ctx;
B.rope_pos = nullptr;
B.rope_mixed = 0;
B.n_mm_rows = 0;
B.mm_rows = nullptr;
B.enc_n_patch = 0;
B.enc_pixels = nullptr;
B.enc_coord = nullptr;
B.enc_n_seg = 0;
B.enc_cu = nullptr;
B.gen = RAD_GEN_PASS_DENOISE;
kout_[rr].block_table_pitch = pitch;
kout_[rr].slot_mapping = nullptr;
RadGenBatch& G = gout_[rr];
G.rows = 0;
G.n_seg = 0;
G.seg_bidi_h = nullptr;
G.n_px = 0;
G.px_h = nullptr;
G.inpaint = 0;
G.n_lane = 0;
G.lane_h = nullptr;
G.rope = dptr<int32_t>(ri, R_GROPE);
G.lane_dh = hptr<int32_t>(R_LANE);
}
pass_.kind = RAD_GEN_PASS_DENOISE;
return &out_[0];
}
const RadBatch* Driver::build_decode(int32_t l, bool preview, int step) {
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
const Lane& ln = lanes_[(size_t)l];
const Job* j = nullptr;
for (auto& jp : jobs_) if (jp->id == ln.job_id) { j = jp.get(); break; }
if (!j) return nullptr;
int32_t* cu = hptr<int32_t>(R_CU);
cu[0] = 0;
cu[1] = (int32_t)j->tokens;
reg_[R_CU].used = 2 * 4;
if (upload() < 0) return nullptr;
finish_batches(j->tokens, 1, (int32_t)j->tokens, step);
for (size_t rr = 0; rr < ranks_.size(); ++rr) {
RadBatch& B = out_[rr];
B.max_ctx_len = 0;
B.rope_pos = nullptr;
B.rope_mixed = 0;
B.n_mm_rows = 0;
B.mm_rows = nullptr;
B.enc_n_patch = 0;
B.enc_pixels = nullptr;
B.enc_coord = nullptr;
B.enc_n_seg = 0;
B.enc_cu = nullptr;
B.gen = RAD_GEN_PASS_DECODE;
B.n_kv_groups = 0;
B.kv = nullptr;
RadGenBatch& G = gout_[rr];
G = RadGenBatch{};
G.dec_lane = l;
G.dec_height = j->req->height;
G.dec_width = j->req->width;
G.dec_preview = preview ? 1 : 0;
}
dec_bytes_ = (int64_t)j->req->width * j->req->height * decl_.pixel_channels;
pass_.kind = RAD_GEN_PASS_DECODE;
pass_.job = j->id;
pass_.lane = l;
pass_.preview = preview;
return &out_[0];
}
int Driver::done() {
std::lock_guard<std::mutex> lk(mu_);
const uint64_t now = rad_mono_ns();
switch (pass_.kind) {
case RAD_GEN_PASS_COND: {
Job* j = job_locked(pass_.job);
if (!j) break;
j->cond[pass_.branch].encoded = true;
bool all = true;
for (int b = 0; b < j->n_branch; ++b) all = all && j->cond[b].encoded;
if (all) j->req->ticket->t_cond_ns = (int64_t)now;
break;
}
case RAD_GEN_PASS_DENOISE:
for (size_t i = 0; i < pass_.lanes.size(); ++i) {
Lane& ln = lanes_[(size_t)pass_.lanes[i]];
Job* j = job_locked(ln.job_id);
if (!j) continue;
if (ln.step == 0 && j->req->ticket->t_first_step_ns == 0)
j->req->ticket->t_first_step_ns = (int64_t)now;
++ln.step;
const int32_t n_steps = (int32_t)j->sigmas.size() - 1;
if (pass_.marks[i]) ln.preview_due = true;
if (ln.step >= n_steps) {
ln.final_due = true;
j->req->ticket->t_denoised_ns = (int64_t)now;
}
}
break;
case RAD_GEN_PASS_DECODE: {
Lane& ln = lanes_[(size_t)pass_.lane];
Job* j = job_locked(pass_.job);
if (!j) break;
Image im;
im.index = ln.index;
im.w = j->req->width;
im.h = j->req->height;
im.ch = (int32_t)decl_.pixel_channels;
im.seed = ln.seed;
im.px.assign((const uint8_t*)img_host_, (const uint8_t*)img_host_ + dec_bytes_);
if (pass_.preview) {
im.preview = true;
im.preview_no = ln.previews_done;
ln.preview_due = false;
++ln.previews_done;
} else {
ln.final_due = false;
ln.finished = true;
++j->images_done;
}
j->req->ticket->push(std::move(im));
if (j->images_done >= j->req->n) {
j->req->ticket->t_done_ns = (int64_t)now;
j->req->ticket->finish(RAD_OK);
}
break;
}
default:
break;
}
pass_ = Pass{};
dec_bytes_ = 0;
return RAD_OK;
}
} /* namespace gen */
} /* namespace rad */
+186
View File
@@ -0,0 +1,186 @@
/* driver.h -- the image generator's pass driver (gen.h says what the passes are).
*
* ONE THREAD DRIVES IT, the engine's, and it asks two things a pass: `next()` decides what runs
* and stages it, `done()` folds the result back once every rank has run it. Requests arrive from
* HTTP threads through `submit()` and leave through their Ticket; the queue is the only thing the
* two kinds of thread share, behind one mutex.
*
* WHAT RUNS NEXT, in this order, one pass at a time:
*
* 1. a DECODE an image is owed -- a finished image, or a preview its last step marked. First,
* because a finished image frees its lane and answers its caller, and a preview must be read
* before the lane's next step writes the preview latent again.
* 2. a COND an admitted request is owed: its conditioning, so its images can join the next
* denoise pass.
* 3. a DENOISE over as many images in flight as fit the step's rows, oldest request first, each
* at its own step.
*
* A request is ADMITTED when it can get lanes for every image and KV for every conditioning
* sequence; until then it waits, in order -- a request that does not fit blocks the ones behind
* it, so a large request is not starved by a stream of small ones.
*
* THE STAGING is one region per rank on its card and one pinned host region with the same layout.
* Every pass is synchronised before the next is built (Engine::gen_loop), so one host region is
* enough: an image pass is tens of milliseconds and more, and the host work between two is
* microseconds.
*/
#pragma once
#include "gen.h"
#include "device/device.h"
#include <mutex>
#include <unordered_map>
namespace rad {
namespace gen {
class Driver {
public:
struct RankIO {
int device = 0;
RadStream stream = nullptr;
};
/* `kv` is rank 0's KV manager: one block table serves every rank. */
int init(const Program& prog, const Config& cfg, IKVManager* kv, const std::vector<RankIO>& ranks);
void fini();
~Driver() { fini(); }
/* The bytes init() allocates on each rank's card, for the VRAM budget. */
static int64_t device_bytes(const Program& prog, const Config& cfg);
/* ---------------------------------------------------------- HTTP threads */
/* Queue a request. Refused at once -- with `why` -- when it can never run: a size past the
* largest image, more pictures than the model takes, a conditioning longer than a pass. */
int submit(std::unique_ptr<Request> r, std::string* why);
/* What a request may ask for: the model's own limits, for the server to check before it does
* the expensive part of preparing one. */
const RadGeneratorDecl& decl() const { return decl_; }
const std::vector<double>& fixed_sigmas() const { return fixed_; }
int64_t max_cond_tokens() const { return max_tok_; }
/* Fail every request queued or in flight, and refuse new ones. */
void shutdown(const char* why, int status);
/* ---------------------------------------------------------- the engine thread */
/* The next pass, staged on every rank's stream, or null when there is nothing to run.
* `step` is the engine's pass counter, carried into RadBatch::step. */
const RadBatch* next(int step);
const RadBatch* batch_for(int rank) const;
/* The bytes of the generator's image buffer the pass just staged makes, 0 for a pass that
* makes none: the engine copies them to `host()` behind the pass. */
int64_t decode_bytes() const { return dec_bytes_; }
void* host_image() const { return img_host_; }
/* The pass has run on every rank and its streams are drained. */
int done();
bool busy() const;
/* For /health, /stats and the dashboard. */
int64_t queued() const;
int64_t running() const;
private:
struct Cond {
Layout lay;
uint64_t seq = 0; /* the KV manager's key */
bool have_kv = false;
bool encoded = false;
std::vector<int32_t> rope_img; /* [3, image tokens]: the image's rows at this sequence */
};
struct Job {
uint64_t id = 0;
std::unique_ptr<Request> req;
int n_branch = 1;
Cond cond[2];
int32_t h_lat = 0, w_lat = 0;
int64_t tokens = 0;
std::vector<float> sigmas;
std::vector<int32_t> lanes;
std::vector<std::pair<int32_t, int32_t>> ref_hw;
int32_t images_done = 0;
bool admitted = false;
bool failed = false;
};
struct Lane {
int64_t job = -1; /* index into jobs_ by id; -1 free */
uint64_t job_id = 0;
int32_t index = 0;
int32_t step = 0;
uint64_t seed = 0;
std::vector<int32_t> preview_at; /* the steps after which a preview is decoded */
int32_t previews_done = 0;
bool preview_due = false;
bool final_due = false;
bool finished = false;
};
/* What the pass being run is, for done(). */
struct Pass {
int kind = 0;
uint64_t job = 0;
int branch = 0;
int32_t lane = -1;
bool preview = false;
std::vector<int32_t> lanes; /* DENOISE: the lanes it stepped, one per image */
std::vector<char> marks; /* ... and whether each was marked for a preview */
};
/* Staging regions: their offsets in the host span and every rank's slab. */
struct Region { int64_t off = 0, bytes = 0, used = 0; };
enum { R_TOK, R_POS, R_ROPE, R_CU, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_SRC, R_GROPE,
R_SEG, R_SLOT, R_PX, R_MASK, R_SIG, R_SIGN, R_CFG, R_PAIR, R_LANE, R_FLAGS, R_SEED,
R_BT, R_USED, R_N };
int layout_regions();
template <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
template <class T> T* dptr(int rank, int r) const {
return reinterpret_cast<T*>((char*)dev_[(size_t)rank] + reg_[r].off);
}
int upload();
void finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int step);
int admit_locked();
void release_locked(Job& j);
void fail_locked(Job& j, int status, const std::string& why);
Job* job_locked(uint64_t id);
const RadBatch* build_cond(Job& j, int branch, int step);
const RadBatch* build_denoise(const std::vector<int32_t>& lanes, int step);
const RadBatch* build_decode(int32_t lane, bool preview, int step);
RadGeneratorDecl decl_{};
std::vector<double> fixed_;
int64_t max_tok_ = 0, max_seqs_ = 0, max_enc_ = 0, patch_dim_ = 0;
int64_t max_rows_ = 0; /* the longest conditioning sequence */
int64_t max_px_ = 0; /* pixels the staging holds */
int64_t block_size_ = 0, max_blocks_ = 0;
int32_t kv_group_ = 0;
std::vector<RankIO> ranks_;
IKVManager* kv_ = nullptr;
char* host_ = nullptr; /* pinned, same layout as each slab */
int64_t bytes_ = 0;
std::vector<void*> dev_;
Region reg_[R_N];
void* img_host_ = nullptr;
int64_t img_bytes_ = 0;
int64_t dec_bytes_ = 0;
std::vector<RadBatch> out_; /* one per rank */
std::vector<RadGenBatch> gout_;
std::vector<RadKVGroupBatch> kout_;
Pass pass_;
/* The host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */
std::vector<int32_t> host_bidi_, host_px_, host_lanes_;
mutable std::mutex mu_;
std::deque<std::unique_ptr<Job>> jobs_; /* arrival order */
std::vector<Lane> lanes_;
std::vector<int32_t> free_lanes_;
uint64_t next_id_ = 1;
uint64_t next_seq_ = 1;
bool closed_ = false;
std::string closed_why_;
int closed_status_ = RAD_E_STATE;
};
} /* namespace gen */
} /* namespace rad */
+213
View File
@@ -0,0 +1,213 @@
/* gen.cpp -- the request side of image generation: the ticket a caller waits on, the sampler's
* schedule, and the generator's sequence built from a conditioning prompt (gen.h). */
#include "gen.h"
#include <chrono>
#include <cmath>
#include <cstring>
namespace rad {
namespace gen {
/* ================================================================== the ticket */
void Ticket::push(Image&& im) {
{
std::lock_guard<std::mutex> lk(mu_);
q_.push_back(std::move(im));
}
cv_.notify_all();
}
void Ticket::finish(int status, const std::string& why) {
{
std::lock_guard<std::mutex> lk(mu_);
if (done_) return;
done_ = true;
status_ = status;
why_ = why;
}
cv_.notify_all();
}
void Ticket::step(int32_t done, int32_t total) {
(void)done;
(void)total;
}
bool Ticket::next(Image* out, int ms, bool* timed_out) {
std::unique_lock<std::mutex> lk(mu_);
if (timed_out) *timed_out = false;
if (q_.empty() && !done_)
cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return !q_.empty() || done_; });
if (!q_.empty()) {
*out = std::move(q_.front());
q_.pop_front();
return true;
}
if (!done_ && timed_out) *timed_out = true;
return false;
}
bool Ticket::finished() const {
std::lock_guard<std::mutex> lk(mu_);
return done_ && q_.empty();
}
int Ticket::status() const {
std::lock_guard<std::mutex> lk(mu_);
return status_;
}
std::string Ticket::why() const {
std::lock_guard<std::mutex> lk(mu_);
return why_;
}
/* ================================================================== the schedule */
/* diffusers' FlowMatchEulerDiscreteScheduler.set_timesteps with explicit sigmas, as the pipeline
* calls it, in the precision it runs at: the sigmas are an f32 array and every shift is numpy f32
* arithmetic, the Python floats in it (exp(mu), the shift, the terminal) taking the array's type. */
std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>& fixed,
int32_t steps, int64_t tokens) {
std::vector<float> s;
if (!fixed.empty()) {
for (double v : fixed) s.push_back((float)v);
} else {
const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps;
/* np.linspace(1.0, 1 / n, n) in f64, then astype(f32). */
const double lo = 1.0 / (double)n;
for (int32_t i = 0; i < n; ++i) {
const double v = n == 1 ? 1.0 : 1.0 + (lo - 1.0) * (double)i / (double)(n - 1);
s.push_back((float)v);
}
}
if (d.dyn_shift) {
const double m = (d.max_shift - d.base_shift) / (double)(d.max_seq - d.base_seq);
const double b = d.base_shift - m * (double)d.base_seq;
const double mu = (double)tokens * m + b;
const float e = d.shift_exp ? (float)std::exp(mu) : (float)mu;
for (float& t : s) t = e / (e + (1.0f / t - 1.0f));
} else {
const float sh = (float)d.shift;
for (float& t : s) t = sh * t / (1.0f + (sh - 1.0f) * t);
}
if (d.shift_terminal > 0 && !s.empty()) {
const float scale = (1.0f - s.back()) / (float)(1.0 - d.shift_terminal);
for (float& t : s) t = 1.0f - ((1.0f - t) / scale);
}
s.push_back(0.0f);
return s;
}
/* ================================================================== the sequence */
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total) {
const int32_t h0 = -(h - h / 2), w0 = -(w - w / 2);
int64_t k = 0;
for (int32_t r = 0; r < h; ++r)
for (int32_t c = 0; c < w; ++c, ++k) {
planes[k] = pos;
planes[n_total + k] = h0 + r;
planes[2 * n_total + k] = w0 + c;
}
}
int build_layout(const Branch& b, int64_t slot_rows,
const std::vector<std::pair<int32_t, int32_t>>& ref_hw, Layout* out,
std::string* why) {
*out = Layout{};
const int64_t T = (int64_t)b.tokens.size();
if (b.n_drop < 0 || b.n_drop >= T) {
if (why) *why = "the conditioning prompt is no longer than its fixed prefix";
return RAD_E_INVAL;
}
/* The media runs, in prompt order: [tok, tok + n) placeholder rows of item `item`. */
struct Run { int64_t tok, n; int32_t item; };
std::vector<Run> runs;
if (b.media)
for (const mm::RopeLayout::Run& r : b.media->rope.runs)
runs.push_back({ r.tok, r.n, r.item });
if (runs.size() != ref_hw.size()) {
if (why) *why = "the prompt places " + std::to_string(runs.size()) + " picture(s) and " +
std::to_string(ref_hw.size()) + " were encoded for it";
return RAD_E_INVAL;
}
/* Each picture's rows and where its latent rows start among all the references'. */
std::vector<int64_t> lat0(ref_hw.size() + 1, 0);
for (size_t i = 0; i < ref_hw.size(); ++i)
lat0[i + 1] = lat0[i] + (int64_t)ref_hw[i].first * ref_hw[i].second;
int64_t rows = 0;
{
int64_t text = T - b.n_drop;
for (const Run& r : runs) {
if (r.tok < b.n_drop) {
if (why) *why = "a picture sits inside the prompt's fixed prefix";
return RAD_E_INVAL;
}
text -= r.n;
}
rows = text;
for (size_t i = 0; i < runs.size(); ++i) {
const int64_t lat = (int64_t)ref_hw[i].first * ref_hw[i].second;
if (runs[i].n * slot_rows != lat) {
if (why) *why = "picture " + std::to_string(i + 1) + " has " +
std::to_string(runs[i].n) + " encoder rows, which do not tile its " +
std::to_string(ref_hw[i].first) + " x " +
std::to_string(ref_hw[i].second) + " latent grid";
return RAD_E_INVAL;
}
rows += lat;
}
}
out->rows = rows;
out->src.assign((size_t)rows, 0);
out->rope.assign((size_t)rows * 3, 0);
out->seg.push_back(0);
int32_t pos = 0;
int64_t row = 0;
size_t ri = 0;
int64_t t = b.n_drop;
bool in_text = false;
auto close_text = [&]() {
if (in_text) {
out->seg.push_back((int32_t)row);
out->bidi.push_back(0);
in_text = false;
}
};
while (t < T) {
if (ri < runs.size() && t == runs[ri].tok) {
close_text();
const int32_t h = ref_hw[ri].first, w = ref_hw[ri].second;
const int64_t n = (int64_t)h * w;
for (int64_t k = 0; k < n; ++k) out->src[(size_t)(row + k)] = -(int32_t)(1 + lat0[ri] + k);
std::vector<int32_t> pl((size_t)n * 3);
image_rope(pos, h, w, pl.data(), n);
for (int c = 0; c < 3; ++c)
std::memcpy(&out->rope[(size_t)(c * rows + row)], &pl[(size_t)(c * n)],
(size_t)n * sizeof(int32_t));
pos += h > w ? h : w;
row += n;
out->seg.push_back((int32_t)row);
out->bidi.push_back(1);
t += runs[ri].n;
++ri;
continue;
}
in_text = true;
out->src[(size_t)row] = (int32_t)t;
for (int c = 0; c < 3; ++c) out->rope[(size_t)(c * rows + row)] = pos;
++pos;
++row;
++t;
}
close_text();
out->next_pos = pos;
if (row != rows) {
if (why) *why = "the generator's sequence did not come out at the length it was sized for";
return RAD_E_STATE;
}
return RAD_OK;
}
} /* namespace gen */
} /* namespace rad */
+145
View File
@@ -0,0 +1,145 @@
/* gen.h -- image generation: what a request is, what comes back, and the driver that turns one
* into the passes an image generator declares (rad_declare_generator, abi/rad_builder.h).
*
* A GENERATOR IS NOT DRIVEN BY TOKEN STEPS. Its work is three kinds of pass -- conditioning,
* denoising, decoding -- and an image is tens of denoising passes over thousands of latent rows,
* every one of them read whole, none of them sampled. The scheduler that serves text owns token
* positions, prefix reuse, preemption and speculation, and none of that has a meaning here, so the
* generator gets a driver of its own (this file) and shares everything below the step with the rest
* of the engine: the ranks, the plugin's step function, the KV manager the conditioning lives in.
*
* THE PASSES, as the driver runs them:
*
* COND once for every conditioning sequence a request has -- its prompt, and with guidance
* its negative prompt -- the prompt (and its reference pictures) encoded into the
* generator's KV group. A request is admitted once its lanes and its KV are free.
* DENOISE one step for each image in flight that fits the pass, any mix of requests, sizes and
* step counts: each image carries its own sigma. With guidance an image is two entries,
* its positive and its negative conditioning, which the plugin combines.
* DECODE one image's latent to pixels, read back and handed to its request.
*
* A request's images run in LANES -- the plugin's own latent state, `max_lanes` of them -- so one
* request of n images takes n lanes and shares one conditioning.
*/
#pragma once
#include "rad_core.h"
#include "mm/processor.h"
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
struct IKVManager;
namespace gen {
/* A picture as the generator's own encoder reads it: RGBA (or `ch` channels), row-major, each value
* bf16 in [-1, 1]. */
struct Pixels {
int32_t w = 0, h = 0, ch = 4;
std::vector<uint16_t> bf16;
};
/* ONE CONDITIONING SEQUENCE: the prompt as tokens, with the media it carries placed, and how many
* of its first tokens the generator does not see (RadGeneratorDecl::drop_prefix). */
struct Branch {
std::vector<int32_t> tokens;
std::shared_ptr<mm::PromptMedia> media; /* null for a prompt with no pictures */
int32_t n_drop = 0;
};
/* ONE IMAGE, or one preview of one, on its way back. */
struct Image {
int32_t index = 0; /* which of the request's n */
int32_t w = 0, h = 0, ch = 4;
std::vector<uint8_t> px; /* [h, w, ch] */
bool preview = false;
int32_t preview_no = 0;
uint64_t seed = 0;
};
/* THE CHANNEL BACK TO THE CALLER: images as they finish, then the end. The driver's thread writes,
* the caller's reads; a mutex is enough -- an image is megabytes and there are a handful a
* request. `cancel` is the caller's, read by the driver at its next pass. */
class Ticket {
public:
/* driver side */
void push(Image&& im);
void finish(int status, const std::string& why = std::string());
void step(int32_t done, int32_t total);
/* caller side: the next image, or false once the request has ended and every image was taken.
* Waits at most `ms` milliseconds; `*timed_out` says a false was a timeout, not the end. */
bool next(Image* out, int ms, bool* timed_out);
bool finished() const;
int status() const;
std::string why() const;
std::atomic<bool> cancel{false};
/* What the request cost, for the response: the conditioning's tokens, the latent rows made, and
* the time each phase took. Written by the driver before finish(). */
int64_t in_tokens = 0, out_tokens = 0;
int64_t t_submit_ns = 0, t_cond_ns = 0, t_first_step_ns = 0, t_denoised_ns = 0, t_done_ns = 0;
int32_t steps = 0;
private:
mutable std::mutex mu_;
std::condition_variable cv_;
std::deque<Image> q_;
bool done_ = false;
int status_ = RAD_OK;
std::string why_;
};
struct Request {
Branch pos, neg;
bool has_neg = false;
float cfg = 1.0f;
int32_t width = 0, height = 0; /* pixels, whole multiples of the declared multiple */
int32_t steps = 0; /* 0: the model's default (or its fixed schedule) */
int32_t n = 1;
uint64_t seed = 0; /* image i draws its noise from seed + i */
int32_t previews = 0; /* partial images per image, 0..3 */
/* The reference pictures' encoder view, one per media item of `pos`, in order. */
std::vector<Pixels> refs;
/* REPAINTING (an edit with a mask): the picture at the size being made, and per latent token
* how much of it is repainted (1) and how much kept (0). */
bool inpaint = false;
Pixels inp_src;
std::vector<float> inp_mask;
std::shared_ptr<Ticket> ticket;
};
/* ================================================================== the sampler's schedule */
/* The sigmas a request steps through, n + 1 of them, the last 0: the decl's fixed schedule, or
* `steps` (0: the default) shifted the way the decl says. `tokens` is the image's latent token
* count, which a dynamic shift reads. f32, as the reference holds them. */
std::vector<float> schedule(const RadGeneratorDecl& d, const std::vector<double>& fixed,
int32_t steps, int64_t tokens);
/* ================================================================== the generator's sequence */
/* ONE CONDITIONING SEQUENCE AS THE GENERATOR SEES IT (RadGeneratorDecl::layout): which prompt row
* or reference latent row each of its rows is, its rotary positions, its segments, and where the
* image being made starts. */
struct Layout {
int64_t rows = 0;
std::vector<int32_t> src; /* [rows] */
std::vector<int32_t> rope; /* [3, rows] component-major */
std::vector<int32_t> seg; /* [n_seg + 1] */
std::vector<int32_t> bidi; /* [n_seg] */
int32_t next_pos = 0; /* the rotary count after the last row: the image's frame */
};
/* `ref_hw` is each reference's latent grid (h, w), in media order. RAD_E_INVAL with `why` when the
* prompt does not start with its drop prefix or a picture's slots do not tile its latent grid. */
int build_layout(const Branch& b, int64_t slot_rows, const std::vector<std::pair<int32_t, int32_t>>& ref_hw,
Layout* out, std::string* why);
/* The rotary positions of an h x w image at frame `pos`: [3, h * w] component-major. */
void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total);
} /* namespace gen */
} /* namespace rad */
+23
View File
@@ -41,6 +41,29 @@ std::string GenSampling::describe(const SamplingParams& sp) {
return buf;
}
std::vector<GenFieldSource> gen_sampling_sources(const GenSampling& stated, const std::string& src,
const SamplingParams& served, const Config& cfg) {
std::vector<GenFieldSource> out;
auto field = [&](const char* flag, const char* name, bool given, bool said, std::string value) {
if (given) return; /* the option's own row says "command line" */
std::string why = said ? "from " + src
: src.empty() ? std::string("the model states no sampling of its own, so "
"this is the built-in default")
: src + " states no " + name +
", so this is the built-in default";
out.push_back({ flag, std::move(value), std::move(why) });
};
field("--temp", "temperature", cfg.sample_temp >= 0.0f, stated.temp >= 0.0f,
fmt("%g", (double)served.temp));
field("--top-k", "top_k", cfg.sample_top_k >= 0, stated.top_k >= 0,
std::to_string(served.top_k));
field("--top-p", "top_p", cfg.sample_top_p >= 0.0f, stated.top_p >= 0.0f,
fmt("%g", (double)served.top_p));
field("--min-p", "min_p", cfg.sample_min_p >= 0.0f, stated.min_p >= 0.0f,
fmt("%g", (double)served.min_p));
return out;
}
bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampling* out) {
nlohmann::json j;
try { j = nlohmann::json::parse(json_text); }
+11
View File
@@ -25,6 +25,7 @@
#include <functional>
#include <string>
#include <vector>
namespace rad {
@@ -49,6 +50,16 @@ struct GenSampling {
static std::string describe(const SamplingParams& sp);
};
/* WHERE EACH OF THE FOUR FIELDS SERVED CAME FROM, for the startup report (core/diag/diag.h): one
* entry a field no flag set, with the option that would have set it, the value served and why.
* `stated` is what the source in force read and `src` that source's name ("" for none). A source
* can state some fields and not others -- a generation_config.json with a temperature and no
* top_k -- and a field it left out is served SamplingParams' own value, so the reason is per field:
* one reason for all four would name the file for values that never came from it. */
struct GenFieldSource { std::string flag, value, why; };
std::vector<GenFieldSource> gen_sampling_sources(const GenSampling& stated, const std::string& src,
const SamplingParams& served, const Config& cfg);
/* Parse the sampler fields out of generation_config.json TEXT. `src` names the origin in any
* warning. Returns whether anything was taken. Unparseable text warns and takes nothing. */
bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampling* out);
+167
View File
@@ -0,0 +1,167 @@
/* hf_model.cpp -- resolve a --model that is a Hugging Face repo id (hf_model.h).
*
* The entry point (main.cpp) calls resolve_hf_model() once, between config_parse and the Engine,
* and the rest of bring-up sees a plain file or directory. The fetching is scripts/hfget.sh (curl
* and jq, no Python), run as a child process; it is installed to libexec/radiance/ and the build
* copies it to the same place under the build tree, so it is found beside the binary either way.
*
* WHERE IT GOES. Not under $RADIANCE_HOME: that is a ':'-separated search path for plugins, and
* its default is the install's share/ directory, which a user cannot write. A model is a cache --
* the XDG cache directory by default, --download-dir (vLLM's name) to put it on another disk.
*
* A HUB THAT CANNOT BE REACHED DOES NOT STOP A RESTART. hfget.sh exits 3 when it changed nothing
* on disk (the listing failed, or an update does not fit), and the copy a complete fetch left --
* marked by the manifest it writes only on success -- is then served with a warning. Any other
* failure may have left a file half-transferred, so it is not served. */
#include "hf_model.h"
#include "rad_internal.h"
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <string>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
namespace rad {
namespace fs = std::filesystem;
namespace {
bool repo_part(const std::string& p) {
if (p.empty() || p.front() == '.' || p.front() == '-') return false;
for (char ch : p) {
const bool ok = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') || ch == '.' || ch == '_' || ch == '-';
if (!ok) return false;
}
return true;
}
bool ends_with(const std::string& s, const char* suf) {
const size_t n = std::strlen(suf);
return s.size() >= n && s.compare(s.size() - n, n, suf) == 0;
}
/* <exe>/../libexec/radiance/hfget.sh, which is where the install puts it and where the build
* copies it. */
std::string hfget_path() {
char buf[4096];
const ssize_t n = readlink("/proc/self/exe", buf, sizeof buf - 1);
if (n <= 0) return std::string();
buf[n] = '\0';
const fs::path p = fs::path(buf).parent_path() / ".." / "libexec" / "radiance" / "hfget.sh";
std::error_code ec;
return fs::is_regular_file(p, ec) ? p.lexically_normal().string() : std::string();
}
/* The script's exit status, or -1 when it could not be run. */
int run_hfget(const std::string& script, const std::string& repo, const std::string& dest) {
const pid_t pid = fork();
if (pid < 0) {
RAD_ERR("hfget: fork: %s", std::strerror(errno));
return -1;
}
if (pid == 0) {
const char* argv[] = { "sh", script.c_str(), repo.c_str(), dest.c_str(), nullptr };
execv("/bin/sh", const_cast<char* const*>(argv));
std::fprintf(stderr, "hfget: /bin/sh: %s\n", std::strerror(errno));
_exit(127);
}
int status = 0;
while (waitpid(pid, &status, 0) < 0)
if (errno != EINTR) return -1;
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}
} /* namespace */
bool hf_repo_id(const std::string& s) {
std::error_code ec;
if (s.empty() || fs::exists(s, ec)) return false;
const size_t slash = s.find('/');
if (slash == std::string::npos || s.find('/', slash + 1) != std::string::npos) return false;
const std::string owner = s.substr(0, slash), name = s.substr(slash + 1);
if (!repo_part(owner) || !repo_part(name)) return false;
for (const char* suf : { ".rad", ".safetensors", ".gguf", ".json" })
if (ends_with(name, suf)) return false;
return true;
}
std::string hf_default_download_dir() {
if (const char* x = std::getenv("XDG_CACHE_HOME"); x && *x)
return std::string(x) + "/radiance/hf";
if (const char* h = std::getenv("HOME"); h && *h)
return std::string(h) + "/.cache/radiance/hf";
return std::string();
}
std::string hf_served_path(const std::string& dir, std::string* why) {
std::vector<std::string> rad;
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) && ends_with(e.path().filename().string(), ".rad"))
rad.push_back(e.path().filename().string());
}
if (ec) {
*why = dir + ": " + ec.message();
return std::string();
}
if (rad.empty()) return dir;
if (rad.size() == 1) 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 +
"); pass the one to serve as --model " + dir + "/<file>";
return std::string();
}
bool resolve_hf_model(Config& c) {
if (!hf_repo_id(c.model)) return true;
const std::string repo = c.model;
const std::string root = c.download_dir.empty() ? hf_default_download_dir() : c.download_dir;
if (root.empty()) {
RAD_ERR("--model %s: no download directory -- neither XDG_CACHE_HOME nor HOME is set; "
"name one with --download-dir", repo.c_str());
return false;
}
const std::string dest = root + "/" + repo;
std::error_code ec;
const bool cached = fs::is_regular_file(dest + "/.hfget-manifest", ec);
const std::string script = hfget_path();
if (script.empty()) {
RAD_ERR("--model %s: not a path here, and hfget.sh, which fetches a Hugging Face repo, is "
"not installed beside this binary (libexec/radiance/)", repo.c_str());
return false;
}
RAD_INFO("model: %s is not a path here; fetching it as a Hugging Face repo into %s",
repo.c_str(), dest.c_str());
const int rc = run_hfget(script, repo, dest);
if (rc != 0) {
if (rc == 3 && cached) {
RAD_WARN("model: %s could not be checked for changes (hfget.sh, above); serving the "
"copy fetched before", repo.c_str());
} else {
RAD_ERR("--model %s: not a path here, and fetching it as a Hugging Face repo failed "
"(hfget.sh exit %d, above)", repo.c_str(), rc);
return false;
}
}
std::string why;
const std::string path = hf_served_path(dest, &why);
if (path.empty()) {
RAD_ERR("--model %s: %s", repo.c_str(), why.c_str());
return false;
}
c.model = path;
RAD_INFO("model: serving %s", c.model.c_str());
return true;
}
} /* namespace rad */
+33
View File
@@ -0,0 +1,33 @@
/* hf_model.h -- a --model that names a Hugging Face repo instead of a local path.
*
* `radiance --model StillDeadcode/minicpm5-2b-fp8` fetches the repo with scripts/hfget.sh into
* the download directory and serves what it fetched: the one container at the repo's top level,
* or the directory as a checkpoint when it holds none. Every start re-checks the hub, so a
* changed file is fetched again before bring-up; a start that cannot reach the hub serves the
* copy a complete earlier fetch left. */
#pragma once
#include "rad_core.h"
#include <string>
namespace rad {
/* Is `s` a repo id ("owner/name") rather than a path? A path that exists always wins. A repo id is
* exactly two non-empty parts of [A-Za-z0-9._-], neither starting with '.' or '-', and a name that
* does not end like a model file (.rad, .safetensors, .gguf, .json): a missing local file should
* be reported as missing, not looked up on the hub. */
bool hf_repo_id(const std::string& s);
/* $XDG_CACHE_HOME/radiance/hf, else $HOME/.cache/radiance/hf; empty if neither is set. */
std::string hf_default_download_dir();
/* What to serve from a fetched repo directory: its one top-level .rad, or the directory itself (a
* checkpoint) when it holds none. Several containers are ambiguous: empty, and *why names them. */
std::string hf_served_path(const std::string& dir, std::string* why);
/* If c.model is a repo id, fetch it and point c.model at what to serve. False after an error has
* been logged. */
bool resolve_hf_model(Config& c);
} /* namespace rad */
+24 -3
View File
@@ -2,6 +2,8 @@
* a command line into that sequence and a status into an exit code.
*/
#include "engine.h"
#include "hf_model.h"
#include "util/stallwatch.h"
int main(int argc, char** argv) {
rad::Config cfg;
@@ -9,11 +11,30 @@ int main(int argc, char** argv) {
if (s == 1) { rad::config_usage(argv[0]); return 0; }
if (s < 0) { rad::config_usage(argv[0]); return 2; }
if (!rad::resolve_hf_model(cfg)) return 1; /* a repo id: fetched, and --model points at it */
rad::Engine engine(std::move(cfg));
s = engine.start();
if (s < 0) return 1; /* start() already said what and why */
{
/* A startup that stops printing says where it waits (util/stallwatch.h). Two minutes:
* the slowest normal step, a container read from a slow disk, logs well inside that. */
rad::StallWatch watch("startup", 120000);
s = engine.start();
}
if (s < 0) {
/* start() already said what and why; the report adds what it was running on and what it
* had decided by then, which is what a log of a server that never came up is read for. */
engine.print_startup_report(s);
return 1;
}
if (engine.config().debug_graph) return engine.dump();
return engine.serve() < 0 ? 1 : 0;
s = engine.serve();
if (s < 0) {
/* A refusal between start() and listening (a chat template the defaults cannot render, a
* thinking budget the model cannot hold) also ends a server that never came up. */
if (!engine.startup_report_printed()) engine.print_startup_report(s);
return 1;
}
return 0;
}
+2 -1
View File
@@ -3,7 +3,8 @@
* Two stores are built from it: the KV tiers' block arena (core/mem/kvtier.h), where one slot is
* one cache entry, and the linear-state snapshot store (KVManager::set_checkpoint_store), where
* one slot is one snapshot. Under tensor parallelism a slot holds EVERY rank's shard of its
* object, each rank at its own offset, so the disk store can read and write it as one payload.
* object, each rank at its own offset, so one slot id -- rank 0's to hand out -- names the object
* on every rank.
*
* Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the
* driver stages an async copy to pageable memory through its own buffer and, on some paths,
+167 -28
View File
@@ -101,8 +101,10 @@ int KVManager::configure(const std::vector<KVGroupInfo>& groups, const Config& c
int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg) {
/* Only to say it is ignored on a model with no recurrent state: the slots are host memory and
* the engine opens them (set_checkpoint_store). */
const int64_t budget_ckpts = cfg.checkpoint_slots > 0 ? cfg.checkpoint_slots : 0;
* the engine opens them (set_checkpoint_store). The operator's own flag, not the default --
* every model without such state would otherwise warn about a flag nobody passed. */
const int64_t budget_ckpts = cfg.given.count("--checkpoint-slots") && cfg.checkpoint_slots > 0
? cfg.checkpoint_slots : 0;
forget();
max_seqs_ = cfg.max_seqs > 0 ? cfg.max_seqs : 1;
@@ -271,7 +273,19 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
/* ---- fixed costs first: they are not negotiable and they are not per-token ---- */
checkpoint_bytes_ = 0;
window_ck_bytes_ = 0;
for (const auto& p : plans_) if (p.stateful()) checkpoint_bytes_ += p.bytes_per_state;
/* AND THE WINDOW BEHIND A CHECKPOINT, after the linear state (see has_window_snapshot). */
bool has_state = false;
for (const auto& p : plans_) has_state = has_state || p.stateful();
for (size_t i = 1; i < plans_.size(); ++i) {
KVGroupPlan& p = plans_[i];
p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
!groups[i].drafter;
if (p.win_snap && !p.zero && p.n_layers > 0)
window_ck_bytes_ += p.window_blocks * p.bytes_per_block;
}
checkpoint_bytes_ += window_ck_bytes_;
/* EVERY RESERVATION IS PADDED TO RAD_ALIGN_UNIT AND THE BUDGET HAS TO SAY SO. Summing the
* fixed costs as raw bytes leaves the paged split free to spend the difference, and the plan
@@ -307,7 +321,7 @@ int64_t KVManager::ceiling(int64_t ctx) const {
if (!p.paged() || p.block_size <= 0) continue;
int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size);
if (p.kind == RAD_KV_WINDOW && p.window_blocks > 0)
blocks = std::min(blocks, max_seqs_ * p.window_blocks);
blocks = std::min(blocks, window_pool_cap(p));
need += blocks * p.bytes_per_block;
}
return need;
@@ -382,10 +396,10 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
for (int32_t i : open) {
const auto& p = plans_[i];
if (p.kind != RAD_KV_WINDOW) continue;
if (tokens / p.block_size > max_seqs_ * p.window_blocks) { capped = i; break; }
if (tokens / p.block_size > window_pool_cap(p)) { capped = i; break; }
}
if (capped < 0) break;
out[capped] = max_seqs_ * plans_[capped].window_blocks;
out[capped] = window_pool_cap(plans_[capped]);
remaining -= out[capped] * plans_[capped].bytes_per_block;
open.erase(std::find(open.begin(), open.end(), capped));
}
@@ -419,13 +433,12 @@ int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
if (tokens == kUnboundedTokens) return 0;
const int64_t b = tokens / p.block_size;
if (p.kind == RAD_KV_WINDOW && b > max_seqs_ * p.window_blocks) return max_seqs_ * p.window_blocks;
if (p.kind == RAD_KV_WINDOW && b > window_pool_cap(p)) return window_pool_cap(p);
return b;
}
int KVManager::carve_into(Pool& kv_pool) {
/* The pool is whatever the operator stated or the resolver derived; nothing here re-decides
* it. What this does decide is how the groups share it, which is arithmetic, not policy. */
/* The pool is what the resolver derived; nothing here re-decides it. What this does decide is how the groups share it, which is arithmetic, not policy. */
const int64_t budget_bytes = kv_pool.avail();
const int64_t fixed = fixed_;
pool_base_ = kv_pool.base();
@@ -434,10 +447,11 @@ int KVManager::carve_into(Pool& kv_pool) {
if (fixed >= budget_bytes) {
RAD_ERR("vram_kv does not fit its fixed costs:\n"
" linear/conv state %10s (%lld sequences)\n"
" --vram-kv-mib %10s\n"
" vram_kv %10s\n"
" SHORT BY %10s\n"
"Lower --max-seqs or raise --vram-kv-mib. The engine will not shrink one of them "
"for you (spec §6).",
"Lower --max-num-seqs, or give the cache more of the card: a smaller "
"--gpu-headroom-mib or a larger --host-pool-mib. The engine will not shrink one of "
"them for you (spec §6).",
humanb(fixed).c_str(), (long long)max_seqs_, humanb(budget_bytes).c_str(),
humanb(fixed - budget_bytes + 1).c_str());
return RAD_E_NOMEM;
@@ -459,8 +473,8 @@ int KVManager::carve_into(Pool& kv_pool) {
}
if (p.n_blocks <= 0) {
RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed "
"linear/conv costs of %s. Raise --vram-kv-mib or --host-pool-mib, or lower "
"--max-seqs.",
"linear/conv costs of %s. Raise --host-pool-mib or lower --gpu-headroom-mib, or "
"lower --max-num-seqs.",
p.name.c_str(), humanb(budget_bytes).c_str(),
humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str());
return RAD_E_NOMEM;
@@ -921,7 +935,7 @@ int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const {
const KVGroupPlan* p = plan(g);
if (!p || !p->paged() || n_tokens <= 0) return 0;
int64_t n = ceil_div(n_tokens, p->block_size);
if (p->kind == RAD_KV_WINDOW) n = std::min(n, p->window_blocks);
if (p->kind == RAD_KV_WINDOW) n = std::min(n, window_seq_cap(*p));
return n;
}
@@ -1156,19 +1170,29 @@ std::vector<BlockCopy> KVManager::take_pending_copies() {
/* ------------------------------------------------------------------ ensure */
int KVManager::ensure(uint64_t id, int64_t n_tokens) {
Seq* s = find(id);
if (!s) return RAD_E_NOTFOUND;
if (n_tokens <= s->n_tokens) return RAD_OK;
int64_t KVManager::window_seq_cap(const KVGroupPlan& p) const {
return p.window_blocks + (max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0) + 1;
}
/* Pass 0: recycle whatever the window has slid past. This only frees, so it cannot fail, and
* doing it first means the availability check below sees the memory it releases. */
int64_t KVManager::window_pool_cap(const KVGroupPlan& p) const {
return max_seqs_ * p.window_blocks + (max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0) +
max_seqs_;
}
/* SLID PAST THE STEP'S FIRST QUERY, NOT ITS LAST. The query at keep_from reads keys down to
* keep_from - window + 1, which lies in block keep_from / block - (window_blocks - 1) or later
* (window_blocks - 1 >= window / block). A target taken from the END of the step --
* ceil(n_tokens / block) - window_blocks -- is the same block for a decode step and drops the keys
* every row of a longer prefill chunk still needs. Measured on Gemma 4 (#75: 50 of 60 layers
* windowed at 1024): a 2185-token prompt rebased the table at 1152, its sliding layers held no KV
* for positions 0..1151, and every prompt past ~1040 tokens came back as nonsense. */
void KVManager::recycle_window(Seq* s, int64_t keep_from) {
for (size_t g = 0; g < plans_.size(); ++g) {
const auto& p = plans_[g];
if (p.kind != RAD_KV_WINDOW) continue;
int64_t want_end = ceil_div(n_tokens, p.block_size);
int64_t first = s->first_block_pos[g] / p.block_size;
int64_t target = std::max<int64_t>(first, want_end - p.window_blocks);
int64_t target = std::max<int64_t>(first,
keep_from / p.block_size - (p.window_blocks - 1));
while (first < target && !s->blocks[g].empty()) {
drop_block((int32_t)g, s->blocks[g].front());
s->blocks[g].erase(s->blocks[g].begin());
@@ -1178,6 +1202,24 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens) {
if (s->blocks[g].empty()) first = target; /* nothing held: rebase to the window */
s->first_block_pos[g] = first * p.block_size;
}
}
void KVManager::trim_window(uint64_t id, int64_t keep_from) {
Seq* s = find(id);
if (!s || keep_from < 0) return;
if (keep_from > s->n_tokens) keep_from = s->n_tokens;
recycle_window(s, keep_from);
}
int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
Seq* s = find(id);
if (!s) return RAD_E_NOTFOUND;
if (n_tokens <= s->n_tokens) return RAD_OK;
if (keep_from < 0 || keep_from > s->n_tokens) keep_from = s->n_tokens;
/* Pass 0: recycle whatever the window has slid past. This only frees, so it cannot fail, and
* doing it first means the availability check below sees the memory it releases. */
recycle_window(s, keep_from);
/* Pass 1: can every group serve this? Check before touching anything, so a group that runs
* out does not leave the sequence half-extended and the caller unable to say what it owns. */
@@ -1316,7 +1358,7 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens,
if (p.paged()) {
int64_t first = s->first_block_pos[g] / p.block_size;
int64_t want = ceil_div(n_tokens, p.block_size) - first;
if (p.kind == RAD_KV_WINDOW) want = std::min(want, p.window_blocks);
if (p.kind == RAD_KV_WINDOW) want = std::min(want, window_seq_cap(p));
int64_t extra = want - (int64_t)s->blocks[g].size() + 1; /* +1 for a COW copy */
if (extra > available_blocks((int32_t)g)) return false;
} else if (p.stateful() && s->state[g] < 0 && free_states_[g].empty()) return false;
@@ -1374,7 +1416,7 @@ void* KVManager::checkpoint_ptr(int32_t slot) const {
* exactly one piece of code decides its order. Two functions that agreed today would be two
* functions that could stop agreeing. */
int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot,
bool save, RadStream s) {
bool save, RadStream s, const std::vector<int32_t>* win) {
/* A SLOT NOBODY HOLDS IS NOT ONE TO WRITE. Rank 0 hands the ids out, so a follower checks the
* shared store rather than a list of its own. Each refusal says which check it is: a slot the
* store gave back is a lifetime fault in whoever handed the id out, and nothing about the copy. */
@@ -1438,14 +1480,111 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
}
off += nbytes * p.n_layers;
}
/* THE WINDOW SECTION: window_blocks pages a WINDOW group, page j of the window in slot j, each
* page n_layers rows of one layer's block -- one pitched copy a page. `win` names the pages
* (window_rows); -1 is a page below position zero and is left alone either way. */
if (window_ck_bytes_ > 0) {
if (!win) {
RAD_ERR("checkpoint %s slot %d: this model snapshots its window and no window rows "
"were named", dir, (int)ck_slot);
return RAD_E_INVAL;
}
size_t wi = 0;
for (size_t g = 0; g < plans_.size(); ++g) {
const KVGroupPlan& p = plans_[g];
if (!p.win_snap) continue;
const size_t row0 = wi;
wi += (size_t)p.window_blocks;
if (p.zero || p.n_layers <= 0) continue;
if (wi > win->size() || !p.base) {
RAD_ERR("checkpoint %s slot %d: window group %d has %zu row(s) named for %lld",
dir, (int)ck_slot, (int)g, win->size(), (long long)wi);
return RAD_E_STATE;
}
const int64_t lb = p.layer_bytes_per_block();
for (int64_t j = 0; j < p.window_blocks; ++j) {
const int32_t b = (*win)[row0 + (size_t)j];
if (b < 0) continue;
if (b >= p.n_blocks) return RAD_E_STATE;
char* dev = (char*)p.base + (int64_t)b * lb;
char* host = ck + off + j * p.bytes_per_block;
const int cs = save ? rad_memcpy_2d_async(host, lb, dev, p.layer_stride(), lb,
p.n_layers, s)
: rad_memcpy_2d_async(dev, p.layer_stride(), host, lb, lb,
p.n_layers, s);
if (cs < 0) {
RAD_ERR("checkpoint %s slot %d: the device refused window page %lld of "
"group %d: %s", dir, (int)ck_slot, (long long)j, (int)g,
rad_strerror(cs));
return cs;
}
}
off += p.window_blocks * p.bytes_per_block;
}
if (off > checkpoint_bytes_) return RAD_E_STATE;
}
return RAD_OK;
}
int KVManager::checkpoint_save(const int32_t* slots, int n, int32_t ck, RadStream s) {
return checkpoint_copy(slots, n, ck, /*save=*/true, s);
int KVManager::checkpoint_save(const int32_t* slots, int n, int32_t ck, RadStream s,
const std::vector<int32_t>* win) {
return checkpoint_copy(slots, n, ck, /*save=*/true, s, win);
}
int KVManager::checkpoint_restore(const int32_t* slots, int n, int32_t ck, RadStream s) {
return checkpoint_copy(slots, n, ck, /*save=*/false, s);
int KVManager::checkpoint_restore(const int32_t* slots, int n, int32_t ck, RadStream s,
const std::vector<int32_t>* win) {
return checkpoint_copy(slots, n, ck, /*save=*/false, s, win);
}
bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector<int32_t>* out) const {
out->clear();
const Seq* s = find(id);
if (!s || pos <= 0) return false;
for (size_t g = 0; g < plans_.size(); ++g) {
const KVGroupPlan& p = plans_[g];
if (!p.win_snap) continue;
const size_t row0 = out->size();
out->resize(row0 + (size_t)p.window_blocks, -1);
if (p.zero || p.block_size <= 0 || pos % p.block_size != 0) {
if (p.zero) continue;
return false;
}
const int64_t lo = window_lo(p, pos), hi = pos / p.block_size;
const int64_t first = s->first_block_pos[g] / p.block_size;
if (lo < first || hi - first > (int64_t)s->blocks[g].size()) return false;
for (int64_t j = lo; j < hi; ++j)
(*out)[row0 + (size_t)(j - lo)] = s->blocks[g][(size_t)(j - first)];
}
return true;
}
int KVManager::seed_window(uint64_t id, int64_t pos) {
Seq* s = find(id);
if (!s) return RAD_E_NOTFOUND;
/* Check every group before taking anything, as ensure() does. */
for (size_t g = 0; g < plans_.size(); ++g) {
const KVGroupPlan& p = plans_[g];
if (!p.win_snap) continue;
if (!s->blocks[g].empty()) return RAD_E_STATE;
if (pos % p.block_size != 0) return RAD_E_INVAL;
const int64_t need = pos / p.block_size - window_lo(p, pos);
if (need > available_blocks((int32_t)g)) return RAD_E_FULL;
RAD_TRY(grow_for((int32_t)g, need));
}
for (size_t g = 0; g < plans_.size(); ++g) {
const KVGroupPlan& p = plans_[g];
if (!p.win_snap) continue;
const int64_t lo = window_lo(p, pos), hi = pos / p.block_size;
s->first_block_pos[g] = lo * p.block_size;
for (int64_t j = lo; j < hi; ++j) {
int32_t b = -1;
grab_block((int32_t)g, &b);
s->blocks[g].push_back(b);
}
s->dirty_from[g] = 0;
}
if (s->n_tokens == 0) s->n_tokens = pos;
return RAD_OK;
}
/* HOW MANY COLUMNS A SEQUENCE'S state_index ROW HAS. One per physical copy would be the obvious
+68 -11
View File
@@ -73,6 +73,11 @@ struct KVGroupPlan {
int64_t bytes_per_state = 0; /* LINEAR/CONV: per sequence, every layer */
int64_t conv_slots = 0; /* CONV: conv_width - 1 + n_spec */
int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Only a trunk
* group of a model with no linear state: a prefix hit there resumes at a checkpoint from the
* window behind it. A drafter's own window is recomputed by draft refill, and a model with
* linear state re-prefills a hit on a windowed trunk, so neither snapshot would ever be read. */
bool win_snap = false;
int64_t n_blocks = 0; /* paged groups: blocks carved from the pool */
/* rad_kv_group_zero: this rank keeps no cache for the group. The plan exists for its position
@@ -156,8 +161,8 @@ public:
* exhaust at the same total token count, and any other split strands memory in whichever
* group outlasts the others.
*
* The byte budget comes from the operator and is not derived here: it is whatever `kv_pool`
* still has (which is --vram-kv-mib). The linear-state snapshots take none of it -- they live
* The byte budget is the budget resolver's and is not re-derived here: it is whatever
* `kv_pool` still has (vram_kv). The linear-state snapshots take none of it -- they live
* in pinned host memory (set_checkpoint_store) -- so the pool is the live cache and nothing
* else (spec §6, §7.3). */
int configure(const std::vector<KVGroupInfo>& groups, const Config& cfg, Pool& kv_pool);
@@ -165,7 +170,7 @@ public:
/* configure(), split at the seam the budget resolver needs. plan_groups() sizes every group
* from the declaration and the run configuration -- no pool, no bytes -- and ceiling() then
* says what a FULL cache for `ctx` tokens on max_seqs sequences would cost. Pools are
* allocated before carve() runs, so a derived --vram-kv-mib has to be decided from these two
* allocated before carve() runs, so the KV pool has to be decided from these two
* and nothing else (core/mem/vram_budget.cpp). carve() spends the pool it is given. */
int plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg);
int64_t ceiling(int64_t ctx) const;
@@ -207,8 +212,31 @@ public:
/* Grow the sequence's mapping to cover `n_tokens` in every group. Unshares a shared partial
* block first (copy-on-write) and appends the copy request to the pending list.
* RAD_E_FULL when a group's free list is empty -- the caller preempts and retries. */
int ensure(uint64_t seq, int64_t n_tokens);
* RAD_E_FULL when a group's free list is empty -- the caller preempts and retries.
*
* `keep_from` is the position of the FIRST query the coming step runs (the scheduler's
* n_computed); -1 means the sequence's current end. A WINDOW group recycles only the blocks no
* query at or past it can read -- below keep_from - window + 1 -- and NOT the blocks below the
* window of the step's END: a prefill chunk longer than a block would otherwise lose the keys
* its first rows attend to (a chunk of C tokens from position 0 rebased the table at
* ceil(C/block) - window_blocks and left every position below it with no KV at all). */
int ensure(uint64_t seq, int64_t n_tokens, int64_t keep_from = -1);
/* A WINDOW group's caps: a sequence holds its window behind the step's first query AND the
* step's own tokens (window_blocks + ceil(max_tok / block) + 1 at most), and one step carries
* at most max_tok tokens across every sequence in it, so the pool needs max_seqs windows plus
* one step's worth on top. */
int64_t window_seq_cap(const KVGroupPlan& p) const;
int64_t window_pool_cap(const KVGroupPlan& p) const;
/* GIVE BACK A FINISHED CHUNK'S BLOCKS once it is committed. ensure() keeps a chunk's own blocks
* beside the window behind its first query, and only the sequence's NEXT ensure() recycles
* them -- so a prefill waiting a step for its next chunk would sit on a whole chunk of window
* blocks while other sequences prefill, and eight of them exhaust the pool (measured on
* Gemma 4: "the KV pool cannot hold 12480 tokens" with eight 16K prompts). Called by the
* scheduler when it advances n_computed: keep_from is the new n_computed, the first query any
* later step can run. */
void trim_window(uint64_t seq, int64_t keep_from);
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
* block size: a partial block is never shared, because the next token written into it would
@@ -322,7 +350,7 @@ public:
* A BLOCK IS NOT LENT WHILE ANYTHING HOLDS IT, and a held block is a block a sequence owns OR
* one the prefix cache still indexes. So a loan cannot evict anything: it is a claim on what
* is free. Everything that makes a block free -- a sequence ending, an eviction, an idle-tier
* demotion to host memory or disk -- makes it lendable, and the min-heap free list is what
* demotion to host memory -- makes it lendable, and the min-heap free list is what
* keeps the free blocks at the top, where a loan can reach them.
*
* THE BUFFER IS DERIVED AND NOT STATED. It is the free blocks the cache keeps in hand so that
@@ -428,8 +456,7 @@ public:
* that resumes from it, each a few milliseconds on a 50-100 MiB snapshot.
*
* THE STORE IS SHARED BY EVERY RANK and owned by the engine: a slot holds every rank's shard
* of one snapshot, each at its own offset (`rank_off`), so the disk tier reads and writes a
* slot as one payload. The slot ids are rank 0's -- its manager hands them out and the others
* of one snapshot, each at its own offset (`rank_off`). The slot ids are rank 0's -- its manager hands them out and the others
* address the id they are given. Without a store no slot is ever handed out and a hybrid
* model's prefix hits replay their linear layers from zero. `checkpoint_bytes()` is THIS
* rank's shard. */
@@ -462,8 +489,35 @@ public:
* and the restore has to precede the step that consumes it, and both are ordered by the
* stream rather than by waiting. One pitched copy a stateful group between the card and the
* store, at the link's rate. RAD_E_INVAL on a bad slot or an unknown sequence. */
int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s);
int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s);
int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s,
const std::vector<int32_t>* win = nullptr);
int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s,
const std::vector<int32_t>* win = nullptr);
/* ---------------- window snapshots (the sliding-window half of a prefix hit) ----------------
* A WINDOW group keeps only the blocks its window can still read, so no block list from the
* prefix cache describes it. What a later prompt that extends a cached prefix at position P
* needs from it is exactly the window behind P: blocks [lo, P/B) with
* lo = max(0, P/B - (window_blocks - 1)) -- the floor recycle_window keeps for a query at P.
* A checkpoint slot therefore carries, after the linear state, window_blocks pages a WINDOW
* group (every layer, layer-major rows), and a hit at a checkpoint restores them into fresh
* blocks seeded at that floor.
*
* has_window_snapshot(): this rank's slot carries a window section. window_rows() names, from
* the LEADER's table, the block ids [lo, P/B) of every non-zero snapshot group (win_snap) in
* plans() order, each group padded with -1 to window_blocks -- one vector every rank addresses
* with its own pool, because followers keep no sequence tables. False when the sequence does
* not hold that range (it is gone, or its floor moved past lo). seed_window() gives a sequence
* with an empty table in each snapshot group the blocks [lo, P/B) a restore will fill, before
* the ensure that extends it; any other WINDOW group starts at the floor that ensure sets. */
bool has_window_snapshot() const { return window_ck_bytes_ > 0; }
bool window_rows(uint64_t seq, int64_t pos, std::vector<int32_t>* out) const;
int seed_window(uint64_t seq, int64_t pos);
/* The floor and end (block indices) of the window a query at `pos` reads in a group. */
static int64_t window_lo(const KVGroupPlan& p, int64_t pos) {
const int64_t b = pos / p.block_size - (p.window_blocks - 1);
return b > 0 ? b : 0;
}
/* Byte address of a state slot, for the slot-mapping builder. Null when the pool has no
* host-visible base (a device pool), which is the normal case -- the offset is what the step
@@ -486,7 +540,7 @@ private:
/* One traversal serving both checkpoint directions; see checkpoint_save. */
int checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save,
RadStream s);
RadStream s, const std::vector<int32_t>* win);
struct Seq {
uint64_t id = 0;
@@ -509,6 +563,8 @@ private:
void drop_state(int32_t g, int32_t s);
Seq* find(uint64_t seq);
const Seq* find(uint64_t seq) const;
/* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. */
void recycle_window(Seq* s, int64_t keep_from);
std::vector<KVGroupPlan> plans_;
std::vector<std::vector<int32_t>> free_blocks_; /* per group */
@@ -524,6 +580,7 @@ private:
HostArena* ck_store_ = nullptr; /* set_checkpoint_store */
int64_t ck_rank_off_ = 0;
int64_t checkpoint_bytes_ = 0;
int64_t window_ck_bytes_ = 0; /* the window section of checkpoint_bytes_ */
std::vector<StateClear> clears_; /* grabbed slots the engine must zero */
void* pool_base_ = nullptr;
BundleComparison bundling_;
+96 -557
View File
@@ -1,6 +1,5 @@
#include "mem/kvtier.h"
#include "mem/sstier.h"
#include "rad_internal.h"
#include <algorithm>
@@ -13,18 +12,16 @@ const char* kv_tier_name(KVTier t) {
switch (t) {
case KVTier::Device: return "device";
case KVTier::Host: return "host";
case KVTier::Disk: return "disk";
}
return "?";
}
/* ------------------------------------------------------------------ IdleTiers */
int IdleTiers::configure(const Config& c, SSDTier* disk) {
int IdleTiers::configure(const Config& c) {
std::lock_guard lk(mu_);
reset();
cfg_ = c;
disk_ = disk;
if (cfg_.host_cap_bytes > 0 && cfg_.entry_bytes > 0) {
const int st = arena_.open(cfg_.entry_bytes, cfg_.host_cap_bytes);
@@ -36,46 +33,27 @@ int IdleTiers::configure(const Config& c, SSDTier* disk) {
} else {
cfg_.host_cap_bytes = 0;
}
if (!disk_ || !disk_->enabled()) cfg_.disk_cap_bytes = 0;
/* A disk tier under no host tier is legal and it is not a mistake: the blocks' path to disk
* runs through host memory, so with no host tier no block ever reaches disk, and saying so at
* startup is cheaper than an operator reading a disk tier's zero counters for an afternoon. */
if (!host_on() && disk_on())
RAD_WARN("kv tiers: --prefix-cache-disk-mib is set but --prefix-cache-host-mib is not, and the "
"blocks' path to disk runs through host memory -- only snapshots will be written");
char buf[512];
if (!any_on()) {
report_ = "kv tiers: off (no --prefix-cache-host-mib), so a finished conversation's KV stays "
report_ = "kv tiers: off (no --prefix-cache-mib), so a finished conversation's KV stays "
"in VRAM until the cache evicts it under pressure -- it is never copied to host "
"memory, and what the pool is holding is mostly cache rather than live requests";
} else {
std::snprintf(buf, sizeof buf,
"kv tiers: a finished conversation's KV is copied to host memory at once "
"(%s, %lld entries) and its VRAM is given up when the expert loan or a "
"request wants it; %s. One entry is %s",
"request wants it; a full host tier drops its least recently used entries. "
"One entry is %s",
humanb(arena_.cap_bytes()).c_str(), (long long)arena_.capacity(),
disk_on() ? ("every host copy is written on to disk (" +
humanb(cfg_.disk_cap_bytes) + ") and its slot is given up "
"when another entry needs it").c_str()
: "no disk tier, so a full host tier drops its oldest entries",
humanb(cfg_.entry_bytes).c_str());
report_ = buf;
/* SAID EVEN WHEN IT IS ZERO, on a model that has recurrent state. A hybrid server whose
* snapshots do not reach disk looks identical from every block counter there is, and the
* difference it makes is a full linear replay of the transcript on what the hit rate will
* happily report as a hit. */
if (cfg_.ckpt_bytes > 0) {
std::snprintf(buf, sizeof buf,
"\nkv tiers: a session's linear state is saved to host memory -- %lld "
"snapshot slot(s) of %s -- and %s",
(long long)cfg_.ckpt_slots, humanb(cfg_.ckpt_bytes).c_str(),
ckpt_disk_on()
? fmt("written on to disk (%lld slots), so a full store detaches "
"the least recently used instead of losing it",
(long long)cfg_.ckpt_disk_slots).c_str()
: "with no disk copy a full store retires the least recently used");
"snapshot slot(s) of %s -- and a full store retires the least recently "
"used",
(long long)cfg_.ckpt_slots, humanb(cfg_.ckpt_bytes).c_str());
report_ += buf;
}
}
@@ -93,18 +71,11 @@ void IdleTiers::reset() {
sessions_.clear();
roots_.clear();
host_lru_.clear();
disk_lru_.clear();
wb_q_.clear();
resume_q_.clear();
dk_q_.clear();
clean_q_.clear();
ck_reading_.clear();
ck_free_after_.clear();
ck_frees_.clear();
starved_ = 0;
wb_stuck_ = false;
arena_.close();
disk_ = nullptr;
cfg_ = Config{};
report_.clear();
}
@@ -113,7 +84,7 @@ std::string IdleTiers::report() const { return report_; }
void IdleTiers::unlist(Rec& r) {
if (!r.listed) return;
list_for(r.tier).erase(r.it);
host_lru_.erase(r.it);
r.listed = false;
}
@@ -122,25 +93,13 @@ void IdleTiers::unlist(Rec& r) {
* header's one-record rule exists to rule out. */
void IdleTiers::relist(const BlockHash& key, Rec& r) {
if (r.pending || r.tier == KVTier::Device || r.listed) return;
std::list<BlockHash>& l = list_for(r.tier);
l.push_back(key);
r.it = std::prev(l.end());
r.it = host_lru_.emplace_hint(host_lru_.end(), r.used_ns, key);
r.listed = true;
}
bool IdleTiers::wants_copy(const Rec& r) const {
if (r.pending || r.doomed) return false;
return host_on() && r.tier == KVTier::Device && r.host_slot < 0 && !r.on_disk &&
!r.blocks.empty();
}
bool IdleTiers::wants_ck_disk(const Rec& r) const {
return ckpt_disk_on() && !r.doomed && r.ck_slot >= 0 && !r.ck_on_disk && r.ck_disk_src < 0;
}
bool IdleTiers::wants_disk(const Rec& r) const {
if (!disk_on() || r.doomed) return false;
return (r.host_slot >= 0 && !r.on_disk && r.disk_src < 0) || wants_ck_disk(r);
return host_on() && r.tier == KVTier::Device && r.host_slot < 0 && !r.blocks.empty();
}
void IdleTiers::queue_copy(const BlockHash& key, Rec& r) {
@@ -149,12 +108,6 @@ void IdleTiers::queue_copy(const BlockHash& key, Rec& r) {
r.queued = true;
}
void IdleTiers::queue_disk(const BlockHash& key, Rec& r) {
if (r.disk_q || !wants_disk(r)) return;
dk_q_.push_back(key);
r.disk_q = true;
}
void IdleTiers::give_slot(int32_t slot) {
if (slot < 0) return;
arena_.free(slot);
@@ -162,106 +115,41 @@ void IdleTiers::give_slot(int32_t slot) {
}
void IdleTiers::free_host(Rec& r) {
if (r.host_slot < 0) return;
if (r.host_slot != r.disk_src) give_slot(r.host_slot);
give_slot(r.host_slot);
r.host_slot = -1;
}
/* THE ONE PLACE `on_disk` CHANGES, because the disk figure in the occupancy view is kept beside it
* rather than counted, and an entry landing on disk is also what unblocks a stuck write-back. */
void IdleTiers::set_on_disk(Rec& r, bool v) {
if (r.on_disk == v) return;
r.on_disk = v;
stats_.disk_bytes += v ? cfg_.entry_bytes : -cfg_.entry_bytes;
if (v) wb_stuck_ = false;
}
void IdleTiers::queue_clean(const BlockHash& key, Rec& r) {
if (r.clean_q) return;
clean_q_.push_back(key);
r.clean_q = true;
}
/* EVERYTHING THIS RECORD HOLDS OFF THE CARD. The blocks' arena slot is the tiers'; SSDTier owns
* its own slots and reclaims them by LRU, so there is nothing to give back for a disk-resident
* copy of either half.
*
* A snapshot in its store slot is the CACHE'S, not this object's: the cache retires snapshots by
* its own retention policy and the slot is still correct and indexed. Only a snapshot that exists
* nowhere but on disk is lost with the record, and only that loss is announced -- the cache
* learns about a lost ENTRY from set_drop_sink at the sites that erase one, and this is also
* called from forget(), where the cache is the caller and already knows. */
void IdleTiers::release_storage(const BlockHash& key, Rec& r) {
free_host(r);
set_on_disk(r, false);
const bool lost_ck = r.ck_slot < 0 && r.ck_on_disk;
r.ck_on_disk = false;
if (lost_ck) { ++stats_.ck_drops; if (on_ck_drop_) on_ck_drop_(key); }
}
/* ------------------------------------------------------------------ the linear half */
void IdleTiers::note_snapshot(const BlockHash& key, int32_t slot, int64_t pos, bool resume) {
/* RECORDED, NOT MOVED. A snapshot is in host memory from the moment it is saved and stays in its
* store slot until the cache retires it; the tiers keep its slot and position for the session
* view. */
void IdleTiers::note_snapshot(const BlockHash& key, int32_t slot, int64_t pos) {
if (slot < 0) return;
std::lock_guard lk(mu_);
Rec& r = recs_[key];
/* A FRESH SNAPSHOT REPLACES WHATEVER DISK COPY THERE WAS, never joins it. The disk copy
* described the state as it was last written; the slot now holds it as it was just written,
* and a record that called the two the same bytes would read the older one back. */
r.ck_on_disk = false;
r.ck_slot = slot;
r.ck_pos = pos;
/* WRITTEN TO DISK ONCE ITS RECORD IS PUBLISHED, like the blocks: note_used queues it then. A
* request commits its checkpoints as its prefill passes them and the store's retention policy
* thins them as it goes, so writing each at commit would send most of them to disk to be
* retired a moment later. A record the request had already published takes a new commit at
* once. A RESUME POINT does not wait: it is the snapshot the next turn needs, and until it is
* on disk a full store can only retire it. */
if (r.tier != KVTier::Device || !r.blocks.empty()) queue_disk(key, r);
if (resume && !r.resume_q && wants_ck_disk(r)) {
resume_q_.push_back(key);
r.resume_q = true;
}
}
bool IdleTiers::release_snapshot(const BlockHash& key, int32_t slot) {
void IdleTiers::release_snapshot(const BlockHash& key) {
std::lock_guard lk(mu_);
bool held = false;
if (slot >= 0 &&
std::find(ck_reading_.begin(), ck_reading_.end(), slot) != ck_reading_.end()) {
ck_free_after_.push_back(slot);
held = true;
}
auto it = recs_.find(key);
if (it == recs_.end()) return held;
if (it == recs_.end()) return;
Rec& r = it->second;
r.ck_slot = -1;
r.ck_on_disk = false;
/* A RECORD THAT ONLY EVER EXISTED FOR THE SNAPSHOT GOES WITH IT. note_snapshot creates one at
* commit time, which is mid-request and long before the chain is published; a request that
* never publishes -- a rebased block table, a cancel before the first whole block -- would
* otherwise leave a record with no blocks, no storage and no way to be reached again. */
if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0 &&
r.ck_disk_src < 0 && !r.disk_q)
if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0)
recs_.erase(it);
return held;
}
void IdleTiers::take_checkpoint_frees(std::vector<int32_t>* out) {
std::lock_guard lk(mu_);
out->insert(out->end(), ck_frees_.begin(), ck_frees_.end());
ck_frees_.clear();
}
bool IdleTiers::slot_reading(int32_t slot) const {
std::lock_guard lk(mu_);
return slot >= 0 && std::find(ck_reading_.begin(), ck_reading_.end(), slot) != ck_reading_.end();
}
bool IdleTiers::snapshot_in_slot(const BlockHash& key, int32_t slot) const {
std::lock_guard lk(mu_);
auto it = recs_.find(key);
return it != recs_.end() && slot >= 0 && it->second.ck_slot == slot;
}
/* ------------------------------------------------------------------ the cache's notices */
@@ -272,17 +160,14 @@ void IdleTiers::note_used(const BlockHash& key, const std::vector<int32_t>& bloc
Rec& r = recs_[key];
r.used_ns = now_ns;
if (r.tier == KVTier::Device && !r.pending) r.blocks = blocks;
/* A record only moves to the back of its list when it is IN one. A device record is a
* timestamp and nothing else, which is what keeps this cheap enough to sit on the publish
* path -- the hash insert is the whole cost. */
/* A record only moves on the host list when it is IN it. A device record is a timestamp and
* nothing else, which is what keeps this cheap enough to sit on the publish path -- the hash
* insert is the whole cost. */
if (r.listed) {
list_for(r.tier).erase(r.it);
r.listed = false;
unlist(r);
relist(key, r);
}
queue_copy(key, r);
/* A snapshot the request committed under this key goes to disk now that its chain is out. */
if (wants_ck_disk(r)) queue_disk(key, r);
}
void IdleTiers::note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns) {
@@ -294,8 +179,7 @@ void IdleTiers::note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns) {
Rec& r = it->second;
r.used_ns = now_ns;
if (r.listed) {
list_for(r.tier).erase(r.it);
r.listed = false;
unlist(r);
relist(keys[i], r);
}
}
@@ -307,7 +191,7 @@ void IdleTiers::rebound(const BlockHash& key, const std::vector<int32_t>& blocks
Rec& r = recs_[key];
if (r.pending) return;
unlist(r);
release_storage(key, r);
free_host(r);
r.tier = KVTier::Device;
r.blocks = blocks;
r.used_ns = now_ns;
@@ -330,18 +214,21 @@ IdleTiers::Stats IdleTiers::stats() const {
return s;
}
/* AND EVERY CONVERSATION THAT STARTED HERE. A chain whose first block has gone cannot be hit at any
* length -- a prefix hit starts at position zero. Leaving the row behind would report blocks the
* pool has already handed to somebody else as this session's, and would hold its whole chain in
* memory for a conversation that can never come back. Called wherever an entry goes for good: the
* cache's forget(), and the sites here that drop an off-device entry and tell the cache. */
void IdleTiers::drop_rooted(const BlockHash& key) {
auto ro = roots_.find(key);
if (ro == roots_.end()) return;
const std::vector<uint64_t> ids = ro->second; /* drop_session rewrites the list */
for (uint64_t id : ids) drop_session(id);
}
void IdleTiers::forget(const BlockHash& key) {
std::lock_guard lk(mu_);
/* AND EVERY CONVERSATION THAT STARTED HERE. This is the only notice the cache gives that an
* entry is gone for good, and a chain whose first block has gone cannot be hit at any length
* -- a prefix hit starts at position zero. Leaving the row behind would report blocks the
* pool has already handed to somebody else as this session's, and would hold its whole chain
* in memory for a conversation that can never come back. */
auto ro = roots_.find(key);
if (ro != roots_.end()) {
const std::vector<uint64_t> ids = ro->second; /* drop_session rewrites the list */
for (uint64_t id : ids) drop_session(id);
}
drop_rooted(key);
auto it = recs_.find(key);
if (it == recs_.end()) return;
Rec& r = it->second;
@@ -353,7 +240,7 @@ void IdleTiers::forget(const BlockHash& key) {
return;
}
unlist(r);
release_storage(key, r);
free_host(r);
recs_.erase(it);
}
@@ -374,74 +261,13 @@ bool IdleTiers::resident_off_device(const BlockHash& key) const {
bool IdleTiers::writeback_waiting() const {
std::lock_guard lk(mu_);
/* NOT WHILE NOTHING CAN MOVE. An arena full of copies the disk does not hold yet has nothing
* to give up, so a plan would pop the queue, find no slot and put it back, every tick, until
* a slot is freed or a disk copy lands -- which is what ends the wait. */
/* NOT WHILE NOTHING CAN MOVE. An arena full of the copies of entries still in VRAM has nothing
* a capacity drop may take, so a plan would pop the queue, find no slot and put it back, every
* tick, until a slot is freed or a VRAM copy is given up -- which is what ends the wait. */
if (wb_stuck_ && arena_.full()) return false;
return !wb_q_.empty() && host_on();
}
bool IdleTiers::disk_waiting() const {
std::lock_guard lk(mu_);
return !dk_q_.empty() || !resume_q_.empty();
}
int64_t IdleTiers::make_room(int64_t n) {
std::lock_guard lk(mu_);
return make_room_locked(n);
}
/* A READ NO REQUEST CLAIMS IS HELD THIS LONG. A request is admitted on the step after its read lands,
* which is milliseconds; this only bounds what one that went away -- cancelled while it waited --
* keeps out of reach of everybody else. */
static constexpr uint64_t kFetchHoldNs = 10ull * 1000000000ull;
bool IdleTiers::held_by_fetch(const Rec& r, uint64_t now_ns) const {
return r.keep || (r.fetched_ns != 0 && now_ns - r.fetched_ns < kFetchHoldNs);
}
int64_t IdleTiers::make_room_locked(int64_t n) {
if (!disk_on() || n <= 0) return 0;
const uint64_t now = rad_mono_ns();
int64_t freed = 0;
/* HOST RECORDS FIRST, oldest first: nothing is in VRAM to use them, and they become disk
* records. The walk skips the ones whose disk copy has not landed, which are the newest --
* the writes go out in the order the copies landed -- so it stops close to the front. */
for (auto it = host_lru_.begin(); it != host_lru_.end() && freed < n;) {
const BlockHash key = *it;
++it;
auto ri = recs_.find(key);
if (ri == recs_.end()) continue;
Rec& r = ri->second;
if (r.pending || !r.on_disk || r.host_slot < 0 || r.host_slot == r.disk_src ||
held_by_fetch(r, now))
continue;
unlist(r);
free_host(r);
r.tier = KVTier::Disk;
relist(key, r);
++freed;
}
/* THEN THE HOST COPIES OF CLEAN VRAM ENTRIES, oldest first. The VRAM copy stays and stays
* clean -- its disk copy is what lets it go now. These are on no list (a device record is
* ordered by the cache), so they are found by a walk, which only a full arena of them pays. */
if (freed < n) {
std::vector<std::pair<uint64_t, Rec*>> c;
for (auto& kv : recs_) {
Rec& r = kv.second;
if (r.tier == KVTier::Device && !r.pending && r.on_disk && r.host_slot >= 0 &&
r.host_slot != r.disk_src && !held_by_fetch(r, now))
c.emplace_back(r.used_ns, &r);
}
const size_t k = std::min(c.size(), (size_t)(n - freed));
std::partial_sort(c.begin(), c.begin() + (long)k, c.end(),
[](const auto& a, const auto& b) { return a.first < b.first; });
for (size_t i = 0; i < k; ++i) { free_host(*c[i].second); ++freed; }
}
stats_.host_freed += freed;
return freed;
}
bool IdleTiers::starved() const {
std::lock_guard lk(mu_);
return starved_ > 0;
@@ -473,7 +299,6 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector<TierJob>* out) {
* front of the queue, and the maintenance plan is told how many copies were refused so it can
* make that much room. */
const int64_t want = (int64_t)(out->size() - first);
if (want > arena_.free_slots()) make_room_locked(want - arena_.free_slots());
std::vector<int32_t> slots;
slots.reserve((size_t)want);
while ((int64_t)slots.size() < want) {
@@ -527,7 +352,7 @@ bool IdleTiers::droppable(const BlockHash& key) const {
auto it = recs_.find(key);
if (it == recs_.end()) return false;
const Rec& r = it->second;
return !r.pending && !r.doomed && r.tier == KVTier::Device && (r.host_slot >= 0 || r.on_disk);
return !r.pending && !r.doomed && r.tier == KVTier::Device && r.host_slot >= 0;
}
void IdleTiers::drop_commit(const BlockHash& key) {
@@ -536,113 +361,26 @@ void IdleTiers::drop_commit(const BlockHash& key) {
if (it == recs_.end()) return;
Rec& r = it->second;
if (r.tier != KVTier::Device) return;
r.tier = r.host_slot >= 0 ? KVTier::Host : KVTier::Disk;
r.tier = KVTier::Host;
++stats_.dropped;
wb_stuck_ = false; /* with no disk tier, a host record is what a capacity drop takes */
wb_stuck_ = false; /* a host record is what a capacity drop takes */
relist(key, r);
}
bool IdleTiers::snapshot_backed(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;
return !r.doomed && r.ck_slot >= 0 && r.ck_on_disk && r.ck_disk_src < 0;
}
void IdleTiers::snapshot_detached(const BlockHash& key) {
std::lock_guard lk(mu_);
auto it = recs_.find(key);
if (it == recs_.end()) return;
it->second.ck_slot = -1;
}
/* ------------------------------------------------------------------ the slow half */
/* ------------------------------------------------------------------ capacity and expiry */
void IdleTiers::plan(int budget, std::vector<TierJob>* out) {
if (!any_on() || budget <= 0) return;
if (!host_on() || budget <= 0) return;
std::lock_guard lk(mu_);
/* ---- disk copies: the resume points first, then in the order the host copies landed --- */
/* ONE SNAPSHOT BUDGET FOR THE WAY TO DISK, apart from the blocks'. A snapshot is a hundred
* megabytes or more and the disk store copies it twice on the way out (an aligned bounce, then
* the write), so a plan that sent a session's whole retained set at once would hold the IO
* thread for most of a second. A record whose snapshot the budget left behind still sends its
* blocks, and goes to the back of the queue for the rest. */
int ck_disk_budget = 2;
int n = 0;
auto take_ck = [&](const BlockHash& key, Rec& r, TierJob& j) {
j.ck_slot = r.ck_slot;
j.ck_pos = r.ck_pos;
j.ck_bytes = cfg_.ckpt_bytes;
r.ck_disk_src = r.ck_slot;
ck_reading_.push_back(r.ck_slot);
--ck_disk_budget;
(void)key;
};
/* A RESUME POINT IS THE SNAPSHOT THE NEXT TURN NEEDS, and the store can only retire it until
* the disk holds it. Its record's blocks are not waited for: they go through the host tier on
* their own clock. */
while (ckpt_disk_on() && ck_disk_budget > 0 && !resume_q_.empty() && n < budget) {
const BlockHash key = resume_q_.front();
resume_q_.pop_front();
auto ri = recs_.find(key);
if (ri == recs_.end()) continue;
Rec& r = ri->second;
r.resume_q = false;
if (!wants_ck_disk(r)) continue;
TierJob j;
j.kind = TierJob::Kind::ToDisk;
j.key = key;
j.bytes = cfg_.entry_bytes;
take_ck(key, r, j);
out->push_back(std::move(j));
++n;
}
std::vector<BlockHash> later;
while (disk_on() && !dk_q_.empty() && n < budget) {
const BlockHash key = dk_q_.front();
dk_q_.pop_front();
auto ri = recs_.find(key);
if (ri == recs_.end()) continue;
Rec& r = ri->second;
if (!r.disk_q) continue;
r.disk_q = false;
if (!wants_disk(r)) continue;
TierJob j;
j.kind = TierJob::Kind::ToDisk;
j.key = key;
j.bytes = cfg_.entry_bytes;
if (r.host_slot >= 0 && !r.on_disk && r.disk_src < 0) {
j.host_slot = r.host_slot;
r.disk_src = r.host_slot;
}
if (wants_ck_disk(r)) {
if (ck_disk_budget > 0) take_ck(key, r, j);
else later.push_back(key);
}
if (j.host_slot < 0 && j.ck_slot < 0) continue;
out->push_back(std::move(j));
++n;
}
for (const BlockHash& k : later) {
auto ri = recs_.find(k);
if (ri != recs_.end()) queue_disk(k, ri->second);
}
/* ---- capacity, with no disk tier: oldest first ----------------------------------------- */
/* HOW MANY, AND NOT "UNTIL THERE IS ROOM". A queued drop does not free its slot until the
* engine reports it, so a loop that tested the arena would queue a drop for every entry on the
* list and empty the whole tier to make room for one. The copies refused since the last plan
* say how much room was wanted; this frees exactly that much. With a disk tier the room comes
* from make_room instead, for nothing, once the disk copies above have landed. */
const int64_t want = starved_;
* say how much room was wanted; this frees exactly that much, least recently used first. */
const int64_t want = std::min<int64_t>(starved_, budget);
starved_ = 0;
if (disk_on()) return;
int n_cap = 0;
for (int64_t k = 0; k < want && n_cap < budget; ) {
if (host_lru_.empty()) break;
auto ri = recs_.find(host_lru_.front());
if (ri == recs_.end()) { host_lru_.pop_front(); continue; }
for (int64_t k = 0; k < want && !host_lru_.empty();) {
auto ri = recs_.find(host_lru_.begin()->second);
if (ri == recs_.end()) { host_lru_.erase(host_lru_.begin()); continue; }
Rec& r = ri->second;
TierJob j;
j.kind = TierJob::Kind::DropHost;
@@ -653,10 +391,17 @@ void IdleTiers::plan(int budget, std::vector<TierJob>* out) {
r.pending = true;
out->push_back(std::move(j));
++k;
++n_cap;
}
}
void IdleTiers::expired(uint64_t cutoff_ns, size_t max, std::vector<BlockHash>* out) const {
std::lock_guard lk(mu_);
/* The list holds no record with a job out (relist), so every key it yields can go now. */
for (auto it = host_lru_.begin();
it != host_lru_.end() && it->first < cutoff_ns && out->size() < max; ++it)
out->push_back(it->second);
}
bool IdleTiers::plan_promote(const BlockHash& key, TierJob* out) {
std::lock_guard lk(mu_);
auto it = recs_.find(key);
@@ -669,189 +414,33 @@ bool IdleTiers::plan_promote(const BlockHash& key, TierJob* out) {
out->key = key;
out->host_slot = r.host_slot;
out->bytes = cfg_.entry_bytes;
if (r.fetched_ns) ++stats_.disk_hits; else ++stats_.host_hits;
++stats_.host_hits;
unlist(r);
r.pending = true;
return true;
}
/* THE DEEPEST SNAPSHOT ON THE CHAIN, wherever it is and whatever tier its blocks are on: that is
* the one the hit resumes from, and it is read off disk only when the disk is the one place it
* is. Its record may be in VRAM -- a snapshot can leave its slot while its blocks stay -- and then
* the read is of the snapshot alone. A record with a job out is passed over. */
size_t IdleTiers::deepest_snapshot(const std::vector<BlockHash>& chain) const {
size_t deep = chain.size();
for (size_t i = 0; i < chain.size(); ++i) {
auto it = recs_.find(chain[i]);
if (it == recs_.end()) continue;
const Rec& r = it->second;
if (r.pending || r.doomed) continue;
if (r.ck_slot >= 0 || r.ck_on_disk) deep = i;
}
return deep;
}
bool IdleTiers::snapshot_fetch_wanted(const std::vector<BlockHash>& chain) const {
if (!ckpt_disk_on() || chain.empty()) return false;
std::lock_guard lk(mu_);
const size_t deep = deepest_snapshot(chain);
if (deep >= chain.size()) return false;
const Rec& r = recs_.find(chain[deep])->second;
return r.ck_slot < 0 && r.ck_on_disk;
}
bool IdleTiers::plan_fetch(const std::vector<BlockHash>& chain, std::vector<TierJob>* out,
uint64_t now_ns, int32_t* ck_slot) {
if (!disk_on() || chain.empty()) return false;
std::lock_guard lk(mu_);
bool wait = false;
std::vector<Rec*> recs(chain.size(), nullptr);
std::vector<size_t> need; /* chain positions whose blocks are only on disk */
for (size_t i = 0; i < chain.size(); ++i) {
auto it = recs_.find(chain[i]);
if (it == recs_.end()) continue;
Rec& r = it->second;
if (r.fetching) { wait = true; continue; }
if (r.pending || r.doomed || r.tier == KVTier::Device) continue;
recs[i] = &r;
if (r.tier == KVTier::Disk) need.push_back(i);
}
const size_t deep = deepest_snapshot(chain);
Rec* deep_rec = deep < chain.size() ? &recs_.find(chain[deep])->second : nullptr;
const bool ck_read = deep_rec && deep_rec->ck_slot < 0 && deep_rec->ck_on_disk &&
ckpt_disk_on() && ck_slot && *ck_slot >= 0;
if (need.empty() && !ck_read) return wait;
/* THE ROOM, OUT OF EVERYTHING BUT THIS CHAIN. What the disk also holds goes for nothing
* (make_room); the chain's own host copies are what the restore is about to read, and giving
* one up to read another would only move the gap. */
for (Rec* r : recs) if (r) r->keep = true;
if (deep_rec) deep_rec->keep = true;
std::vector<int32_t> slots;
if (!need.empty()) {
const int64_t want = (int64_t)need.size();
if (want > arena_.free_slots()) make_room_locked(want - arena_.free_slots());
slots.reserve((size_t)want);
while ((int64_t)slots.size() < want) {
int32_t got = 0;
const int32_t s = arena_.alloc_run((int32_t)(want - (int64_t)slots.size()), &got);
if (s < 0) break;
for (int32_t k = 0; k < got; ++k) slots.push_back(s + k);
}
}
for (Rec* r : recs) if (r) r->keep = false;
if (deep_rec) deep_rec->keep = false;
/* IN CHAIN ORDER, AND CUT WHERE THE SLOTS RAN OUT: a hit needs a contiguous prefix, so an entry
* read past a gap would be read for nothing. */
const size_t first = out->size();
for (size_t k = 0; k < slots.size(); ++k) {
TierJob j;
j.kind = TierJob::Kind::ToHost;
j.key = chain[need[k]];
j.host_slot = slots[k];
j.bytes = cfg_.entry_bytes;
out->push_back(std::move(j));
}
/* ONLY A SNAPSHOT THE RESTORE WILL REACH: every disk entry at or before it has a slot.
* Otherwise the store slot stays the caller's. */
if (ck_read && (slots.size() == need.size() || need[slots.size()] > deep)) {
TierJob* j = nullptr;
for (size_t k = first; k < out->size(); ++k)
if ((*out)[k].key == chain[deep]) { j = &(*out)[k]; break; }
if (!j) {
out->push_back(TierJob{});
j = &out->back();
j->kind = TierJob::Kind::ToHost;
j->key = chain[deep];
j->bytes = cfg_.entry_bytes;
}
j->ck_want = true;
j->ck_slot = *ck_slot;
j->ck_pos = deep_rec->ck_pos;
j->ck_bytes = cfg_.ckpt_bytes;
*ck_slot = -1;
}
for (size_t k = first; k < out->size(); ++k) {
Rec& r = recs_[(*out)[k].key];
unlist(r);
r.pending = true;
r.fetching = true;
r.used_ns = now_ns;
}
return wait || out->size() > first;
}
void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
std::lock_guard lk(mu_);
auto it = recs_.find(job.key);
/* A DISK WRITE IS NOT A PENDING JOB, so it is settled before anything below touches the
* record's pending state -- which may belong to a restore running beside it. The slots it
* read are the record's, unless the record gave them up (or went) while the write was out:
* then the write's report is what frees them. */
if (job.kind == TierJob::Kind::ToDisk) {
if (!ok) ++stats_.failures;
Rec* r = it == recs_.end() ? nullptr : &it->second;
if (job.host_slot >= 0) {
if (r && r->disk_src == job.host_slot) r->disk_src = -1;
if (!r || r->host_slot != job.host_slot) give_slot(job.host_slot);
else if (ok) { set_on_disk(*r, true); ++stats_.to_disk; }
}
if (job.ck_slot >= 0) {
/* THE STORE SLOT IS FREE TO WRITE AGAIN, and one the cache let go of meanwhile goes
* back now. */
auto rd = std::find(ck_reading_.begin(), ck_reading_.end(), job.ck_slot);
if (rd != ck_reading_.end()) ck_reading_.erase(rd);
auto fa = std::find(ck_free_after_.begin(), ck_free_after_.end(), job.ck_slot);
if (fa != ck_free_after_.end()) {
ck_free_after_.erase(fa);
ck_frees_.push_back(job.ck_slot);
}
/* ON DISK ONLY IF THE RECORD STILL NAMES THE SLOT THE WRITE READ. A new commit at this
* key, or a release by the cache, moved it while the write ran, and the bytes that
* landed describe a state nobody holds any more; a new commit is written on its own. */
if (r && r->ck_disk_src == job.ck_slot) {
r->ck_disk_src = -1;
if (ok && job.ck_ok && r->ck_slot == job.ck_slot) {
r->ck_on_disk = true;
++stats_.ck_to_disk;
}
}
if (r) queue_disk(job.key, *r);
}
/* A write that failed is not tried again: a store that refused it once will refuse the
* next, and the entry stays host-only, which is what it was before. */
return;
}
/* A store slot a read was given and nothing took goes back to the store. */
auto ck_back = [&] { if (job.ck_want && job.ck_slot >= 0) ck_frees_.push_back(job.ck_slot); };
if (it == recs_.end()) {
/* Nothing names the slots a job was handed but the job itself. */
/* Nothing names the slots a copy was handed but the job itself. */
if (job.kind == TierJob::Kind::WriteBack) give_slot(job.host_slot);
ck_back();
return;
}
Rec& r = it->second;
r.pending = false;
r.fetching = false;
/* A promotion the chain was cut before, or a read that never ran, is not a failure: nothing
* was tried. */
const bool may_skip = job.kind == TierJob::Kind::ToDevice || job.kind == TierJob::Kind::ToHost;
if (!ok && (!may_skip || job.started)) ++stats_.failures;
/* A promotion the chain was cut before is not a failure: nothing was tried. */
if (!ok && (job.kind != TierJob::Kind::ToDevice || job.started)) ++stats_.failures;
/* A record that was forgotten mid-transfer is finished off here and nowhere else. Doing it at
* the top, before the per-kind handling, means no branch below has to remember to check. */
if (r.doomed) {
/* THE JOB'S SLOTS AND THE RECORD'S ARE NOT THE SAME SLOTS on every path. A copy's host
* slots were the job's until it reported, and a promotion out of disk ran through a join
* slot the record never owned; freeing only the record's would leak those, and freeing
* the job's as well where they ARE the record's would return one slot twice. */
/* THE JOB'S SLOT AND THE RECORD'S ARE NOT THE SAME SLOT on every path. A copy's host slot
* is the job's until it reports; freeing only the record's would leak it, and freeing the
* job's as well where it IS the record's would return one slot twice. */
if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot);
ck_back();
release_storage(job.key, r);
free_host(r);
recs_.erase(it);
return;
}
@@ -871,8 +460,6 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
if (r.tier == KVTier::Device && r.host_slot >= 0) queue_clean(job.key, r);
/* A copy that failed is tried again. */
queue_copy(job.key, r);
/* And what landed goes on to disk. */
queue_disk(job.key, r);
return;
}
@@ -882,16 +469,12 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
r.blocks = job.blocks;
/* THE HOST COPY IS KEPT, which is what makes the entry clean the moment it lands:
* its VRAM copy can go again at no cost, and the next copy this conversation needs
* is only of the tokens its next turn adds. A disk entry keeps the slot it was
* read into for the same reason -- it holds exactly the entry's bytes -- and keeps
* its disk copy, which is what lets that slot go again for nothing. */
* is only of the tokens its next turn adds. */
r.host_slot = job.host_slot;
/* THE CLOCK RESTARTS: the entry came back because a request is about to hit it. */
if (now_ns) r.used_ns = now_ns;
r.fetched_ns = 0;
++stats_.promoted;
queue_clean(job.key, r);
queue_disk(job.key, r);
return;
}
if (!job.started) {
@@ -908,68 +491,19 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
* still holds an entry naming blocks that are not ours any more, and left alone it
* would serve them. */
if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot);
release_storage(job.key, r);
free_host(r);
recs_.erase(it);
drop_rooted(job.key);
if (on_drop_) on_drop_(job.key);
return;
case TierJob::Kind::DropHost:
give_slot(job.host_slot);
free_host(r);
++stats_.host_drops;
r.host_slot = -1;
release_storage(job.key, r);
recs_.erase(it);
drop_rooted(job.key);
if (on_drop_) on_drop_(job.key);
return;
case TierJob::Kind::ToHost: {
if (!job.started) {
/* NEVER READ: the slots go back and the record is where it was, on disk. */
give_slot(job.host_slot);
ck_back();
relist(job.key, r);
return;
}
if (!ok) {
/* THE STORE NO LONGER HOLDS WHAT THE RECORD SAYS IT DOES -- its own eviction does
* not tell the tiers, and a slot that fails its verify is dropped by the read. The
* record claims bytes nobody has, so it goes, and the cache has to hear so. */
give_slot(job.host_slot);
ck_back();
release_storage(job.key, r);
recs_.erase(it);
if (on_drop_) on_drop_(job.key);
return;
}
if (job.host_slot >= 0) {
r.host_slot = job.host_slot;
r.tier = KVTier::Host;
++stats_.fetched;
}
if (job.ck_want && job.ck_slot >= 0) {
/* THE SNAPSHOT IS IN ITS STORE SLOT AGAIN, and keeps its disk copy -- which is what
* lets the slot go again for nothing. The engine hands the slot to the cache's
* index entry (PrefixCache::reattach_snapshot). */
if (job.ck_ok && r.ck_slot < 0) {
r.ck_slot = job.ck_slot;
++stats_.ck_fetched;
} else {
ck_back();
if (!job.ck_ok && r.ck_slot < 0 && r.ck_on_disk) {
/* The disk store lost it; the blocks are still good. */
r.ck_on_disk = false;
++stats_.ck_drops;
if (on_ck_drop_) on_ck_drop_(job.key);
}
}
}
r.fetched_ns = now_ns ? now_ns : rad_mono_ns();
relist(job.key, r);
return;
}
case TierJob::Kind::ToDisk:
return; /* settled above */
}
}
@@ -988,7 +522,7 @@ static bool chain_extends(const std::vector<BlockHash>& shorter,
}
void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, int64_t n_tokens,
uint64_t now_ns) {
uint64_t now_ns, const std::string& label) {
if (chain.empty()) return;
std::lock_guard lk(mu_);
@@ -1008,6 +542,9 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
* to say which of them republished. So the most recent of them is touched and no row is
* added, which is the one answer that is wrong about nothing. */
uint64_t first_seen = 0;
/* A conversation's label outlives the turn that sent it: a later turn without one keeps the
* name an earlier one gave. */
std::string kept_label = label;
bool absorbed = false;
std::vector<uint64_t>& at_root = roots_[chain[0]];
for (size_t i = 0; i < at_root.size();) {
@@ -1016,6 +553,7 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
if (!chain_extends(it->second.chain, chain)) { ++i; continue; }
if (first_seen == 0 || it->second.first_seen_ns < first_seen)
first_seen = it->second.first_seen_ns;
if (kept_label.empty()) kept_label = it->second.label;
sessions_.erase(it);
at_root.erase(at_root.begin() + (long)i);
absorbed = true;
@@ -1028,7 +566,11 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
if (it == sessions_.end() || !chain_extends(chain, it->second.chain)) continue;
if (!newest || it->second.last_used_ns > newest->last_used_ns) newest = &it->second;
}
if (newest) { newest->last_used_ns = now_ns; return; }
if (newest) {
newest->last_used_ns = now_ns;
if (!label.empty()) newest->label = label;
return;
}
}
Session& s = sessions_[id];
@@ -1036,6 +578,7 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
s.n_tokens = n_tokens;
s.first_seen_ns = first_seen ? first_seen : now_ns;
s.chain = chain;
s.label = std::move(kept_label);
at_root.push_back(id);
}
@@ -1079,16 +622,17 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
si.model = model_;
si.n_tokens = kv.second.n_tokens;
si.first_seen_ns = kv.second.first_seen_ns;
si.label = kv.second.label;
si.last_used_ns = kv.second.last_used_ns;
si.bytes = (int64_t)kv.second.chain.size() * cfg_.entry_bytes;
out.push_back(std::move(si));
}
}
/* SNAPSHOTS IN THE STORE AND ON DISK, each once. The store is the engine's and is not read
* from this thread, and a disk snapshot has only a flag on its record -- but this walk visits
* every record a stored conversation reaches, so it counts them here. They are sparse, one
* per checkpoint interval, so the sets stay small beside the walk that fills them. */
std::unordered_set<BlockHash, BlockHashHash> disk_snaps, host_snaps;
/* SNAPSHOTS IN THE STORE, each once. The store is the engine's and is not read from this
* thread -- but this walk visits every record a stored conversation reaches, so it counts them
* here. They are sparse, one per checkpoint interval, so the set stays small beside the walk
* that fills it. */
std::unordered_set<BlockHash, BlockHashHash> host_snaps;
size_t kept = 0;
for (size_t k = 0; k < out.size(); ++k) {
SessionInfo& si = out[k];
@@ -1114,17 +658,14 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
switch (rr.tier) {
case KVTier::Device: ++si.on_device; break;
case KVTier::Host: ++si.on_host; break;
case KVTier::Disk: ++si.on_disk; break;
}
/* THE LINEAR HALF, COUNTED WHERE ITS BYTES ACTUALLY ARE and not where the blocks
* are: a snapshot is in host memory from the moment it is saved, whatever tier
* its blocks are on, and on disk alone once the store has given its slot up. */
const bool ck = rr.ck_slot >= 0 || rr.ck_on_disk;
if (rr.ck_slot >= 0) { ++si.snapshots; ++si.snap_host; }
else if (rr.ck_on_disk) { ++si.snapshots; ++si.snap_disk; }
if (rr.ck_on_disk && occ) disk_snaps.insert(h);
if (rr.ck_slot >= 0 && occ) host_snaps.insert(h);
if (ck && rr.ck_pos > si.resume_tokens) si.resume_tokens = rr.ck_pos;
/* THE LINEAR HALF, which is in host memory from the moment it is saved, whatever
* tier its blocks are on. */
if (rr.ck_slot >= 0) {
++si.snapshots;
if (occ) host_snaps.insert(h);
if (rr.ck_pos > si.resume_tokens) si.resume_tokens = rr.ck_pos;
}
}
if (at >= chain.size()) break;
}
@@ -1142,12 +683,10 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
Slice lk(mu_);
occ->host_bytes = arena_.used_slots() * cfg_.entry_bytes +
(int64_t)host_snaps.size() * cfg_.ckpt_bytes;
occ->disk_bytes = stats_.disk_bytes + (int64_t)disk_snaps.size() * cfg_.ckpt_bytes;
/* What the operator gave the block arena and the snapshot store -- the same scope as
* `host_bytes` above, which counts both. */
occ->host_cap_bytes = (host_on() ? cfg_.host_cap_bytes : 0) +
cfg_.ckpt_slots * cfg_.ckpt_bytes;
occ->disk_cap_bytes = disk_on() ? cfg_.disk_cap_bytes : 0;
}
return out;
}
+90 -252
View File
@@ -1,5 +1,5 @@
/* kvtier.h -- where a finished conversation's KV is kept once VRAM has a better use for it
* (spec §7.3).
* (spec §7.3): VRAM, then host memory, and nowhere else.
*
* The prefix cache holds a KV reference on every block it indexes, so a finished turn's context
* survives into the next one. That is the whole value of it, and it is also the whole cost: those
@@ -20,15 +20,14 @@
* published --(copy, at once)--> clean on device --(memory wanted)--> host
* ^ |
* +------------(a hit restores)------+
* host copy --(copy to disk, at once)--> clean on host --(a slot wanted)--> disk
*
* THE DISK TIER IS A COPY TOO, by the same argument one level down. Every host copy is written to
* the disk store in the background as soon as it lands, and keeps its host slot. Once the write
* has landed the host slot is as free to give up as a clean entry's VRAM: when a copy or a
* restore needs a slot and the arena is full, the oldest entries the disk also holds give theirs
* up, which is bookkeeping and nothing else. Moving an entry to disk only when its slot is wanted
* would put a write on the path of whatever wanted it -- a restore out of disk needs a host slot to
* read through, and an arena full of host-only entries has no slot to give it at all.
* HOST MEMORY IS THE LAST TIER. When a copy needs a slot and the arena is full, the oldest
* entries only the host holds are dropped, as many as the copies refused. Nothing is written to a
* drive: a tier there wears it at the rate the server prefills -- every block and every snapshot a
* prompt produces -- to spare a re-prefill only for what outgrows VRAM and host memory together.
*
* AND EVERY ENTRY EXPIRES. One no request has used for --prefix-cache-ttl seconds leaves the cache
* from whichever tier holds it (PrefixCache::expire); it is not moved anywhere first.
*
* THERE IS NO IDLE THRESHOLD ON THE WAY OUT OF VRAM, and that is the point of the design rather
* than an omission. A threshold is a guess at when an entry stops being worth its VRAM, made in
@@ -74,8 +73,7 @@
* is on no list: the copy it keeps off the card is what lets the VRAM copy go, and the tiers'
* lists are for entries no longer in VRAM. A Rec with a transfer through the pool outstanding is
* `pending` and is in no list either: it cannot be chosen as a victim, cannot be planned again,
* and cannot be erased until the engine reports the job finished or failed. A disk write is not
* such a transfer -- it reads host memory and nothing else -- and holds only the slots it reads.
* and cannot be erased until the engine reports the job finished or failed.
*/
#pragma once
#include "mem/hostarena.h"
@@ -86,7 +84,7 @@
#include <cstdint>
#include <deque>
#include <functional>
#include <list>
#include <map>
#include <atomic>
#include <mutex>
#include <string>
@@ -96,9 +94,7 @@
namespace rad {
class SSDTier;
enum class KVTier : uint8_t { Device = 0, Host = 1, Disk = 2 };
enum class KVTier : uint8_t { Device = 0, Host = 1 };
const char* kv_tier_name(KVTier t);
/* What the engine is being asked to do. One job is one entry moving one step. The block ids are
@@ -107,47 +103,23 @@ const char* kv_tier_name(KVTier t);
struct TierJob {
enum class Kind : uint8_t {
WriteBack, /* gather_rows out of the pool into a host slot; the entry stays in VRAM */
ToDisk, /* a host slot written to the disk store; the host copy is kept */
ToDevice, /* allocate blocks, scatter_rows in; the host copy is kept */
DropHost, /* no disk tier and the arena is full: this record's bytes go */
ToHost, /* the disk store read into a host slot, ahead of the restore that wants it */
DropHost, /* the arena is full: this record's bytes go */
};
Kind kind = Kind::WriteBack;
BlockHash key;
/* Per cached group, in PrefixCache::cached_groups() order. For a write-back these are the
* blocks to read -- EMPTY when only the snapshot is being copied, because the blocks already
* have their host copy; for a promotion they are filled in by the engine with the blocks it
* blocks to read; for a promotion they are filled in by the engine with the blocks it
* allocated. */
std::vector<int32_t> blocks;
int32_t host_slot = -1;
int64_t bytes = 0;
/* ---- the linear half, on a hybrid model ----
*
* A session's recurrent state lives in a SNAPSHOT SLOT of the checkpoint store -- pinned host
* memory, one contiguous KVManager::checkpoint_bytes() shard a rank -- rather than in blocks,
* so it never crosses the link with them: a lookup restores it straight out of its slot. The
* tiers only move it between that slot and the disk store, on the disk thread: a ToDisk job
* reads `ck_slot`, a ToHost job writes it.
*
* `ck_slot` is an INPUT to both. A read off disk is planned with `ck_want` and the engine
* allocates the slot before the job leaves its hands (it holds the store's free list); a
* write names the slot the snapshot is in. */
int32_t ck_slot = -1;
int64_t ck_pos = 0; /* the token position, which the disk store verifies on the way back */
bool ck_want = false; /* a read off disk should bring the snapshot in too */
int64_t ck_bytes = 0;
/* DID THE SNAPSHOT HALF SUCCEED. Separate from the job's own result because the two halves
* fail for different reasons and are repaired differently: a snapshot whose disk write failed
* is still correct in its slot, and one whose read failed costs the session a replay of its
* linear layers, not its blocks. */
bool ck_ok = true;
/* A PROMOTION THAT WAS NEVER STARTED, as opposed to one that failed part of the way through.
* A restore reserves every block before it moves a byte, and a chain that did not fit is cut
* where the reservation ran out: the entries past that point were not touched, their host
* copies are exactly what they were, and they stay on the host tier. Only an entry whose
* scatter may have run is dropped on failure. A read off disk that never ran -- its batch
* could not be handed to the thread -- is the same: the record stays on disk. */
* scatter may have run is dropped on failure. */
bool started = false;
};
@@ -156,23 +128,19 @@ class IdleTiers {
public:
struct Config {
int64_t host_cap_bytes = 0; /* 0 is off */
int64_t disk_cap_bytes = 0;
int64_t entry_bytes = 0; /* one entry: sum over cached groups of bytes_per_block */
/* ---- the linear half ----
* `ckpt_bytes` is ONE SNAPSHOT, every rank's shard of it, laid out exactly like
* `entry_bytes`. The snapshots live in the engine's checkpoint store, `ckpt_slots` deep,
* which is reported here and not allocated: --prefix-cache-host-mib is the blocks' alone.
* `ckpt_disk_slots` zero means snapshots never reach disk, and the blocks still do. */
* which is reported here and not allocated: --prefix-cache-mib is the blocks' alone. */
int64_t ckpt_bytes = 0;
int64_t ckpt_slots = 0; /* the checkpoint store's capacity, for the report and view */
int64_t ckpt_disk_slots = 0; /* how many the disk store was opened for */
};
int configure(const Config& c, SSDTier* disk);
int configure(const Config& c);
void close();
bool host_on() const { return cfg_.host_cap_bytes > 0 && arena_.enabled(); }
bool disk_on() const { return cfg_.disk_cap_bytes > 0 && disk_ != nullptr; }
bool any_on() const { return host_on() || disk_on(); }
bool any_on() const { return host_on(); }
std::string report() const;
/* Called by PrefixCache whenever an entry is inserted. The blocks come with it because a copy
@@ -189,7 +157,7 @@ public:
* storage it held is returned. A record with work outstanding is marked instead of erased and
* is cleaned up when the job reports. */
void forget(const BlockHash& key);
/* AN OFF-DEVICE ENTRY WAS RECOMPUTED. A request that could not reach the tier copy -- a
/* AN OFF-DEVICE ENTRY WAS RECOMPUTED. A request that could not reach the host copy -- a
* restore that did not fit, a chain past the point a promotion was cut -- computes the same
* tokens again and publishes them, and the cache takes those blocks as the entry's device
* copy. The tier copy goes: two copies of one entry computed by two different batches agree
@@ -209,10 +177,9 @@ public:
* slots already allocated. Oldest first, so a conversation that went idle before another is
* copied before it. Blocks only: a snapshot is in host memory from the moment it is saved.
*
* Every record named by a returned job is `pending` until report() is called for it. An arena
* too full to take the batch first gives up the host slots of the oldest entries the disk also
* holds (make_room); what is still short stays queued, and with no disk tier the next
* maintenance plan drops that many of the oldest host-only entries. */
* Every record named by a returned job is `pending` until report() is called for it. What an
* arena too full to take the batch cannot hold stays queued, and the next maintenance plan
* drops that many of the oldest host-only entries. */
void plan_writeback(int64_t max_entries, std::vector<TierJob>* out);
bool writeback_waiting() const;
/* Has the arena refused a copy since the last maintenance plan? That plan is then due now. */
@@ -223,87 +190,36 @@ public:
* free nothing -- and reports what it did through drop_commit. A key handed out here and not
* dropped is the cache's to ask about again. */
void take_clean(std::vector<BlockHash>* out);
/* Can this entry's blocks leave VRAM for nothing, right now: a copy off the card has landed --
* in host memory or on disk -- and no job is out on the record. */
/* Can this entry's blocks leave VRAM for nothing, right now: its host copy has landed and no
* job is out on the record. */
bool droppable(const BlockHash& key) const;
/* The cache released the blocks. The record is now a host record with its copy, on the host
* tier's list like any other -- or a disk record, when its host slot was already given up.
* Its snapshot stays in its slot: the store is not the pool, and the blocks leaving frees
* nothing there. */
* tier's list like any other. Its snapshot stays in its slot: the store is not the pool, and
* the blocks leaving frees nothing there. */
void drop_commit(const BlockHash& key);
/* ---------------- the snapshots' own pressure ----------------
/* ---------------- capacity ----------------
*
* The checkpoint store is --checkpoint-slots deep for the whole server, and when it is full
* the cache retires the least recently used snapshot to make room. One the disk also holds
* need not be lost: the cache DETACHES it instead -- the slot goes back, the index entry
* stays, and the next restore of the session reads the state back off disk (plan_fetch).
* True when this key's snapshot is in a slot and has a finished disk copy that no write is
* still producing. */
bool snapshot_backed(const BlockHash& key) const;
/* Is this key's snapshot in store slot `slot` by this object's record? */
bool snapshot_in_slot(const BlockHash& key, int32_t slot) const;
/* The cache gave the slot back; the disk copy is now the snapshot. */
void snapshot_detached(const BlockHash& key);
/* ---------------- the slow half ----------------
*
* The host copies waiting for their disk copy, in the order they landed, as ToDisk jobs --
* blocks and snapshot halves together where both are waiting, and a resume point's snapshot
* ahead of everything (note_snapshot). A ToDisk job does NOT make its record pending: it only
* reads the host slots it names, which a restore may read at the same time, and a slot given
* up while the write is out is freed when the write reports rather than under it. With no disk tier, the copies the arena refused since the last plan
* are made room for by dropping that many of the oldest host-only entries. `budget` bounds
* one plan so the IO a pass asks for is bounded too. */
* The copies the arena refused since the last plan are made room for by dropping that many of
* the oldest host-only entries, as DropHost jobs; `budget` bounds one plan. */
void plan(int budget, std::vector<TierJob>* out);
/* Is a host copy waiting for its disk copy? The slow half is then due now rather than on its
* once-a-second clock: an entry the disk does not hold yet is one whose host slot cannot be
* given up for nothing. */
bool disk_waiting() const;
/* ROOM IN THE ARENA, FOR NOTHING. Up to `n` host slots of entries the disk also holds, given
* up oldest first: host records first -- they become disk records -- and then the host copies
* of clean VRAM entries, which stay clean through their disk copy. Nothing is written; an
* entry whose disk copy has not landed is not a candidate. Returns how many were freed. */
int64_t make_room(int64_t n);
/* ---------------- reading a chain back off disk, before its request runs ----------------
/* ---------------- expiry ----------------
*
* A RESTORE COPIES HOST MEMORY TO THE DEVICE AND NOTHING ELSE. It runs inside the scheduler's
* step, and a disk read there -- thousands of entries for a long conversation -- would hold
* every other request's next token for as long as the reads take. So the disk half of a chain
* is read into host slots on the IO thread first, as ToHost jobs, while the request that wants
* it waits outside admission and everything else keeps running; the restore then finds the
* chain in host memory.
*
* `chain` is every key a prompt's prefix matched, in order. True when the request must wait:
* a read for one of its entries was planned now, into `out`, or is already out. False when
* none of the chain is on disk, or none of what is can be given a slot -- a chain larger than
* the arena comes back as far as the arena holds, and the rest is prefilled.
*
* The chain's deepest snapshot, when it is only on disk, is read with it -- that is the state
* the hit resumes from -- into the store slot `*ck_slot` the caller allocated after asking
* snapshot_fetch_wanted. The slot is taken (and `*ck_slot` set to -1) only when the read is
* planned; otherwise it is still the caller's to free. Every record named is `pending` until
* the read reports, and what a read brought in is not given up to make room for anybody else
* until the request has had the step it needs to claim it. */
bool plan_fetch(const std::vector<BlockHash>& chain, std::vector<TierJob>* out,
uint64_t now_ns, int32_t* ck_slot = nullptr);
/* Would plan_fetch read this chain's deepest snapshot off disk -- is it there and nowhere
* else? Asked first, because the slot it reads into is the store's, which the caller owns. */
bool snapshot_fetch_wanted(const std::vector<BlockHash>& chain) const;
* THE HOST RECORDS NO REQUEST HAS USED SINCE `cutoff_ns`, oldest first, up to `max`: what
* --prefix-cache-ttl takes out of host memory. The cache drops each one (drop_offdevice) and
* the record goes with it; a record with a job out is passed over and asked about again. */
void expired(uint64_t cutoff_ns, size_t max, std::vector<BlockHash>* out) const;
/* A promotion, asked for by a lookup that hit off-device. Returns false when the entry is not
* in host memory -- a disk entry is read in by plan_fetch first -- or already has work
* outstanding. */
* in host memory or already has work outstanding. */
bool plan_promote(const BlockHash& key, TierJob* out);
/* The engine finished (or failed) a job. On failure the record returns to the state it was in
* with its storage intact, EXCEPT for a failed ToDevice that had started, which cannot leave a
* half-scattered pool behind and so drops the entry -- and a disk read that failed is marked
* started for that reason too: the store no longer holds what the record says it does. A
* successful ToDevice restarts the record's clock at `now_ns` when one is given: the promotion
* happened because something is about to use it. */
* half-scattered pool behind and so drops the entry. A successful ToDevice restarts the
* record's clock at `now_ns` when one is given: the promotion happened because something is
* about to use it. */
void report(const TierJob& job, bool ok, uint64_t now_ns = 0);
/* WAS THIS KEY FORGOTTEN WHILE ITS JOB WAS OUT -- or is it not known at all. The engine asks
@@ -314,8 +230,8 @@ public:
/* ============================ WHEN THE BYTES ARE GONE, SO IS THE ENTRY ====================
*
* A record erased while its bytes are OFF-DEVICE -- a capacity drop, or a promotion that
* failed -- leaves the prefix cache holding an entry whose block ids the pool has already
* A record erased while its bytes are OFF-DEVICE -- a capacity drop, a promotion that failed,
* an expiry -- leaves the prefix cache holding an entry whose block ids the pool has already
* given to somebody else. `resident_off_device` then answers false, because there is no
* record any more, and the cache would serve those ids as an ordinary hit: one conversation
* gets another's context, as fluent and plausible text.
@@ -326,43 +242,18 @@ public:
/* ---------------- the linear half of an idle session ----------------
*
* Told by PrefixCache::commit_checkpoint, for the same reason note_used carries the block ids:
* a copy has to know what to move and the cache's index is the only place it is written down.
* `slot` is a checkpoint store slot and `pos` the token position the disk store verifies a
* read against.
*
* A record may hear this BEFORE it hears note_used -- a checkpoint is committed mid-request
* and the chain is published when the request closes -- so this creates the record if it has
* to. The snapshot is queued for its disk copy when the record is published, or at once when
* it already was -- or AT ONCE AND AHEAD OF EVERYTHING when it is a resume point (`resume`):
* the deepest checkpoint its prompt gets, which the next turn resumes from. Until it is on disk
* the store can only retire it, and a burst of prefills churns the store through the whole
* decode in between. */
void note_snapshot(const BlockHash& key, int32_t slot, int64_t pos, bool resume = false);
/* The cache is done with the snapshot at `key`, which is in store slot `slot`: return whatever
* the tiers hold for it. The record's BLOCKS are untouched -- the two halves are retired by
* different policies on different clocks, and a snapshot the retention policy drops says
* nothing about the prefix.
*
* TRUE WHEN A DISK WRITE IS STILL READING THE SLOT, and then the slot is NOT the caller's to
* free: a save into it would put half of another snapshot on disk under this key. The tiers
* keep the slot and hand it back through `take_checkpoint_frees` once the write has reported.
* Decided by the slot and not by the record, which may have gone while the write was out. */
bool release_snapshot(const BlockHash& key, int32_t slot);
/* Store slots whose release waited on a disk write, now safe to free. */
void take_checkpoint_frees(std::vector<int32_t>* out);
/* Is a disk write reading store slot `slot` right now? A save into it would tear the write. */
bool slot_reading(int32_t slot) const;
/* THE TIERS LOST A SNAPSHOT BUT KEPT THE BLOCKS: its only copy was on disk and the disk store
* no longer has it. The cache has to stop offering an index entry whose bytes nobody holds.
* Wired to PrefixCache::drop_snapshot; separate from set_drop_sink because losing half an
* entry and losing all of it are different events with different repairs. Never said of a
* snapshot still in its slot: that one is the cache's. */
void set_snapshot_drop_sink(std::function<void(const BlockHash&)> f) { on_ck_drop_ = std::move(f); }
/* Do snapshots reach disk at all? */
bool ckpt_disk_on() const { return disk_on() && cfg_.ckpt_bytes > 0 && cfg_.ckpt_disk_slots > 0; }
* Told by PrefixCache::commit_checkpoint and PrefixCache::retire_ckpt, so the session view can
* say which conversations hold a snapshot and where a return resumes from. A snapshot lives in
* its checkpoint store slot, in host memory, and never moves: the tiers only record it. A
* record may hear of a snapshot BEFORE it hears note_used -- a checkpoint is committed
* mid-request and the chain is published when the request closes -- so this creates the
* record if it has to. */
void note_snapshot(const BlockHash& key, int32_t slot, int64_t pos);
/* The cache is done with the snapshot at `key`. The record's BLOCKS are untouched -- the two
* halves are retired by different policies on different clocks, and a snapshot the retention
* policy drops says nothing about the prefix. */
void release_snapshot(const BlockHash& key);
int64_t ckpt_bytes() const { return cfg_.ckpt_bytes; }
int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; }
int64_t ckpt_slots() const { return cfg_.ckpt_slots; }
/* ---------------- the session view ----------------
@@ -375,48 +266,43 @@ public:
*
* THE SIZES THEREFORE OVERLAP AND THE TOTAL IS NOT A SUM. Sharing is the point of the cache;
* a view that hid it would make a server look like it was storing several times what it is.
* Anything reporting these numbers says so.
*
* The model name is carried rather than looked up because the disk tier outlives the process:
* a store written by one container and read back under another is refused by fingerprint, and
* the name is what turns that refusal into something an operator can act on. */
* Anything reporting these numbers says so. */
struct SessionInfo {
uint64_t id = 0;
std::string model;
std::string label; /* the client's own name for the conversation, or "" */
int64_t n_tokens = 0;
int64_t bytes = 0;
uint64_t first_seen_ns = 0;
uint64_t last_used_ns = 0;
int64_t on_device = 0, on_host = 0, on_disk = 0; /* blocks, by tier */
int64_t on_device = 0, on_host = 0; /* blocks, by tier */
/* LINEAR STATE, on a hybrid model. Counted separately from blocks because it is a
* different resource with a different scarcity: a snapshot is thousands of blocks' worth
* of bytes and there are only --checkpoint-slots of them in host memory. A session showing
* blocks on disk and no snapshot anywhere is one that will come back and re-run every
* blocks in host memory and no snapshot is one that will come back and re-run every
* recurrent layer over its whole transcript, which is not what "restored" should mean. */
int64_t snapshots = 0; /* this session holds, any tier */
int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */
int64_t snapshots = 0; /* this session holds */
int64_t snap_bytes = 0;
/* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain, in any
* tier. On a hybrid model the scheduler clamps a hit to the last linear checkpoint it can
/* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain. On a
* hybrid model the scheduler clamps a hit to the last linear checkpoint it can
* reach, so this -- not n_tokens and not the blocks -- is the prefix the next turn skips,
* and n_tokens minus it is what that turn prefills. Zero with no snapshot anywhere. */
int64_t resume_tokens = 0;
bool moving = false; /* a job is outstanding */
};
/* WHAT THE TIERS OFF THE CARD ARE HOLDING, blocks and snapshots together, each counted once.
* The per-session figures cannot be summed into this: sessions sharing a prefix share its
* blocks and its snapshots. Caps are what the operator configured, snapshots included. A
* clean entry's host copy is counted: it occupies the arena whether or not the VRAM copy has
* gone yet. */
/* WHAT HOST MEMORY IS HOLDING FOR THE CACHE, each block counted once. The per-session figures
* cannot be summed into this: sessions sharing a prefix share its blocks. The cap is what the
* operator configured. A clean entry's host copy is counted: it occupies the arena whether or
* not the VRAM copy has gone yet. */
struct Occupancy {
int64_t host_bytes = 0, disk_bytes = 0;
int64_t host_cap_bytes = 0, disk_cap_bytes = 0;
int64_t host_bytes = 0;
int64_t host_cap_bytes = 0;
};
/* Publish one request's chain. Called from PrefixCache::insert, which is the only place that
* knows a chain was completed rather than merely touched.
*
* KEPT WHETHER OR NOT ANY TIER IS ON, because what it records is not a tiering fact. A server
* with no --prefix-cache-host-mib still stores conversations -- it stores them all in VRAM, which
* with no --prefix-cache-mib still stores conversations -- it stores them all in VRAM, which
* is the case the table most wants to show -- and gating the record on the mover would make
* the view report an empty server to every operator who has not opted into tiering.
*
@@ -426,7 +312,7 @@ public:
* is a row per turn -- a table nobody can read, holding a copy of every prefix of the
* transcript for as long as the newest. */
void note_session(uint64_t id, const std::vector<BlockHash>& chain, int64_t n_tokens,
uint64_t now_ns);
uint64_t now_ns, const std::string& label = std::string());
void set_model(const std::string& m) { model_ = m; }
/* Newest activity first. Recomputes each session's tier histogram from the records, so it is
* a view and never a second copy of the truth. The walk takes the lock in slices and lets
@@ -440,19 +326,11 @@ public:
* then given up. They are different events: a copy is link traffic and a drop is VRAM
* handed to something else, and a conversation that returns before anything wants its
* VRAM is copied and never dropped. */
int64_t to_host = 0, dropped = 0, to_disk = 0, promoted = 0;
/* `host_freed` is host slots given up because the disk holds the entry -- the host tier's
* counterpart of `dropped`; `host_drops` is entries lost with no disk tier to hold them. */
int64_t host_freed = 0, host_drops = 0, failures = 0;
int64_t host_bytes = 0, disk_bytes = 0;
int64_t host_hits = 0, disk_hits = 0;
/* Entries and snapshots read off disk into host memory ahead of a restore. */
int64_t fetched = 0, ck_fetched = 0;
/* SNAPSHOTS MOVED, counted apart from blocks. A hybrid session can move its whole chain
* off the device and still replay every linear layer from zero on the way back, and no
* block counter can tell the two apart -- these are the numbers that can. `ck_drops` is
* snapshots whose only copy was lost. */
int64_t ck_to_disk = 0, ck_drops = 0;
int64_t to_host = 0, dropped = 0, promoted = 0;
/* `host_drops` is entries the full arena gave up. */
int64_t host_drops = 0, failures = 0;
int64_t host_bytes = 0;
int64_t host_hits = 0;
/* WHAT THE STEP THREAD SPENT ON THEM, under the scheduler's lock: restores issued at
* admission, and copies landed synchronously because pressure could not wait for them.
* Host time, not link time -- what every other request waits through. */
@@ -473,82 +351,47 @@ private:
KVTier tier = KVTier::Device;
uint64_t used_ns = 0;
/* THE HOST COPY. On a device record it is a copy that makes the record clean; on a host
* record it is where the bytes are read from. -1 on a disk record always. */
* record it is where the bytes are read from. */
int32_t host_slot = -1;
/* THE DISK STORE HOLDS THESE BYTES, written from the host copy. What makes the host slot
* free to give up, and a device record with no host copy clean. The store evicts on its own
* and does not say so; a read that finds the entry gone drops it (report). */
bool on_disk = false;
/* The host slot a disk write is reading right now, -1 when none. A slot given up while
* this names it is freed when the write reports, not under it. */
int32_t disk_src = -1;
bool disk_q = false; /* in dk_q_: waiting for a disk copy */
bool pending = false;
bool fetching = false; /* the pending job is a read off disk (plan_fetch) */
bool doomed = false; /* forget() arrived while pending */
bool queued = false; /* in wb_q_: waiting for a copy */
bool resume_q = false; /* in resume_q_: a resume point waiting for its disk copy */
bool clean_q = false; /* in clean_q_: a drop the cache has not been asked about */
bool listed = false; /* on host_lru_ or disk_lru_; `it` is valid */
bool listed = false; /* on host_lru_; `it` is valid */
std::vector<int32_t> blocks;
/* ---- the linear half ----
* `ck_slot` is the snapshot's checkpoint store slot and `ck_on_disk` the disk store's
* copy. A snapshot the store gave up has only the second. All clear when the record
* carries no snapshot, which is the common case -- one block in every
* (interval / block_size) is a checkpoint position. */
* `ck_slot` is the snapshot's checkpoint store slot and `ck_pos` its token position, for the
* session view. -1 when the record carries no snapshot, which is the common case -- one
* block in every (interval / block_size) is a checkpoint position. */
int32_t ck_slot = -1;
bool ck_on_disk = false;
int64_t ck_pos = 0;
/* The store slot a disk write is reading, as `disk_src` is for the blocks. */
int32_t ck_disk_src = -1;
/* WHEN A READ OFF DISK BROUGHT THIS RECORD IN, 0 when none did or its restore has run.
* Until the request that asked for it has been admitted the slots are its and not the
* arena's to give up: two conversations waiting on reads into a full arena would
* otherwise each evict what the other had read, and neither would ever be restored. Held
* for kFetchHoldNs at most, which bounds what a request that went away can pin. */
uint64_t fetched_ns = 0;
/* Set only while plan_fetch makes room: this record is part of the chain being read, and
* giving its slot up to read another part of the same chain would be no progress. */
bool keep = false;
std::list<BlockHash>::iterator it;
std::multimap<uint64_t, BlockHash>::iterator it;
};
/* Does this record want a host copy it does not have yet? Its blocks are in VRAM with none. */
bool wants_copy(const Rec& r) const;
/* And a disk copy: a host copy of either half that the disk does not hold yet. */
bool wants_disk(const Rec& r) const;
bool wants_ck_disk(const Rec& r) const;
void queue_copy(const BlockHash& key, Rec& r);
void queue_clean(const BlockHash& key, Rec& r);
void queue_disk(const BlockHash& key, Rec& r);
/* GIVE UP A HOST SLOT, the record's or a finished job's. Every block-arena free goes through
* `give_slot`, because a freed slot is what unblocks a write-back that found the arena full.
* `free_host` is the record's own: a slot a disk write is reading is left
* for that write's report to free. */
* `free_host` is the record's own. */
void give_slot(int32_t slot);
void free_host(Rec& r);
void set_on_disk(Rec& r, bool v);
int64_t make_room_locked(int64_t n);
/* May this record's host copies be given up to make room right now? Not while a read put
* them there for a request that has not claimed them yet, nor while the chain being read
* includes it. */
bool held_by_fetch(const Rec& r, uint64_t now_ns) const;
void unlist(Rec& r);
void relist(const BlockHash& key, Rec& r);
std::list<BlockHash>& list_for(KVTier t) { return t == KVTier::Host ? host_lru_ : disk_lru_; }
void release_storage(const BlockHash& key, Rec& r);
/* The chain position of the deepest snapshot no job is out on, or chain.size(). */
size_t deepest_snapshot(const std::vector<BlockHash>& chain) const;
struct Session {
int64_t n_tokens = 0;
uint64_t first_seen_ns = 0;
uint64_t last_used_ns = 0;
std::vector<BlockHash> chain;
std::string label;
};
/* Erase one row and its root index entry together. */
void drop_session(uint64_t id);
/* Every row whose chain starts at `key`, which has gone for good. */
void drop_rooted(const BlockHash& key);
/* The body of close(), for a caller that already holds the lock. */
void reset();
@@ -592,42 +435,37 @@ private:
mutable YieldingMutex mu_;
Config cfg_;
SSDTier* disk_ = nullptr;
HostArena arena_;
std::unordered_map<BlockHash, Rec, BlockHashHash> recs_;
std::list<BlockHash> host_lru_, disk_lru_; /* front = oldest */
/* THE HOST-ONLY RECORDS BY LAST USE, begin() the least recently used. Keyed by the clock rather
* than kept in the order records arrive, because a record arrives here when its VRAM copy is
* given up, which says nothing about when a request last read it -- and both the capacity drop
* and the expiry take the oldest by use. */
std::multimap<uint64_t, BlockHash> host_lru_;
/* THE WORK QUEUES, in the order the work arrived. Each holds a key at most once -- the Rec's
* flag says whether it is in -- and a key whose record changed under it is skipped when it is
* reached rather than searched for, so both stay a push and a pop. */
std::deque<BlockHash> wb_q_; /* records wanting a host copy */
std::deque<BlockHash> resume_q_; /* resume points wanting a disk copy, served first */
std::deque<BlockHash> dk_q_; /* records wanting a disk copy, in the order they landed */
std::vector<BlockHash> clean_q_; /* records whose VRAM copy may now go */
/* STORE SLOTS A DISK WRITE IS READING, and those the cache let go of meanwhile. Kept by slot
* and not on the record, because the record can be forgotten while the write is out and the
* slot is the cache's either way. A few entries at most: one write batch is out at a time. */
std::vector<int32_t> ck_reading_;
std::vector<int32_t> ck_free_after_;
std::vector<int32_t> ck_frees_; /* store slots a finished write released */
/* COPIES THE ARENA REFUSED since the last maintenance plan, which is what that plan frees
* room for. A count and not a list: any host-only entry makes room for any copy. */
int64_t starved_ = 0;
/* A WRITE-BACK FOUND THE ARENA FULL AND NOTHING TO GIVE UP. Waiting again changes nothing until
* a slot is freed or an entry's disk copy lands, so the copy is not planned until one does --
* otherwise every tick pops the queue, finds no slot and puts it back. */
* a slot is freed, so the copy is not planned until one is -- otherwise every tick pops the
* queue, finds no slot and puts it back. */
bool wb_stuck_ = false;
std::unordered_map<uint64_t, Session> sessions_;
/* THE DEATH SIGNAL FOR A ROW, and the reason the table is bounded. A published chain is only
* ever reachable from position zero, so the moment the cache evicts its FIRST block the
* conversation cannot be hit at any length and the row describes blocks that are not there.
* The cache announces every eviction through forget(), which is the only notice this object
* gets, so the root is indexed and the row goes with it. Several sessions share a root when
* The cache announces its evictions and expiries through forget(), and the entries this object
* drops itself -- a full arena's, a failed restore's -- go through drop_rooted as well, so the
* root is indexed and the row goes with it. Several sessions share a root when
* they share a system prompt and all of them are unreachable together, which is why the value
* is a list. */
std::unordered_map<BlockHash, std::vector<uint64_t>, BlockHashHash> roots_;
std::string model_;
std::function<void(const BlockHash&)> on_drop_;
std::function<void(const BlockHash&)> on_ck_drop_;
Stats stats_;
std::string report_;
};
+11 -37
View File
@@ -199,22 +199,20 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
const int64_t MiB = 1024 * 1024;
const int64_t w = cfg.vram_weights_mib * MiB;
const int64_t kv = cfg.vram_kv_mib * MiB;
const int64_t hp = cfg.host_pool_mib * MiB;
const int64_t hp = cfg.host_pool_total_mib() * MiB;
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM. Either the
* operator stated them or core/mem/vram_budget.cpp derived them from the card, the measured
* driver residency and the computed arena -- and either way they arrive here as two numbers
* with a report behind them. Either way this component refuses rather than shrinking
* anything: an engine that quietly re-optimises a split is an engine whose
* benchmarks do not reproduce (spec §6). A zero here means the resolver was never called,
* which is a wiring bug and gets named as one. */
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM.
* core/mem/vram_budget.cpp derived them from the card, the measured driver residency and the
* computed arena, and they arrive here as two numbers with a report behind them. This
* component refuses rather than shrinking anything: an engine that quietly re-optimises a
* split is an engine whose benchmarks do not reproduce (spec §6). A zero here means the
* resolver was never called, which is a wiring bug and gets named as one. */
std::string missing;
if (cfg.vram_weights_mib <= 0) missing += " vram_weights resolved to 0 MiB\n";
if (cfg.vram_kv_mib <= 0) missing += " vram_kv resolved to 0 MiB\n";
if (!missing.empty()) {
fit_report_ = "VRAM pool budgets are empty -- state --vram-weights-mib / --vram-kv-mib, or "
"let the card be split from --gpu-headroom-mib and --host-pool-mib:\n"
+ missing;
fit_report_ = "VRAM pool budgets are empty: the budget resolver (core/mem/vram_budget.cpp) "
"did not run before the pools were configured:\n" + missing;
RAD_ERR("%s", fit_report_.c_str());
return RAD_E_INVAL;
}
@@ -230,8 +228,8 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
" total %10s\n"
" card total %10s\n"
" OVER BY %10s\n"
"Lower --vram-weights-mib / --vram-kv-mib, or state neither and let the card be split "
"from --gpu-headroom-mib and --host-pool-mib (spec §6).\n",
"The resolved split is larger than the card, which the resolver does not produce: a "
"wiring bug (spec §6).\n",
humanb(w).c_str(), humanb(kv).c_str(),
humanb(want).c_str(), humanb(vram_capacity).c_str(),
humanb(want - vram_capacity).c_str());
@@ -239,30 +237,6 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
return RAD_E_NOMEM;
}
/* THE SLACK IS NAMED, because nothing else will name it -- and after the resolver ran there
* should be almost none. `vram_capacity` is totalGlobalMem: it is not the free VRAM and it is
* not the sum of the budgets. What is left over here is the driver's residency, the activation
* arena, --gpu-headroom-mib, and whatever MiB rounding could not place; vram_budget.cpp's
* report breaks that down term by term. A budget a couple of GiB under the card is that much
* of the expert plane streaming from host memory instead, which costs real prefill throughput
* on a model whose experts do not fit.
*
* THIS IS FOR A STATED BUDGET AND ONLY FOR ONE. A size threshold cannot tell the two apart: a
* small dense model whose cache is already at the largest context it can address leaves many
* GiB that NOTHING can spend, and warning there would tell the operator to leave unset the
* very flags they already left unset. Where the resolver made the split it has already printed
* every term including the unusable one, and there is nothing to add. */
if (vram_capacity > 0 && !cfg.vram_budget_derived) {
const int64_t slack = vram_capacity - want;
if (slack >= 1024 * MiB)
RAD_WARN("VRAM budgets total %s of the card's %s, so %s is neither budgeted nor "
"accounted. The driver's context, the activation arena and "
"--gpu-headroom-mib come out of it; anything past those is throughput on the "
"floor. Leave --vram-weights-mib / --vram-kv-mib unset to have the card split "
"automatically.",
humanb(want).c_str(), humanb(vram_capacity).c_str(), humanb(slack).c_str());
}
int st = RAD_OK;
int s;
/* Order matters only for the diagnostic: allocate the two big ones first so a failure names
+111 -184
View File
@@ -13,9 +13,7 @@ namespace rad {
* shared and long-lived is usually keyed by SHA-256, because a cheap hash's collision would serve
* one caller another caller's context. We get the same guarantee more cheaply: every entry keeps
* its BLOCK'S TOKEN IDS and compares them on a hit, so a collision is a miss rather than a wrong
* answer, and the hash only has to be good enough to keep the bucket chains short. The SSD tier,
* which is such a store, carries the token ids into the slot header for the same reason
* (sstier.h).
* answer, and the hash only has to be good enough to keep the bucket chains short.
*
* splitmix64's finaliser, which is a full 64-bit bijection -- so folding one token cannot lose the
* bits of the previous one, which is the failure mode of a plain multiply-xor chain. */
@@ -158,6 +156,9 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
}
interval_ = checkpoint_interval;
/* A WINDOW SNAPSHOT is state in the same sense: a hit is reusable at a checkpoint only, where
* the slot carries the window behind it (KVManager::has_window_snapshot). */
if (kv->has_window_snapshot() && interval_ > 0) has_linear_ = true;
if (has_linear_) {
if (interval_ <= 0) {
RAD_ERR("checkpoint_interval is %lld but the model has linear-attention state. A "
@@ -216,10 +217,11 @@ std::vector<BlockHash> PrefixCache::chain_all(const std::vector<int32_t>& tokens
return hs;
}
void PrefixCache::touch(const BlockHash& h) const {
void PrefixCache::touch(const BlockHash& h, uint64_t now_ns) const {
auto it = map_.find(h);
if (it == map_.end() || !it->second.in_lru) return;
lru_.splice(lru_.end(), lru_, it->second.lru);
it->second.used_ns = now_ns;
}
CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
@@ -271,7 +273,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
auto best = ck_by_prefix_.end();
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
const Ckpt& c = it->second;
if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > limit ||
if (!c.valid || c.slot < 0 || c.pos <= 0 || c.pos > limit ||
c.pos % block_size_ != 0)
continue;
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
@@ -299,8 +301,9 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
}
}
const uint64_t now = rad_mono_ns();
for (int64_t b = 0; b < matched; ++b) {
touch(hs[(size_t)b]);
touch(hs[(size_t)b], now);
if (!blocks_out) continue;
const Entry& e = map_.find(hs[(size_t)b])->second;
for (size_t g = 0; g < groups_.size(); ++g)
@@ -310,7 +313,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
* entry leaves the device, and without this it runs from when the chain was published, so a
* prefix hit on every turn -- or one just promoted back for this very lookup -- would read as
* idle and be demoted from under the request using it. */
if (tiers_ && matched > 0) tiers_->note_hits(hs.data(), matched, rad_mono_ns());
if (tiers_ && matched > 0) tiers_->note_hits(hs.data(), matched, now);
hit.n_attn_tokens = (int32_t)(matched * block_size_);
stats_.block_hits += matched;
stats_.block_misses += n_full - matched;
@@ -333,6 +336,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
hit.n_linear_tokens = (int32_t)best->second.pos;
hit.checkpoint_slot = best->second.slot;
best->second.used = ++clock_;
best->second.used_ns = now;
handed_.push_back(best->first);
++stats_.ckpt_hits;
return hit;
@@ -342,7 +346,7 @@ int PrefixCache::insert(uint64_t session,
const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
const std::vector<std::vector<int32_t>>& blocks,
int64_t n_tokens) {
int64_t n_tokens, const std::string& label) {
if (!enabled_) return RAD_OK;
if (blocks.size() != groups_.size()) return RAD_E_INVAL;
if (n_tokens > (int64_t)tokens.size()) return RAD_E_INVAL;
@@ -356,7 +360,7 @@ int PrefixCache::insert(uint64_t session,
for (int64_t b = 0; b < n_full; ++b) {
const BlockHash& h = hs[(size_t)b];
auto it = map_.find(h);
if (it != map_.end() && it->second.in_lru) { touch(h); continue; }
if (it != map_.end() && it->second.in_lru) { touch(h, now); continue; }
if (it != map_.end()) {
/* AN ENTRY WHOSE ONLY COPY IS OFF THE CARD, AND THIS REQUEST JUST COMPUTED IT AGAIN --
* a restore that did not fit, or a chain cut short. The request's blocks become the
@@ -376,6 +380,7 @@ int PrefixCache::insert(uint64_t session,
}
Entry& e = it->second;
e.blocks = std::move(mine);
e.used_ns = now;
lru_.push_back(h);
e.lru = std::prev(lru_.end());
e.in_lru = true;
@@ -400,6 +405,7 @@ int PrefixCache::insert(uint64_t session,
}
e.tokens.assign(tokens.begin() + b * block_size_,
tokens.begin() + (b + 1) * block_size_);
e.used_ns = now;
lru_.push_back(h);
e.lru = std::prev(lru_.end());
e.in_lru = true;
@@ -427,7 +433,7 @@ int PrefixCache::insert(uint64_t session,
if (it == map_.end()) continue;
tiers_->note_used(hs[(size_t)b], it->second.blocks, now);
}
tiers_->note_session(session, hs, n_tokens, now);
tiers_->note_session(session, hs, n_tokens, now, label);
}
/* A CONVERSATION'S SNAPSHOTS BELONG TO ITS LATEST TURN. The index keys a session by REQUEST
@@ -457,15 +463,13 @@ int PrefixCache::insert(uint64_t session,
/* ------------------------------------------------------------------ idle session tiers */
std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
std::vector<BlockHash>* chain) const {
const std::vector<MMContentKey>& mm) const {
std::vector<BlockHash> out;
if (chain) chain->clear();
if (!enabled_ || !tiers_ || tokens.empty()) return out;
/* THE BLOCKS A HIT CAN USE: one token must remain to compute a logit from, so a prompt that
* ends on a block boundary never reuses its last block (lookup backs off by one) and neither
* restoring it nor bringing back a snapshot keyed there would be read. */
* restoring it would be read. */
const int64_t n_full = ((int64_t)tokens.size() - 1) / block_size_;
std::vector<BlockHash> hs = chain_all(tokens, mm, n_full);
@@ -492,7 +496,6 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
if ((int64_t)it->second.tokens.size() != block_size_ ||
std::memcmp(it->second.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) != 0)
break;
if (chain) chain->push_back(hs[(size_t)b]);
if (tiers_->resident_off_device(hs[(size_t)b])) out.push_back(hs[(size_t)b]);
}
return out;
@@ -507,13 +510,9 @@ void PrefixCache::drop_offdevice(const BlockHash& key) {
if (it->second.in_lru) lru_.erase(it->second.lru);
map_.erase(it);
++stats_.evictions;
/* AND THE SNAPSHOT KEYED BY THE SAME HASH, when the disk was all it had: its record is gone,
* and an index entry left behind would be a detached snapshot nobody can read back. One still
* in its store slot stays -- no lookup reaches it past the missing block, the slot may be
* under a disk write this sink cannot ask about, and the retention policy retires it through
* the path that does ask (retire_ckpt). */
auto ck = ck_by_prefix_.find(key);
if (ck != ck_by_prefix_.end() && ck->second.detached) drop_snapshot(key);
/* A SNAPSHOT KEYED BY THE SAME HASH STAYS. No lookup reaches it past the missing block, and
* the retention policy or the expiry retires it through the path that tells the tiers
* (retire_ckpt) -- this one is called by the tiers, holding their lock. */
}
int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks) {
@@ -530,6 +529,8 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks
e.blocks = blocks;
for (size_t g = 0; g < groups_.size(); ++g) kv_->cache_reserved_block(groups_[g], blocks[g]);
if (!e.in_lru) {
/* A restore is a use: a request is about to hit it. */
e.used_ns = rad_mono_ns();
lru_.push_back(key);
e.lru = std::prev(lru_.end());
e.in_lru = true;
@@ -549,7 +550,9 @@ int64_t PrefixCache::evict_lru(int64_t n) {
* goes to the back rather than being evicted: releasing the cache's reference on it frees no
* block, and an entry that had no host copy would be erased for nothing. It is in use, which is
* what the back of the list means, and moving it is what keeps a caller that asks again from
* walking the same shared run every time. */
* walking the same shared run every time. It is stamped as used, which keeps the list in the
* clock's order. */
const uint64_t now = rad_mono_ns();
for (int64_t seen = (int64_t)lru_.size(); done < n && seen > 0 && !lru_.empty(); --seen) {
const BlockHash h = lru_.front();
auto it = map_.find(h);
@@ -557,6 +560,7 @@ int64_t PrefixCache::evict_lru(int64_t n) {
Entry& e = it->second;
if (shared_with_live(e)) {
lru_.splice(lru_.end(), lru_, lru_.begin());
e.used_ns = now;
continue;
}
lru_.pop_front();
@@ -584,6 +588,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) {
/* TIERS ATTACHED AND OFF are no tiers: nothing becomes droppable, and waiting for a copy that
* nobody will make would leave the reserve unkept for good. */
const bool keep = tiers_ && tiers_->any_on();
const uint64_t now = rad_mono_ns();
int64_t done = 0;
auto it = lru_.begin();
for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_blocks && seen > 0;
@@ -596,6 +601,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) {
/* In use: to the back, as evict_lru does, and the walk carries on from the next. */
auto next = std::next(it);
lru_.splice(lru_.end(), lru_, it);
e.used_ns = now;
it = next;
continue;
}
@@ -667,7 +673,7 @@ int64_t PrefixCache::drop_clean() {
* the answer by the group count.
*
* OFF-DEVICE ENTRIES COUNT FOR NOTHING. A demoted entry released its blocks, and the mark went
* with the release; its bytes are on the host or on disk and it is holding none of the card. */
* with the release; its bytes are in host memory and it is holding none of the card. */
int64_t PrefixCache::unshared_tokens() const {
if (!kv_ || groups_.empty() || block_size_ <= 0) return 0;
return kv_->cache_only_blocks(groups_[0]) * block_size_;
@@ -714,19 +720,11 @@ int64_t PrefixCache::retain(uint64_t session) {
auto it = ck_by_session_.find(session);
if (it == ck_by_session_.end()) return 0;
/* SNAPSHOTS IN THE STORE ONLY. This policy exists to spend a fixed number of --checkpoint-
* slots well, and it runs when the store is exhausted. A detached snapshot occupies none of
* it, so retiring one would free nothing here and would cost a session the state it was
* written to disk precisely in order to keep. The disk store bounds its own, oldest first,
* which is the right policy for the resource it actually spends.
*
* It stays in `kept` rather than being skipped, or the session index would forget it. */
std::vector<std::pair<int64_t, BlockHash>> all;
std::vector<BlockHash> kept;
for (const BlockHash& h : it->second) {
auto e = ck_by_prefix_.find(h);
if (e == ck_by_prefix_.end()) continue;
if (e->second.detached) { kept.push_back(h); continue; }
all.push_back({e->second.pos, h});
}
std::sort(all.begin(), all.end(),
@@ -745,15 +743,6 @@ int64_t PrefixCache::retain(uint64_t session) {
if (handed(a.second)) { kept.push_back(a.second); continue; }
auto e = ck_by_prefix_.find(a.second);
if (e == ck_by_prefix_.end()) continue;
/* A SNAPSHOT THE DISK HOLDS LEAVES THE SLOT AND STAYS IN THE INDEX: the policy is about
* the slots, and that copy costs none of them. */
if (tiers_ && tiers_->snapshot_backed(a.second)) {
(void)detach_snapshot(a.second);
tiers_->snapshot_detached(a.second);
kept.push_back(a.second);
++freed;
continue;
}
retire_ckpt(e);
++freed;
++stats_.ckpt_evictions;
@@ -783,30 +772,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
}
auto existing = ck_by_prefix_.find(prefix);
if (existing != ck_by_prefix_.end()) {
/* A DETACHED SNAPSHOT IS NOT ONE THIS CALL CAN HAND BACK. Returning its -1 slot would
* look to the scheduler exactly like a refusal (it tests `cs >= 0`) and the chunk would
* silently stop checkpointing; handing back a slot that is not in the store would be
* worse. The state is about to be recomputed anyway -- that is what a reservation at this
* prefix means -- so the disk copy is retired and a fresh slot allocated below. */
/* NOR ONE A DISK WRITE IS READING. The save that follows this reservation writes the slot
* while the write reads it, and the disk would keep a snapshot that is half of each. A
* fresh slot costs one allocation. */
if (!existing->second.detached &&
!(tiers_ && tiers_->slot_reading(existing->second.slot))) {
*slot_out = existing->second.slot;
return RAD_OK;
}
/* ONE HANDED OUT THIS STEP IS NOT RETIRED either: an admission restores from it ahead of
* the step. This chunk goes without a checkpoint, which costs a later hit some replay. */
if (handed(prefix)) return RAD_E_FULL;
const uint64_t vs = existing->second.session;
retire_ckpt(existing);
auto sit = ck_by_session_.find(vs);
if (sit != ck_by_session_.end()) {
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), prefix),
sit->second.end());
if (sit->second.empty()) ck_by_session_.erase(sit);
}
existing->second.used_ns = rad_mono_ns();
*slot_out = existing->second.slot;
return RAD_OK;
}
int32_t slot = -1;
@@ -840,14 +808,7 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
const Ckpt* victim = nullptr;
const Ckpt* tip_victim = nullptr;
for (const auto& kvp : ck_by_prefix_) {
/* A DETACHED SNAPSHOT IS NOT A CANDIDATE, because evicting it frees nothing HERE.
* Its slot went back to the store when it was detached, so picking it as the
* victim would retire a usable snapshot and then fail the retry anyway. */
if (kvp.second.detached) continue;
/* NOR ONE A DISK WRITE IS READING: its slot comes back only when the write
* reports, so retiring it now loses the snapshot and frees nothing yet. */
if (tiers_ && tiers_->slot_reading(kvp.second.slot)) continue;
/* NOR ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot
/* NOT ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot
* ahead of the step, and a slot freed under it restores nothing. */
if (handed(kvp.first)) continue;
auto sit = ck_by_session_.find(kvp.second.session);
@@ -865,54 +826,34 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
}
if (!victim) victim = tip_victim;
if (!victim) return RAD_E_FULL;
BlockHash vh = victim->prefix;
uint64_t vs = victim->session;
/* A VICTIM THE DISK HOLDS IS DETACHED, NOT LOST. The slot goes back all the same; the
* index entry stays, and the session's next restore reads the state back instead of
* replaying every recurrent layer from an older point. */
if (tiers_ && tiers_->snapshot_backed(vh)) {
(void)detach_snapshot(vh);
tiers_->snapshot_detached(vh);
if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL;
Ckpt c;
c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot;
c.used = ++clock_;
ck_by_prefix_.emplace(prefix, c);
ck_by_session_[session].push_back(prefix);
*slot_out = slot;
return RAD_OK;
}
const BlockHash vh = victim->prefix;
const uint64_t vs = victim->session;
retire_ckpt(ck_by_prefix_.find(vh));
++stats_.ckpt_evictions;
auto sit = ck_by_session_.find(vs);
if (sit != ck_by_session_.end()) {
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), vh),
sit->second.end());
if (sit->second.empty()) ck_by_session_.erase(sit);
}
unindex_ckpt(vs, vh);
if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL;
}
}
Ckpt c;
c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot; c.used = ++clock_;
c.used_ns = rad_mono_ns();
ck_by_prefix_.emplace(prefix, c);
ck_by_session_[session].push_back(prefix);
*slot_out = slot;
return RAD_OK;
}
void PrefixCache::commit_checkpoint(const BlockHash& prefix, bool resume) {
void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
auto it = ck_by_prefix_.find(prefix);
if (it == ck_by_prefix_.end()) return;
/* One that lost its slot between the reservation and now holds nothing to serve. */
if (it->second.detached || it->second.slot < 0) return;
if (it->second.slot < 0) return;
it->second.valid = true;
/* THE TIERS LEARN THE SNAPSHOT HERE, for the same reason note_used tells them the block ids:
* a demotion has to know what to move and this index is the only place it is written down.
* Before the commit there is nothing to move -- the slot still holds the previous tenant's
* state -- so this is also the earliest moment at which telling them would be true. */
if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos, resume);
/* THE TIERS LEARN THE SNAPSHOT HERE, for the session view: before the commit the slot still
* holds the previous tenant's state, so this is the earliest moment at which telling them
* would be true. */
if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos);
}
@@ -920,73 +861,19 @@ void PrefixCache::commit_checkpoint(const BlockHash& prefix, bool resume) {
void PrefixCache::retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it) {
if (it == ck_by_prefix_.end()) return;
/* THE TIERS ARE ASKED FIRST, because a disk write may be reading the slot: a save into it
* before the write is done would put half of another snapshot on disk under this key. When
* one is, the tiers keep the slot and hand it back once the write has reported. */
const bool held = tiers_ && tiers_->release_snapshot(it->first, it->second.slot);
if (it->second.slot >= 0 && !held) kv_->free_checkpoint(it->second.slot);
/* TOLD EITHER WAY, AND NOT ONLY WHEN THE DISK HOLDS THE BYTES. The tiers also remember a
* snapshot's slot -- note_snapshot records it at commit, because a disk write has to know
* what to read and this index is the only place it is written down. Freeing that slot here
* without saying so leaves the tiers naming a slot the store has since given to another
* session, and the next write puts THAT session's recurrent state on disk as this one's. The
* text that comes back is fluent, deterministic and about the wrong conversation, which is
* the exact failure the whole tier design is arranged to make impossible.
*
* Not reachable from the tiers' own drop sink, which erases the index entry through
* drop_snapshot instead -- so this never calls back into a record being erased. */
/* THE TIERS ARE TOLD, because they name the slot too: note_snapshot records it for the session
* view, and a view that kept it would count a slot the store has since given to another
* session as this one's resume point. */
if (tiers_) tiers_->release_snapshot(it->first);
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
ck_by_prefix_.erase(it);
}
int PrefixCache::detach_snapshot(const BlockHash& key) {
auto it = ck_by_prefix_.find(key);
if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND;
if (it->second.detached) return RAD_OK; /* already only on disk */
/* Only ever asked of a snapshot the tiers call backed, which no write is reading. */
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
it->second.slot = -1;
it->second.detached = true;
/* NOT SERVABLE FROM HERE ON, which is the same state a reserved-but-unwritten snapshot is in
* and is handled by the same branch in lookup(). A hit that reaches this position simply walks
* back to an older checkpoint, or to none -- shorter, never wrong. */
it->second.valid = false;
return RAD_OK;
}
int PrefixCache::reattach_snapshot(const BlockHash& key, int32_t slot) {
auto it = ck_by_prefix_.find(key);
if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND;
if (slot < 0) return RAD_E_INVAL;
/* AN ENTRY ALREADY IN A SLOT keeps it: taking the new one would leak the old. The caller gives
* the new slot back. */
if (!it->second.detached && it->second.slot >= 0) return it->second.slot == slot ? RAD_OK
: RAD_E_STATE;
/* A SLOT THIS ENTRY DID NOT ASK FOR IS STILL ITS OWN. The read allocated it and filled it
* from the disk copy of THIS key's state, so the identity that matters -- which prefix the
* bytes describe -- is carried by the key and not by the slot number it happened to get. */
it->second.slot = slot;
it->second.detached = false;
it->second.valid = true;
it->second.used = ++clock_;
return RAD_OK;
}
bool PrefixCache::free_checkpoint_for_restore() {
if (!tiers_) return false;
const Ckpt* victim = nullptr;
for (const auto& kvp : ck_by_prefix_) {
const Ckpt& c = kvp.second;
if (c.detached || c.slot < 0 || !c.valid) continue;
if (victim && c.used >= victim->used) continue;
if (handed(kvp.first)) continue;
if (!tiers_->snapshot_backed(kvp.first)) continue;
victim = &c;
}
if (!victim) return false;
const BlockHash vh = victim->prefix;
(void)detach_snapshot(vh);
tiers_->snapshot_detached(vh);
return true;
void PrefixCache::unindex_ckpt(uint64_t session, const BlockHash& key) {
auto sit = ck_by_session_.find(session);
if (sit == ck_by_session_.end()) return;
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), key), sit->second.end());
if (sit->second.empty()) ck_by_session_.erase(sit);
}
void PrefixCache::hold(uint64_t req, const std::vector<int32_t>& tokens,
@@ -1027,25 +914,65 @@ void PrefixCache::release(uint64_t req) {
released_ = true;
}
void PrefixCache::drop_snapshot(const BlockHash& key) {
auto it = ck_by_prefix_.find(key);
if (it == ck_by_prefix_.end()) return;
const uint64_t session = it->second.session;
/* No release_snapshot on this path: the tiers are the caller, holding their lock, and the
* bytes are already gone. They say this only of a detached snapshot, so there is normally no
* slot to give back. */
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
ck_by_prefix_.erase(it);
++stats_.ckpt_evictions;
auto sit = ck_by_session_.find(session);
if (sit == ck_by_session_.end()) return;
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), key), sit->second.end());
if (sit->second.empty()) ck_by_session_.erase(sit);
}
/* ------------------------------------------------------------------ expiry */
int64_t PrefixCache::snapshots_detached() const {
int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
if (!enabled_ || ttl_ns == 0 || now_ns <= ttl_ns) return 0;
const uint64_t cutoff = now_ns - ttl_ns;
int64_t n = 0;
for (const auto& kvp : ck_by_prefix_) if (kvp.second.detached) ++n;
/* ---- in VRAM: the LRU list is in the clock's order, so the walk stops at the first entry it
* keeps. A block a running sequence also holds stays allocated -- releasing the cache's
* reference is not freeing the block -- and that sequence publishes it again when it ends. */
while (!lru_.empty()) {
const BlockHash h = lru_.front();
auto it = map_.find(h);
if (it == map_.end()) { lru_.pop_front(); continue; }
Entry& e = it->second;
if (e.used_ns >= cutoff) break;
lru_.pop_front();
e.in_lru = false;
for (size_t g = 0; g < groups_.size(); ++g)
kv_->release_block(groups_[g], e.blocks[g]);
/* The host copy goes with it: an expired entry is not demoted. */
if (tiers_) tiers_->forget(h);
map_.erase(it);
++n;
}
/* ---- only in host memory: the tiers keep these in the clock's order too. */
if (tiers_) {
std::vector<BlockHash> keys;
tiers_->expired(cutoff, (size_t)-1, &keys);
for (const BlockHash& h : keys) {
tiers_->forget(h);
auto it = map_.find(h);
if (it == map_.end() || it->second.in_lru) continue;
map_.erase(it);
++n;
}
}
/* ---- snapshots, used when their prefix entry is or when a lookup hands them out. Not one
* that is still being written (a reservation not yet committed) and not one handed out this
* step: its admission restores from the slot ahead of the step. There are --checkpoint-slots
* of them at most, so the whole index is walked. */
std::vector<BlockHash> gone;
for (const auto& kvp : ck_by_prefix_) {
const Ckpt& c = kvp.second;
if (!c.valid || handed(kvp.first)) continue;
auto e = map_.find(kvp.first);
const uint64_t used = std::max(c.used_ns, e == map_.end() ? 0 : e->second.used_ns);
if (used < cutoff) gone.push_back(kvp.first);
}
for (const BlockHash& h : gone) {
auto it = ck_by_prefix_.find(h);
const uint64_t session = it->second.session;
retire_ckpt(it);
unindex_ckpt(session, h);
}
stats_.expired += n;
stats_.ckpt_expired += (int64_t)gone.size();
return n;
}
} /* namespace rad */
+36 -42
View File
@@ -206,7 +206,8 @@ public:
const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
const std::vector<std::vector<int32_t>>& blocks,
int64_t n_tokens);
int64_t n_tokens,
const std::string& label = std::string());
/* Drop the least recently used entries, releasing their KV references. Returns how many were
* dropped. Blocks a live sequence still holds stay allocated -- releasing the cache's
@@ -265,11 +266,8 @@ public:
* It is a separate call rather than something lookup does because lookup is const and has no
* device: a promotion allocates blocks and runs a scatter, which is the engine's to do
* between steps and not something a cache query may trigger under the caller. */
/* `chain`, when given, receives every key the walk matched, wherever it is -- what the tiers
* need to see whether any of it is still being read off disk (IdleTiers::plan_fetch). */
std::vector<BlockHash> restorable_from(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
std::vector<BlockHash>* chain = nullptr) const;
const std::vector<MMContentKey>& mm) const;
/* THE TIERS LOST THE BYTES. Erase the entry WITHOUT releasing blocks: an off-device entry
* owns none -- demotion released them -- and its recorded ids belong to whoever the pool gave
@@ -296,25 +294,10 @@ public:
* and re-prefills its whole transcript.
*
* A snapshot never needs to follow its blocks: it is restored straight out of its slot into
* the new sequence's state, wherever the blocks are. The only tier below the store is disk,
* and a snapshot the disk holds can give its slot up and stay in the index (DETACHED) until a
* read brings it back. */
* the new sequence's state, wherever the blocks are. There is no tier below the store: a
* snapshot the store retires is gone, and a session that needed it replays its recurrent
* layers from an older one. */
/* Its bytes are only on disk now: give the slot back and stop offering it. The index entry
* STAYS, because that is what a read off disk puts the snapshot back into, and an entry whose
* state is not in the store is exactly the `valid` flag's existing meaning -- lookup already
* walks past one and falls back to an older position. */
int detach_snapshot(const BlockHash& key);
/* And back again, into a slot the caller has already filled. */
int reattach_snapshot(const BlockHash& key, int32_t slot);
/* A STORE SLOT FOR A READ OFF DISK. The store is --checkpoint-slots deep for the whole server,
* and it is full whenever as many sessions have run since; a session whose snapshot is only on
* disk would then replay every recurrent layer from an older point, because its state has
* nowhere to land. One slot is freed by detaching the least recently used snapshot the disk
* also holds -- which the next restore of THAT session reads back -- and never one whose only
* copy is the slot, and never one a lookup has handed out since the step began: that request's
* restore reads the slot ahead of its step. True when a slot was freed. */
bool free_checkpoint_for_restore();
/* KEEP A WAITING REQUEST'S CHAIN ON THE CARD. An admission that restored a chain and was then
* refused -- no free sequence, no room in the pool -- gives its hit back, and its entries are
* clean: drop_clean would let them go at the next pass and the next attempt would restore the
@@ -328,13 +311,22 @@ public:
/* A step's admissions begin. The snapshots the last step's lookups handed out have been read
* by its forward, which committed before this step was planned. Until then a handed snapshot
* keeps its slot through every path that would give one up: retention, the eviction in
* reserve_checkpoint, and free_checkpoint_for_restore. */
* reserve_checkpoint, and the expiry. */
void begin_step() { handed_.clear(); }
/* The tiers lost it -- the disk store let it go, a failed read, or an entry they were told to
* forget. Erase the index entry and give back the slot, if it still has one. */
void drop_snapshot(const BlockHash& key);
/* How many snapshots the index holds whose bytes are only on disk. */
int64_t snapshots_detached() const;
/* ---------------- expiry ----------------
*
* TAKE OUT EVERYTHING NO REQUEST HAS USED FOR `ttl_ns`: entries in VRAM (their blocks go back
* to the pool), entries only the host holds (their slots go back to the arena), and snapshots
* (their store slots go back). An entry is used when a lookup hits it or a request publishes
* it, and a snapshot when its prefix entry is or when a lookup hands it out. Nothing is moved
* anywhere first: an expired conversation is one the operator has said is not coming back.
*
* A PREFIX IS NEVER OLDER THAN WHAT FOLLOWS IT. A hit or a publish stamps every block of the
* chain up to where it ends with one clock, so a conversation expires from its tip inwards and
* a shared system prompt outlives every conversation that still reads it. Returns how many
* entries went. */
int64_t expire(uint64_t now_ns, uint64_t ttl_ns);
/* ---------------- linear checkpoints ---------------- */
/* The next position strictly after `pos` at which the scheduler must split a chunk so that a
* checkpoint lands on a boundary (spec §7.1, §7.3). */
@@ -349,9 +341,8 @@ public:
int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix,
int32_t* slot_out);
/* The state named by `prefix` is now IN its slot. Until this is called the reservation is only
* a promise and lookup() will not offer it -- see Ckpt::valid. A `resume` point is copied off
* the card at once (IdleTiers::note_snapshot). */
void commit_checkpoint(const BlockHash& prefix, bool resume = false);
* a promise and lookup() will not offer it -- see Ckpt::valid. */
void commit_checkpoint(const BlockHash& prefix);
/* Every checkpoint of a session, ascending. */
std::vector<int64_t> checkpoints(uint64_t session) const;
/* Apply the retention policy to one session now. Returns how many snapshots were released.
@@ -372,6 +363,9 @@ public:
* was lost, and a counter that mixed the two would read a working tier as a thrashing
* cache. */
int64_t drops = 0;
/* Entries and snapshots --prefix-cache-ttl took, from whichever tier held them. Not
* evictions either: nothing wanted the memory. */
int64_t expired = 0, ckpt_expired = 0;
};
const Stats& stats() const { return stats_; }
@@ -385,6 +379,10 @@ private:
* valid only while this is set. */
bool in_lru = false;
bool drop_wait = false; /* in drop_wait_: clean, but a sequence still reads it */
/* LAST USE, on the monotonic clock: a hit or a publish. The LRU list is in this order --
* every path that puts an entry at its back stamps it -- which is what lets the expiry
* stop at the first entry it keeps. */
uint64_t used_ns = 0;
std::list<BlockHash>::iterator lru;
};
struct Ckpt {
@@ -393,30 +391,26 @@ private:
BlockHash prefix;
int32_t slot = -1;
uint64_t used = 0;
uint64_t used_ns = 0; /* reserved, or handed out by a lookup */
/* HAS THE STATE ACTUALLY BEEN WRITTEN INTO THE SLOT YET. reserve_checkpoint runs when the
* scheduler PLANS the chunk; the copy happens after the step that computes the state. A
* lookup between those two points would hand out a slot holding the previous tenant's
* history, which is the exact failure this whole mechanism exists to prevent. */
bool valid = false;
/* ARE THE BYTES ONLY ON DISK. A detached snapshot gave its store slot up because the disk
* holds it, and `slot` is -1 until a read brings it back. Kept as its own flag rather than
* inferred from the slot so that the two reasons a snapshot cannot be served -- not written
* yet, and not here -- stay distinguishable in a debugger and in a report. */
bool detached = false;
};
std::vector<BlockHash> chain_all(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
int64_t n_blocks) const;
void touch(const BlockHash& h) const;
void touch(const BlockHash& h, uint64_t now_ns) const;
/* Does a live sequence hold any of this entry's blocks as well? Then releasing the cache's
* reference frees nothing. */
bool shared_with_live(const Entry& e) const;
/* Retire one snapshot whatever tier holds its bytes: a slot goes back to the store, and a disk
* copy goes back to the tiers. One place, because three call sites that each remembered to
* check `detached` would be three places to forget. The session index is the caller's, since
* every caller is already rebuilding or erasing it. */
/* Retire one snapshot: its slot goes back to the store and the tiers stop naming it. The
* session index is the caller's, since every caller is already rebuilding or erasing it. */
void retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it);
/* Take one key out of a session's index entry, and the entry when it empties. */
void unindex_ckpt(uint64_t session, const BlockHash& key);
KVManager* kv_ = nullptr;
IdleTiers* tiers_ = nullptr;
-536
View File
@@ -1,536 +0,0 @@
/* sstier.cpp -- see sstier.h. IT HOLDS CONVERSATION CONTENT ON DISK, UNENCRYPTED. */
#include "mem/sstier.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <thread>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
namespace rad {
/* The device layer's alignment, not a second opinion about it: every slot, every header region and
* every staging buffer here is a multiple of it, which is what keeps every transfer on
* DirectFile's aligned fast path and its bounce buffer unallocated. */
static constexpr int64_t kAlign = DirectFile::alignment();
static void* alloc_aligned(int64_t bytes) {
void* p = nullptr;
if (posix_memalign(&p, (size_t)kAlign, (size_t)align_up(bytes, kAlign)) != 0) return nullptr;
return p;
}
static constexpr uint32_t kMagicBlock = 0x4b4c4252u; /* "RBLK" */
static constexpr uint32_t kMagicCkpt = 0x504b4352u; /* "RCKP" */
struct SSSlotHeader {
uint32_t magic;
uint32_t n_tokens;
uint64_t fingerprint;
uint64_t payload_bytes;
uint64_t key_hi, key_lo;
int64_t pos; /* checkpoint: the token position it restores to; 0 for a block */
uint64_t reserved[3];
};
/* ------------------------------------------------------------------ TokenBucket */
const char* ssd_consumer_name(SSDConsumer c) {
switch (c) {
case SSDConsumer::PrefixCache: return "prefix-cache";
case SSDConsumer::WeightTier: return "weight-tier";
default: return "?";
}
}
static int64_t now_ns() {
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
void TokenBucket::configure(int64_t bytes_per_sec, int64_t burst_bytes) {
std::lock_guard<std::mutex> lk(mu_);
rate_ = bytes_per_sec > 0 ? bytes_per_sec : 0;
burst_ = burst_bytes > 0 ? burst_bytes : rate_;
tokens_ = (double)burst_;
last_ns_ = now_ns();
}
void TokenBucket::refill_locked() {
int64_t t = now_ns();
double dt = (double)(t - last_ns_) * 1e-9;
last_ns_ = t;
tokens_ = std::min((double)burst_, tokens_ + dt * (double)rate_);
}
bool TokenBucket::try_take(int64_t bytes, SSDConsumer who) {
std::lock_guard<std::mutex> lk(mu_);
Use& u = use_[(int)who];
if (rate_ <= 0) { u.bytes += bytes; ++u.grants; return true; }
refill_locked();
if (tokens_ < (double)bytes) return false;
tokens_ -= (double)bytes;
u.bytes += bytes;
++u.grants;
return true;
}
void TokenBucket::take(int64_t bytes, SSDConsumer who) {
int64_t t0 = now_ns();
bool waited = false;
for (;;) {
if (try_take(bytes, who)) break;
waited = true;
/* Sleep for the deficit rather than spinning. Coarse on purpose: this is a placeholder
* and a precise scheduler for a policy nobody has measured would be effort spent on the
* wrong thing (spec §19.5). */
std::this_thread::sleep_for(std::chrono::microseconds(200));
}
if (waited) {
std::lock_guard<std::mutex> lk(mu_);
++use_[(int)who].waits;
use_[(int)who].wait_us += (now_ns() - t0) / 1000;
}
}
TokenBucket::Use TokenBucket::use(SSDConsumer c) const {
std::lock_guard<std::mutex> lk(mu_);
return use_[(int)c];
}
std::string TokenBucket::report() const {
std::lock_guard<std::mutex> lk(mu_);
std::string s = rate_ > 0
? fmt("SSD token bucket: %s/s, burst %s (PLACEHOLDER, spec §19.5)\n",
humanb(rate_).c_str(), humanb(burst_).c_str())
: std::string("SSD token bucket: off (no measured rate to enforce, spec §19.5)\n");
for (int i = 0; i < (int)SSDConsumer::N; ++i)
s += fmt(" %-14s %10s in %lld ops, %lld waits totalling %lld ms\n",
ssd_consumer_name((SSDConsumer)i), humanb(use_[i].bytes).c_str(),
(long long)use_[i].grants, (long long)use_[i].waits,
(long long)(use_[i].wait_us / 1000));
return s;
}
TokenBucket& rad_ssd_bucket() { static TokenBucket b; return b; }
/* ------------------------------------------------------------------ SSDTier */
std::string SSDTier::disclosure(const std::string& dir) {
return fmt("SSD prefix tier active at %s.\n"
" It stores CONVERSATION CONTENT ON DISK, UNENCRYPTED: the cached KV blocks are a\n"
" lossless function of the prompt, and the prompt's token ids are written beside\n"
" them so a hit can be verified. Anything that persists across restarts says so\n"
" (spec §7.3). Put this directory on storage you are willing to treat as holding\n"
" the text itself.\n", dir.c_str());
}
SSDTier::~SSDTier() { close(); }
static int64_t hdr_region_bytes(int64_t tok_bytes) {
return align_up((int64_t)sizeof(SSSlotHeader) + tok_bytes, kAlign);
}
int SSDTier::open_store(Store& s, const std::string& path, int64_t payload, int64_t n_slots,
int64_t tok_bytes, bool allow_buffered) {
s.payload = payload;
s.hdr_bytes = hdr_region_bytes(tok_bytes);
s.slot_bytes = s.hdr_bytes + align_up(payload, kAlign);
if (n_slots <= 0) return RAD_OK;
int flags = RAD_DIO_READ | RAD_DIO_WRITE | RAD_DIO_CREATE;
if (allow_buffered) flags |= RAD_DIO_ALLOW_BUFFERED;
RAD_TRY(s.file.open(path.c_str(), flags));
/* Size the store up front. DirectFile does not take a size hint and does not need one -- a
* write past the end extends the file -- but a store laid out in one ftruncate is one extent
* rather than N, which is the difference between a slot read being one seek and being several
* once the filesystem has interleaved somebody else's writes between ours. */
if (::ftruncate(s.file.fd(), (off_t)(s.slot_bytes * n_slots)) != 0)
RAD_WARN("ftruncate %s to %s: %s -- the store will be extended by its writes instead",
path.c_str(), humanb(s.slot_bytes * n_slots).c_str(), strerror(errno));
s.slots.assign((size_t)n_slots, Slot{});
s.freelist.resize((size_t)n_slots);
for (int64_t i = 0; i < n_slots; ++i) s.freelist[(size_t)i] = (int32_t)(n_slots - 1 - i);
s.stage = alloc_aligned(s.slot_bytes);
if (!s.stage) return RAD_E_NOMEM;
return RAD_OK;
}
int SSDTier::open(const SSDTierConfig& cfg) {
close();
cfg_ = cfg;
if (cfg.dir.empty()) { enabled_ = false; return RAD_OK; }
if (cfg.block_payload <= 0 && cfg.ckpt_payload <= 0) {
RAD_ERR("--prefix-cache-dir is set but neither a block payload nor a checkpoint payload was "
"given; there is nothing for the tier to store");
return RAD_E_INVAL;
}
/* The engine says so at startup. Not behind a verbosity flag. */
RAD_WARN("%s", disclosure(cfg.dir).c_str());
if (::mkdir(cfg.dir.c_str(), 0700) != 0 && errno != EEXIST) {
RAD_ERR("cannot create %s: %s", cfg.dir.c_str(), strerror(errno));
return RAD_E_IO;
}
RAD_TRY(open_store(blocks_, cfg.dir + "/blocks.bin", cfg.block_payload, cfg.n_block_slots,
cfg.block_tokens * (int64_t)sizeof(uint32_t), cfg.allow_buffered));
RAD_TRY(open_store(ckpts_, cfg.dir + "/ckpts.bin", cfg.ckpt_payload, cfg.n_ckpt_slots,
0, cfg.allow_buffered));
enabled_ = true;
if (cfg.persistent) {
/* Rebuild the index by scanning the slot headers rather than persisting a separate index
* file. One sequential pass at startup, and no way for an index to disagree with the data
* it names -- which is the failure a separate index file has and which produces exactly
* the "serves one caller another caller's context" outcome this tier verifies against. */
const int64_t nb = scan_store(blocks_, kMagicBlock);
if (nb < 0) return (int)nb;
const int64_t nc = scan_store(ckpts_, kMagicCkpt);
if (nc < 0) return (int)nc;
RAD_INFO("SSD tier: recovered %lld block and %lld checkpoint slots from %s",
(long long)nb, (long long)nc, cfg.dir.c_str());
} else {
/* Not persistent means the store must not outlive the process, and unlinking now rather
* than at exit means it also does not outlive a crash. The descriptors stay valid. */
::unlink((cfg.dir + "/blocks.bin").c_str());
::unlink((cfg.dir + "/ckpts.bin").c_str());
}
report_ = fmt("SSD tier %s: %lld block slots x %s, %lld checkpoint slots x %s, %s%s\n",
cfg.dir.c_str(),
(long long)cfg.n_block_slots, humanb(blocks_.slot_bytes).c_str(),
(long long)cfg.n_ckpt_slots, humanb(ckpts_.slot_bytes).c_str(),
blocks_.file.direct() ? "O_DIRECT" : "BUFFERED",
cfg.persistent ? ", persistent" : ", volatile");
return RAD_OK;
}
void SSDTier::close() {
for (Store* s : { &blocks_, &ckpts_ }) {
s->file.close();
if (s->stage) { ::free(s->stage); s->stage = nullptr; }
s->slots.clear(); s->index.clear(); s->freelist.clear();
}
enabled_ = false;
}
std::string SSDTier::report() const {
std::string s = report_;
s += fmt(" %lld hits, %lld misses, %lld verify misses, %lld evictions; "
"%s read, %s written\n",
(long long)stats_.hits, (long long)stats_.misses, (long long)stats_.verify_misses,
(long long)stats_.evictions, humanb(stats_.bytes_read).c_str(),
humanb(stats_.bytes_written).c_str());
s += rad_ssd_bucket().report();
return s;
}
void SSDTier::lru_unlink(Store& s, int32_t i) {
Slot& x = s.slots[(size_t)i];
if (x.prev >= 0) s.slots[(size_t)x.prev].next = x.next; else s.lru_head = x.next;
if (x.next >= 0) s.slots[(size_t)x.next].prev = x.prev; else s.lru_tail = x.prev;
x.prev = x.next = -1;
}
void SSDTier::lru_push(Store& s, int32_t i) {
Slot& x = s.slots[(size_t)i];
x.prev = s.lru_tail;
x.next = -1;
if (s.lru_tail >= 0) s.slots[(size_t)s.lru_tail].next = i; else s.lru_head = i;
s.lru_tail = i;
}
/* THE HEADERS ARE READ MANY AT A TIME. Each is one 4 KiB direct read at its own slot, so a single
* reader waits one device round trip a slot -- some tens of microseconds, over the millions of
* slots a store sized in hundreds of GiB holds, which is over a minute of every start. The device
* serves dozens of such reads at once at little more latency than one, so the scan keeps
* kScanDepth in flight: one thread each, over its own contiguous run of slots with its own staging
* page. The threads only record each slot's verdict in the slot itself; the index, the order and
* the free list are built afterwards in one descending pass, which is the order a single
* sequential reader would produce. */
static constexpr int64_t kScanDepth = 64;
int64_t SSDTier::scan_store(Store& s, uint32_t magic) {
if (s.slots.empty()) return 0;
s.index.clear();
s.freelist.clear();
s.lru_head = s.lru_tail = -1;
for (Slot& x : s.slots) { x.used = 0; x.prev = x.next = -1; }
const int64_t n = (int64_t)s.slots.size();
const int64_t nt = std::min(kScanDepth, n);
std::atomic<bool> nomem{false};
std::vector<std::thread> th;
th.reserve((size_t)nt);
for (int64_t t = 0; t < nt; ++t)
th.emplace_back([&, t] {
void* stage = alloc_aligned(s.hdr_bytes);
if (!stage) { nomem.store(true); return; }
for (int64_t i = n * t / nt; i < n * (t + 1) / nt; ++i) {
if (s.file.read_at(stage, i * s.slot_bytes, s.hdr_bytes) < 0) continue;
const SSSlotHeader* h = (const SSSlotHeader*)stage;
if (h->magic != magic || h->fingerprint != cfg_.fingerprint
|| h->payload_bytes != (uint64_t)s.payload) continue;
Slot& x = s.slots[(size_t)i];
x.key.hi = h->key_hi;
x.key.lo = h->key_lo;
x.pos = h->pos;
x.used = 1;
}
std::free(stage);
});
for (std::thread& x : th) x.join();
if (nomem.load()) {
for (Slot& x : s.slots) x.used = 0;
RAD_ERR("SSD tier: no staging page for the header scan");
return RAD_E_NOMEM;
}
int64_t live = 0;
for (const Slot& x : s.slots) live += x.used;
s.index.reserve((size_t)live);
s.freelist.reserve((size_t)(n - live));
for (int64_t i = n - 1; i >= 0; --i) {
if (!s.slots[(size_t)i].used) { s.freelist.push_back((int32_t)i); continue; }
lru_push(s, (int32_t)i);
s.index[s.slots[(size_t)i].key] = (int32_t)i;
}
return live;
}
int SSDTier::claim(Store& s, const BlockHash& key, int32_t* out) {
auto it = s.index.find(key);
if (it != s.index.end()) { *out = it->second; return RAD_OK; }
if (!s.freelist.empty()) { *out = s.freelist.back(); s.freelist.pop_back(); return RAD_OK; }
/* LRU. Evicting the DEEPEST entry first would be better -- a deeper block chains more tokens,
* is less shareable, and losing it only shortens the usable prefix, whereas losing a shallow
* one strands everything above it -- but depth is not a property this tier is told. Straight
* LRU until the caller carries depth in. */
const int32_t victim = s.lru_head;
if (victim < 0) return RAD_E_FULL;
lru_unlink(s, victim);
s.index.erase(s.slots[(size_t)victim].key);
s.slots[(size_t)victim].used = 0;
++stats_.evictions;
*out = victim;
return RAD_OK;
}
int SSDTier::put(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
const int32_t* toks, int32_t n_toks, const void* payload, int64_t bytes) {
if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED;
if (bytes != s.payload) return RAD_E_SHAPE;
if ((int64_t)sizeof(SSSlotHeader) + (int64_t)n_toks * 4 > s.hdr_bytes) return RAD_E_SHAPE;
int32_t slot = -1;
RAD_TRY(claim(s, key, &slot));
const int64_t base = (int64_t)slot * s.slot_bytes;
std::memset(s.stage, 0, (size_t)s.slot_bytes);
SSSlotHeader* h = (SSSlotHeader*)s.stage;
h->magic = magic;
h->n_tokens = (uint32_t)n_toks;
h->fingerprint = cfg_.fingerprint;
h->payload_bytes = (uint64_t)bytes;
h->key_hi = key.hi; h->key_lo = key.lo;
h->pos = pos;
if (n_toks > 0) std::memcpy((char*)s.stage + sizeof(SSSlotHeader), toks, (size_t)n_toks * 4);
std::memcpy((char*)s.stage + s.hdr_bytes, payload, (size_t)bytes);
rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache);
/* Payload first, header last. Written front to back, a short write would leave the header
* COMPLETE and the payload truncated, so the slot verifies and the engine loads whatever was
* in the file underneath it -- which is the worst failure this tier can have.
*
* A WRITE THAT FAILS GIVES THE SLOT BACK. claim() took it off the free list or out of the
* index, so returning here without that leaves a slot no list names and the store one slot
* smaller for good. Whatever the slot held before is no longer trustworthy either -- the
* payload may be half overwritten under a header that still verifies -- so the key comes out
* of the index and the header is cleared on a best-effort basis, which keeps a persistent
* store from indexing it again at the next start. */
int wst = s.file.write_at((char*)s.stage + s.hdr_bytes, base + s.hdr_bytes,
s.slot_bytes - s.hdr_bytes);
if (wst >= 0) wst = s.file.write_at(s.stage, base, s.hdr_bytes);
if (wst < 0) {
auto it = s.index.find(key);
if (it != s.index.end() && it->second == slot) s.index.erase(it);
if (s.slots[(size_t)slot].used) lru_unlink(s, slot);
s.slots[(size_t)slot].used = 0;
s.freelist.push_back(slot);
std::memset(s.stage, 0, (size_t)s.hdr_bytes);
(void)s.file.write_at(s.stage, base, s.hdr_bytes);
return wst;
}
if (s.slots[(size_t)slot].used) lru_unlink(s, slot);
s.slots[(size_t)slot].key = key;
s.slots[(size_t)slot].used = 1;
s.slots[(size_t)slot].pos = pos;
lru_push(s, slot);
s.index[key] = slot;
++stats_.writes;
stats_.bytes_written += s.slot_bytes;
return RAD_OK;
}
int SSDTier::get(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
const int32_t* toks, int32_t n_toks, void* payload, int64_t bytes) {
if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED;
if (bytes != s.payload) return RAD_E_SHAPE;
auto it = s.index.find(key);
if (it == s.index.end()) { ++stats_.misses; return RAD_E_NOTFOUND; }
const int32_t slot = it->second;
const int64_t base = (int64_t)slot * s.slot_bytes;
rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache);
RAD_TRY(s.file.read_at(s.stage, base, s.slot_bytes));
++stats_.reads;
stats_.bytes_read += s.slot_bytes;
if (!header_ok(s, s.stage, magic, key, pos, toks, n_toks, bytes)) {
/* Drop it rather than leaving it to fail every future probe: without this a single bad
* slot poisons its prefix permanently. */
forget_slot(s, slot);
++stats_.verify_misses;
return RAD_E_NOTFOUND;
}
std::memcpy(payload, (const char*)s.stage + s.hdr_bytes, (size_t)bytes);
lru_unlink(s, slot);
lru_push(s, slot);
++stats_.hits;
return RAD_OK;
}
/* Belt and braces on top of the index: verify the header AND the token ids. A store that survives
* a restart, a model change or a layout change would otherwise serve one caller another caller's
* context, and that is not a failure anybody would ever diagnose. */
bool SSDTier::header_ok(const Store& s, const void* stage, uint32_t magic, const BlockHash& key,
int64_t pos, const int32_t* toks, int32_t n_toks, int64_t bytes) const {
(void)s;
const SSSlotHeader* h = (const SSSlotHeader*)stage;
bool ok = h->magic == magic && h->fingerprint == cfg_.fingerprint
&& h->key_hi == key.hi && h->key_lo == key.lo
&& h->payload_bytes == (uint64_t)bytes && h->pos == pos
&& h->n_tokens == (uint32_t)n_toks;
if (ok && n_toks > 0)
ok = std::memcmp((const char*)stage + sizeof(SSSlotHeader), toks, (size_t)n_toks * 4) == 0;
return ok;
}
void SSDTier::forget_slot(Store& s, int32_t slot) {
auto it = s.index.find(s.slots[(size_t)slot].key);
if (it != s.index.end() && it->second == slot) s.index.erase(it);
if (s.slots[(size_t)slot].used) lru_unlink(s, slot);
s.slots[(size_t)slot].used = 0;
s.freelist.push_back(slot);
}
/* READS OUTSTANDING AT ONCE. An NVMe drive reading tens-of-kilobyte extents at random reaches its
* bandwidth only with many requests in flight; a thread each is the simplest way to have them, and
* every thread has an aligned staging buffer of its own. */
static constexpr int kReaders = 16;
int SSDTier::get_blocks(const BlockHash* keys, int64_t n, void* const* payloads, int64_t bytes,
char* ok) {
std::lock_guard<std::mutex> lk(io_mu_);
Store& s = blocks_;
for (int64_t i = 0; i < n; ++i) ok[i] = 0;
if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED;
if (bytes != s.payload) return RAD_E_SHAPE;
std::vector<int32_t> slot((size_t)n, -1);
int64_t found = 0;
for (int64_t i = 0; i < n; ++i) {
auto it = s.index.find(keys[i]);
if (it == s.index.end()) { ++stats_.misses; continue; }
slot[(size_t)i] = it->second;
++found;
}
if (found == 0) return RAD_OK;
/* The reads, and nothing that touches the index or the order: those are settled after, on this
* thread. 1 read and verified, 2 read and not the key asked for, negative a failed read. */
std::vector<int> st((size_t)n, 0);
std::atomic<int64_t> next{0};
auto reader = [&](void* stage) {
for (int64_t i; (i = next.fetch_add(1, std::memory_order_relaxed)) < n;) {
if (slot[(size_t)i] < 0) continue;
rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache);
const int r = s.file.read_at(stage, (int64_t)slot[(size_t)i] * s.slot_bytes,
s.slot_bytes);
if (r < 0) { st[(size_t)i] = r; continue; }
if (!header_ok(s, stage, kMagicBlock, keys[i], 0, nullptr, 0, bytes)) {
st[(size_t)i] = 2;
continue;
}
std::memcpy(payloads[i], (const char*)stage + s.hdr_bytes, (size_t)bytes);
st[(size_t)i] = 1;
}
};
const int nt = (int)std::min<int64_t>(kReaders, found);
std::vector<void*> stages;
for (int t = 1; t < nt; ++t) {
void* p = alloc_aligned(s.slot_bytes);
if (!p) break;
stages.push_back(p);
}
std::vector<std::thread> th;
th.reserve(stages.size());
for (void* p : stages) th.emplace_back(reader, p);
reader(s.stage);
for (std::thread& t : th) t.join();
for (void* p : stages) ::free(p);
for (int64_t i = 0; i < n; ++i) {
const int32_t sl = slot[(size_t)i];
if (sl < 0 || st[(size_t)i] < 0) continue;
++stats_.reads;
stats_.bytes_read += s.slot_bytes;
if (st[(size_t)i] == 2) {
forget_slot(s, sl);
++stats_.verify_misses;
continue;
}
lru_unlink(s, sl);
lru_push(s, sl);
++stats_.hits;
ok[i] = 1;
}
return RAD_OK;
}
/* ONE CALLER AT A TIME. Every call is the KV tiers' IO thread today, but a store is one staging
* buffer, one slot table and one index, and nothing about the interface says who may call it. */
int SSDTier::put_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
const void* payload, int64_t bytes) {
std::lock_guard<std::mutex> lk(io_mu_);
return put(blocks_, kMagicBlock, key, 0, toks, n_toks, payload, bytes);
}
int SSDTier::get_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
void* payload, int64_t bytes) {
std::lock_guard<std::mutex> lk(io_mu_);
return get(blocks_, kMagicBlock, key, 0, toks, n_toks, payload, bytes);
}
int SSDTier::put_checkpoint(const BlockHash& key, int64_t pos, const void* payload, int64_t bytes) {
std::lock_guard<std::mutex> lk(io_mu_);
return put(ckpts_, kMagicCkpt, key, pos, nullptr, 0, payload, bytes);
}
int SSDTier::get_checkpoint(const BlockHash& key, int64_t pos, void* payload, int64_t bytes) {
std::lock_guard<std::mutex> lk(io_mu_);
return get(ckpts_, kMagicCkpt, key, pos, nullptr, 0, payload, bytes);
}
} /* namespace rad */
-181
View File
@@ -1,181 +0,0 @@
/* sstier.h -- the optional SSD tier for served attention state and linear checkpoints alike, so
* an agent session does not re-prefill its whole transcript every turn (spec §7.3).
*
* ============================== IT HOLDS CONVERSATION CONTENT ON DISK, UNENCRYPTED ==============
* A KV block IS the prompt: the token ids are stored beside it so a hit can be verified, and the
* cached tensors are a lossless function of the text. Anything that persists it across restarts
* says so, and this engine says so at startup whenever --prefix-cache-dir is set. There is no
* encryption option, no obfuscation, and no claim of one; if the content is sensitive the
* directory must be on storage the operator is willing to treat as sensitive.
* ================================================================================================
*
* O_DIRECT, same as the weight tier. Going through the page cache would evict the weight tier's own
* file mappings, which is paid for in decode and would never show up as a *cache* problem. O_DIRECT
* wants offsets, lengths and buffers all on the logical block size, so every slot and every
* sub-region here is a multiple of it and there is no unaligned tail to handle.
*
* Spec §19.5 records that prefix-cache and weight-tier contention on one SSD has NO PLAN. The
* TokenBucket below is a placeholder for a measured policy, and it is labelled as one: it is a
* shared byte budget between the two consumers, which at least makes the contention visible and
* boundable instead of invisible. What the right split is, or whether a rate limit is even the
* right shape of answer rather than a priority queue, is a measurement nobody has taken.
*/
#pragma once
#include "device/directio.h"
#include "mem/prefix.h"
#include "rad_core.h"
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
namespace rad {
/* The O_DIRECT file is the device layer's rad::DirectFile (core/device/directio.h). Every extent
* this tier reads or writes is a whole slot or a whole aligned header region, so every transfer
* lands on its fast path and its bounce buffer is never allocated -- which is the property worth
* stating, since the bounce exists for callers reading a header or a file tail and one on this
* path would mean a slot geometry bug rather than a performance problem. */
/* ------------------------------------------------------------------ the shared rate limiter */
enum class SSDConsumer { PrefixCache = 0, WeightTier = 1, N = 2 };
const char* ssd_consumer_name(SSDConsumer c);
/* PLACEHOLDER FOR A MEASURED POLICY (spec §19.5).
*
* Both the prefix cache and the weight tier want O_DIRECT bandwidth and under load they fight. A
* token bucket is the simplest thing that bounds the fight: one shared byte budget, refilled at a
* stated rate, drawn on by both. What it does NOT do is decide who should win, and that is the
* actual open question -- a weight-tier read blocks a layer that is about to execute, while a
* prefix-cache read only makes a prefill shorter, so a priority scheme is probably the right shape
* and a flat rate limit certainly is not. Replace this once there is a workload to measure
* against; the per-consumer counters exist so that measurement has something to read. */
class TokenBucket {
public:
/* 0 bytes_per_sec disables the limiter entirely, which is the default: an unmeasured rate
* limit that throttles a machine nobody profiled is worse than none. */
void configure(int64_t bytes_per_sec, int64_t burst_bytes);
bool enabled() const { return rate_ > 0; }
bool try_take(int64_t bytes, SSDConsumer who); /* non-blocking */
void take(int64_t bytes, SSDConsumer who); /* sleeps until the budget allows */
struct Use { int64_t bytes = 0; int64_t grants = 0; int64_t waits = 0; int64_t wait_us = 0; };
Use use(SSDConsumer c) const;
std::string report() const;
private:
void refill_locked();
mutable std::mutex mu_;
int64_t rate_ = 0; /* bytes per second */
int64_t burst_ = 0;
double tokens_ = 0;
int64_t last_ns_ = 0;
Use use_[(int)SSDConsumer::N];
};
/* The one bucket both consumers share. The weight tier (core/place/) draws on the same object;
* that is the entire point of it living here rather than inside either one. */
TokenBucket& rad_ssd_bucket();
/* ------------------------------------------------------------------ the tier */
struct SSDTierConfig {
std::string dir; /* Config::prefix_cache_dir */
int64_t block_payload = 0; /* bytes one cached attention block occupies, all groups */
int64_t block_tokens = 0; /* the attention block size, for the verify */
int64_t ckpt_payload = 0; /* KVManager::checkpoint_bytes() */
/* Slot counts are STATED, not derived from statvfs. A tier that sizes itself from the free
* space it happens to see at startup is a tier whose capacity changes when somebody untars
* something, and §6's rule is that budgets do not move on their own. */
int64_t n_block_slots = 0;
int64_t n_ckpt_slots = 0;
uint64_t fingerprint = 0; /* model + layout identity; a mismatch invalidates the store */
bool persistent = false; /* keep the files across restarts */
/* Passes RAD_DIO_ALLOW_BUFFERED. Off by default: the device layer REFUSES a filesystem
* without O_DIRECT rather than downgrading it, because a silent buffered fallback costs the
* weight tier its own page cache and shows up only as a decode regression nobody can
* attribute. The flag is for tests, which run on whatever /tmp happens to be. */
bool allow_buffered = false;
};
class SSDTier {
public:
~SSDTier();
int open(const SSDTierConfig& cfg);
void close();
bool enabled() const { return enabled_; }
/* The line the engine prints at startup when the flag is on. Not optional. */
static std::string disclosure(const std::string& dir);
std::string report() const;
/* Attention blocks. `toks` is the block's token ids: they are stored in the slot header and
* memcmp'd on the way back in, so a hash collision is a miss and never a wrong answer. */
int put_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
const void* payload, int64_t bytes);
int get_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
void* payload, int64_t bytes);
/* MANY BLOCKS AT ONCE, READ IN PARALLEL. A conversation coming back off disk is thousands of
* entries of tens of kilobytes each, and read one at a time they keep the drive at a queue
* depth of one -- a fraction of what it delivers with dozens of reads outstanding. `ok[i]` is
* whether block i was found, read and verified into `payloads[i]`; one that was not is a miss
* exactly as get_block's would be. Blocks stored with no token ids only. */
int get_blocks(const BlockHash* keys, int64_t n, void* const* payloads, int64_t bytes,
char* ok);
/* Linear-state checkpoints. Keyed by the chained block hash at the checkpoint position, which
* is exactly what PrefixCache::reserve_checkpoint keys them by in VRAM. */
int put_checkpoint(const BlockHash& key, int64_t pos, const void* payload, int64_t bytes);
int get_checkpoint(const BlockHash& key, int64_t pos, void* payload, int64_t bytes);
struct Stats {
int64_t reads = 0, writes = 0, hits = 0, misses = 0, verify_misses = 0, evictions = 0;
int64_t bytes_read = 0, bytes_written = 0;
};
const Stats& stats() const { return stats_; }
private:
/* `prev`/`next` link the used slots from least to most recently used, so a full store finds
* the one to give up without a walk. A walk would be over every slot of a store sized in the
* millions, once per write, on the thread that has to keep up with the host tier's copies. */
struct Slot { BlockHash key; int32_t used = 0; int64_t pos = 0; int32_t prev = -1, next = -1; };
struct Store {
DirectFile file;
int64_t slot_bytes = 0;
int64_t hdr_bytes = 0; /* header + token ids, padded */
int64_t payload = 0;
std::vector<Slot> slots;
std::unordered_map<BlockHash, int32_t, BlockHashHash> index;
std::vector<int32_t> freelist;
int32_t lru_head = -1, lru_tail = -1; /* least and most recently used */
void* stage = nullptr;
};
/* A used slot leaves the order; a slot becomes the most recently used. */
static void lru_unlink(Store& s, int32_t i);
static void lru_push(Store& s, int32_t i);
int open_store(Store& s, const std::string& path, int64_t payload, int64_t n_slots,
int64_t tok_bytes, bool allow_buffered);
int64_t scan_store(Store& s, uint32_t magic);
int claim(Store& s, const BlockHash& key, int32_t* out);
int put(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
const int32_t* toks, int32_t n_toks, const void* payload, int64_t bytes);
int get(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
const int32_t* toks, int32_t n_toks, void* payload, int64_t bytes);
/* Is the slot read into `stage` the one asked for: this store, this model, this key. */
bool header_ok(const Store& s, const void* stage, uint32_t magic, const BlockHash& key,
int64_t pos, const int32_t* toks, int32_t n_toks, int64_t bytes) const;
/* A slot whose bytes are not what the index says: out of the index and the order, and free. */
static void forget_slot(Store& s, int32_t slot);
SSDTierConfig cfg_;
std::mutex io_mu_;
Store blocks_, ckpts_;
bool enabled_ = false;
Stats stats_;
std::string report_;
};
} /* namespace rad */
+52 -72
View File
@@ -60,6 +60,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
freeb = std::min(freeb, f.free);
b.arena = std::max(b.arena, f.arena);
b.staging = std::max(b.staging, f.staging);
b.prefetch = std::max(b.prefetch, f.prefetch);
if ((int64_t)f.n_queues * f.queue_bytes > b.queues) {
b.queues = (int64_t)f.n_queues * f.queue_bytes;
b.n_queues = f.n_queues;
@@ -82,11 +83,21 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
const bool shared = host_reserve > b.headroom;
if (shared) b.headroom = host_reserve;
/* A host backend has no VRAM to speak of and reports none; there is nothing here to resolve
* and inventing a capacity would be exactly the inference §6 forbids. */
/* A DEVICE THAT REPORTS NO CAPACITY HAS NOTHING TO SPLIT, and inventing a capacity would be
* exactly the inference §6 forbids. What each pool needs is still known: the weights pool
* holds what the planner would copy out of the container -- the statics and experts
* weight_footprint counts -- and the cache is its ceiling, every sequence at the full context.
* (The host backend reports half the machine's memory and is split like a card.) */
if (b.capacity <= 0) {
b.weights = cfg.vram_weights_mib * kMiB;
b.kv = cfg.vram_kv_mib * kMiB;
b.weights = std::max<int64_t>(b.statics + b.expert_ceiling, kMiB);
b.kv = std::max<int64_t>(b.kv_ceiling, kMiB);
cfg.vram_weights_mib = to_mib_up(b.weights);
cfg.vram_kv_mib = to_mib_up(b.kv);
if (log)
b.report = fmt("the device reports no capacity: weights pool %s (what the planner "
"copies out of the container), cache %s (every sequence at the full "
"context)", humanb(cfg.vram_weights_mib * kMiB).c_str(),
humanb(cfg.vram_kv_mib * kMiB).c_str());
if (out) *out = b;
return RAD_OK;
}
@@ -98,17 +109,10 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
* plugin's init has run and its code object is resident. */
b.already_held = std::max<int64_t>(b.capacity - freeb, 0);
const bool want_w = cfg.vram_weights_mib <= 0;
const bool want_kv = cfg.vram_kv_mib <= 0;
b.derived_weights = want_w;
b.derived_kv = want_kv;
/* What is left after the terms nobody gets to spend. */
b.drift = (want_w || want_kv) ? kDriverDrift : 0;
int64_t fixed = b.already_held + b.drift + b.headroom + b.arena + b.staging + b.queues;
if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */
if (!want_kv) fixed += cfg.vram_kv_mib * kMiB;
b.claimable = b.capacity - fixed;
b.drift = kDriverDrift;
b.claimable = b.capacity - (b.already_held + b.drift + b.headroom + b.arena + b.staging +
b.queues + b.prefetch);
if (b.claimable < 0) {
b.report = fmt(
@@ -120,7 +124,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
" activation arena %10s (buffer plan + kernel scratch)\n"
" step staging %10s (block tables, media and KV tier staging)\n"
" hardware queues %10s (%d at %s each, measured)\n"
"%s%s"
" expert prefetch %10s (its ring of expert units and buffers)\n"
" ------------------------------\n"
" SHORT BY %10s\n"
"Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
@@ -128,42 +132,31 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(),
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n",
humanb(cfg.vram_weights_mib * kMiB).c_str()).c_str(),
want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n",
humanb(cfg.vram_kv_mib * kMiB).c_str()).c_str(),
humanb(-b.claimable).c_str());
humanb(b.prefetch).c_str(), humanb(-b.claimable).c_str());
if (log) RAD_ERR("%s", b.report.c_str());
if (out) *out = b;
return RAD_E_NOMEM;
}
b.weights = want_w ? 0 : cfg.vram_weights_mib * kMiB;
b.kv = want_kv ? 0 : cfg.vram_kv_mib * kMiB;
/* ---- the static weights come off the top ------------------------------------------------
*
* They are a floor and not a share. Only a DERIVED weight budget pays them here: an operator
* who stated --vram-weights-mib has already decided what the weights get, and second-guessing
* that is the re-optimisation §6 forbids. */
if (want_w) {
b.statics = std::min(b.statics, b.claimable);
if (b.statics >= b.claimable && b.claimable > 0) {
/* Not fatal: the planner will demote what does not fit and the model still serves,
* badly. Name it, because "why is this model 8x slower than it should be" has no other
* answer at startup. */
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
"give. Every expert will stream from host memory and the KV cache has "
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
"--max-num-batched-tokens.",
humanb(b.statics).c_str(), humanb(b.claimable).c_str());
}
* They are a floor and not a share. */
b.statics = std::min(b.statics, b.claimable);
if (b.statics >= b.claimable && b.claimable > 0) {
/* Not fatal: the planner will demote what does not fit and the model still serves,
* badly. Name it, because "why is this model 8x slower than it should be" has no other
* answer at startup. */
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
"give. Every expert will stream from host memory and the KV cache has "
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
"--max-num-batched-tokens.",
humanb(b.statics).c_str(), humanb(b.claimable).c_str());
}
b.elastic = want_w ? b.claimable - b.statics : b.claimable;
b.elastic = b.claimable - b.statics;
if (b.elastic < 0) b.elastic = 0;
/* ---- and only what is left is divided --------------------------------------------------- */
if (want_w && want_kv) {
{
/* An unset cache ceiling (plan_groups failed) bounds nothing; zero experts is a ceiling of
* zero, which weight_footprint always measures. */
const int64_t kv_cap = b.kv_ceiling > 0 ? b.kv_ceiling : b.elastic;
@@ -180,7 +173,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
exp = std::min(std::max(b.expert_ceiling, b.expert_floor), b.elastic - kv);
/* THE ONE SEQUENCE WINS, and the experts it pushes off the card have no tier: the
* planner refuses them by name. Said here too, with what moves it. */
if (log && exp < b.expert_floor)
if (log && b.expert_floor > 0 && exp < b.expert_floor)
RAD_WARN("one --max-model-len sequence's cache (%s) leaves the experts %s, short of "
"the %s the pinned host pool cannot hold: raise --host-pool-mib or lower "
"--max-model-len",
@@ -198,20 +191,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
b.kv = kv;
b.weights = b.statics + exp;
b.unusable = std::max<int64_t>(b.elastic - kv - exp, 0);
} else if (want_kv) {
b.kv = b.kv_ceiling > 0 ? std::min(b.claimable, b.kv_ceiling) : b.claimable;
b.unusable = b.claimable - b.kv;
} else if (want_w) {
/* The KV pool was stated, so `claimable` is already net of it; the weights take the rest,
* still capped at what the model has to put there. */
int64_t exp = b.elastic;
if (exp > b.expert_ceiling) {
b.unusable = exp - b.expert_ceiling;
exp = b.expert_ceiling;
}
b.experts = exp;
b.weights = b.statics + exp;
}
/* A POOL NOTHING IS PLACED IN STILL HAS TO EXIST. Where every weight is read where the
* container's mapping has it -- every op on the host, on the host backend -- the statics and
* experts are zero, and the pools refuse a zero budget as a resolver that never ran. A MiB,
* out of the headroom as the rounding's is. */
b.weights = std::max<int64_t>(b.weights, kMiB);
/* ---- THE PREFILL STAGING REGION, out of the expert share ---------------------------------
*
@@ -227,12 +212,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
* The share is the budget's -- what the slab alone leaves off -- which is the most a step can
* see: the loans the KV cache and the smaller arena levels make only ever add residency. A
* layer whose pooled part is larger than a buffer stages what fits and streams the rest. */
if (want_w && layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
cfg.placement != "layer_offload") {
const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling;
const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) /
RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
if (b.lends && want_kv) {
if (b.lends) {
/* A LENDING CACHE PAYS FOR IT: the experts are at their floor and a byte less would
* leave one with no tier, while the region is lent to the slab whenever the steps are
* small -- the same memory the cache would have lent. */
@@ -263,7 +248,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
* because it is a real limit rather than a ratio, is that ONE max-length sequence fits: a
* context no single request can complete is a configuration error however much slack the pool
* has (core/engine_bringup.cpp, configure_kv). */
if (log && b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0)
if (log && b.kv_ceiling > 0 && cfg.max_ctx > 0)
RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), "
"%.1f full-length sessions. That is concurrency at length before the scheduler "
"preempts, not a bound on any one request. WITH PREFIX CACHING a finished "
@@ -276,13 +261,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
(double)cfg.max_seqs * paged_share(b));
/* Rounding the floor up claims up to a MiB the split did not hand out. Take it back from the
* cache where the cache is ours to size -- a paged pool a MiB smaller addresses a handful
* fewer tokens and nothing else -- so the headroom stays whole. Where the KV budget was
* STATED it is not ours to shave and the MiB comes out of the headroom instead. */
cfg.vram_budget_derived = want_w || want_kv;
* cache -- a paged pool a MiB smaller addresses a handful fewer tokens and nothing else -- so
* the headroom stays whole. */
cfg.vram_weights_mib = to_mib_up(b.weights);
const int64_t w_over = cfg.vram_weights_mib * kMiB - b.weights;
cfg.vram_kv_mib = want_kv ? to_mib(std::max<int64_t>(b.kv - w_over, 0)) : to_mib(b.kv);
cfg.vram_kv_mib = to_mib(std::max<int64_t>(b.kv - w_over, 0));
/* THE RECEIPT. Every term, in the order it was spent, so that a split anybody disagrees with
* can be argued about against numbers instead of re-derived from sysfs by hand. The unclaimed
@@ -290,7 +273,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
* the headroom. */
const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB;
const int64_t unclaimed = b.capacity - b.already_held - b.drift - b.arena - b.staging - b.queues -
b.stage - granted;
b.prefetch - b.stage - granted;
const double ela = b.elastic > 0 ? (double)b.elastic : 1.0;
b.report = fmt(
"VRAM budget, per card:\n"
@@ -301,6 +284,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
" step staging %10s the step batch's block tables and media staging, and the\n"
" KV tiers' copy staging\n"
" hardware queues %10s %d a card at %s each, measured: the engine's streams\n"
" expert prefetch %10s the next-layer prefetch's ring of expert units and buffers\n"
" %-18s %10s %s\n"
" ------------------------------\n"
" claimable %10s\n"
@@ -318,15 +302,13 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
" could not place\n",
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
humanb(b.arena).c_str(), humanb(b.staging).c_str(),
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), humanb(b.prefetch).c_str(),
shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(),
shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool "
"outright"
shared ? "integrated graphics: this memory is the host's"
: "left unclaimed on purpose",
humanb(b.claimable).c_str(),
humanb(b.statics).c_str(),
b.derived_weights ? "off the top: every rank's own shard, and not a share of anything"
: "(not charged here -- --vram-weights-mib was stated)",
"off the top: every rank's own shard, and not a share of anything",
humanb(b.elastic).c_str(),
b.lends ? "the experts keep what the host pool cannot hold; the cache takes the rest\n"
" and lends what no live request holds to the "
@@ -375,10 +357,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
"slab while steps are small\n", humanb(b.stage).c_str(),
b.lends ? "cache" : "experts").c_str()
: "",
humanb(cfg.vram_weights_mib * kMiB).c_str(),
b.derived_weights ? "static + experts" : "stated by --vram-weights-mib",
humanb(cfg.vram_kv_mib * kMiB).c_str(),
b.derived_kv ? "the cache's share" : "stated by --vram-kv-mib",
humanb(cfg.vram_weights_mib * kMiB).c_str(), "static + experts",
humanb(cfg.vram_kv_mib * kMiB).c_str(), "the cache's share",
humanb(unclaimed).c_str());
if (out) *out = b;
+18 -7
View File
@@ -3,7 +3,7 @@
* ============================== WHY THIS IS NOT THE §6 VIOLATION IT LOOKS LIKE ==============================
*
* Spec §6 says the engine does not derive its budgets, and core/mem/pools.cpp still refuses to
* re-optimise a split the operator stated. The reason given there is exact and worth repeating:
* re-optimise the split it is handed. The reason given there is exact and worth repeating:
* a budget derived from the FREE VRAM at startup is a benchmark that moves when somebody opens a
* window on the machine's desktop.
*
@@ -46,10 +46,17 @@
* (KVManager::ceiling), and an expert plane that fits entirely in VRAM has no use for more; when
* both fit, both are whole.
*
* A stated --vram-weights-mib or --vram-kv-mib still wins outright and turns the whole of this
* off for that pool. The point is that the DEFAULT is a full card rather than a guess: VRAM left
* THERE IS NO FLAG THAT STATES A POOL. The split is a full card rather than a guess: VRAM left
* unbudgeted is VRAM no pool can use, and on a model whose experts do not fit, every unbudgeted
* GiB costs measurable decode time.
* GiB costs measurable decode time. What an operator moves is the inputs -- --gpu-headroom-mib
* takes card space away, --max-model-len and --max-num-seqs bound the cache, --host-pool-mib
* decides which experts must stay on the card -- and the arithmetic follows from them.
*
* A HOST BACKEND HAS NO CARD, and half the machine's memory stands in for one (host_vram_bytes),
* split as a card's is. Its weights pool is host memory and holds what a host kernel cannot read
* where the container stores it (mapped_unit in core/place/planner.h). A device that reports no
* capacity at all is sized at what each pool needs: the weights the planner copies, and the cache
* at its ceiling.
*/
#pragma once
#include "../rad_core.h"
@@ -74,6 +81,9 @@ struct VramFacts {
* times the ring). */
int n_queues = 0;
int64_t queue_bytes = 0;
/* THE NEXT-LAYER EXPERT PREFETCH's ring of expert units and its buffers (xprefetch.h), where it
* will be on; its stream is one of `n_queues`. */
int64_t prefetch = 0;
int64_t kv_ceiling = 0; /* KVManager::ceiling(max_ctx) for this rank's declared groups */
int64_t kv_fixed = 0; /* KVManager::fixed_bytes(): the part of the ceiling that is state */
/* weight_footprint() for this rank, which under tensor parallel is already this card's even
@@ -97,12 +107,14 @@ struct VramFacts {
int64_t host_reserve = 0;
};
/* The resolved split, in bytes, beside every term it came from. Always filled, including when the
* operator stated the budgets -- the placement report and the pool report both want the totals. */
/* The resolved split, in bytes, beside every term it came from. Always filled, including for a
* device that reports no capacity -- the placement report and the pool report both want the
* totals. */
struct VramBudget {
int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0;
int64_t drift = 0; /* kDriverDrift: what already_held moves by after it is read */
int64_t queues = 0; /* n_queues * queue_bytes, from the rank that needs most */
int64_t prefetch = 0; /* the expert prefetch's ring and buffers */
int n_queues = 0;
int64_t queue_bytes = 0;
int64_t claimable = 0; /* after the fixed terms above */
@@ -120,7 +132,6 @@ struct VramBudget {
* any. */
int64_t stage = 0;
int64_t weights = 0; /* statics + experts: what vram_weights is set to */
bool derived_weights = false, derived_kv = false;
std::string report; /* the block the engine prints at startup */
};
+167
View File
@@ -0,0 +1,167 @@
/* imaging.cpp -- PIL's Lanczos resize and alpha paste (imaging.h). The constants and the order of
* every operation are Pillow's (src/libImaging/Resample.c, Convert.c, Paste.c). */
#include "mm/imaging.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
namespace rad {
namespace mm {
namespace {
constexpr int kPrecision = 32 - 8 - 2;
double sinc(double x) {
if (x == 0.0) return 1.0;
x *= M_PI;
return std::sin(x) / x;
}
double lanczos(double x) { return (-3.0 <= x && x < 3.0) ? sinc(x) * sinc(x / 3.0) : 0.0; }
/* One axis: for each output index its first input index, its tap count, and `ksize` fixed-point
* coefficients. */
struct Axis {
int ksize = 0;
std::vector<int> bounds; /* [out, 2]: xmin, count */
std::vector<int> kk; /* [out, ksize] */
};
Axis coeffs(int in_size, int out_size) {
Axis a;
const double scale = (double)in_size / (double)out_size;
double filterscale = scale < 1.0 ? 1.0 : scale;
const double support = 3.0 * filterscale;
a.ksize = (int)std::ceil(support) * 2 + 1;
a.bounds.assign((size_t)out_size * 2, 0);
a.kk.assign((size_t)out_size * a.ksize, 0);
std::vector<double> k((size_t)a.ksize);
for (int xx = 0; xx < out_size; ++xx) {
const double center = (xx + 0.5) * scale;
double ww = 0.0;
const double ss = 1.0 / filterscale;
int xmin = (int)(center - support + 0.5);
if (xmin < 0) xmin = 0;
int xmax = (int)(center + support + 0.5);
if (xmax > in_size) xmax = in_size;
xmax -= xmin;
int x = 0;
for (; x < xmax; ++x) {
const double w = lanczos((x + xmin - center + 0.5) * ss);
k[(size_t)x] = w;
ww += w;
}
for (x = 0; x < xmax; ++x)
if (ww != 0.0) k[(size_t)x] /= ww;
for (; x < a.ksize; ++x) k[(size_t)x] = 0.0;
a.bounds[(size_t)xx * 2] = xmin;
a.bounds[(size_t)xx * 2 + 1] = xmax;
for (x = 0; x < a.ksize; ++x) {
const double v = k[(size_t)x] * (double)(1 << kPrecision);
a.kk[(size_t)xx * a.ksize + x] = v < 0 ? (int)(-0.5 + v) : (int)(0.5 + v);
}
}
return a;
}
inline uint8_t clip8(int v) {
if (v >= (1 << kPrecision << 8)) return 255;
if (v <= 0) return 0;
return (uint8_t)(v >> kPrecision);
}
inline unsigned muldiv255(unsigned a, unsigned b) {
const unsigned t = a * b + 128;
return ((t >> 8) + t) >> 8;
}
} /* namespace */
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) {
const int iw = src.w, ih = src.h;
/* RGBA -> RGBa: the colour premultiplied by the alpha */
std::vector<uint8_t> pre((size_t)iw * ih * 4);
for (size_t i = 0; i < (size_t)iw * ih; ++i) {
const unsigned al = src.rgba[i * 4 + 3];
for (int c = 0; c < 3; ++c) pre[i * 4 + c] = (uint8_t)muldiv255(src.rgba[i * 4 + c], al);
pre[i * 4 + 3] = (uint8_t)al;
}
const bool horiz = w != iw, vert = h != ih;
const Axis ax = coeffs(iw, w), ay = coeffs(ih, h);
/* the rows the vertical pass reads */
const int y_first = ay.bounds[0];
const int y_last = ay.bounds[(size_t)(h - 1) * 2] + ay.bounds[(size_t)(h - 1) * 2 + 1];
std::vector<uint8_t> tmp;
const uint8_t* rows = pre.data();
int rw = iw, row0 = 0;
if (horiz) {
const int th = vert ? y_last - y_first : ih;
const int off = vert ? y_first : 0;
tmp.assign((size_t)w * th * 4, 0);
for (int yy = 0; yy < th; ++yy)
for (int xx = 0; xx < w; ++xx) {
const int xmin = ax.bounds[(size_t)xx * 2], xn = ax.bounds[(size_t)xx * 2 + 1];
const int* k = &ax.kk[(size_t)xx * ax.ksize];
int s[4] = { 1 << (kPrecision - 1), 1 << (kPrecision - 1), 1 << (kPrecision - 1),
1 << (kPrecision - 1) };
const uint8_t* p = pre.data() + ((size_t)(yy + off) * iw + xmin) * 4;
for (int x = 0; x < xn; ++x)
for (int c = 0; c < 4; ++c) s[c] += (int)p[(size_t)x * 4 + c] * k[x];
for (int c = 0; c < 4; ++c) tmp[((size_t)yy * w + xx) * 4 + c] = clip8(s[c]);
}
rows = tmp.data();
rw = w;
row0 = vert ? y_first : 0;
}
std::vector<uint8_t> res;
if (vert) {
res.assign((size_t)rw * h * 4, 0);
for (int yy = 0; yy < h; ++yy) {
const int ymin = ay.bounds[(size_t)yy * 2] - row0, yn = ay.bounds[(size_t)yy * 2 + 1];
const int* k = &ay.kk[(size_t)yy * ay.ksize];
for (int xx = 0; xx < rw; ++xx) {
int s[4] = { 1 << (kPrecision - 1), 1 << (kPrecision - 1), 1 << (kPrecision - 1),
1 << (kPrecision - 1) };
for (int y = 0; y < yn; ++y) {
const uint8_t* p = rows + ((size_t)(y + ymin) * rw + xx) * 4;
for (int c = 0; c < 4; ++c) s[c] += (int)p[c] * k[y];
}
for (int c = 0; c < 4; ++c) res[((size_t)yy * rw + xx) * 4 + c] = clip8(s[c]);
}
}
} else {
res.assign(rows, rows + (size_t)rw * (horiz ? h : ih) * 4);
}
/* RGBa -> RGBA */
out->w = w;
out->h = h;
out->rgba.resize((size_t)w * h * 4);
for (size_t i = 0; i < (size_t)w * h; ++i) {
const unsigned al = res[i * 4 + 3];
for (int c = 0; c < 3; ++c) {
const unsigned v = res[i * 4 + c];
out->rgba[i * 4 + c] =
(al == 255 || al == 0) ? (uint8_t)v : (uint8_t)std::min(255u, (255u * v) / al);
}
out->rgba[i * 4 + 3] = (uint8_t)al;
}
}
void composite_white(const FrameRGBA& src, Frame* out) {
out->w = src.w;
out->h = src.h;
out->rgb.resize((size_t)src.w * src.h * 3);
for (size_t i = 0; i < (size_t)src.w * src.h; ++i) {
const unsigned a = src.rgba[i * 4 + 3];
for (int c = 0; c < 3; ++c) {
const unsigned t = src.rgba[i * 4 + c] * a + 255u * (255u - a) + 128u;
out->rgb[i * 3 + c] = (uint8_t)(((t >> 8) + t) >> 8);
}
}
}
} /* namespace mm */
} /* namespace rad */
+25
View File
@@ -0,0 +1,25 @@
/* imaging.h -- the picture arithmetic an image generator's reference pipeline does in PIL, done the
* way PIL does it, so a picture reaches the model as the reference's would.
*
* THE RESIZE IS PIL's Image.resize WITH LANCZOS, bit for bit: per-axis filter coefficients
* computed in double (support 3 times the downscale, normalised to sum one), turned into 22-bit
* fixed point, a horizontal pass then a vertical one over 8-bit values, each output rounded and
* clipped -- and an RGBA picture premultiplied by its alpha first and divided back after, which is
* what PIL's resize does to RGBA. Diffusers' VaeImageProcessor resizes a picture exactly this way.
*
* THE COMPOSITE is Image.paste(picture, mask=alpha) onto white: each channel
* (c * a + 255 * (255 - a)) / 255 in PIL's rounding -- how the reference flattens a transparent
* picture for a text encoder that reads RGB. */
#pragma once
#include "mm/media.h"
namespace rad {
namespace mm {
/* `src` resized to w x h. */
void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out);
/* `src` over an opaque white ground. */
void composite_white(const FrameRGBA& src, Frame* out);
} /* namespace mm */
} /* namespace rad */
+19 -5
View File
@@ -7,13 +7,27 @@ namespace rad {
namespace mm {
void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
/* AN AUDIO CLIP IS 1-D (RadBatch::enc): the frame's index, whether it is real, the clip's real
* frames and its staged ones. */
if (kind == Kind::Audio) {
for (int64_t k = 0; k < count; ++k) {
const int64_t f = first + k;
planes[k] = (int32_t)f;
planes[count + k] = f < valid ? 1 : 0;
planes[2 * count + k] = valid;
planes[3 * count + k] = grid_h;
}
return;
}
/* Merge-block order inverted: a patch's index within its segment is
* ((block_row * blocks_w + block_col) * merge + in_row) * merge + in_col. */
const int64_t seg = (int64_t)grid_h * grid_w;
const int32_t merge = grid_h / rows_h;
const int64_t bw = grid_w / merge;
int32_t s = 0;
while (s + 1 < n_seg && patch_at(s + 1) <= first) ++s;
for (int64_t k = 0; k < count; ++k) {
const int64_t within = (first + k) % seg;
while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s;
const int64_t within = first + k - patch_at(s);
const int64_t bw = seg_w(s) / merge;
const int64_t in_col = within % merge;
const int64_t in_row = (within / merge) % merge;
const int64_t blk = within / (merge * merge);
@@ -21,8 +35,8 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
const int64_t col = (blk % bw) * merge + in_col;
planes[k] = (int32_t)row;
planes[count + k] = (int32_t)col;
planes[2 * count + k] = grid_h;
planes[3 * count + k] = grid_w;
planes[2 * count + k] = seg_h(s);
planes[3 * count + k] = seg_w(s);
}
}
+363 -8
View File
@@ -10,8 +10,10 @@
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/channel_layout.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
}
#endif
@@ -32,10 +34,21 @@ static int no_decoder(std::string* why) {
int decode_image(const uint8_t*, size_t, int64_t, Frame*, std::string* why) {
return no_decoder(why);
}
int decode_image_rgba(const uint8_t*, size_t, int64_t, FrameRGBA*, std::string* why) {
return no_decoder(why);
}
int encode_image(const uint8_t*, int32_t, int32_t, int32_t, const std::string&, int32_t,
std::vector<uint8_t>*, std::string* why) {
return no_decoder(why);
}
int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*,
std::string* why) {
return no_decoder(why);
}
int decode_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector<float>*,
std::string* why) {
return no_decoder(why);
}
#else
@@ -150,13 +163,19 @@ struct Input {
/* One decoded frame to packed RGB24 at its own size. The YUV coefficients and range are the
* frame's own, so a BT.709 video and a full-range JPEG both come out with the colours they were
* encoded with; ACCURATE_RND and FULL_CHR_H_INT keep the conversion from truncating and from
* sampling chroma at half resolution. */
* encoded with.
*
* THE SCALER FLAGS ARE THE REFERENCE PIPELINE'S: transformers decodes video through PyAV
* (`to_ndarray(format="rgb24")`, its default backend), which converts with plain SWS_BILINEAR.
* The flags decide how chroma is upsampled, and at a sharp colour edge two choices differ by up to
* 70 levels: measured on an EmbeddingGemma 2 clip, SWS_BICUBIC | ACCURATE_RND | FULL_CHR_H_INT
* left the embedding at cosine 0.9995 against the reference, these at 0.99998 with every patch
* within one level. */
int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
const AVPixelFormat src = (AVPixelFormat)f->format;
*sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height,
AV_PIX_FMT_RGB24,
SWS_BICUBIC | SWS_ACCURATE_RND | SWS_FULL_CHR_H_INT, nullptr,
SWS_BILINEAR, nullptr,
nullptr, nullptr);
if (!*sws) { *why = "no colour conversion from this pixel format"; return RAD_E_UNSUPPORTED; }
int cs = f->colorspace;
@@ -167,13 +186,75 @@ int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P;
sws_setColorspaceDetails(*sws, coef, src_full, sws_getCoefficients(SWS_CS_DEFAULT), 1, 0,
1 << 16, 1 << 16);
/* THE SCALER WRITES INTO A FRAME FFMPEG ALLOCATED, and the rows are copied out. Its SIMD paths
* store whole vectors, so a row ends wherever the last vector does: a 4:2:0 or 4:2:2 picture
* 1788 wide converted with these flags writes 12 bytes past 1788 x 3, and into a buffer of
* exactly width x height x 3 those land on the next heap chunk's header -- the process aborts
* at a later allocation ("malloc(): corrupted top size"). av_frame_get_buffer pads every line
* and the end as the scaler expects. */
AVFrame* rgb = av_frame_alloc();
if (!rgb) { *why = "out of memory"; return RAD_E_NOMEM; }
rgb->format = AV_PIX_FMT_RGB24;
rgb->width = f->width;
rgb->height = f->height;
if (av_frame_get_buffer(rgb, 0) < 0) {
av_frame_free(&rgb);
*why = "out of memory";
return RAD_E_NOMEM;
}
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, rgb->data, rgb->linesize);
if (e != f->height) {
av_frame_free(&rgb);
*why = "colour conversion failed";
return RAD_E_INVAL;
}
out->w = f->width;
out->h = f->height;
out->rgb.resize((size_t)f->width * (size_t)f->height * 3);
uint8_t* dst[4] = { out->rgb.data(), nullptr, nullptr, nullptr };
int dst_ls[4] = { f->width * 3, 0, 0, 0 };
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, dst, dst_ls);
if (e != f->height) { *why = "colour conversion failed"; return RAD_E_INVAL; }
const size_t row = (size_t)f->width * 3;
out->rgb.resize(row * (size_t)f->height);
for (int y = 0; y < f->height; ++y)
std::memcpy(out->rgb.data() + (size_t)y * row, rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0], row);
av_frame_free(&rgb);
return RAD_OK;
}
/* The same conversion to packed RGBA, for a picture whose alpha is kept. */
int to_rgba(const AVFrame* f, SwsContext** sws, FrameRGBA* out, std::string* why) {
const AVPixelFormat src = (AVPixelFormat)f->format;
*sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height,
AV_PIX_FMT_RGBA, SWS_BILINEAR, nullptr, nullptr, nullptr);
if (!*sws) { *why = "no colour conversion from this pixel format"; return RAD_E_UNSUPPORTED; }
int cs = f->colorspace;
if (cs == AVCOL_SPC_UNSPECIFIED || cs == AVCOL_SPC_RGB) cs = AVCOL_SPC_BT470BG;
const int src_full = f->color_range == AVCOL_RANGE_JPEG ||
src == AV_PIX_FMT_YUVJ420P || src == AV_PIX_FMT_YUVJ422P ||
src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P;
sws_setColorspaceDetails(*sws, sws_getCoefficients(cs), src_full,
sws_getCoefficients(SWS_CS_DEFAULT), 1, 0, 1 << 16, 1 << 16);
AVFrame* dst = av_frame_alloc();
if (!dst) { *why = "out of memory"; return RAD_E_NOMEM; }
dst->format = AV_PIX_FMT_RGBA;
dst->width = f->width;
dst->height = f->height;
if (av_frame_get_buffer(dst, 0) < 0) {
av_frame_free(&dst);
*why = "out of memory";
return RAD_E_NOMEM;
}
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, dst->data, dst->linesize);
if (e != f->height) {
av_frame_free(&dst);
*why = "colour conversion failed";
return RAD_E_INVAL;
}
out->w = f->width;
out->h = f->height;
const size_t row = (size_t)f->width * 4;
out->rgba.resize(row * (size_t)f->height);
for (int y = 0; y < f->height; ++y)
std::memcpy(out->rgba.data() + (size_t)y * row, dst->data[0] + (ptrdiff_t)y * dst->linesize[0],
row);
av_frame_free(&dst);
return RAD_OK;
}
@@ -279,6 +360,138 @@ int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out,
return RAD_OK;
}
int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRGBA* out,
std::string* why) {
std::string w;
if (!why) why = &w;
if (!data || n == 0) { *why = "empty"; return RAD_E_INVAL; }
Input in;
RAD_TRY(in.open(data, n, true, why));
const AVCodecParameters* cp = in.fmt->streams[in.stream]->codecpar;
if (cp->width <= 0 || cp->height <= 0) { *why = "the image has no size"; return RAD_E_INVAL; }
if ((int64_t)cp->width * cp->height > max_pixels) {
*why = "the image is " + std::to_string(cp->width) + "x" + std::to_string(cp->height) +
", over the server's " + std::to_string(max_pixels) + "-pixel limit for a source";
return RAD_E_INVAL;
}
SwsContext* sws = nullptr;
bool got = false;
const int s = decode_frames(in, [&](int64_t, const AVFrame* f) -> int {
const int c = to_rgba(f, &sws, out, why);
if (c < 0) return c;
got = true;
return 1;
}, why);
sws_freeContext(sws);
if (s < 0) return s;
if (!got) { *why = "the image decoded to no frame"; return RAD_E_INVAL; }
return RAD_OK;
}
/* ONE PICTURE THROUGH ONE ENCODER. The pixels are converted to the pixel format the encoder takes
* (swscale, full-range BT.601 for jpeg's YUV, as PIL writes it), sent as one frame, and the one
* packet that comes back is the file: png, mjpeg and libwebp all write a complete image file a
* packet. */
int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format,
int32_t quality, std::vector<uint8_t>* out, std::string* why) {
std::string wy;
if (!why) why = &wy;
if (!px || w <= 0 || h <= 0 || (ch != 3 && ch != 4) || !out) {
*why = "no picture to encode";
return RAD_E_INVAL;
}
const AVCodec* codec = nullptr;
AVPixelFormat pf = AV_PIX_FMT_NONE;
if (format == "png") {
codec = avcodec_find_encoder(AV_CODEC_ID_PNG);
pf = ch == 4 ? AV_PIX_FMT_RGBA : AV_PIX_FMT_RGB24;
} else if (format == "jpeg") {
if (ch == 4) { *why = "jpeg carries no alpha"; return RAD_E_INVAL; }
codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG);
pf = AV_PIX_FMT_YUVJ420P;
} else if (format == "webp") {
codec = avcodec_find_encoder_by_name("libwebp");
pf = AV_PIX_FMT_BGRA;
} else {
*why = "'" + format + "' is not an image format this server writes (png, jpeg, webp)";
return RAD_E_INVAL;
}
if (!codec) {
*why = "this build has no " + format + " encoder";
return RAD_E_UNSUPPORTED;
}
AVCodecContext* cx = avcodec_alloc_context3(codec);
AVFrame* fr = av_frame_alloc();
AVPacket* pk = av_packet_alloc();
SwsContext* sws = nullptr;
int st = RAD_OK;
auto fail = [&](const std::string& m, int code) { *why = m; st = code; };
do {
if (!cx || !fr || !pk) { fail("out of memory", RAD_E_NOMEM); break; }
cx->width = w;
cx->height = h;
cx->pix_fmt = pf;
cx->time_base = AVRational{ 1, 25 };
cx->color_range = format == "jpeg" ? AVCOL_RANGE_JPEG : AVCOL_RANGE_UNSPECIFIED;
if (format == "jpeg") {
const int q = quality > 0 && quality <= 100 ? quality : 90;
/* qscale 2 (best) .. 31 (worst), linear in the quality */
const int qs = 2 + (100 - q) * 29 / 100;
cx->flags |= AV_CODEC_FLAG_QSCALE;
cx->global_quality = FF_QP2LAMBDA * qs;
}
/* PNG AT zlib LEVEL 1 WITH PER-ROW PREDICTION: a 2048^2 picture in 0.16 s and 5.9 MB, where
* the encoder's default (level 6) takes 1.0 s for 5.3 MB -- a second of a few-step image
* model's request, on one core, for a tenth of the bytes. */
if (format == "png") {
cx->compression_level = 1;
av_opt_set(cx->priv_data, "pred", "mixed", 0);
}
if (format == "webp") {
const int q = quality > 0 && quality <= 100 ? quality : 90;
if (q >= 100) av_opt_set_int(cx->priv_data, "lossless", 1, 0);
else av_opt_set_double(cx->priv_data, "quality", (double)q, 0);
}
int r = avcodec_open2(cx, codec, nullptr);
if (r < 0) { fail("the " + format + " encoder would not open (" + averr(r) + ")", RAD_E_INVAL); break; }
fr->format = pf;
fr->width = w;
fr->height = h;
if (av_frame_get_buffer(fr, 0) < 0) { fail("out of memory", RAD_E_NOMEM); break; }
const AVPixelFormat src = ch == 4 ? AV_PIX_FMT_RGBA : AV_PIX_FMT_RGB24;
sws = sws_getContext(w, h, src, w, h, pf, SWS_BILINEAR | SWS_ACCURATE_RND, nullptr,
nullptr, nullptr);
if (!sws) { fail("no colour conversion to the encoder's format", RAD_E_UNSUPPORTED); break; }
if (format == "jpeg")
sws_setColorspaceDetails(sws, sws_getCoefficients(SWS_CS_DEFAULT), 1,
sws_getCoefficients(SWS_CS_ITU601), 1, 0, 1 << 16, 1 << 16);
const uint8_t* sp[1] = { px };
const int sl[1] = { w * ch };
if (sws_scale(sws, sp, sl, 0, h, fr->data, fr->linesize) != h) {
fail("colour conversion failed", RAD_E_INVAL);
break;
}
fr->pts = 0;
r = avcodec_send_frame(cx, fr);
if (r >= 0) r = avcodec_send_frame(cx, nullptr);
if (r < 0) { fail("encoding failed (" + averr(r) + ")", RAD_E_INVAL); break; }
out->clear();
for (;;) {
r = avcodec_receive_packet(cx, pk);
if (r == AVERROR_EOF || r == AVERROR(EAGAIN)) break;
if (r < 0) { fail("encoding failed (" + averr(r) + ")", RAD_E_INVAL); break; }
out->insert(out->end(), pk->data, pk->data + pk->size);
av_packet_unref(pk);
}
if (st == RAD_OK && out->empty()) fail("the encoder wrote nothing", RAD_E_INVAL);
} while (false);
sws_freeContext(sws);
av_packet_free(&pk);
av_frame_free(&fr);
avcodec_free_context(&cx);
return st;
}
int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user,
int64_t max_pixels, Video* out, std::string* why) {
std::string w;
@@ -360,6 +573,148 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
return RAD_OK;
}
/* ================================================================== audio */
namespace {
/* THE AUDIO DEMUXERS A REQUEST MAY REACH, chosen as the video list is: formats that hold one
* stream of samples and cannot name another file. */
constexpr const char* kAudioFormats = "wav,w64,mp3,flac,ogg,mov,mp4,m4a,matroska,webm,aac,aiff";
struct AudioIn {
MemIO io;
AVIOContext* avio = nullptr;
AVFormatContext* fmt = nullptr;
AVCodecContext* dec = nullptr;
SwrContext* swr = nullptr;
int stream = -1;
~AudioIn() {
if (swr) swr_free(&swr);
if (dec) avcodec_free_context(&dec);
if (fmt) avformat_close_input(&fmt);
if (avio) {
av_freep(&avio->buffer);
avio_context_free(&avio);
}
}
int open(const uint8_t* data, size_t n, std::string* why) {
io.p = data; io.n = n; io.at = 0;
constexpr int kBuf = 64 * 1024;
uint8_t* buf = static_cast<uint8_t*>(av_malloc(kBuf));
if (!buf) { *why = "out of memory"; return RAD_E_NOMEM; }
avio = avio_alloc_context(buf, kBuf, 0, &io, mem_read, nullptr, mem_seek);
if (!avio) { av_free(buf); *why = "out of memory"; return RAD_E_NOMEM; }
fmt = avformat_alloc_context();
if (!fmt) { *why = "out of memory"; return RAD_E_NOMEM; }
fmt->pb = avio;
fmt->flags |= AVFMT_FLAG_CUSTOM_IO;
AVDictionary* opts = nullptr;
av_dict_set(&opts, "format_whitelist", kAudioFormats, 0);
av_dict_set(&opts, "protocol_whitelist", "", 0);
int e = avformat_open_input(&fmt, nullptr, nullptr, &opts);
av_dict_free(&opts);
if (e < 0) {
fmt = nullptr;
*why = "not a recognised audio format (" + averr(e) + ")";
return RAD_E_INVAL;
}
e = avformat_find_stream_info(fmt, nullptr);
if (e < 0) { *why = "could not read the stream headers (" + averr(e) + ")"; return RAD_E_INVAL; }
const AVCodec* codec = nullptr;
stream = av_find_best_stream(fmt, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
if (stream < 0 || !codec) { *why = "no sound in it: the media holds no audio stream"; return RAD_E_INVAL; }
dec = avcodec_alloc_context3(codec);
if (!dec) { *why = "out of memory"; return RAD_E_NOMEM; }
e = avcodec_parameters_to_context(dec, fmt->streams[stream]->codecpar);
if (e < 0) { *why = "decoder setup failed (" + averr(e) + ")"; return RAD_E_INVAL; }
dec->thread_count = 1;
e = avcodec_open2(dec, codec, nullptr);
if (e < 0) { *why = std::string("no decoder for ") + codec->name + " (" + averr(e) + ")"; return RAD_E_UNSUPPORTED; }
return RAD_OK;
}
};
} /* namespace */
int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples,
std::vector<float>* out, std::string* why) {
std::string w;
if (!why) why = &w;
out->clear();
if (rate <= 0 || max_samples <= 0) { *why = "no sample rate or length to decode to"; return RAD_E_INVAL; }
AudioIn in;
RAD_TRY(in.open(data, n, why));
AVCodecContext* dec = in.dec;
const int channels = dec->ch_layout.nb_channels > 0 ? dec->ch_layout.nb_channels : 1;
if (dec->sample_rate <= 0) { *why = "the audio stream states no sample rate"; return RAD_E_INVAL; }
/* Resampled at the source's own layout, float interleaved; the mono mean is taken after. A
* layout the stream does not state is taken as `channels` unordered channels. */
AVChannelLayout layout{};
if (av_channel_layout_check(&dec->ch_layout)) av_channel_layout_copy(&layout, &dec->ch_layout);
else av_channel_layout_default(&layout, channels);
int e = swr_alloc_set_opts2(&in.swr, &layout, AV_SAMPLE_FMT_FLT, rate, &layout,
(AVSampleFormat)dec->sample_fmt, dec->sample_rate, 0, nullptr);
av_channel_layout_uninit(&layout);
if (e < 0 || !in.swr || swr_init(in.swr) < 0) {
*why = "no resampler for this audio (" + averr(e) + ")";
return RAD_E_UNSUPPORTED;
}
std::vector<float> buf;
auto take = [&](const uint8_t** src, int n_in) -> int {
const int cap = swr_get_out_samples(in.swr, n_in);
if (cap <= 0) return 0;
buf.resize((size_t)cap * (size_t)channels);
uint8_t* dst = reinterpret_cast<uint8_t*>(buf.data());
const int got = swr_convert(in.swr, &dst, cap, src, n_in);
if (got < 0) { *why = "resampling failed (" + averr(got) + ")"; return RAD_E_INVAL; }
for (int i = 0; i < got && (int64_t)out->size() < max_samples; ++i) {
float s = 0.0f;
for (int c = 0; c < channels; ++c) s += buf[(size_t)i * channels + c];
out->push_back(channels == 1 ? s : s / (float)channels);
}
return 0;
};
AVPacket* pkt = av_packet_alloc();
AVFrame* f = av_frame_alloc();
if (!pkt || !f) {
av_packet_free(&pkt);
av_frame_free(&f);
*why = "out of memory";
return RAD_E_NOMEM;
}
int st = RAD_OK;
bool done = false;
while (!done && (int64_t)out->size() < max_samples) {
e = av_read_frame(in.fmt, pkt);
if (e < 0) {
avcodec_send_packet(dec, nullptr); /* drain */
done = true;
} else {
if (pkt->stream_index == in.stream) e = avcodec_send_packet(dec, pkt);
av_packet_unref(pkt);
if (e < 0 && e != AVERROR(EAGAIN)) { *why = "the audio would not decode (" + averr(e) + ")"; st = RAD_E_INVAL; break; }
}
while ((e = avcodec_receive_frame(dec, f)) >= 0) {
if ((st = take(const_cast<const uint8_t**>(f->extended_data), f->nb_samples)) < 0) break;
av_frame_unref(f);
}
if (st < 0) break;
if (e != AVERROR(EAGAIN) && e != AVERROR_EOF) { *why = "the audio would not decode (" + averr(e) + ")"; st = RAD_E_INVAL; break; }
}
/* What the resampler still holds. */
if (st == RAD_OK && (int64_t)out->size() < max_samples) st = take(nullptr, 0);
av_packet_free(&pkt);
av_frame_free(&f);
if (st < 0) return st;
if (out->empty()) { *why = "the audio decoded to no samples"; return RAD_E_INVAL; }
return RAD_OK;
}
#endif /* RAD_HAVE_FFMPEG */
} /* namespace mm */
+25
View File
@@ -27,6 +27,13 @@ struct Frame {
std::vector<uint8_t> rgb; /* [h, w, 3] */
};
/* A picture with its alpha: packed 8-bit RGBA, row-major, no padding -- what an image generator
* reads and writes. A source without alpha comes back opaque. */
struct FrameRGBA {
int32_t w = 0, h = 0;
std::vector<uint8_t> rgba; /* [h, w, 4] */
};
/* Is there a decoder in this build. */
bool decoder_available();
@@ -34,6 +41,16 @@ bool decoder_available();
* `max_pixels` in the SOURCE, which is what bounds the memory a request can make the server
* allocate before any resize happens. */
int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, std::string* why);
/* The same, keeping the alpha channel. */
int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRGBA* out,
std::string* why);
/* A PICTURE TO A FILE: `px` is [h, w, ch] 8-bit, ch 3 (RGB) or 4 (RGBA), and `format` one of png,
* jpeg and webp. `quality` 0..100 is jpeg's and lossy webp's (0 or above 100: the format's own
* default); png is lossless and webp is lossless at 100. jpeg has no alpha and is refused one.
* RAD_E_UNSUPPORTED, with the reason, for a format this build has no encoder for. */
int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format,
int32_t quality, std::vector<uint8_t>* out, std::string* why);
/* HOW A VIDEO IS SAMPLED, and it happens INSIDE the decode rather than after it: a minute of 1080p
* is 10 GB of RGB, so frames that are not sampled are never converted or kept. The choice of which
@@ -56,5 +73,13 @@ struct Video {
int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user,
int64_t max_pixels, Video* out, std::string* why);
/* AN AUDIO CLIP as mono float samples at `rate` Hz: the first audio stream, resampled with
* libswresample at the source's channel layout and then averaged across channels -- the plain
* mean every reference loader (librosa, torchaudio's to-mono) takes, where swresample's own
* downmix would weight a stereo pair by 0.707. At most `max_samples` are kept: a longer clip is
* cut there, as the reference feature extractor truncates. */
int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples,
std::vector<float>* out, std::string* why);
} /* namespace mm */
} /* namespace rad */
+799 -33
View File
@@ -26,7 +26,113 @@ static bool read_triple(const RadModelMeta& m, const char* key, float out[3]) {
return true;
}
static bool soft_budget_ok(int32_t n) {
return n == 70 || n == 140 || n == 280 || n == 560 || n == 1120;
}
/* A flag a container flattened from JSON: `true`/`false`, or a number. */
static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) {
const char* v = rad_meta_gets(&m, key, nullptr);
if (!v || !*v) return dflt;
if (!std::strcmp(v, "true")) return true;
if (!std::strcmp(v, "false")) return false;
return std::strtol(v, nullptr, 10) != 0;
}
int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
/* LFM2-VL states its processor twice, in config.json and in processor_config.json's
* image_processor; the latter is what the reference processor reads, so it goes first. */
if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "lfm2_vl")) {
family = Family::Lfm2;
auto key = [](const char* k) { return std::string("processor.image_processor.") + k; };
auto geti = [&](const char* k, int64_t dflt) {
return rad_meta_geti(&m, key(k).c_str(), rad_meta_geti(&m, k, dflt));
};
auto getb = [&](const char* k, bool dflt) {
return meta_bool(m, key(k).c_str(), meta_bool(m, k, dflt));
};
patch = (int32_t)geti("encoder_patch_size", rad_meta_geti(&m, "vision_config.patch_size", 0));
merge = (int32_t)geti("downsample_factor", 0);
temporal = 1;
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
if (patch <= 0 || merge <= 0 || tok_image < 0) {
if (why) *why = "the container states no LFM2-VL processor geometry (encoder_patch_size, "
"downsample_factor, image_token_id)";
return RAD_E_NOTFOUND;
}
const int64_t f2 = (int64_t)factor() * factor();
image_min_pixels = geti("min_image_tokens", 64) * f2;
image_max_pixels = geti("max_image_tokens", 256) * f2;
video_min_pixels = image_min_pixels; /* no video; consistent for check() */
video_max_pixels = image_max_pixels;
/* The markers around a picture and before each tile are what the model was trained on;
* a checkpoint that turns them off spells its pictures differently, which is not served. */
if (!meta_bool(m, "use_image_special_tokens", true)) {
if (why) *why = "use_image_special_tokens is off; this processor writes LFM2-VL's "
"picture markers and serves only the checkpoints that read them";
return RAD_E_UNSUPPORTED;
}
const bool split = getb("do_image_splitting", true);
min_tiles = split ? (int32_t)geti("min_tiles", 2) : 1;
max_tiles = split ? (int32_t)geti("max_tiles", 10) : 1;
tile = (int32_t)geti("tile_size", 512);
use_thumbnail = getb("use_thumbnail", true);
max_pixels_tolerance = rad_meta_getf(&m, key("max_pixels_tolerance").c_str(),
rad_meta_getf(&m, "max_pixels_tolerance", 2.0));
max_segment_patches = geti("max_num_patches", 1024);
if (!read_triple(m, key("image_mean").c_str(), mean)) read_triple(m, "preprocessor.image_mean", mean);
if (!read_triple(m, key("image_std").c_str(), stdv)) read_triple(m, "preprocessor.image_std", stdv);
std::string bad;
if (check(&bad) < 0) {
if (why) *why = "the container's LFM2-VL processor configuration is inconsistent: " + bad;
return RAD_E_INVAL;
}
return RAD_OK;
}
const char* mt = rad_meta_gets(&m, "vision_config.model_type", "");
if (mt && !std::strcmp(mt, "gemma4_vision")) {
family = Family::Gemma4;
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
merge = (int32_t)rad_meta_geti(&m, "vision_config.pooling_kernel_size", 0);
temporal = 1;
if (patch <= 0 || merge <= 0) {
if (why) *why = "the container states no vision tower geometry (vision_config."
"patch_size, pooling_kernel_size)";
return RAD_E_NOTFOUND;
}
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
tok_video = (int32_t)rad_meta_geti(&m, "video_token_id", -1);
tok_start = (int32_t)rad_meta_geti(&m, "boi_token_id", -1);
tok_end = (int32_t)rad_meta_geti(&m, "eoi_token_id", -1);
if (tok_image < 0 || tok_video < 0 || tok_start < 0 || tok_end < 0) {
if (why) *why = "the container states no media token ids (image_token_id, "
"video_token_id, boi_token_id, eoi_token_id)";
return RAD_E_NOTFOUND;
}
/* The budgets from the processor config, the model's stated default when it is absent. */
image_soft_tokens = (int32_t)rad_meta_geti(
&m, "processor.image_processor.max_soft_tokens",
rad_meta_geti(&m, "vision_soft_tokens_per_image",
rad_meta_geti(&m, "vision_config.default_output_length", 280)));
video_soft_tokens = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_soft_tokens",
70);
fps = rad_meta_getf(&m, "processor.video_processor.fps", 1.0);
min_frames = 1;
max_frames = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_frames", 32);
max_frame_rows = 0;
/* The pixel bands are QwenVL's; here they only have to be consistent for check(). */
const int64_t f2 = (int64_t)factor() * factor();
image_min_pixels = video_min_pixels = f2;
image_max_pixels = (int64_t)image_soft_tokens * f2;
video_max_pixels = (int64_t)video_soft_tokens * f2 * max_frames;
std::string bad;
if (check(&bad) < 0) {
if (why) *why = "the container's processor configuration is inconsistent: " + bad;
return RAD_E_INVAL;
}
return RAD_OK;
}
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
temporal = (int32_t)rad_meta_geti(&m, "vision_config.temporal_patch_size", 0);
merge = (int32_t)rad_meta_geti(&m, "vision_config.spatial_merge_size", 0);
@@ -90,6 +196,24 @@ int VisionConfig::check(std::string* why) const {
if (max_frames < min_frames)
return no("max_frames " + std::to_string(max_frames) + " is below min_frames " +
std::to_string(min_frames));
if (family == Family::Lfm2) {
if (min_tiles < 1 || max_tiles < min_tiles || tile <= 0 || tile % factor())
return no("the tiling (min_tiles " + std::to_string(min_tiles) + ", max_tiles " +
std::to_string(max_tiles) + ", tile_size " + std::to_string(tile) +
") is not a range of whole merged patches");
if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0)
return no("max_pixels_tolerance and max_num_patches must be positive");
for (int c = 0; c < 3; ++c)
if (!(stdv[c] > 0.0f)) return no("image_std must be positive");
}
if (family == Family::Gemma4) {
if (!soft_budget_ok(image_soft_tokens))
return no("the image soft-token budget " + std::to_string(image_soft_tokens) +
" is not one of 70, 140, 280, 560, 1120");
if (!soft_budget_ok(video_soft_tokens))
return no("the video frame soft-token budget " + std::to_string(video_soft_tokens) +
" is not one of 70, 140, 280, 560, 1120");
}
return RAD_OK;
}
@@ -173,6 +297,65 @@ std::vector<int64_t> sample_frames(const VideoInfo& info, double fps, int32_t mi
return idx;
}
int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches,
int64_t* oh, int64_t* ow, std::string* why) {
if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; }
/* get_aspect_ratio_preserving_size, in Python's doubles. */
const double total = (double)h * (double)w;
const double target = (double)max_patches * (double)patch * (double)patch;
const double factor = std::sqrt(target / total);
const int64_t side = (int64_t)patch * pool;
int64_t th = (int64_t)std::floor(factor * (double)h / (double)side) * side;
int64_t tw = (int64_t)std::floor(factor * (double)w / (double)side) * side;
if (th == 0 && tw == 0) {
if (why) *why = "the picture is too small to make one pooled patch";
return RAD_E_INVAL;
}
const int64_t max_side = (max_patches / ((int64_t)pool * pool)) * side;
if (th == 0) {
th = side;
tw = std::min<int64_t>((int64_t)std::floor((double)w / (double)h) * side, max_side);
} else if (tw == 0) {
tw = side;
th = std::min<int64_t>((int64_t)std::floor((double)h / (double)w) * side, max_side);
}
if ((double)th * (double)tw > target) {
if (why) *why = "the picture's aspect ratio does not fit the patch budget";
return RAD_E_INVAL;
}
*oh = th;
*ow = tw;
return RAD_OK;
}
/* The reference's (EmbeddingGemma2VideoProcessor.sample_frames): the stream's duration at `fps`,
* one frame each 1/fps seconds as int(i * native_fps / fps), then `max_frames` of those chosen by
* numpy's linspace truncated to integers. */
std::vector<int64_t> sample_frames_gemma4(const VideoInfo& info, double fps, int32_t max_frames) {
const int64_t total = info.n_frames;
if (total <= 0) return {};
std::vector<int64_t> idx;
if (info.fps > 0.0) {
const double step = info.fps / fps;
const double duration = (double)total / info.fps;
const int64_t n = std::max<int64_t>(1, (int64_t)(duration * fps));
for (int64_t i = 0; i < n; ++i)
idx.push_back(std::min<int64_t>(total - 1, (int64_t)((double)i * step)));
} else {
for (int64_t i = 0; i < total; ++i) idx.push_back(i);
}
if (max_frames > 0 && (int64_t)idx.size() > max_frames) {
std::vector<int64_t> keep((size_t)max_frames);
const double span = (double)(idx.size() - 1);
for (int32_t i = 0; i < max_frames; ++i) {
const double t = max_frames == 1 ? 0.0 : span * (double)i / (double)(max_frames - 1);
keep[(size_t)i] = idx[(size_t)(int64_t)t];
}
idx.swap(keep);
}
return idx;
}
/* ================================================================== the resample
*
* Pillow's ImagingResample for an 8-bit RGB image, transcribed: the coefficient table in double,
@@ -192,20 +375,21 @@ inline double bicubic(double x) {
return 0.0;
}
inline uint8_t clip8(int32_t v) {
const int32_t s = v >> kPrec;
inline uint8_t clip8(int32_t v, int prec) {
const int32_t s = v >> prec;
return (uint8_t)(s < 0 ? 0 : (s > 255 ? 255 : s));
}
/* One axis: `bounds` gets (first, count) per output pixel and `kk` its fixed-point weights, `ksize`
* a row. */
* a row, `*prec` their fraction bits: PIL's fixed 22, or -- `torch` -- ATen's per-axis choice, the
* most bits at which the largest weight still fits an int16. */
int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
std::vector<int32_t>* kk) {
std::vector<int32_t>* kk, bool torch, int* prec) {
const double scale = (double)in_size / (double)out_size;
const double fscale = scale < 1.0 ? 1.0 : scale;
const double support = 2.0 * fscale;
const int ksize = (int)std::ceil(support) * 2 + 1;
std::vector<double> k((size_t)ksize);
std::vector<double> k((size_t)ksize), w((size_t)out_size * (size_t)ksize, 0.0);
bounds->assign((size_t)out_size * 2, 0);
kk->assign((size_t)out_size * (size_t)ksize, 0);
for (int xx = 0; xx < out_size; ++xx) {
@@ -226,24 +410,32 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
for (x = 0; x < xmax; ++x)
if (ww != 0.0) k[(size_t)x] /= ww;
for (; x < ksize; ++x) k[(size_t)x] = 0.0;
for (x = 0; x < ksize; ++x) {
const double v = k[(size_t)x];
(*kk)[(size_t)xx * ksize + x] = v < 0 ? (int32_t)(-0.5 + v * (1 << kPrec))
: (int32_t)(0.5 + v * (1 << kPrec));
}
for (x = 0; x < ksize; ++x) w[(size_t)xx * ksize + x] = k[(size_t)x];
(*bounds)[(size_t)xx * 2] = xmin;
(*bounds)[(size_t)xx * 2 + 1] = xmax;
}
*prec = kPrec;
if (torch) {
double largest = 0.0;
for (double v : w) largest = std::max(largest, v);
for (*prec = 0; *prec < 22; ++*prec)
if ((int)(0.5 + largest * (1 << (*prec + 1))) >= (1 << 15)) break;
}
for (size_t i = 0; i < w.size(); ++i) {
const double v = w[i];
(*kk)[i] = v < 0 ? (int32_t)(-0.5 + v * (1 << *prec)) : (int32_t)(0.5 + v * (1 << *prec));
}
return ksize;
}
} /* namespace */
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch) {
if (in.w == w && in.h == h) { *out = in; return; }
std::vector<int32_t> bh, kh, bv, kv;
const int ksh = coeffs(in.w, w, &bh, &kh);
const int ksv = coeffs(in.h, h, &bv, &kv);
int ph = kPrec, pv = kPrec;
const int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph);
const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv);
/* The source rows the vertical pass reads, which is all the horizontal pass has to produce. */
const int y_first = bv[0];
@@ -265,16 +457,16 @@ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
for (int xx = 0; xx < w; ++xx) {
const int xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
const int32_t* k = kh.data() + (size_t)xx * ksh;
int32_t s0 = 1 << (kPrec - 1), s1 = s0, s2 = s0;
int32_t s0 = 1 << (ph - 1), s1 = s0, s2 = s0;
for (int x = 0; x < xmax; ++x) {
const uint8_t* p = row + (size_t)(x + xmin) * 3;
s0 += p[0] * k[x];
s1 += p[1] * k[x];
s2 += p[2] * k[x];
}
o[xx * 3 + 0] = clip8(s0);
o[xx * 3 + 1] = clip8(s1);
o[xx * 3 + 2] = clip8(s2);
o[xx * 3 + 0] = clip8(s0, ph);
o[xx * 3 + 1] = clip8(s1, ph);
o[xx * 3 + 2] = clip8(s2, ph);
}
}
src = &tmp;
@@ -289,20 +481,34 @@ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
const int32_t* k = kv.data() + (size_t)yy * ksv;
uint8_t* o = out->rgb.data() + (size_t)yy * src->w * 3;
for (int xx = 0; xx < src->w; ++xx) {
int32_t s0 = 1 << (kPrec - 1), s1 = s0, s2 = s0;
int32_t s0 = 1 << (pv - 1), s1 = s0, s2 = s0;
for (int y = 0; y < ymax; ++y) {
const uint8_t* p = src->rgb.data() + ((size_t)(y + ymin) * src->w + xx) * 3;
s0 += p[0] * k[y];
s1 += p[1] * k[y];
s2 += p[2] * k[y];
}
o[xx * 3 + 0] = clip8(s0);
o[xx * 3 + 1] = clip8(s1);
o[xx * 3 + 2] = clip8(s2);
o[xx * 3 + 0] = clip8(s0, pv);
o[xx * 3 + 1] = clip8(s1, pv);
o[xx * 3 + 2] = clip8(s2, pv);
}
}
}
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
resize_bicubic_impl(in, w, h, out, false);
}
void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out) {
resize_bicubic_impl(in, w, h, out, true);
}
void cap_area(const Frame& in, int64_t max_pixels, Frame* out) {
if (max_pixels <= 0 || (int64_t)in.w * in.h <= max_pixels) { *out = in; return; }
const double scale = std::sqrt((double)max_pixels / ((double)in.w * in.h));
resize_bicubic(in, std::max(1, (int)(in.w * scale)), std::max(1, (int)(in.h * scale)), out);
}
/* ================================================================== patches */
namespace {
@@ -320,7 +526,12 @@ inline uint64_t mix64(uint64_t x) {
void content_key(const Item& it, uint64_t* hi, uint64_t* lo) {
uint64_t a = 0x6a09e667f3bcc908ull ^ mix64((uint64_t)it.grid_t << 42 ^
(uint64_t)it.grid_h << 21 ^ (uint64_t)it.grid_w);
uint64_t b = 0xbb67ae8584caa73bull ^ mix64(it.kind == Kind::Image ? 1u : 2u);
uint64_t b = 0xbb67ae8584caa73bull ^
mix64(it.kind == Kind::Image ? 1u : it.kind == Kind::Video ? 2u : 3u);
/* The tiling, when the segments have sizes of their own: the same patches cut differently
* are different encoder inputs. */
for (const Item::Segment& sg : it.segments)
a = mix64(a ^ ((uint64_t)(uint32_t)sg.h << 32 | (uint32_t)sg.w)) + (uint64_t)sg.patch0;
const uint8_t* p = reinterpret_cast<const uint8_t*>(it.pixels.data());
const size_t n = it.pixels.size() * sizeof(uint16_t);
size_t i = 0;
@@ -375,6 +586,37 @@ void patchify(const VisionConfig& c, const std::vector<const Frame*>& frames, It
}
}
/* Gemma 4's patch rows: merge-block order like patchify's (each pooling window's patches are
* consecutive, which is what lets the pooler be a mean of k^2 consecutive rows; attention and the
* position terms read each patch's own coordinates, so the order is free), each row (y, x,
* channel), each value 2 * (u * (1/255)) - 1 in f32 -- the processor's rescale and then the
* model's own input scaling -- rounded to bf16. One frame a segment. */
void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& frames, Item* it) {
const int P = c.patch, M = c.merge;
const int gh = it->grid_h, gw = it->grid_w;
uint16_t lut[256];
for (int v = 0; v < 256; ++v) {
const float p = (float)v * (float)(1.0 / 255.0);
lut[v] = rad_f32_to_bf16(2.0f * (p - 0.5f));
}
const int64_t dim = it->patch_dim;
it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0);
uint16_t* dst = it->pixels.data();
for (int g = 0; g < it->grid_t; ++g) {
const Frame& f = *frames[(size_t)g];
for (int bh = 0; bh < gh / M; ++bh)
for (int bw = 0; bw < gw / M; ++bw)
for (int mh = 0; mh < M; ++mh)
for (int mw = 0; mw < M; ++mw) {
const int py0 = (bh * M + mh) * P, px0 = (bw * M + mw) * P;
for (int y = 0; y < P; ++y) {
const uint8_t* row = f.rgb.data() + ((size_t)(py0 + y) * f.w + px0) * 3;
for (int x = 0; x < 3 * P; ++x) *dst++ = lut[row[x]];
}
}
}
}
void finish_item(const VisionConfig& c, Item* it) {
it->patch_dim = c.patch_dim();
it->n_patch = (int64_t)it->grid_t * it->grid_h * it->grid_w;
@@ -389,10 +631,42 @@ void finish_item(const VisionConfig& c, Item* it) {
/* ================================================================== the processor */
int Processor::init(const VisionConfig& cfg,
std::function<std::vector<int32_t>(const std::string&)> encode_text) {
std::function<std::vector<int32_t>(const std::string&)> encode_text,
std::function<int32_t(const std::string&)> token_id) {
if (cfg.patch <= 0 || cfg.temporal <= 0 || cfg.merge <= 0 || cfg.max_patches <= 0)
return RAD_E_INVAL;
cfg_ = cfg;
if (cfg.family == Family::Lfm2) {
/* The markers are named, not numbered, in the config: resolved here, every one, so a
* vocabulary missing one is refused at startup rather than on the first large picture. */
if (!token_id) return RAD_E_INVAL;
cfg_.tok_start = token_id("<|image_start|>");
cfg_.tok_end = token_id("<|image_end|>");
tok_thumbnail_ = token_id("<|img_thumbnail|>");
if (cfg_.tok_start < 0 || cfg_.tok_end < 0 || tok_thumbnail_ < 0) return RAD_E_NOTFOUND;
tok_tiles_.assign((size_t)cfg.max_tiles * cfg.max_tiles, -1);
for (int32_t r = 1; r <= cfg.max_tiles; ++r)
for (int32_t c = 1; r * c <= cfg.max_tiles; ++c) {
const int32_t id = token_id("<|img_row_" + std::to_string(r) + "_col_" +
std::to_string(c) + "|>");
if (id < 0) return RAD_E_NOTFOUND;
tok_tiles_[(size_t)(r - 1) * cfg.max_tiles + (c - 1)] = id;
}
/* A tile and the largest thumbnail are one segment each: of the tower and of a pass. */
const int64_t seg = std::max<int64_t>((int64_t)(cfg.tile / cfg.patch) * (cfg.tile / cfg.patch),
cfg.image_max_pixels / ((int64_t)cfg.patch * cfg.patch));
if (seg > cfg.max_patches || seg > cfg.max_segment_patches) return RAD_E_INVAL;
encode_text_ = std::move(encode_text);
return RAD_OK;
}
if (cfg.family == Family::Gemma4) {
/* A budget is a patch count, and an image is one segment of one pass. */
if ((int64_t)cfg.image_soft_tokens * cfg.merge * cfg.merge > cfg.max_patches ||
(int64_t)cfg.video_soft_tokens * cfg.merge * cfg.merge > cfg.max_patches)
return RAD_E_INVAL;
encode_text_ = std::move(encode_text);
return RAD_OK;
}
/* The largest image the encoder takes in one pass, in pixels: the band's ceiling comes down to
* it, so smart_resize itself keeps every image inside a pass. */
const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch;
@@ -404,8 +678,133 @@ int Processor::init(const VisionConfig& cfg,
return RAD_OK;
}
void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px,
int64_t* oh, int64_t* ow) {
const double f = factor;
int64_t hb = std::max<int64_t>(factor, pyround((double)h / f) * factor);
int64_t wb = std::max<int64_t>(factor, pyround((double)w / f) * factor);
if (hb * wb > max_px) {
const double beta = std::sqrt((double)(h * w) / (double)max_px);
hb = std::max<int64_t>(factor, (int64_t)std::floor((double)h / beta / f) * factor);
wb = std::max<int64_t>(factor, (int64_t)std::floor((double)w / beta / f) * factor);
} else if (hb * wb < min_px) {
const double beta = std::sqrt((double)min_px / (double)(h * w));
hb = (int64_t)std::ceil((double)h * beta / f) * factor;
wb = (int64_t)std::ceil((double)w * beta / f) * factor;
}
*oh = hb;
*ow = wb;
}
bool lfm2_too_large(int64_t h, int64_t w, int32_t patch, int32_t factor, int64_t max_px,
double tolerance) {
const int64_t hb = std::max<int64_t>(patch, pyround((double)h / factor) * factor);
const int64_t wb = std::max<int64_t>(patch, pyround((double)w / factor) * factor);
return (double)(hb * wb) > (double)max_px * tolerance;
}
/* The reference walks the ratios sorted by tile count; within one count it orders them as a
* Python set happens to, which this walks by columns. The two can differ only on an exact tie
* between two grids of one count, both nearest. */
void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
int32_t* cols, int32_t* rows) {
const double aspect = (double)w / (double)h;
double best = INFINITY;
*cols = *rows = 1;
for (int32_t n = min_tiles; n <= max_tiles; ++n)
for (int32_t c = 1; c <= n; ++c) {
if (n % c) continue;
const int32_t r = n / c;
const double diff = std::fabs(aspect - (double)c / (double)r);
if (diff < best) {
best = diff; *cols = c; *rows = r;
} else if (diff == best && (double)(w * h) > 0.5 * tile * tile * (double)n) {
*cols = c; *rows = r;
}
}
}
/* LFM2-VL's image processor (transformers' Lfm2VlImageProcessor), segment by segment: the tiles
* in row-major order, then the thumbnail; within one, patches in merge-block order (each
* merge x merge block's patches consecutive, dy then dx -- which is how the projector's pixel
* unshuffle reads them, so its merge is a view), each patch (y, x, channel). */
int Processor::image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
const int32_t F = c.factor(), P = c.patch, M = c.merge;
int64_t th = 0, tw = 0;
lfm2_size(f.h, f.w, F, c.image_min_pixels, c.image_max_pixels, &th, &tw);
const bool large = lfm2_too_large(f.h, f.w, P, F, c.image_max_pixels, c.max_pixels_tolerance);
int32_t cols = 1, rows = 1;
if (large && !(c.min_tiles == 1 && c.max_tiles == 1))
lfm2_grid(f.h, f.w, c.min_tiles, c.max_tiles, c.tile, &cols, &rows);
const bool tiled = cols * rows > 1;
if (th / P * (tw / P) > std::min(c.max_patches, c.max_segment_patches)) {
if (why) *why = "the picture's aspect ratio needs more patches than one encoder segment holds";
return RAD_E_INVAL;
}
uint16_t lut[3][256];
for (int ch = 0; ch < 3; ++ch)
for (int v = 0; v < 256; ++v)
lut[ch][v] = rad_f32_to_bf16(((float)v - 255.0f * c.mean[ch]) / (255.0f * c.stdv[ch]));
auto it = std::make_shared<Item>();
it->kind = Kind::Image;
it->patch_dim = c.patch_dim();
it->rope_1d = true;
it->expand.push_back(c.tok_start);
/* One segment of `frame`'s gh x gw patches from (x0, y0), its placeholders after `marker`. */
auto append = [&](const Frame& frame, int x0, int y0, int gh, int gw, int32_t marker) {
it->segments.push_back({ gh, gw, it->n_patch });
it->n_patch += (int64_t)gh * gw;
if (marker >= 0) it->expand.push_back(marker);
it->seg_at.push_back((int32_t)it->expand.size());
it->expand.insert(it->expand.end(), (size_t)gh * gw / (M * M), c.tok_image);
const size_t at = it->pixels.size();
it->pixels.resize(at + (size_t)gh * gw * it->patch_dim);
uint16_t* dst = it->pixels.data() + at;
for (int bh = 0; bh < gh / M; ++bh)
for (int bw = 0; bw < gw / M; ++bw)
for (int mh = 0; mh < M; ++mh)
for (int mw = 0; mw < M; ++mw)
for (int y = 0; y < P; ++y) {
const uint8_t* row = frame.rgb.data() +
((size_t)(y0 + (bh * M + mh) * P + y) * frame.w +
x0 + (bw * M + mw) * P) * 3;
for (int x = 0; x < 3 * P; ++x) *dst++ = lut[x % 3][row[x]];
}
};
if (tiled) {
Frame big;
resize_bicubic_torch(f, cols * c.tile, rows * c.tile, &big);
const int g = c.tile / P;
for (int32_t r = 0; r < rows; ++r)
for (int32_t col = 0; col < cols; ++col)
append(big, col * c.tile, r * c.tile, g, g,
tok_tiles_[(size_t)r * c.max_tiles + col]);
}
if (!tiled || c.use_thumbnail) {
Frame small;
resize_bicubic_torch(f, (int32_t)tw, (int32_t)th, &small);
append(small, 0, 0, (int)(th / P), (int)(tw / P), tiled ? tok_thumbnail_ : -1);
}
it->expand.push_back(c.tok_end);
it->n_seg = it->grid_t = (int32_t)it->segments.size();
it->grid_h = it->segments[0].h;
it->grid_w = it->segments[0].w;
it->rows_h = it->grid_h / M;
it->rows_w = it->grid_w / M;
it->seg_rows = it->rows_h * it->rows_w;
if (it->n_seg == 1) it->segments.clear(); /* one segment is the uniform form */
content_key(*it, &it->key_hi, &it->key_lo);
*out = std::move(it);
return RAD_OK;
}
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why);
if (c.family == Family::Lfm2) return image_lfm2(f, out, why);
int64_t h = 0, w = 0;
RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels,
&h, &w, why));
@@ -435,8 +834,80 @@ int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::strin
return RAD_OK;
}
int Processor::image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
std::string* why) const {
const VisionConfig& c = cfg_;
int64_t h = 0, w = 0;
RAD_TRY(gemma4_size(f.h, f.w, c.patch, c.merge, (int64_t)soft * c.merge * c.merge, &h, &w,
why));
Frame r;
const Frame* src = &f;
if (h != f.h || w != f.w) {
resize_bicubic(f, (int32_t)w, (int32_t)h, &r);
src = &r;
}
auto it = std::make_shared<Item>();
it->kind = Kind::Image;
it->grid_t = 1;
it->grid_h = (int32_t)(h / c.patch);
it->grid_w = (int32_t)(w / c.patch);
finish_item(c, it.get());
if (it->n_patch > c.max_patches) {
if (why) *why = "the image's soft-token budget is more patches than one encoder pass holds";
return RAD_E_INVAL;
}
patchify_gemma4(c, { src }, it.get());
content_key(*it, &it->key_hi, &it->key_lo);
it->expand.reserve((size_t)it->seg_rows + 2);
it->expand.push_back(c.tok_start);
it->seg_at.push_back(1);
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image);
it->expand.push_back(c.tok_end);
*out = std::move(it);
return RAD_OK;
}
int Processor::video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
int64_t h = 0, w = 0;
RAD_TRY(gemma4_size(v.frames[0].h, v.frames[0].w, c.patch, c.merge,
(int64_t)c.video_soft_tokens * c.merge * c.merge, &h, &w, why));
auto it = std::make_shared<Item>();
it->kind = Kind::Video;
it->grid_t = (int32_t)v.frames.size();
it->grid_h = (int32_t)(h / c.patch);
it->grid_w = (int32_t)(w / c.patch);
finish_item(c, it.get());
if ((int64_t)it->grid_h * it->grid_w > c.max_patches) {
if (why) *why = "a video frame's soft-token budget is more patches than one encoder pass "
"holds";
return RAD_E_INVAL;
}
std::vector<Frame> resized(v.frames.size());
std::vector<const Frame*> rf;
for (size_t i = 0; i < v.frames.size(); ++i) {
if (v.frames[i].h == h && v.frames[i].w == w) { rf.push_back(&v.frames[i]); continue; }
resize_bicubic(v.frames[i], (int32_t)w, (int32_t)h, &resized[i]);
rf.push_back(&resized[i]);
}
patchify_gemma4(c, rf, it.get());
content_key(*it, &it->key_hi, &it->key_lo);
/* One <boi> placeholders <eoi> run a frame, back to back: the reference's visual-only form
* (add_timestamps off). */
for (int32_t g = 0; g < it->grid_t; ++g) {
it->expand.push_back(c.tok_start);
it->seg_at.push_back((int32_t)it->expand.size());
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_video);
it->expand.push_back(c.tok_end);
}
*out = std::move(it);
return RAD_OK;
}
int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
if (c.family == Family::Gemma4) return video_gemma4(v, out, why);
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
/* The frames and their indices, padded to whole temporal groups by repeating the last. A clip
* shorter than one group is padded the same way, so a single-frame video is one group. */
@@ -516,29 +987,319 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
return RAD_OK;
}
int Processor::image(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
std::string* why) const {
int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
std::shared_ptr<Item>* out, std::string* why, int64_t max_pixels) const {
if (image_tokens != 0) {
if (cfg_.family != Family::Gemma4) {
if (why) *why = "this model's processor sizes an image by its pixels, not by a token "
"budget";
return RAD_E_UNSUPPORTED;
}
if (!soft_budget_ok(image_tokens) ||
(int64_t)image_tokens * cfg_.merge * cfg_.merge > cfg_.max_patches) {
if (why) *why = "the image token budget must be one of 70, 140, 280, 560, 1120 and "
"fit one encoder pass (" + std::to_string(cfg_.max_patches) +
" patches)";
return RAD_E_INVAL;
}
}
Frame f;
RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why));
if (max_pixels > 0 && (int64_t)f.w * f.h > max_pixels) {
Frame capped;
cap_area(f, max_pixels, &capped);
f = std::move(capped);
}
if (cfg_.family == Family::Gemma4)
return image_gemma4(f, image_tokens ? image_tokens : cfg_.image_soft_tokens, out, why);
return image_from(f, out, why);
}
namespace {
struct SampleArgs { double fps; int32_t lo, hi; };
struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; };
std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
const SampleArgs* a = static_cast<const SampleArgs*>(user);
return sample_frames(info, a->fps, a->lo, a->hi);
return a->gemma4 ? sample_frames_gemma4(info, a->fps, a->hi)
: sample_frames(info, a->fps, a->lo, a->hi);
}
} /* namespace */
int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
std::string* why) const {
if (cfg_.family == Family::Lfm2) {
if (why) *why = "this model's processor takes pictures, not video";
return RAD_E_UNSUPPORTED;
}
Video v;
const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames };
const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames,
cfg_.family == Family::Gemma4 };
RAD_TRY(decode_video(bytes, n, sample_cb, &a, cfg_.max_source_pixels, &v, why));
return video_from(v, out, why);
}
/* ================================================================== audio */
/* A list a container flattened from a JSON array ("1 2 3"), or nothing when it is absent or null. */
static std::vector<double> read_list(const RadModelMeta& m, const char* key) {
std::vector<double> v;
const char* s = rad_meta_gets(&m, key, nullptr);
if (!s || !*s) return v;
std::istringstream is(s);
double x;
while (is >> x) v.push_back(x);
return v;
}
int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) {
const char* mt = rad_meta_gets(&m, "audio_config.model_type", "");
if (!mt || std::strcmp(mt, "gemma4_audio")) {
if (why) *why = "the container states no audio tower this processor knows (audio_config."
"model_type gemma4_audio)";
return RAD_E_NOTFOUND;
}
rate = (int32_t)rad_meta_geti(&m, "preprocessor.sampling_rate", 16000);
frame_length = (int32_t)rad_meta_geti(&m, "preprocessor.frame_length", 320);
hop = (int32_t)rad_meta_geti(&m, "preprocessor.hop_length", 160);
n_mels = (int32_t)rad_meta_geti(&m, "preprocessor.feature_size", 128);
fft = (int32_t)rad_meta_geti(&m, "preprocessor.fft_length", 0);
if (fft <= 0) {
fft = 1;
while (fft < frame_length) fft *= 2;
}
if (rad_meta_geti(&m, "preprocessor.fft_overdrive", 0)) fft *= 2;
min_freq = rad_meta_getf(&m, "preprocessor.min_frequency", 0.0);
max_freq = rad_meta_getf(&m, "preprocessor.max_frequency", 8000.0);
mel_floor = rad_meta_getf(&m, "preprocessor.mel_floor", 1e-3);
preemphasis = rad_meta_getf(&m, "preprocessor.preemphasis", 0.0);
preemphasis_htk = rad_meta_geti(&m, "preprocessor.preemphasis_htk_flavor", 1) != 0;
input_scale = rad_meta_getf(&m, "preprocessor.input_scale_factor", 1.0);
bin_mean = read_list(m, "preprocessor.per_bin_mean");
bin_std = read_list(m, "preprocessor.per_bin_stddev");
max_samples = 480000;
tok_audio = (int32_t)rad_meta_geti(&m, "audio_token_id", -1);
tok_start = (int32_t)rad_meta_geti(&m, "boa_token_id", -1);
tok_end = (int32_t)rad_meta_geti(&m, "eoa_token_id", rad_meta_geti(&m, "eoa_token_index", -1));
/* DITHER IS NOISE: the reference adds Gaussian noise of this deviation to every sample, a
* different draw each call, and no fixed input reproduces it. */
if (rad_meta_getf(&m, "preprocessor.dither", 0.0) != 0.0) {
if (why) *why = "the feature extractor dithers its input (preprocessor.dither), which no "
"deterministic front end reproduces";
return RAD_E_UNSUPPORTED;
}
if (rate <= 0 || frame_length <= 1 || hop <= 0 || n_mels <= 0 || fft < frame_length ||
!(max_freq > min_freq) || !(mel_floor > 0.0) || tok_audio < 0 || tok_start < 0 ||
tok_end < 0 || (!bin_mean.empty() && (int64_t)bin_mean.size() != n_mels) ||
(!bin_std.empty() && (int64_t)bin_std.size() != n_mels)) {
if (why) *why = "the container's audio feature configuration is incomplete or "
"inconsistent (rate, frame and hop lengths, mel bins, frequencies, "
"audio_token_id, boa_token_id, eoa_token_id)";
return RAD_E_INVAL;
}
return RAD_OK;
}
int64_t AudioConfig::real_frames(int64_t n) const {
/* Frame i's last sample is (frame_length / 2 zeros) + i * hop + frame_length, and it is real
* when that is inside the clip: i * hop + frame_length < frame_length / 2 + n. */
const int64_t room = n + frame_length / 2 - frame_length - 1;
return room < 0 ? 0 : room / hop + 1;
}
namespace {
/* An in-place radix-2 complex FFT, n a power of two: the frame's real spectrum in double, as the
* reference's numpy rfft computes it. */
void fft_inplace(std::vector<double>& re, std::vector<double>& im,
const std::vector<double>& tw_re, const std::vector<double>& tw_im,
const std::vector<int32_t>& brev) {
const size_t n = re.size();
for (size_t i = 1; i < n; ++i) {
const size_t j = (size_t)brev[i];
if (i < j) { std::swap(re[i], re[j]); std::swap(im[i], im[j]); }
}
for (size_t len = 2; len <= n; len <<= 1) {
const size_t step = n / len; /* stage len's k-th twiddle is the table's k * step */
for (size_t i = 0; i < n; i += len)
for (size_t k = 0; k < len / 2; ++k) {
const double wr = tw_re[k * step], wi = tw_im[k * step];
const size_t a = i + k, b = i + k + len / 2;
const double xr = re[b] * wr - im[b] * wi, xi = re[b] * wi + im[b] * wr;
re[b] = re[a] - xr; im[b] = im[a] - xi;
re[a] += xr; im[a] += xi;
}
}
}
/* numpy.linspace's values: start + i * step, the last exactly `stop`. */
std::vector<double> linspace(double a, double b, int64_t n) {
std::vector<double> v((size_t)n);
const double step = n > 1 ? (b - a) / (double)(n - 1) : 0.0;
for (int64_t i = 0; i < n; ++i) v[(size_t)i] = a + (double)i * step;
if (n > 1) v[(size_t)n - 1] = b;
return v;
}
} /* namespace */
int Processor::init_audio(const AudioConfig& cfg) {
if (cfg.merge <= 0 || cfg.max_frames <= 0 || cfg.max_frames % cfg.merge) return RAD_E_INVAL;
acfg_ = cfg;
/* np.hanning(frame_length + 1)[:-1], the periodic window, stored as float32. */
hann_.resize((size_t)cfg.frame_length);
for (int32_t i = 0; i < cfg.frame_length; ++i)
hann_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * M_PI * (double)i /
(double)cfg.frame_length));
/* transformers' mel_filter_bank(norm=None, mel_scale="htk"): triangles between consecutive
* mel points, in Hz, over the FFT bins' frequencies. */
const int64_t nb = cfg.fft / 2 + 1, nm = cfg.n_mels;
auto hz2mel = [](double f) { return 2595.0 * std::log10(1.0 + f / 700.0); };
auto mel2hz = [](double m) { return 700.0 * (std::pow(10.0, m / 2595.0) - 1.0); };
const std::vector<double> fft_f = linspace(0.0, (double)(cfg.rate / 2), nb);
std::vector<double> filt = linspace(hz2mel(cfg.min_freq), hz2mel(cfg.max_freq), nm + 2);
for (double& f : filt) f = mel2hz(f);
mel_.assign((size_t)(nb * nm), 0.0);
mel_lo_.assign((size_t)nm, 0);
mel_hi_.assign((size_t)nm, 0);
for (int64_t i = 0; i < nm; ++i) {
int32_t lo = -1, hi = 0;
for (int64_t k = 0; k < nb; ++k) {
const double down = -(filt[(size_t)i] - fft_f[(size_t)k]) /
(filt[(size_t)i + 1] - filt[(size_t)i]);
const double up = (filt[(size_t)i + 2] - fft_f[(size_t)k]) /
(filt[(size_t)i + 2] - filt[(size_t)i + 1]);
const double w = std::max(0.0, std::min(down, up));
mel_[(size_t)(i * nb + k)] = w;
if (w != 0.0) { if (lo < 0) lo = (int32_t)k; hi = (int32_t)k + 1; }
}
/* A triangle covers a few bins; the sum skips the zeros, which add nothing to it. */
mel_lo_[(size_t)i] = lo < 0 ? 0 : lo;
mel_hi_[(size_t)i] = hi;
}
/* The FFT's twiddles, once: a butterfly that evaluates its own sin and cos makes the
* transform cost a 30 s clip over 100 ms. */
brev_.assign((size_t)cfg.fft, 0);
for (int32_t i = 1, j = 0; i < cfg.fft; ++i) {
int32_t bit = cfg.fft >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
brev_[(size_t)i] = j;
}
tw_re_.resize((size_t)cfg.fft / 2);
tw_im_.resize((size_t)cfg.fft / 2);
for (int32_t k = 0; k < cfg.fft / 2; ++k) {
const double ang = -2.0 * M_PI * (double)k / (double)cfg.fft;
tw_re_[(size_t)k] = std::cos(ang);
tw_im_[(size_t)k] = std::sin(ang);
}
audio_on_ = true;
return RAD_OK;
}
int Processor::audio_from(const std::vector<float>& samples, std::shared_ptr<Item>* out,
std::string* why) const {
if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
const AudioConfig& c = acfg_;
const int64_t n = std::min<int64_t>((int64_t)samples.size(), c.max_samples);
const int64_t real = c.real_frames(n);
const int64_t rows = (real + c.merge - 1) / c.merge;
const int64_t frames = rows * c.merge;
if (frames > c.max_frames) {
if (why) *why = "the clip is more frames than one audio encoder pass holds";
return RAD_E_INVAL;
}
auto it = std::make_shared<Item>();
it->kind = Kind::Audio;
it->grid_t = 1;
it->grid_h = (int32_t)frames;
it->grid_w = 1;
it->patch_dim = c.n_mels;
it->n_patch = frames;
it->valid = (int32_t)real;
it->rows_h = (int32_t)rows;
it->rows_w = 1;
it->seg_rows = (int32_t)rows;
it->n_seg = rows > 0 ? 1 : 0;
it->pixels.assign((size_t)(frames * c.n_mels), 0);
const int64_t pad = c.frame_length / 2;
const int64_t nb = c.fft / 2 + 1;
std::vector<double> re((size_t)c.fft), im((size_t)c.fft), mag((size_t)nb);
std::vector<float> fr((size_t)c.frame_length + 1);
auto sample = [&](int64_t p) -> float { /* the zero-led clip, zero past its end */
const int64_t q = p - pad;
return q >= 0 && q < n ? samples[(size_t)q] * (float)c.input_scale : 0.0f;
};
/* Frame i's windowed samples into dst, zero past the frame. */
auto window = [&](int64_t i, double* dst) {
for (int32_t j = 0; j <= c.frame_length; ++j) fr[(size_t)j] = sample(i * c.hop + j);
for (int32_t j = 0; j < c.frame_length; ++j) {
float v;
if (c.preemphasis > 0.0) {
const float pe = (float)c.preemphasis;
v = c.preemphasis_htk ? (j == 0 ? fr[0] * (1.0f - pe) : fr[(size_t)j] - pe * fr[(size_t)j - 1])
: fr[(size_t)j + 1] - pe * fr[(size_t)j];
} else {
v = fr[(size_t)j];
}
dst[j] = (double)(v * hann_[(size_t)j]); /* the product in float32 */
}
for (int32_t j = c.frame_length; j < c.fft; ++j) dst[j] = 0.0;
};
/* Frame i's mel bins from its magnitudes. */
auto emit = [&](int64_t i, const double* m) {
uint16_t* dst = it->pixels.data() + i * c.n_mels;
for (int32_t b = 0; b < c.n_mels; ++b) {
double s = 0.0;
const double* w = mel_.data() + (size_t)b * nb;
for (int32_t k = mel_lo_[(size_t)b]; k < mel_hi_[(size_t)b]; ++k) s += m[k] * w[k];
double v = std::log(s + c.mel_floor);
if (!c.bin_mean.empty()) v -= c.bin_mean[(size_t)b];
if (!c.bin_std.empty()) v /= c.bin_std[(size_t)b];
dst[b] = rad_f32_to_bf16((float)v);
}
};
/* TWO REAL FRAMES A COMPLEX TRANSFORM: frame a in the real part, frame b in the imaginary,
* and the two spectra separate by symmetry -- A[k] = (Z[k] + conj Z[n-k]) / 2 and
* B[k] = (Z[k] - conj Z[n-k]) / 2i. Half the transforms; the magnitudes agree with one
* transform a frame to a few ulps of double. |X| is sqrt(re^2 + im^2), within an ulp of
* numpy's hypot and far below the float32 the features are rounded to. */
std::vector<double> mag2((size_t)nb);
const int64_t N = c.fft;
for (int64_t i = 0; i < real; i += 2) {
const bool pair = i + 1 < real;
window(i, re.data());
if (pair) window(i + 1, im.data());
else std::fill(im.begin(), im.end(), 0.0);
fft_inplace(re, im, tw_re_, tw_im_, brev_);
for (int64_t k = 0; k < nb; ++k) {
const size_t a = (size_t)k, b = k ? (size_t)(N - k) : 0;
const double ar = 0.5 * (re[a] + re[b]), ai = 0.5 * (im[a] - im[b]);
const double br = 0.5 * (im[a] + im[b]), bi = -0.5 * (re[a] - re[b]);
mag[a] = std::sqrt(ar * ar + ai * ai);
mag2[a] = std::sqrt(br * br + bi * bi);
}
emit(i, mag.data());
if (pair) emit(i + 1, mag2.data());
}
content_key(*it, &it->key_hi, &it->key_lo);
it->expand.push_back(c.tok_start);
it->seg_at.push_back(1);
it->expand.insert(it->expand.end(), (size_t)rows, c.tok_audio);
it->expand.push_back(c.tok_end);
/* A clip too short for one real frame is <boa><eoa> and nothing to encode. */
if (rows == 0) it->encoded = true;
*out = std::move(it);
return RAD_OK;
}
int Processor::audio(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
std::string* why) const {
if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
std::vector<float> s;
RAD_TRY(decode_audio(bytes, n, acfg_.rate, acfg_.max_samples, &s, why));
return audio_from(s, out, why);
}
/* ================================================================== rotary layout */
void PromptMedia::layout() {
@@ -547,19 +1308,24 @@ void PromptMedia::layout() {
for (size_t pi = 0; pi < items.size(); ++pi) {
const Placed& p = items[pi];
const Item& it = *p.item;
const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1;
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s];
pos += run_tok - tok; /* the text in front of the run counts up */
const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m;
const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m;
RopeLayout::Run r;
r.tok = (int32_t)run_tok;
r.n = it.seg_rows;
r.w = it.rows_w;
r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s));
r.w = rw;
r.base = (int32_t)pos;
pos += std::max(it.rows_h, it.rows_w);
tok = run_tok + it.seg_rows;
r.flat = it.rope_1d;
/* A grid advances the rotary by its longer side; a 1-D run by its length. */
pos += it.rope_1d ? r.n : std::max(rh, rw);
tok = run_tok + r.n;
r.shift = (int32_t)(pos - tok);
r.item = (int32_t)pi;
r.row0 = s * it.seg_rows;
r.row0 = (int32_t)it.row_at(s);
rope.runs.push_back(r);
}
}
+147 -6
View File
@@ -37,10 +37,33 @@ struct RadModelMeta;
namespace rad {
namespace mm {
enum class Kind { Image, Video };
enum class Kind { Image, Video, Audio };
/* THE PROCESSOR FAMILY, from the container's vision_config.model_type. The two differ in how a
* picture is sized, what a patch value is, and how a video is sampled and spelled in the prompt;
* the Item they produce and everything after it is shared.
*
* QwenVL smart_resize into a pixel band; patches (channel, frame, y, x) normalised by the
* configured mean and deviation; videos in temporal groups, each after a "<T seconds>".
* Gemma4 the largest size whose sides are multiples of patch * pooling and whose patch count
* fits the soft-token budget (budget * pooling^2), aspect ratio kept; patches (y, x,
* channel) as 2 * (u / 255) - 1, the reference model's own input scaling; a video is
* frames sampled at `fps` (at most `max_frames`, thinned evenly), each its own segment
* at the per-frame budget, each spelled <boi> placeholders <eoi> with no timestamp.
* Lfm2 LFM2-VL's: a picture within its token budget (times a tolerance) is resized whole --
* sides multiples of patch * merge, pixels within the budget's band -- and one past it
* is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its
* own, followed by the whole picture at the budgeted size as a thumbnail. Patches
* (y, x, channel) normalised by the mean and deviation, resized with torchvision's
* fixed-point bicubic; images only, and the tokens rotate at their positions. */
enum class Family { QwenVL, Gemma4, Lfm2 };
struct VisionConfig {
Family family = Family::QwenVL;
int32_t patch = 0, temporal = 0, merge = 0;
/* Gemma4: soft tokens (output rows) an image, and a video frame, may take. One of 70, 140,
* 280, 560, 1120 -- the budgets the model was trained at. */
int32_t image_soft_tokens = 0, video_soft_tokens = 0;
int64_t image_min_pixels = 0, image_max_pixels = 0;
int64_t video_min_pixels = 0, video_max_pixels = 0;
double fps = 2.0;
@@ -52,6 +75,11 @@ struct VisionConfig {
float mean[3] = { 0.5f, 0.5f, 0.5f };
float stdv[3] = { 0.5f, 0.5f, 0.5f };
int32_t tok_image = -1, tok_video = -1, tok_start = -1, tok_end = -1;
/* Lfm2: the tiling (see Family). `max_segment_patches` is the tower's longest segment. */
int32_t min_tiles = 0, max_tiles = 0, tile = 0;
bool use_thumbnail = false;
double max_pixels_tolerance = 0.0;
int64_t max_segment_patches = 0;
/* THE DEPLOYMENT'S BOUNDS, not the checkpoint's. `max_patches` is the encoder's pass size: an
* image is one segment and a segment is never split, so no image may resize past it, and the
@@ -75,6 +103,37 @@ struct VisionConfig {
int from_meta(const RadModelMeta& m, std::string* why);
};
/* WHAT AN AUDIO CLIP BECOMES: Gemma 4's feature extractor (Gemma4AudioFeatureExtractor), read
* from the container's `preprocessor.*` (the checkpoint's preprocessor_config.json) and its
* audio_config. The samples are mono at `rate`, cut at `max_samples`; `frame_length / 2` zeros go
* in front; frame i is samples [i * hop, i * hop + frame_length) of that, pre-emphasised when the
* config says so, times a periodic Hann window, through a `fft`-point real FFT; its magnitudes go
* through an HTK mel bank (no area normalisation) and log(x + mel_floor), optionally standardised
* per bin. A frame is real when its last sample is a real one -- the reference's mask -- so a clip
* of n samples has floor((n - frame_length / 2 - 1) / hop) + 1 real frames and the reference's
* output keeps ceil(real / merge) rows of it: that many placeholders, between <boa> and <eoa>.
* The staged patches are the real frames then zero frames to a whole number of rows -- equal, for
* every row the reference keeps, to the frames past the end the reference zeroes. */
struct AudioConfig {
int32_t rate = 0, frame_length = 0, hop = 0, fft = 0, n_mels = 0;
double min_freq = 0.0, max_freq = 0.0, mel_floor = 0.0;
double preemphasis = 0.0, input_scale = 1.0;
bool preemphasis_htk = true;
std::vector<double> bin_mean, bin_std; /* empty: no per-bin standardisation */
/* The longest clip in samples: Gemma 4's extractor truncates at 480000 (30 s at 16 kHz). */
int64_t max_samples = 0;
int32_t tok_audio = -1, tok_start = -1, tok_end = -1;
/* THE ENCODER'S: frames an output row, and the most frames a pass carries. */
int32_t merge = 0;
int64_t max_frames = 0;
/* Read from the container; refuses one that states no Gemma 4 audio tower. */
int from_meta(const RadModelMeta& m, std::string* why);
/* The real frames of an n-sample clip. */
int64_t real_frames(int64_t n_samples) const;
};
/* One media part after processing: its patches, its place in the prompt's token stream, and --
* once the encoder has run -- its rows. Shared between the request that owns it and the engine
* thread that encodes it; the engine writes `embd` once and nothing reads it before then. */
@@ -88,7 +147,33 @@ struct Item {
/* The encoder's output: n_seg segments of seg_rows rows, one segment per temporal group.
* `rows_w` is a segment's width in output rows, which is where its rotary grid wraps. */
int32_t n_seg = 0, seg_rows = 0, rows_w = 0, rows_h = 0;
int64_t n_rows() const { return (int64_t)n_seg * seg_rows; }
/* An audio clip's REAL feature frames; the rest of its `grid_h` are the zero frames that make
* it whole output rows. 0 for a picture or a video. */
int32_t valid = 0;
/* SEGMENTS OF THEIR OWN SIZE, when an item's segments differ -- an LFM2-VL picture is its
* tiles and a thumbnail -- each `h` x `w` patches from patch `patch0` on. Empty, every segment
* is grid_h x grid_w (a picture, a video's temporal groups, an audio clip). The accessors
* below are the only way the rest of the engine reads a segment, so both forms look alike. */
struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; };
std::vector<Segment> segments;
/* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not
* on the grid the Qwen-VL family's M-RoPE lays out (RopeLayout). */
bool rope_1d = false;
int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; }
int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; }
/* Segment s's first patch and first output row; s == n_seg is the end of the item. */
int64_t patch_at(int32_t s) const {
if (segments.empty()) return (int64_t)s * grid_h * grid_w;
return s >= n_seg ? n_patch : segments[(size_t)s].patch0;
}
int64_t row_at(int32_t s) const {
if (segments.empty()) return (int64_t)s * seg_rows;
const int64_t m = rows_h > 0 ? grid_h / rows_h : 1;
return patch_at(s) / (m * m);
}
int64_t n_rows() const { return row_at(n_seg); }
/* THE TOKENS THAT REPLACE THE MEDIA MARKER, and where in them each segment's run of
* placeholders starts. Placeholders are the checkpoint's own pad ids, not an arbitrary one:
@@ -124,6 +209,7 @@ struct RopeLayout {
int32_t shift = 0; /* rotary minus token index for the text AFTER the run */
int32_t item = 0; /* which of PromptMedia::items the run belongs to */
int32_t row0 = 0; /* the item's encoder row that its first token takes */
bool flat = false; /* Item::rope_1d: the run's tokens rotate at their positions */
};
std::vector<Run> runs; /* ascending */
@@ -144,7 +230,7 @@ struct RopeLayout {
const Run* r = last_at(i);
if (!r) { out[0] = out[1] = out[2] = (int32_t)i; return; }
const int64_t k = i - r->tok;
if (k < r->n) {
if (k < r->n && !r->flat) {
out[0] = r->base;
out[1] = r->base + (int32_t)(k / r->w);
out[2] = r->base + (int32_t)(k % r->w);
@@ -180,19 +266,50 @@ struct PromptMedia {
class Processor {
public:
/* `encode_text` tokenises the timestamp text between a video's groups: plain text, no
* special tokens added and none parsed. */
int init(const VisionConfig& cfg, std::function<std::vector<int32_t>(const std::string&)> encode_text);
* special tokens added and none parsed. `token_id` is the id of the vocabulary entry spelled
* exactly so, or -1: how a family whose markers the config does not number (LFM2-VL's tile
* and thumbnail markers) finds them. */
int init(const VisionConfig& cfg, std::function<std::vector<int32_t>(const std::string&)> encode_text,
std::function<int32_t(const std::string&)> token_id = {});
const VisionConfig& config() const { return cfg_; }
int image(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
/* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a
* processor that sizes images by pixels refuses a non-zero one. `max_pixels`, when set, first
* scales a larger picture down to that area (PIL's bicubic), as a caller's own pipeline may. */
int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr<Item>* out,
std::string* why, int64_t max_pixels = 0) const;
int video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
/* The pieces, exposed for the test suite: an already-decoded picture or frame list. */
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
/* AUDIO, when the program declared an audio encoder: `merge` and `max_frames` are its. */
int init_audio(const AudioConfig& cfg);
bool has_audio() const { return audio_on_; }
const AudioConfig& audio_config() const { return acfg_; }
int audio(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
/* ...and from samples already decoded (mono at the configured rate), for the test suite. */
int audio_from(const std::vector<float>& samples, std::shared_ptr<Item>* out,
std::string* why) const;
private:
int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
std::string* why) const;
int image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
/* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */
int32_t tok_thumbnail_ = -1;
std::vector<int32_t> tok_tiles_;
int video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
VisionConfig cfg_{};
AudioConfig acfg_{};
bool audio_on_ = false;
std::vector<float> hann_; /* the window, float32 as the reference stores it */
std::vector<double> mel_; /* [n_mels, fft/2 + 1]: filter b's weight on bin k */
std::vector<int32_t> mel_lo_, mel_hi_; /* filter b's nonzero bins, [lo, hi) */
std::vector<double> tw_re_, tw_im_; /* exp(-2 pi i k / fft), k < fft/2 */
std::vector<int32_t> brev_; /* the FFT's bit-reversal permutation */
std::function<std::vector<int32_t>(const std::string&)> encode_text_;
};
@@ -205,9 +322,33 @@ int smart_resize_video(int64_t t, int64_t h, int64_t w, int32_t tfactor, int32_t
/* Which frames a video keeps. */
std::vector<int64_t> sample_frames(const VideoInfo& info, double fps, int32_t min_frames,
int32_t max_frames);
/* ...the Gemma 4 rule: one frame each 1 / fps seconds, thinned evenly to `max_frames`. */
std::vector<int64_t> sample_frames_gemma4(const VideoInfo& info, double fps, int32_t max_frames);
/* Gemma 4's target size: the largest (h, w), both multiples of `side`, whose patch count stays
* within `max_patches`, aspect ratio kept (get_aspect_ratio_preserving_size). */
int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches,
int64_t* oh, int64_t* ow, std::string* why);
/* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a
* horizontal pass into an 8-bit intermediate and then a vertical one. */
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out);
/* ...and torchvision's on a uint8 tensor (ATen's CPU kernel), which is the same filter with the
* coefficients at the most precision 16 bits hold, chosen per axis, rather than PIL's 22. */
void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out);
/* LFM2-VL's smart_resize: (height, width) to multiples of `factor`, at least one each, pixels
* within [min_px, max_px] where the rounding left them outside. */
void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px,
int64_t* oh, int64_t* ow);
/* LFM2-VL's test for a picture to tile: its sides rounded to whole merged patches cover more than
* `max_px` times `tolerance` pixels. */
bool lfm2_too_large(int64_t h, int64_t w, int32_t patch, int32_t factor, int64_t max_px,
double tolerance);
/* A picture over `max_pixels` scaled down to that area with PIL's bicubic, sides truncated; any
* other picture as it is. */
void cap_area(const Frame& in, int64_t max_pixels, Frame* out);
/* LFM2-VL's tile grid for a w x h picture: (columns, rows) of the min..max-tile ratio nearest its
* aspect, the larger grid of two equally near when the picture fills over half of it. */
void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
int32_t* cols, int32_t* rows);
} /* namespace mm */
} /* namespace rad */
+20 -12
View File
@@ -139,11 +139,12 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
return RAD_OK;
}
enabled_ = true;
RAD_INFO("heat engine: %lld movable units, %d move%s a dispatch, "
"decay %.3f hysteresis %.2f min-gain %.2f",
(long long)movable, params_.moves_per_dispatch,
params_.moves_per_dispatch == 1 ? "" : "s",
(double)params_.decay, (double)params_.hysteresis, (double)params_.min_gain);
RAD_INFO("heat engine: %lld movable units, %d move%s a step, "
"decay %.3f hysteresis %.2f min-gain %.2f credit cap %.0f",
(long long)movable, params_.moves_per_step,
params_.moves_per_step == 1 ? "" : "s",
(double)params_.decay, (double)params_.hysteresis, (double)params_.min_gain,
(double)params_.credit_cap);
return RAD_OK;
}
@@ -206,6 +207,13 @@ void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert,
* (prefetch()), which makes this a no-op. */
prefetch(counts, n);
/* The credit cap (HeatParams::credit_cap) scales the whole histogram, so its experts keep
* their order. The pricing below counts every pass whatever the credit is. */
int64_t total = 0;
for (int32_t j = 0; j < n; ++j) total += counts[j] > 0 ? counts[j] : 0;
const float cap = params_.credit_cap;
const float w = cap > 0.0f && (float)total > cap ? weight * cap / (float)total : weight;
float* __restrict h = heat_.data() + lo;
for (int32_t j = 0; j < len; ++j) h[j] *= d;
@@ -219,7 +227,7 @@ void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert,
const int32_t c = counts[j];
const size_t q = (size_t)(lo + j);
const float was = h[j];
const float x = was + (float)c * weight;
const float x = was + (float)c * w;
h[j] = x;
routed += routed_as_[q] != 0;
resident += routed_as_[q] == 2;
@@ -380,12 +388,12 @@ bool HeatEngine::pick(Swap* out) const {
return true;
}
/* THE WHOLE DISPATCH'S PROPOSALS FROM ONE PASS. Marking a pair busy changes neither a unit's heat
* nor any layer's resident count, so the m-th pair repeated pick() calls would return is simply the
* m-th entry at each end of the same ranking. One pass keeps the `moves_per_dispatch` best of each
/* THE WHOLE STEP'S PROPOSALS FROM ONE PASS. Marking a pair busy changes neither a unit's heat nor
* any layer's resident count, so the m-th pair repeated pick() calls would return is simply the
* m-th entry at each end of the same ranking. One pass keeps the `moves_per_step` best of each
* end; the proposals, and the counters that say why the list stopped, are the ones the repeated
* picks produce. This runs before every pass a rank issues -- draft passes included, where the
* device waits for the issue -- so a scan per proposed move would be most of its cost. */
* picks produce. This runs once a step on the thread that issues the next one, and the budget is
* dozens of swaps, so a scan per proposed move would be most of its cost. */
namespace {
using Ranked = HeatRanked;
/* Hotter first, then the layer with fewer residents, then the lower index. */
@@ -414,7 +422,7 @@ int HeatEngine::step(std::vector<Swap>* out) {
if (!out) return RAD_E_INVAL;
out->clear();
if (!enabled_) return RAD_OK;
const int k = params_.moves_per_dispatch;
const int k = params_.moves_per_step;
if (k <= 0) return RAD_OK;
/* THE BEST PAIR FROM THE LAYERS' ENDS FIRST. If it fails the guard every pair does -- the
+48 -33
View File
@@ -35,14 +35,15 @@
* ---- WHY LFU-WITH-DECAY AND NOT SOMETHING CLEVERER --------------------------------------------
*
* Replaying real routing traces against cache policies settles the shape of this. Runtime
* placement beats static profile placement by a wide margin, so it is worth building; LFU-with-
* decay and LRU score the same, so the decay constant is not where the wins are and this does not
* need to be subtle. Belady is a few points of hit rate above both -- but an oracle restricted to
* a disjoint sample of the future keeps most of that gap, so the remainder is knowledge of the
* realised future and is not reachable. Of what is left, no statistic of PAST USE captures any of
* it: an expert never selected has count zero, no age and no history, and most of the space is in
* that state. The router's own gate value does separate those cases, so a scorer built on it is
* the one direction here that measurement has not refuted.
* placement beats static profile placement by a wide margin, so it is worth building. What bounds
* it is the MOVE RATE, not the ranking: held to the same swaps a step at the same step boundaries,
* an oracle that knows every future routing scores no better than this policy (78.0% against 78.4%
* at 64 swaps a step, Qwen3.8-Flash-Next TP1 with 40% of the experts resident). The unrestricted
* Belady figure is far higher -- 92% on the same trace -- because it admits every miss the moment
* it happens, and a miss admitted here is a second copy of bytes the GEMM has just streamed. So
* the decay constant and the guards are not where the wins are, and this does not need to be
* subtle; the budget (RAD_PLACE_MOVES_PER_STEP), the slots behind it, and keeping a prompt's
* routing from swamping the answer's (HeatParams::credit_cap) are.
*/
#pragma once
#include "planner.h"
@@ -53,14 +54,15 @@
namespace rad {
struct HeatParams {
/* Applied to a layer's whole plane each time that layer is dispatched. Every layer is
* dispatched exactly once per forward, so all planes decay in lockstep and heats stay
* comparable ACROSS layers -- which the global ranking below depends on.
/* Applied to a layer's whole plane each time that layer's histogram is credited. Every layer is
* credited once a step, so all planes decay in lockstep and heats stay comparable ACROSS
* layers -- which the global ranking below depends on.
*
* 0.98 is a half-life of a few dozen dispatches: long enough to survive a paragraph, short
* enough to follow a change of subject. Nearby values are not distinguishable from each other
* above the run-to-run spread, which is what the offline replay predicts. */
float decay = 0.98f;
* 0.95 is a half-life of about fourteen steps. At 64 swaps a step the replay is flat from 0.8
* to 0.95 (77.96% to 78.37%) and falls off above it -- 77.1% at 0.98, 74.2% at 0.99 -- because
* a heat that remembers longer ranks the experts a conversation has moved past above the ones
* it routes to now. */
float decay = 0.95f;
/* Promote only when the candidate beats the victim by this ratio. Without it the two ends of
* the ranking trade places on noise and the engine spends the whole link on churn that
@@ -79,27 +81,40 @@ struct HeatParams {
* MISS, and a miss is a shard streamed over the same link on the same budget. A tighter bar
* then gives up hit rate and buys no traffic back.
*
* The exchange rate behind the value: the two link directions share one budget, so
* a demotion costs about what a promotion does, and a swap therefore has to repay about 1.4
* future hits rather than the 0.74 a half-price demotion would imply. */
* What a swap costs is its promotion. The link is close to full duplex -- on an R9700, 28.5
* GB/s up and 25.0 down at once, against 28.8 up alone -- so a demotion's copy rides the idle
* direction, while a promotion shares the upstream one with every miss the GEMM streams. At
* the default budget lower values replay within 0.2 points of hit rate and promote a fifth
* more. */
float min_gain = 1.5f;
/* A BOUNDED MOVE BUDGET PER LAYER DISPATCH. The apparent risk is that a high budget makes the
* mover compete with the tier it is trying to shrink -- a promotion and a streamed miss are
* the same bytes over the same link. At this scale that does not bind: a larger budget pays
* even though it moves considerably more bytes, because converging sooner is worth more than
* the traffic costs. The benefit then SATURATES, and this sits where the knob stops mattering
* rather than at the largest value that still helps. Past that point the guard, not the
* budget, is what declines the extra opportunities -- so raising this alone is worth nothing
* until min_gain moves with it.
/* A BOUNDED MOVE BUDGET PER STEP: step() is called once a step, after every layer's histogram
* has been credited, and proposes at most this many swaps a slab class. The value and why it
* is that are at RAD_PLACE_MOVES_PER_STEP, which also sizes the free slots a swap lands in
* (the shadow and turnover slots); a budget raised here without them is spent on
* `starved_slab`.
*
* The apparent risk is that a high budget makes the mover compete with the tier it is trying
* to shrink -- a promotion and a streamed miss are the same bytes over the same link. At this
* scale that does not bind: each swap moves an expert the ranking says will be read again
* soon, and the misses it saves are many times its own bytes.
*
* IT IS A BUDGET PER SLAB CLASS. A rank holding an uneven slice of every expert has two expert
* classes -- the wider slice of one parity's experts and the narrower slice of the other's --
* each about half a whole expert, and a budget shared between them would move half the bytes
* a dispatch that whole experts do: residency would converge half as fast, and a fresh server
* would run about 2% slower for its first minute. Per class, the two together move about as
* many whole experts as one class of whole experts does. */
int moves_per_dispatch = 8;
* a step that whole experts do: residency would converge half as fast. Per class, the two
* together move about as many whole experts as one class of whole experts does. */
int moves_per_step = RAD_PLACE_MOVES_PER_STEP;
/* THE MOST ONE HISTOGRAM CREDITS, in selections: a histogram that routed more is credited
* at this total, each expert in proportion to its count. A decode step routes a few rows a
* sequence and stays under it; a prefill chunk routes thousands, and at full weight one chunk
* outweighs dozens of decode steps, so for that many steps after a prompt the resident set is
* the prompt's rather than the answer's. What the resident set buys a prefill is little in
* any case: a chunk reads nearly every expert of a layer, and the stager copies whichever are
* not resident. Replaying a mixed workload at Qwen3.8-Flash-Next TP1, decode rows hit 77.3%
* uncapped, 78.9% at 1024 and 79.0% at 512 or 256. */
float credit_cap = 512.0f;
/* Dispatches to watch before moving anything, and it is 0 because THE GUARD ALREADY DOES THIS
* JOB. min_gain means a promotion needs `hot >= cold*hysteresis + 1.5`, and against a
@@ -195,7 +210,7 @@ public:
/* The best swap available, or false when the guards refuse. */
bool pick(Swap* out) const;
/* One layer dispatch's worth of proposals, at most `moves_per_dispatch` of them a class.
/* One step's worth of proposals, at most `moves_per_step` of them a class.
*
* CONTRACT: every unit named in the result is marked busy on the way out. The caller must
* either issue the transfer -- in which case set_tier() on publish and set_busy(false) after
@@ -284,8 +299,8 @@ private:
* unit's class as a dense index, -1 for a unit that cannot move. */
std::vector<int32_t> cls_;
int32_t n_cls_ = 1;
/* step()'s two ends of the ranking, `moves_per_dispatch` entries a class, kept between calls
* so a dispatch allocates nothing. */
/* step()'s two ends of the ranking, `moves_per_step` entries a class, kept between calls so a
* step allocates nothing. */
std::vector<HeatRanked> rank_hot_, rank_cold_;
std::vector<int32_t> n_hot_, n_cold_, m_of_;
/* Per slot, its lowest movable unit index: the bound step()'s layer screen needs on a tie. */
+399 -76
View File
@@ -90,6 +90,7 @@ Mover::~Mover() {
* that name the events below and the copies into and out of the memory below, so each of
* those goes only once nothing queued refers to it. */
if (mover_) {
(void)flush_moves();
rad_stream_sync(mover_);
rad_stream_destroy(mover_);
}
@@ -114,8 +115,8 @@ Mover::~Mover() {
}
/* One place the mover asks for memory. Everything device-side and everything pinned comes out of
* the budgets the operator stated (spec §6); the fallback exists so the placement test can run
* without standing a whole Pools up, and it announces itself. */
* the resolved budgets (spec §6); the fallback exists so the placement test can run without
* standing a whole Pools up, and it announces itself. */
void* Mover::reserve(const char* what, int64_t bytes, int kind) {
if (bytes <= 0) return nullptr;
if (budget_) {
@@ -134,10 +135,15 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
stats_ = MoverStats{};
if (!budget_)
RAD_WARN("mover: no Pools handed over; allocating its slab and host pool directly. That "
"double-spends --vram-weights-mib against whatever else already reserved it, so "
"double-spends the weights pool against whatever else already reserved it, so "
"it is a test path and not a deployment.");
unit_.assign(plan.units.size(), UnitState{});
copying_.assign(plan.units.size(), 0);
pool_layer_.assign(plan.classes.size(), {});
donors_.assign(plan.classes.size(), DonorRank{});
n_layers_ = 0;
for (const MoveUnit& mu : plan.units) n_layers_ = std::max(n_layers_, mu.layer + 1);
pools_.clear();
pools_.resize(plan.classes.size());
@@ -162,6 +168,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
static_need = us.static_off + mu.bytes;
} else if (mu.tier == Tier::HostPinned) {
us.pool_slot = n_pool[(size_t)mu.slab_class]++;
pool_layer_[(size_t)mu.slab_class].push_back(mu.layer);
} else if (mu.tier == Tier::HostPageable) {
us.static_off = align_up(pageable_need, RAD_ALIGN_UNIT);
pageable_need = us.static_off + mu.bytes;
@@ -170,7 +177,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
}
/* ---- allocate ------------------------------------------------------------------------- */
int64_t total_shadow = 0;
int64_t total_shadow = 0, total_turn = 0;
for (size_t c = 0; c < plan.classes.size(); ++c) {
const SlabClass& sc = plan.classes[c];
ClassPools& cp = pools_[c];
@@ -180,7 +187,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
* resident count is untouched by turning the engine on. Under a static plan the plan
* asked for none and the slab is exactly the resident set. */
/* THE PLAN'S NUMBER, not a config cap. The planner reserved these out of
* --vram-weights-mib and the report told the operator how many; allocating a different
* the weights pool and the report told the operator how many; allocating a different
* count here would mean the mover works against one number while the operator was charged
* for another, and the direction that is wrong in is an overrun. */
const int64_t shadow = plan.dynamic ? sc.n_shadow : 0;
@@ -193,6 +200,9 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
* lend_from() adds them once it is. */
cp.n_fixed = slab_slots;
cp.n_work = shadow + sc.n_stage;
cp.n_turn = std::min<int64_t>(std::max(cfg.turnover_slots, 0),
shadow * RAD_PLACE_TURNOVER_SLOTS / RAD_PLACE_SHADOW_SLOTS);
total_turn += cp.n_turn;
cp.slab.init(slab_slots, sc.stride);
if (slab_slots > 0) {
/* Tail padding: a kernel that assembles a packed code window from a wide read
@@ -366,13 +376,13 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
lead_.assign((size_t)lead + 1, nullptr);
for (RadEvent& e : lead_) RAD_TRY(rad_event_create_as(&e, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
/* TWO records per shadow slot, not one. A promotion holds a slab slot for its whole life, so
* there can never be more promotions in flight than there are shadows -- but a swap is two
* transfers, and the matching demotion needs a record of its own or the pair can never be in
* flight together and the engine never issues a demotion at all. That failure is silent: it
* shows up as `no_record` where the real symptom is a resident set that only ever grows.
* The floor is what makes a one-shadow plan still able to hold a swap. */
const int64_t n_records = std::max<int64_t>(2 * total_shadow, 4);
/* TWO records per free slot, shadow or turnover, not one. A promotion holds a slab slot for
* its whole life, so there can never be more promotions in flight than there are free slots --
* but a swap is two transfers, and the matching demotion needs a record of its own or the pair
* can never be in flight together and the engine never issues a demotion at all. That failure
* is silent: it shows up as `no_record` where the real symptom is a resident set that only ever
* grows. The floor is what makes a one-shadow plan still able to hold a swap. */
const int64_t n_records = std::max<int64_t>(2 * (total_shadow + total_turn), 4);
moves_.assign((size_t)n_records, Move{});
for (Move& m : moves_) RAD_TRY(rad_event_create_local(&m.ev));
@@ -383,9 +393,10 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
republish(u);
}
RAD_INFO("mover: %lld slab slots (%lld shadow), %lld pinned pool slots, %s static vram%s",
RAD_INFO("mover: %lld slab slots (%lld shadow, %lld more kept free out of a loan), %lld pinned "
"pool slots, %s static vram%s",
(long long)[&] { int64_t n = 0; for (auto& c : pools_) n += c.slab.size(); return n; }(),
(long long)total_shadow,
(long long)total_shadow, (long long)total_turn,
(long long)[&] { int64_t n = 0; for (auto& c : pools_) n += c.pool.size(); return n; }(),
humanb(static_bytes_).c_str(), file_.ok() ? ", file tier open" : "");
/* The pageable host region is allocated here and charged to no budget -- Pools has no
@@ -436,9 +447,7 @@ void Mover::republish(int32_t unit) {
* a record past Copying has its bytes in place, and treating it as in-flight holds the slot for
* as long as the record takes to recycle rather than as long as the copy takes to land. */
bool Mover::unit_in_flight(int32_t unit) const {
for (const Move& m : moves_)
if (m.state == Move::State::Copying && m.unit == unit) return true;
return false;
return unit >= 0 && (size_t)unit < copying_.size() && copying_[(size_t)unit] > 0;
}
int Mover::free_move_record() const {
@@ -577,6 +586,7 @@ int Mover::start_stage(int32_t unit, int64_t slab_slot) {
m.state = Move::State::Copying;
m.kind = Move::Kind::Stage;
m.unit = unit;
++copying_[(size_t)unit];
m.slab_slot = slab_slot;
m.pool_slot = -1;
stats_.h2d_bytes += (uint64_t)us.bytes;
@@ -602,42 +612,76 @@ int Mover::start_stage(int32_t unit, int64_t slab_slot) {
/* ---- staging within a pass (see mover.h) ---------------------------------------------------- */
int Mover::stage_units(const std::vector<int32_t>& units, char* dst, int64_t cap, RadEvent after,
RadEvent done, std::vector<int32_t>* staged) {
if (!plan_ || !dst || !staged || !done) return RAD_E_INVAL;
const StageSpan one{dst, cap};
return stage_units(units, &one, 1, after, done, staged);
}
int Mover::stage_units(const std::vector<int32_t>& units, const StageSpan* spans, int n_spans,
RadEvent after, RadEvent done, std::vector<int32_t>* staged) {
if (!plan_ || !spans || n_spans < 1 || n_spans > 2 || !staged || !done) return RAD_E_INVAL;
for (int k = 0; k < n_spans; ++k)
if (!spans[k].dst) return RAD_E_INVAL;
staged->clear();
std::vector<int64_t> at;
at.reserve(units.size());
int64_t off = 0;
bool waited = false;
stage_picks_.clear();
for (int32_t u : units) {
if (u < 0 || (size_t)u >= unit_.size()) return RAD_E_INVAL;
const UnitState& us = unit_[(size_t)u];
if (us.tier != Tier::HostPinned || us.pool_slot < 0 || us.slab_slot >= 0 || us.klass < 0)
continue;
if (unit_in_flight(u)) continue;
const int64_t need = align_up(us.bytes, RAD_ALIGN_UNIT);
if (off + need > cap) { ++stats_.stage_overflow; continue; }
if (!waited) {
if (after) RAD_TRY(rad_event_wait(mover_, after));
waited = true;
}
const ClassPools& cp = pools_[(size_t)us.klass];
const char* src = (const char*)cp.pool_base + us.pool_slot * cp.stride;
RAD_TRY(rad_memcpy_async(dst + off, src, us.bytes, mover_));
staged->push_back(u);
at.push_back(off);
stats_.h2d_bytes += (uint64_t)us.bytes;
stats_.staged_bytes += (uint64_t)us.bytes;
off += need;
stage_picks_.push_back(StagePick{src, u, us.bytes, align_up(us.bytes, RAD_ALIGN_UNIT),
nullptr});
}
if (staged->empty()) return RAD_OK;
if (stage_picks_.empty()) return RAD_OK;
/* THE SPANS ARE FILLED IN POOL ORDER, so units on neighbouring pool slots land side by side
* and go as one copy. A layer's pooled experts were given their slots together and mostly
* still hold them, so a layer's ~90 units go as fewer copies -- each one a launch or a DMA
* packet whatever its size. A class's stride is its units' aligned size, so a run's source and
* destination advance alike, padding included. A unit the span in hand has no room left for
* goes to the start of the next; one that no span has room for is read across the link in
* place. */
std::sort(stage_picks_.begin(), stage_picks_.end(),
[](const StagePick& a, const StagePick& b) { return a.src < b.src; });
int k = 0;
int64_t off = 0;
size_t taken = 0;
for (StagePick& p : stage_picks_) {
if (off + p.need > spans[k].cap && k + 1 < n_spans && p.need <= spans[k + 1].cap) {
++k;
off = 0;
}
if (off + p.need > spans[k].cap) { ++stats_.stage_overflow; continue; }
p.dst = spans[k].dst + off;
off += p.need;
++taken;
}
if (taken == 0) return RAD_OK;
if (after) RAD_TRY(rad_event_wait(mover_, after));
stage_segs_.clear();
for (const StagePick& p : stage_picks_) {
if (!p.dst) continue;
RadCopySeg* run = stage_segs_.empty() ? nullptr : &stage_segs_.back();
if (run && p.src - (const char*)run->src == p.dst - (char*)run->dst)
run->bytes = (int64_t)(p.dst - (char*)run->dst) + p.bytes;
else
stage_segs_.push_back(RadCopySeg{p.src, p.dst, p.bytes});
staged->push_back(p.u);
stats_.h2d_bytes += (uint64_t)p.bytes;
stats_.staged_bytes += (uint64_t)p.bytes;
}
RAD_TRY(rad_memcpy_list_async(stage_segs_.data(), (int)stage_segs_.size(), RAD_COPY_YIELD,
mover_));
RAD_TRY(rad_event_record(done, mover_));
for (size_t k = 0; k < staged->size(); ++k) {
const MoveUnit& mu = plan_->units[(size_t)(*staged)[k]];
for (size_t i = 0; i < mu.weights.size(); ++i)
res_.publish(mu.weights[i], dst + at[k] + mu.offset[i]);
for (const StagePick& p : stage_picks_) {
if (!p.dst) continue;
const MoveUnit& mu = plan_->units[(size_t)p.u];
for (size_t i = 0; i < mu.weights.size(); ++i) res_.publish(mu.weights[i], p.dst + mu.offset[i]);
}
++stats_.stage_layers;
stats_.staged_units += (uint64_t)staged->size();
stats_.stage_copies += (uint64_t)stage_segs_.size();
return RAD_OK;
}
@@ -645,6 +689,23 @@ void Mover::unstage_units(const std::vector<int32_t>& staged) {
for (int32_t u : staged) republish(u);
}
/* The same choice of units as stage_units, without a cap. */
int64_t Mover::stage_need(const std::vector<int32_t>& units, int64_t* largest) const {
int64_t total = 0, most = 0;
for (int32_t u : units) {
if (u < 0 || (size_t)u >= unit_.size()) continue;
const UnitState& us = unit_[(size_t)u];
if (us.tier != Tier::HostPinned || us.pool_slot < 0 || us.slab_slot >= 0 || us.klass < 0)
continue;
if (unit_in_flight(u)) continue;
const int64_t need = align_up(us.bytes, RAD_ALIGN_UNIT);
total += need;
most = std::max(most, need);
}
if (largest) *largest = most;
return total;
}
/* ---- a routed layer read from the container (see mover.h) ---------------------------------- */
namespace {
@@ -817,7 +878,7 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
if (record_gate() < 0) return false;
Move& m = moves_[(size_t)rec];
{
const int64_t g = cp.pool.take();
const int64_t g = pool_slot_for(unit, heat);
if (g < 0) { ++stats_.starved_pool; return false; }
char* dst = (char*)cp.pool_base + g * cp.stride;
if (us.slab_slot < 0) { cp.pool.add_free(g); return false; }
@@ -829,11 +890,10 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
* demotion costs about what a promotion does. That is the exchange rate heat.h's
* min_gain is tuned against. */
if (rad_event_wait(mover_, gate_) < 0) { cp.pool.add_free(g); return false; }
if (rad_memcpy_async(dst, src, us.bytes, mover_) < 0) {
if (queue_move_copy(dst, src, us.bytes, (int)(&m - moves_.data())) < 0) {
cp.pool.add_free(g);
return false;
}
(void)rad_event_record(m.ev, mover_);
m.kind = Move::Kind::Demote;
m.slab_slot = us.slab_slot;
m.pool_slot = g;
@@ -841,6 +901,7 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
}
m.state = Move::State::Copying;
m.unit = unit;
++copying_[(size_t)unit];
return true;
};
@@ -1042,6 +1103,134 @@ int Mover::drop(int32_t unit, HeatEngine* heat) {
return RAD_OK;
}
/* THE POOL IS SIZED TO THE UNITS THAT LIVE IN IT, so it has a slot free only while a promotion
* into a budgeted slot is on its way through the quarantine -- and the budgeted range turns over
* only as fast as those few slots come round. A budgeted unit that goes cold then stays, and the
* engine's swap drops the coldest lent unit in its place, which is warmer: replaying a mixed
* workload's routing at TP1, the hit rate is 72.7% that way against 76.7% with up to n_turn
* donors a class, and 78.5% for one resident set with no regions at all.
*
* A unit in a lent slot keeps its host copy only so that a recall is a change of address. Giving
* the copy to the victim costs that for this one unit: a recall moves it, into a free budgeted
* slot or back across the link (reclaim), and a loan that shrinks under it moves it the same way
* (balance). There is always somewhere for it to go -- each donor's copy went to a unit
* whose budgeted slot it left free, so the free budgeted slots and the free pool slots together
* number at least the donors once the quarantine has emptied (a recall drains it first). The
* donors are bounded by the turnover slots, and they come out of the KV cache's loan only: the
* arena takes its loan back at every prompt's first chunk, and that recall stays a change of
* address.
*
* THE HOTTEST UNIT GIVES ITS COPY -- of the victim's layer, when pool_slot_for asks for one --
* because a donor the engine later demotes needs a pool slot of its own where it would have been a
* drop. Its pool slot has no reader: the unit has been resident since its promotion retired, and
* the copy into the slot waits on the gate besides. */
int64_t Mover::donor_slot(size_t klass, int32_t layer, HeatEngine* heat) {
ClassPools& cp = pools_[klass];
if (cp.n_donated >= cp.n_turn) return -1;
/* NOT WHILE THE TURNOVER SLOTS ARE HELD: through a prompt and the few steps after it
* (Engine::tiering_dispatch). A donation lets a starved demotion go and the swap behind it
* with it, two copies on the stream the next prompt stages on; at TP2, where the resident set
* is nine tenths of the experts and a donor buys no decode at all, 26K-token prompts back to
* back ran 0.3% slower with them. A decode run reaches the count in a few steps. */
if (hold_turnover_) return -1;
DonorRank& d = donors_[klass];
if (d.at != dispatch_) {
d.at = dispatch_;
d.by_layer.assign((size_t)std::max(n_layers_, 1), {});
for (const ClassPools::Lent& l : cp.lent) {
if (l.lender != kLendKV) continue;
const int64_t lo = cp.slab.seg_lo(l.seg), hi = cp.slab.target(l.seg);
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
const UnitState& us = unit_[(size_t)u];
if (us.klass != (int32_t)klass || us.slab_slot < lo || us.slab_slot >= hi) continue;
const int32_t ul = plan_->units[(size_t)u].layer;
if (ul < 0 || ul >= n_layers_) continue;
d.by_layer[(size_t)ul].push_back({ heat ? heat->heat(u) : 0.0f, u });
}
}
for (auto& v : d.by_layer) std::sort(v.begin(), v.end());
}
for (;;) {
/* The hottest candidate of the layer asked for, or of every layer. */
std::vector<std::pair<float, int32_t>>* pick = nullptr;
if (layer >= 0) {
if (layer < (int32_t)d.by_layer.size() && !d.by_layer[(size_t)layer].empty())
pick = &d.by_layer[(size_t)layer];
} else {
for (auto& v : d.by_layer)
if (!v.empty() && (!pick || v.back() > pick->back())) pick = &v;
}
if (!pick) return -1;
const int32_t u = pick->back().second;
pick->pop_back();
UnitState& us = unit_[(size_t)u];
if (us.klass != (int32_t)klass || us.pool_slot < 0 || us.slab_slot < 0) continue;
if (us.tier != Tier::VRAM || us.site != Site::Device || !cp.slab.covered(us.slab_slot))
continue;
if ((heat && heat->busy(u)) || unit_in_flight(u)) continue;
const int64_t g = us.pool_slot;
us.pool_slot = -1;
++cp.n_donated;
++stats_.donated;
return g;
}
}
/* THE STAGER COPIES A LAYER'S POOLED UNITS IN RUNS OF NEIGHBOURING POOL SLOTS (stage_units), and
* the pool is laid out in unit order, so a layer's pooled units start out side by side. A demotion
* that lands in a slot another layer's unit left breaks one run in that layer and starts a run of
* one in its own, a copy more in each, for every prompt after it. So a slot one of the unit's own
* layer started out in comes first, then a donor of the same layer -- its slot most likely one of
* those -- and only then any free slot, or any donor. At TP1, 26K-token prompts with 256 tokens
* decoded between them staged a layer in 162 copies without the preference and 112 with it (95
* when the budget was 8 swaps a step). */
int64_t Mover::pool_slot_for(int32_t unit, HeatEngine* heat) {
const UnitState& us = unit_[(size_t)unit];
ClassPools& cp = pools_[(size_t)us.klass];
const int32_t layer = plan_->units[(size_t)unit].layer;
const std::vector<int32_t>& home = pool_layer_[(size_t)us.klass];
int64_t g = -1;
if (layer >= 0) {
g = cp.pool.take_where([&](int64_t p) { return (size_t)p < home.size() && home[(size_t)p] == layer; });
if (g < 0) g = donor_slot((size_t)us.klass, layer, heat);
}
if (g < 0) g = cp.pool.take();
if (g < 0) g = donor_slot((size_t)us.klass, -1, heat);
return g;
}
bool Mover::migrate(int32_t unit, HeatEngine* heat) {
UnitState& us = unit_[(size_t)unit];
ClassPools& cp = pools_[(size_t)us.klass];
const int64_t to = cp.slab.take();
if (to < 0) return false;
if (to >= cp.n_fixed) {
cp.slab.add_free(to);
return false;
}
const int rec = free_move_record();
if (rec < 0 || record_gate() < 0) {
if (rec < 0) ++stats_.no_record;
cp.slab.add_free(to);
return false;
}
Move& m = moves_[(size_t)rec];
if (rad_event_wait(mover_, gate_) < 0 ||
queue_move_copy(cp.slot_ptr(to), cp.slot_ptr(us.slab_slot), us.bytes, rec) < 0) {
cp.slab.add_free(to);
return false;
}
m.state = Move::State::Copying;
m.kind = Move::Kind::Migrate;
m.unit = unit;
m.slab_slot = us.slab_slot;
m.pool_slot = -1;
m.to_slot = to;
++copying_[(size_t)unit];
if (heat) heat->set_busy(unit, true);
return true;
}
int Mover::promote_to(int32_t unit, int64_t slot) {
UnitState& us = unit_[(size_t)unit];
ClassPools& cp = pools_[(size_t)us.klass];
@@ -1052,8 +1241,7 @@ int Mover::promote_to(int32_t unit, int64_t slot) {
const void* src = (const char*)cp.pool_base + us.pool_slot * cp.stride;
Move& m = moves_[(size_t)rec];
RAD_TRY(rad_event_wait(mover_, gate_));
RAD_TRY(rad_memcpy_async(cp.slot_ptr(slot), src, us.bytes, mover_));
(void)rad_event_record(m.ev, mover_);
RAD_TRY(queue_move_copy(cp.slot_ptr(slot), src, us.bytes, rec));
m.kind = Move::Kind::Promote;
m.slab_slot = slot;
/* INTO A LENT SLOT, THE HOST COPY STAYS. The loan can be recalled at any time and a unit that
@@ -1063,6 +1251,7 @@ int Mover::promote_to(int32_t unit, int64_t slot) {
m.pool_slot = cp.is_flex(slot) ? -1 : us.pool_slot;
m.state = Move::State::Copying;
m.unit = unit;
++copying_[(size_t)unit];
stats_.h2d_bytes += (uint64_t)us.bytes;
return RAD_OK;
}
@@ -1125,7 +1314,7 @@ int Mover::fill(size_t klass, int64_t room, HeatEngine* heat) {
return RAD_OK;
}
int Mover::balance(HeatEngine* heat) {
int Mover::balance(HeatEngine* heat, bool turnover) {
if (!plan_ || !plan_->dynamic) return RAD_OK;
for (size_t c = 0; c < pools_.size(); ++c) {
@@ -1149,6 +1338,20 @@ int Mover::balance(HeatEngine* heat) {
left = true;
continue;
}
/* A donor has no host copy to drop to: it moves into a free budgeted slot, or
* else back across the link, and stays past the loan until the copy lands. */
if (us.pool_slot < 0) {
if (migrate(u, heat)) {
drained = true;
} else {
if (heat) heat->set_busy(u, true);
Swap s;
s.demote = u;
if (issue(s, heat) >= 0) drained = true;
}
left = true;
continue;
}
if (drop(u, heat) < 0) { left = true; break; }
drained = true;
}
@@ -1160,36 +1363,54 @@ int Mover::balance(HeatEngine* heat) {
* slots that were serving as the reserve leaves the slab too full by that many, and the
* coldest lent units go -- drops, never copies. A slot already on its way back below the
* target counts as free, because it is, a barrier from now; draining against it again is
* how a slab empties itself. */
* how a slab empties itself.
*
* THE TURNOVER SLOTS ARE REBUILT THE SAME WAY, out of the lent units alone. They are the
* top of the lent range, which is exactly what a cache that wants memory back takes first,
* and the loan grows back only a prefill chunk at a time: left to the fill, they would be
* gone for as long as requests keep arriving. Dropping the coldest lent units costs
* nothing on the link -- each still has its host copy -- and gives up the same residents
* the slots would have cost anyway. A swap whose demotion found no pool slot is completed
* the same way, by the coldest lent unit instead. */
int64_t pending = 0;
for (const Move& m : moves_) {
if (m.state == Move::State::Free || m.unit < 0 || m.slab_slot < 0) continue;
if (unit_[(size_t)m.unit].klass != (int32_t)c || !cp.slab.covered(m.slab_slot)) continue;
if (m.kind == Move::Kind::Drop || m.kind == Move::Kind::Demote ||
m.kind == Move::Kind::Release)
m.kind == Move::Kind::Release || m.kind == Move::Kind::Migrate)
++pending;
}
int64_t short_by = cp.n_work - (cp.slab.n_free() + pending);
while (short_by > 0) {
int32_t victim = -1;
float coldest = 0.0f;
const int64_t turn = turnover ? cp.n_turn : 0;
int64_t short_by = cp.n_work + turn - (cp.slab.n_free() + pending);
if (short_by > 0) {
drop_cand_.clear();
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
const UnitState& us = unit_[(size_t)u];
if (us.klass != (int32_t)c || us.slab_slot < 0 || !cp.is_flex(us.slab_slot)) continue;
if (us.tier != Tier::VRAM || us.site != Site::Device || us.pool_slot < 0) continue;
if (heat && heat->busy(u)) continue;
const float h = heat ? heat->heat(u) : 0.0f;
if (victim < 0 || h < coldest) { victim = u; coldest = h; }
drop_cand_.push_back({ heat ? heat->heat(u) : 0.0f, u });
}
/* The coldest first, and on a tie the lower unit, so the choice is the same every run. */
auto colder = [](const std::pair<float, int32_t>& a, const std::pair<float, int32_t>& b) {
return a.first != b.first ? a.first < b.first : a.second < b.second;
};
const size_t k = std::min(drop_cand_.size(), (size_t)short_by);
std::partial_sort(drop_cand_.begin(), drop_cand_.begin() + (ptrdiff_t)k, drop_cand_.end(),
colder);
for (size_t i = 0; i < k; ++i) {
if (drop(drop_cand_[i].second, heat) < 0) break;
drained = true;
--short_by;
}
if (victim < 0 || drop(victim, heat) < 0) break;
drained = true;
--short_by;
}
/* AND WITH NO LENT UNIT LEFT TO DROP, THE COLDEST BUDGETED ONE GOES BACK TO THE POOL -- a
* real demotion, one a call. A swap can leave the free slots in the lent range, and a loan
* that then shrinks away takes them with it; the reserve has to be rebuilt out of the
* real demotion, one a call, and for the working reserve only: the turnover slots are the
* loan's to give, and a copy across the link to keep them would spend the very link they
* exist to save. A swap can leave the free slots in the lent range, and a loan that then
* shrinks away takes them with it; the working reserve has to be rebuilt out of the
* budgeted slots or the mover stops turning over. */
if (short_by > 0) {
if (short_by > turn) {
int32_t victim = -1;
float coldest = 0.0f;
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
@@ -1212,17 +1433,17 @@ int Mover::balance(HeatEngine* heat) {
* trying to hand back. */
if (drained) continue;
/* ---- THEN FILL, every free slot past the working reserve. */
RAD_TRY(fill(c, cp.slab.n_free() - cp.n_work, heat));
/* ---- THEN FILL, every free slot past the working reserve and the turnover slots. */
RAD_TRY(fill(c, cp.slab.n_free() - cp.n_work - turn, heat));
}
count_flex();
return RAD_OK;
return flush_moves();
}
int Mover::idle_tick(HeatEngine* heat) {
if (!plan_ || !plan_->dynamic) return RAD_OK;
RAD_TRY(retire(heat));
return balance(heat);
return balance(heat, !hold_turnover_);
}
int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
@@ -1235,20 +1456,69 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
}
/* NO COPY IS STILL WRITING A SLOT: everything the mover issued has landed, and retiring it
* publishes the promotions that landed in slots about to be taken back. */
RAD_TRY(flush_moves());
RAD_TRY(rad_stream_sync(mover_));
RAD_TRY(retire(heat));
/* AND NO SLOT IS STILL IN QUARANTINE. The slots the donors below are owed come back through
* it: a donation's victim leaves its budgeted slot that way, and a promotion that refilled the
* slot leaves its pool slot that way (donor_slot). Looked for before the compute stream has
* passed their barriers, the slots of the last few dispatches' swaps are not free yet, and a
* donor finds nowhere to go. Nothing goes on the compute stream from this drain to the end of
* the recall, which issues only the mover's own copies. */
RAD_TRY(rad_stream_sync(compute_));
RAD_TRY(retire(heat));
/* EVERY UNIT PAST THE LOAN GOES BACK TO ITS HOST COPY, which is a change of address. */
/* EVERY UNIT PAST THE LOAN GOES BACK TO ITS HOST COPY, which is a change of address -- or,
* for a donor (donor_slot), which has none, it moves: into a free budgeted slot, a copy inside
* the card, or else back across the link into a free pool slot. One of the two is free for
* every donor once the quarantine is empty (donor_slot says why). Nothing is published until
* the copies have landed.
*
* A DONOR WITH NOWHERE TO GO STAYS WHERE IT IS, and the recall still finishes: every other
* slot is given back and every moved donor published, so the loan stops short only by that
* unit's slot, and a later recall or balance() moves it. Stopping at it instead would leave
* the slots already taken off their units held by nothing, for the life of the process. */
std::vector<std::pair<size_t, int64_t>> freed;
std::vector<int32_t> moved;
int stuck = 0;
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
UnitState& us = unit_[(size_t)u];
if (us.klass < 0 || us.slab_slot < 0) continue;
const ClassPools& cp = pools_[(size_t)us.klass];
ClassPools& cp = pools_[(size_t)us.klass];
if (!cp.is_flex(us.slab_slot) || cp.slab.covered(us.slab_slot)) continue;
if (us.pool_slot < 0) {
RAD_ERR("mover: unit %d sits in lent slot %lld with no host copy to go back to",
(int)u, (long long)us.slab_slot);
return RAD_E_STATE;
const int64_t from = us.slab_slot;
int64_t to = cp.slab.take();
if (to >= cp.n_fixed) {
cp.slab.add_free(to);
to = -1;
}
const int64_t g = to < 0 ? cp.pool.take() : -1;
if (to >= 0) {
RAD_TRY(rad_memcpy_async(cp.slot_ptr(to), cp.slot_ptr(from), us.bytes, mover_));
us.slab_slot = to;
} else if (g >= 0) {
RAD_TRY(rad_memcpy_async((char*)cp.pool_base + g * cp.stride, cp.slot_ptr(from),
us.bytes, mover_));
us.pool_slot = g;
us.slab_slot = -1;
us.tier = Tier::HostPinned;
us.site = Site::DeviceZeroCopy;
stats_.d2h_bytes += (uint64_t)us.bytes;
++stats_.demotions;
if (heat) {
heat->set_tier(u, Tier::HostPinned);
heat->set_busy(u, false);
}
} else {
++stuck;
continue;
}
--cp.n_donated;
++stats_.relocated;
freed.push_back({ (size_t)us.klass, from });
moved.push_back(u);
continue;
}
freed.push_back({ (size_t)us.klass, us.slab_slot });
us.slab_slot = -1;
@@ -1263,10 +1533,15 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
}
}
if (!moved.empty()) {
RAD_TRY(rad_stream_sync(mover_));
for (int32_t u : moved) republish(u);
}
/* AND NO KERNEL STILL NAMES ONE. The compute stream is the only reader of the slab -- the
* quarantine barrier rests on the same fact -- so once it has drained, nothing already issued
* can reach a slot past the loan, and everything issued from here reads the host copies. */
RAD_TRY(rad_stream_sync(compute_));
* quarantine barrier rests on the same fact -- and it drained above with nothing issued since,
* so nothing can reach a slot past the loan, and everything issued from here reads the host
* copies. */
for (const auto& f : freed) pools_[f.first].slab.add_free(f.second);
/* EVERY RECORD WAITING ON ONE OF THOSE SLOTS IS DONE WAITING: its barrier is behind the
@@ -1279,15 +1554,24 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
ClassPools& cp = pools_[(size_t)klass];
if (!cp.is_flex(m.slab_slot) || cp.slab.covered(m.slab_slot)) continue;
if (m.kind == Move::Kind::Drop || m.kind == Move::Kind::Demote ||
m.kind == Move::Kind::Release)
m.kind == Move::Kind::Release || m.kind == Move::Kind::Migrate)
cp.slab.add_free(m.slab_slot);
if (heat && m.kind != Move::Kind::Stage && m.kind != Move::Kind::Release)
heat->set_busy(m.unit, false);
if (m.state == Move::State::Copying) --copying_[(size_t)m.unit];
m.state = Move::State::Free;
m.unit = -1;
m.slab_slot = m.pool_slot = -1;
m.slab_slot = m.pool_slot = m.to_slot = -1;
}
count_flex();
if (stuck > 0) {
stats_.stranded += (uint64_t)stuck;
RAD_ERR("mover: %d unit(s) that gave their host copy away found no free slot to move to; "
"the %s loan stops at %lld instead of %lld until they move", stuck,
lender == kLendKV ? "KV" : "arena", (long long)loan_held(lender),
(long long)loan_[lender]);
return RAD_E_FULL;
}
if (loan_held(lender) > loan_[lender]) {
RAD_ERR("mover: recalled the %s loan to %lld and a slot at %lld is still held",
lender == kLendKV ? "KV" : "arena", (long long)loan_[lender],
@@ -1297,13 +1581,38 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
return RAD_OK;
}
int Mover::queue_move_copy(void* dst, const void* src, int64_t bytes, int rec) {
move_segs_.push_back(RadCopySeg{ src, dst, bytes });
move_recs_.push_back((int32_t)rec);
return RAD_OK;
}
/* THE DMA ENGINE AND NOT COPY KERNELS. A copy kernel runs on the compute units beside the step's
* kernels: at the heat engine's budget of 64 swaps a step, Qwen3.8-Flash-Next at one card spent 10 ms
* a step in about 68 of them while the step took 36. The engine moves the same bytes at the link's
* rate and takes nothing from the kernels; decode at one sequence went 34.1 -> 33.0 ms a step, and
* two cards, prefill and the output were unchanged. A card with no DMA queue of this process's own
* gets the list as copy kernels (rad_memcpy_list_async), as before. The list yields to the link's
* collectives like the prefill stager's. */
int Mover::flush_moves() {
if (move_segs_.empty()) return RAD_OK;
const int rc = rad_memcpy_list_async(move_segs_.data(), (int)move_segs_.size(), RAD_COPY_YIELD,
mover_);
for (int32_t rec : move_recs_) (void)rad_event_record(moves_[(size_t)rec].ev, mover_);
move_segs_.clear();
move_recs_.clear();
return rc;
}
int Mover::retire(HeatEngine* heat) {
RAD_TRY(flush_moves());
for (Move& m : moves_) {
if (m.state != Move::State::Copying) continue;
const int q = rad_event_query(m.ev);
if (q < 0) return RAD_E_DEVICE;
if (q == 0) continue;
--copying_[(size_t)m.unit];
UnitState& us = unit_[(size_t)m.unit];
switch (m.kind) {
case Move::Kind::Promote:
@@ -1317,6 +1626,9 @@ int Mover::retire(HeatEngine* heat) {
if (heat) heat->set_tier(m.unit, Tier::VRAM);
break;
case Move::Kind::Demote:
/* Out of a lent slot, the unit was a donor (donor_slot): any other unit there is
* dropped, not demoted. */
if (pools_[(size_t)us.klass].is_flex(m.slab_slot)) --pools_[(size_t)us.klass].n_donated;
us.pool_slot = m.pool_slot;
us.slab_slot = -1;
us.tier = Tier::HostPinned;
@@ -1348,8 +1660,13 @@ int Mover::retire(HeatEngine* heat) {
* and the pipeline simply stops turning over. */
m.state = Move::State::Free;
m.unit = -1;
m.slab_slot = m.pool_slot = -1;
m.slab_slot = m.pool_slot = m.to_slot = -1;
continue;
case Move::Kind::Migrate:
us.slab_slot = m.to_slot;
--pools_[(size_t)us.klass].n_donated;
++stats_.relocated;
break;
case Move::Kind::Release:
case Move::Kind::Drop:
break;
@@ -1393,14 +1710,15 @@ int Mover::retire(HeatEngine* heat) {
case Move::Kind::Demote: cp.slab.add_free(m.slab_slot); break;
case Move::Kind::Release: cp.slab.add_free(m.slab_slot); break;
case Move::Kind::Drop: cp.slab.add_free(m.slab_slot); break;
case Move::Kind::Migrate: cp.slab.add_free(m.slab_slot); break;
case Move::Kind::Stage: break; /* never reaches here; freed as soon as it lands */
}
if (heat && (m.kind == Move::Kind::Promote || m.kind == Move::Kind::Demote ||
m.kind == Move::Kind::Drop))
m.kind == Move::Kind::Drop || m.kind == Move::Kind::Migrate))
heat->set_busy(m.unit, false);
m.state = Move::State::Free;
m.unit = -1;
m.slab_slot = m.pool_slot = -1;
m.slab_slot = m.pool_slot = m.to_slot = -1;
}
count_flex();
return RAD_OK;
@@ -1421,6 +1739,11 @@ std::string Mover::report() const {
"slot; %llu slots quarantined\n",
(unsigned long long)stats_.no_record, (unsigned long long)stats_.starved_slab,
(unsigned long long)stats_.starved_pool, (unsigned long long)stats_.quarantined);
if (stats_.donated)
s += fmt(" %llu host copies given by lent units to budgeted victims, %llu such units moved "
"by a recall, %llu left past one with no free slot\n",
(unsigned long long)stats_.donated, (unsigned long long)stats_.relocated,
(unsigned long long)stats_.stranded);
if (stats_.ssd_reads)
s += fmt(" file tier: %llu demand reads (%.2f GiB), each a blocking pread in the middle "
"of a dispatch. Raise --host-pool-mib.\n",
+130 -12
View File
@@ -45,6 +45,7 @@
* the slot has retired.
*/
#pragma once
#include "../device/device.h"
#include "../device/directio.h"
#include "../mem/pools.h"
#include "heat.h"
@@ -212,6 +213,25 @@ public:
}
return got;
}
/* take(), restricted to the free slots `want` accepts: the lowest of them, or -1. A scan of
* the free list, which holds the slots on their way back through a swap -- a few dozen. */
template <class Want> int64_t take_where(Want want) {
size_t best = free_.size();
for (size_t i = 0; i < free_.size(); ++i) {
const int64_t s = free_[i];
if (!covered(s) || held_[(size_t)s] || !want(s)) continue;
if (best == free_.size() || s < free_[best]) best = i;
}
if (best == free_.size()) return -1;
const int64_t s = free_[best];
free_[best] = free_.back();
free_.pop_back();
std::make_heap(free_.begin(), free_.end(), std::greater<int64_t>());
held_[(size_t)s] = 1;
++n_held_;
--n_usable_;
return s;
}
/* The highest slot of segment `k` something holds -- a unit, a copy in flight, a slot in
* quarantine -- or -1. A scan down from the segment's mark. */
int64_t top_held(int k = 0) const {
@@ -336,7 +356,7 @@ private:
/* ------------------------------------------------------------------ configuration */
struct MoverConfig {
/* Shadow slots and the staging ring are NOT here. They are budgeted by the planner out of
* --vram-weights-mib and reported in the plan (SlabClass::n_shadow, n_stage), and a second
* the weights pool and reported in the plan (SlabClass::n_shadow, n_stage), and a second
* knob for the same quantity is a second number for the mover and the operator to disagree
* about -- with an overrun as the direction that disagreement goes wrong in.
*
@@ -356,6 +376,13 @@ struct MoverConfig {
* layer. */
int max_lead_dispatches = 2;
/* Lent slots kept free for swaps to land in, a slab class (planner.h's
* RAD_PLACE_TURNOVER_SLOTS; Mover::balance keeps them). A knob here and not in the plan because the planner charges
* nothing for them: they are the KV cache's memory, free only while it lends. A class whose
* shadow slots the quarter-of-the-slab cap cut keeps at most the same multiple of them, so a
* small loan is not left emptier than it is filled. */
int turnover_slots = RAD_PLACE_TURNOVER_SLOTS;
/* The container, for the file tier. Empty means there is no file tier and a unit the planner
* put there is an error rather than a slow path. */
std::string container_path;
@@ -393,10 +420,17 @@ struct MoverStats {
/* Demotions that copied nothing: the unit sat in a lent slot and kept its host copy, so going
* back to the host tier was a change of address. Counted inside `demotions` as well. */
uint64_t dropped = 0;
/* Host copies a unit in a lent slot gave to a budgeted victim that had no pool slot to go to
* (Mover::donor_slot), and such units moved rather than dropped when their loan was recalled
* or shrank. `stranded` counts the recalls that found no free slot for one of them: it stayed
* past the loan until a later recall or balance() moved it. */
uint64_t donated = 0, relocated = 0, stranded = 0;
uint64_t ssd_reads = 0, ssd_bytes = 0;
/* The prefill stager's copies (stage_units): layers staged, units and bytes copied, and
* pooled units a buffer had no room left for -- those were read across the link in place. */
* pooled units a buffer had no room left for -- those were read across the link in place.
* `stage_copies` is how many copies carried the units: neighbouring pool slots go as one. */
uint64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0;
uint64_t stage_copies = 0;
/* The file stager's reads (stage_file_units): routed layers read from the container, the
* units and bytes they carried, the preads that carried them, and the host time spent inside
* those reads and waiting for a window's copies to drain -- the two halves of what a step
@@ -419,7 +453,7 @@ public:
* diagnosis.
*
* `budget` IS THE PRODUCTION PATH AND SHOULD ALWAYS BE PASSED. Pools already allocated
* --vram-weights-mib as one block; a mover that called rad_dev_alloc beside it would spend
* the weights pool as one block; a mover that called rad_dev_alloc beside it would spend
* that budget TWICE and the overrun would surface as an out-of-memory from an unrelated
* launch much later. Reserving from Pools::weights() is also what makes it structurally
* impossible for a promotion to reach a KV block -- there is no path from the weights pool to
@@ -547,6 +581,13 @@ public:
int64_t flex_used_bytes() const { return flex_used_.load(std::memory_order_relaxed); }
int64_t flex_offered_bytes() const { return flex_offered_.load(std::memory_order_relaxed); }
int64_t flex_capacity() const;
/* The lent slots the fill leaves free for the engine to swap into
* (MoverConfig::turnover_slots), summed over the slab classes. */
int64_t turnover_slots() const {
int64_t n = 0;
for (const ClassPools& cp : pools_) n += cp.n_turn;
return n;
}
/* THE LOAN PAST WHICH NOTHING MORE WOULD BE USED, in the lender's measure: the one that
* covers every slot carved from it. The slots were carved no deeper than the units the host
* pool holds, so a loan this size already has room for every unit that could move -- more VRAM
@@ -556,14 +597,38 @@ public:
/* FILL EVERY SLOT THERE IS ROOM IN, AND EMPTY EVERY SLOT THE LOAN NO LONGER COVERS -- the
* half-swaps the heat engine never proposes, because its decision is a COMPARISON and a
* comparison needs a victim. Not bounded by a count: a slot left empty while a unit streams
* across the link is VRAM bought and wasted on every step, so every free slot is filled in
* one call, hottest units first, and the copies run at the rate the link carries them. */
int balance(HeatEngine* heat);
* across the link is VRAM bought and wasted on every step, so every free slot past the
* turnover slots is filled in one call, hottest units first, and the copies run at the rate
* the link carries them. The turnover slots are left free because the engine's swaps land in
* them; filled, they would cap the move rate at what the shadow slots alone allow. When fewer
* than the working and turnover slots are free, the coldest lent units are dropped until
* enough are -- a change of address, never a copy.
*
* `turnover` false treats the turnover slots as room, filled like any other: a step bound by
* its own staging copies swaps nothing (Engine::tiering_dispatch), and every unit resident is
* one its stager does not copy. The next call with it true drops them back out. */
int balance(HeatEngine* heat, bool turnover = true);
/* balance() for a rank with no step to ride on. Retires what has landed and fills what is
* free, so a loan made while the server is idle is filled before the next request rather
* than by it. Only while the rank thread is parked. */
* than by it -- the turnover slots too while they are held. Only while the rank thread is
* parked. */
int idle_tick(HeatEngine* heat);
/* Whether idle ticks keep the turnover slots filled: the engine holds them through a prompt
* and the few steps after it (Engine::tiering_dispatch). */
void hold_turnover(bool held) { hold_turnover_ = held; }
/* Each class's pinned pool as the card addresses it: [lo, hi) and the unit stride. At most `max`. */
int pool_ranges(uint64_t* lo, uint64_t* hi, uint64_t* stride, int max) const {
int n = 0;
for (const ClassPools& cp : pools_)
if (cp.pool_dev && cp.stride > 0 && n < max) {
lo[n] = (uint64_t)(uintptr_t)cp.pool_dev;
hi[n] = lo[n] + (uint64_t)cp.pool.size() * (uint64_t)cp.stride;
stride[n] = (uint64_t)cp.stride;
++n;
}
return n;
}
/* Where a unit's bytes are right now, as a device-visible address, or null for a file-tier
* unit that has not been staged. */
@@ -587,10 +652,20 @@ public:
* unstage_units publish those units at their pool slots again. The caller must already have
* ordered the next writer of `dst` behind every op that read the copies; this
* only moves the address the NEXT issue resolves.
* stage_need the room stage_units would fill with `units` given room for all of them, so
* a caller packing several layers into one region can size each one's share;
* `largest`, when not null, gets the room the largest of those units takes.
*
* The span form packs into up to two stretches, the second taking what the first has no
* room left for: a ring's place that wraps past the region's end is two.
*/
struct StageSpan { char* dst; int64_t cap; };
int stage_units(const std::vector<int32_t>& units, char* dst, int64_t cap, RadEvent after,
RadEvent done, std::vector<int32_t>* staged);
int stage_units(const std::vector<int32_t>& units, const StageSpan* spans, int n_spans,
RadEvent after, RadEvent done, std::vector<int32_t>* staged);
void unstage_units(const std::vector<int32_t>& staged);
int64_t stage_need(const std::vector<int32_t>& units, int64_t* largest = nullptr) const;
/* ---- ROUTED LAYERS READ FROM THE CONTAINER: the file stager (core/place/stager.h) --------
*
@@ -598,7 +673,7 @@ public:
* grouped GEMM is handed every expert's pointer at issue -- so before a routed layer's first
* expert op, every one of its file-tier units is read into a VRAM buffer and published there,
* and after the layer it is published as null again (unstage_units does that half). The
* buffers are the two the plan charged out of --vram-weights-mib (Plan::file_stage_vram).
* buffers are the two the plan charged out of the weights pool (Plan::file_stage_vram).
*
* stage_file_units read every unit of `units` that is on the file tier into `dst`, packed at
* RAD_ALIGN_UNIT in the order given, through the pinned read windows: the
@@ -629,18 +704,22 @@ private:
* mid-layer, because placement would then depend on host timing and stop being reproducible. */
struct Move {
enum class State { Free, Copying, Published, Quarantine };
/* Five kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is
/* Six kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is
* the exact prefetch bringing an offloaded unit into a slot. Release is the same slot
* going back once the declared order says nothing will read it again this step -- it
* copies nothing and still needs the quarantine, because the barrier is about kernels
* already issued and not about bytes in flight. Drop is a unit in a lent slot going back
* to the host copy it kept: no copy either, and the same quarantine for the same reason. */
enum class Kind { Promote, Demote, Stage, Release, Drop };
* to the host copy it kept: no copy either, and the same quarantine for the same reason.
* Migrate is a donor (Mover::donor_slot) leaving a lent slot the loan no longer covers
* for a free budgeted one, a copy inside the card; `slab_slot` is the slot it leaves and
* `to_slot` the one it lands in. */
enum class Kind { Promote, Demote, Stage, Release, Drop, Migrate };
State state = State::Free;
Kind kind = Kind::Promote;
int32_t unit = -1;
int64_t slab_slot = -1;
int64_t pool_slot = -1;
int64_t to_slot = -1;
RadEvent ev = nullptr;
};
@@ -655,7 +734,7 @@ private:
};
/* One weight class's memory. The slab is two kinds of slot rather than one: the BUDGETED slots
* come out of --vram-weights-mib like every other weight allocation and sit at a fixed stride
* come out of the weights pool like every other weight allocation and sit at a fixed stride
* from one base, and the FLEX slots past them are addresses inside another pool's memory --
* the KV cache's carve, the activation arena's top -- lent while that pool is not using them.
* They cannot be one range because the flex slots are scattered over every layer's stripe of
@@ -672,6 +751,11 @@ private:
int64_t stride = 0;
int64_t n_fixed = 0; /* slots in the budgeted range; the flex ones start here */
int64_t n_work = 0; /* shadow + staging: free slots the mover needs to move at all */
int64_t n_turn = 0; /* lent slots kept free past those: the fill stops short
* of them and balance() drops lent units to rebuild them
* (MoverConfig::turnover_slots) */
int64_t n_donated = 0; /* units in lent slots that gave their host copy away
* (Mover::donor_slot); at most n_turn of them */
std::vector<char*> flex_ptr;
/* ONE SEGMENT OF THE SLAB PER LENDER THAT CARVED SLOTS FOR THIS CLASS. `need[i]` is the
* loan, in the lender's measure, that covers the segment's i-th slot; ascending, so a
@@ -703,11 +787,36 @@ private:
RadStream mover_ = nullptr;
RadStream compute_ = nullptr;
RadEvent gate_ = nullptr; /* recorded on compute, waited on by the mover stream */
std::vector<RadCopySeg> stage_segs_; /* stage_units' list, kept so a layer allocates nothing */
struct StagePick { const char* src; int32_t u; int64_t bytes, need; char* dst; };
std::vector<StagePick> stage_picks_; /* the units stage_units may take, in pool order */
int gate_dispatch_ = -1;
/* A DISPATCH'S SWAP COPIES -- demotions, promotions and migrations -- GO TO THE CARD'S DMA ENGINE
* AS ONE LIST (flush_moves), sent at the end of balance() and before anything reads their events.
* Each move's event is recorded behind the list, so a move lands with its list. */
std::vector<RadCopySeg> move_segs_;
std::vector<int32_t> move_recs_;
int queue_move_copy(void* dst, const void* src, int64_t bytes, int rec);
int flush_moves();
std::vector<ClassPools> pools_;
std::vector<UnitState> unit_;
std::vector<Move> moves_;
/* Per unit, how many records are Copying it: unit_in_flight() without a walk of the records.
* The prefill stager asks for every pooled unit of every layer it stages, and the records
* number twice the slots a swap can hold, so a walk would grow with the move budget. */
std::vector<uint16_t> copying_;
/* balance()'s drop candidates, (heat, unit), kept between calls so a step allocates nothing. */
std::vector<std::pair<float, int32_t>> drop_cand_;
bool hold_turnover_ = false;
/* donor_slot()'s candidates a class, by layer, each layer's coldest first so its hottest is at
* the back; ranked once a dispatch, `at` being the dispatch they were ranked for. */
struct DonorRank { int at = -1; std::vector<std::vector<std::pair<float, int32_t>>> by_layer; };
std::vector<DonorRank> donors_;
/* The layer whose unit each pool slot held when the pool was laid out, a class: the pool is
* filled in unit order, so a layer's pooled units start out side by side (pool_slot_for). */
std::vector<std::vector<int32_t>> pool_layer_;
int32_t n_layers_ = 0;
void* static_vram_ = nullptr;
int64_t static_bytes_ = 0;
@@ -756,6 +865,15 @@ private:
bool unit_in_flight(int32_t unit) const;
/* A unit in a lent slot back to the host copy it kept. See Move::Kind::Drop. */
int drop(int32_t unit, HeatEngine* heat);
/* The pool slot a demotion copies `unit` into: one its layer's units started out in, else a
* same-layer donor's, else any free one, else any donor's; -1 when there is none. */
int64_t pool_slot_for(int32_t unit, HeatEngine* heat);
/* A pool slot for a budgeted victim when the pool has none free: the host copy of a unit in a
* slot the KV cache lent, which keeps its place in VRAM without one -- a unit of `layer`, or
* of any layer when it is negative. -1 when no unit may give one. See the definition. */
int64_t donor_slot(size_t klass, int32_t layer, HeatEngine* heat);
/* A donor out of a lent slot into a free budgeted one, if one is free: false when none is. */
bool migrate(int32_t unit, HeatEngine* heat);
/* One promotion out of the unit's pool slot into `slot`, which the caller has taken. */
int promote_to(int32_t unit, int64_t slot);
/* Promote the hottest pooled units of one class into up to `room` free slots. */
+96 -18
View File
@@ -80,7 +80,7 @@ int strategy_parse(const char* s, Strategy* out) {
Budgets Budgets::from(const Config& c) {
Budgets b;
b.vram_weights = c.vram_weights_mib * 1024 * 1024;
b.host_pool = c.host_pool_mib * 1024 * 1024;
b.host_pool = c.host_pool_total_mib() * 1024 * 1024;
b.ssd = c.weights_disk_tier;
return b;
}
@@ -123,7 +123,7 @@ int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
}
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
TablePlacement ngram) {
TablePlacement ngram, bool host_backend, bool container) {
if (!out) return;
*out = WeightFootprint{};
@@ -146,7 +146,8 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
/* build_units: a model-level weight is its own unit, everything else groups by the declared
* (layer, expert). Ordered, for the same reason build_units is. */
struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false;
bool emb = false, ngram = false, host = true; };
bool emb = false, ngram = false, host = true, direct = true;
int access = -1; };
std::map<std::pair<int32_t, int32_t>, size_t> by_group;
std::vector<U> units;
@@ -175,7 +176,11 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
mu.bytes = align_up(mu.bytes, a) + weight_bytes(wi);
/* pin_mapped: THE WHOLE UNIT GOES, not the one weight. */
if (w < device_ok.size() && !device_ok[w]) mu.mapped = true;
if (!weight_file_direct(wi, prog.ctx.world_size)) mu.direct = false;
if (w < host_ok.size() && !host_ok[w]) mu.host = false;
/* build_units: the group's strongest access class, which says whether it is a tower's. */
if (mu.access < 0 || access_strength(wi.decl.access) > access_strength(mu.access))
mu.access = wi.decl.access;
/* The placement flags' tables: model-level, so the unit is this one weight. */
if (layer < 0) {
mu.emb = is_embedding_table(prog, w);
@@ -186,6 +191,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
/* And one align_up a unit, because that is how Mover::init spends the slab: `us.static_off =
* align_up(static_need, RAD_ALIGN_UNIT)` before every unit it places. A budget that summed raw
* bytes would be short by one alignment per unit, which on a 512-expert MoE is real. */
for (U& mu : units) mu.mapped = mapped_unit(mu.mapped, container && mu.direct, host_backend);
std::map<int32_t, int64_t> layer_experts;
std::set<int64_t> expert_strides;
bool ngram_host = true;
@@ -196,6 +202,8 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
if (mu.emb && !mu.mapped) out->embedding += b;
if (mu.ngram) out->ngram += b;
if (mu.ngram && !mu.mapped) out->ngram_device = true;
/* pin_towers moves an encoder tower's unit out of the statics on the same test. */
if (mu.access == RAD_ACCESS_PER_REQUEST && !mu.mapped && mu.expert < 0) out->tower += b;
/* pin_mapped: an n-gram table a device kernel reads stays off the card unless it was
* placed in VRAM. */
if (mu.mapped || (mu.ngram && ngram != TablePlacement::Vram)) out->mapped += b;
@@ -284,8 +292,8 @@ void Planner::resolve_sites(const Program& prog) {
* consulted, because it is not a budget question -- and so is an n-gram table --ngram-placement put
* in RAM or on disk, whatever kernels could read it on a card. The other three off-device tiers are
* what the planner falls back to when VRAM runs out; this one is where the weight has to be
* whatever the budgets say, and charging a pool for bytes that are never copied would make the
* operator size a pool against a number that does not exist.
* whatever the budgets say, and charging a pool for bytes that are never copied would size that
* pool against a number that does not exist.
*
* THE WHOLE UNIT GOES, not the one weight. A unit is the movement granularity and a half-mapped one
* has no meaning -- and it costs nothing here, because `device_ok_` is cleared for EVERY weight
@@ -295,9 +303,15 @@ void Planner::resolve_sites(const Program& prog) {
void Planner::pin_mapped(const Program& prog, Plan* p) {
const TablePlacement ng = in_.config->ngram_resolved;
for (MoveUnit& mu : p->units) {
bool host_only = false;
for (rad_weight w : mu.weights)
bool host_only = false, direct = in_.container;
for (rad_weight w : mu.weights) {
if (w < device_ok_.size() && !device_ok_[w]) host_only = true;
if (w < prog.weights.size() &&
!weight_file_direct(prog.weights[w], prog.ctx.world_size)) direct = false;
}
/* On the host backend a unit stored in another form than its host kernel reads is placed
* like any other weight, in the pool its kernel can read too (mapped_unit). */
host_only = mapped_unit(host_only, direct, in_.host_backend);
/* --ngram-placement keeps an n-gram table OFF THE CARD unless it says vram, whether or not
* a device kernel could read it there: ram and disk are where the operator put it, and the
* strategies below would otherwise spend the card on 48 GB of rows read sixteen a token. */
@@ -619,8 +633,8 @@ int Planner::assign_all_vram(Plan* p) {
used += mu.slot_bytes;
}
if (p->vram_budget > 0 && used > p->vram_budget) {
p->notes.push_back(fmt("all_vram needs %s of weights against a --vram-weights-mib "
"budget of %s: %s short",
p->notes.push_back(fmt("all_vram needs %s of weights against a weights pool "
"of %s: %s short",
humanb(used).c_str(), humanb(p->vram_budget).c_str(),
humanb(used - p->vram_budget).c_str()));
return RAD_E_NOMEM;
@@ -768,9 +782,9 @@ int Planner::assign_expert_tiered(Plan* p) {
rank_units(p, &order);
/* RESERVE THE SPARE SLOTS OUT OF THE BUDGET. The slab has to hold the residents AND the
* shadow slots a promotion writes into, and they all come out of --vram-weights-mib -- so a
* shadow slots a promotion writes into, and they all come out of the weights pool -- so a
* fill that spends the whole budget on residents leaves the mover with nowhere to move into
* and, worse, makes the mover's allocation overrun the pool the operator sized.
* and, worse, makes the mover's allocation overrun the weights pool.
*
* Two passes, and the second is enough: the reserve depends only on the first pass's slot
* counts, and the first pass over-counts (it had more room), so the reserve it produces is an
@@ -900,7 +914,7 @@ int Planner::assign_expert_tiered(Plan* p) {
k = fill(uncapped, --cap);
if (fixed + k.used + k.spare + k.file > p->vram_budget) {
p->notes.push_back(fmt("the file tier's two layer buffers need %s, beside %s of "
"fixed weights, against a --vram-weights-mib budget of %s",
"fixed weights, against a weights pool of %s",
humanb(k.file).c_str(), humanb(fixed).c_str(),
humanb(p->vram_budget).c_str()));
return RAD_E_NOMEM;
@@ -1065,7 +1079,7 @@ void Planner::finish(const Program& prog, Plan* p) {
pl.reason = mu.reason;
pl.bytes = weight_bytes(prog.weights[w]);
p->totals.bytes[(int)mu.tier] += pl.bytes;
if (mu.host_forced) p->embedding_host_used += pl.bytes;
if (mu.host_forced) p->forced_host_used += pl.bytes;
}
}
}
@@ -1119,8 +1133,8 @@ int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) cons
mu.host_forced = true;
mu.reason = "--embedding-placement ram; read over the link in place";
RAD_INFO("placement: '%s' (%s) in the pinned host pool, read in place "
"(--embedding-placement %s)", name.c_str(), humanb(mu.bytes).c_str(),
cfg.embedding_placement == TablePlacement::Auto ? "auto" : "ram");
"(--embedding-placement ram%s)", name.c_str(), humanb(mu.bytes).c_str(),
cfg.embedding_placement_given ? "" : ", the default");
}
/* Engine::plan resolves Ram only where weight_footprint found a table with this same test,
* so an empty pass is a plan built from a different program than the budget was: a wiring
@@ -1134,6 +1148,53 @@ int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) cons
return rc;
}
/* --vision-tower-placement ram: EVERY UNIT OF AN ENCODER TOWER goes to the pinned host pool before
* any strategy runs, as the embedding does, at the DeviceZeroCopy site: the encoder's kernels read
* the weights over the link in place, once an image or a clip, and a text-only request never
* touches them. A tower's unit is one whose every weight the architecture declared read once per
* request (RAD_ACCESS_PER_REQUEST) -- the test weight_footprint counted out of the statics with,
* so the budget the card was split by is the one spent here. The test is the access class and not
* the unit's level: a tower is model-level weights (a stem, a merger) and a layer unit a block. */
int Planner::pin_towers(const Config& cfg, Plan* p) const {
if (cfg.tower_resolved != TablePlacement::Ram) return RAD_OK;
auto tower = [](const MoveUnit& mu) {
return mu.access == RAD_ACCESS_PER_REQUEST && mu.expert < 0 && mu.tier != Tier::Mapped &&
!mu.host_forced;
};
int64_t need = 0, n = 0;
for (const MoveUnit& mu : p->units)
if (tower(mu)) { need += mu.slot_bytes; ++n; }
/* Engine::plan resolves Ram only where weight_footprint found a tower with this same test. */
if (!n) {
RAD_ERR("placement: --vision-tower-placement ram, and this rank's program has no weight it "
"reads once per request");
p->notes.push_back("--vision-tower-placement ram: no encoder tower to place");
return RAD_E_STATE;
}
if (need > p->host_budget) {
RAD_ERR("placement: --vision-tower-placement ram: the encoder towers need %s of the pinned "
"host pool and %s of it is left%s", humanb(need).c_str(),
humanb(p->host_budget).c_str(),
p->file_stage_reserve ? " after the file tier's staging" : "");
p->notes.push_back(fmt("--vision-tower-placement ram: the encoder towers (%s) do not fit "
"the host pool", humanb(need).c_str()));
return RAD_E_NOMEM;
}
for (MoveUnit& mu : p->units) {
if (!tower(mu)) continue;
p->host_budget -= mu.slot_bytes;
p->tower_host_bytes += mu.slot_bytes;
mu.tier = Tier::HostPinned;
mu.site = Site::DeviceZeroCopy;
mu.movable = false;
mu.host_forced = true;
mu.reason = "--vision-tower-placement ram; read over the link in place";
}
RAD_INFO("placement: the encoder towers, %lld units (%s), in the pinned host pool, read in place "
"(--vision-tower-placement ram)", (long long)n, humanb(need).c_str());
return RAD_OK;
}
/* ------------------------------------------------------------------ plan */
int Planner::plan(Plan* out) {
if (!out || !in_.program || !in_.config) return RAD_E_INVAL;
@@ -1208,7 +1269,9 @@ int Planner::plan(Plan* out) {
}
/* NOT a RAD_TRY: a refusal still leaves `out` filled in far enough to print. */
const int hrc = pin_embedding(prog, cfg, out);
int hrc = pin_embedding(prog, cfg, out);
const int trc = pin_towers(cfg, out);
if (hrc >= 0) hrc = trc;
int rc = assign(out);
enforce_op_site_agreement(prog, out);
@@ -1235,6 +1298,17 @@ int Planner::assign(Plan* p) {
else if (has_conditional) s = Strategy::ExpertTiered;
else s = Strategy::LayerOffload;
p->strategy = s;
p->strategy_why =
s == Strategy::AllVram
? fmt("%s of weights fit the %s weights pool", humanb(total).c_str(),
humanb(p->vram_budget).c_str())
: s == Strategy::ExpertTiered
? fmt("%s of weights against a %s weights pool: routed experts, read only when "
"selected, are what spills to host memory", humanb(total).c_str(),
humanb(p->vram_budget).c_str())
: fmt("%s of weights against a %s weights pool and no routed experts to spill: "
"whole layers are offloaded", humanb(total).c_str(),
humanb(p->vram_budget).c_str());
RAD_DEBUG("placement: auto chose %s (%s of weights against a %s budget)",
strategy_name(s), humanb(total).c_str(), humanb(p->vram_budget).c_str());
}
@@ -1243,7 +1317,8 @@ int Planner::assign(Plan* p) {
/* Every pool is budgeted explicitly (spec §6). An offload strategy with no number to
* spill against would have to infer one from free VRAM, and an engine that quietly
* re-optimises its own split is an engine whose benchmarks do not reproduce. */
RAD_ERR("placement: %s needs --vram-weights-mib; there is nothing to spill against",
RAD_ERR("placement: %s needs a weights budget and none was resolved; there is nothing to "
"spill against",
strategy_name(s));
return RAD_E_INVAL;
}
@@ -1309,7 +1384,7 @@ std::string Plan::report(const Program& prog) const {
humanb(totals.bytes[(int)Tier::VRAM]).c_str());
s += fmt(" host pinned %12s %12s\n",
host_budget > 0 ? humanb(host_budget).c_str() : "none",
humanb(totals.bytes[(int)Tier::HostPinned] - embedding_host_used).c_str());
humanb(totals.bytes[(int)Tier::HostPinned] - forced_host_used).c_str());
if (totals.bytes[(int)Tier::HostPageable])
s += fmt(" host pageable %12s %12s\n", "-",
humanb(totals.bytes[(int)Tier::HostPageable]).c_str());
@@ -1334,6 +1409,9 @@ std::string Plan::report(const Program& prog) const {
if (embedding_host_bytes)
s += fmt(" embedding %12s %12s (--embedding-placement ram, pinned, read in place)\n",
"-", humanb(embedding_host_bytes).c_str());
if (tower_host_bytes)
s += fmt(" encoder tower %12s %12s (--vision-tower-placement ram, pinned, read in place)\n",
"-", humanb(tower_host_bytes).c_str());
if (ngram_copy_bytes)
s += fmt(" n-gram copy %12s %12s (--ngram-placement ram, %s, filled at load)\n",
"-", humanb(ngram_copy_bytes).c_str(),
Loaded 100 of 338 files, more files were not shown because too many files have changed in this diff. Show more