qwen4exp: verify/decode pass launch order, prefetch width, chain polling, turnover slots

Lossless (no kernel arithmetic or operand change): the router weight is read beside the mixer
all-reduce; k/v projections before q|gate; the indexer's keys behind the attention launches within
the exact bound; verify-height prefetch at 32 workgroups (`prefetch` takes an optional `blocks`
param) and the shared down arm before the routed down from 2 rows (kVerifyRows); chain waits poll by
grid size (R4D_CHAIN_TINY/SMALL/MID); the mover's kept-free turnover slots follow the swaps the
engine asked for (MoverConfig::turnover_adaptive) instead of a fixed 640.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Code000andClaude Opus 5.5 authored and StillDeadcode committed 2026-11-17 20:33:07 +01:00
1 parent 946a6f9e2b
commit ca7a7212ec
20 files changed
+598 -44

No files matched your search

+22 -1
View File
@@ -676,8 +676,13 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
}
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. A plugin declares
* none where the deployment turns the reads off (RadBuildCtx::weight_prefetch_off). */
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes, int64_t blocks = 0) {
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
/* `blocks`: the workgroups reading, where the architecture measured its own count (docs/OPS.md);
* 0 leaves the kernel's. Stated only when asked, so a declaration without it is what it was. */
if (blocks > 0)
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes), RAD_INT("blocks", blocks)),
RAD_WEIGHTS(w));
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
}
@@ -1482,6 +1487,22 @@ inline void batch_split(const RadBatch* b, int64_t* n_seq_dec, int64_t* n_tok_de
* always; no later layer issues a query, a score or a select. */
enum QsaUse : int { kQsaSelect = 0, kQsaUnread = 1, kQsaOnce = 2 };
/* Ops of a chain that is independent of a block's own, for the block to issue behind its ordered
* launches. A recorded pass lets a launch start beside the last ordered one when it touches
* nothing in flight (Ctx::haz_mark). A dependent chain issued in one piece is therefore a row of
* ordered launches, each paid in turn; issued one op behind each of the block's own ordered
* launches, every op of it is unordered behind the block's launch in front of it, and still
* behind its own predecessor, which that launch already waited for. The block calls `at(k)` for
* k = 0, 1, 2, ... behind its ordered launches in turn, and the owner issues what is left once
* the block returns. The chain must read nothing the block writes and write nothing the block
* touches, and its buffers must be excluded from sharing (rad_buf_concurrent): they are in use at
* launches the linear order puts after their last declared use. */
struct SideOps {
void (*fn)(void* u, int stage) = nullptr;
void* u = nullptr;
void at(int stage) const { if (fn) fn(u, stage); }
};
/* RADIANCE_DEBUG_QSA_EAGER: every step is kQsaSelect, the issue sequence before the forms above
* existed. An instrument for comparing the two (the text must not move); read once. */
inline bool qsa_eager() {
+33 -6
View File
@@ -126,6 +126,14 @@ struct AttnGatedFP8 {
* (decl_prefetch, rad_arch.h), issued behind the q, k and v projections on decode steps
* (prefetch_beside). 0 where none is declared. */
rad_op op_pf_o = 0;
/* The same read as a second op for steps of at least pf_o_v_rows rows, where the
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
* every step takes op_pf_o. */
rad_op op_pf_o_v = 0;
int64_t pf_o_v_rows = 0;
/* The most rows of a decode step whose k and v projections are issued in front of the q|gate
* projection (step()); 0, the default, keeps the declared order on every step. */
int64_t kv_first_rows = 0;
NormQuantFP8 nq_h{};
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
@@ -183,8 +191,12 @@ struct AttnGatedFP8 {
/* The block's tail, declared last by every rank: the all-reduce and the trailing add. */
int declare_out(RadBuilder* b, bool add_out);
/* `own_ar` false: the caller issues the all-reduce itself (GdnFP8::step says when). */
/* `side`: an independent chain's ops, issued behind this block's ordered launches (SideOps,
* rad_arch.h): one behind the prologue and the store, one behind the attention, one behind
* the gate where the gate is a launch of its own. Null, and on the paths that return early,
* nothing is asked of it. */
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
ArPieces* pieces = nullptr) const;
ArPieces* pieces = nullptr, const SideOps* side = nullptr) const;
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
@@ -621,7 +633,7 @@ inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
}
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
ArPieces* pieces) const {
ArPieces* pieces, const SideOps* side) const {
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
@@ -683,11 +695,23 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
return;
}
qg.step(c, w.h, w.qg, T);
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
/* The three projections read the same input and none reads another's output, so a recorded
* pass starts them together (Ctx::haz_mark) whatever their order; the order decides which
* the card launches first. On a decode step of up to `kv_first_rows` rows the two small ones
* go first: behind the wide q|gate projection their launches wait until its blocks are all
* on the card, and the prologue then waits for them. Qwen3.8-Flash-Next at tp 2, chain 3
* with coupling (twelve trunk layers and the head's): -0.66% a step. */
if (T <= kv_first_rows && batch->phase == RAD_PHASE_DECODE) {
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
qg.step(c, w.h, w.qg, T);
} else {
qg.step(c, w.h, w.qg, T);
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
}
/* The out projection's weight, read beside the prologue and the attention (op_pf_o). */
prefetch_beside(c, op_pf_o, o.w, T);
prefetch_beside(c, op_pf_o_v && T >= pf_o_v_rows ? op_pf_o_v : op_pf_o, o.w, T);
/* Fused or unfused prologue. The fused kernel takes the whole [q|gate] projection and splits it
* itself, and rotates k in place like the unfused ops. It reads one rotary component per
@@ -732,6 +756,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
}
if (!fused_kv && !folded_stream) store_cache(c, kvb, slot, T);
if (side) side->at(0);
/* Sparse attention issues one row per query. `attn_paged` indexes its block table and length
* by row, and a row need not be a sequence, so T queries issued as T rows of q_len 1, each with
@@ -900,6 +925,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
/* Every attention launch of this layer is issued: start the next layer's stage copy, which
* crosses the link under the out projection and the next layer's projections. */
if (kvb && kvb->stream) kv_stage_next(c, kv, layer);
if (side) side->at(1);
if (gated) {
/* the sparse attention gated and quantised in its merge */
} else if (op_sig) {
@@ -913,6 +939,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.attn.x, T),
brows(w.attn.cq(), T), brows(w.attn.cs(), T), brows(w.attn.x, T));
}
if (side && !gated) side->at(2);
o.step(c, w.attn, w.h.x, T);
if (own_ar && op_ar && !ar_taken(g, T, ar_out, ar_out_take))
+8 -2
View File
@@ -134,6 +134,11 @@ struct GdnFP8 {
* pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */
rad_op op_pf_out = 0;
int64_t pf_out_rows = 0, pf_out_seqs = 0;
/* The same read as a second op for steps of at least pf_out_v_rows rows, where the
* architecture measured another workgroup count for them (decl_prefetch's `blocks`); 0 where
* every step takes op_pf_out. */
rad_op op_pf_out_v = 0;
int64_t pf_out_v_rows = 0;
rad_op op_ar = 0, op_add = 0;
/* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_fp8.h). */
bool ar_out = false;
@@ -508,11 +513,12 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
* holds nothing behind it), else on the second lane behind a join from lane 0 (as
* prefetch_beside). */
if (op_pf_out && D > 0 && D <= pf_out_seqs && P == 0 && T <= pf_out_rows) {
const rad_op pf = op_pf_out_v && T >= pf_out_v_rows ? op_pf_out_v : op_pf_out;
if (prefetch_lane0()) {
RAD_ISSUE(c, op_pf_out, RAD_W(out.w));
RAD_ISSUE(c, pf, RAD_W(out.w));
} else {
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK)
RAD_ISSUE(c, op_pf_out, RAD_W(out.w));
RAD_ISSUE(c, pf, RAD_W(out.w));
rad_lane(c, 0);
}
}
+18 -1
View File
@@ -388,6 +388,10 @@ struct MoeFP8 {
* which the shared arm's first stage then runs beside the router instead (pass()). */
bool gu_trellis = false;
static constexpr int64_t kSharedFirstRows = 100;
/* The steps, by their rows [lo, hi], whose shared down projection is issued in front of the
* routed down GEMM instead of behind it (pass()); hi 0, the default, keeps it behind on
* every step. */
int64_t sh_down_first_lo = 0, sh_down_first_hi = 0;
LinearFP8 sh_gate_up{}, sh_down{};
rad_op op_router = 0, op_topk = 0, op_scatter = 0;
/* `op_scatter` is moe_scatter_inv and `op_gather` moe_gather_inv: the sort writes `w.inv` and
@@ -1942,6 +1946,19 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
gq_exp.step(c_, w.egu, rows * k, 0, rows * k);
if (shared && !(op_sh_gated && rows <= sh_gated_rows)) gq_sh.step(c_, w.sgu, T, r0, rows);
/* The shared arm's down projection in front of the routed down GEMM on a step of
* [sh_down_first_lo, sh_down_first_hi] rows. Behind it (below) the two still run together,
* but the card launches the arm only once every block of the routed GEMM is on it; at a
* verify step's forty routed rows that is a few microseconds before that GEMM ends, and the
* gather then waits for the arm. In front, the arm is the ordered launch behind the two
* quantisers and the routed GEMM starts beside it (it reads nothing the arm writes): the same
* start for the routed GEMM, and the arm is done long before it. At one row the routed GEMM
* is a quarter of the blocks, the arm behind it is launched in time, and in front it only
* delays that GEMM's launch (+0.38% a step), hence the lower bound. The arm's buffers are
* excluded from sharing (declare), so the order is free. Qwen3.8-Flash-Next at tp 2 with
* coupling, chain 1 / 2 / 3 (two / three / four rows): -0.28% / -0.21% / -0.25% a step. */
const bool sh_dn_first = shared && T >= sh_down_first_lo && T <= sh_down_first_hi;
if (sh_dn_first) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
if (c.expert_bf16)
RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.x, rows * k), RAD_WTAB(w_dn[0], ne),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.edn, rows * k));
@@ -1976,7 +1993,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
RAD_ISSUE_N(c_, op_pdn, rows, brows(pff.x, rows * k), RAD_WTAB(w_pdn[0], np),
brows(w.sorted, rows * k), poff, brows(w.edn, rows * k));
}
if (shared) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
if (shared && !sh_dn_first) sh_down.step(c_, w.sff, w.sout, T, r0, rows);
/* The calibration tap reads the GEMMs' operands and writes nothing they touch, so it does not
* change the model's output. */
if (op_gram_gu && !calib_done) {
+43 -16
View File
@@ -135,7 +135,30 @@ struct QsaIndexer {
/* Stores the pass's block keys and tail exactly as step() does, with no query, score or
* selection (see AttnGatedFP8::store_kv). */
void store(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
bool store_keys(RadCtx* c, const RadBatch* batch) const;
/* `part` 0 issues all of it; 1, 2 and 3 its three stages apart and in that order (the work
* list, the block keys, the tail store), for a caller that issues them behind another block's
* launches (deferrable, below). */
bool store_keys(RadCtx* c, const RadBatch* batch, int part = 0) const;
/* Whether this step's keys and tail may be issued behind the attention block's launches
* instead of in front of them (SideOps, rad_arch.h): nothing reads a selection of this
* layer's (`use` as step() resolves it), so the attention reads nothing the three ops write.
* The caller answers for the buffers (Wire: qk, stage, page, bpos, nc excluded from
* sharing). */
bool deferrable(const RadBatch* batch, int use, bool first) const {
if (!on() || qsa_eager()) return false;
/* step() stores no keys for a batch without the attention's group; leave that to it. */
if (!kv_batch(batch, c.kv_attn)) return false;
if (use == kQsaOnce) use = first ? kQsaSelect : kQsaUnread;
return use == kQsaUnread;
}
/* What step() issues on a deferrable step, a piece at a time: the projection, then
* store_keys's stages 1..3. */
void step_proj(RadCtx* c, const ActFP8& in, const RadBatch* batch) const {
proj.step(c, in, w.qk, batch->n_tok);
}
void step_part(RadCtx* c, const RadBatch* batch, int part) const {
(void)store_keys(c, batch, part);
}
};
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -275,7 +298,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
/* Stores the block keys of the blocks the pass completes and the tail of raw keys after them,
* from the projection's raw-key head. False when the step has no batch for the indexer's
* groups. */
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch, int part) const {
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t nw = (c.heads + 1) * c.head_dim;
const int64_t koff = c.heads * c.head_dim; /* the raw-key head, after the query heads */
@@ -297,20 +320,24 @@ inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
const bool mc = g.rope_mc && batch->rope_pos;
RadOperand bpos = g.rope_mc ? RAD_B_COL(w.bpos, 0, mc ? 3 : 1) : brows(w.bpos, work);
if (g.rope_mc) bpos.rows = work;
RAD_ISSUE_N(c_, op_work, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw),
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
brows(w.nc, S));
RAD_ISSUE_N(c_, op_bkey, work,
brows(w.stage, work * c.ratio), RAD_W(w_kn),
brows(w.page, work), bpos,
kv_cache(kv_bk, layer));
if (part <= 1)
RAD_ISSUE_N(c_, op_work, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw),
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
brows(w.nc, S));
if (part == 1) return true;
if (part == 0 || part == 2)
RAD_ISSUE_N(c_, op_bkey, work,
brows(w.stage, work * c.ratio), RAD_W(w_kn),
brows(w.page, work), bpos,
kv_cache(kv_bk, layer));
if (part == 2) return true;
RAD_ISSUE_N(c_, op_tail, T,
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
praw(batch->positions, RAD_I32, T),
+108 -2
View File
@@ -114,11 +114,35 @@ using namespace rad::arch;
* and 13.17): a read here pays ~2 us of launch for what it saves. */
constexpr int64_t kGdnOutPrefetchBytes = (int64_t)8 << 20;
constexpr int64_t kGdnOutPrefetchSeqs = 4;
/* The rows from which a decode step is taken for a speculative verify, a step of several rows:
* where the shared arm's place and the reads' workgroup count below help, against the one row of
* a plain decode step, where both cost. ms a step at tp 2 with coupling, in one server with the
* rounds interleaved, at two / three / four rows (chain 1 / 2 / 3) and at one: the arm's down
* projection in front -0.28% / -0.21% / -0.25% and +0.38%; the reads at 32 workgroups -0.65% /
* -0.35% / -0.31% and +0.41%. */
constexpr int64_t kVerifyRows = 2;
/* A full-attention layer's out projection likewise, read behind its q, k and v projections
* (AttnGatedFP8::op_pf_o): the prologue and the attention between them and the projection are
* short launches with the memory idle. Twelve layers, so less: five interleaved rounds, ms a step
* without -> with, one stream 12.51 -> 12.45 (every round), two 16.88 -> 16.85. */
constexpr int64_t kAttnOutPrefetchBytes = (int64_t)8 << 20;
/* The workgroups of this model's weight reads on a verify step (the `prefetch` op's `blocks`, from
* kVerifyRows rows): 32, half the kernel's own 64. The reads run beside the delta net's update,
* the attention's prologue and the connections' reductions, all latency-bound kernels of a few
* loads a block whose loads queue behind the read's, and at four rows the update lasts half again
* as long as at one, so a slower read still lands. Chain 3 with coupling at tp 2, ms a step
* against 64 in one server, interleaved: 16 +0.77%, 24 +0.14%, 32 -0.31%, 48 -0.24%, 128 +2.0%,
* 256 +7.4%; -0.6% at 32 with the router's read beside. A one-row step keeps 64 (kVerifyRows). */
constexpr int64_t kPrefetchBlocksVerify = 32;
/* A layer's router likewise, read behind its mixer's out projection, beside the mixer's reduction
* and the feed-forward's connection read (both latency, with the card's memory mostly idle): the
* router is 2.5 MB of bf16 that its GEMM otherwise streams cold in front of a top-k that waits for
* all of it. Chain 3 with coupling at tp 2, ms a step without -> with, each the mean of two
* interleaved rounds in one server: 12.19 -> 12.13 (-0.42% and -0.93%); 12.14 -> 12.09 in another
* session. The same read of the shared expert's two weights, or of the indexer's projection, moved
* nothing (-0.02%, -0.04%, +0.04%), and of the mixer's first projection in front of its
* connection read cost 1.0%: a read there takes the memory from the connection's own. */
constexpr int64_t kRouterPrefetchBytes = (int64_t)4 << 20;
struct Layer {
int full = 0;
@@ -136,6 +160,11 @@ struct Layer {
/* The layer's calibration inputs (rad_calib_full.h, site_i8), -1 where this run records none:
* the mixer's input (the delta net's in projection, or q, k and v) and its output projection's. */
int cs_in = -1, cs_o = -1;
/* The router's weight read beside the mixer's reduction (kRouterPrefetchBytes); 0 where the
* deployment reads no weights ahead. */
rad_op op_pf_router = 0;
/* The same at a verify step's workgroup count (kPrefetchBlocksVerify), from kVerifyRows rows. */
rad_op op_pf_router_v = 0;
};
struct Model {
@@ -235,6 +264,9 @@ struct Model {
rad_weight w_tok = 0, w_lm_head = 0;
rad_op op_embed = 0, op_embed_ar = 0, op_rope_cs = 0, op_gather = 0, op_logits = 0;
/* The indexer's within-step buffers store_keys touches are excluded from sharing (declare),
* so a layer's keys may be issued behind its attention's launches (step_serial, QsaSide). */
bool qsa_defer = false;
/* ---- media (arch/common/rad_block_vit.h): the vision tower and the scatter of its rows over
* the token embeddings, declared only when the container carries a tower and the deployment
@@ -884,6 +916,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
{ g.max_tok, m.qsacfg.topk + 1 });
m.qsaw.nsel = decl_b(b, nm.f("qsa_nsel"), RAD_I32, { g.max_tok });
m.qsaw.sequ = decl_b(b, nm.f("qsa_sequ"), RAD_I32, { g.max_tok });
if (m.qsaw.qk && m.qsaw.stage && m.qsaw.page && m.qsaw.bpos && m.qsaw.nc) {
/* What store_keys reads and writes is in use behind the attention's launches when a
* layer's keys are deferred behind them (QsaSide), past the last use the linear order
* gives these buffers, so the planner must not lay an attention buffer over them.
* A few MiB of arena (qk is the largest, max_tok x 640 bf16). */
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.qk));
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.stage));
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.page));
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.bpos));
RAD_ARCH_TRY(rad_buf_concurrent(b, m.qsaw.nc));
m.qsa_defer = true;
}
if (!m.qsaw.qk || !m.qsaw.q || !m.qsaw.stage || !m.qsaw.page ||
!m.qsaw.bpos || !m.qsaw.nc || !m.qsaw.score || !m.qsaw.sel || !m.qsaw.nsel ||
!m.qsaw.sequ)
@@ -1325,6 +1369,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ARCH_TRY(m.mixer.declare(b, nm, g, nm.f("output_hc"), mc, mixw, mixs));
}
/* ---- the issue order of a decode step's small launches (AttnGatedFP8::kv_first_rows,
* MoeFP8::sh_down_first_lo): at decode and verify heights the k and v projections go in
* front of the q|gate projection, and from kVerifyRows rows the shared down projection in
* front of the routed down GEMM, so the card launches the small ones while the wide one is
* still being placed. The same kernels on the same operands; only what a recorded pass
* starts first changes. */
{
for (Layer& lay : m.layers) {
if (lay.full) lay.attn.kv_first_rows = kPrefetchRows;
lay.mlp.sh_down_first_lo = kVerifyRows;
lay.mlp.sh_down_first_hi = kPrefetchRows;
}
}
/* ---- the delta nets' out projections, read beside their decode recurrent updates
* (kGdnOutPrefetchBytes), and the full-attention layers' beside the attention
* (kAttnOutPrefetchBytes). At more than one rank; --weight-prefetch off declares none. */
@@ -1332,11 +1390,23 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
for (Layer& lay : m.layers) {
if (lay.full) {
lay.attn.op_pf_o = decl_prefetch(b, lay.attn.o.w, kAttnOutPrefetchBytes);
lay.attn.op_pf_o_v = decl_prefetch(b, lay.attn.o.w, kAttnOutPrefetchBytes,
kPrefetchBlocksVerify);
lay.attn.pf_o_v_rows = kVerifyRows;
continue;
}
lay.gdn.op_pf_out = decl_prefetch(b, lay.gdn.out.w, kGdnOutPrefetchBytes);
lay.gdn.pf_out_rows = kPrefetchRows;
lay.gdn.pf_out_seqs = kGdnOutPrefetchSeqs;
lay.gdn.op_pf_out_v = decl_prefetch(b, lay.gdn.out.w, kGdnOutPrefetchBytes,
kPrefetchBlocksVerify);
lay.gdn.pf_out_v_rows = kVerifyRows;
}
for (Layer& lay : m.layers) {
if (!lay.mlp.w_router) continue;
lay.op_pf_router = decl_prefetch(b, lay.mlp.w_router, kRouterPrefetchBytes);
lay.op_pf_router_v = decl_prefetch(b, lay.mlp.w_router, kRouterPrefetchBytes,
kPrefetchBlocksVerify);
}
}
@@ -1486,6 +1556,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* Set before declare(), as for the trunk: `attn_paged` declares `sel` and `seqused` as
* reads, which must precede the op. */
m.mtp.attn.kv_block = 4;
/* The head's layer takes the trunk's issue order at decode heights (declare, above). */
m.mtp.attn.kv_first_rows = kPrefetchRows;
m.mtp.mlp.sh_down_first_lo = kVerifyRows;
m.mtp.mlp.sh_down_first_hi = kPrefetchRows;
if (m.qsaw.qk) {
m.mtp.attn.qsa_sel = m.qsaw.sel;
m.mtp.attn.qsa_nsel = m.qsaw.nsel;
@@ -1737,6 +1811,18 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
}
}
/* A full-attention layer's indexer keys behind its attention's launches (QsaIndexer::deferrable,
* SideOps): store_keys's three stages in turn, one a call, and whatever is left at flush(). */
struct QsaSide {
RadCtx* c = nullptr;
const QsaIndexer* q = nullptr;
const RadBatch* batch = nullptr;
int next = 1;
void one() { if (next <= 3) q->step_part(c, batch, next++); }
void flush() { while (next <= 3) one(); }
static void at(void* u, int) { ((QsaSide*)u)->one(); }
};
/* The trunk one stream at a time over the whole step: every step a span of 1 makes, and every
* other where step_pipelined's conditions do not hold. */
static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
@@ -1771,12 +1857,32 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_
/* The indexer runs first, since the attention reads its selection. The block's input is
* already normed and quantised by the connection (`ext_in`), so `w.h` is final. */
if (l.full) {
l.qsa.step(c, l.attn.w.h, batch, pcu, l.attn.qsa_use(batch), qsa_first);
const int use = l.attn.qsa_use(batch);
/* At decode heights within the exactness bound nothing of the layer reads the
* indexer's keys or tail (they are for later steps), so only the projection stays in
* front, beside the attention's own, and the three launches behind it ride behind the
* attention's (QsaSide) instead of holding its projections back in turn: -0.3% to
* -0.8% a step on chain 3 with coupling at tp 2. */
if (m.qsa_defer && T <= kPrefetchRows && batch->phase == RAD_PHASE_DECODE &&
l.qsa.deferrable(batch, use, qsa_first)) {
QsaSide sd{c, &l.qsa, batch};
const SideOps so{QsaSide::at, &sd};
l.qsa.step_proj(c, l.attn.w.h, batch);
l.attn.step(c, batch, true, nullptr, &so);
sd.flush();
} else {
l.qsa.step(c, l.attn.w.h, batch, pcu, use, qsa_first);
l.attn.step(c, batch);
}
if (l.qsa.on()) qsa_first = false;
l.attn.step(c, batch);
}
else l.gdn.step(c, batch);
if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, T);
/* The router's weight, read beside the write's reduction and the read behind it. */
if (batch->phase == RAD_PHASE_DECODE)
prefetch_beside(c, l.op_pf_router_v && T >= kVerifyRows ? l.op_pf_router_v
: l.op_pf_router,
l.mlp.w_router, T);
l.hc_mix.write(c, T, 0, T);
dbg_resid(c, (int)li, "mix", g.n_embd, m.b_h, m.a_x.x);
l.hc_ffn.read_pieces(c, T);
+3
View File
@@ -1017,6 +1017,9 @@ void Engine::tiering_dispatch(Rank& r, int step) {
* credited; the next unstaged step swaps on them. */
std::vector<Swap> swaps;
if (!r.stager.staged() && r.heat.step(&swaps) < 0) return;
/* What the turnover slots follow (MoverConfig::turnover_adaptive). A staged step proposes
* nothing and holds the turnover filled anyway (below), so it is not a quiet step. */
if (!r.stager.staged()) r.mover.swap_demand((int64_t)swaps.size());
for (const Swap& s : swaps) {
/* Contract: every proposed unit is busy until `issue` takes it or `abandon` returns it;
* a dropped proposal stays busy forever. */
+3
View File
@@ -3737,6 +3737,9 @@ int Engine::load_weights() {
* aligned (rad_format.h), DirectFile's alignment, so stages take the no-bounce path. */
MoverConfig mc{};
mc.container_path = file_ ? cfg_.model : std::string();
/* The lent slots kept free for swaps follow the swaps asked for (mover.h): a rank that
* holds nearly all its experts gets the idle ones back as residents. */
mc.turnover_adaptive = true;
RAD_TRY(r->mover.init(r->program, r->plan, mc, &r->pools));
/* What the mover took, before the first copy. Its slabs are allocated in init, so the pool
* is as full as it will get; a load stopping with zero free is a placement failure, not
+37 -5
View File
@@ -8,6 +8,7 @@
#include "../device/device.h"
#include <algorithm>
#include <cmath>
#include <chrono>
#include <cstring>
#include <map>
@@ -174,6 +175,12 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
cp.n_work = shadow + sc.n_stage;
cp.n_turn = std::min<int64_t>(std::max(cfg.turnover_slots, 0),
shadow * RAD_PLACE_TURNOVER_SLOTS / RAD_PLACE_SHADOW_SLOTS);
/* Under MoverConfig::turnover_adaptive the kept-free count starts at its floor: a fresh
* placement fills what it can at once, and the first burst of swaps lands in the shadow
* slots and these while balance() frees the rest. */
cp.turn_now = cfg.turnover_adaptive
? std::min<int64_t>(cp.n_turn, std::max(cfg.turnover_floor, 0))
: cp.n_turn;
total_turn += cp.n_turn;
cp.slab.init(slab_slots, sc.stride);
total_slab += slab_slots;
@@ -379,9 +386,10 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
republish(u);
}
RAD_INFO("mover: %lld slab slots (%lld shadow, %lld more kept free out of a loan), %lld pinned "
"pool slots, %s static vram%s",
(long long)total_slab, (long long)total_shadow, (long long)total_turn,
RAD_INFO("mover: %lld slab slots (%lld shadow, %s%lld more kept free out of a loan%s), %lld "
"pinned pool slots, %s static vram%s",
(long long)total_slab, (long long)total_shadow, cfg.turnover_adaptive ? "up to " : "",
(long long)total_turn, cfg.turnover_adaptive ? " as swaps ask for them" : "",
(long long)total_pool,
humanb(static_bytes_).c_str(), file_.ok() ? ", file tier open" : "");
/* The pageable region is charged to no budget, so this is the only place it is reported. */
@@ -1126,7 +1134,13 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
if (promote) {
const int64_t slot = cp.slab.take();
if (slot < 0) { ++stats_.starved_slab; return false; }
if (slot < 0) {
++stats_.starved_slab;
/* The slots kept free were too few for this step's swaps: all of them, for a
* while (balance). */
if (cfg_.turnover_adaptive) turn_boost_ = kTurnBoost;
return false;
}
if (promote_to(unit, slot) < 0) { cp.slab.add_free(slot); return false; }
return true;
}
@@ -1625,7 +1639,19 @@ int Mover::balance(HeatEngine* heat, bool turnover) {
if (unit_[(size_t)m.unit].klass != (int32_t)c || !cp.slab.covered(m.slab_slot)) continue;
if (m.frees_slab()) ++pending;
}
const int64_t turn = turnover ? cp.n_turn : 0;
if (cfg_.turnover_adaptive) {
/* Three steps of the mean swaps a step (a swap holds its slot about three steps,
* RAD_PLACE_TURNOVER_SLOTS), between the floor and the configured count; all of
* them while a starved promotion is recent. The mean is over every class, so a
* class keeps a little more than its own share asks for. */
const int64_t floor_ = std::min<int64_t>(cp.n_turn, std::max(cfg_.turnover_floor, 0));
const int64_t want = turn_boost_ > 0 ? cp.n_turn : std::min<int64_t>(
cp.n_turn, std::max<int64_t>(floor_, (int64_t)std::lround(3.0f * demand_mean_)));
cp.turn_now = want >= cp.turn_now ? want : std::max(want, cp.turn_now - kTurnShrink);
} else {
cp.turn_now = cp.n_turn;
}
const int64_t turn = turnover ? cp.turn_now : 0;
int64_t short_by = cp.n_work + turn - (cp.slab.n_free() + pending);
if (short_by > 0) {
drop_cand_.clear();
@@ -1683,6 +1709,12 @@ int Mover::balance(HeatEngine* heat, bool turnover) {
return flush_moves();
}
void Mover::swap_demand(int64_t proposed) {
if (!cfg_.turnover_adaptive) return;
demand_mean_ += ((float)std::max<int64_t>(proposed, 0) - demand_mean_) / kTurnMean;
if (turn_boost_ > 0) --turn_boost_;
}
int Mover::idle_tick(HeatEngine* heat) {
if (!plan_ || !plan_->dynamic) return RAD_OK;
RAD_TRY(retire(heat));
+40
View File
@@ -307,6 +307,23 @@ struct MoverConfig {
* gets proportionally fewer, so a small loan is not left emptier than it is filled. */
int turnover_slots = RAD_PLACE_TURNOVER_SLOTS;
/* Whether the turnover slots a class keeps free follow the swaps the engine lately asked for
* (Mover::swap_demand) instead of always being all of them, and the fewest it keeps then.
*
* The count above is three steps of the full move budget, what a placement that changes
* every step needs (the planner.h figures are for a rank with 40% of its experts on the
* card). A rank that holds nearly all its experts swaps a few units a step once it has
* warmed up, and the 160 free slots a class are then experts left in the pool for nothing:
* Qwen3.8-Flash-Next at tp 2 keeps 640 slots a rank free (0.8 GiB) beside ~1000 units read
* over the link. Following demand, a class keeps three steps of the swaps a step the engine
* has lately proposed (a running mean, so one step's burst lands in the slots already free
* and moves nothing), never fewer than `turnover_floor`; the rest is filled like any other
* lent slot. A promotion that finds no free slot takes all of them back for a while, by
* dropping the coldest lent units, an address change (balance). Off by default, so a caller
* that sizes the turnover itself gets what it set. */
bool turnover_adaptive = false;
int turnover_floor = RAD_PLACE_SHADOW_SLOTS;
/* The container, for the file tier. Empty means no file tier; a unit planned there is then
* an error. */
std::string container_path;
@@ -577,6 +594,17 @@ public:
/* Whether idle ticks keep the turnover slots filled; the engine holds them through a prompt
* and the few steps after it (Engine::tiering_dispatch). */
void hold_turnover(bool held) { hold_turnover_ = held; }
/* The swaps the heat engine proposed this step (all classes), once a step before they are
* issued: what the kept-free turnover follows under MoverConfig::turnover_adaptive, as a
* running mean over about kTurnMean steps. */
void swap_demand(int64_t proposed);
/* The turnover slots kept free now, summed over the slab classes: turnover_slots(), or under
* MoverConfig::turnover_adaptive what the demand asks for. */
int64_t turnover_now() const {
int64_t n = 0;
for (const ClassPools& cp : pools_) n += cp.turn_now;
return n;
}
/* Each class's pinned pool as the card addresses it: [lo, hi) and the unit stride. At most `max`. */
int pool_ranges(uint64_t* lo, uint64_t* hi, uint64_t* stride, int max) const {
int n = 0;
@@ -746,6 +774,8 @@ private:
int64_t n_turn = 0; /* lent slots kept free past those: the fill stops short
* of them and balance() drops lent units to rebuild them
* (MoverConfig::turnover_slots) */
int64_t turn_now = 0; /* of n_turn, the slots kept free now: all of them, or
* what the recent swaps ask for (swap_demand) */
int64_t n_donated = 0; /* units in lent slots that gave their host copy away
* (Mover::donor_slot); at most n_turn of them */
std::vector<char*> flex_ptr;
@@ -803,6 +833,16 @@ private:
/* balance()'s drop candidates, (heat, unit), kept between calls so a step allocates nothing. */
std::vector<std::pair<float, int32_t>> drop_cand_;
bool hold_turnover_ = false;
/* The running mean of swaps proposed a step (swap_demand), and the steps left for which a
* promotion that found no free slab slot keeps every turnover slot free. */
float demand_mean_ = 0.0f;
int64_t turn_boost_ = 0;
static constexpr float kTurnMean = 64.0f;
static constexpr int64_t kTurnBoost = 512;
/* The most slots a class's kept-free count falls by in one balance(): each slot given up is
* a unit copied in over the link, and all of them at once would be hundreds of copies behind
* one step. Growing is immediate (drops cost nothing). */
static constexpr int64_t kTurnShrink = 8;
/* donor_slot()'s candidates per class, by layer, each layer sorted coldest first (hottest at
* the back). Ranked once per dispatch; `at` is that dispatch. */
struct DonorRank { int at = -1; std::vector<std::vector<std::pair<float, int32_t>>> by_layer; };
+19
View File
@@ -739,6 +739,25 @@ that equality. `docs/QSA.md` is the decomposition.
The vision tower is declared when the container carries one and `mm-max-patches` is not 0
(`arch/common/rad_block_vit.h`, `spec.md` §11).
**A decode step is its launches.** A verify pass at depth 3 is ~900 launches a rank in ~10 ms on two
R9700, against 4.1 GB of weights read a rank (6.4 ms at the cards' 640 GB/s): the connections' reads,
the delta net's update, the routers and the reductions are bound by their own chains of loads, not
by bytes, and every launch behind another costs the step ~1.6 us where it waits for it and ~0.5 us
where it does not (measured by adding launches; `scripts/stampseq.py`). So where a recorded pass
lets a launch start beside the last ordered one (`Ctx::haz_mark`), the plugin issues the small
launches of a decode step where they ride, the same kernels on the same operands in another order
(`qwen4exp_fp8.cpp`, `kVerifyRows`): k and v in front of the q|gate projection; the indexer's
keys behind the attention's own launches where nothing of the layer reads them (within the
exactness bound); the router's weight read beside the mixer's reduction; and from two rows the
shared expert's down projection in front of the routed one and the weight reads at 32 workgroups
instead of 64. Chain 3 with coupling, one server, interleaved rounds: 12.11 -> 11.82 ms a step
(-2.5%) with the chained kernels' wait polling by grid size (`libr4d/r4d_chain.h`); a plain decode
step takes the order that helps at one row (router read, k and v, the indexer's keys). What did not
help is in the comments beside each: a read of the mixer's first projection or of the connections'
matrices in front of their reads, the shared arm beside the router, more workgroups for the reads
(128: +2.0%, 256: +7.4%), and a connection read that asks for its own matrices before its wait
(+2.3%).
---
# `glm5next`: GLM-5.3-Flash
+5 -2
View File
@@ -945,10 +945,13 @@ the count from `tail`, as a GEMM takes its M from its operands.
| op | params | operands |
|---|---|---|
| `prefetch` | `bytes` | `w`w |
| `prefetch` | `bytes` `blocks`/opt | `w`w |
Reads the first `bytes` of a weight's stored form and writes nothing, so a kernel that streams the
weight next finds those bytes in the on-die cache (64 MB on gfx1201). It is issued beside a
weight next finds those bytes in the on-die cache (64 MB on gfx1201). `blocks` is the number of
workgroups reading where the architecture measured its own (the read holds wave slots and queues
its loads in front of the kernels it runs beside, so the best count depends on them); absent or 0
it is the kernel's `nb` axis. It is issued beside a
collective that leaves the card's memory idle: on the second lane (`rad_lane`), or, where launches
chain (`rad_chain_on`), as its chained form on the same lane right behind the GEMM before the
collective, which waits for that GEMM only and does not hold the collective. A plain read on the
+5
View File
@@ -75,6 +75,11 @@ extern "C" int halo_rad_prefetch(const RadArgs* a, RadStream stream) {
if ((uintptr_t)w->data % 16) return HALO_NO(RAD_E_ALIGN);
int nb = halo_cfg_prefetch_nb(a);
if (nb < 1) nb = 64;
/* The architecture's own count (`blocks`), as libr4d's prefetch takes it. */
{
const long long blocks = halo_geti_or(a, "blocks", 0);
if (blocks > 0 && blocks <= 1024) nb = (int)blocks;
}
const bool ch = halo_geti_or(a, "chain", 0) != 0;
return HALO_EMIT(stream, (ch ? halo_r4dchain_prefetch : prefetch_kernel), dim3((unsigned)nb), dim3(256), 0,
(const int4*)w->data, (size_t)(bytes / 16));
+3
View File
@@ -804,6 +804,9 @@ static const RadOperandSpec oKvLenTrim[] = {
/* `prefetch` reads a weight's leading `bytes` into the cache and writes nothing (docs/OPS.md). */
static const RadParamSpec pPrefetch[] = {
{ "bytes", RAD_P_INT, RAD_REQUIRED },
/* The workgroups reading, where the architecture measured its own count; absent or 0, the
* kernel's (its `nb` axis). */
{ "blocks", RAD_P_INT, RAD_OPTIONAL },
};
static const RadOperandSpec oPrefetch[] = {
{ "w", RAD_OPD_WEIGHT, 0 },
+22
View File
@@ -63,6 +63,14 @@ __device__ __forceinline__ const R4dChainRec* r4d_chain_rec() {
// clocks for as long as the wait lasts, slowing whatever else that channel serves. The first
// R4D_CHAIN_FAST polls are ~64 clocks apart, the rest R4D_CHAIN_SLOW x 64: a long wait ends at most
// that much late and puts 1/R4D_CHAIN_SLOW of the load on the channel.
//
// A grid of a few blocks puts little on the channel however often it polls, and a decode step is
// mostly such grids behind one another (a reduction's four blocks, a quantiser's, a router's
// seventeen), each ending its wait up to a slow period late: so up to R4D_CHAIN_TINY blocks keep
// the fast period for the whole wait and up to R4D_CHAIN_SMALL poll every R4D_CHAIN_MID x 64 clocks,
// which is at most the load a 256-block grid puts there at the slow period. Qwen3.8-Flash-Next at
// tp 2, chain 3 with coupling, ~670 dependent launches a verify pass: -0.32% a step; every grid at
// 8 or 4 instead of 16 gave -0.16% and -0.25% for two and four times the polls of the wide ones.
#ifndef R4D_CHAIN_FAST
#define R4D_CHAIN_FAST 8
#endif
@@ -77,17 +85,31 @@ __device__ __forceinline__ void r4d_chain_acquire() {
asm volatile("s_dcache_inv" ::: "memory");
}
#ifndef R4D_CHAIN_TINY
#define R4D_CHAIN_TINY 16
#endif
#ifndef R4D_CHAIN_SMALL
#define R4D_CHAIN_SMALL 64
#endif
#ifndef R4D_CHAIN_MID
#define R4D_CHAIN_MID 4
#endif
__device__ __forceinline__ void r4d_chain_wait() {
const R4dChainRec* r = r4d_chain_rec();
if (!r) return;
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0) {
const unsigned long long target = r->target;
unsigned long long* ctr = r->ctr;
const unsigned nblk = gridDim.x * gridDim.y * gridDim.z;
int n = 0;
while (__hip_atomic_load(ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < target) {
if (n < R4D_CHAIN_FAST) {
__builtin_amdgcn_s_sleep(1);
++n;
} else if (nblk <= R4D_CHAIN_TINY) {
__builtin_amdgcn_s_sleep(1);
} else if (nblk <= R4D_CHAIN_SMALL) {
__builtin_amdgcn_s_sleep(R4D_CHAIN_MID);
} else {
__builtin_amdgcn_s_sleep(R4D_CHAIN_SLOW);
}
+10
View File
@@ -73,6 +73,16 @@ extern "C" int r4d_rad_prefetch(const RadArgs* a, RadStream stream) {
if ((uintptr_t)w->data % 16) return R4D_NO(RAD_E_ALIGN);
int nb = r4d_cfg_prefetch_nb(a);
if (nb < 1) nb = 64;
/* The architecture's own count (`blocks`): the read shares the card with the kernels it runs
* beside, whose loads queue behind its own and whose launches wait for the wave slots it
* holds, so the best count follows what those kernels are. Qwen3.8-Flash-Next's delta-net
* update, a latency-bound kernel of a few loads a block, loses more to 64 blocks of reads in
* flight than the projection behind it gains (ms a step at 16 / 24 / 32 / 48 / 64 / 128 / 256
* blocks, against 64: +0.77% / +0.14% / -0.31% / -0.24% / 0 / +2.0% / +7.4%). */
{
const long long blocks = r4d_geti_or(a, "blocks", 0);
if (blocks > 0 && blocks <= 1024) nb = (int)blocks;
}
const bool ch = r4d_geti_or(a, "chain", 0) != 0;
return R4D_EMIT(stream, (ch ? r4dchain_prefetch : prefetch_kernel), dim3((unsigned)nb), dim3(256), 0,
(const int4*)w->data, (size_t)(bytes / 16));
+3
View File
@@ -908,6 +908,9 @@ static const RadOperandSpec oKvLenTrim[] = {
/* `prefetch` reads a weight's leading `bytes` into the cache and writes nothing (docs/OPS.md). */
static const RadParamSpec pPrefetch[] = {
{ "bytes", RAD_P_INT, RAD_REQUIRED },
/* The workgroups reading, where the architecture measured its own count; absent or 0, the
* kernel's (its `nb` axis). */
{ "blocks", RAD_P_INT, RAD_OPTIONAL },
};
static const RadOperandSpec oPrefetch[] = {
{ "w", RAD_OPD_WEIGHT, 0 },
+14
View File
@@ -30766,6 +30766,20 @@ static void device_phase(const Plugin& pl) {
std::vector<RadTensor> ts = { T(d, RAD_U8, { (int64_t)1 << 20 }) };
std::vector<RadParam> ps = { PI("bytes", (int64_t)1 << 20) };
run_case(r, ts, ps);
/* With the architecture's own workgroup count (`blocks`): one block, the count
* Qwen3.8-Flash-Next asks for at a verify, the most the row takes, and absent, 0 and
* one past the most (the kernel's own count each) all launch, and the weight they read
* is the weight afterwards: the row writes nothing at any count. */
std::vector<uint8_t> h((size_t)1 << 20), back((size_t)1 << 20);
for (size_t i = 0; i < h.size(); ++i) h[i] = (uint8_t)(i * 131u + (i >> 9));
st_memcpy(d, h.data(), h.size(), hipMemcpyHostToDevice);
for (const long long nb : { 0ll, 1ll, 32ll, 1024ll, 1025ll }) {
std::vector<RadParam> pb = { PI("bytes", (int64_t)1 << 20), PI("blocks", nb) };
run_case(r, ts, pb);
}
st_memcpy(back.data(), d, back.size(), hipMemcpyDeviceToHost);
ok("prefetch at its caller's workgroup count leaves the weight as it was", back == h,
"the weight's bytes changed");
RadLayout L{};
const int st = r->layout ? r->layout(nullptr, 0, 0, nullptr, nullptr, nullptr, 0, &L) : 0;
ok("prefetch's layout hook takes any stored form (RAD_LAYOUT_ANY)", st == RAD_LAYOUT_ANY,
+134 -9
View File
@@ -2680,6 +2680,123 @@ TEST(qsa_below_the_exact_bound_the_indexer_issues_no_query_score_or_select) {
}
}
/* At decode heights the plugin issues a layer's small launches where a recorded pass lets them
* ride (qwen4exp_fp8.cpp: kVerifyRows, QsaSide): the k and v projections in front of the q|gate
* projection; the indexer's keys behind the attention's own launches where nothing of the layer
* reads them; the router's weight read beside the mixer's write; and from kVerifyRows rows the
* shared down projection in front of the routed one and the reads at the verify step's workgroup
* count. A prompt step keeps the declared order. */
TEST(a_flash_next_decode_step_orders_its_small_launches) {
RadModelMeta meta = qwen4exp_meta();
RadBuildCtx c = build_ctx(0, 2);
c.max_tok = 64; c.max_seqs = 4; c.max_spec = 3; c.max_ctx = 200000;
RadBuilder b;
REQUIRE_EQ(qwen4exp_fp8::declare(&b, &meta, &c), RAD_OK);
const qwen4exp_fp8::Model& m = qwen4exp_fp8::g_model[0];
REQUIRE(m.qsa_defer);
auto run = [&](const Kit& k) {
RadCtx ctx;
ctx.b = &b;
ctx.batch = &k.b;
qwen4exp_fp8::step(&ctx, &k.b);
return ctx.issues;
};
/* Where an op was issued, when it was issued exactly once; -1 never, -2 more than once. */
auto pos = [](const std::vector<RecIssue>& is, rad_op op) {
int64_t at = -1;
for (size_t i = 0; i < is.size(); ++i)
if (is[i].op == op) at = at == -1 ? (int64_t)i : -2;
return at;
};
const auto ver = kit(b, { 4 }, {}); /* a chain-3 verify */
const auto two = kit(b, { 2 }, {}); /* a chain-1 verify, the fewest rows of one */
const auto one = kit(b, { 1 }, {}); /* a plain decode step */
const auto pre = kit(b, {}, { 32 }); /* a prompt chunk */
const auto iv = run(*ver), i2 = run(*two), i1 = run(*one), ip = run(*pre);
size_t full = 0;
for (const auto& l : m.layers) {
const rad_op wr = l.hc_mix.op_ar_write ? l.hc_mix.op_ar_write : l.hc_mix.op_write;
const rad_op out = l.full ? l.attn.o.op : l.gdn.out.op;
/* The router's read: behind the mixer's out projection and in front of its write, at the
* step's workgroup count; a prompt step reads nothing ahead. */
REQUIRE(l.op_pf_router != 0);
REQUIRE(l.op_pf_router_v != 0);
for (const auto* is : { &iv, &i2 }) {
CHECK(pos(*is, l.op_pf_router_v) > pos(*is, out));
CHECK(pos(*is, l.op_pf_router_v) < pos(*is, wr));
CHECK_EQ(pos(*is, l.op_pf_router), (int64_t)-1);
}
CHECK(pos(i1, l.op_pf_router) > pos(i1, out));
CHECK(pos(i1, l.op_pf_router) < pos(i1, wr));
CHECK_EQ(pos(i1, l.op_pf_router_v), (int64_t)-1);
CHECK_EQ(pos(ip, l.op_pf_router), (int64_t)-1);
CHECK_EQ(pos(ip, l.op_pf_router_v), (int64_t)-1);
/* The shared down projection: in front of the routed down GEMM from kVerifyRows rows,
* behind it at one row and on a prompt step. */
REQUIRE(pos(iv, l.mlp.op_dn) >= 0);
REQUIRE(pos(iv, l.mlp.sh_down.op) >= 0);
CHECK(pos(iv, l.mlp.sh_down.op) < pos(iv, l.mlp.op_dn));
CHECK(pos(i2, l.mlp.sh_down.op) < pos(i2, l.mlp.op_dn));
CHECK(pos(i1, l.mlp.sh_down.op) > pos(i1, l.mlp.op_dn));
CHECK(pos(ip, l.mlp.sh_down.op) > pos(ip, l.mlp.op_dn));
if (!l.full) {
/* The out projection's read at the step's workgroup count. */
REQUIRE(l.gdn.op_pf_out != 0);
REQUIRE(l.gdn.op_pf_out_v != 0);
for (const auto* is : { &iv, &i2 }) {
CHECK(pos(*is, l.gdn.op_pf_out_v) >= 0);
CHECK_EQ(pos(*is, l.gdn.op_pf_out), (int64_t)-1);
}
CHECK(pos(i1, l.gdn.op_pf_out) >= 0);
CHECK_EQ(pos(i1, l.gdn.op_pf_out_v), (int64_t)-1);
continue;
}
++full;
REQUIRE(l.attn.op_pf_o != 0);
REQUIRE(l.attn.op_pf_o_v != 0);
for (const auto* is : { &iv, &i2 }) {
CHECK(pos(*is, l.attn.op_pf_o_v) >= 0);
CHECK_EQ(pos(*is, l.attn.op_pf_o), (int64_t)-1);
}
CHECK(pos(i1, l.attn.op_pf_o) >= 0);
CHECK_EQ(pos(i1, l.attn.op_pf_o_v), (int64_t)-1);
for (const auto* is : { &iv, &i2, &i1 }) {
/* k and v in front of q|gate, the indexer's projection in front of all three. */
REQUIRE(pos(*is, l.attn.qg.op) >= 0);
CHECK(pos(*is, l.qsa.proj.op) >= 0);
CHECK(pos(*is, l.qsa.proj.op) < pos(*is, l.attn.kp.op));
CHECK(pos(*is, l.attn.kp.op) < pos(*is, l.attn.vp.op));
CHECK(pos(*is, l.attn.vp.op) < pos(*is, l.attn.qg.op));
/* The keys behind the attention's projections, in their own order, and all of them
* in front of the write that ends the block. */
CHECK(pos(*is, l.qsa.op_work) > pos(*is, l.attn.qg.op));
CHECK(pos(*is, l.qsa.op_bkey) > pos(*is, l.qsa.op_work));
CHECK(pos(*is, l.qsa.op_tail) > pos(*is, l.qsa.op_bkey));
CHECK(pos(*is, l.qsa.op_tail) < pos(*is, wr));
}
/* A prompt step: the indexer in front of the attention, q|gate in front of k and v. */
CHECK(pos(ip, l.qsa.op_tail) > pos(ip, l.qsa.op_work));
CHECK(pos(ip, l.qsa.op_tail) < pos(ip, l.attn.qg.op));
CHECK(pos(ip, l.attn.qg.op) < pos(ip, l.attn.kp.op));
CHECK(pos(ip, l.attn.kp.op) < pos(ip, l.attn.vp.op));
}
REQUIRE(full > 0);
/* Past the exactness bound the attention reads this layer's selection, so the indexer stays
* in front of it at every height. */
{
const auto k = kit(b, { 4 }, {});
k->b.max_ctx_len = 3072;
const auto is = run(*k);
for (const auto& l : m.layers) {
if (!l.full) continue;
CHECK(pos(is, l.qsa.op_work) >= 0);
CHECK(pos(is, l.qsa.op_tail) < pos(is, l.attn.kp.op));
}
}
}
/* Whether a step is within the indexer's budget is read from the attention group's exact host
* ceiling where the batch carries it (RadBatch::kv_used_max_h), not from the context bound rounded
* up to 1024 tokens: a 4-row verify at 1500 tokens of context is within it though
@@ -12365,10 +12482,10 @@ struct ArchCases {
qwen35moe_fp8::step, 3, {}, 0x325d0299495a0dd8ull);
add("qwen4exp_fp8", [this](RadBuilder* b) {
auto c = q4_ctx(0, 1); return qwen4exp_fp8::declare(b, &q4, &c); },
qwen4exp_fp8::step, 3, {}, 0x9c8d2b5a6052248aull);
qwen4exp_fp8::step, 3, {}, 0x0f402d93ca192adbull);
add("qwen4exp_fp8, two ranks", [this](RadBuilder* b) {
auto c = q4_ctx(0, 2); return qwen4exp_fp8::declare(b, &q4, &c); },
nullptr, 3, { "ar_hc_write" }, 0x0a1227593eb26a3full);
nullptr, 3, { "ar_hc_write" }, 0x81339abe032a433bull);
/* The cache dtype stated rather than left to the plugin's default. The streamed store and
* the prologue that folds it are declared only where the vocabulary has them, and both are
* written at the KV group's dtype -- bf16 being the copy-only one, and it is what
@@ -12380,7 +12497,7 @@ struct ArchCases {
auto c = q4_ctx(0, 1);
c.kv_dtype = RAD_BF16;
return qwen4exp_fp8::declare(b, &q4, &c); },
qwen4exp_fp8::step, 3, {}, 0x9c8d2b5a6052248aull);
qwen4exp_fp8::step, 3, {}, 0x0f402d93ca192adbull);
add("lfm2_bf16", [this, sc](RadBuilder* b) {
auto c = sc(1, 0); return lfm2_bf16::declare(b, &lfm, &c); },
lfm2_bf16::step, 0, {}, 0x5bce917918dbd478ull);
@@ -13320,12 +13437,20 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) {
* decode step, verify, history pass and round are below the indexer's exactness bound,
* where the indexer now issues no query, score or select and a one-row sequence attends
* over its block table (docs/QSA.md, "Below the bound"). Its prefill and mixed steps,
* past the bound, are issued as before. */
{ "qwen4exp_fp8", 1, 0, 0x64fffe1f970fe9a3ull, 0x65d43fc170c2c598ull },
{ "qwen4exp_fp8", 2, 0, 0xe616c803347c8d63ull, 0x521774d19f34781full },
{ "qwen4exp_fp8", 2, 1, 0x5551ab9dbf8f611cull, 0x3afe8bf2df1eaa7bull },
{ "qwen4exp_fp8", 4, 0, 0x015eb0ed4d0951a1ull, 0xe78350c7803a9437ull },
{ "qwen4exp_fp8", 4, 3, 0x0e4fc56b33d75da3ull, 0xdb6d50824b015389ull },
* past the bound, are issued as before.
*
* Both moved again with the decode step's issue order (qwen4exp_fp8.cpp, kVerifyRows;
* a_flash_next_decode_step_orders_its_small_launches pins what moved): the graphs by the
* indexer's within-step buffers leaving the planner's sharing and, past one rank, by the
* router's weight read and each read's verify-height twin; the steps by k and v in front
* of q|gate, the indexer's keys behind the attention's launches and, at the verify, the
* shared down projection in front of the routed one. Prefill and mixed steps are issued
* as before. */
{ "qwen4exp_fp8", 1, 0, 0xe733184739f30fd2ull, 0x816cd78a65a92598ull },
{ "qwen4exp_fp8", 2, 0, 0x92921730d6df8e8full, 0x3b5931abdde2195dull },
{ "qwen4exp_fp8", 2, 1, 0x9c9352c2e075cb44ull, 0x7cb5889253d852cdull },
{ "qwen4exp_fp8", 4, 0, 0x74b4bf4e70c955e5ull, 0x4292bbe719b32ed1ull },
{ "qwen4exp_fp8", 4, 3, 0xc36df9e24f272283ull, 0x9c08be223ae002dbull },
{ "qwen35_fp8", 1, 0, 0x0f08ba5027cba71aull, 0xa7ec3cf6252cd441ull },
{ "qwen35_fp8", 2, 1, 0xe7780f241685a18bull, 0xdd5d65ef158c4136ull },
{ "qwen35moe_fp8", 1, 0, 0xb1e6173bd121dc2aull, 0x2b5989b2a6dbc7dfull },
+68
View File
@@ -2108,6 +2108,9 @@ struct LoanRig {
/* None by default: on a slab this small the production count would leave most of the loan
* empty. Tests of turnover set their own. */
int turnover = 0;
/* MoverConfig::turnover_adaptive and its floor, for the test of it. */
bool adaptive = false;
int floor = 0;
explicit LoanRig(int n_expert = 8) : hf(n_expert) {}
@@ -2116,6 +2119,8 @@ struct LoanRig {
RAD_TRY(h.init(hf.plan, hp));
MoverConfig mc;
mc.turnover_slots = turnover;
mc.turnover_adaptive = adaptive;
if (adaptive) mc.turnover_floor = floor;
RAD_TRY(m.init(hf.f.prog, hf.plan, mc));
RAD_TRY(rad_stream_create(&compute, 0));
RAD_TRY(m.bind_compute_stream(compute));
@@ -2212,6 +2217,69 @@ TEST(every_lent_slot_is_filled_in_one_dispatch) {
CHECK(at[k] - at[k - 1] >= r.hf.plan.classes[0].stride);
}
/* MoverConfig::turnover_adaptive: the slots kept free follow the swaps asked for. A quiet run keeps
* only the floor free and fills the rest; steps that propose swaps get three steps' worth of
* their mean back, up to the configured count, by drops (nothing crosses the link for them); and
* a quiet run gives them up again, each a copy in. */
TEST(an_adaptive_turnover_follows_the_swaps_asked_for) {
LoanRig r(24);
r.turnover = 4;
r.adaptive = true;
r.floor = 1;
CHECK_OK(r.build());
CHECK_EQ(r.m.turnover_slots(), (int64_t)4); /* the most it keeps */
CHECK_EQ(r.m.turnover_now(), (int64_t)1); /* and what it starts from */
const int64_t stride = r.hf.plan.classes[0].stride;
const int64_t slots = r.m.flex_capacity() / stride;
CHECK(r.pooled() > slots);
REQUIRE(slots > 4);
auto settle = [&](int64_t proposed, int steps) {
for (int k = 0; k < steps; ++k) {
r.m.swap_demand(proposed);
CHECK_OK(r.dispatch());
}
for (Deadline dl; any_busy(r.h, r.hf.plan) && !dl.passed();) CHECK_OK(r.dispatch());
for (int k = 0; k < 4; ++k) CHECK_OK(r.dispatch());
};
CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll));
for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();) {
r.m.swap_demand(0);
CHECK_OK(r.dispatch());
}
CHECK_EQ(r.m.turnover_now(), (int64_t)1);
CHECK_EQ(r.m.flex_used_bytes(), (slots - 1) * stride);
/* One swap a step, step after step: the mean reaches one, and three steps of it are three. */
const uint64_t d2h = r.m.stats().d2h_bytes, h2d = r.m.stats().h2d_bytes;
settle(1, 600);
CHECK_EQ(r.m.turnover_now(), (int64_t)3);
CHECK_EQ(r.m.flex_used_bytes(), (slots - 3) * stride);
CHECK_EQ(r.m.stats().dropped, (uint64_t)2);
/* Two a step would ask for six: the configured count bounds it. */
settle(2, 600);
CHECK_EQ(r.m.turnover_now(), (int64_t)4);
CHECK_EQ(r.m.flex_used_bytes(), (slots - 4) * stride);
CHECK_EQ(r.m.stats().dropped, (uint64_t)3);
CHECK_EQ(r.m.stats().d2h_bytes, d2h); /* the drops crossed no link */
CHECK_EQ(r.m.stats().h2d_bytes, h2d);
/* Quiet again: back to the floor, and the three slots are filled again. */
settle(0, 800);
CHECK_EQ(r.m.turnover_now(), (int64_t)1);
CHECK_EQ(r.m.flex_used_bytes(), (slots - 1) * stride);
CHECK(r.m.stats().h2d_bytes > h2d);
/* Off, the count is the configured one whatever is asked for. */
LoanRig s(24);
s.turnover = 4;
CHECK_OK(s.build());
s.m.swap_demand(0);
CHECK_OK(s.dispatch());
CHECK_EQ(s.m.turnover_now(), (int64_t)4);
}
/* The turnover slots stay free, and a shrinking loan does not take them for good. The fill stops
* that many slots short so the engine's swaps have somewhere to land. Free slots are at the loan's
* top, which a reclaiming cache takes first; the mover then rebuilds them by dropping the coldest