radiance 1.13.0

New models:
- Tencent Hy-Memory (HYV3) from its BF16, FP8 and GGUF checkpoints, with its native tool calls
- M2XFP4: metadata-augmented MXFP4 weights for Qwen3.8-27B and its DFlash2 drafter (top-1 89.1% ->
  92.4% against plain MXFP4), its quantiser and recipe, and ParoQuant's M2XFP4 checkpoints
- Gemma 4 E2B/E4B audio input; NVIDIA-Nemotron-3.5-Bolt-E4B in int8 and 4-bit, on two cards by
  default; Ornith-1.5-122B compose files

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

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

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

Changes: Plugin ABI 31: out-of-tree plugins must be rebuilt. RADIANCE_PREFETCH_BESIDE is
--weight-prefetch now; RADIANCE_NO_HUGE_PAGES, RADIANCE_IDS_EARLY, RADIANCE_ATTN_BAND_SPLIT,
R4D_PREFILL_SPLITS, RAD_PLE_TIMING and RAD_PLE_CACHE_ROWS are gone.
This commit is contained in:
Deadcode committed 2026-10-27 16:47:35 +01:00
198 files changed
+20904 -3240

No files matched your search

+128 -12
View File
@@ -608,18 +608,8 @@ constexpr int64_t kPrefetchRows = 16;
* would read in series on lane 0, so elsewhere the read goes on lane 1, behind a join from lane
* 0. */
inline bool prefetch_lane0() { return rad_chain_on() != 0; }
/* RADIANCE_PREFETCH_BESIDE=0 issues none of these reads. Beside another server on the same card
* the lane-1 form costs more than it gains: the card has fewer hardware queue slots than the two
* servers have queues, and the join puts a queue switch into every decode step. */
inline bool prefetch_beside_on() {
static const bool on = [] {
const char* e = std::getenv("RADIANCE_PREFETCH_BESIDE");
return !(e && e[0] == '0' && e[1] == 0);
}();
return on;
}
inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
if (!op || T > kPrefetchRows || !prefetch_beside_on()) return;
if (!op || T > kPrefetchRows) return;
if (prefetch_lane0()) {
RAD_ISSUE(c, op, RAD_W(w));
return;
@@ -627,7 +617,8 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w));
rad_lane(c, 0);
}
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. */
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. A plugin declares
* none where the deployment turns the reads off (RadBuildCtx::weight_prefetch_off). */
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
@@ -673,6 +664,9 @@ struct Geom {
int64_t max_tok = 0;
int64_t max_seqs = 0;
int64_t max_ctx = 0;
/* --kv-resident in tokens (RadBuildCtx::kv_resident_blocks), 0 when nothing streams: what
* kv_resolve_declare states as the ring's depth. */
int64_t kv_resident = 0;
int max_spec = 0;
/* Most rows the sampler can want in one step: one per sequence, or one per draft position per
* sequence at a speculative verify. Bounds the logits buffer (at a 248K vocab, 63 MiB rather
@@ -949,6 +943,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
g.max_tok = c->max_tok;
g.max_seqs = c->max_seqs;
g.max_ctx = c->max_ctx;
g.kv_resident = c->kv_resident_blocks;
g.max_spec = c->max_spec;
g.max_logit_rows = c->max_seqs * (c->max_spec > 0 ? c->max_spec + 1 : 1);
if (g.max_logit_rows > c->max_tok) g.max_logit_rows = c->max_tok;
@@ -1069,6 +1064,95 @@ inline int64_t vocab_head_rows(const Geom& g) {
* handle. */
inline RadOperand kv_cache(rad_kvgroup group, int layer) { return RAD_KV(group, layer); }
/* One layer of a streamed group (RadKVStream): its rows of the host mirror and the ring's maps.
* The mirror is layer-major over the group's bound layers in KVPoolBinding::layer_slot order, not
* over model layers (Flash-Next's full-attention layers are every other layer, plus the MTP head),
* so the row comes from rad_kv_layer_index. `host` is null when the group does not stream on this
* rank or has no row for the layer. */
struct KVStreamLayer {
const RadKVStream* st = nullptr;
const uint8_t* host = nullptr; /* [blocks, bbytes] mirror row */
int32_t* res = nullptr; /* [blocks] block -> ring slot, -1 when absent */
int32_t* slot_block = nullptr; /* [slots] ring slot -> block */
int32_t* slot_state = nullptr; /* [slots, 2] */
int64_t blocks = 0, bbytes = 0, slots = 0;
};
inline KVStreamLayer kv_stream_layer(RadCtx* c, rad_kvgroup group, int layer,
const RadKVGroupBatch* kvb) {
KVStreamLayer L;
const RadKVStream* st = kvb ? kvb->stream : nullptr;
if (!st || !st->host || st->block_bytes <= 0) return L;
const int64_t li = rad_kv_layer_index(c, group, layer);
if (li < 0) return L;
L.st = st;
L.bbytes = st->block_bytes;
L.blocks = st->host_layer_stride / L.bbytes;
L.slots = st->slots;
L.host = st->host + li * st->host_layer_stride;
L.res = st->res + li * L.blocks;
L.slot_block = st->slot_block + li * L.slots;
L.slot_state = st->slot_state + li * L.slots * 2;
return L;
}
/* The prefill stage of a streamed group (the ordering rule is in core/kvstream/stage.h):
*
* kv_stage_wait -- immediately before the layer's store: the copy from the mirror must land
* before the store writes this chunk's newer bytes into the stage;
* kv_stage_layer -- before the attention: true when the pass uses the stage, so the caller
* reads block ids directly and must not resolve;
* kv_stage_next -- after every attention launch of the layer: the next layer's copy starts
* once the last read of the aliased stage is behind it.
*
* Both of the first two are rad_kv_stage_layer, which stages a layer once per pass. */
inline bool kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer) {
return rad_kv_stage_layer(c, group, kvb, layer) != 0;
}
inline bool kv_stage_wait(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer) {
return rad_kv_stage_layer(c, group, kvb, layer) != 0;
}
inline void kv_stage_next(RadCtx* c, rad_kvgroup group, int layer) {
(void)rad_kv_stage_next(c, group, layer);
}
/* The `kv_resolve` a streamed group's block declares. None of its geometry is free:
*
* blocks the block-id space a selection can name: max_seqs sequences of the context;
* slots the ring --kv-resident carves, in whole blocks, raised to one decode step's
* selection (max_seqs x (1 + n_spec) x sel_pitch) as kvstream_ring raises it, and
* at most `blocks`; the resolve is issued with the pool's depth, so declaring the
* context would size its scratch for slots it cannot reach;
* sel_pitch the selection row's pitch, which the attention declares its rows with
* (`qsa_topk + 1` on the sparse path, the indexer's count on GLM).
*
* The kernel sizes its claim list from these (`M * sel_pitch`, r4d_kv_resolve.hip's
* kv_claim_cap); ctl[12] reports the largest claim count a launch made, so a wrong declaration
* shows in the engine's stream report. `sel` is read as well as written, so the arena keeps it
* live from its producer to the attention. Returns 0 when the op is not declared or the group has
* nothing to address. */
inline rad_op kv_resolve_declare(RadBuilder* b, const Geom& g, rad_kvgroup kv, rad_buf sel,
rad_buf nsel, int64_t sel_pitch) {
if (!rad_op_declared(b, "kv_resolve") || !sel || !nsel || sel_pitch <= 0) return 0;
const int64_t bs = rad_kv_block_size(b, kv);
const int64_t bbytes = rad_kv_layer_bytes(b, kv);
const int64_t blocks = bs > 0 ? g.max_seqs * ((g.max_ctx + bs - 1) / bs) : 0;
if (bs <= 0 || bbytes <= 0 || blocks <= 0) return 0;
const int64_t ring = g.kv_resident > 0 ? (g.kv_resident + bs - 1) / bs : 0;
const int64_t step = g.max_seqs * (1 + (g.max_spec > 0 ? g.max_spec : 0)) * sel_pitch;
const int64_t want = ring > 0 && step > ring ? step : ring;
const int64_t slots = want > 0 && want < blocks ? want : blocks;
const rad_op op = RAD_OP(b, "kv_resolve",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", blocks),
RAD_INT("slots", slots), RAD_INT("sel_pitch", sel_pitch),
RAD_INT("block_bytes", bbytes)),
RAD_NOWEIGHTS);
if (!op) return 0;
const rad_buf rd[2] = { sel, nsel };
rad_op_reads(b, op, rd, 2);
rad_op_writes(b, op, &sel, 1);
return op;
}
/* ================================================================== step-sized operands */
/* Every operand a step issues carries the step's row count, not the buffer's.
*
@@ -1134,6 +1218,16 @@ inline RadOperand praw(const void* p, uint32_t dtype, int64_t rows) {
return o;
}
/* kv_resolve over `rows` selection rows (kv_resolve_declare): makes the blocks they name resident
* in the ring and rewrites `sel` from block ids to ring slots. */
inline void kv_resolve_issue(RadCtx* c, rad_op op, const KVStreamLayer& L, RadOperand sel,
RadOperand nsel, rad_kvgroup group, int layer, int64_t rows) {
RAD_ISSUE_N(c, op, rows, sel, nsel, praw(L.res, RAD_I32, L.blocks),
praw(L.slot_block, RAD_I32, L.slots), praw2(L.slot_state, RAD_I32, L.slots, 2),
praw(L.st->ctl, RAD_I32, 16), praw2(L.host, RAD_U8, L.blocks, L.bbytes),
kv_cache(group, layer));
}
/* Rotary positions of a pass, in the two forms consumers take.
*
* `rope_pos1`: one component per token, RadBatch::rope_pos's plane 0 if present, else
@@ -1317,6 +1411,28 @@ inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
return nullptr;
}
/* ================================================================== calibration in slices */
/* The layers [lo, hi) of n a calibration taps: the environment variable `var` as "lo:hi", else
* all of them. A large model's Grams do not fit beside its weights at once, so it is calibrated
* in slices of layers, the corpus pushed through once a slice. */
inline int calib_layers(const char* who, const char* var, int64_t n, int64_t* lo, int64_t* hi) {
*lo = 0;
*hi = n;
const char* s = std::getenv(var);
if (!s) return RAD_OK;
long long l = 0, h = 0;
int used = 0;
if (std::sscanf(s, "%lld:%lld%n", &l, &h, &used) != 2 || s[used] != '\0' || l < 0 || h > n ||
l >= h) {
fprintf(stderr, "radiance: %s: %s '%s' is not lo:hi within 0:%lld\n", who, var, s,
(long long)n);
return RAD_E_INVAL;
}
*lo = l;
*hi = h;
return RAD_OK;
}
/* ================================================================== a block drafter */
/* A drafter's Geom: the target's (n_embd, vocabulary, deployment bounds, rank, wire) with the
* layer, head, feed-forward, norm and rotary geometry of the container's `draft.` config, split
+165 -45
View File
@@ -21,21 +21,17 @@
#include "rad_fp8.h"
#include <cstdlib>
#include <cstring>
namespace rad {
namespace arch {
/* RADIANCE_ATTN_BAND_SPLIT=0 issues a mixed step's dense attention as one launch at the step's
* widest band, as before the per-band issue in AttnGatedFP8::step; unset or anything else splits.
* An A/B and debugging knob, not configuration. Read once. */
inline bool attn_band_split() {
static const bool on = [] {
const char* e = std::getenv("RADIANCE_ATTN_BAND_SPLIT");
return !(e && !std::strcmp(e, "0"));
}();
return on;
/* Whether the streamed store has a row for this cache layout: libr4d's are E4M3 and bf16 only. A
* packed cache (fp8_v4, k6_v4) must not declare it, since a weightless op with no row is a hole
* that refuses startup even with --kv-resident off; kvstream_configure then names the layout. */
inline bool kv_store_streamed_dtype(const char* kv_dtype) {
return kv_dtype && (std::strcmp(kv_dtype, "fp8_e4m3") == 0 ||
std::strcmp(kv_dtype, "bf16") == 0);
}
struct AttnGatedFP8 {
@@ -81,6 +77,7 @@ struct AttnGatedFP8 {
* block table and context length: same op, same kernel, different list. `sel` is `topk + 1`
* wide and the kernel takes its block-table pitch from the operand. */
rad_buf qsa_sel = 0;
rad_buf qsa_nsel = 0; /* [max_tok] i32, the valid entries of each `qsa_sel` row */
rad_buf qsa_sequ = 0;
/* Context length up to which dense attention gives the same result, `budget + ratio - 1`.
* Below it every complete block is selected, the paths agree to the bit, and dense is cheaper
@@ -122,10 +119,19 @@ struct AttnGatedFP8 {
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
rad_op op_fused_kv = 0; /* the same with kv_store folded in */
/* The same with the streamed store folded in, issued instead when the batch hands this group a
* stream (its mirror and map are the batch's). */
rad_op op_fused_stream = 0;
int64_t fused_rows = 0; /* widest T the fused ops take */
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
rad_op op_attn = 0, op_kv_store = 0, op_gq = 0;
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */
/* kv_store_streamed: the host mirror always, the ring slot when `res` says the block is resident
* (docs/OPS.md). Zero when no row serves it; a streamed group then fails the step. */
rad_op op_kv_stream = 0;
/* kv_resolve: this layer's selection made resident and rewritten as ring slots, issued before
* each sparse launch. */
rad_op op_resolve = 0;
/* The output gate as `sigmoid` then `mul`: the bf16-linear form (Geom::w_bf16), and with fp8
* linears the chain gate_quant_fp8 fuses, where it is not served. `gate` is the sigmoid's
* output (the wire's with bf16 linears, the block's own otherwise) and `q_gate` the chain's
@@ -155,6 +161,13 @@ struct AttnGatedFP8 {
* by passes that only leave layer state behind, such as the MTP head's history pass over a
* prompt chunk with no drafting row. */
void store_kv(RadCtx* c, const RadBatch* batch) const;
/* The layer's cache store, before its resolve and attention: `kv_store`, or for a streamed
* group the stage wait and `kv_store_streamed`. */
void store_cache(RadCtx* c, const RadKVGroupBatch* kvb, const int32_t* slot, int64_t T) const;
/* A staged pass reads the pool at block-id identity, while the streamed store writes only
* where the residency map names a ring slot (none before the group's first decode). This
* stores the same bytes at identity, after the mirror writer. */
void store_stage_identity(RadCtx* c, const int32_t* slot, int64_t T) const;
/* The block's tail, declared last by every rank: the all-reduce and the trailing add. */
int declare_out(RadBuilder* b, bool add_out);
@@ -174,7 +187,8 @@ struct AttnGatedFP8 {
* normed pieces (ArPieces::in_ready): one prefill sequence in two pieces, each the chunk a
* span of 1 makes, on the unfused prologue with one rotary component per token (every token's
* components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and
* the gate quantised by gate_quant_fp8. */
* the gate quantised by gate_quant_fp8. A streamed group never takes it: the pieces path's
* plain store never writes the host mirror. */
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
const int64_t T = batch->n_tok;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
@@ -182,7 +196,7 @@ struct AttnGatedFP8 {
T <= 2 * pieces->rows && !op_add && !op_fill && op_gq && !op_sig && !qsa_sel &&
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL &&
!(T <= fused_rows) && batch->positions && !rope_mixed(batch) &&
kvb && kvb->slot_mapping && kvb->block_table && kvb->seqused;
kvb && !kvb->stream && kvb->slot_mapping && kvb->block_table && kvb->seqused;
}
};
@@ -338,11 +352,18 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
* ids: an aperture violation outside the cache. rad_op_reads rather than rw() because the list
* depends on whether the layer has an indexer. */
if (op_attn) {
const rad_buf rd[3] = { w.q, qsa_sel, qsa_sequ };
rad_op_reads(b, op_attn, rd, (qsa_sel && qsa_sequ) ? 3 : 1);
const rad_buf rd[4] = { w.q, qsa_sel, qsa_sequ, qsa_nsel };
rad_op_reads(b, op_attn, rd,
(qsa_sel && qsa_sequ) ? (qsa_nsel ? 4 : 3) : 1);
rad_op_writes(b, op_attn, &w.attn.x, 1);
}
/* The resolve belongs here rather than in the indexer: it must follow this layer's store,
* since a block copied in from the mirror has to carry this step's tokens. Its band is the
* step's widest launch and its row `qsa_topk + 1` wide, as the attention declares. */
if (qsa_sel && qsa_nsel)
op_resolve = kv_resolve_declare(b, g, kv, qsa_sel, qsa_nsel, qsa_topk + 1);
op_kv_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
@@ -351,6 +372,19 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
RAD_NOWEIGHTS),
{w.k, w.v}, {});
/* The streamed store: kv_store's operands and parameters plus the residency map and the layer's
* mirror row, which the batch carries (store_cache). `block_size` does not bind the group;
* `attn_paged` already has. Only for a layout with a row (kv_store_streamed_dtype). */
if (kv_store_streamed_dtype(g.kv_dtype) && rad_op_declared(b, "kv_store_streamed"))
op_kv_stream = rw(b, RAD_OP(b, "kv_store_streamed",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.k, w.v}, {});
/* The fused prologue with the cache store folded in: a k head's block already holds its
* token's rotated k, so it also writes k and v into the cache, byte-identical to kv_store.
* Declared here because the cache block size is read back from the attention op above.
@@ -367,6 +401,21 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
RAD_WEIGHTS(w_q_norm, w_k_norm)),
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
/* The fold for a streamed group: also writes the mirror and consults the residency map, whose
* operands are added at issue. Gated on the same layouts. */
if (op_fused && kv_store_streamed_dtype(g.kv_dtype) &&
rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed"))
op_fused_stream = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store_streamed",
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
RAD_INT("n_head_kv", g.n_head_kv), RAD_INT("rot", n_rot),
RAD_STR("q_dtype", g.dtype), RAD_F64("eps", g.eps),
RAD_F64("wadd", g.wadd_qk), RAD_INT("cs_f32", 1),
RAD_INT("block_size", rad_kv_block_size(b, kv)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_WEIGHTS(w_q_norm, w_k_norm)),
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
/* Output gate, multiply and quantiser in one pass (`gate_quant_fp8`); at decode the dispatch
* gaps between three small ops are comparable to the work. Each row is a (token, head) pair:
* the gate is a fixed stride inside [q|gate], the attention output is contiguous, and the
@@ -481,6 +530,34 @@ inline int AttnGatedFP8::declare_out(RadBuilder* b, bool add_out) {
return RAD_OK;
}
inline void AttnGatedFP8::store_stage_identity(RadCtx* c, const int32_t* slot, int64_t T) const {
RAD_ISSUE_N(c, op_kv_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
kv_cache(kv, layer));
}
inline void AttnGatedFP8::store_cache(RadCtx* c, const RadKVGroupBatch* kvb,
const int32_t* slot, int64_t T) const {
if (!kvb || !kvb->stream) {
RAD_ISSUE(c, op_kv_store,
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
return;
}
/* A streamed group writes its host mirror, and the ring slot only where the block is resident
* (docs/OPS.md "kv_store_streamed"). kv_store alone would treat a block id as a ring slot, so
* a build without the streamed store fails the step. */
const bool staged = kv_stage_wait(c, kv, kvb, layer);
const KVStreamLayer L = kv_stream_layer(c, kv, layer, kvb);
if (!op_kv_stream || !L.host || L.blocks <= 0) {
rad_step_fail(c, "kv streaming: this layer's KV group streams but the build has no "
"kv_store_streamed row to write its host mirror with");
return;
}
RAD_ISSUE(c, op_kv_stream,
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer),
praw(L.res, RAD_I32, L.blocks), praw2(L.host, RAD_U8, L.blocks, L.bbytes));
if (staged) store_stage_identity(c, slot, T);
}
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);
@@ -491,8 +568,7 @@ inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
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));
store_cache(c, kvb, slot, T);
}
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
@@ -567,8 +643,24 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
* token, so a pass with media tokens (differing components) takes the unfused path with the
* full [3, T] positions. */
const bool fuse_ok = T <= fused_rows && !rope_mixed(batch);
const bool fused_kv = op_fused_kv && fuse_ok;
if (fused_kv) {
/* A streamed group folds the streamed store into the prologue instead (op_fused_stream); one
* whose layer has no mirror row leaves the store to store_cache, which fails the step. */
const bool streamed = kvb && kvb->stream;
const bool fused_kv = op_fused_kv && fuse_ok && !streamed;
const KVStreamLayer L = streamed && op_fused_stream && fuse_ok
? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{};
const bool folded_stream = L.host && L.blocks > 0;
if (folded_stream) {
/* The prologue is the store, so the stage copy must land before it (kv_stage_wait). */
const bool staged = kv_stage_wait(c, kv, kvb, layer);
RAD_ISSUE_N(c, op_fused_stream, T,
brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_W(w_q_norm), RAD_W(w_k_norm),
brows(w.q, T), brows(w.k, T), RAD_NONE,
brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer),
praw(L.res, RAD_I32, L.blocks), praw2(L.host, RAD_U8, L.blocks, L.bbytes));
if (staged) store_stage_identity(c, slot, T);
} else if (fused_kv) {
RAD_ISSUE_N(c, op_fused_kv, T,
brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_W(w_q_norm), RAD_W(w_k_norm),
@@ -588,9 +680,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
}
if (!fused_kv)
RAD_ISSUE(c, op_kv_store,
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
if (!fused_kv && !folded_stream) store_cache(c, kvb, slot, T);
/* Sparse attention issues one row per query. `attn_paged` indexes its block table and length
* by row, and a row need not be a sequence, so T queries issued as T rows of q_len 1, each with
@@ -604,9 +694,31 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
* `q_len` (rows = max_seqs * q_len_max * heads); more rows are refused as RAD_E_SCRATCH at
* issue. Rows of q_len 1 up to the declared max_seqs always fit. */
const int64_t reach = (int64_t)batch->max_ctx_len + batch->max_q_len;
/* A pass on a streamed group's ring (a ring smaller than the id space, and not staged) must
* take the sparse path: on the ring a block id is not a pool address, so the dense path would
* read ring slots as pages. `T == n_seq` alone misses a verify pass, whose T is
* n_seq x (1 + n_spec), on a context under qsa_exact_to. A ring that covers the context keeps
* the dense path, where ids and slots coincide. */
const RadKVStream* st = kvb ? kvb->stream : nullptr;
const int64_t st_blocks =
(st && st->block_bytes > 0) ? st->host_layer_stride / st->block_bytes : 0;
const bool ring_addressed = st && st->slots > 0 && st_blocks > 0 && st->slots < st_blocks;
const bool ring_bound = ring_addressed && !kv_stage_layer(c, kv, kvb, layer);
const bool sparse = qsa_sel && qsa_sequ &&
(T == batch->n_seq || qsa_exact_to <= 0 || reach > qsa_exact_to);
(ring_bound || T == batch->n_seq || qsa_exact_to <= 0 ||
reach > qsa_exact_to);
const bool gated = sparse && op_attn_gq;
/* A streamed group's selection, per launch: make the rows' blocks resident and rewrite `sel`
* as ring slots, after this layer's store (a block copied in from the mirror must carry this
* step's tokens) and before the attention. A pass on the stage view leaves `sel` as block ids
* and never resolves, so a prefill cannot overflow the ring. */
const KVStreamLayer res_l = op_resolve ? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{};
auto resolve_sel = [&](int64_t off, int64_t rows) {
if (kv_stage_layer(c, kv, kvb, layer)) return;
if (!res_l.host || res_l.blocks <= 0 || res_l.slots <= 0 || rows <= 0) return;
kv_resolve_issue(c, op_resolve, res_l, brow_slice(qsa_sel, off, rows, qsa_topk + 1),
brow_slice(qsa_nsel, off, rows, 1), kv, layer, rows);
};
/* A piece at a time where the caller takes the all-reduce that way (ArPieces). On the gated
* sparse path every query row is its own (q_len 1) and the gate rides in the merge, so the
* attention and out projection can finish a piece's rows and hand off its reduction while the
@@ -619,6 +731,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
const int64_t pn = T - p0 < pieces->rows ? T - p0 : pieces->rows;
for (int64_t off = p0; off < p0 + pn; off += chunk) {
const int64_t rows = (p0 + pn - off) < chunk ? (p0 + pn - off) : chunk;
resolve_sel(off, rows);
RAD_ISSUE_N(c, op_attn_gq, 1,
brow_slice(w.q, off, rows, qw),
kv_cache(kv, layer),
@@ -633,6 +746,8 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
o.step(c, w.attn, w.h.x, T, p0, pn);
if (p0 + pn < T) pieces->hand(p0, pn);
}
/* Every attention launch of this layer is issued: start the next layer's stage copy. */
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
return;
}
if (gated) {
@@ -640,6 +755,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
const int64_t qw = g.q_dim(), hd = g.head_dim;
for (int64_t off = 0; off < T; off += chunk) {
const int64_t rows = (T - off) < chunk ? (T - off) : chunk;
resolve_sel(off, rows);
RAD_ISSUE_N(c, op_attn_gq, 1,
brow_slice(w.q, off, rows, qw),
kv_cache(kv, layer),
@@ -656,6 +772,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
const int64_t qw = g.q_dim();
for (int64_t off = 0; off < T; off += chunk) {
const int64_t rows = (T - off) < chunk ? (T - off) : chunk;
resolve_sel(off, rows);
RAD_ISSUE_N(c, op_attn, 1,
brow_slice(w.q, off, rows, qw),
kv_cache(kv, layer),
@@ -665,34 +782,35 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
brow_slice(w.attn.x, off, rows, qw));
}
} else {
/* A mixed step once per band, as the GDN blocks issue theirs (rad_block_gdn_fp8.h): one
* launch at the chunk's band would serve the decode rows by the query-tiled prefill kernel,
* one workgroup a kv head walking each decode sequence's whole context, the step's tail
* beside a chunk of thousands of rows (one sequence decoding at 188k beside a 25k prompt's
* 2048-row chunks: 512 ms a mixed step against 218 ms at 0.7k of context, the prompt's
* prefill 5.1 -> 11.3 s). The decode half, sequences [0, D) and rows [0, DT), is the prefix:
* its own band (the split-KV decode row) over its rows, tables and cu. The prefill half
* takes its per-sequence arrays past the decode sequences and keeps q, out and cu at their
* absolute rows (the kernels index q and out by cu, and the merge of a split launch keeps
* to cu's span).
/* Below qsa_exact_to the dense path reads block ids straight from the table and never
* resolves, so a staged pass stages this layer here (a no-op without a stage view). A
* ring-bound pass with no selection to resolve cannot be served at all. */
if (ring_bound) {
rad_step_fail(c, "kv streaming: a pass on the streamed group's ring has no selection "
"to resolve, so its block ids are not pool addresses");
} else if (kvb && kvb->stream) {
(void)kv_stage_layer(c, kv, kvb, layer);
}
/* A mixed step issues its attention once per band, as the GDN blocks do: one launch at
* the chunk's band would walk every decode sequence's whole context with one query-tiled
* workgroup a KV head, the step's tail beside a long chunk. The decode half (sequences
* [0, D), rows [0, DT)) is a prefix at its own band. The prefill half takes its
* per-sequence arrays past the decode sequences and keeps q, out and cu at their absolute
* rows, as the kernels index q and out by cu.
*
* The prefill half is issued at the op's top band (max_tok), not at its own query length:
* a launch over part of the step (q and out whole, cu past row 0, as ArPieces issues its
* pieces) is served by the query-tiled row, while the band of a short chunk (10 rows or
* fewer at gqa 6) is the split-KV decode row's, whose partials are laid out by the step's
* rows and sized at declare for its own band: 1.10-next6u issued it there and stopped
* under load on RAD_E_SCRATCH. Kernels read exact lengths from cu, so the loose band costs
* nothing. A chunk no longer than the verify blocks beside it keeps the one launch at
* their band, as before the split: the whole step is decode-shaped then.
*
* Pure steps issue one launch, as before. */
* The prefill half is issued at the op's top band, not at its own query length: a launch
* over part of the step must be served by the query-tiled row, while a short chunk's band
* (10 rows or fewer at gqa 6) is the split-KV decode row's, whose partials are sized at
* declare for that band and would overflow the scratch. Kernels read exact lengths from
* cu, so the loose band costs nothing. A chunk no longer than the verify blocks beside it
* keeps one launch at their band: the whole step is decode-shaped then. */
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
const int64_t pitch = kvb ? kvb->block_table_pitch : 0;
const int32_t qp = batch->max_q_len_prefill > 0 ? batch->max_q_len_prefill
: batch->max_q_len;
if (batch->phase == RAD_PHASE_MIXED && D > 0 && D < batch->n_seq &&
batch->max_q_len_decode > 0 && qp > batch->max_q_len_decode && attn_band_split()) {
batch->max_q_len_decode > 0 && qp > batch->max_q_len_decode) {
const int64_t P = batch->n_seq - D;
RAD_ISSUE_N(c, op_attn, batch->max_q_len_decode,
brows(w.q, DT), kv_cache(kv, layer),
@@ -711,13 +829,15 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
praw2(table, RAD_I32, batch->n_seq, pitch),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
/* cu_seqlens: the batch may be ragged (verify rows of different
* lengths; a chunk beside decode rows at RADIANCE_ATTN_BAND_SPLIT=0). */
/* cu_seqlens: verify rows may be of different lengths. */
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn.x, T));
}
}
/* Every attention launch of this layer is issued: start the next layer's stage copy, which
* crosses the link under the out projection and the next layer's projections. */
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
if (gated) {
/* the sparse attention gated and quantised in its merge */
} else if (op_sig) {
+22 -2
View File
@@ -109,6 +109,11 @@ struct GdnFP8 {
rad_weight w_norm = 0, w_ab = 0, w_conv = 0;
/* The input was normed and quantised by the caller; this block declares no norm. */
bool ext_in = false;
/* Set by the architecture before declare: the a|b projection runs on the second lane beside the
* in-projection at decode and verify sizes. Not where lane 1 carries collectives, which the
* projection would queue behind. Its concurrent buffers cost memory (at Qwen3.8-27B TP2: +70
* MiB arena and +33 MiB queues a card) for about +1 % at one stream. */
bool ab_lane = false;
rad_weight w_a_log = 0, w_dt_bias = 0, w_out_norm = 0;
LinearFP8 in{}, out{};
NormQuantFP8 nq_h{};
@@ -271,6 +276,10 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", ab_dim),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_ab)), {w.h.x}, {w.ab});
if (ab_lane) {
RAD_ARCH_TRY(rad_buf_concurrent(b, w.h.x));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.ab));
}
/* ---- the chunked path. As in the bf16 block, except `a` and `b_gate` are views of `ab`. */
op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
@@ -436,8 +445,19 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
}
if (!ext_in) nq_h.step(c, T);
in.step(c, w.h, w.in.x, T);
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
/* At decode and verify sizes the a|b projection is nearly all launch cost and reads only the
* norm's output, as the in-projection does, so it runs beside it on lane 1 and is joined before
* the convolution reads `ab`. A prefill chunk keeps one lane, where the two would share
* bandwidth. */
if (ab_lane && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) {
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
rad_lane(c, 0);
in.step(c, w.h, w.in.x, T);
rad_lane_join(c, 1, 0);
} else {
in.step(c, w.h, w.in.x, T);
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
}
/* Each path runs over its own run of sequences. The step is sorted decode-first: decode rows
* are sequences [0, D) with tokens [0, DT), prefill chunks are [D, S) with the rest. A pure
+3
View File
@@ -90,6 +90,9 @@ struct DsaCache {
d.n_head_kv = 1;
d.head_dim = 17;
*index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d);
/* dsa_score reads this group over the whole history every step, so it stays resident and
* holds every sequence's context while a sibling streams (kvstream/carve.cpp). */
RAD_ARCH_TRY(rad_kv_group_dense_read(b, *index_group));
}
index = *index_group;
if (!index) return RAD_E_INVAL;
+64 -8
View File
@@ -29,6 +29,9 @@ struct MlaLatent {
};
struct Wire {
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
/* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`.
* Never `length`, which is a token count. */
rad_buf nsel = 0;
};
Geom g{};
Config c{};
@@ -128,7 +131,7 @@ struct GlmMla {
QuantFP8 attn_quant{};
MlaLatent core{};
rad_weight q_gain = 0, kv_gain = 0;
rad_op op_kv_norm = 0, op_store = 0, op_ar = 0;
rad_op op_kv_norm = 0, op_store = 0, op_store_stream = 0, op_resolve = 0, op_ar = 0;
LinearFP8 rows_q_b{}, rows_output{};
QuantFP8 rows_quant{};
rad_weight rows_kv_b = 0;
@@ -189,6 +192,20 @@ struct GlmMla {
RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096,
GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer),
{ nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out));
/* The streamed store: kv_store's operands plus the residency map and the layer's mirror row,
* added at issue (prepare). */
if (rad_op_declared(b, "kv_store_streamed") && rad_kv_block_size(b, kv) == 4)
op_store_stream = rw(b,
RAD_OP(b, "kv_store_streamed",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("head_dim", 256), RAD_INT("n_head_kv", 1),
RAD_INT("block_size", 4),
RAD_STR("kv_dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.latent }, {});
/* Issued in finish, after this layer's indexer selects and before the attention reads
* `selected`. `sel_pitch` is the row pitch MlaLatent declares its attention with. */
op_resolve = kv_resolve_declare(b, g, kv, w.core.selected, w.core.nsel, core.c.blocks);
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
if (!op_store || ((reduce && g.world > 1) && !op_ar)) return RAD_E_INVAL;
return reduce ? declare_rows(b, nm, prefix) : RAD_OK;
@@ -265,20 +282,59 @@ struct GlmMla {
kv_a.step(ctx, w.input, w.kv_raw, T);
q_norm.step(ctx, T);
RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T));
/* The row form splits the query projection into finish_rows (per rank), so q_b runs here
* only in the head form; the latent store below is full length either way. */
if (!rows_take(T)) q_b.step(ctx, w.q_low, w.core.q, T);
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
if (!kb->stream) {
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
return;
}
/* A streamed group writes its host mirror, and the ring slot only where the block is
* resident; the stage wait goes immediately before the store (core/kvstream/stage.h). A
* staged pass also stores at block-id identity, which is how the stage view is read. */
const bool staged = kv_stage_wait(ctx, kv, kb, layer);
const KVStreamLayer L = kv_stream_layer(ctx, kv, layer, kb);
if (!op_store_stream || !L.host || L.blocks <= 0) {
rad_step_fail(ctx, "GLM MLA: this layer's KV group streams but the build has no "
"kv_store_streamed row to write its host mirror with");
return;
}
RAD_ISSUE_N(ctx, op_store_stream, T, bcol(w.latent, 0, 256, T),
bcol(w.latent, 256, 256, T), praw(kb->slot_mapping, RAD_I32, T),
kv_cache(kv, layer), praw(L.res, RAD_I32, L.blocks),
praw2(L.host, RAD_U8, L.blocks, L.bbytes));
if (staged)
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
}
void finish(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
const auto* kb = kv_batch(batch, kv);
/* A streamed group's selection is resolved here, after this layer's indexer wrote fresh
* block ids into the one `selected` buffer every layer shares and before either form of
* the attention reads it. A pass on the stage view reads block ids and never resolves. */
if (kb && kb->stream && !kv_stage_layer(ctx, kv, kb, layer) && T > 0) {
const KVStreamLayer L = kv_stream_layer(ctx, kv, layer, kb);
if (!op_resolve || !w.core.nsel || !L.host || L.blocks <= 0 || L.slots <= 0) {
rad_step_fail(ctx, "GLM MLA: this layer's KV group streams but the build has no "
"kv_resolve for its selection");
return;
}
/* The count is qsa_select's entry count, never `length` (a token count). */
kv_resolve_issue(ctx, op_resolve, L, brow_slice(w.core.selected, 0, T, core.c.blocks),
brow_slice(w.core.nsel, 0, T, 1), kv, layer, T);
}
if (rows_take(T)) {
finish_rows(ctx, T);
return;
} else {
core.step(ctx, T);
attn_quant.step(ctx, T);
output.step(ctx, w.attn, w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
}
core.step(ctx, T);
attn_quant.step(ctx, T);
output.step(ctx, w.attn, w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
/* After every attention launch of this layer (core/kvstream/stage.h). */
if (kb && kb->stream) kv_stage_next(ctx, kv, layer);
}
/* This rank's rows [first, first + n) end to end; the last rank's run may be short, and the
* gather sends its unwritten tail rows, which land past T. */
+4 -5
View File
@@ -119,11 +119,10 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false,
swiglu_limit));
/* The fold: decl_gated_fold, an fp8a8 tile, for block-fp8 weights; decl_gated_fold_mx for a
* plain MXFP4 one at one to eight rows. bf16, f32-scaled, rotated MXFP4, rotated 5-bit, 4-bit
* and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product, which
* neither fold computes. Declared over int8 codes, only a host kernel would take it, and that
* would pin the layer's weights to the host. An M2XFP4 gate_up takes the pair too. */
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain
* MXFP4 at one to eight rows. Other gate_up encodings (M2XFP4 included), and a clamped
* (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would take it, which
* would pin the layer's weights to the host. */
const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale;
if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 &&
!gate_up.i8)
+5 -8
View File
@@ -106,11 +106,9 @@ struct PleLayer {
rad_op op_gate = 0, op_conv = 0, op_add = 0;
int64_t hn() const { return c.hc * g.n_embd; }
/* The read-ahead queue's depth, in steps: the scheduler stages this many steps of the
* following prompt per step (batch.cpp, k_ahead_chunks) and the gather hands them to the
* reader thread, which prefetches their rows off the step path while the current chunk runs.
* Clamped to what `b_ids` was declared to hold, so a scheduler that offers more degrades the
* queue's depth, never an overflow. */
/* The read-ahead queue's depth in steps: batch.cpp's k_ahead_chunks steps of the following
* prompt, whose rows the gather's reader thread prefetches. Clamped to what `b_ids` holds, so
* a larger offer only shortens the queue. */
static constexpr int64_t kAheadChunks = 8;
/* The prompt that follows the step, bounded by what `b_ids` holds after the step's rows. */
int64_t ahead_rows(const RadBatch* batch) const {
@@ -283,9 +281,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
* follows declared order, where the two ops are adjacent, so a transient could be overwritten
* in between. */
{
/* The step's rows, then the read-ahead queue's: up to kAheadChunks further steps of the
* following prompt (RadBatch::n_ahead), which the gather's reader prefetches while the
* step runs, so a prefill's table rows are read at disk speed off the step path. */
/* The step's rows, then kAheadChunks further steps of the following prompt
* (RadBatch::n_ahead) for the reader to prefetch. */
RadBufDecl d{};
d.dtype = RAD_I32; d.rank = 2;
d.shape[0] = (1 + kAheadChunks) * g.max_tok; d.shape[1] = c.heads;
+25 -4
View File
@@ -78,16 +78,33 @@ struct VisionTower {
return rad_meta_geti(m, "vision_config.depth", 0) > 0;
}
/* With `gate_weights`, a checkpoint or container without the tower's weights declares nothing
* and leaves `on` false, for a model whose config names a tower its weights may not have. */
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group, bool deepstack = false);
int64_t model_embd, int first_group, bool deepstack = false,
bool gate_weights = false);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
Names& nm, int64_t model_embd, int first_group, bool deepstack) {
Names& nm, int64_t model_embd, int first_group, bool deepstack,
bool gate_weights) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
/* Whether the stem is there: its map first, then its encoding, which convert answers from the
* checkpoint and load from the container alike. A map left behind is inert. */
if (gate_weights) {
if (map_copy(b, nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight")) < 0)
return RAD_E_INVAL;
RadEncoding enc;
if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) {
std::fprintf(stderr, "radiance: vision_config names a tower the checkpoint does not "
"ship; declaring without it\n");
return RAD_OK;
}
}
depth = rad_meta_geti(m, "vision_config.depth", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_heads", 0);
@@ -173,8 +190,12 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, g);
};
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
RAD_BF16, { width, patch_dim }, grp_model());
/* Mapped above with `gate_weights`. */
w_patch = gate_weights
? decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim },
RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_model())
: bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
RAD_BF16, { width, patch_dim }, grp_model());
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("model.visual.patch_embed.proj.bias"),
RAD_BF16, { width }, grp_model());
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("model.visual.pos_embed.weight"),
+99 -183
View File
@@ -77,25 +77,29 @@ struct ActFP8 {
rad_buf cq() const { return q8_fed ? q8 : q; }
rad_buf cs() const { return q8_fed ? s8 : s; }
/* Declares the codes (and the int8 pair with `i8`); `x` is set by the caller.
/* Declares the codes: the E4M3 pair with `fp8_pair`, the int8 pair with `i8` (an int8 model's
* activations need no E4M3 plane taking arena); `x` is set by the caller.
*
* `rows` defaults to g.max_tok and must be given for any buffer that is not one row per token
* (a MoE expert plane is `rows * top_k`, an encoder tower's its patch count); too small a value
* overruns the arena (core/runtime/issue.cpp refuses such an issue). */
int declare_qs(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n,
int64_t rows = 0, bool i8 = false) {
int64_t rows = 0, bool i8 = false, bool fp8_pair = true) {
/* bf16 linears read only `x` (Geom::w_bf16), so declare no codes; an unused plane would
* still take arena space. */
if (g.w_bf16) { q = s = q8 = s8 = 0; return RAD_OK; }
const int64_t m = rows > 0 ? rows : g.max_tok;
q = decl_b(b, nm.f("%s.q", name), RAD_F8E4M3, { m, n });
s = decl_b(b, nm.f("%s.s", name), RAD_F32, { m, fp8_blocks(n) });
if (fp8_pair) {
q = decl_b(b, nm.f("%s.q", name), RAD_F8E4M3, { m, n });
s = decl_b(b, nm.f("%s.s", name), RAD_F32, { m, fp8_blocks(n) });
if (!q || !s) return RAD_E_INVAL;
}
if (i8) {
q8 = decl_b(b, nm.f("%s.q8", name), RAD_I8, { m, n });
s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, fp8_blocks(n) });
if (!q8 || !s8) return RAD_E_INVAL;
}
return (q && s) ? RAD_OK : RAD_E_INVAL;
return (fp8_pair || i8) ? RAD_OK : RAD_E_INVAL;
}
};
@@ -525,6 +529,10 @@ struct GateQuantFP8 {
* codes (`op_q`). */
rad_op op_q = 0;
/* Set before declare: the product in bf16 alone, as for bf16 linears, for a consumer that
* quantises its input itself (an int8 linear's op_q). */
bool silu_only = false;
int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n,
const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true,
bool rot = false, double limit = 0);
@@ -541,15 +549,16 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
want_x = bf16_out;
op_quant = 0;
this->n = n;
/* bf16 linears read the product itself: `silu_mul` into the bf16 plane only, and no
* rotation. */
bf16 = g.w_bf16;
/* bf16 linears and `silu_only` read the product itself: `silu_mul` into the bf16 plane only,
* and no rotation. */
bf16 = g.w_bf16 || silu_only;
clipped = limit > 0;
clamped_fused = false;
if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL;
if (clipped) {
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated. */
if (!gate_up || !a.x || n <= 0 || rot || (a.q8_fed && a.q8_rot) ||
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated; and no clamp
* with `silu_only`. */
if (!gate_up || !a.x || n <= 0 || rot || silu_only || (a.q8_fed && a.q8_rot) ||
std::strcmp(act_name, "silu"))
return RAD_E_INVAL;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
@@ -725,10 +734,8 @@ struct LinearFP8 {
* view whose layout hook reduces it). Read from the weight's encoding. */
bool mx = false;
rad_weight wref = 0;
/* The M2XFP4 sibling (libquant `m2xfp4`): the MXFP4 weight plus one metadata byte a group,
* read by `gemm_nt_q` at dtype m2xfp4 with the same E4M3 pair, `b_scale` and `b_ref` as MXFP4's
* are, the meta plane riding the weight operand's stored blob. Read from the weight's
* encoding. */
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 views, the meta plane riding the weight operand,
* read by `gemm_nt_q` at dtype m2xfp4. */
bool m2x = false;
/* Rotated (ParoQuant) variant of `mx`: the same GEMM over an activation that
* `givens_dense_quant` makes from the bf16 plane (channel scale, dense per-group rotation and
@@ -898,10 +905,9 @@ inline bool linear_is_mxfp4(const RadEncoding& e) {
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
}
/* The M2XFP4 sibling (arXiv 2601.19213, the paper's weight-side Sg-EM): the MXFP4 weight plus one
* metadata byte per group of 32, four 2-bit subgroup extra mantissas that refine the exponent to
* (1 + k/4) . 2^E (libquant's `m2xfp4` quantiser; libr4d's m2xfp4 layout hook). The exponent byte
* carries the adaptive bias; the GEMM applies nothing beyond the planes. */
/* M2XFP4 (arXiv 2601.19213, weight-side Sg-EM): the MXFP4 weight plus one metadata byte per group
* of 32, four 2-bit subgroup extra mantissas that refine the scale to (1 + k/4) . 2^E. The
* exponent byte carries the adaptive bias; the GEMM applies nothing beyond the planes. */
inline bool linear_is_m2xfp4(const RadEncoding& e) {
if (!rad_enc_is(&e, "m2xfp4") || e.n_planes != 3 || e.transform[0]) return false;
const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *mt = rad_enc_plane(&e, "meta");
@@ -1165,10 +1171,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
rot8 ? "unrotated" : "rotated");
return RAD_E_DTYPE;
}
if (!a.x || !a.q8 || !a.s8) {
fprintf(stderr, "radiance: '%s' is an int8 weight and its input lacks the bf16 plane "
"or the int8 code pair (the model declared its input before learning "
"the trunk is int8)\n", wn);
/* The bf16 plane only when this linear quantises it itself. */
if (!a.q8 || !a.s8 || (!a.q8_fed && !a.x)) {
fprintf(stderr, "radiance: '%s' is an int8 weight and its input lacks the int8 code "
"pair%s (the model declared its input before learning the trunk is "
"int8)\n", wn, a.q8_fed ? "" : " or the bf16 plane it quantises");
return RAD_E_DTYPE;
}
if (N % 16 || K % RAD_FP8_BLOCK) {
@@ -1358,12 +1365,18 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
return RAD_E_DTYPE;
}
/* ---- OCP-MXFP4 weight over the E4M3 pair. Three views: codes, exponents as `b_scale`, and
* the same plane as `b_ref`. Row parts apply as is (the exponent grid is one row tall); column
* slices must be whole 128s, the activation's scale block. */
paro = known && linear_is_paro_mxfp4(enc);
mx = known && (linear_is_mxfp4(enc) || paro);
if (mx) {
/* ---- OCP-MXFP4 or M2XFP4 weight over an E4M3 pair, the producer's or, for a rotated
* (ParoQuant) weight, its own. Three views: codes (M2XFP4's with its meta plane, which rides
* the weight operand), exponents as `b_scale`, and the same plane as `b_ref`. Row parts apply
* as is (the exponent grid is one row tall); column slices must be whole 128s, the
* activation's scale block. */
const bool paro_mx = known && linear_is_paro_mxfp4(enc);
const bool paro_m2 = known && linear_is_paro_m2xfp4(enc);
paro = paro_mx || paro_m2;
mx = known && (linear_is_mxfp4(enc) || paro_mx);
m2x = known && (linear_is_m2xfp4(enc) || paro_m2);
if (mx || m2x) {
const char* fmt = m2x ? "M2XFP4" : "MXFP4";
if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
"may\n", wn, stored);
@@ -1373,29 +1386,29 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
/* The rotation is applied to the activation, so this linear needs the input's bf16
* plane (probe() set reads_x) 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);
fprintf(stderr, "radiance: '%s' is a rotated %s weight, rotated and quantised "
"from its input's bf16 plane, and its input has none\n", wn, fmt);
return RAD_E_DTYPE;
}
if (g.world > 1 || span_hi > 0) {
fprintf(stderr, "radiance: '%s' is a rotated MXFP4 weight; its rotation is per "
fprintf(stderr, "radiance: '%s' is a rotated %s weight; its rotation is per "
"projection and is not cut by a tensor-parallel shard (world %d)\n",
wn, g.world);
wn, fmt, 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);
fprintf(stderr, "radiance: '%s' is an %s weight read against its input's E4M3 "
"pair, and its input has none\n", wn, fmt);
return RAD_E_DTYPE;
}
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows in "
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an %s 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);
base, (long long)N, (long long)K, fmt, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
RowParts rp;
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "MXFP4 tiles"));
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, m2x ? "M2XFP4 tiles" : "MXFP4 tiles"));
int64_t pb1 = 0, pb2 = 0;
if (paro) {
std::vector<int64_t> cut;
@@ -1413,8 +1426,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
}
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 }, access,
shard, grp, rp.w, rp.n);
w = decl_view(b, wn, nullptr, m2x ? "codes,meta" : "codes", RAD_FP4E2M1, { N, K },
access, shard, grp, rp.w, rp.n);
ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, rp.w, rp.n);
wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
@@ -1435,100 +1448,12 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi));
}
/* One GEMM: 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,
op = decl_gemm_q(b, 1, max_rows > 0 ? max_rows : g.max_tok, RAD_MX_GROUP,
m2x ? "m2xfp4" : "mxfp4a8", pb1, pb2,
{ w, ws, wref }, { paro ? rot_q : a.q, paro ? rot_s : a.s }, y);
return op ? RAD_OK : RAD_E_INVAL;
}
/* ---- M2XFP4 weight over the E4M3 pair: the MXFP4 weight's views plus the metadata plane,
* which rides the weight operand -- the declared view takes codes and meta together, and the
* stored blob carries the meta in its tail (libr4d's m2xfp4 layout). The exponent plane is
* `b_scale` and `b_ref` as MXFP4's is; the row parts, the shape bounds and the column-shard
* rule are the MXFP4 ones.
*
* A rotated weight (ParoQuant) carries the same planes in the basis its "givens" tables name
* and is declared like the rotated MXFP4 one: `givens_dense_quant` makes the E4M3 pair from
* the input's bf16 plane, once per rotated part, and the GEMM meets copy p with part p's rows
* (`pb1`/`pb2`). `paro` makes step() issue that rotation first. */
const bool m2rot = known && linear_is_paro_m2xfp4(enc);
m2x = known && (linear_is_m2xfp4(enc) || m2rot);
if (m2x) {
paro = m2rot;
if (stored) {
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
"may\n", wn, stored);
return RAD_E_INVAL;
}
if (m2rot) {
if (!a.x) {
fprintf(stderr, "radiance: '%s' is a rotated M2XFP4 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 M2XFP4 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 M2XFP4 weight read against its input's E4M3 "
"pair, and its input has none\n", wn);
return RAD_E_DTYPE;
}
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an M2XFP4 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;
}
RowParts rp;
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "M2XFP4 tiles"));
int64_t pb1 = 0, pb2 = 0;
if (m2rot) {
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,meta", RAD_FP4E2M1, { N, K }, access, shard, grp,
rp.w, rp.n);
ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, rp.w, rp.n);
wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, rp.w, rp.n);
if (!w || !ws || !wref) return RAD_E_INVAL;
if (span_hi > 0) {
const bool col = shard == RAD_SHARD_COL;
if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
"%d-column activation scale block\n", base, (long long)span_lo,
(long long)span_hi, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
const int64_t lo = col ? span_lo / RAD_MX_GROUP : span_lo;
const int64_t hi = col ? span_hi / RAD_MX_GROUP : span_hi;
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, lo, hi));
RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi));
}
/* One GEMM: 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, "m2xfp4", pb1,
pb2, { w, ws, wref }, { m2rot ? rot_q : a.q, m2rot ? rot_s : a.s }, y);
return op ? RAD_OK : RAD_E_INVAL;
}
/* Block fp8 is the last form; any other encoding is refused by name with the ones read. */
if (known) {
const RadEncPlane* sc = rad_enc_plane(&enc, "scale");
@@ -1652,17 +1577,9 @@ 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, yr, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (m2x && !paro) {
/* The MXFP4 operands over the producer's pair; the meta rides the weight's stored blob. */
RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_W(wref));
return;
}
if (mx || m2x) {
/* A rotated weight first rotates its input into its own codes, `rot_parts` copies side by
* side; a plain weight reads the producer's. A rotated M2XFP4 weight is issued here as the
* rotated MXFP4 one is, its meta riding the weight operand's stored blob. */
/* A rotated weight (MXFP4 or M2XFP4) first rotates its input into its own codes,
* `rot_parts` copies side by side; a plain weight 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)
@@ -1697,10 +1614,7 @@ struct DenseFP8 {
* works against the same E4M3 activation pair. */
rad_weight ref = 0;
bool mx = false;
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 weight plus one metadata byte a group, read by
* `gemm_nt_q` at dtype m2xfp4 with the same views and the same `b_ref`. The meta plane rides
* the weight operand's stored blob (libr4d's m2xfp4 layout), so the declared weight takes the
* codes and meta planes together. */
/* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 views, the meta plane riding the weight operand. */
bool m2x = false;
/* `mapped`: the caller made the name map already, to ask the encoding before choosing this
@@ -1739,16 +1653,11 @@ struct DenseFP8 {
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes,
int64_t split_n = 0) const {
if (m2x)
if (mx || m2x)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "m2xfp4")),
RAD_WEIGHTS(w, s, ref)),
reads, writes);
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_INT("group", RAD_MX_GROUP),
RAD_STR("dtype", m2x ? "m2xfp4" : "mxfp4a8")),
RAD_WEIGHTS(w, s, ref)),
reads, writes);
if (split_n > 0)
@@ -1775,44 +1684,27 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
std::initializer_list<int64_t> row_parts, bool mapped) {
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
/* ---- OCP-MXFP4, from the weight's encoding. The exponent grid is one row tall, so parts need
* only whole 16-row tiles; K takes whole 128s for the activation's per-(row, 128) scale. */
/* ---- OCP-MXFP4 or M2XFP4, from the weight's encoding. The exponent grid is one row tall, so
* parts need only whole 16-row tiles; K takes whole 128s for the activation's per-(row, 128)
* scale. */
{
const char* wn = nm.f("%s.weight", base);
if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src));
RadEncoding enc{};
mx = weight_enc(b, wn, &enc) && linear_is_mxfp4(enc);
m2x = !mx && linear_is_m2xfp4(enc); /* enc stays zero when there is no encoding */
if (mx) {
const bool known = weight_enc(b, wn, &enc);
mx = known && linear_is_mxfp4(enc);
m2x = known && linear_is_m2xfp4(enc);
if (mx || m2x) {
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows "
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an %s 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);
base, (long long)N, (long long)K, m2x ? "M2XFP4" : "MXFP4", RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
RowParts rp;
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "MXFP4 tiles"));
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, shard, grp,
rp.w, rp.n);
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, m2x ? "M2XFP4 tiles" : "MXFP4 tiles"));
w = decl_view(b, wn, nullptr, m2x ? "codes,meta" : "codes", RAD_FP4E2M1, { N, K },
access, shard, grp, rp.w, rp.n);
ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, rp.w, rp.n);
return w && s && ref ? RAD_OK : RAD_E_INVAL;
}
/* ---- M2XFP4: the MXFP4 views with the metadata plane riding the weight operand, the
* same bounds. */
if (m2x) {
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an M2XFP4 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;
}
RowParts rp;
RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "M2XFP4 tiles"));
w = decl_view(b, wn, nullptr, "codes,meta", RAD_FP4E2M1, { N, K }, access, shard, grp,
rp.w, rp.n);
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
access, shard, grp, rp.w, rp.n);
ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
@@ -1859,10 +1751,9 @@ inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K,
}
/* The same fold over an OCP-MXFP4 [2n, K] gate_up weight (`gemm_nt_q_gated_mx`: codes, the E8M0
* plane and that plane again as the per-row reference), declared for M up to min(rows, 8), the band
* of libr4d's one-to-eight-row GEMM it is built on. Optional like decl_gated_fold, and asked for
* only when a loaded library declares the op: libref does not, so a CPU-only engine takes the pair
* without ever naming it. */
* plane and that plane again as the per-row reference), up to min(rows, 8) rows, the band of
* libr4d's one-to-eight-row GEMM. Declared only when a loaded library declares the op (libref
* does not), so a CPU-only engine takes the pair. */
inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
rad_weight ws, rad_weight wref,
std::initializer_list<rad_buf> reads,
@@ -1880,6 +1771,31 @@ inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t
return op;
}
/* ================================================== a calibration tap */
/* One tap of the GPTQ calibration (calib_dir): the Gram of a linear's bf16 input, summed over the
* corpus in a PERSIST [K, K] f32 buffer that calib_write() saves. */
struct CalibTap {
rad_buf h = 0;
rad_op op = 0;
int64_t K = 0;
int declare(RadBuilder* b, Names& nm, int64_t max_tok, const char* name, rad_buf a, int64_t k) {
K = k;
h = decl_b(b, nm.f("%s.gram", name), RAD_F32, { k, k }, RAD_BUF_PERSIST);
if (!h) return RAD_E_INVAL;
op = rw(b, RAD_OP(b, "gram_accum",
RAD_PARAMS(RAD_RANGE("M", 1, max_tok), RAD_INT("n", k),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ a, h }, { h });
return op ? RAD_OK : RAD_E_INVAL;
}
/* gram_accum takes a, a_scale?, h: no scale for a bf16 input. */
void step(RadCtx* c, rad_buf a, int64_t T, bool live) const {
if (op && live) RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K));
}
};
} /* namespace arch */
} /* namespace rad */
+6
View File
@@ -216,6 +216,9 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
d.head_dim = c.head_dim / (2 * c.ratio);
*bk = rad_decl_kv_group(b, nm.f("kv_qsa_bkey"), &d);
if (!*bk) return RAD_E_INVAL;
/* qsa_score reads every complete block of the history each step, so this group stays resident
* and holds every sequence's context while a sibling streams (kvstream/carve.h). */
RAD_ARCH_TRY(rad_kv_group_dense_read(b, *bk));
}
kv_bk = *bk;
/* Under M-RoPE a block key rotates at its first token's three components, which qsa_work
@@ -255,6 +258,9 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_INT("ratio", c.ratio), RAD_INT("seqs", g.max_seqs)),
RAD_NOWEIGHTS),
{w.score, w.nc}, {w.sel, w.nsel, w.sequ});
/* When the attention group streams, the attention block resolves `sel` to ring slots after its
* layer's store (AttnGatedFP8::step); prefill runs on the stage and never resolves. */
return RAD_OK;
}