Archived
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:
commit
6645337f69
198 files changed
+20904
-3240
No files matched your search
+128
-12
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
@@ -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 */
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+37
-165
@@ -347,33 +347,6 @@ inline void G3Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int
|
||||
gemm_rows(c, y, r0, n);
|
||||
}
|
||||
|
||||
/* ---- the GPTQ calibration tap (rad_arch.h's calib_*): the Gram of one linear's bf16 input,
|
||||
* summed over the corpus in a PERSIST [K, K] f32 buffer. Declared only with RADIANCE_CALIB_DIR set,
|
||||
* for the layers RADIANCE_G3_CALIB_LAYERS names ("lo:hi", default every layer): a down projection's
|
||||
* Gram is 10752^2 f32 a rank at TP2, so 62 layers of four taps do not fit beside the weights and a
|
||||
* calibration runs in slices of layers, the corpus pushed through once per slice. */
|
||||
struct G3Tap {
|
||||
rad_buf h = 0;
|
||||
rad_op op = 0;
|
||||
int64_t K = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& g, 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, g.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, const bool* live) const {
|
||||
if (op && live && *live) RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K));
|
||||
}
|
||||
};
|
||||
|
||||
/* ---- one attention block, parameterised by class. */
|
||||
struct Gemma3Attn {
|
||||
struct Wire { rad_buf x = 0, h = 0, q = 0, k = 0, v = 0, attn = 0; };
|
||||
@@ -393,7 +366,7 @@ struct Gemma3Attn {
|
||||
* resolves; byte-identical to the four */
|
||||
rad_op op_qnr = 0;
|
||||
/* Calibration: q|k|v's shared input and o_proj's (this rank's columns). */
|
||||
G3Tap tap_in{}, tap_o{};
|
||||
CalibTap tap_in{}, tap_o{};
|
||||
const bool* tap_live = nullptr;
|
||||
/* Set before declare by a pipelined deployment: the all-reduce a second time at `overlap` 1 (a
|
||||
* launch that leaves the CUs to the compute beside it), and q|k|v's input pair shared by every
|
||||
@@ -410,10 +383,6 @@ struct Gemma3Attn {
|
||||
void post(RadCtx* c, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
|
||||
}
|
||||
/* The block's all-reduce alone, as Gemma3Mlp::ar. */
|
||||
void ar(RadCtx* c, int64_t T) const {
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
}
|
||||
/* The pipelined prefill (step_pipelined): the block over one prefill sequence in two pieces,
|
||||
* its input pair already written; hands the first piece behind its out projection. */
|
||||
void step_pieces(RadCtx* c, const RadBatch* batch, ArPieces* pc, const int32_t* used0) const;
|
||||
@@ -615,7 +584,7 @@ void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
ln_q.step(c, w.h, w.q, T);
|
||||
ln_k.step(c, w.h, w.k, T);
|
||||
ln_v.step(c, w.h, w.v, T);
|
||||
tap_in.step(c, w.h, T, tap_live);
|
||||
tap_in.step(c, w.h, T, tap_live && *tap_live);
|
||||
}
|
||||
|
||||
if (op_qnr) {
|
||||
@@ -639,7 +608,7 @@ void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
|
||||
tap_o.step(c, w.attn, T, tap_live);
|
||||
tap_o.step(c, w.attn, T, tap_live && *tap_live);
|
||||
ln_o.step(c, w.attn, w.h, T);
|
||||
/* All-reduce before the post-norm: o_proj is column-sharded, and the norm is of the sum. */
|
||||
if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
@@ -659,17 +628,13 @@ struct Gemma3Mlp {
|
||||
G3Linear ln_gu{}, ln_down{};
|
||||
rad_op op_norm = 0, op_act = 0, op_post = 0, op_ar = 0, op_add = 0;
|
||||
rad_op op_gq = 0;
|
||||
/* gate|up, the GeGLU and down's E4M3 quantiser in one launch (libr4d gemm_nt_q_gated_mx at
|
||||
* gelu_tanh) at up to `fold_rows` rows, when both linears are MXFP4: byte-identical to the
|
||||
* GEMM, gelu_mul and quant_act_fp8 it replaces. */
|
||||
/* gate|up, the GeGLU and down's E4M3 quantiser in one launch (gemm_nt_q_gated_mx at gelu_tanh)
|
||||
* up to `fold_rows` rows, when both linears are MXFP4: byte-identical to the GEMM, gelu_mul and
|
||||
* quant_act_fp8 it replaces. */
|
||||
rad_op op_fold = 0;
|
||||
int64_t fold_rows = 0;
|
||||
/* Set before declare: the band the fold is declared over (RADIANCE_G3_FOLD_ROWS). libr4d's
|
||||
* gemm_mxfp4a8_gated_gemv serves 1..8 rows and _gated_gemv_wide 9..64, each byte-identical to
|
||||
* the GEMM row of its band (gemv, gemv_wide) followed by gelu_mul and quant_act_fp8. */
|
||||
int64_t fold_max = 8;
|
||||
/* Calibration: gate|up's input and down's (this rank's columns). */
|
||||
G3Tap tap_gu{}, tap_dn{};
|
||||
CalibTap tap_gu{}, tap_dn{};
|
||||
const bool* tap_live = nullptr;
|
||||
/* Set before declare by a pipelined deployment, as Gemma3Attn's. */
|
||||
int ar_overlap = 0;
|
||||
@@ -682,11 +647,6 @@ struct Gemma3Mlp {
|
||||
void post(RadCtx* c, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
|
||||
}
|
||||
/* The block's all-reduce alone, for a caller that issues it after something of its own (the
|
||||
* step's read beside it, RADIANCE_G3_PF_EARLY). */
|
||||
void ar(RadCtx* c, int64_t T) const {
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
}
|
||||
/* The pipelined prefill: the block over rows [r0, r0 + n), its input pair already written, up
|
||||
* to the down projection; then the tail a piece at a time on the second lane. */
|
||||
void body_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
@@ -745,6 +705,10 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
{w.gu}, {ln_down.q8, ln_down.s8});
|
||||
// Not under calibration either: the down tap reads the bf16 product, which the fold never writes.
|
||||
{
|
||||
/* libr4d folds 1..8 rows (gemm_mxfp4a8_gated_gemv) and, from K 2688, 9..64
|
||||
* (_gated_gemv_wide), each byte-identical to its band's GEMM row followed by gelu_mul and
|
||||
* quant_act_fp8. At 2-8 sequences with speculation a decode step is 16-64 rows. */
|
||||
const int64_t fold_max = ln_gu.K >= 2688 ? 64 : 8;
|
||||
const int64_t hi = g.max_tok < fold_max ? g.max_tok : fold_max;
|
||||
// G3Linear's mx is linear_is_mxfp4, never a rotated (ParoQuant) weight, so one part.
|
||||
if (ln_gu.mx && ln_down.mx && !ln_down.shared_in && !calib_dir() && hi > 0 &&
|
||||
@@ -797,7 +761,7 @@ void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai
|
||||
ln_gu.step(c, w.h, w.gu, T);
|
||||
else if (!ln_gu.shared_in)
|
||||
RAD_ISSUE_N(c, ln_gu.op_q, T, brows(w.h, T), brows(ln_gu.q8, T), brows(ln_gu.s8, T));
|
||||
tap_gu.step(c, w.h, T, tap_live);
|
||||
tap_gu.step(c, w.h, T, tap_live && *tap_live);
|
||||
}
|
||||
if (fold) {
|
||||
RAD_ISSUE_N(c, op_fold, T, brows(ln_gu.q8, T), brows(ln_gu.s8, T), RAD_W(ln_gu.w),
|
||||
@@ -809,7 +773,7 @@ void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai
|
||||
ln_down.gemm(c, w.h, T);
|
||||
} else {
|
||||
RAD_ISSUE(c, op_act, brows(w.gu, T), brows(w.ffn, T));
|
||||
tap_dn.step(c, w.ffn, T, tap_live);
|
||||
tap_dn.step(c, w.ffn, T, tap_live && *tap_live);
|
||||
ln_down.step(c, w.ffn, w.h, T);
|
||||
}
|
||||
if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
@@ -929,82 +893,23 @@ struct G3JunctionFP8 {
|
||||
|
||||
/* The weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h): a weight's first
|
||||
* kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows (a verify of four sequences at
|
||||
* speculation 7, as qwen35_fp8's). TranslateGemma-27B MXFP4 + DFlash2 at tp 2 on 2x R9700 (Gen5 x8),
|
||||
* no speculation, two rounds each, x1 / x4 / x8 tok/s against none (56.8 / 182.0 / 325.0): 8 MB 63.3 /
|
||||
* 203.1 / 354.9; 12 MB 63.0 / 202.6 / 354.9; 16 MB 63.5 / 203.9 / 356.6; 20 MB 64.1 / 204.0 / 359.4;
|
||||
* 24 MB 64.4 / 206.4 / 359.3; 32 MB 63.1 / 201.4 / 351.9. Larger than qwen35_fp8's 12 MB: this
|
||||
* model's hidden width (5376) and weights are larger, so its all-reduces take longer and its GEMMs
|
||||
* read more; past ~24 MB the read outlasts the reduction and takes bandwidth from the GEMM it should
|
||||
* feed. With speculation 7 (three rounds, greedy, medians) x1 / x4 / x8 / x16 158.1 / 409.0 / 592.0 / 710.8 -> 177.3 / 428.4 / 592.3 / 717.6. The drafter's reads (Dflash2::Config::prefetch) take the same size. */
|
||||
* speculation 7). TranslateGemma-27B MXFP4 + DFlash2, tp 2 on two R9700s: 24 MB was best, +13 %
|
||||
* at one stream and +10 % at eight with no speculation, +12 % / +5 % at one / four streams with
|
||||
* speculation 7. Larger than qwen35_fp8's 12 MB, since this model's wider all-reduces take longer;
|
||||
* past ~24 MB the read outlasts the reduction and takes bandwidth from the GEMM it feeds. The
|
||||
* drafter's reads (Dflash2::Config::prefetch) take the same size. */
|
||||
constexpr int64_t kPrefetchBytes = (int64_t)24 << 20;
|
||||
constexpr int64_t kPrefetchStepRows = 32;
|
||||
|
||||
/* A/B knobs over the decode steps, read at declare; unset, each is today's behaviour and the graph
|
||||
* and steps are the ones pinned before they existed (arch_test,
|
||||
* gemma3_served_knobs_at_their_defaults_keep_the_pinned_graph_and_steps).
|
||||
*
|
||||
* RADIANCE_G3_PF_ROWS the tallest decode step that reads beside its reductions (default
|
||||
* kPrefetchStepRows, 32, qwen35_fp8's). Eight sequences at speculation 7
|
||||
* verify 64 rows, and every all-reduce of such a step runs with the card's
|
||||
* memory idle (~5.8 ms eager a step on 2x R9700).
|
||||
* RADIANCE_G3_PF_MIB the read's size on the steps above 32 rows (default kPrefetchBytes, whose
|
||||
* sweep was at 1..32-row steps): a 64-row step's GEMMs are partly compute-
|
||||
* bound, so the size that fits beside its longer reduction may differ.
|
||||
* RADIANCE_G3_PF_EARLY 1: issue the read between the GEMM and a bare (unfused) all-reduce
|
||||
* rather than after it. Above ar_wire_is_exact's rows the lossy wire's
|
||||
* all-reduce is issued by the block itself, so the read's join on lane 1
|
||||
* comes after the reduction and the read runs beside the post-norm, the
|
||||
* junction and the next GEMM, not beside the reduction. The fused steps
|
||||
* (exact wire) have it in front either way.
|
||||
* RADIANCE_G3_FOLD_ROWS the gated fold's band (Gemma3Mlp::fold_max): 0 is today's 8; up to 64. */
|
||||
struct G3Knobs {
|
||||
int64_t pf_rows = kPrefetchStepRows;
|
||||
int64_t pf_wide = kPrefetchBytes; /* bytes, steps of more than kPrefetchStepRows rows */
|
||||
bool pf_early = false;
|
||||
int64_t fold = 8;
|
||||
};
|
||||
|
||||
/* An integer knob in [lo, hi], or `dflt` when unset; anything else is refused by name, so a typo
|
||||
* in an A/B does not silently measure the default. */
|
||||
static int g3_knob(const char* name, long long lo, long long hi, long long dflt, long long* out) {
|
||||
*out = dflt;
|
||||
const char* s = std::getenv(name);
|
||||
if (!s || !*s) return RAD_OK;
|
||||
char* end = nullptr;
|
||||
const long long v = std::strtoll(s, &end, 10);
|
||||
if (!end || *end != '\0' || v < lo || v > hi) {
|
||||
fprintf(stderr, "radiance: gemma3: %s='%s' is not an integer in %lld..%lld\n", name, s, lo, hi);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
*out = v;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int g3_knobs(G3Knobs* k) {
|
||||
long long v = 0;
|
||||
RAD_ARCH_TRY(g3_knob("RADIANCE_G3_PF_ROWS", 1, 1 << 20, kPrefetchStepRows, &v));
|
||||
k->pf_rows = v;
|
||||
RAD_ARCH_TRY(g3_knob("RADIANCE_G3_PF_MIB", 1, 256, kPrefetchBytes >> 20, &v));
|
||||
k->pf_wide = (int64_t)v << 20;
|
||||
RAD_ARCH_TRY(g3_knob("RADIANCE_G3_PF_EARLY", 0, 1, 0, &v));
|
||||
k->pf_early = v != 0;
|
||||
RAD_ARCH_TRY(g3_knob("RADIANCE_G3_FOLD_ROWS", 0, 64, 0, &v));
|
||||
k->fold = v == 0 ? 8 : v;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
struct Layer {
|
||||
bool global = false;
|
||||
Gemma3Attn attn{};
|
||||
Gemma3Mlp mlp{};
|
||||
G3Junction j_am{}, j_ma{};
|
||||
G3JunctionFP8 jf_am{}, jf_ma{};
|
||||
/* The reads beside the decode all-reduces: gate|up's leading bytes beside the attention block's
|
||||
* reduction, the next layer's q's beside the feed-forward's. 0 where none is declared. The
|
||||
* `_wide` pair serves the steps above kPrefetchStepRows rows; it is the narrow pair itself
|
||||
* unless RADIANCE_G3_PF_MIB gives those steps another size. */
|
||||
/* gate|up's leading bytes beside the attention block's reduction, the next layer's q's beside
|
||||
* the feed-forward's; 0 where none is declared. */
|
||||
rad_op op_pf_gu = 0, op_pf_next = 0;
|
||||
rad_op op_pf_gu_wide = 0, op_pf_next_wide = 0;
|
||||
rad_weight pf_gu_w = 0, pf_next_w = 0;
|
||||
};
|
||||
|
||||
@@ -1024,7 +929,6 @@ struct Model {
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final = 0, op_gather = 0, op_logits = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
G3Knobs knobs{};
|
||||
|
||||
G3Junction j0{};
|
||||
bool fuse = false;
|
||||
@@ -1220,7 +1124,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(g3_knobs(&m.knobs));
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
/* The rotary scaling (linear, factor 8 on the 27B) into g.rope_scale, for the global class. */
|
||||
RAD_ARCH_TRY(yarn_from(m.g, meta, "", m.g.head_dim));
|
||||
@@ -1377,7 +1280,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
lay.attn.ar_overlap = lay.mlp.ar_overlap = 1;
|
||||
lay.attn.pipe_in = lay.mlp.pipe_in = &m.pipe_in;
|
||||
}
|
||||
lay.mlp.fold_max = m.knobs.fold;
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, attn_scale));
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw));
|
||||
}
|
||||
@@ -1445,9 +1347,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
m.fuse_mx_ar = ar;
|
||||
}
|
||||
/* ---- the weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h). Only at
|
||||
* more than one rank; RADIANCE_PREFETCH_BESIDE=0 issues none (prefetch_beside). */
|
||||
if (g.world > 1 && rad_op_declared(b, "prefetch")) {
|
||||
/* ---- the weight reads beside the decode all-reduces, at more than one rank;
|
||||
* --weight-prefetch off declares none. */
|
||||
if (g.world > 1 && !ctx->weight_prefetch_off && rad_op_declared(b, "prefetch")) {
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.pf_gu_w = lay.mlp.ln_gu.w;
|
||||
@@ -1456,14 +1358,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
lay.pf_next_w = m.layers[(size_t)l + 1].attn.ln_q.w;
|
||||
lay.op_pf_next = decl_prefetch(b, lay.pf_next_w, kPrefetchBytes);
|
||||
}
|
||||
/* A size of their own for the steps above kPrefetchStepRows, declared only when some
|
||||
* step can take it, so an unused RADIANCE_G3_PF_MIB leaves the graph as it was. */
|
||||
lay.op_pf_gu_wide = lay.op_pf_gu;
|
||||
lay.op_pf_next_wide = lay.op_pf_next;
|
||||
if (m.knobs.pf_rows > kPrefetchStepRows && m.knobs.pf_wide != kPrefetchBytes) {
|
||||
lay.op_pf_gu_wide = decl_prefetch(b, lay.pf_gu_w, m.knobs.pf_wide);
|
||||
if (lay.pf_next_w) lay.op_pf_next_wide = decl_prefetch(b, lay.pf_next_w, m.knobs.pf_wide);
|
||||
}
|
||||
}
|
||||
}
|
||||
/* The pipeline needs the fused fp8 junctions and every block's overlap all-reduce. */
|
||||
@@ -1502,26 +1396,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* ---- the calibration tap. It reads the bf16 input of every linear, which the fused junctions
|
||||
* never write, so under it none is declared (above): any container calibrates, unfused. */
|
||||
if (calib_dir()) {
|
||||
m.calib_lo = 0;
|
||||
m.calib_hi = g.n_layer;
|
||||
if (const char* s = std::getenv("RADIANCE_G3_CALIB_LAYERS")) {
|
||||
long long lo = 0, hi = 0;
|
||||
int used = 0;
|
||||
if (std::sscanf(s, "%lld:%lld%n", &lo, &hi, &used) != 2 || s[used] != '\0' || lo < 0 ||
|
||||
hi > g.n_layer || lo >= hi) {
|
||||
fprintf(stderr, "radiance: gemma3: RADIANCE_G3_CALIB_LAYERS '%s' is not lo:hi within "
|
||||
"0:%lld\n", s, (long long)g.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
m.calib_lo = lo;
|
||||
m.calib_hi = hi;
|
||||
}
|
||||
RAD_ARCH_TRY(calib_layers("gemma3", "RADIANCE_G3_CALIB_LAYERS", g.n_layer, &m.calib_lo,
|
||||
&m.calib_hi));
|
||||
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
RAD_ARCH_TRY(lay.attn.tap_in.declare(b, nm, g, nm.f("blk.%d.attn_in", (int)l), m.b_h, g.n_embd));
|
||||
RAD_ARCH_TRY(lay.attn.tap_o.declare(b, nm, g, nm.f("blk.%d.attn_o", (int)l), m.b_attn, m.cs.q_dim()));
|
||||
RAD_ARCH_TRY(lay.mlp.tap_gu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", (int)l), m.b_h, g.n_embd));
|
||||
RAD_ARCH_TRY(lay.mlp.tap_dn.declare(b, nm, g, nm.f("blk.%d.ffn_down", (int)l), m.b_ffn, g.n_ff));
|
||||
RAD_ARCH_TRY(lay.attn.tap_in.declare(b, nm, g.max_tok, nm.f("blk.%d.attn_in", (int)l), m.b_h, g.n_embd));
|
||||
RAD_ARCH_TRY(lay.attn.tap_o.declare(b, nm, g.max_tok, nm.f("blk.%d.attn_o", (int)l), m.b_attn, m.cs.q_dim()));
|
||||
RAD_ARCH_TRY(lay.mlp.tap_gu.declare(b, nm, g.max_tok, nm.f("blk.%d.ffn_gate_up", (int)l), m.b_h, g.n_embd));
|
||||
RAD_ARCH_TRY(lay.mlp.tap_dn.declare(b, nm, g.max_tok, nm.f("blk.%d.ffn_down", (int)l), m.b_ffn, g.n_ff));
|
||||
}
|
||||
m.calib = true;
|
||||
m.tap_live = true;
|
||||
@@ -1783,11 +1665,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
if (m.op_embed_ar)
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, T * m.g.n_embd, brows(m.b_x, T), RAD_NONE);
|
||||
|
||||
/* The reads beside the reductions go on decode steps of up to RADIANCE_G3_PF_ROWS rows
|
||||
* (kPrefetchStepRows by default), none on a step that carries a prompt's rows (as
|
||||
* qwen35_fp8's); the steps above kPrefetchStepRows take the `_wide` reads. */
|
||||
const int64_t pf_h = batch->phase == RAD_PHASE_DECODE && T <= m.knobs.pf_rows ? 1 : INT64_MAX;
|
||||
const bool pf_wide = T > kPrefetchStepRows;
|
||||
/* Decode steps of up to kPrefetchStepRows rows only, as qwen35_fp8's. */
|
||||
const int64_t pf_h = batch->phase == RAD_PHASE_DECODE && T <= kPrefetchStepRows ? 1 : INT64_MAX;
|
||||
if (m.fuse_mx) {
|
||||
/* MXFP4 trunk: [post-norm, then add + next norm + quantiser as one op] at every junction;
|
||||
* the last block's tail runs unfused into the final norm. */
|
||||
@@ -1797,20 +1676,13 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const bool last = li + 1 == m.layers.size();
|
||||
/* Per step: the fused junction sends the exact wire only (G3JunctionFP8::op_ar). */
|
||||
const bool far = m.fuse_mx_ar && ar_wire_is_exact(m.g, T);
|
||||
/* RADIANCE_G3_PF_EARLY: a bare all-reduce issued here, behind the read, rather than by
|
||||
* the block (the last feed-forward, with no read after it, keeps its own). */
|
||||
const bool early = m.knobs.pf_early && !far;
|
||||
const rad_op pf_gu = pf_wide ? l.op_pf_gu_wide : l.op_pf_gu;
|
||||
const rad_op pf_next = pf_wide ? l.op_pf_next_wide : l.op_pf_next;
|
||||
l.attn.step(c, batch, true, true, far || early);
|
||||
prefetch_beside(c, pf_gu, l.pf_gu_w, pf_h);
|
||||
if (early) l.attn.ar(c, T);
|
||||
l.attn.step(c, batch, true, true, far);
|
||||
prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h);
|
||||
if (!far) l.attn.post(c, T);
|
||||
l.jf_am.step(c, T, far);
|
||||
l.mlp.step(c, batch, true, !last, far || early);
|
||||
prefetch_beside(c, pf_next, l.pf_next_w, pf_h);
|
||||
l.mlp.step(c, batch, true, !last, far);
|
||||
prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h);
|
||||
if (!last) {
|
||||
if (early) l.mlp.ar(c, T);
|
||||
if (!far) l.mlp.post(c, T);
|
||||
l.jf_ma.step(c, T, far);
|
||||
}
|
||||
@@ -1823,10 +1695,10 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const bool last = li + 1 == m.layers.size();
|
||||
const bool ar = m.fuse_ar && ar_wire_is_exact(m.g, T); /* exact wire only, as above */
|
||||
l.attn.step(c, batch, m.fuse, m.fuse, ar);
|
||||
prefetch_beside(c, pf_wide ? l.op_pf_gu_wide : l.op_pf_gu, l.pf_gu_w, pf_h);
|
||||
prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h);
|
||||
if (m.fuse) l.j_am.step(c, T, ar);
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last, ar);
|
||||
prefetch_beside(c, pf_wide ? l.op_pf_next_wide : l.op_pf_next, l.pf_next_w, pf_h);
|
||||
prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h);
|
||||
if (m.fuse && !last) l.j_ma.step(c, T, ar);
|
||||
tap(li);
|
||||
}
|
||||
|
||||
+3
-42
@@ -141,33 +141,6 @@ struct Kind {
|
||||
int64_t kv_dim() const { return nkv * hd; }
|
||||
};
|
||||
|
||||
/* ---- the GPTQ calibration tap (rad_arch.h's calib_*): the Gram of one bf16 linear's input,
|
||||
* summed over a corpus in a PERSIST [K, K] f32 buffer. Declared only with RADIANCE_CALIB_DIR set,
|
||||
* for the dense layers RADIANCE_G4_CALIB_LAYERS names ("lo:hi", default every layer): the 31B's
|
||||
* four taps a layer are ~364 MiB a rank at --tp 4, so its 60 layers do not fit beside the bf16
|
||||
* weights and a calibration runs in slices of layers, the corpus pushed through once per slice. */
|
||||
struct G4Tap {
|
||||
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));
|
||||
}
|
||||
};
|
||||
|
||||
struct Layer {
|
||||
int full = 0;
|
||||
/* attention */
|
||||
@@ -217,7 +190,7 @@ struct Layer {
|
||||
/* Calibration: the attention's input (q, k and v share it), its output (this rank's columns,
|
||||
* o_proj's input), the dense arm's input and its gated product (this rank's columns, down's
|
||||
* input). */
|
||||
G4Tap tap_in{}, tap_o{}, tap_gu{}, tap_dn{};
|
||||
CalibTap tap_in{}, tap_o{}, tap_gu{}, tap_dn{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -1269,20 +1242,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (calib_dir()) {
|
||||
m.overlap = false;
|
||||
m.arms = false;
|
||||
m.calib_lo = 0;
|
||||
m.calib_hi = (int64_t)m.layers.size();
|
||||
if (const char* s = std::getenv("RADIANCE_G4_CALIB_LAYERS")) {
|
||||
long long lo = 0, hi = 0;
|
||||
int used = 0;
|
||||
if (std::sscanf(s, "%lld:%lld%n", &lo, &hi, &used) != 2 || s[used] != '\0' || lo < 0 ||
|
||||
hi > (long long)m.layers.size() || lo >= hi) {
|
||||
fprintf(stderr, "radiance: gemma4: RADIANCE_G4_CALIB_LAYERS '%s' is not lo:hi within "
|
||||
"0:%zu\n", s, m.layers.size());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
m.calib_lo = lo;
|
||||
m.calib_hi = hi;
|
||||
}
|
||||
RAD_ARCH_TRY(calib_layers("gemma4", "RADIANCE_G4_CALIB_LAYERS", (int64_t)m.layers.size(),
|
||||
&m.calib_lo, &m.calib_hi));
|
||||
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
|
||||
Layer& y = m.layers[(size_t)l];
|
||||
const Kind& k = y.full ? m.kf : m.ks;
|
||||
|
||||
@@ -1867,7 +1867,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dc.group = df2_geti(meta, "conv_group_size", 16);
|
||||
dc.sel_rank = df2_geti(meta, "selector_rank", 0);
|
||||
dc.sel_topk = df2_geti(meta, "selector_top_k", 0);
|
||||
dc.prefetch = gemma4::kPrefetchBytes;
|
||||
dc.prefetch = ctx->weight_prefetch_off ? 0 : gemma4::kPrefetchBytes;
|
||||
if (dc.sel_rank <= 0 || dc.sel_topk <= 0) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash2 drafter states no selector geometry (rank "
|
||||
"%lld, top_k %lld)\n", (long long)dc.sel_rank, (long long)dc.sel_topk);
|
||||
@@ -2454,8 +2454,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* attention block's all-reduce and the next layer's q|k|v's (q alone, unfused; after the last
|
||||
* layer, the lm_head's) beside the feed-forward's (gemma4::kPrefetchBytes), then down_proj's
|
||||
* first 9 MB beside the attention (gemma4::kPrefetchDownBytes). Only at more than one rank,
|
||||
* where there are reductions to sit beside. */
|
||||
if (g.world > 1 && rad_op_declared(b, "prefetch")) {
|
||||
* where there are reductions to sit beside, and not under --weight-prefetch off. */
|
||||
if (g.world > 1 && !ctx->weight_prefetch_off && rad_op_declared(b, "prefetch")) {
|
||||
for (size_t l = 0; l < m.layers.size(); ++l) {
|
||||
Layer& lay = m.layers[l];
|
||||
lay.attn.pf_w = lay.mlp.ln_gu.w;
|
||||
|
||||
@@ -214,6 +214,8 @@ static int indexer_buffers(RadBuilder* b, Model& m) {
|
||||
c.selected = m.aw.core.selected;
|
||||
c.length = m.aw.core.length;
|
||||
c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
|
||||
/* The MLA block's resolve count: qsa_select's second output, never `length`. */
|
||||
m.aw.core.nsel = c.nsel;
|
||||
if (g.world > 1) {
|
||||
c.cu_part = decl_b(b, nm.f("index_part_bounds"), RAD_I32, { g.max_seqs + 1 });
|
||||
c.sel_part = decl_b(b, nm.f("selected_part"), RAD_I32, { part, 513 });
|
||||
@@ -396,6 +398,9 @@ static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, i
|
||||
g.max_ctx = ctx->max_ctx;
|
||||
g.max_seqs = ctx->max_seqs;
|
||||
g.max_spec = ctx->max_spec;
|
||||
/* Filled by hand here, not by geom_from: without it kv_resolve would declare the whole context as
|
||||
* the ring. */
|
||||
g.kv_resident = ctx->kv_resident_blocks;
|
||||
g.max_logit_rows = std::min<int64_t>(g.max_tok, g.max_seqs * (g.max_spec + 1));
|
||||
if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows;
|
||||
g.eps = meta->rms_eps;
|
||||
@@ -593,6 +598,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
/* The MLA block declares the streamed store and the resolve (rad_block_glm_mla.h). */
|
||||
out->kv_stream_ok = 1;
|
||||
if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth;
|
||||
// The tower's merged block, so a pass size the core picks itself is whole output rows.
|
||||
if (GlmVision::present(meta)) {
|
||||
|
||||
@@ -7,4 +7,9 @@ if(NOT COMMAND rad_add_plugin)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.cpp)
|
||||
# rad_ref2va_pack.cpp holds the reference sequence's packing and rad_vae_geom.cpp the encoders'
|
||||
# geometry: pure host arithmetic, which tests/ref2va_pack_test.cpp and tests/vae_geom_test.cpp
|
||||
# compile in directly.
|
||||
rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/rad_ref2va_pack.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/rad_vae_geom.cpp)
|
||||
+1696
-168
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,301 @@
|
||||
/* rad_ref2va_pack.cpp -- see rad_ref2va_pack.h. The positions are computed in f64 as ComfyUI
|
||||
* computes them and stored in f32. */
|
||||
|
||||
#include "rad_ref2va_pack.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace minimaxh3 {
|
||||
|
||||
/* The pixel frames the k-th latent frame of a video covers, cycling, and the time a pixel frame
|
||||
* spans in soundtrack latents. */
|
||||
static const int kFramePerToken[5] = { 1, 4, 4, 4, 4 };
|
||||
static const double kFrameRescale = 5.0 / 3.0;
|
||||
|
||||
int ref2va_seg_tag(int kind) {
|
||||
switch (kind) {
|
||||
case kR2VText: return 1;
|
||||
case kR2VAudio: case kR2VCondAudio: case kR2VRefAudio: return 2;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int ref2va_is_img(int kind) {
|
||||
return kind == kR2VCond || kind == kR2VRefImg || kind == kR2VVideo;
|
||||
}
|
||||
|
||||
int ref2va_is_audio(int kind) {
|
||||
return kind == kR2VCondAudio || kind == kR2VRefAudio || kind == kR2VAudio;
|
||||
}
|
||||
|
||||
/* A side of `dim` latents in 2x2 patches: dim / 2 positions over
|
||||
* [(1 - ratio) / 2, (1 + ratio) / 2) x 32, ratio = dim / sqrt(h w), so every aspect spans the same
|
||||
* area. */
|
||||
static std::vector<double> axis_from_sqrt_area(int dim, int patch, double sqrt_area) {
|
||||
const double ratio = (double)dim / sqrt_area;
|
||||
const int n = dim / patch;
|
||||
std::vector<double> v((size_t)n);
|
||||
for (int i = 0; i < n; ++i)
|
||||
v[(size_t)i] = ((double)i * (ratio / n) + (1.0 - ratio) / 2.0) * 32.0;
|
||||
return v;
|
||||
}
|
||||
|
||||
/* A latent frame's patches as (row, column) pairs, row-major, and the column axis, whose ends the
|
||||
* two soundtrack channels sit at. */
|
||||
static void frame_grid(int h, int w, std::vector<double>* frame, std::vector<double>* w_grid) {
|
||||
const double area = std::sqrt((double)h * (double)w);
|
||||
std::vector<double> hg = axis_from_sqrt_area(h, 2, area), wg = axis_from_sqrt_area(w, 2, area);
|
||||
frame->clear();
|
||||
frame->reserve(hg.size() * wg.size() * 2);
|
||||
for (const double& r : hg)
|
||||
for (const double& c : wg) { frame->push_back(r); frame->push_back(c); }
|
||||
*w_grid = std::move(wg);
|
||||
}
|
||||
|
||||
/* The time n latent frames of video span. */
|
||||
static double video_t_span_sum(int n) {
|
||||
double s = 0.0;
|
||||
for (int k = 0; k < n; ++k) s += kFrameRescale * (double)kFramePerToken[k % 5];
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Each latent frame's time: where the frames before it end. */
|
||||
static std::vector<double> video_t_grid(int n, double origin) {
|
||||
std::vector<double> g((size_t)n);
|
||||
double t = origin;
|
||||
for (int k = 0; k < n; ++k) {
|
||||
g[(size_t)k] = t;
|
||||
t += kFrameRescale * (double)kFramePerToken[k % 5];
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
/* The time a reference spans: a picture 1, a soundtrack its length, a video the longer of its two
|
||||
* streams. */
|
||||
static double ref_t_span(const Ref2VARef& r) {
|
||||
if (r.kind == kR2VRefImage) return 1.0;
|
||||
if (r.kind == kR2VRefAudioOnly) return (double)r.audio_t;
|
||||
return std::max((double)r.audio_t, video_t_span_sum(r.latent_t));
|
||||
}
|
||||
|
||||
/* A soundtrack's rows, the first channel's then the second's, a latent each at `cursor` onwards;
|
||||
* the channels sit at the two ends of the width axis, row 0. */
|
||||
static void audio_grid(double cursor, int t, double w_low, double w_high, std::vector<float>* pos) {
|
||||
if (!pos) return;
|
||||
for (int ch = 0; ch < 2; ++ch) {
|
||||
const double w = ch == 0 ? w_low : w_high;
|
||||
for (int i = 0; i < t; ++i) {
|
||||
pos->push_back((float)(cursor + (double)i));
|
||||
pos->push_back(0.0f);
|
||||
pos->push_back((float)w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* A video's rows: each latent frame's patches at its time. */
|
||||
static void video_grid(int vt, const std::vector<double>& frame, double origin,
|
||||
std::vector<float>* pos) {
|
||||
if (!pos) return;
|
||||
const std::vector<double> tg = video_t_grid(vt, origin);
|
||||
for (int k = 0; k < vt; ++k)
|
||||
for (size_t j = 0; j < frame.size(); j += 2) {
|
||||
pos->push_back((float)tg[(size_t)k]);
|
||||
pos->push_back((float)frame[j]);
|
||||
pos->push_back((float)frame[j + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
int ref2va_build(int text_len, const Ref2VAGeom& g, const std::vector<Ref2VAKeyframe>& keyframes,
|
||||
const std::vector<Ref2VARef>& refs, Ref2VAPack* out, bool positions) {
|
||||
if (text_len < 0 || g.latent_t < 0 || g.latent_h < 0 || g.latent_w < 0 || g.audio_t < 0)
|
||||
return -1;
|
||||
for (const Ref2VAKeyframe& kf : keyframes)
|
||||
if (kf.frame < 0 || kf.video_t < 0 || kf.audio_t < 0) return -1;
|
||||
for (const Ref2VARef& r : refs) {
|
||||
if (r.kind < kR2VRefImage || r.kind > kR2VRefVideoAudio) return -1;
|
||||
if (r.lat_h < 0 || r.lat_w < 0 || r.latent_t < 0 || r.audio_t < 0) return -1;
|
||||
}
|
||||
|
||||
Ref2VAPack p;
|
||||
std::vector<double> frame, w_grid;
|
||||
frame_grid(g.latent_h, g.latent_w, &frame, &w_grid);
|
||||
const size_t frame_rows = frame.size() / 2;
|
||||
const double w_low = w_grid.empty() ? 0.0 : w_grid.front();
|
||||
const double w_high = w_grid.empty() ? 0.0 : w_grid.back();
|
||||
|
||||
/* The prompt: its token positions on the time axis. */
|
||||
p.segs.push_back({ kR2VText, 0, (int64_t)text_len, 0 });
|
||||
std::vector<float>* pos = positions ? &p.pos : nullptr;
|
||||
for (int i = 0; i < text_len && pos; ++i) {
|
||||
p.pos.push_back((float)i);
|
||||
p.pos.push_back(0.0f);
|
||||
p.pos.push_back(0.0f);
|
||||
}
|
||||
int64_t row = text_len;
|
||||
|
||||
/* The video's clock, and the keyframes on it, starts after every reference's span. */
|
||||
double cursor = (double)text_len;
|
||||
for (const Ref2VARef& r : refs) cursor += ref_t_span(r);
|
||||
|
||||
/* A keyframe is on the video's grid, at its frame's time. */
|
||||
for (const Ref2VAKeyframe& kf : keyframes) {
|
||||
const double cond_t = cursor + kFrameRescale * (double)kf.frame;
|
||||
if (kf.video_t > 0) {
|
||||
const int64_t n = (int64_t)kf.video_t * (int64_t)frame_rows;
|
||||
video_grid(kf.video_t, frame, cond_t, pos);
|
||||
p.segs.push_back({ kR2VCond, row, row + n, 0 });
|
||||
row += n;
|
||||
}
|
||||
if (kf.audio_t > 0) {
|
||||
const int64_t n = (int64_t)kf.audio_t * 2;
|
||||
audio_grid(cond_t, kf.audio_t, w_low, w_high, pos);
|
||||
p.segs.push_back({ kR2VCondAudio, row, row + n, 0 });
|
||||
row += n;
|
||||
}
|
||||
}
|
||||
|
||||
/* The references in request order, each after the last. */
|
||||
cursor = (double)text_len;
|
||||
for (const Ref2VARef& r : refs) {
|
||||
if (r.kind == kR2VRefImage) {
|
||||
std::vector<double> rf, rw;
|
||||
frame_grid(r.lat_h, r.lat_w, &rf, &rw);
|
||||
const int64_t n = (int64_t)rf.size() / 2;
|
||||
for (int64_t i = 0; i < n && pos; ++i) {
|
||||
p.pos.push_back((float)cursor);
|
||||
p.pos.push_back((float)rf[(size_t)i * 2]);
|
||||
p.pos.push_back((float)rf[(size_t)i * 2 + 1]);
|
||||
}
|
||||
p.segs.push_back({ kR2VRefImg, row, row + n, 0 });
|
||||
row += n;
|
||||
cursor += 1.0;
|
||||
} else if (r.kind == kR2VRefAudioOnly) {
|
||||
if (r.audio_t > 0) {
|
||||
const int64_t n = (int64_t)r.audio_t * 2;
|
||||
audio_grid(cursor, r.audio_t, w_low, w_high, pos);
|
||||
p.segs.push_back({ kR2VRefAudio, row, row + n, 0 });
|
||||
row += n;
|
||||
}
|
||||
cursor += (double)r.audio_t;
|
||||
} else {
|
||||
/* A video's soundtrack, at the video's time and the ends of the video's own width
|
||||
* axis, comes right before it. */
|
||||
std::vector<double> rf, rw;
|
||||
frame_grid(r.lat_h, r.lat_w, &rf, &rw);
|
||||
if (r.audio_t > 0) {
|
||||
const int64_t n = (int64_t)r.audio_t * 2;
|
||||
audio_grid(cursor, r.audio_t, rw.empty() ? 0.0 : rw.front(),
|
||||
rw.empty() ? 0.0 : rw.back(), pos);
|
||||
p.segs.push_back({ kR2VRefAudio, row, row + n, 0 });
|
||||
row += n;
|
||||
}
|
||||
const int64_t n = (int64_t)r.latent_t * (int64_t)(rf.size() / 2);
|
||||
video_grid(r.latent_t, rf, cursor, pos);
|
||||
p.segs.push_back({ kR2VRefImg, row, row + n, 0 });
|
||||
row += n;
|
||||
cursor += std::max((double)r.audio_t, video_t_span_sum(r.latent_t));
|
||||
}
|
||||
}
|
||||
|
||||
/* The soundtrack and the video the sampler steps, last. */
|
||||
{
|
||||
const int64_t n = (int64_t)g.audio_t * 2;
|
||||
audio_grid(cursor, g.audio_t, w_low, w_high, pos);
|
||||
p.segs.push_back({ kR2VAudio, row, row + n, 1 });
|
||||
row += n;
|
||||
}
|
||||
{
|
||||
const int64_t n = (int64_t)g.latent_t * (int64_t)frame_rows;
|
||||
video_grid(g.latent_t, frame, cursor, pos);
|
||||
p.segs.push_back({ kR2VVideo, row, row + n, 1 });
|
||||
row += n;
|
||||
}
|
||||
|
||||
p.rows = row;
|
||||
if (positions) {
|
||||
/* From (t, h, w) triples to [3, rows]. */
|
||||
std::vector<float> tri = std::move(p.pos);
|
||||
p.pos.assign((size_t)row * 3, 0.0f);
|
||||
for (int64_t r = 0; r < row; ++r) {
|
||||
p.pos[(size_t)r] = tri[(size_t)r * 3];
|
||||
p.pos[(size_t)row + r] = tri[(size_t)r * 3 + 1];
|
||||
p.pos[2 * (size_t)row + r] = tri[(size_t)r * 3 + 2];
|
||||
}
|
||||
}
|
||||
*out = std::move(p);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* A kind's modulation cell (rad_ref2va_pack.h): the latents and the prompt read their schedule's
|
||||
* embeddings, a keyframe or reference its stream's pinned ones. */
|
||||
static void cell_of_kind(int kind, int64_t S, int* md, int64_t* r0) {
|
||||
switch (kind) {
|
||||
case kR2VAudio: *md = 2; *r0 = S; break;
|
||||
case kR2VCondAudio:
|
||||
case kR2VRefAudio: *md = 2; *r0 = 3 * S; break;
|
||||
case kR2VText: *md = 1; *r0 = 0; break;
|
||||
case kR2VCond:
|
||||
case kR2VRefImg: *md = 0; *r0 = 2 * S; break;
|
||||
default: *md = 0; *r0 = 0; break;
|
||||
}
|
||||
}
|
||||
|
||||
void ref2va_mod_groups(const Ref2VAPack& p, int64_t S, const std::vector<Ref2VATagRun>& runs,
|
||||
Ref2VAModGroups* out) {
|
||||
out->bound.clear(); out->col.clear(); out->md.clear(); out->r0.clear();
|
||||
std::vector<Ref2VATagRun> sorted;
|
||||
for (const Ref2VATagRun& r : runs)
|
||||
if (r.end > r.start) sorted.push_back(r);
|
||||
std::sort(sorted.begin(), sorted.end(),
|
||||
[](const Ref2VATagRun& a, const Ref2VATagRun& b) { return a.start < b.start; });
|
||||
|
||||
/* The rows in pieces of one cell each: a segment is one, except the prompt, which the runs cut
|
||||
* into text and pad pieces, every one on the text's block. */
|
||||
struct Piece { int64_t start, end; int md; int64_t r0; };
|
||||
std::vector<Piece> pieces;
|
||||
for (const Ref2VASeg& s : p.segs) {
|
||||
if (s.end <= s.start) continue;
|
||||
if (s.kind != kR2VText) {
|
||||
Piece pc{ s.start, s.end, 0, 0 };
|
||||
cell_of_kind(s.kind, S, &pc.md, &pc.r0);
|
||||
pieces.push_back(pc);
|
||||
continue;
|
||||
}
|
||||
int64_t at = s.start;
|
||||
for (const Ref2VATagRun& r : sorted) {
|
||||
const int64_t a = std::max(r.start, at), b = std::min(r.end, s.end);
|
||||
if (a >= s.end) break;
|
||||
if (b <= a) continue;
|
||||
if (a > at) pieces.push_back({ at, a, 1, 0 });
|
||||
pieces.push_back({ a, b, r.tag, 0 });
|
||||
at = b;
|
||||
}
|
||||
if (at < s.end) pieces.push_back({ at, s.end, 1, 0 });
|
||||
}
|
||||
|
||||
/* A group opens where the cell changes; cells are numbered in their first group's order. */
|
||||
auto column_of = [&](int md, int64_t r0) {
|
||||
for (size_t c = 0; c < out->md.size(); ++c)
|
||||
if (out->md[c] == md && out->r0[c] == r0) return (int)c;
|
||||
out->md.push_back(md);
|
||||
out->r0.push_back(r0);
|
||||
return (int)out->md.size() - 1;
|
||||
};
|
||||
int cur = -1;
|
||||
bool open = false;
|
||||
int64_t prev_end = 0;
|
||||
for (const Piece& pc : pieces) {
|
||||
const int col = column_of(pc.md, pc.r0);
|
||||
if (!open || col != cur || pc.start != prev_end) {
|
||||
out->bound.push_back(open ? pc.start : 0);
|
||||
cur = col;
|
||||
open = true;
|
||||
out->col.push_back(col);
|
||||
}
|
||||
prev_end = pc.end;
|
||||
}
|
||||
if (open) out->bound.push_back(p.rows);
|
||||
}
|
||||
|
||||
} /* namespace minimaxh3 */
|
||||
@@ -0,0 +1,107 @@
|
||||
/* rad_ref2va_pack.h -- MiniMax-H3's packed sequence with keyframes and reference media, on the
|
||||
* host: ComfyUI's PackedLayout (comfy/ldm/minimax/model.py), tested against that code's own numbers
|
||||
* (tests/data/ref2va).
|
||||
*
|
||||
* The sequence is [text | keyframes | references in request order | soundtrack | video]. The
|
||||
* video's clock starts after every reference's time span; a keyframe sits on it at 5/3 a pixel
|
||||
* frame; a reference clip's soundtrack rows come right before its video rows, at the same time
|
||||
* origin. Keyframes and references keep a near-clean timestep; the sampler steps the last two
|
||||
* segments only.
|
||||
*/
|
||||
|
||||
#ifndef RAD_ARCH_MINIMAXH3_REF2VA_PACK_H
|
||||
#define RAD_ARCH_MINIMAXH3_REF2VA_PACK_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace minimaxh3 {
|
||||
|
||||
/* Segment kinds, named as the reference implementation names them. */
|
||||
enum Ref2VAKind {
|
||||
kR2VText = 0, /* the prompt's hidden states */
|
||||
kR2VCond, /* a keyframe's video latent rows */
|
||||
kR2VCondAudio, /* a keyframe's soundtrack latent rows */
|
||||
kR2VRefImg, /* a reference photo, or a reference clip's video */
|
||||
kR2VRefAudio, /* a reference clip's (or standalone audio's) soundtrack */
|
||||
kR2VAudio, /* the target soundtrack -- sampler-owned */
|
||||
kR2VVideo, /* the target video -- sampler-owned */
|
||||
kR2VKinds
|
||||
};
|
||||
|
||||
/* A reference's kind; a video with a soundtrack of its own is either of the last two. */
|
||||
enum Ref2VARefKind { kR2VRefImage = 0, kR2VRefAudioOnly = 1, kR2VRefVideo = 2, kR2VRefVideoAudio = 3 };
|
||||
|
||||
/* A keyframe: the frame of the video it is pinned at and its latent frames of each stream. */
|
||||
struct Ref2VAKeyframe {
|
||||
int frame; /* >= 0 */
|
||||
int video_t; /* 0: none */
|
||||
int audio_t; /* 0: none */
|
||||
};
|
||||
|
||||
/* A reference, in latents: its own grid and frames for a picture or video, its soundtrack's
|
||||
* length for one that has sound. */
|
||||
struct Ref2VARef {
|
||||
int kind; /* Ref2VARefKind */
|
||||
int lat_h, lat_w;
|
||||
int latent_t;
|
||||
int audio_t;
|
||||
};
|
||||
|
||||
/* The target, in latent units. */
|
||||
struct Ref2VAGeom {
|
||||
int latent_t, latent_h, latent_w, audio_t;
|
||||
};
|
||||
|
||||
struct Ref2VASeg {
|
||||
int kind;
|
||||
int64_t start, end; /* rows [start, end) */
|
||||
int update; /* 1 for the soundtrack and the video the sampler steps */
|
||||
};
|
||||
|
||||
struct Ref2VAPack {
|
||||
std::vector<Ref2VASeg> segs;
|
||||
int64_t rows = 0;
|
||||
/* The rotary positions, [3, rows]: every row's time, then row, then column. */
|
||||
std::vector<float> pos;
|
||||
};
|
||||
|
||||
/* A kind's modality in the modulation (ComfyUI's seg_tag): 0 video, 1 text, 2 sound. */
|
||||
int ref2va_seg_tag(int kind);
|
||||
/* Whether a kind's rows are video latents or soundtrack latents; text is neither. */
|
||||
int ref2va_is_img(int kind);
|
||||
int ref2va_is_audio(int kind);
|
||||
/* A keyframe's or reference's timestep is the larger of its stream's and these. */
|
||||
constexpr double kR2VVisualPin = 0.999, kR2VAudioPin = 1.0;
|
||||
|
||||
/* The modulation groups: runs of consecutive rows that read the same modulation cell, which the
|
||||
* segment's kind fixes (`md` its modality's projection, `r0` its block of timestep embeddings) --
|
||||
* except inside the prompt, where a picture's vision pads read the video projection on the text's
|
||||
* block, as ComfyUI tags them (`runs`). The modulated norm takes the group boundaries, the attention
|
||||
* the segments'. Groups that share a cell read one column of the modulation table (`col`), so the
|
||||
* table grows with the distinct cells, not with the references or the pads: nine pictures add one
|
||||
* cell. The groups cover the sequence; an empty segment opens none. */
|
||||
struct Ref2VATagRun {
|
||||
int64_t start, end; /* prompt rows [start, end) */
|
||||
int tag; /* the projection they read: 0 video for vision pads */
|
||||
};
|
||||
struct Ref2VAModGroups {
|
||||
std::vector<int64_t> bound; /* [groups + 1], from 0 to the rows */
|
||||
std::vector<int> col; /* [groups]: the cell the group reads */
|
||||
std::vector<int> md; /* [cells]: 0 video, 1 text, 2 sound */
|
||||
std::vector<int64_t> r0; /* [cells] */
|
||||
};
|
||||
/* `S` is the steps a schedule has, and the embeddings are [0, S) the video's, [S, 2S) the
|
||||
* soundtrack's, then each again with its pin, [2S, 3S) and [3S, 4S). The boundaries do not depend
|
||||
* on S. `runs` may come in any order; the parts outside the prompt are ignored. Without runs every
|
||||
* group has a cell of its own. */
|
||||
void ref2va_mod_groups(const Ref2VAPack& p, int64_t S, const std::vector<Ref2VATagRun>& runs,
|
||||
Ref2VAModGroups* out);
|
||||
|
||||
/* The sequence, and its positions when `positions`; -1 for a negative size or an unknown kind. */
|
||||
int ref2va_build(int text_len, const Ref2VAGeom& g, const std::vector<Ref2VAKeyframe>& keyframes,
|
||||
const std::vector<Ref2VARef>& refs, Ref2VAPack* out, bool positions = true);
|
||||
|
||||
} /* namespace minimaxh3 */
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,48 @@
|
||||
/* rad_vae_geom.cpp -- see rad_vae_geom.h. */
|
||||
|
||||
#include "rad_vae_geom.h"
|
||||
|
||||
namespace minimaxh3 {
|
||||
|
||||
/* vae.py's encode_temporal for more than one frame, its plain encode for one. */
|
||||
int64_t vae_latent_frames(int64_t frames) {
|
||||
if (frames <= 0) return -1;
|
||||
if (frames == 1) return 1;
|
||||
const int64_t clips = (frames + kVaeClipLength - 1) / kVaeClipLength;
|
||||
return clips * kVaeClipLatents - kVaeTokenDrop;
|
||||
}
|
||||
|
||||
int64_t vae_clip_latents(int64_t frames) {
|
||||
if (frames <= 0) return -1;
|
||||
if (frames == 1) return 1;
|
||||
return (frames + 3) / 4; /* ceil(ceil(T / 2) / 2) */
|
||||
}
|
||||
|
||||
/* Every strided convolution (k = 2 s, pad ceil(s / 2)) divides a padded length exactly. */
|
||||
int64_t vae_audio_latents(int64_t samples) {
|
||||
if (samples < 0) return -1;
|
||||
return (samples + kAudioHop - 1) / kAudioHop;
|
||||
}
|
||||
|
||||
const double kVaeLatentsMean[24] = {
|
||||
0.858090341091156, -0.9606591463088989, 1.0661640167236328, -0.5090325474739075,
|
||||
-0.2727581858634949, -1.3675414323806763, -0.2553254961967468, -0.26907554268836975,
|
||||
-0.5376840829849243, -0.0464097298681736, 0.6657370328903198, 0.19690127670764923,
|
||||
-0.5460608005523682, -0.4035342037677765, -0.23683024942874908, 0.25928452610969543,
|
||||
-0.30133944749832153, 0.211341992020607, -1.1206848621368408, 0.3581933379173279,
|
||||
-0.04225143790245056, 0.2604829967021942, 0.22864092886447906, 0.7056031823158264,
|
||||
};
|
||||
|
||||
const double kVaePixelMean[3] = { 0.485, 0.456, 0.406 };
|
||||
const double kVaePixelStd[3] = { 0.229, 0.224, 0.225 };
|
||||
|
||||
const double kVaeLatentsStd[24] = {
|
||||
1.2223774194717407, 1.2767263650894165, 1.68317747116088865, 1.7549455165863037,
|
||||
1.5636216402053833, 2.194143533706665, 0.96531379222869875, 1.05698859691619875,
|
||||
0.841948926448822, 0.7729952931404114, 1.8955937623977661, 0.946841835975647,
|
||||
0.7996809482574463, 0.44988900423049925, 0.7197399735450745, 0.69362932443618775,
|
||||
2.961095094680786, 2.7694199085235595, 3.0496184825897215, 2.1088054180145265,
|
||||
3.276226282119751, 3.1627357006073, 2.28168129920959475, 2.6127843856811525,
|
||||
};
|
||||
|
||||
} /* namespace minimaxh3 */
|
||||
@@ -0,0 +1,43 @@
|
||||
/* rad_vae_geom.h -- the latents MiniMax-H3's VAE encoders make of a media's frames or samples,
|
||||
* and their normalisation constants, on the host. ComfyUI's comfy/ldm/minimax/vae.py and
|
||||
* audio_vae.py, tested against those encoders' own outputs (tests/data/vae_geom). */
|
||||
|
||||
#ifndef RADIANCE_ARCH_MINIMAXH3_RAD_VAE_GEOM_H
|
||||
#define RADIANCE_ARCH_MINIMAXH3_RAD_VAE_GEOM_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace minimaxh3 {
|
||||
|
||||
/* The video VAE: 16 pixels a latent side, and in time clips of 17 frames to 5 latent frames
|
||||
* (17 -> 9 -> 5), of which an encode of more than one frame drops the last 3. */
|
||||
constexpr int kVaeRatio = 16;
|
||||
constexpr int kVaeClipLength = 17;
|
||||
constexpr int kVaeClipLatents = 5;
|
||||
constexpr int kVaeTokenDrop = 3;
|
||||
|
||||
/* The audio VAE: strides 2 4 4 5 5, a latent per 800 samples (40 a second at 32 kHz), the samples
|
||||
* padded with zeros to a whole latent. */
|
||||
constexpr int kAudioHop = 800;
|
||||
|
||||
/* The latent frames of `frames` pixel frames: 1 for a picture, else 5 a clip of 17 (the last
|
||||
* padded by repeating its last frame) less 3. -1 for no frames. */
|
||||
int64_t vae_latent_frames(int64_t frames);
|
||||
|
||||
/* The latent frames one clip of `frames` encodes to, ceil(T / 4) (one frame stays one). */
|
||||
int64_t vae_clip_latents(int64_t frames);
|
||||
|
||||
/* The latents of `samples` samples; -1 for a negative count. */
|
||||
int64_t vae_audio_latents(int64_t samples);
|
||||
|
||||
/* A video latent is normalised as (moments - mean) / std, vae.py's LATENTS_MEAN and LATENTS_STD. */
|
||||
extern const double kVaeLatentsMean[24];
|
||||
extern const double kVaeLatentsStd[24];
|
||||
|
||||
/* A pixel x in [0, 1] goes in as (x - mean) / std, ImageNet's. */
|
||||
extern const double kVaePixelMean[3];
|
||||
extern const double kVaePixelStd[3];
|
||||
|
||||
} /* namespace minimaxh3 */
|
||||
|
||||
#endif
|
||||
@@ -107,16 +107,11 @@ using MtpHead = MtpFP8;
|
||||
#endif
|
||||
|
||||
/* The weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h): a weight's first
|
||||
* kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows. Qwen3.8-27B MXFP4 + DFlash2 at tp 2
|
||||
* on 2x R9700 (Gen5 x8), one round each, no speculation, x1 / x4 / x8 / x16 tok/s against none
|
||||
* (61.2 / 225.0 / 403.7 / 650.8): 8 MB 65.1 / 246.4 / 410.9 / 663.3; 10 MB 66.0 / 250.1 / 425.0 /
|
||||
* 668.5; 12 MB 67.9 / 251.2 / 438.6 / 668.1; 14 MB 67.8 / 249.5 / 432.4 / 659.1; 16 MB 67.0 / 244.9 /
|
||||
* 422.7 / 649.4; 20 MB 63.4 / 232.0 / 408.1 / 630.7; 32 MB 57.9 / 210.2 / 372.8 / 605.9 -- past
|
||||
* ~12 MB the read outlasts the reduction and takes bandwidth from the GEMM it should feed. Reads up
|
||||
* to 128 rows: x32 963.8 against 956.0, x64 1206.7 against 1216.6, so the ceiling is 32 rows (a
|
||||
* verify of four sequences at speculation 7). With speculation 7 (three rounds) x1..x16 +0.1..+1.9 %.
|
||||
* The drafter's reads (Dflash2::Config::prefetch) take the same size: speculation 7, eight rounds,
|
||||
* median x1 +6 %, x16 unchanged. */
|
||||
* kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows. Qwen3.8-27B MXFP4 + DFlash2, tp
|
||||
* 2 on two R9700s, no speculation: 12 MB was best, +11 % at one stream, +9 % at eight, +3 % at
|
||||
* sixteen; past ~12 MB the read outlasts the reduction and takes bandwidth from the GEMM it feeds.
|
||||
* Up to 32 rows (a verify of four sequences at speculation 7): at 32 and 64 rows the reads are a
|
||||
* wash. The drafter's reads (Dflash2::Config::prefetch) take the same size. */
|
||||
constexpr int64_t kPrefetchBytes = (int64_t)12 << 20;
|
||||
constexpr int64_t kPrefetchStepRows = 32;
|
||||
|
||||
@@ -125,9 +120,8 @@ struct Layer {
|
||||
AttnGatedFP8 attn;
|
||||
GdnFP8 gdn;
|
||||
Ffn mlp;
|
||||
/* The reads beside the decode all-reduces (prefetch_beside, rad_arch.h): gate_up's leading
|
||||
* bytes beside the mixer's reduction, the next layer's first projection's beside the
|
||||
* feed-forward's. 0 where none is declared. */
|
||||
/* gate_up's leading bytes beside the mixer's reduction, the next layer's first projection's
|
||||
* beside the feed-forward's; 0 where none is declared. */
|
||||
rad_op op_pf_gu = 0, op_pf_next = 0;
|
||||
rad_weight pf_gu_w = 0, pf_next_w = 0;
|
||||
};
|
||||
@@ -1017,6 +1011,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
gs.out = nm.ckpt("%s.%lld.linear_attn.out_proj.weight", pre, (long long)l);
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_state));
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_conv));
|
||||
/* Lane 1 carries no collectives here (rad_block_gdn_fp8.h, ab_lane). */
|
||||
lay.gdn.ab_lane = true;
|
||||
RAD_ARCH_TRY(lay.gdn.declare(b, nm, g, gc, (int)l, m.kv_state, m.kv_conv, gw, gs,
|
||||
f.mix_fold, false, f.mix_ar_in, f.mix_ar_out));
|
||||
}
|
||||
@@ -1047,13 +1043,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
#endif
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* ---- the weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h). At decode
|
||||
* heights each block's reduction leaves the card's memory idle for its round trip over the link,
|
||||
* so the GEMM behind it has its weight's leading bytes read into the on-die cache there: gate_up
|
||||
* behind the mixer's reduction, the next layer's first projection (the delta net's in-projection,
|
||||
* an attention layer's q|gate) behind the feed-forward's. Only at more than one rank;
|
||||
* RADIANCE_PREFETCH_BESIDE=0 issues none (prefetch_beside). */
|
||||
if (g.world > 1 && rad_op_declared(b, "prefetch")) {
|
||||
/* ---- the weight reads beside the decode all-reduces. A decode-height reduction leaves the
|
||||
* card's memory idle for its round trip, so the next GEMM's leading weight bytes are read
|
||||
* into the on-die cache then: gate_up behind the mixer's, the next layer's first projection
|
||||
* behind the feed-forward's. At more than one rank; --weight-prefetch off declares none. */
|
||||
if (g.world > 1 && !ctx->weight_prefetch_off && rad_op_declared(b, "prefetch")) {
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.pf_gu_w = lay.mlp.gate_up.w;
|
||||
@@ -1538,9 +1532,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
RAD_ISSUE_N(c, m.op_rope_cs, batch->n_tok,
|
||||
rope_pos1(batch, batch->n_tok), RAD_B(m.b_rope_cs));
|
||||
|
||||
/* The reads beside the reductions go on decode steps of up to kPrefetchStepRows rows, none on a
|
||||
* step that carries a prompt's rows. This ceiling, not prefetch_beside's own (16), decides: it
|
||||
* is passed a height of 1 where the step qualifies. */
|
||||
/* Decode steps of up to kPrefetchStepRows rows only. This ceiling decides, not
|
||||
* prefetch_beside's own (16): it is passed a height of 1 where the step qualifies. */
|
||||
const int64_t pf_h =
|
||||
batch->phase == RAD_PHASE_DECODE && batch->n_tok <= kPrefetchStepRows ? 1 : INT64_MAX;
|
||||
for (int64_t li = 0; li < (int64_t)m.layers.size(); ++li) {
|
||||
|
||||
@@ -1090,6 +1090,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* paths must give identical text; any difference is a defect. */
|
||||
if (m.qsaw.qk) {
|
||||
lay.attn.qsa_sel = m.qsaw.sel;
|
||||
lay.attn.qsa_nsel = m.qsaw.nsel;
|
||||
lay.attn.qsa_sequ = m.qsaw.sequ;
|
||||
lay.attn.qsa_topk = m.qsacfg.topk;
|
||||
/* The exactness bound, below which prefill issues the cheaper dense attention.
|
||||
@@ -1357,6 +1358,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.mtp.attn.kv_block = 4;
|
||||
if (m.qsaw.qk) {
|
||||
m.mtp.attn.qsa_sel = m.qsaw.sel;
|
||||
m.mtp.attn.qsa_nsel = m.qsaw.nsel;
|
||||
m.mtp.attn.qsa_sequ = m.qsaw.sequ;
|
||||
m.mtp.attn.qsa_topk = m.qsacfg.topk;
|
||||
m.mtp.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1;
|
||||
@@ -1692,6 +1694,9 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
* mapped table). */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
/* The gated attention block declares the streamed store and the resolve
|
||||
* (rad_block_attn_gated_fp8.h). */
|
||||
out->kv_stream_ok = 1;
|
||||
out->draft_depth = 0;
|
||||
if (meta_int2(meta, "qwen4exp.mtp_num_hidden_layers", "mtp_num_hidden_layers", 0) > 0)
|
||||
out->draft_depth = 3;
|
||||
|
||||
Reference in new issue
Block a user