Archived
core, libr4d, arch: chained launches with block drafters, more prefill overlap, weight reads beside the all-reduces
Chained launches on the AQL backend (a dependent kernel waits on a queue counter in its own prologue), on by default where the model's plugin measured a gain with its block drafter (the Gemma 4 31B and 26B); the prefill overlap runs attention per slice with narrower lane-1 reductions; the next GEMM's weight is read into the on-die cache beside each all-reduce at decode heights. Squashed from: - core, libr4d: chained launches -- dependent kernels wait in their prologue, not behind the barrier bit - core, libr4d: chain a kernel by its name, not by the row that launched it - libr4d, core: chained forms hold nothing across their body - libr4d: a chained kernel's prologue polls its counter less often after the first few tries - core/sched: the advance kernel's chained form - docs: GUIDE lists RADIANCE_CHAIN; chained launches stay opt-in - core/device: a chained packet behind a chained one keeps its barrier bit while a plain one may run - libr4d: qkv_norm_rope and its kv_store fold as chained forms - libr4d: the split-KV decode attention and its merge as chained forms - libr4d: the four-rank fused junction's tail form as a chained form - libr4d: the attention, prologue and junction chained forms hold nothing across their body - libr4d: the 31B's windowed attention and quant_act_i8 as chained forms; r4d_chain.h stubs for the host emulator - libr4d: DFlash2's kernels as chained forms - libr4d: chained forms for the decode tail - abi, core, arch: chained launches on by default where the plugin measured a gain with its drafter - arch/gemma4_bf16: the prefill overlap's lane-1 all-reduces take the narrow launch (`overlap` 1) - arch/gemma4_bf16, libr4d: the prefill overlap runs attention per slice; kv_len_trim - abi, core, libr4d: RAD_LAYOUT_ANY, and a device-only weight read (prefetch) - arch: read the next GEMM's weight into the cache beside each collective at decode heights Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1bb7ad3ef9
commit
ab2b3be6c0
53 files changed
+2239
-220
No files matched your search
+25
-1
@@ -135,7 +135,13 @@ typedef struct RadLayout {
|
||||
* RAD_E_DTYPE the kernel does not read this encoding (an fp8 GEMM handed int4, a rotated
|
||||
* weight to a kernel that does not rotate its activation). A declare-time
|
||||
* error naming the weight, the encoding and the kernel.
|
||||
* RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads. */
|
||||
* RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads.
|
||||
* RAD_LAYOUT_ANY the kernel reads the stored bytes without interpreting them (a prefetch
|
||||
* into the cache), so it takes whatever form another reader chose and claims
|
||||
* none: the builder does not count it when settling the stored form, and the
|
||||
* runtime's layout check accepts it. A weight only such kernels read is
|
||||
* stored as it is. */
|
||||
#define RAD_LAYOUT_ANY 1
|
||||
typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n_planes,
|
||||
RadLayout* out);
|
||||
@@ -498,6 +504,24 @@ typedef void (*RadPluginCloseFn)(void);
|
||||
* it, which is always correct. Symbol name: `rad_kernel_concurrent`. */
|
||||
typedef int (*RadKernelConcurrentFn)(int i);
|
||||
|
||||
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it can chain. Chaining replaces
|
||||
* the packet processor's ordering between dependent launches (the AQL barrier bit) with a wait in
|
||||
* the kernel. Where chaining is on the engine resolves the row with the parameter `chain` = 1, and
|
||||
* the launch may then emit chained forms of its kernels, recognised by "r4dchain" in the kernel's
|
||||
* name; only those get a record and lose the bit. A chained form, before its first read of an
|
||||
* operand, one lane a block waits until the 64-bit word at the record's `ctr` reaches `target`,
|
||||
* then the block barriers and acquires at agent scope; after its last write the block releases at
|
||||
* agent scope, barriers, and one lane adds 1 to `ctr`. Every block, including one with nothing to
|
||||
* do, adds exactly once. The record is RAD_CHAIN_REC_BYTES at byte RAD_CHAIN_KARG_OFF of the
|
||||
* kernel's argument segment: { magic, target, ctr, check }, with check = magic ^ target ^ ctr ^
|
||||
* RAD_CHAIN_CHECK. A record whose magic or check does not match means: run without waiting and do
|
||||
* not add. Without the symbol, or with 0, the engine never asks. Symbol name: `rad_kernel_chain`. */
|
||||
typedef int (*RadKernelChainFn)(int i);
|
||||
#define RAD_CHAIN_KARG_OFF 992
|
||||
#define RAD_CHAIN_REC_BYTES 32
|
||||
#define RAD_CHAIN_MAGIC 0x3130434e48434452ull /* "RDCHCN01" */
|
||||
#define RAD_CHAIN_CHECK 0x9e3779b97f4a7c15ull
|
||||
|
||||
/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it is a collective. Its
|
||||
* launches exchange data with the other ranks' cards, so the interconnect carries their bytes
|
||||
* while they run and the step waits on it. The engine keeps its own bulk traffic on those links
|
||||
|
||||
@@ -643,6 +643,15 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
|
||||
* checkpoint was trained with is the plugin's to know. */
|
||||
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
|
||||
|
||||
/* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on
|
||||
* the AQL backend only, which keeps a completion counter per queue -- by default where the model's
|
||||
* plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter
|
||||
* decodes speculatively, or as RADIANCE_CHAIN says. A plugin that places work by whether a kernel
|
||||
* waits in its prologue behind the one before it -- a weight read issued on lane 0 right after its
|
||||
* GEMM -- asks this instead of reading the environment, so it follows that decision. Additive
|
||||
* export; RAD_ABI_VERSION does not move. */
|
||||
int rad_chain_on(void);
|
||||
|
||||
/* ================================================================== the encoder */
|
||||
/* A media encoder the plugin runs on an encoder pass (RadBatch::enc). The core drives the pass and
|
||||
* reads its result, so the plugin declares it. A plugin that declares none serves text only, and
|
||||
@@ -1281,6 +1290,12 @@ typedef struct RadArchProbe {
|
||||
* libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at
|
||||
* startup with the plugin named. */
|
||||
int32_t kv_quant_ok;
|
||||
/* Nonzero when this plugin measured its speculative step faster with chained launches
|
||||
* (RadKernelChainFn: a dependent kernel waits in its own prologue rather than behind the
|
||||
* queue's barrier bit). With a drafter decoding speculatively on the AQL backend, the core
|
||||
* then takes them by default; RADIANCE_CHAIN overrides either way. Zero keeps them off: plain
|
||||
* decode measured slower chained, and a plugin that never measured them asks for nothing. */
|
||||
int32_t chain_pays;
|
||||
} RadArchProbe;
|
||||
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
|
||||
@@ -587,6 +587,53 @@ inline rad_op rw(RadBuilder* b, rad_op h,
|
||||
return h;
|
||||
}
|
||||
|
||||
/* ---- A weight read into the on-die cache beside a collective (libr4d `prefetch`, docs/OPS.md).
|
||||
* At decode heights a GEMM streams its weight once from memory, and a collective in front of it
|
||||
* leaves the card's memory idle for its round trip. prefetch_beside issues `op`, a `prefetch` of
|
||||
* the next GEMM's weight `w`, behind the GEMM before the collective, so the two do not share the
|
||||
* memory, and the next GEMM finds its leading bytes in the cache. Nothing it reads or writes is a
|
||||
* model value, so on the second lane it keeps that lane's rules with no buffer named
|
||||
* (core/runtime/ctx.h): it is no collective, keeps no counter and touches no arena byte.
|
||||
*
|
||||
* Only at decode and verify heights, up to kPrefetchRows rows: a DFlash2 verify's 8 a sequence, a
|
||||
* z-lab DFlash verify's 16, a plain decode's one. With the ceiling at 64, a prompt's prefill steps
|
||||
* (40 rows on the 31B's test prompt) took the reads too, and a freshly started 31B server's first
|
||||
* greedy reply then differed on 4 of 6 starts (4x R9700, the cards' memory scribbled before each
|
||||
* start); at 16, and with no reads at all, 0 of 6. Per-op output hashes later located that
|
||||
* divergence at the prefill all-reduce's first reuse of a double-buffered slot: a race in the
|
||||
* all-reduce, which its full fence on prefill-sized messages (libr4d) cures, not in anything the
|
||||
* reads touch. The reads stay off prompt steps all the same. */
|
||||
constexpr int64_t kPrefetchRows = 16;
|
||||
/* The read goes on lane 0 itself, right after the GEMM, where its chained form (libr4d
|
||||
* r4dchain_prefetch) waits for that GEMM and then reads beside the collective after it without
|
||||
* holding the collective: no join between the lanes, so no record on the GEMM and no barrier bit
|
||||
* on it, and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1. On
|
||||
* 4x R9700 (31B DFlash2, three rounds, every reply identical): code 385-386 tok/s against 363-365,
|
||||
* prose 284-286 against 269-270, decode after a 6.4k prompt 580-583 against 538-541. Only where
|
||||
* launches chain (rad_chain_on, the core's decision), since a plain launch would read in series
|
||||
* there; elsewhere the read goes on lane 1, behind a join from lane 0. */
|
||||
inline bool prefetch_lane0() { return rad_chain_on() != 0; }
|
||||
inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
if (!op || T > kPrefetchRows) return;
|
||||
if (prefetch_lane0()) {
|
||||
RAD_ISSUE(c, op, RAD_W(w));
|
||||
return;
|
||||
}
|
||||
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);
|
||||
}
|
||||
/* RADIANCE_PREFETCH=0 declares no reads at all (docs/GUIDE.md); read at declare. */
|
||||
inline bool prefetch_enabled() {
|
||||
const char* e = std::getenv("RADIANCE_PREFETCH");
|
||||
return !(e && !std::strcmp(e, "0"));
|
||||
}
|
||||
/* The `prefetch` of `w`'s first `bytes`, where a library serves it and the reads are on; 0
|
||||
* otherwise. */
|
||||
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
|
||||
if (!w || bytes <= 0 || !prefetch_enabled() || !rad_op_declared(b, "prefetch")) return 0;
|
||||
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
|
||||
}
|
||||
|
||||
/* ================================================================== geometry */
|
||||
/* Dimensions come from model metadata, so one plugin covers every size in a family. Sharded
|
||||
* dimensions are already divided by world_size: the plugin declares divided dimensions and emits
|
||||
|
||||
@@ -127,6 +127,9 @@ struct Dflash2 {
|
||||
/* The target's embedding scale, applied to the query block as the drafter was trained
|
||||
* (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */
|
||||
double escale = 1.0;
|
||||
/* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query
|
||||
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
|
||||
int64_t prefetch = 0;
|
||||
int64_t steps() const { return block - 1; }
|
||||
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
|
||||
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
|
||||
@@ -264,6 +267,13 @@ struct Dflash2 {
|
||||
* op_aan[i] after layer i-1's feed-forward (layer i's attention norm, i >= 1), op_afinal after
|
||||
* the last layer's (the final norm). All or none. */
|
||||
rad_op op_afn[MAX_LAYERS] = {}, op_aan[MAX_LAYERS] = {}, op_afinal = 0;
|
||||
/* The reads beside the query pass's all-reduces (cfg.prefetch), each the GEMMs that follow
|
||||
* in their order: beside the attention's, the feed-forward's coefficient projection, then
|
||||
* gate_up; beside the feed-forward's, the next layer's attention coefficient projection, then
|
||||
* its q -- after the last layer, the draft head; and o's beside the attention itself. 0 where
|
||||
* none is declared. */
|
||||
rad_op op_pfa[MAX_LAYERS][2] = {}, op_pff[MAX_LAYERS][2] = {}, op_pfo[MAX_LAYERS] = {};
|
||||
rad_weight pfa_w[MAX_LAYERS][2] = {}, pff_w[MAX_LAYERS][2] = {}, pfo_w[MAX_LAYERS] = {};
|
||||
|
||||
/* head and selector */
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
@@ -900,6 +910,22 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp}, {w.tokens});
|
||||
|
||||
/* The reads beside the all-reduces, after every weight they read is declared. */
|
||||
if (op_ar && cfg.prefetch > 0)
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
pfa_w[i][0] = w_fcp[i];
|
||||
pfa_w[i][1] = w_gu[i].w;
|
||||
pff_w[i][0] = l + 1 < g.n_layer ? w_acp[i + 1] : w_dh;
|
||||
pff_w[i][1] = l + 1 < g.n_layer ? w_q[i + 1].w : 0;
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
op_pfa[i][j] = decl_prefetch(b, pfa_w[i][j], cfg.prefetch);
|
||||
op_pff[i][j] = decl_prefetch(b, pff_w[i][j], cfg.prefetch);
|
||||
}
|
||||
pfo_w[i] = w_o[i].w;
|
||||
op_pfo[i] = decl_prefetch(b, pfo_w[i], cfg.prefetch);
|
||||
}
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -989,6 +1015,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
|
||||
prefetch_beside(c, op_pfo[i], pfo_w[i], T);
|
||||
if (op_qkr[i]) {
|
||||
RAD_ISSUE_N(c, op_qkr[i], T, brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
praw(batch->positions, RAD_I32, T), RAD_W(w_qn[i]), RAD_W(w_kn[i]),
|
||||
@@ -1012,6 +1039,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
|
||||
for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pfa[i][j], pfa_w[i][j], T);
|
||||
/* Reduce before the closing convolution. It is linear with coefficients from the
|
||||
* replicated norm, so either order gives the same result; reducing first keeps x's
|
||||
* update agreed across ranks. */
|
||||
@@ -1038,6 +1066,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
}
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
|
||||
for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pff[i][j], pff_w[i][j], T);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
|
||||
@@ -112,6 +112,23 @@ inline double embed_scale(int64_t hidden) {
|
||||
return rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)hidden)));
|
||||
}
|
||||
|
||||
/* prefetch where a library serves it: the 31B trunk reading the next GEMM's leading weight bytes
|
||||
* into the on-die cache beside the all-reduce in front of that GEMM, at decode heights (on lane 0
|
||||
* as a chained read, or on the second lane: rad_arch.h prefetch_lane0), and the DFlash2 drafter's
|
||||
* reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB. With
|
||||
* the reads on lane 0 (two rounds on 4x R9700): 20 MB 391 / 391 code tok/s, 289 / 288 prose;
|
||||
* 16 MB 386 / 384, 285 / 283; 24 MB 388 / 387; 12 MB 368 / 369. */
|
||||
constexpr int64_t kPrefetchBytes = (int64_t)20 << 20;
|
||||
|
||||
/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention. It
|
||||
* took the place of o_proj's read there: the 31B at tp 4 on 4x R9700, two rounds, every reply
|
||||
* identical, 380 / 281 / 203 tok/s against 367 / 271 / 196 with o_proj's 16 MB; 10, 11, 12, 14
|
||||
* and 20 MB of down_proj 379, 377, 373, 373 and 362; down_proj beside o_proj's read, or beside the
|
||||
* feed-forward reduction, slower than either alone. The reads beside a reduction are one queue,
|
||||
* and a longer one beside the attention pushes gate_up's read past the reduction it should hide
|
||||
* in. */
|
||||
constexpr int64_t kPrefetchDownBytes = (int64_t)9 << 20;
|
||||
|
||||
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
|
||||
* transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */
|
||||
inline bool block_fp8_128(const RadEncoding& e) {
|
||||
@@ -149,25 +166,30 @@ inline long long dflash_block(const RadModelMeta* meta) {
|
||||
|
||||
/* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less
|
||||
* the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). True when the
|
||||
* container carries one and `out` now names its depth. */
|
||||
* container carries one and `out` now names its depth. Chained launches measured a gain with it
|
||||
* (the 26B-A4B's speculative step, +1% on 4x R9700), so the probe asks for them
|
||||
* (RadArchProbe::chain_pays). */
|
||||
inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (dflash_kind(meta) != 1) return false;
|
||||
const long long bs = dflash_block(meta);
|
||||
if (bs <= 1) return false;
|
||||
out->draft_depth = (int)(bs - 1);
|
||||
out->draft_depth_fixed = 1;
|
||||
out->chain_pays = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The same for a DFlash2 drafter, for a plugin that serves rad_block_dflash2.h (the 31B's): its
|
||||
* anchor predicts nothing either, so the depth is the trained block less one, 7 for RedHatAI's
|
||||
* gemma-4-31B-it-speculator.dflash2 (block_size 8). */
|
||||
* gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches measured a gain with it (the
|
||||
* 31B's speculative step, +13% on 4x R9700), so the probe asks for them. */
|
||||
inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (dflash_kind(meta) != 2) return false;
|
||||
const long long bs = dflash_block(meta);
|
||||
if (bs <= 1) return false;
|
||||
out->draft_depth = (int)(bs - 1);
|
||||
out->draft_depth_fixed = 1;
|
||||
out->chain_pays = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -286,6 +286,13 @@ struct Gemma4Attn {
|
||||
* the copies of k and v too, ahead of the unfused prologue, which reads them dense. */
|
||||
rad_op op_attn_row = 0, op_attn_dec = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0;
|
||||
int64_t dec_hi = 0;
|
||||
/* the feed-forward's gate_up read into the cache beside this block's all-reduce, or 0 (see
|
||||
* "Prefetch beside the reductions") */
|
||||
rad_op op_pf = 0;
|
||||
rad_weight pf_w = 0;
|
||||
/* the feed-forward's down_proj read into the cache beside the attention itself, or 0 */
|
||||
rad_op op_pfd = 0;
|
||||
rad_weight pfd_w = 0;
|
||||
|
||||
/* The linear whose int8 pair a junction writes, and whether every projection reads it. */
|
||||
const G4Linear& ln_in() const { return fused ? ln_qkv : ln_q; }
|
||||
@@ -306,6 +313,13 @@ struct Gemma4Attn {
|
||||
void project(RadCtx* c, int64_t r0, int64_t n) const;
|
||||
void attend(RadCtx* c, const RadBatch* batch) const;
|
||||
void out_proj(RadCtx* c, int64_t r0, int64_t n) const;
|
||||
/* The prologue and the attention over rows [r0, r0 + n) of a one-sequence step alone (the
|
||||
* prefill overlap's slices), `used` the context the slice ends at (kv_len_trim for a slice
|
||||
* that ends before the step does). Only with the one-launch prologue and a prefill-height
|
||||
* attention that reads q dense or in the row (slicable). */
|
||||
bool slicable() const { return op_qnr_kv && (op_attn_row || op_attn); }
|
||||
void attend_rows(RadCtx* c, const RadBatch* batch, int64_t r0, int64_t n,
|
||||
RadOperand used) const;
|
||||
};
|
||||
|
||||
int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
@@ -575,6 +589,22 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- Prefetch beside the reductions (prefetch_beside, rad_arch.h). The all-reduce in front of
|
||||
* each GEMM leaves the card's memory idle for its round trip (~20 us at a DFlash2 verify's rows on
|
||||
* 4x R9700), so the trunk reads the next GEMM's leading bytes in that window -- gate_up's after
|
||||
* o_proj, the next layer's q|k|v after down_proj -- and the GEMM finds them in the 64 MB on-die
|
||||
* cache. The attention leaves it mostly idle too at a verify's few rows and a chat's context, so
|
||||
* down_proj's weight is read beside it, after q|k|v. On four cards (a microbenchmark of the
|
||||
* two-shot and a GEMM-like stream of a cold 29 MB weight) 16 MB read beside the reduction took a
|
||||
* layer from 84.0 us to 70.1; read on the same lane it gained nothing. */
|
||||
|
||||
/* The height prefetch_beside judges a trunk step by: its rows on a decode step (decode and verify
|
||||
* rows only), and none at all on one that carries a prompt's rows (rad_arch.h, kPrefetchRows): the
|
||||
* row ceiling keeps long prefills out, and this keeps out the short ones it would let in. */
|
||||
static int64_t prefetch_height(const RadBatch* batch) {
|
||||
return batch->phase == RAD_PHASE_DECODE ? batch->n_tok : INT64_MAX;
|
||||
}
|
||||
|
||||
void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused,
|
||||
bool ar_fused) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
@@ -593,9 +623,11 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
ln_k.step(c, w.h, w.k, T);
|
||||
if (cls.has_v) ln_v.step(c, w.h, w.v, T);
|
||||
}
|
||||
prefetch_beside(c, op_pfd, pfd_w, prefetch_height(batch));
|
||||
attend(c, batch);
|
||||
|
||||
ln_o.step(c, w.attn, w.h, T);
|
||||
prefetch_beside(c, op_pf, pf_w, prefetch_height(batch));
|
||||
/* The all-reduce comes before the post-norm: o_proj is column-sharded, so each rank holds a
|
||||
* partial sum, and the norm is of the whole output (sum_r rmsnorm(p_r) != rmsnorm(sum_r p_r)). */
|
||||
if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
@@ -676,6 +708,37 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
|
||||
brows(w.attn, T));
|
||||
}
|
||||
|
||||
/* A slice's rows see exactly the keys they see in the whole step: the cache holds the step's
|
||||
* earlier rows (the slices run in order, each storing its own keys first), `used` ends the context
|
||||
* at the slice's last row, the kernel counts each row's position back from there, and the key
|
||||
* tiles start at the sequence's first key in both cases. The prologue is a row at a time. */
|
||||
void Gemma4Attn::attend_rows(RadCtx* c, const RadBatch* batch, int64_t r0, int64_t n,
|
||||
RadOperand used) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0);
|
||||
const bool row = fused && op_qnr;
|
||||
const RadOperand Q = row ? bcol_at(w.qkv, r0, qkvd, 0, qd, n) : brow_slice(w.q, r0, n, qd);
|
||||
const RadOperand K = row ? bcol_at(w.qkv, r0, qkvd, qd, kvd, n) : brow_slice(w.k, r0, n, kvd);
|
||||
const RadOperand V = row && cls.has_v ? bcol_at(w.qkv, r0, qkvd, qd + kvd, kvd, n)
|
||||
: brow_slice(w.v, r0, n, kvd);
|
||||
RAD_ISSUE_N(c, op_qnr_kv, n, Q, K, V, praw(batch->positions + r0, RAD_I32, n), RAD_W(w_qn),
|
||||
RAD_W(w_kn), praw(slot ? slot + r0 : nullptr, RAD_I32, n), kv_cache(kv, layer));
|
||||
rad_op a_op = op_attn;
|
||||
RadOperand a_q = brow_slice(w.q, r0, n, qd);
|
||||
if (op_attn_row) {
|
||||
a_op = op_attn_row;
|
||||
a_q = Q;
|
||||
} else if (row) {
|
||||
RAD_ISSUE_N(c, op_lift_q, n, Q, a_q);
|
||||
}
|
||||
RAD_ISSUE_N(c, a_op, n, a_q, kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, 1, kvb ? kvb->block_table_pitch : 0), used,
|
||||
RAD_NONE, RAD_NONE, RAD_NONE, brow_slice(w.attn, r0, n, qd));
|
||||
}
|
||||
|
||||
/* ---- the feed-forward: GELU (not SwiGLU), with a second norm on the down-projection output. */
|
||||
struct Gemma4Mlp {
|
||||
struct Wire { rad_buf x = 0, h = 0, gu = 0, ffn = 0; };
|
||||
@@ -688,6 +751,10 @@ struct Gemma4Mlp {
|
||||
rad_op op_norm = 0, op_act = 0, op_post = 0, op_ar = 0, op_add = 0;
|
||||
/* gelu_mul and down's quantiser as one, where it resolves (libr4d `gelu_mul_quant_i8`) */
|
||||
rad_op op_gq = 0;
|
||||
/* the next layer's q|k|v read into the cache beside this block's all-reduce, or 0 (see
|
||||
* "Prefetch beside the reductions") */
|
||||
rad_op op_pf = 0;
|
||||
rad_weight pf_w = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre);
|
||||
void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false,
|
||||
@@ -791,6 +858,7 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai
|
||||
RAD_ISSUE(c, op_act, brows(w.gu, T), brows(w.ffn, T));
|
||||
ln_down.step(c, w.ffn, w.h, T);
|
||||
}
|
||||
prefetch_beside(c, op_pf, pf_w, prefetch_height(batch));
|
||||
/* The all-reduce before the post-norm, as in the attention block: down_proj is column-sharded. */
|
||||
if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
if (tail_fused) return;
|
||||
@@ -1362,6 +1430,17 @@ struct Layer {
|
||||
G4Junction j_am{}, j_ma{};
|
||||
/* the DFlash drafter's tap: this layer's output into its column slice of `dflash_src` */
|
||||
rad_op op_tap = 0;
|
||||
/* The prefill overlap's reductions (trunk_overlap): attn.op_ar and mlp.op_ar at `overlap` 1,
|
||||
* the narrow launch that leaves the CUs to the other slice's compute; 0 where not declared. */
|
||||
rad_op op_ar_att_ov = 0, op_ar_ff_ov = 0;
|
||||
};
|
||||
|
||||
/* The prefill overlap's attention per slice (trunk_overlap): slice A's context end, one
|
||||
* kv_len_trim a KV group the attention reads. */
|
||||
struct SliceTrim {
|
||||
rad_kvgroup kv = 0;
|
||||
rad_op op = 0;
|
||||
rad_buf used = 0; /* [max_seqs] int32 */
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -1417,6 +1496,10 @@ struct Model {
|
||||
Dflash2 df2{};
|
||||
Dflash2::Wire df2w{};
|
||||
bool have_df2 = false;
|
||||
/* The prefill overlap runs attention per slice: a trim a KV group (sliding, global). */
|
||||
SliceTrim trim[2]{};
|
||||
int n_trim = 0;
|
||||
bool slice_attn = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
@@ -1483,6 +1566,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;
|
||||
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);
|
||||
@@ -1881,6 +1965,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.ar_rows = ar ? rows : 0;
|
||||
}
|
||||
|
||||
/* ---- prefetch beside the reductions (see prefetch_beside): gate_up's first 20 MB beside the
|
||||
* 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. RADIANCE_PREFETCH=0 declares none
|
||||
* (decl_prefetch). */
|
||||
if (g.world > 1 && 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;
|
||||
lay.attn.op_pf = decl_prefetch(b, lay.attn.pf_w, gemma4::kPrefetchBytes);
|
||||
/* after the last layer the lm_head is the next weight streamed */
|
||||
if (l + 1 < m.layers.size()) {
|
||||
const Gemma4Attn& nx = m.layers[l + 1].attn;
|
||||
lay.mlp.pf_w = nx.fused ? nx.ln_qkv.w : nx.ln_q.w;
|
||||
} else {
|
||||
lay.mlp.pf_w = m.w_lm;
|
||||
}
|
||||
lay.mlp.op_pf = decl_prefetch(b, lay.mlp.pf_w, gemma4::kPrefetchBytes);
|
||||
}
|
||||
for (Layer& lay : m.layers) {
|
||||
lay.attn.pfd_w = lay.mlp.ln_down.w;
|
||||
lay.attn.op_pfd = decl_prefetch(b, lay.attn.pfd_w, gemma4::kPrefetchDownBytes);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the prefill overlap (trunk_overlap). It needs a reduction to hide, every junction fused
|
||||
* (the slices issue only the fused forms), and the exact wire, the one shown to give a slice
|
||||
* the bits it gives the whole. The buffer the second lane reduces in place is taken out of the
|
||||
@@ -1892,6 +2002,64 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
for (const Layer& lay : m.layers)
|
||||
m.overlap = m.overlap && lay.attn.op_ar && lay.mlp.op_ar;
|
||||
if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h));
|
||||
/* The reductions the overlap runs on lane 1 are their own ops at `overlap` 1. Declared like
|
||||
* op_ar, they resolve to the wide launch: the exact two-shot over every word of a 512- to
|
||||
* 1024-row slice takes nb_for_shard's ceiling, 24 blocks of 1024 threads, each a whole CU
|
||||
* spinning on a peer flag for the ~1 ms the link takes -- a third of the card held away from
|
||||
* the other slice's GEMMs. At `overlap` 1 the row is ar_twoshot_4rank_exact_lane: the same
|
||||
* entry and the same fold per word (the block count moves no byte), four blocks by default
|
||||
* (tArTs4Lane). Its range starts at a slice, which is above every one-shot band. */
|
||||
if (m.overlap) {
|
||||
auto lane_ar = [&]() {
|
||||
return rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", kOverlapRows * g.n_embd,
|
||||
g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes),
|
||||
RAD_INT("overlap", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_h}, {m.b_h});
|
||||
};
|
||||
for (Layer& lay : m.layers) {
|
||||
lay.op_ar_att_ov = lane_ar();
|
||||
lay.op_ar_ff_ov = lane_ar();
|
||||
}
|
||||
}
|
||||
/* ...and with attention per slice. Run whole between the slices, a layer's attention leaves
|
||||
* slice A's attention-side reduction only slice B's o_proj to hide behind, and slice B's
|
||||
* feed-forward reduction only slice A's junction and q|k|v. Per slice (A's projection,
|
||||
* prologue, attention and o_proj, then B's), each of the four reductions sits beside a whole
|
||||
* block: on 4x R9700 the exact two-shot of a 1024-row slice takes ~1.05 ms alone and ~1.4x
|
||||
* that beside any card-filling compute (a four-card microbenchmark, 2026-10-18). Slice A's
|
||||
* attention reads its context end from kv_len_trim, one a KV group. A one-sequence step only
|
||||
* (the slices' rows are then one sequence's), with the one-launch prologue and no
|
||||
* multi-component rotary. Byte-identical: every greedy reply matches the whole attention's
|
||||
* (4x R9700, two rounds, and 16 of 16 fresh starts on a 5310-token prompt); prefill +5%. */
|
||||
if (m.overlap) {
|
||||
bool ok = !g.rope_mc && rad_op_declared(b, "kv_len_trim");
|
||||
for (const Layer& lay : m.layers) ok = ok && lay.attn.slicable();
|
||||
for (const Layer& lay : m.layers) {
|
||||
if (!ok) break;
|
||||
int i = 0;
|
||||
while (i < m.n_trim && m.trim[i].kv != lay.attn.kv) ++i;
|
||||
if (i < m.n_trim) continue;
|
||||
if (m.n_trim == 2) { ok = false; break; }
|
||||
SliceTrim& t = m.trim[m.n_trim];
|
||||
t.kv = lay.attn.kv;
|
||||
t.used = decl_b(b, nm.f("slice_used_%d", m.n_trim), RAD_I32, {g.max_seqs});
|
||||
ok = t.used && rad_buf_concurrent(b, t.used) == RAD_OK;
|
||||
t.op = ok ? rw(b, RAD_OP(b, "kv_len_trim",
|
||||
RAD_PARAMS(RAD_RANGE("trim", 1, g.max_tok),
|
||||
RAD_INT("max_seqs", g.max_seqs)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {t.used})
|
||||
: 0;
|
||||
ok = ok && t.op;
|
||||
++m.n_trim;
|
||||
}
|
||||
m.slice_attn = ok && m.n_trim > 0;
|
||||
}
|
||||
|
||||
/* ---- the tail: final norm, the sampled rows, the lm_head, and the soft-cap. */
|
||||
m.op_final = rw(b, RAD_OP(b, "rmsnorm",
|
||||
@@ -2088,6 +2256,60 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
|
||||
|
||||
m.j0.step(c, T);
|
||||
const size_t L = m.layers.size();
|
||||
if (m.slice_attn && batch->n_seq == 1) {
|
||||
/* Attention per slice (see Model::slice_attn): slice A's context end first, then each
|
||||
* layer as A's attention block, B's beside A's attention-side reduction, A's feed-forward
|
||||
* beside B's, B's feed-forward beside A's, and the next layer's A block beside B's. Each
|
||||
* join is issued before the reduction it must not wait for, so it orders lane 0 behind
|
||||
* exactly the ones issued so far; lane 1 always reduces rows of `h` lane 0 is not
|
||||
* touching. */
|
||||
auto used_of = [&](rad_kvgroup kv, bool slice_a) -> RadOperand {
|
||||
if (slice_a)
|
||||
for (int i = 0; i < m.n_trim; ++i)
|
||||
if (m.trim[i].kv == kv) return brows(m.trim[i].used, 1);
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
return praw(kvb ? kvb->seqused : nullptr, RAD_I32, 1);
|
||||
};
|
||||
for (int i = 0; i < m.n_trim; ++i) {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, m.trim[i].kv);
|
||||
/* the trim is `tail`'s extent, slice B's rows: a launch reads its ranged parameter
|
||||
* as the band's upper bound, not as bn */
|
||||
RAD_ISSUE_N(c, m.trim[i].op, bn, praw(kvb ? kvb->seqused : nullptr, RAD_I32, 1),
|
||||
praw(batch->positions + b0, RAD_I32, bn), brows(m.trim[i].used, 1));
|
||||
}
|
||||
for (size_t li = 0; li < L; ++li) {
|
||||
const Layer& y = m.layers[li];
|
||||
const rad_op ar_att = y.op_ar_att_ov ? y.op_ar_att_ov : y.attn.op_ar;
|
||||
const rad_op ar_ff = y.op_ar_ff_ov ? y.op_ar_ff_ov : y.mlp.op_ar;
|
||||
if (li > 0) join_ff(li - 1, a0, an); /* its reduction was waited for below */
|
||||
y.attn.project(c, a0, an);
|
||||
y.attn.attend_rows(c, batch, a0, an, used_of(y.attn.kv, true));
|
||||
y.attn.out_proj(c, a0, an);
|
||||
if (li > 0) join_back(); /* the last layer's feed-forward, slice B */
|
||||
reduce(ar_att, a0, an);
|
||||
if (li > 0) join_ff(li - 1, b0, bn);
|
||||
y.attn.project(c, b0, bn);
|
||||
y.attn.attend_rows(c, batch, b0, bn, used_of(y.attn.kv, false));
|
||||
y.attn.out_proj(c, b0, bn);
|
||||
join_back(); /* attention, slice A */
|
||||
reduce(ar_att, b0, bn);
|
||||
y.j_am.step_rows(c, E, a0, an);
|
||||
y.mlp.arm(c, a0, an);
|
||||
join_back(); /* attention, slice B */
|
||||
reduce(ar_ff, a0, an);
|
||||
y.j_am.step_rows(c, E, b0, bn);
|
||||
y.mlp.arm(c, b0, bn);
|
||||
join_back(); /* the feed-forward, slice A */
|
||||
reduce(ar_ff, b0, bn);
|
||||
}
|
||||
join_ff(L - 1, a0, an);
|
||||
join_back(); /* the last feed-forward, slice B */
|
||||
join_ff(L - 1, b0, bn);
|
||||
if (!lanes_ok)
|
||||
rad_step_fail(c, "gemma4_bf16: the prefill overlap could not order its second lane "
|
||||
"against the first");
|
||||
return;
|
||||
}
|
||||
for (size_t li = 0; li < L; ++li) {
|
||||
const Layer& y = m.layers[li];
|
||||
if (li == 0) {
|
||||
@@ -2101,19 +2323,21 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
|
||||
y.attn.project(c, b0, bn);
|
||||
}
|
||||
y.attn.attend(c, batch);
|
||||
const rad_op ar_att = y.op_ar_att_ov ? y.op_ar_att_ov : y.attn.op_ar;
|
||||
const rad_op ar_ff = y.op_ar_ff_ov ? y.op_ar_ff_ov : y.mlp.op_ar;
|
||||
y.attn.out_proj(c, a0, an);
|
||||
reduce(y.attn.op_ar, a0, an);
|
||||
reduce(ar_att, a0, an);
|
||||
y.attn.out_proj(c, b0, bn);
|
||||
join_back(); /* attention, slice A */
|
||||
reduce(y.attn.op_ar, b0, bn);
|
||||
reduce(ar_att, b0, bn);
|
||||
y.j_am.step_rows(c, E, a0, an);
|
||||
y.mlp.arm(c, a0, an);
|
||||
join_back(); /* attention, slice B */
|
||||
reduce(y.mlp.op_ar, a0, an);
|
||||
reduce(ar_ff, a0, an);
|
||||
y.j_am.step_rows(c, E, b0, bn);
|
||||
y.mlp.arm(c, b0, bn);
|
||||
join_back(); /* the feed-forward, slice A */
|
||||
reduce(y.mlp.op_ar, b0, bn);
|
||||
reduce(ar_ff, b0, bn);
|
||||
}
|
||||
join_ff(L - 1, a0, an);
|
||||
join_back(); /* the last feed-forward, slice B */
|
||||
|
||||
@@ -1966,6 +1966,8 @@ void Builder::finish_layouts() {
|
||||
const int st = ki->layout ? ki->layout(r.geom.params(), r.geom.n_params(),
|
||||
operand, &w.enc, w.sel, t, w.n_sel, &L)
|
||||
: RAD_E_UNSUPPORTED;
|
||||
/* Reads the bytes uninterpreted (a prefetch): no claim (rad_abi.h). */
|
||||
if (st == RAD_LAYOUT_ANY) continue;
|
||||
char enc[256];
|
||||
rad_enc_format(&w.enc, enc, sizeof enc);
|
||||
if (st == RAD_E_DTYPE) {
|
||||
@@ -2353,6 +2355,8 @@ int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const ch
|
||||
return B(b)->lora_alias(native, from, to, from_lo, from_hi, to_lo);
|
||||
}
|
||||
|
||||
int rad_chain_on(void) { return rad_dev_chain_enabled(); }
|
||||
|
||||
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_encoder(d);
|
||||
|
||||
+86
-8
@@ -161,6 +161,9 @@ struct KernelRec {
|
||||
int32_t hid[16]; /* offset of each Hidden kind, or -1 */
|
||||
uint8_t hid_size[16];
|
||||
std::string name;
|
||||
/* A chained form (RadKernelChainFn): its name carries "r4dchain". Only such a kernel gets a
|
||||
* chain record and may lose its barrier bit; a row's other kernels keep the bit. */
|
||||
bool chained = false;
|
||||
};
|
||||
|
||||
struct ModuleImage {
|
||||
@@ -509,6 +512,7 @@ KernelRec* resolve(Func* fn, int ord) {
|
||||
}
|
||||
auto k = std::make_unique<KernelRec>();
|
||||
k->name = fn->name;
|
||||
k->chained = k->name.find("r4dchain") != std::string::npos;
|
||||
hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT, &k->object);
|
||||
hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_SIZE,
|
||||
&k->kernarg_size);
|
||||
@@ -596,6 +600,16 @@ struct Stream {
|
||||
std::atomic<int> fault{0};
|
||||
char* bounce = nullptr; /* pinned, for pageable copies */
|
||||
std::mutex bounce_mu;
|
||||
/* Chained launches (RadKernelChainFn): the completion counter every block of a chained kernel
|
||||
* adds 1 to (in the slot after the argument ring), the blocks of chained kernels issued so
|
||||
* far, and whether the last packet on the queue was a chained kernel. */
|
||||
uint64_t* chain_ctr = nullptr;
|
||||
uint64_t chain_issued = 0;
|
||||
bool prev_chained = false;
|
||||
/* Whether a packet that adds nothing to the counter (a plain kernel) may still be running: one
|
||||
* launched since the last packet whose barrier bit held it behind everything before. A chained
|
||||
* kernel's wait covers only chained blocks, so while this is set the next one keeps its bit. */
|
||||
bool plain_inflight = false;
|
||||
|
||||
void lock() {
|
||||
while (busy.exchange(true, std::memory_order_acquire))
|
||||
@@ -955,6 +969,9 @@ struct TapeRec {
|
||||
* on the queue still run. Set only where the dispatch touches nothing those packets write
|
||||
* (tape_set_overlap). */
|
||||
uint8_t overlap = 0;
|
||||
/* A chained kernel (RadKernelChainFn): played from the queue's own argument slot with a chain
|
||||
* record, and without the barrier bit behind another chained kernel. */
|
||||
uint8_t chain = 0;
|
||||
};
|
||||
|
||||
struct Tape {
|
||||
@@ -975,11 +992,12 @@ inline bool capturing() { return t_tape && t_tape_pause == 0; }
|
||||
|
||||
/* A dispatch just written at `p` on `s`, with its argument block `ka`. */
|
||||
void tape_note_dispatch(Stream* s, const hsa_kernel_dispatch_packet_t* p, uint16_t setup,
|
||||
const unsigned char* ka, uint32_t n, uint8_t fence) {
|
||||
const unsigned char* ka, uint32_t n, uint8_t fence, bool chain) {
|
||||
Tape* t = t_tape;
|
||||
TapeRec r;
|
||||
r.kind = kTapeDispatch;
|
||||
r.fence = fence;
|
||||
r.chain = chain ? 1 : 0;
|
||||
r.s = s;
|
||||
r.pkt = *p;
|
||||
r.pkt.header = 0;
|
||||
@@ -1014,12 +1032,32 @@ inline int acquire_scope(Stream* s, uint64_t idx, bool forced) {
|
||||
return HSA_FENCE_SCOPE_AGENT;
|
||||
}
|
||||
|
||||
/* The chain record of a chained launch (RadKernelChainFn) at `slot`: wait for every chained
|
||||
* block issued before it on `s`. `on` false writes a record no kernel accepts. */
|
||||
inline void chain_record(Stream* s, char* slot, bool on) {
|
||||
uint64_t rec[4];
|
||||
rec[0] = on ? RAD_CHAIN_MAGIC : 0;
|
||||
rec[1] = s->chain_issued;
|
||||
rec[2] = (uint64_t)(uintptr_t)s->chain_ctr;
|
||||
rec[3] = rec[0] ^ rec[1] ^ rec[2] ^ RAD_CHAIN_CHECK;
|
||||
std::memcpy(slot + RAD_CHAIN_KARG_OFF, rec, sizeof rec);
|
||||
}
|
||||
inline uint64_t blocks_of(const hsa_kernel_dispatch_packet_t* p) {
|
||||
auto n = [](uint32_t g, uint16_t b) { return b ? (uint64_t)((g + b - 1u) / b) : 1u; };
|
||||
return n(p->grid_size_x, p->workgroup_size_x) * n(p->grid_size_y, p->workgroup_size_y) *
|
||||
n(p->grid_size_z, p->workgroup_size_z);
|
||||
}
|
||||
static_assert(RAD_CHAIN_KARG_OFF >= kKargMax && RAD_CHAIN_KARG_OFF + RAD_CHAIN_REC_BYTES <= kKargSlot,
|
||||
"the chain record sits in an argument slot's tail, past every kernel's arguments");
|
||||
|
||||
int barrier(Stream* s, hsa_signal_t dep, hsa_signal_t done, int acq, int rel,
|
||||
uint64_t* out_idx = nullptr) {
|
||||
s->lock();
|
||||
uint64_t idx = 0;
|
||||
const int rc = reserve(s, &idx);
|
||||
if (rc < 0) { s->unlock(); return rc; }
|
||||
s->prev_chained = false;
|
||||
s->plain_inflight = false;
|
||||
if (out_idx) *out_idx = idx;
|
||||
auto* p = reinterpret_cast<hsa_barrier_and_packet_t*>(
|
||||
static_cast<hsa_kernel_dispatch_packet_t*>(s->q->base_address) + (idx & s->mask));
|
||||
@@ -1079,7 +1117,11 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
|
||||
p->reserved2 = 0;
|
||||
p->completion_signal.handle = 0;
|
||||
constexpr uint16_t setup = 3u << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS;
|
||||
if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence);
|
||||
/* A chained kernel (RadKernelChainFn, named r4dchain*): its record in the slot's tail. */
|
||||
const bool chain = k->chained && rad_dev_chain_enabled() && s->chain_ctr &&
|
||||
n <= RAD_CHAIN_KARG_OFF;
|
||||
if (k->chained) chain_record(s, slot, chain);
|
||||
if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence, chain);
|
||||
/* Attach the ride after the tape copied the packet: a recorded packet carries no signal, and
|
||||
* a play attaches whichever ride is pending then (PlayRun::put). */
|
||||
if (s->ride.handle) {
|
||||
@@ -1088,7 +1130,13 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t
|
||||
}
|
||||
const int acq = acquire_scope(s, idx, (fence & kFenceAcquireSystem) != 0);
|
||||
const int rel = (fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT;
|
||||
publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel), setup);
|
||||
/* Behind another chained kernel a chained one waits in its prologue; a completion signal keeps
|
||||
* the bit, since its completion must cover everything before it. */
|
||||
const bool keep = !(chain && s->prev_chained && !s->plain_inflight && !p->completion_signal.handle);
|
||||
publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, keep), setup);
|
||||
if (chain) s->chain_issued += blocks_of(p);
|
||||
s->prev_chained = chain;
|
||||
s->plain_inflight = keep ? !chain : s->plain_inflight || !chain;
|
||||
s->unlock();
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1110,6 +1158,7 @@ constexpr int kPlayLeft = 8;
|
||||
thread_local PlayLeft t_left[kPlayLeft];
|
||||
|
||||
struct PlayRun {
|
||||
const Tape* tape = nullptr; /* the tape played, for a chained record's argument bytes */
|
||||
Stream* s = nullptr;
|
||||
uint64_t next = 0; /* the write index after the last packet written */
|
||||
int unrung = 0;
|
||||
@@ -1167,16 +1216,38 @@ struct PlayRun {
|
||||
s->ride.handle = 0;
|
||||
}
|
||||
if (done.handle) p->completion_signal = done;
|
||||
/* A chained record plays from this queue's own argument slot, where its chain record goes:
|
||||
* the tape's copy is shared by every play, and the next step's play may be written while
|
||||
* this one runs. */
|
||||
bool chain = false;
|
||||
if (r.chain && tape) {
|
||||
char* slot = s->karg + (size_t)(idx & s->mask) * kKargSlot;
|
||||
chain = s->chain_ctr && r.karg_len <= RAD_CHAIN_KARG_OFF;
|
||||
if (chain) {
|
||||
std::memcpy(slot, tape->karg_host.data() + r.karg_off, r.karg_len);
|
||||
p->kernarg_address = slot;
|
||||
chain_record(s, slot, true);
|
||||
}
|
||||
}
|
||||
const int acq = acquire_scope(s, idx, (r.fence & kFenceAcquireSystem) != 0);
|
||||
int rel = (r.fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT;
|
||||
if (rel < rel_min) rel = rel_min;
|
||||
/* A dispatch carrying a record keeps the bit: its completion must cover everything before
|
||||
* it on the queue, which an unordered dispatch's does not. */
|
||||
const bool ordered = foreign || !r.overlap || done.handle;
|
||||
* it on the queue, which an unordered dispatch's does not. A chained kernel behind another chained one
|
||||
* on this queue waits in its prologue instead. */
|
||||
bool ordered = foreign || !r.overlap || done.handle;
|
||||
/* Not while a plain packet may still run: a played plain kernel the overlap analysis let
|
||||
* start early (it touched nothing in flight) adds nothing to the counter, so a chained
|
||||
* kernel that reads its output and sits behind a chained one (a cache read beside a
|
||||
* collective, say) would wait for the chained blocks only. */
|
||||
if (chain && s->prev_chained && !s->plain_inflight && !foreign && !done.handle) ordered = false;
|
||||
const uint16_t h = header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, ordered);
|
||||
__atomic_store_n(reinterpret_cast<uint32_t*>(p), (uint32_t)h | ((uint32_t)r.pkt.setup << 16),
|
||||
__ATOMIC_RELEASE);
|
||||
foreign = false;
|
||||
if (chain) s->chain_issued += blocks_of(p);
|
||||
s->prev_chained = chain;
|
||||
s->plain_inflight = ordered ? !chain : s->plain_inflight || !chain;
|
||||
s->wr = idx + 1;
|
||||
next = idx + 1;
|
||||
*out_idx = idx;
|
||||
@@ -1423,7 +1494,7 @@ int a_stream_create(RadStream* out, int high_priority) {
|
||||
void* ka = nullptr;
|
||||
hsa_amd_memory_pool_t kpool = d.host_kargs ? G().host_fine : d.vram;
|
||||
hsa_agent_t kpeer = d.host_kargs ? d.agent : G().cpu;
|
||||
if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 1) * kKargSlot, 0, &ka) !=
|
||||
if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 2) * kKargSlot, 0, &ka) !=
|
||||
HSA_STATUS_SUCCESS ||
|
||||
hsa_amd_agents_allow_access(1, &kpeer, nullptr, ka) != HSA_STATUS_SUCCESS) {
|
||||
hsa_queue_destroy(s->q);
|
||||
@@ -1432,6 +1503,9 @@ int a_stream_create(RadStream* out, int high_priority) {
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
s->karg = static_cast<char*>(ka);
|
||||
s->chain_ctr = reinterpret_cast<uint64_t*>(s->karg + (size_t)(s->mask + 1) * kKargSlot);
|
||||
*reinterpret_cast<volatile uint64_t*>(s->chain_ctr) = 0;
|
||||
_mm_sfence();
|
||||
void* bb = nullptr;
|
||||
if (hsa_amd_memory_pool_allocate(G().host_fine, kBounceBytes, 0, &bb) != HSA_STATUS_SUCCESS ||
|
||||
hsa_amd_agents_allow_access(1, &d.agent, nullptr, bb) != HSA_STATUS_SUCCESS) {
|
||||
@@ -1441,7 +1515,7 @@ int a_stream_create(RadStream* out, int high_priority) {
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
s->bounce = static_cast<char*>(bb);
|
||||
note_alloc(ka, (int64_t)(s->mask + 1) * kKargSlot, -1);
|
||||
note_alloc(ka, (int64_t)(s->mask + 2) * kKargSlot, -1);
|
||||
note_alloc(bb, kBounceBytes, -1);
|
||||
s->id = g_next_queue_id.fetch_add(1, std::memory_order_relaxed);
|
||||
if (s->id >= kMaxQueues) {
|
||||
@@ -1802,9 +1876,12 @@ RadTape a_tape_end(int keep) {
|
||||
if (!t->karg_host.empty()) {
|
||||
const Dev& d = G().dev[(size_t)ord];
|
||||
void* ka = nullptr;
|
||||
/* Padded by a slot: a chained kernel played from here reads its record's place
|
||||
* (RAD_CHAIN_KARG_OFF) past its own arguments. */
|
||||
hsa_amd_memory_pool_t pool = d.host_kargs ? G().host_fine : d.vram;
|
||||
hsa_agent_t peer = d.host_kargs ? d.agent : G().cpu;
|
||||
if (hsa_amd_memory_pool_allocate(pool, t->karg_host.size(), 0, &ka) != HSA_STATUS_SUCCESS ||
|
||||
if (hsa_amd_memory_pool_allocate(pool, t->karg_host.size() + kKargSlot, 0, &ka) !=
|
||||
HSA_STATUS_SUCCESS ||
|
||||
hsa_amd_agents_allow_access(1, &peer, nullptr, ka) != HSA_STATUS_SUCCESS) {
|
||||
if (ka) hsa_amd_memory_pool_free(ka);
|
||||
device_set_error("the pass cannot be recorded: %zu bytes of kernel arguments could "
|
||||
@@ -1854,6 +1931,7 @@ int a_tape_play(RadTape rt, int from, int to) {
|
||||
++t_tape_pause;
|
||||
int rc = RAD_OK;
|
||||
PlayRun run;
|
||||
run.tape = t;
|
||||
for (int i = from; i < to && rc >= 0; ++i) {
|
||||
const TapeRec& r = t->rec[(size_t)i];
|
||||
if (r.kind == kTapeDispatch) {
|
||||
|
||||
@@ -36,6 +36,15 @@ extern "C" int rad_event_create_as(RadEvent* out, unsigned flags);
|
||||
/* The host has just written memory that a kernel issued after this call reads, with no host wait
|
||||
* in between (e.g. a host-site op's output read over the link by the next device op). */
|
||||
extern "C" void rad_dev_host_wrote(void);
|
||||
/* Chained launches: chainable rows run their chained forms (RadKernelChainFn), and the backend
|
||||
* lets a chained kernel (named r4dchain*) wait in its prologue instead of behind the barrier bit.
|
||||
* Only on the AQL backend, whose queues keep the completion counter. On by default where the
|
||||
* model's plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays: the
|
||||
* Gemma 4 31B and 26B) and that drafter decodes speculatively (rad_dev_chain_infer, from the
|
||||
* engine before any row resolves). RADIANCE_CHAIN=0 turns them off and =1 on wherever the backend
|
||||
* chains; `auto` is the default. */
|
||||
extern "C" int rad_dev_chain_enabled(void);
|
||||
extern "C" void rad_dev_chain_infer(int pays);
|
||||
|
||||
/* One range of a ranged copy: `bytes` from source offset `src` to destination offset `dst`, all
|
||||
* three multiples of four. */
|
||||
|
||||
@@ -556,6 +556,29 @@ int rad_event_sync(RadEvent e) {
|
||||
return dev()->event_sync(e);
|
||||
}
|
||||
void rad_dev_host_wrote(void) { dev()->host_wrote(); }
|
||||
|
||||
/* Chaining's default, from the engine (rad_dev_chain_infer), and the answer once taken. Only
|
||||
* where the backend chains: the AQL backend writes the record a chained form reads, while a HIP
|
||||
* launch carries only the kernel's own arguments. */
|
||||
static std::atomic<int> g_chain_pays{0};
|
||||
static std::atomic<int> g_chain{-1};
|
||||
void rad_dev_chain_infer(int pays) {
|
||||
g_chain_pays.store(pays ? 1 : 0, std::memory_order_relaxed);
|
||||
g_chain.store(-1, std::memory_order_relaxed);
|
||||
}
|
||||
int rad_dev_chain_enabled(void) {
|
||||
int on = g_chain.load(std::memory_order_relaxed);
|
||||
if (on < 0) {
|
||||
const char* e = std::getenv("RADIANCE_CHAIN");
|
||||
const bool want = e && *e && std::strcmp(e, "auto") != 0
|
||||
? *e != '0'
|
||||
: g_chain_pays.load(std::memory_order_relaxed) != 0;
|
||||
on = want && std::strcmp(rad::device_backend_name(), "aql") == 0 ? 1 : 0;
|
||||
g_chain.store(on, std::memory_order_relaxed);
|
||||
}
|
||||
return on;
|
||||
}
|
||||
|
||||
int rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
|
||||
return dev()->event_elapsed_ms(a, b, out);
|
||||
}
|
||||
|
||||
@@ -1026,6 +1026,25 @@ int Engine::declare() {
|
||||
cfg_.n_spec > 0 ? "the depth the drafter in this container states as its operating point"
|
||||
: "this container carries no draft head");
|
||||
}
|
||||
/* Chained launches pay on some speculative steps and cost plain decode (4x R9700: the 31B
|
||||
* with DFlash2 +13%, the 26B-A4B with DFlash +1%, Qwen3.8-27B with DFlash2 even; the 31B with
|
||||
* no drafter -6.5%), so they are on by default only where the model's plugin measured a gain
|
||||
* with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
|
||||
* speculatively. */
|
||||
{
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
rad_dev_chain_infer(cfg_.n_spec > 0 && pb.chain_pays);
|
||||
const char* e = std::getenv("RADIANCE_CHAIN");
|
||||
const bool on = rad_dev_chain_enabled() != 0;
|
||||
const char* why = e && *e && std::strcmp(e, "auto") != 0
|
||||
? (on || *e == '0' ? "RADIANCE_CHAIN says so" : "the backend does not chain")
|
||||
: on ? "the model's plugin measured a gain with its speculative drafter"
|
||||
: "no drafter whose plugin measured a gain with them decodes "
|
||||
"speculatively, or the backend does not chain";
|
||||
RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why);
|
||||
decide("RADIANCE_CHAIN", on ? "1" : "0", why);
|
||||
}
|
||||
/* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio
|
||||
* encoder (`radiance.encoder` names one) and the deployment is not text-only. */
|
||||
if (cfg_.mm_audio_frames < 0) {
|
||||
|
||||
@@ -441,6 +441,7 @@ int Registry::commit_(Staged& s, int order) {
|
||||
}
|
||||
const auto concurrent = dl_fn<RadKernelConcurrentFn>(s.handle, "rad_kernel_concurrent");
|
||||
const auto collective = dl_fn<RadKernelCollectiveFn>(s.handle, "rad_kernel_collective");
|
||||
const auto chainable = dl_fn<RadKernelChainFn>(s.handle, "rad_kernel_chain");
|
||||
for (const auto& sr : staged_rows) {
|
||||
KernelRow row;
|
||||
row.info = sr.first;
|
||||
@@ -452,6 +453,7 @@ int Registry::commit_(Staged& s, int order) {
|
||||
row.collective = coll != 0;
|
||||
row.releases_link = coll == 2;
|
||||
row.reference = p.reference;
|
||||
row.chain = chainable && chainable(sr.second) != 0;
|
||||
rows_.push_back(row);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* one. A match is necessary, not sufficient: strides, contiguity, alignment and buffer sizes are
|
||||
* properties of a call, and the entry point still rejects what it cannot run.
|
||||
*/
|
||||
#include "../device/device.h"
|
||||
#include "registry.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -384,6 +385,10 @@ Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, S
|
||||
for (const auto& kv : chosen) r.geom.set_i(kv.first, kv.second);
|
||||
r.choice = TuneCache::canon_choice(chosen);
|
||||
}
|
||||
/* A chainable row runs its chained form wherever chaining is on (RadKernelChainFn); the
|
||||
* parameter is outside the tune cache's key, which was taken above. */
|
||||
if (r.row->chain && rad_dev_chain_enabled())
|
||||
r.geom.set_i("chain", 1);
|
||||
|
||||
/* scratch_bytes stays 0: the scratch hook needs a RadArgs with the operand tensors, which the
|
||||
* builder owns and sizes the arena with. */
|
||||
|
||||
@@ -346,8 +346,8 @@ extern "C" int rad_plugin_reference(void) { return 1; }
|
||||
|
||||
/* ================================================================== radtest_extra */
|
||||
/* Rows for rules the base plugin's ops do not reach: a constraint on the ranged key that is not an
|
||||
* interval, a tunable axis with a cross-axis test, a kernel that relayouts its weight, and a
|
||||
* capacity parameter. In testkernels/extra, so loading testkernels/ alone is unchanged. */
|
||||
* interval, a tunable axis with a cross-axis test, a kernel that relayouts its weight, a kernel
|
||||
* that reads any stored form, and a capacity parameter. In testkernels/extra, so loading testkernels/ alone is unchanged. */
|
||||
#elif defined(RADTEST_EXTRA)
|
||||
|
||||
static const RadOperandSpec kOpdCap[] = {
|
||||
@@ -368,6 +368,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"a kernel that stores its weight in its own layout" },
|
||||
{ "t_join", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm),
|
||||
"a weight of several planes: a device kernel's own form, a host kernel's joined one" },
|
||||
{ "t_any", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm),
|
||||
"a kernel that reads its weight's stored bytes uninterpreted (a prefetch)" },
|
||||
{ "t_cap", kPCap, NELEM(kPCap), kOpdCap, NELEM(kOpdCap),
|
||||
"a capacity a sizing declare may shrink" },
|
||||
};
|
||||
@@ -417,6 +419,12 @@ static int t_join_host_layout(const RadParam* p, int n_p, int operand, const Rad
|
||||
return rad_planes_layout(enc, sel, planes, n_planes, out);
|
||||
}
|
||||
|
||||
/* Reads the stored bytes without interpreting them: any form, and claims none. */
|
||||
static int t_any_layout(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, RadLayout*) {
|
||||
return RAD_LAYOUT_ANY;
|
||||
}
|
||||
|
||||
static const RadConstraint kCLayTiled[] = { RAD_CLE("M", 16) };
|
||||
static const RadConstraint kCLayPlain[] = { RAD_CLE("M", 4096) };
|
||||
|
||||
@@ -462,6 +470,11 @@ static const RadKernelInfo kKernels[] = {
|
||||
.domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch,
|
||||
.layout = t_join_host_layout },
|
||||
|
||||
{ .name = "t_any_read", .op = "t_any", .family = "misc",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any stored form",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch,
|
||||
.layout = t_any_layout },
|
||||
|
||||
{ .name = "t_cap_any", .op = "t_cap", .family = "norm",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch },
|
||||
|
||||
@@ -57,6 +57,8 @@ struct KernelRow {
|
||||
bool releases_link = false;
|
||||
/* The row's plugin declared itself a reference implementation (RadPluginReferenceFn). */
|
||||
bool reference = false;
|
||||
/* rad_kernel_chain: its launches can wait in the kernel instead of behind the barrier bit. */
|
||||
bool chain = false;
|
||||
};
|
||||
|
||||
/* A kernel bound to one geometry, one domain and one variant, with init() already run. */
|
||||
|
||||
@@ -455,6 +455,7 @@ int Ctx::check_domain_layout(rad_op h, int domain, std::string* why) const {
|
||||
const int st = ki->layout ? ki->layout(ip.args.p, ip.args.n_p, opd, &w.enc, w.sel, t,
|
||||
w.n_sel, &L)
|
||||
: RAD_E_UNSUPPORTED;
|
||||
if (st == RAD_LAYOUT_ANY) continue; /* reads the bytes as they lie (rad_abi.h) */
|
||||
const std::string tag = st == RAD_OK ? (L.tag && *L.tag ? L.tag : ki->name)
|
||||
: std::string();
|
||||
if (st >= 0 || st == RAD_E_UNSUPPORTED) {
|
||||
|
||||
+51
-2
@@ -5,7 +5,12 @@
|
||||
*/
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
#include "advance_impl.h"
|
||||
#include "rad_abi.h"
|
||||
|
||||
extern "C" int rad_dev_chain_enabled(void); /* core/device/device.h */
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -16,12 +21,56 @@ __global__ __launch_bounds__(kThreads) void rad_step_advance(rad::AdvanceArgs a)
|
||||
if (i < a.n_seq) rad::adv_row(a, i);
|
||||
}
|
||||
|
||||
/* The chained form (RadKernelChainFn, abi/rad_abi.h): the backend gives a kernel named r4dchain*
|
||||
* a record at RAD_CHAIN_KARG_OFF and drops its barrier bit behind another chained kernel. Before
|
||||
* the first read one lane waits for the queue's counter to reach the record's target; after the
|
||||
* last write the block releases and adds 1. A record that does not check out means: run plain. */
|
||||
struct ChainRec {
|
||||
unsigned long long magic, target;
|
||||
unsigned long long* ctr;
|
||||
unsigned long long check;
|
||||
};
|
||||
__device__ __forceinline__ const ChainRec* chain_rec() {
|
||||
const ChainRec* r = (const ChainRec*)((const char*)__builtin_amdgcn_kernarg_segment_ptr() +
|
||||
RAD_CHAIN_KARG_OFF);
|
||||
const unsigned long long magic = r->magic, target = r->target, check = r->check;
|
||||
if (magic != RAD_CHAIN_MAGIC ||
|
||||
check != (magic ^ target ^ (unsigned long long)(uintptr_t)r->ctr ^ RAD_CHAIN_CHECK))
|
||||
return nullptr;
|
||||
return r;
|
||||
}
|
||||
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_step_advance(rad::AdvanceArgs a) {
|
||||
const ChainRec* r = chain_rec();
|
||||
if (r) {
|
||||
if (threadIdx.x == 0)
|
||||
while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target)
|
||||
__builtin_amdgcn_s_sleep(1);
|
||||
__syncthreads();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
|
||||
}
|
||||
const int i = (int)(blockIdx.x * kThreads + threadIdx.x);
|
||||
if (i < a.n_seq) rad::adv_row(a, i);
|
||||
if (r) {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0)
|
||||
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream) {
|
||||
if (!args || args->n_seq <= 0) return 0;
|
||||
const unsigned blocks = (unsigned)((args->n_seq + kThreads - 1) / kThreads);
|
||||
hipLaunchKernelGGL(rad_step_advance, dim3(blocks), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
*args);
|
||||
/* The chained form only where launches chain (rad_dev_chain_enabled): there the backend writes
|
||||
* its record; elsewhere a launch carries only these arguments, so the plain kernel runs. */
|
||||
if (!rad_dev_chain_enabled())
|
||||
hipLaunchKernelGGL(rad_step_advance, dim3(blocks), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
*args);
|
||||
else
|
||||
hipLaunchKernelGGL(r4dchain_step_advance, dim3(blocks), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, *args);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -1;
|
||||
}
|
||||
@@ -3086,6 +3086,8 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp
|
||||
| `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) |
|
||||
| `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) |
|
||||
| `RADIANCE_AR_FENCE_FROM` | four-rank all-reduces of at least this many elements take a full fence before their flag (default 131072: prefill chunks, never decode or verify); cures a rare fresh-start divergence on the 31B at tp 4; `0` turns it off |
|
||||
| `RADIANCE_PREFETCH` | `0` declares none of the weight reads the Gemma 4 31B and its DFlash2 drafter issue beside each all-reduce at decode and verify heights (libr4d `prefetch`: the next GEMM's leading weight bytes read into the on-die cache while the collective leaves the memory idle); on by default at more than one rank where the kernel library serves the op |
|
||||
| `RADIANCE_CHAIN` | chained launches, where a dependent kernel waits for the one before it in its own prologue rather than behind the queue's barrier bit: on by default on the AQL backend where the model's plugin measured a gain with its speculative drafter (the Gemma 4 31B and 26B) and that drafter decodes speculatively (`auto`, the default); `0` turns them off, `1` on wherever the backend chains |
|
||||
| `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) |
|
||||
| `RADIANCE_GEMMA4_OVERLAP` | the Gemma 4 31B's prefill overlap (`arch/gemma4_bf16`, two or more ranks, fused junctions, the exact all-reduce wire): a prefill step of 1024 rows or more runs as two slices, each slice's all-reduces on a second stream beside the other's compute. On by default; `0` turns it off and runs every step whole (the startup notes say which) |
|
||||
| `RADIANCE_AR8_SHARD_WEIGHTS`, `RADIANCE_AR8_PIECES` | the eight-rank two-shot's shard weights (`auto`, the default, reads the PCIe links; `off`; or eight integers) and piece count, with `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` for the message size each starts at (§4.7) |
|
||||
|
||||
+26
@@ -811,6 +811,32 @@ tiled rows over row tiles that outrank them: a WMMA shrink whose summation order
|
||||
and `R`, and an expand that stages `lora_b[s]` in LDS for a tile of rows and computes libref's
|
||||
bytes).
|
||||
|
||||
### `kv_len_trim` (device-only)
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `kv_len_trim` | `trim` `max_seqs` | `seqused`, `tail` → `out` |
|
||||
|
||||
`out[s] = max(seqused[s] - trim, 0)` for each of the batch's sequences, `trim` the extent of
|
||||
`tail`: the rows past the slice (their positions; the values are not read). A step's attention
|
||||
over a slice of its rows that ends `trim` rows before the step does takes `out` as its `seqused`:
|
||||
those rows then see exactly the keys they see in the whole step, and the positions the kernel
|
||||
counts back from the context's end are theirs. `trim` is the op's ranged parameter, issued at the
|
||||
count, but a launch sees every parameter collapsed to its band's upper bound, so the kernel takes
|
||||
the count from `tail`, as a GEMM takes its M from its operands.
|
||||
|
||||
### `prefetch` (device-only)
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `prefetch` | `bytes` | `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 on the second
|
||||
lane beside a collective that leaves the card's memory idle (`rad_lane`); on the same lane it would
|
||||
only add its own time. Its layout hook answers RAD_LAYOUT_ANY (abi/rad_abi.h): it takes the bytes
|
||||
as the weight's GEMM stored them and claims no form. It changes no value.
|
||||
|
||||
## Attention
|
||||
|
||||
| op | params | operands |
|
||||
|
||||
@@ -161,6 +161,10 @@ set(R4D_UNITS
|
||||
"r4d_quant_act_i8|"
|
||||
"r4d_rmsnorm_quant_i8|"
|
||||
"r4d_qkv_norm_rope|"
|
||||
# A batch's context lengths less a runtime trim (the 31B's per-slice prefill attention).
|
||||
"r4d_kv_len_trim|"
|
||||
# A weight read into the on-die cache beside a collective (the prefetch op).
|
||||
"r4d_prefetch|"
|
||||
"r4d_gelu_mul_quant_i8|"
|
||||
"r4d_had_quant_act_i8|"
|
||||
"r4d_rmsnorm_had_quant_i8|"
|
||||
|
||||
+6
-2
@@ -79,6 +79,9 @@ struct R4DArgs {
|
||||
// rows of q_len * GQA: the 31B's DFlash drafter, gqa 8 at a block of 16, on the gqa-4 kernel.
|
||||
long q_ld;
|
||||
int kv_rep;
|
||||
// The engine's chained launch (RadKernelChainFn, r4d_chain.h): the decode path launches its
|
||||
// chained forms. fill_paged sets it from the resolved `chain` parameter.
|
||||
int chain;
|
||||
};
|
||||
|
||||
// Rows of q and out. The split-KV scratch is laid out by dense query row, so the host sizing hook
|
||||
@@ -428,7 +431,7 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee
|
||||
long my_scratch, long my_flags, long seq_ctrs,
|
||||
long slot_stride16, long inp, long out, long n_elem, long dtype,
|
||||
long rank, long stream, long nblocks, long nthreads, long drain,
|
||||
long acq, long pub, long gate, long gate_ctr);
|
||||
long acq, long pub, long gate, long gate_ctr, long chain);
|
||||
void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
long peer_scratch3, long peer_scratch4, long peer_scratch5,
|
||||
long peer_scratch6, long peer_flags0, long peer_flags1,
|
||||
@@ -799,7 +802,8 @@ int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, long
|
||||
int sc_f32, long y, long q, long s, int M, int n, float eps,
|
||||
float wadd, int w_f32, int r_ld, int y_ld, int rank,
|
||||
long stream, int nblocks, int drain, int acq, int pub,
|
||||
long gate, long gate_ctr, long tail_ctr, int tail_nbt);
|
||||
long gate, long gate_ctr, long tail_ctr, int tail_nbt,
|
||||
int chain);
|
||||
|
||||
// ---- sampling ----------------------------------------------------------------------------------
|
||||
//
|
||||
|
||||
+15
-5
@@ -675,6 +675,12 @@ static int nb_for(long words16, int max_nb) {
|
||||
* rows (2688 words, four blocks either way) the two rules agree (4x R9700, a four-card
|
||||
* microbenchmark of this kernel, 2026-10-17). The block count moves no byte: every word is folded
|
||||
* by one thread in ascending rank order whatever the grid. */
|
||||
/* The chained two-shot (r4d_chain.h) where the row resolved with `chain`, for a decode-sized
|
||||
* message only (64 rows of an 8192-wide residual): DFlash2's verify-height reductions. */
|
||||
static long ar_chain(const RadArgs* a, long numel) {
|
||||
return r4d_geti_or(a, "chain", 0) != 0 && numel <= 64L * 8192L ? 1L : 0L;
|
||||
}
|
||||
|
||||
static int nb_for_shard(long shard16, int max_nb) {
|
||||
long nb = shard16 / 672;
|
||||
if (nb < 2) nb = 2;
|
||||
@@ -752,7 +758,7 @@ extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long
|
||||
long slot_stride16, long inp, long out, long n_elem,
|
||||
long dtype, long rank, long row_elems, long stream,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub,
|
||||
long gate, long gate_ctr, long dpitch, long spitch);
|
||||
long gate, long gate_ctr, long dpitch, long spitch, long chain);
|
||||
extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
long peer_scratch3, long peer_scratch4, long peer_scratch5,
|
||||
long peer_scratch6, long peer_flags0, long peer_flags1,
|
||||
@@ -876,7 +882,8 @@ extern "C" int r4d_rad_ar_gather_4rank(const RadArgs* a, RadStream s) {
|
||||
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
|
||||
c.inp, c.out, c.numel, in->dtype, in->rank, (long)row,
|
||||
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub,
|
||||
early, early ? in->gate_ctr : 0L, (long)dpitch, (long)spitch));
|
||||
early, early ? in->gate_ctr : 0L, (long)dpitch, (long)spitch,
|
||||
ar_chain(a, c.numel)));
|
||||
return early ? RAD_LINK_ENDED : RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1026,7 +1033,8 @@ extern "C" int r4d_rad_ar_oneshot_4rank_exact(const RadArgs* a, RadStream s) {
|
||||
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
|
||||
c.inp, c.out, c.numel, in->dtype, in->rank,
|
||||
(long)(uintptr_t)s, nb, c.nthreads, c.drain, c.acq,
|
||||
c.pub, early, early ? in->gate_ctr : 0L));
|
||||
c.pub, early, early ? in->gate_ctr : 0L,
|
||||
ar_chain(a, c.numel)));
|
||||
return early ? RAD_LINK_ENDED : RAD_OK;
|
||||
}
|
||||
/* The wide release, the two-rank family's rule: over P2P the kernel ends the engine's hold
|
||||
@@ -1115,7 +1123,8 @@ extern "C" int r4d_rad_ar_twoshot_4rank_exact(const RadArgs* a, RadStream s) {
|
||||
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
|
||||
c.inp, c.out, c.numel, in->dtype, in->rank,
|
||||
(long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq,
|
||||
c.pub, early, early ? in->gate_ctr : 0L));
|
||||
c.pub, early, early ? in->gate_ctr : 0L,
|
||||
ar_chain(a, c.numel)));
|
||||
return early ? RAD_LINK_ENDED : RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1549,7 +1558,8 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s)
|
||||
v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc),
|
||||
(int)v.M, (int)v.K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
|
||||
v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (int)in->rank, (long)(uintptr_t)s, nblocks,
|
||||
cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L, tail_ctr, tail_nbt);
|
||||
cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L, tail_ctr, tail_nbt,
|
||||
r4d_geti_or(a, "chain", 0) != 0 ? 1 : 0);
|
||||
if (e != 0) return RAD_E_SHAPE;
|
||||
return early ? RAD_LINK_ENDED : RAD_OK;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
// the peer arrays.
|
||||
#include "r4d.h"
|
||||
#include "r4d_ar_wide.h"
|
||||
#include "r4d_chain.h"
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
@@ -40,7 +41,7 @@ extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long
|
||||
long slot_stride16, long inp, long out, long n_elem,
|
||||
long dtype, long rank, long row_elems, long stream,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub,
|
||||
long gate, long gate_ctr, long dpitch, long spitch);
|
||||
long gate, long gate_ctr, long dpitch, long spitch, long chain);
|
||||
extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
long peer_scratch3, long peer_scratch4, long peer_scratch5,
|
||||
long peer_scratch6, long peer_flags0, long peer_flags1,
|
||||
@@ -70,8 +71,11 @@ __device__ __forceinline__ int r4d_g_src_ws(int k, int row16, int n16, int sp16)
|
||||
|
||||
// Block b owns words [start,end) of the 16B-word space and drives its own handshake; no cross-block
|
||||
// sync, as in the all-reduce.
|
||||
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. The chained form
|
||||
// waits before the sequence take, so a block of the next launch on the instance never starts
|
||||
// ahead of this one's; no block returns early.
|
||||
template <int WS>
|
||||
__global__ void r4d_ar_gather_wide_kernel(
|
||||
__device__ __forceinline__ void r4d_ar_gather_wide_body(
|
||||
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
|
||||
const int4* __restrict__ my_base, int4* __restrict__ out4,
|
||||
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs,
|
||||
@@ -156,6 +160,28 @@ __global__ void r4d_ar_gather_wide_kernel(
|
||||
}
|
||||
}
|
||||
}
|
||||
template <int WS>
|
||||
__global__ void r4d_ar_gather_wide_kernel(
|
||||
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
|
||||
const int4* __restrict__ my_base, int4* __restrict__ out4,
|
||||
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs,
|
||||
int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq,
|
||||
int pub, long long* gate, unsigned int* gate_ctr) {
|
||||
r4d_ar_gather_wide_body<WS>(in4, peers, my_base, out4, my_flags, seq_ctrs, n16, slot_stride16,
|
||||
rank, row16, dp16, sp16, drain, acq, pub, gate, gate_ctr);
|
||||
}
|
||||
template <int WS>
|
||||
__global__ void r4dchain_ar_gather_wide(
|
||||
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
|
||||
const int4* __restrict__ my_base, int4* __restrict__ out4,
|
||||
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs,
|
||||
int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq,
|
||||
int pub, long long* gate, unsigned int* gate_ctr) {
|
||||
r4d_chain_wait();
|
||||
r4d_ar_gather_wide_body<WS>(in4, peers, my_base, out4, my_flags, seq_ctrs, n16, slot_stride16,
|
||||
rank, row16, dp16, sp16, drain, acq, pub, gate, gate_ctr);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
// --- host side ---
|
||||
// `row_elems` is the row width in elements, 0 for plain concatenation. The entry point checks it
|
||||
@@ -165,7 +191,8 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla
|
||||
long my_flags, long seq_ctrs, long slot_stride16, long inp,
|
||||
long out, long n_elem, long dtype, long rank, long row_elems,
|
||||
long stream_i, long nblocks, long nthreads, long drain, long acq,
|
||||
long pub, long gate, long gate_ctr, long dpitch, long spitch) {
|
||||
long pub, long gate, long gate_ctr, long dpitch, long spitch,
|
||||
bool chain = false) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound");
|
||||
|
||||
@@ -236,7 +263,7 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla
|
||||
}
|
||||
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
r4d_ar_gather_wide_kernel<WS><<<nb, nt, 0, st>>>(
|
||||
(chain ? r4dchain_ar_gather_wide<WS> : r4d_ar_gather_wide_kernel<WS>)<<<nb, nt, 0, st>>>(
|
||||
(const int4*)inp, peers, (const int4*)my_scratch, (int4*)out, (unsigned int*)my_flags,
|
||||
(unsigned int*)seq_ctrs, n16, (int)slot_stride16, (int)rank, row16, dp16, sp16, (int)drain,
|
||||
(int)acq, (int)pub, (long long*)gate, (unsigned int*)gate_ctr);
|
||||
@@ -262,12 +289,12 @@ void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scrat
|
||||
long my_flags, long seq_ctrs, long slot_stride16, long inp, long out,
|
||||
long n_elem, long dtype, long rank, long row_elems, long stream,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub, long gate,
|
||||
long gate_ctr, long dpitch, long spitch) {
|
||||
long gate_ctr, long dpitch, long spitch, long chain) {
|
||||
const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2};
|
||||
const long pf[3] = {peer_flags0, peer_flags1, peer_flags2};
|
||||
ar_gather_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub,
|
||||
gate, gate_ctr, dpitch, spitch);
|
||||
gate, gate_ctr, dpitch, spitch, chain != 0);
|
||||
}
|
||||
|
||||
void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
#include "r4d.h"
|
||||
#include "r4d_ar_wide.h"
|
||||
#include "r4d_ar_shards.h"
|
||||
#include "r4d_chain.h"
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
@@ -40,13 +41,16 @@ struct R4DArShardOff {
|
||||
};
|
||||
|
||||
// PIECED false fixes pieces at 1, so the unpipelined launch keeps the straight-line kernel.
|
||||
template <typename T, int LANES, int WS, bool PIECED>
|
||||
__global__ void r4d_ar_twoshot_wide_exact_kernel(
|
||||
// CHAIN: the chained form's wait (before the sequence take, so a block of the next launch on the
|
||||
// instance never starts ahead of this one's) and add (r4d_chain.h); no block returns early.
|
||||
template <typename T, int LANES, int WS, bool PIECED, bool CHAIN>
|
||||
__device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body(
|
||||
const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers,
|
||||
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags,
|
||||
int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff<WS> sh,
|
||||
int slot_stride16, int rank, int drain, int acq, int pub,
|
||||
long long* gate, unsigned int* gate_ctr, int pieces_arg) {
|
||||
if (CHAIN) r4d_chain_wait();
|
||||
constexpr int NPEERS = WS - 1;
|
||||
const int pieces = PIECED ? pieces_arg : 1;
|
||||
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
|
||||
@@ -151,8 +155,27 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel(
|
||||
assemble(pieces - 1);
|
||||
#undef R4D_TS_OFF
|
||||
#undef R4D_TS_LEN
|
||||
if (CHAIN) r4d_chain_done();
|
||||
}
|
||||
|
||||
#define R4D_ARTS_PARAMS const int4* __restrict__ in4, R4DArWidePeers<int4, WS - 1> peers, \
|
||||
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \
|
||||
int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff<WS> sh, \
|
||||
int slot_stride16, int rank, int drain, int acq, int pub, long long* gate, \
|
||||
unsigned int* gate_ctr, int pieces_arg
|
||||
#define R4D_ARTS_ARGS in4, peers, my_base, my_flags, out4, seq_ctrs, sh, slot_stride16, rank, \
|
||||
drain, acq, pub, gate, gate_ctr, pieces_arg
|
||||
template <typename T, int LANES, int WS, bool PIECED>
|
||||
__global__ void r4d_ar_twoshot_wide_exact_kernel(R4D_ARTS_PARAMS) {
|
||||
r4d_ar_twoshot_wide_exact_body<T, LANES, WS, PIECED, false>(R4D_ARTS_ARGS);
|
||||
}
|
||||
template <typename T, int LANES, int WS, bool PIECED>
|
||||
__global__ void r4dchain_ar_twoshot_wide_exact(R4D_ARTS_PARAMS) {
|
||||
r4d_ar_twoshot_wide_exact_body<T, LANES, WS, PIECED, true>(R4D_ARTS_ARGS);
|
||||
}
|
||||
#undef R4D_ARTS_ARGS
|
||||
#undef R4D_ARTS_PARAMS
|
||||
|
||||
// --- host side ---
|
||||
template <int WS>
|
||||
static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, long my_scratch,
|
||||
@@ -160,7 +183,7 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags,
|
||||
long out, long n_elem, long dtype, long rank, long stream_i,
|
||||
long nblocks, long nthreads, long drain, long acq, long pub,
|
||||
long gate, long gate_ctr, const int* shard_weights,
|
||||
long pieces) {
|
||||
long pieces, bool chain = false) {
|
||||
constexpr int NPEERS = WS - 1;
|
||||
if (rank < 0 || rank >= WS)
|
||||
throw std::runtime_error("all_reduce: rank " + std::to_string(rank) +
|
||||
@@ -238,7 +261,8 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags,
|
||||
|
||||
hipStream_t st = (hipStream_t)stream_i;
|
||||
#define R4D_AR_TS_LAUNCH_P(T, LN, P) \
|
||||
r4d_ar_twoshot_wide_exact_kernel<T, LN, WS, P><<<nb, nt, 0, st>>>( \
|
||||
(chain ? r4dchain_ar_twoshot_wide_exact<T, LN, WS, P> \
|
||||
: r4d_ar_twoshot_wide_exact_kernel<T, LN, WS, P>)<<<nb, nt, 0, st>>>( \
|
||||
(const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \
|
||||
(int4*)out, (unsigned int*)seq_ctrs, sh, (int)slot_stride16, \
|
||||
(int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, \
|
||||
@@ -274,12 +298,12 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee
|
||||
long my_scratch, long my_flags, long seq_ctrs,
|
||||
long slot_stride16, long inp, long out, long n_elem, long dtype,
|
||||
long rank, long stream, long nblocks, long nthreads, long drain,
|
||||
long acq, long pub, long gate, long gate_ctr) {
|
||||
long acq, long pub, long gate, long gate_ctr, long chain) {
|
||||
const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2};
|
||||
const long pf[3] = {peer_flags0, peer_flags1, peer_flags2};
|
||||
ar_twoshot_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem,
|
||||
dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr,
|
||||
nullptr, 1L);
|
||||
nullptr, 1L, chain != 0);
|
||||
}
|
||||
|
||||
void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2,
|
||||
|
||||
@@ -362,6 +362,8 @@ int r4d_cfg_ar_tail(const RadArgs*);
|
||||
/* The four-rank exact one-shot's size, in elements, from which it takes the exact two-shot instead
|
||||
* (0: never); the all-reduce rows' `ts_min` axis. */
|
||||
long r4d_cfg_ar_ts_min(const RadArgs*);
|
||||
/* The prefetch's workgroup count (the row's `nb` axis). */
|
||||
int r4d_cfg_prefetch_nb(const RadArgs*);
|
||||
void r4d_cfg_topk (const RadArgs*, struct R4dTopkCfg*);
|
||||
void r4d_cfg_mv (const RadArgs*, struct R4dMvCfg*);
|
||||
/* rmsnorm_quant_i8's decode form: 1 the row's operands in registers before the reductions, 0 the
|
||||
|
||||
@@ -154,6 +154,7 @@ static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_d
|
||||
|
||||
/* Set by the caller from the tuned `splits`; 0 means libr4d's own split law. */
|
||||
r->splits = 0;
|
||||
r->chain = r4d_geti_or(a, "chain", 0) != 0 ? 1 : 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_dt16.h"
|
||||
#include "r4d_q8.h" // the gate quantiser's 8-bit codes: E4M3, or int8 (GQ == 2)
|
||||
#include "r4d_chain.h"
|
||||
#include <algorithm>
|
||||
#include <type_traits>
|
||||
|
||||
@@ -80,10 +81,12 @@ __host__ __device__ __forceinline__ int r4d_attn_used(int ctx, int tile, int spl
|
||||
|
||||
// WIN enables a sliding window (a.window positions ending at each row's causal limit). As a
|
||||
// template parameter defaulting to 0, full attention compiles with no window code.
|
||||
// The body: its blocks return early (empty slots, tiles past the window), so the chained form
|
||||
// (r4d_chain.h) wraps it below rather than bracketing it in place.
|
||||
template<int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT,
|
||||
int WIN = 0>
|
||||
__global__ __launch_bounds__(NWARPS * 32)
|
||||
void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
__device__ __forceinline__
|
||||
void r4d_attn_decode_body(const R4DArgs& a, int splits)
|
||||
{
|
||||
constexpr int F16 = (OPT & O_F16) ? 1 : 0;
|
||||
constexpr int MSKIP = (OPT & O_MSKIP) ? 1 : 0;
|
||||
@@ -598,6 +601,24 @@ __device__ __forceinline__ uint16_t r4d_gq_gate(uint16_t gb, uint16_t xb) {
|
||||
}
|
||||
__device__ __forceinline__ float r4d_gq_clamp(float v) { return fminf(fmaxf(v, -448.0f), 448.0f); }
|
||||
|
||||
// The plain decode kernel, and the chained one (r4dchain*, r4d_chain.h) over the same body.
|
||||
template<int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT,
|
||||
int WIN = 0>
|
||||
__global__ __launch_bounds__(NWARPS * 32)
|
||||
void r4d_attn_decode_kernel(const R4DArgs a, int splits)
|
||||
{
|
||||
r4d_attn_decode_body<NWARPS, TILE, HEAD_DIM, GQA, BS, KVP, OPT, WIN>(a, splits);
|
||||
}
|
||||
template<int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT,
|
||||
int WIN = 0>
|
||||
__global__ __launch_bounds__(NWARPS * 32)
|
||||
void r4dchain_attn_decode(const R4DArgs a, int splits)
|
||||
{
|
||||
r4d_chain_wait();
|
||||
r4d_attn_decode_body<NWARPS, TILE, HEAD_DIM, GQA, BS, KVP, OPT, WIN>(a, splits);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
// Vectorised merge, used by the h256 launcher whenever the split count fits a wave. Bit-identical
|
||||
// to splitkv_combine_body below; only the thread map differs. One wave owns one output row and
|
||||
// each lane HEAD_DIM/32 dims, so a segment is one 16-byte load per lane; a block carries JPB rows.
|
||||
@@ -767,6 +788,15 @@ void r4d_attn_splitkv_combine_vec_kernel(const R4DArgs a, int splits, int tile)
|
||||
splitkv_combine_vec_body<HEAD_DIM, CHAINS, PF16, JPB, WIN, 0>(a, splits, tile,
|
||||
R4DGateQuant{});
|
||||
}
|
||||
template<int HEAD_DIM, int CHAINS, int PF16, int JPB, int WIN = 0>
|
||||
__global__ __launch_bounds__(32 * JPB)
|
||||
void r4dchain_attn_splitkv_combine_vec(const R4DArgs a, int splits, int tile)
|
||||
{
|
||||
r4d_chain_wait();
|
||||
splitkv_combine_vec_body<HEAD_DIM, CHAINS, PF16, JPB, WIN, 0>(a, splits, tile,
|
||||
R4DGateQuant{});
|
||||
r4d_chain_done();
|
||||
}
|
||||
template<int HEAD_DIM, int CHAINS, int PF16, int JPB, int WIN = 0, int GQ = 1>
|
||||
__global__ __launch_bounds__(32 * JPB)
|
||||
void r4d_attn_splitkv_combine_vec_gq_kernel(const R4DArgs a, int splits, int tile,
|
||||
@@ -901,6 +931,14 @@ void r4d_attn_splitkv_combine_kernel(const R4DArgs a, int splits, int tile)
|
||||
{
|
||||
splitkv_combine_body<HEAD_DIM, CHAINS, PF16, WIN, 0>(a, splits, tile, R4DGateQuant{});
|
||||
}
|
||||
template<int HEAD_DIM, int CHAINS, int PF16, int WIN = 0>
|
||||
__global__ __launch_bounds__(HEAD_DIM)
|
||||
void r4dchain_attn_splitkv_combine(const R4DArgs a, int splits, int tile)
|
||||
{
|
||||
r4d_chain_wait();
|
||||
splitkv_combine_body<HEAD_DIM, CHAINS, PF16, WIN, 0>(a, splits, tile, R4DGateQuant{});
|
||||
r4d_chain_done();
|
||||
}
|
||||
template<int HEAD_DIM, int CHAINS, int PF16, int WIN = 0, int GQ = 1>
|
||||
__global__ __launch_bounds__(HEAD_DIM)
|
||||
void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile,
|
||||
@@ -978,9 +1016,13 @@ static int r4d_decode_launch_win(const R4DArgs* a, hipStream_t s) {
|
||||
if (rows > 64) return -4;
|
||||
const int nw = (rows + 15) / 16;
|
||||
const int splits = r4d_decode_splits_win(a, TILE);
|
||||
#define R4D_WIN_LAUNCH(NW) \
|
||||
#define R4D_WIN_LAUNCH(NW) do { if (a->chain) \
|
||||
hipLaunchKernelGGL((r4dchain_attn_decode<NW, TILE, HEAD_DIM, GQA, BS, KVP, OPT, 1>), \
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits); \
|
||||
else \
|
||||
hipLaunchKernelGGL((r4d_attn_decode_kernel<NW, TILE, HEAD_DIM, GQA, BS, KVP, OPT, 1>), \
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits)
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits); \
|
||||
} while (0)
|
||||
if (nw == 1) R4D_WIN_LAUNCH(1);
|
||||
else if (nw == 2) R4D_WIN_LAUNCH(2);
|
||||
else if (nw == 3) R4D_WIN_LAUNCH(3);
|
||||
@@ -990,9 +1032,15 @@ static int r4d_decode_launch_win(const R4DArgs* a, hipStream_t s) {
|
||||
if (e != hipSuccess) return -100 - (int)e;
|
||||
|
||||
const int jobs3 = r4d_q_total(*a) * a->q_heads;
|
||||
if (splits <= 64 && jobs3 >= VECMIN)
|
||||
if (splits <= 64 && jobs3 >= VECMIN && a->chain)
|
||||
hipLaunchKernelGGL((r4dchain_attn_splitkv_combine_vec<HEAD_DIM, 4, PF16, JPB, 1>),
|
||||
dim3((jobs3 + JPB - 1) / JPB), dim3(32 * JPB), 0, s, *a, splits, TILE);
|
||||
else if (splits <= 64 && jobs3 >= VECMIN)
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel<HEAD_DIM, 4, PF16, JPB, 1>),
|
||||
dim3((jobs3 + JPB - 1) / JPB), dim3(32 * JPB), 0, s, *a, splits, TILE);
|
||||
else if (a->chain)
|
||||
hipLaunchKernelGGL((r4dchain_attn_splitkv_combine<HEAD_DIM, 4, PF16, 1>), dim3(jobs3),
|
||||
dim3(HEAD_DIM), splits * sizeof(float), s, *a, splits, TILE);
|
||||
else
|
||||
hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel<HEAD_DIM, 4, PF16, 1>), dim3(jobs3),
|
||||
dim3(HEAD_DIM), splits * sizeof(float), s, *a, splits, TILE);
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
|
||||
#include "r4d_plugin.h"
|
||||
#include "r4d_launch.h"
|
||||
#include "r4d_chain.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#if defined(__HIP_DEVICE_COMPILE__) && defined(__AMDGCN_WAVEFRONT_SIZE) && __AMDGCN_WAVEFRONT_SIZE != 32
|
||||
@@ -232,8 +233,10 @@ __device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int*
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the attention kernel */
|
||||
/* The body; attn_kernel and its chained form r4dchain_attn_window (r4d_chain.h) wrap it below,
|
||||
* since its blocks return early. */
|
||||
template <int HD, int GQA, bool KV8>
|
||||
__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) {
|
||||
__device__ __forceinline__ void attn_body(AttnArgs A) {
|
||||
constexpr int R = Geo<HD>::R, BK = Geo<HD>::BK, RW = R / kWaves, BQ = R / GQA;
|
||||
constexpr int NC = HD / 128; /* 4-element chunks a lane holds of a row */
|
||||
constexpr int ESZ = KV8 ? 1 : 2;
|
||||
@@ -830,7 +833,7 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) {
|
||||
* (kMaxSplit is 64), so the row max and denominator are one wave reduction each. Then one sweep
|
||||
* over the splits that saw a key, four at a time, each lane accumulating its 4 * NC dims. */
|
||||
template <int HD, int GQA>
|
||||
__global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) {
|
||||
__device__ __forceinline__ void merge_body(AttnArgs A) {
|
||||
constexpr int R = Geo<HD>::R, NC = HD / 128;
|
||||
static_assert(kMaxSplit <= 64, "two splits a lane");
|
||||
const int tile = (int)blockIdx.x, kh = (int)blockIdx.y;
|
||||
@@ -964,6 +967,25 @@ static constexpr int64_t scratch_need() {
|
||||
return part_bytes<HD>() + (int64_t)kTinfoMax * 2 * (int64_t)sizeof(int);
|
||||
}
|
||||
|
||||
/* The plain kernels and their chained forms (r4dchain*, RadKernelChainFn): the chained ones wait
|
||||
* for the kernels before them on the queue in their prologue and count themselves in at the end. */
|
||||
template <int HD, int GQA, bool KV8>
|
||||
__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { attn_body<HD, GQA, KV8>(A); }
|
||||
template <int HD, int GQA, bool KV8>
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_attn_window(AttnArgs A) {
|
||||
r4d_chain_wait();
|
||||
attn_body<HD, GQA, KV8>(A);
|
||||
r4d_chain_done();
|
||||
}
|
||||
template <int HD, int GQA>
|
||||
__global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { merge_body<HD, GQA>(A); }
|
||||
template <int HD, int GQA>
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_merge_window(AttnArgs A) {
|
||||
r4d_chain_wait();
|
||||
merge_body<HD, GQA>(A);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
template <int HD, int GQA, bool KV8>
|
||||
static int launch_attn(const RadArgs* a, RadStream stream) {
|
||||
constexpr int R = Geo<HD>::R, BK = Geo<HD>::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2;
|
||||
@@ -1134,11 +1156,23 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
|
||||
A.n_split = (int)ns;
|
||||
|
||||
hipStream_t s = (hipStream_t)stream;
|
||||
R4D_KLAUNCH(R4D_KNAME(attn_kernel<HD, GQA, KV8>), dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns),
|
||||
dim3(kThreads), s, A);
|
||||
if (ns > 1)
|
||||
R4D_KLAUNCH(R4D_KNAME(merge_kernel<HD, GQA>), dim3((unsigned)nt, (unsigned)kvh), dim3(kThreads),
|
||||
s, A);
|
||||
/* The chained forms where the row resolved with `chain` (a chainable row, RADIANCE_CHAIN), at
|
||||
* decode heights only: the 31B's full layers at a verify. */
|
||||
const bool chain = rad_args_geti_or(a, "chain", 0) != 0 && rows <= 64;
|
||||
if (chain)
|
||||
R4D_KLAUNCH(R4D_KNAME(r4dchain_attn_window<HD, GQA, KV8>),
|
||||
dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), dim3(kThreads), s, A);
|
||||
else
|
||||
R4D_KLAUNCH(R4D_KNAME(attn_kernel<HD, GQA, KV8>),
|
||||
dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), dim3(kThreads), s, A);
|
||||
if (ns > 1) {
|
||||
if (chain)
|
||||
R4D_KLAUNCH(R4D_KNAME(r4dchain_merge_window<HD, GQA>), dim3((unsigned)nt, (unsigned)kvh),
|
||||
dim3(kThreads), s, A);
|
||||
else
|
||||
R4D_KLAUNCH(R4D_KNAME(merge_kernel<HD, GQA>), dim3((unsigned)nt, (unsigned)kvh),
|
||||
dim3(kThreads), s, A);
|
||||
}
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// r4d_chain.h -- a chained launch's wait and completion (RadKernelChainFn, abi/rad_abi.h).
|
||||
//
|
||||
// Between two dependent kernels on one queue the packet processor waits for the first to finish
|
||||
// before it launches the second (the AQL barrier bit): ~1.3 ms of a 14 ms DFlash2 step on the 31B
|
||||
// (4x R9700, 2026-10-17). A chained launch drops the bit. The engine writes a record into the
|
||||
// kernel's argument slot, and the kernel waits for its queue's completion counter to reach the
|
||||
// blocks issued before it, then adds its own blocks as they finish. A kernel's chained form
|
||||
// (`CHAIN` true) brackets its body with r4d_chain_wait / r4d_chain_done; the plain form never reads
|
||||
// the record, so a launch from outside the engine (r4d_selftest, rad-kbench) is untouched.
|
||||
//
|
||||
// Every block must reach r4d_chain_done exactly once, so a kernel whose blocks return early keeps
|
||||
// its body in a __device__ function called from the chained wrapper.
|
||||
#pragma once
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "rad_abi.h"
|
||||
|
||||
#if !defined(__HIP__)
|
||||
/* The host SIMT emulator (tests/r4d_emu) compiles some of these sources as C++: no engine record
|
||||
* ever reaches a launch there, so a chained form is its plain form. */
|
||||
__device__ __forceinline__ void r4d_chain_wait() {}
|
||||
__device__ __forceinline__ void r4d_chain_done() {}
|
||||
#else
|
||||
|
||||
struct R4dChainRec {
|
||||
unsigned long long magic, target;
|
||||
unsigned long long* ctr;
|
||||
unsigned long long check;
|
||||
};
|
||||
|
||||
// The record, or null where it is not the engine's. Read from the argument segment (scalar loads)
|
||||
// at both ends of the kernel, so nothing is held across the body: a register-heavy body (the
|
||||
// split-KV decode attention) would otherwise pay for the pointer.
|
||||
__device__ __forceinline__ const R4dChainRec* r4d_chain_rec() {
|
||||
const R4dChainRec* r = (const R4dChainRec*)((const char*)__builtin_amdgcn_kernarg_segment_ptr() +
|
||||
RAD_CHAIN_KARG_OFF);
|
||||
const unsigned long long magic = r->magic, target = r->target, check = r->check;
|
||||
const unsigned long long* ctr = r->ctr;
|
||||
if (magic != RAD_CHAIN_MAGIC ||
|
||||
check != (magic ^ target ^ (unsigned long long)(uintptr_t)ctr ^ RAD_CHAIN_CHECK))
|
||||
return nullptr;
|
||||
return r;
|
||||
}
|
||||
|
||||
// Before the first read of an operand: one lane waits for the counter to reach the target.
|
||||
// Every resident block polls the same word, so a wide kernel launched behind a long one (a GEMM
|
||||
// behind a junction's all-reduce) would put hundreds of loads into one L2 channel every few dozen
|
||||
// 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.
|
||||
#ifndef R4D_CHAIN_FAST
|
||||
#define R4D_CHAIN_FAST 8
|
||||
#endif
|
||||
#ifndef R4D_CHAIN_SLOW
|
||||
#define R4D_CHAIN_SLOW 16
|
||||
#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;
|
||||
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 {
|
||||
__builtin_amdgcn_s_sleep(R4D_CHAIN_SLOW);
|
||||
}
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
|
||||
}
|
||||
|
||||
// After the block's last write: release, then one add a block.
|
||||
__device__ __forceinline__ void r4d_chain_done() {
|
||||
const R4dChainRec* r = r4d_chain_rec();
|
||||
if (!r) return;
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0)
|
||||
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
|
||||
}
|
||||
#endif /* __HIP__ */
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d_gdn_args.h"
|
||||
#include "r4d_dflash_conv_body.h"
|
||||
#include "r4d_chain.h"
|
||||
|
||||
#define DFC_THREADS 128
|
||||
#define DFC_VEC 8 // bf16 lanes per thread: one dwordx4 in and one out
|
||||
@@ -19,15 +20,40 @@ __global__ __launch_bounds__(DFC_THREADS) void r4d_dflash_conv_kernel(
|
||||
blockmask, blockIdx.y, hv);
|
||||
}
|
||||
|
||||
// The chained form (r4d_chain.h): the body returns for lanes past the row, the block still adds.
|
||||
template <int TAPS, int GROUP>
|
||||
__global__ __launch_bounds__(DFC_THREADS) void r4dchain_dflash_conv(
|
||||
const r4d_u16* __restrict__ x, const r4d_u16* __restrict__ delta,
|
||||
const r4d_u16* __restrict__ base, r4d_u16* __restrict__ out,
|
||||
int H, int dpitch, int NG, int vpr, int blockmask)
|
||||
{
|
||||
r4d_chain_wait();
|
||||
const int hv = blockIdx.x * DFC_THREADS + threadIdx.x;
|
||||
r4d_dflash_conv_body<TAPS, GROUP>(x, delta, base, out, H, dpitch, NG, vpr,
|
||||
blockmask, blockIdx.y, hv);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
// x [T, H] bf16, row pitch H
|
||||
// delta [T, taps, NG] bf16, row pitch dpitch: a slice of the [T, 2, taps, NG] kernel projection,
|
||||
// so dpitch is 2*taps*NG. The packed pitch (taps*NG) would silently read the
|
||||
// other half's coefficients.
|
||||
// base [taps, H] bf16, contiguous
|
||||
// out [T, H] bf16. Must not alias x: tap 1 of row t reads input row t-1.
|
||||
static int dflash_conv_launch(const void* x, const void* delta, const void* base, void* out,
|
||||
int T, int H, int dpitch, int NG, int taps, int group,
|
||||
int block_size, void* stream, bool chain);
|
||||
extern "C" int r4d_dflash_conv_t2_g16_bf16(
|
||||
const void* x, const void* delta, const void* base, void* out,
|
||||
int T, int H, int dpitch, int NG, int taps, int group, int block_size, void* stream)
|
||||
{
|
||||
return dflash_conv_launch(x, delta, base, out, T, H, dpitch, NG, taps, group, block_size,
|
||||
stream, false);
|
||||
}
|
||||
/* `chain`: the chained form at decode heights (r4d_rad_dflash_conv passes the row's parameter). */
|
||||
static int dflash_conv_launch(const void* x, const void* delta, const void* base, void* out,
|
||||
int T, int H, int dpitch, int NG, int taps, int group,
|
||||
int block_size, void* stream, bool chain)
|
||||
{
|
||||
if (taps != 2 || group != 16) return -1;
|
||||
if (H % (group * DFC_VEC) || NG != H / group) return -1;
|
||||
@@ -36,7 +62,9 @@ extern "C" int r4d_dflash_conv_t2_g16_bf16(
|
||||
|
||||
const int vpr = H / DFC_VEC;
|
||||
dim3 grid((vpr + DFC_THREADS - 1) / DFC_THREADS, T), blk(DFC_THREADS);
|
||||
hipLaunchKernelGGL((r4d_dflash_conv_kernel<2, 16>), grid, blk, 0, (hipStream_t)stream,
|
||||
hipLaunchKernelGGL((chain && T <= 64 ? r4dchain_dflash_conv<2, 16>
|
||||
: r4d_dflash_conv_kernel<2, 16>),
|
||||
grid, blk, 0, (hipStream_t)stream,
|
||||
(const r4d_u16*)x, (const r4d_u16*)delta, (const r4d_u16*)base,
|
||||
(r4d_u16*)out, H, dpitch, NG, vpr, block_size - 1);
|
||||
return (int)hipGetLastError();
|
||||
@@ -79,7 +107,8 @@ extern "C" int r4d_rad_dflash_conv(const RadArgs* a, RadStream s) {
|
||||
if (bsz & (bsz - 1)) return R4D_NO(RAD_E_INVAL);
|
||||
if (dpitch != 2LL * taps * NG) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
return R4D_RAW(r4d_dflash_conv_t2_g16_bf16(x->data, d->data, bs->data, o->data, (int)T,
|
||||
(int)H, (int)dpitch, NG, taps, group, bsz, s));
|
||||
return R4D_RAW(dflash_conv_launch(x->data, d->data, bs->data, o->data, (int)T,
|
||||
(int)H, (int)dpitch, NG, taps, group, bsz, s,
|
||||
r4d_geti_or(a, "chain", 0) != 0));
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
#include "r4d_gdn_args.h"
|
||||
#include "r4d_dflash_conv_body.h" // r4d_bf2f, r4d_u16
|
||||
#include "r4d_common.h" // r4d_wave_sum
|
||||
#include "r4d_chain.h"
|
||||
|
||||
#define DSL_THREADS 256
|
||||
#define DSL_WAVE 32
|
||||
@@ -47,7 +48,8 @@
|
||||
// Ids outside [0, V) do occur (row_topk_merge reports an unfilled slot as -1, and step 0's
|
||||
// predecessor is whatever the anchor plane holds). As in ref_dflash_select, an out-of-range
|
||||
// predecessor contributes nothing and an out-of-range candidate scores its unary term alone.
|
||||
__global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
|
||||
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
|
||||
__device__ __forceinline__ void r4d_dflash_select_body(
|
||||
const int* __restrict__ cand, const float* __restrict__ unary,
|
||||
const r4d_u16* __restrict__ hp, const int* __restrict__ anchor,
|
||||
const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ,
|
||||
@@ -134,12 +136,49 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
__global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
|
||||
const int* __restrict__ cand, const float* __restrict__ unary,
|
||||
const r4d_u16* __restrict__ hp, const int* __restrict__ anchor,
|
||||
const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ,
|
||||
int* __restrict__ out, int steps, int K, int R, int V,
|
||||
int cand_ld, int hp_ld, int out_ld, int anchor_stride) {
|
||||
r4d_dflash_select_body(cand, unary, hp, anchor, pred, succ, out, steps, K, R, V, cand_ld, hp_ld,
|
||||
out_ld, anchor_stride);
|
||||
}
|
||||
__global__ __launch_bounds__(DSL_THREADS) void r4dchain_dflash_select(
|
||||
const int* __restrict__ cand, const float* __restrict__ unary,
|
||||
const r4d_u16* __restrict__ hp, const int* __restrict__ anchor,
|
||||
const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ,
|
||||
int* __restrict__ out, int steps, int K, int R, int V,
|
||||
int cand_ld, int hp_ld, int out_ld, int anchor_stride) {
|
||||
r4d_chain_wait();
|
||||
r4d_dflash_select_body(cand, unary, hp, anchor, pred, succ, out, steps, K, R, V, cand_ld, hp_ld,
|
||||
out_ld, anchor_stride);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
/* `chain`: the chained form (the plugin entry, where the row resolved with `chain`). */
|
||||
static int dflash_select_emit(
|
||||
const void* cand, const void* unary, const void* hp, const void* anchor,
|
||||
const void* pred, const void* succ, void* out,
|
||||
int M, int steps, int K, int R, int V, int cand_ld, int hp_ld, int out_ld,
|
||||
int anchor_stride, void* stream, bool chain);
|
||||
|
||||
extern "C" int r4d_dflash_select_bf16(
|
||||
const void* cand, const void* unary, const void* hp, const void* anchor,
|
||||
const void* pred, const void* succ, void* out,
|
||||
int M, int steps, int K, int R, int V, int cand_ld, int hp_ld, int out_ld,
|
||||
int anchor_stride, void* stream)
|
||||
{
|
||||
return dflash_select_emit(cand, unary, hp, anchor, pred, succ, out, M, steps, K, R, V, cand_ld,
|
||||
hp_ld, out_ld, anchor_stride, stream, false);
|
||||
}
|
||||
|
||||
static int dflash_select_emit(
|
||||
const void* cand, const void* unary, const void* hp, const void* anchor,
|
||||
const void* pred, const void* succ, void* out,
|
||||
int M, int steps, int K, int R, int V, int cand_ld, int hp_ld, int out_ld,
|
||||
int anchor_stride, void* stream, bool chain)
|
||||
{
|
||||
if (M <= 0 || steps <= 0) return 0;
|
||||
if (K < 1 || K > DSL_MAX_K) return -1;
|
||||
@@ -149,7 +188,8 @@ extern "C" int r4d_dflash_select_bf16(
|
||||
/* hp may be null (the bigram form); then hp_ld is unused. */
|
||||
if (hp && hp_ld < R) return -1;
|
||||
|
||||
hipLaunchKernelGGL(r4d_dflash_select_kernel, dim3(M), dim3(DSL_THREADS), 0, (hipStream_t)stream,
|
||||
hipLaunchKernelGGL((chain ? r4dchain_dflash_select : r4d_dflash_select_kernel), dim3(M),
|
||||
dim3(DSL_THREADS), 0, (hipStream_t)stream,
|
||||
(const int*)cand, (const float*)unary, (const r4d_u16*)hp,
|
||||
(const int*)anchor, (const r4d_u16*)pred, (const r4d_u16*)succ,
|
||||
(int*)out, steps, K, R, V, cand_ld, hp_ld, out_ld, anchor_stride);
|
||||
@@ -222,8 +262,10 @@ extern "C" int r4d_rad_dflash_select(const RadArgs* a, RadStream s) {
|
||||
if (astr < 1 || !r4d_contig(anc)) return R4D_NO(RAD_E_SHAPE);
|
||||
if (r4d_numel(anc) < (M - 1) * astr + 1) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
return R4D_RAW(r4d_dflash_select_bf16(cand->data, un->data, has_hp ? hp->data : nullptr,
|
||||
anc->data, pr->data, sc->data,
|
||||
out->data, (int)M, (int)steps, (int)K, (int)R, (int)V,
|
||||
(int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr, s));
|
||||
/* The chained form at decode heights, where the row resolved with `chain`. */
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return R4D_RAW(dflash_select_emit(cand->data, un->data, has_hp ? hp->data : nullptr,
|
||||
anc->data, pr->data, sc->data,
|
||||
out->data, (int)M, (int)steps, (int)K, (int)R, (int)V,
|
||||
(int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr, s, ch));
|
||||
}
|
||||
@@ -9,14 +9,18 @@
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_chain.h"
|
||||
#include <cstdint>
|
||||
|
||||
namespace {
|
||||
|
||||
template <uint32_t THR>
|
||||
__global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
|
||||
// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); every block runs
|
||||
// to the end. The plain kernel and the chained one (r4dchain*) follow.
|
||||
template <uint32_t THR, bool CHAIN>
|
||||
__device__ __forceinline__ void gelu_mul_quant_i8_body(
|
||||
const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S,
|
||||
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
|
||||
if (CHAIN) r4d_chain_wait();
|
||||
extern __shared__ uint16_t ybuf[];
|
||||
__shared__ float lm[THR / 32];
|
||||
const uint32_t row = blockIdx.x;
|
||||
@@ -49,6 +53,20 @@ __global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
|
||||
const int t = __float2int_rn(bf16_to_f32(ybuf[src]) * inv);
|
||||
qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
|
||||
}
|
||||
if (CHAIN) r4d_chain_done();
|
||||
}
|
||||
|
||||
template <uint32_t THR>
|
||||
__global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
|
||||
const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S,
|
||||
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
|
||||
gelu_mul_quant_i8_body<THR, false>(gu, q, S, yo, n, gu_ld, y_ld);
|
||||
}
|
||||
template <uint32_t THR>
|
||||
__global__ __launch_bounds__(THR) void r4dchain_gelu_mul_quant_i8(
|
||||
const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S,
|
||||
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
|
||||
gelu_mul_quant_i8_body<THR, true>(gu, q, S, yo, n, gu_ld, y_ld);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -79,13 +97,17 @@ extern "C" int r4d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream) {
|
||||
const size_t lds = (size_t)n * sizeof(uint16_t);
|
||||
if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE);
|
||||
const int thr = r4d_act_threads((int)M, (int)n);
|
||||
#define R4D_GMQ_T(T) emit_rc = R4D_EMIT(stream, (gelu_mul_quant_i8_kernel<T>), dim3((uint32_t)M), dim3(T), lds, \
|
||||
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; /* RadKernelChainFn, decode */
|
||||
#define R4D_GMQ_C(T, C) R4D_EMIT(stream, (C ? r4dchain_gelu_mul_quant_i8<T> : gelu_mul_quant_i8_kernel<T>), \
|
||||
dim3((uint32_t)M), dim3(T), lds, \
|
||||
(const uint16_t*)r4d_p(gu), (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), \
|
||||
(uint32_t)n, (uint32_t)gp, (uint32_t)yp)
|
||||
#define R4D_GMQ_T(T) emit_rc = chain ? R4D_GMQ_C(T, true) : R4D_GMQ_C(T, false)
|
||||
if (thr == 1024) R4D_GMQ_T(1024);
|
||||
else if (thr == 512) R4D_GMQ_T(512);
|
||||
else if (thr == 256) R4D_GMQ_T(256);
|
||||
else return R4D_NO(RAD_E_INVAL);
|
||||
#undef R4D_GMQ_T
|
||||
#undef R4D_GMQ_C
|
||||
return emit_rc;
|
||||
}
|
||||
@@ -19,6 +19,7 @@
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
#include "r4d_chain.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
@@ -48,10 +49,13 @@ __device__ __forceinline__ v8bf fragU(r4d_gu2 p, int u) {
|
||||
// More amortises each weight fragment, fewer puts more blocks on the machine, so MT is tunable.
|
||||
// KU is the k-step unroll; see the loop.
|
||||
constexpr int KU = 8;
|
||||
template <int MT>
|
||||
__global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel(
|
||||
// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); no block returns
|
||||
// early. r4d_gemm_bf16_nt_m64_kernel and r4dchain_gemm_bf16_nt_m64 below wrap it.
|
||||
template <int MT, bool CHAIN>
|
||||
__device__ __forceinline__ void r4d_gemm_bf16_nt_m64_body(
|
||||
const unsigned short* __restrict__ A, const unsigned short* __restrict__ W,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
if (CHAIN) r4d_chain_wait();
|
||||
extern __shared__ float red[]; // WV*SK*256 floats: one 16x16 tile per (column, split)
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
@@ -124,12 +128,33 @@ __global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel(
|
||||
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)v;
|
||||
}
|
||||
}
|
||||
if (CHAIN) r4d_chain_done();
|
||||
}
|
||||
|
||||
template <int MT>
|
||||
__global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned short* __restrict__ W,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
r4d_gemm_bf16_nt_m64_body<MT, false>(A, W, C, M, K, N, WV, SK);
|
||||
}
|
||||
template <int MT>
|
||||
__global__ __launch_bounds__(1024) void r4dchain_gemm_bf16_nt_m64(
|
||||
const unsigned short* __restrict__ A, const unsigned short* __restrict__ W,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
r4d_gemm_bf16_nt_m64_body<MT, true>(A, W, C, M, K, N, WV, SK);
|
||||
}
|
||||
|
||||
// grid = ceil(ceil(N/16)/WV) x ceil(ceil(M/16)/MB) blocks; block = WV*SK waves. MT = MB is
|
||||
// compile-time so the accumulators are sized exactly.
|
||||
static void gemm_bf16_m64_launch(long a, long w, long c, int M, int K, int N, int WV, int SK,
|
||||
int MB, long stream, bool chain);
|
||||
void r4d_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, int SK, int MB,
|
||||
long stream) {
|
||||
gemm_bf16_m64_launch(a, w, c, M, K, N, WV, SK, MB, stream, false);
|
||||
}
|
||||
/* `chain`: the chained form (r4d_rad_gemm_bf16_m64 passes the row's parameter; M <= 64 always). */
|
||||
static void gemm_bf16_m64_launch(long a, long w, long c, int M, int K, int N, int WV, int SK,
|
||||
int MB, long stream, bool chain) {
|
||||
if (M < 1 || M > R4D_GEMM64_MAX_M) throw std::runtime_error("r4d gemm_bf16_nt_m64: M out of range");
|
||||
if (K % (SK * 16)) throw std::runtime_error("r4d gemm_bf16_nt_m64: K must be divisible by SK*16");
|
||||
if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_bf16_nt_m64: threads/block > 1024");
|
||||
@@ -140,8 +165,9 @@ void r4d_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, i
|
||||
auto Ap = (const unsigned short*)a; auto Wp = (const unsigned short*)w;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(MT) hipLaunchKernelGGL(r4d_gemm_bf16_nt_m64_kernel<MT>, grid, block, smem, st, \
|
||||
Ap, Wp, Cp, M, K, N, WV, SK)
|
||||
#define LAUNCH(MT) hipLaunchKernelGGL((chain ? r4dchain_gemm_bf16_nt_m64<MT> \
|
||||
: r4d_gemm_bf16_nt_m64_kernel<MT>), \
|
||||
grid, block, smem, st, Ap, Wp, Cp, M, K, N, WV, SK)
|
||||
switch (MB) {
|
||||
case 1: LAUNCH(1); break;
|
||||
case 2: LAUNCH(2); break;
|
||||
@@ -166,9 +192,9 @@ extern "C" int r4d_rad_gemm_bf16_m64(const RadArgs* a, RadStream s) {
|
||||
rc = cfg_for(a, g.K, g.M, 16, BR_FLAT, &c, (g.N + 15) / 16); /* "K divisible by SK*16" */
|
||||
if (rc != RAD_OK) return rc;
|
||||
R4D_TRY("gemm_bf16_nt_m64",
|
||||
r4d_gemm_bf16_nt_m64(r4d_addr(g.a), r4d_addr(g.b), r4d_addr(g.y),
|
||||
gemm_bf16_m64_launch(r4d_addr(g.a), r4d_addr(g.b), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb,
|
||||
(long)(uintptr_t)s));
|
||||
(long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_fp8_lm.h"
|
||||
#include "r4d_fp8_wmma.h"
|
||||
#include "r4d_chain.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
@@ -479,8 +480,9 @@ constexpr uint32_t lm_waves(uint32_t mt, uint32_t fkb) {
|
||||
return fkb == 2u ? 6u : mt >= 4u ? 6u : mt == 3u ? 7u : mt == 2u ? 9u : 12u;
|
||||
}
|
||||
|
||||
template <uint32_t MT, uint32_t FKB, bool I8 = false>
|
||||
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel(
|
||||
// The body; lm_wmma_kernel and its chained form (RadKernelChainFn) wrap it.
|
||||
template <uint32_t MT, uint32_t FKB, bool I8>
|
||||
__device__ __forceinline__ void lm_wmma_body(
|
||||
const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, uint32_t a_ld,
|
||||
float* __restrict__ C, uint32_t c_ld,
|
||||
uint32_t rows, uint32_t cols, uint32_t w_ld, uint32_t m_real) {
|
||||
@@ -597,6 +599,23 @@ __global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#define R4D_LMW_PARAMS const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, \
|
||||
uint32_t a_ld, float* __restrict__ C, uint32_t c_ld, uint32_t rows, uint32_t cols, \
|
||||
uint32_t w_ld, uint32_t m_real
|
||||
template <uint32_t MT, uint32_t FKB, bool I8 = false>
|
||||
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel(
|
||||
R4D_LMW_PARAMS) {
|
||||
lm_wmma_body<MT, FKB, I8>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
|
||||
}
|
||||
template <uint32_t MT, uint32_t FKB, bool I8 = false>
|
||||
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void r4dchain_lm_wmma(
|
||||
R4D_LMW_PARAMS) {
|
||||
r4d_chain_wait();
|
||||
lm_wmma_body<MT, FKB, I8>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
|
||||
r4d_chain_done();
|
||||
}
|
||||
#undef R4D_LMW_PARAMS
|
||||
} // namespace
|
||||
|
||||
extern "C" int r4d_gemm_fp8a16_nt_m1_block(void) { return (int)kBlock; }
|
||||
@@ -677,7 +696,7 @@ extern "C" int r4d_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c,
|
||||
// core/build/rad_builder.cpp refuses such a split at declare time.
|
||||
template <bool I8>
|
||||
static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld,
|
||||
int w_ld, long stream);
|
||||
int w_ld, long stream, bool chain = false);
|
||||
|
||||
extern "C" int r4d_logits_gemm_fp8(long a, long wq, long c, int M, int K, int N,
|
||||
int a_ld, int c_ld, int w_ld, long stream) {
|
||||
@@ -691,9 +710,11 @@ extern "C" int r4d_logits_gemm_i8(long a, long wq, long c, int M, int K, int N,
|
||||
return logits_gemm_8<true>(a, wq, c, M, K, N, a_ld, c_ld, w_ld, stream);
|
||||
}
|
||||
|
||||
/* `chain`: the WMMA pass's chained form (the plugin entry, where the row resolved with `chain`);
|
||||
* the matvec below three rows stays plain. */
|
||||
template <bool I8>
|
||||
static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld,
|
||||
int w_ld, long stream) {
|
||||
int w_ld, long stream, bool chain) {
|
||||
if (!a || !wq || !c) return -1;
|
||||
if (M <= 0 || K <= 0 || N <= 0) return -2;
|
||||
if (K % (int)kBlock) return -4;
|
||||
@@ -722,7 +743,8 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld,
|
||||
const uint16_t* ac = (const uint16_t*)a + (size_t)m0 * a_ld;
|
||||
float* cc = (float*)c + (size_t)m0 * c_ld;
|
||||
#define R4D_LMW2(MTV, FKV) \
|
||||
hipLaunchKernelGGL((lm_wmma_kernel<MTV, FKV, I8>), dim3(blocks), dim3(kDenseThreads), 0, \
|
||||
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<MTV, FKV, I8> : lm_wmma_kernel<MTV, FKV, I8>), \
|
||||
dim3(blocks), dim3(kDenseThreads), 0, \
|
||||
(hipStream_t)stream, (const uint8_t*)wq, ac, (uint32_t)a_ld, cc, \
|
||||
(uint32_t)c_ld, rows, cols, (uint32_t)w_ld, (uint32_t)Mc)
|
||||
#define R4D_LMW(MTV) do { if (fkb == 2u) R4D_LMW2(MTV, 2); else R4D_LMW2(MTV, 1); } while (0)
|
||||
@@ -836,9 +858,11 @@ static int rad_logits_gemm_8(const RadArgs* a, RadStream s, bool i8) {
|
||||
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16)) return R4D_NO(RAD_E_ALIGN);
|
||||
|
||||
return (i8 ? r4d_logits_gemm_i8 : r4d_logits_gemm_fp8)(
|
||||
/* The chained form at decode heights, where the row resolved with `chain`. */
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return (i8 ? logits_gemm_8<true> : logits_gemm_8<false>)(
|
||||
r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n_embd, (int)n_vocab,
|
||||
(int)x_ld, (int)y_ld, (int)stride, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
(int)x_ld, (int)y_ld, (int)stride, (long)(uintptr_t)s, ch) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_logits_gemm_fp8(const RadArgs* a, RadStream s) {
|
||||
|
||||
+68
-11
@@ -28,6 +28,7 @@
|
||||
#include "r4d.h"
|
||||
#include "r4d_fp8_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_chain.h"
|
||||
#include "r4d_fp8_wmma.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -176,10 +177,12 @@ constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bo
|
||||
//
|
||||
// The narrow tile: MW waves a block, a wave one 16-row weight tile (A, fragments straight from the
|
||||
// plane into registers) against NT 16-token tiles (B, staged through LDS).
|
||||
/* The body. gemm_fp8a8_kernel and its chained form r4dchain_gemm_fp8a8 (r4d_chain.h) wrap it
|
||||
* after it: its blocks return early (an empty K slice, the finisher's losers), and every block of
|
||||
* a chained launch must still count itself in. */
|
||||
template <bool Full, uint32_t NT, uint32_t MW, uint32_t FK,
|
||||
bool GATED = false, bool I8 = false, bool BIAS = false>
|
||||
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8))
|
||||
void gemm_fp8a8_kernel(
|
||||
__device__ __forceinline__ void gemm_fp8a8_body(
|
||||
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
|
||||
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
|
||||
void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr,
|
||||
@@ -591,6 +594,42 @@ void gemm_fp8a8_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
#define R4D_F8K_ARGS Ap, Sa, Bp, Sb, Y, C, Ctr, rows, cols, nb, a_ld, b_ld, sa_ld, sb_ld, ck, Q, \
|
||||
Sc, Yb, q_ld, s_ld, y_ld, Bias, c_ld
|
||||
template <bool Full, uint32_t NT, uint32_t MW, uint32_t FK,
|
||||
bool GATED = false, bool I8 = false, bool BIAS = false>
|
||||
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8))
|
||||
void gemm_fp8a8_kernel(
|
||||
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
|
||||
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
|
||||
void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr,
|
||||
uint32_t rows, uint32_t cols, uint32_t nb,
|
||||
uint32_t a_ld, uint32_t b_ld, uint32_t sa_ld, uint32_t sb_ld, uint32_t ck,
|
||||
uint8_t* __restrict__ Q = nullptr, float* __restrict__ Sc = nullptr,
|
||||
uint16_t* __restrict__ Yb = nullptr,
|
||||
uint32_t q_ld = 0, uint32_t s_ld = 0, uint32_t y_ld = 0,
|
||||
const uint16_t* __restrict__ Bias = nullptr, uint32_t c_ld = 0) {
|
||||
gemm_fp8a8_body<Full, NT, MW, FK, GATED, I8, BIAS>(R4D_F8K_ARGS);
|
||||
}
|
||||
template <bool Full, uint32_t NT, uint32_t MW, uint32_t FK,
|
||||
bool GATED = false, bool I8 = false, bool BIAS = false>
|
||||
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8))
|
||||
void r4dchain_gemm_fp8a8(
|
||||
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
|
||||
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
|
||||
void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr,
|
||||
uint32_t rows, uint32_t cols, uint32_t nb,
|
||||
uint32_t a_ld, uint32_t b_ld, uint32_t sa_ld, uint32_t sb_ld, uint32_t ck,
|
||||
uint8_t* __restrict__ Q = nullptr, float* __restrict__ Sc = nullptr,
|
||||
uint16_t* __restrict__ Yb = nullptr,
|
||||
uint32_t q_ld = 0, uint32_t s_ld = 0, uint32_t y_ld = 0,
|
||||
const uint16_t* __restrict__ Bias = nullptr, uint32_t c_ld = 0) {
|
||||
r4d_chain_wait();
|
||||
gemm_fp8a8_body<Full, NT, MW, FK, GATED, I8, BIAS>(R4D_F8K_ARGS);
|
||||
r4d_chain_done();
|
||||
}
|
||||
#undef R4D_F8K_ARGS
|
||||
|
||||
// Sum the split-K partials into bf16 C, in fixed z order with no atomics. Latency bound, so eight
|
||||
// loads are issued before their adds; the order of the adds is unchanged.
|
||||
__global__ void splitk_reduce_kernel(const float* __restrict__ ws, uint16_t* __restrict__ y,
|
||||
@@ -931,7 +970,7 @@ extern "C" int r4d_gemm_fp8a8_block(void) { return (int)kBlock; }
|
||||
static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
|
||||
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
|
||||
long scratch, long scratch_bytes, RadStream stream,
|
||||
bool i8 = false, int split_n = 0);
|
||||
bool i8 = false, int split_n = 0, bool chain = false);
|
||||
|
||||
extern "C" int r4d_gemm_fp8a8_nt_m16(long a, long ascale, long wq, long ws, long c,
|
||||
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
|
||||
@@ -990,7 +1029,7 @@ extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) {
|
||||
static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
|
||||
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
|
||||
long scratch, long scratch_bytes, RadStream stream, bool i8,
|
||||
int split_n) {
|
||||
int split_n, bool chain) {
|
||||
int emit_rc = RAD_OK;
|
||||
if (!a || !ascale || !wq || !ws || !c) return -1;
|
||||
if (M <= 0 || K <= 0 || N <= 0) return -2;
|
||||
@@ -1034,7 +1073,9 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
|
||||
(ksplit > 1 && gx <= kMaxCtr) ? split_ctr(stream, (const void*)c) : nullptr;
|
||||
|
||||
#define R4D_F8D(f, mw_, nt_, fk_, i8_) \
|
||||
emit_rc = R4D_EMIT(stream, (gemm_fp8a8_kernel<f, nt_, mw_, fk_, false, i8_>), \
|
||||
emit_rc = R4D_EMIT(stream, \
|
||||
(chain ? r4dchain_gemm_fp8a8<f, nt_, mw_, fk_, false, i8_> \
|
||||
: gemm_fp8a8_kernel<f, nt_, mw_, fk_, false, i8_>), \
|
||||
grid, dim3(mw_ * kWave), \
|
||||
0, (const uint8_t*)wq, (const void*)ws, \
|
||||
(const uint8_t*)a, (const void*)ascale, dst, (void*)c, ctr, \
|
||||
@@ -1157,11 +1198,23 @@ extern "C" int r4d_gemm_fp8a8_bias_nt_m16(long a, long ascale, long wq, long ws,
|
||||
// The weight is the gate_up plane [2*nout][K], gate first, as the unfused GEMM reads it.
|
||||
extern "C" int r4d_gemm_fp8a8_gated_nt_m16_max_m(void) { return 64; }
|
||||
|
||||
static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q, long s,
|
||||
long y, int act, int M, int K, int nout, int a_ld, int sa_ld,
|
||||
int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream,
|
||||
bool chain);
|
||||
extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws,
|
||||
long q, long s, long y, int act,
|
||||
int M, int K, int nout,
|
||||
int a_ld, int sa_ld, int w_ld, int sw_ld,
|
||||
int q_ld, int s_ld, int y_ld, long stream) {
|
||||
return gemm_fp8a8_gated_launch(a, ascale, wq, ws, q, s, y, act, M, K, nout, a_ld, sa_ld,
|
||||
w_ld, sw_ld, q_ld, s_ld, y_ld, stream, false);
|
||||
}
|
||||
/* `chain`: the chained form (r4d_rad_gemm_fp8a8_gated_m16 passes the row's parameter). */
|
||||
static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q, long s,
|
||||
long y, int act, int M, int K, int nout, int a_ld, int sa_ld,
|
||||
int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream,
|
||||
bool chain) {
|
||||
if (!a || !ascale || !wq || !ws || !q || !s) return -1;
|
||||
if (M <= 0 || K <= 0 || nout <= 0) return -2;
|
||||
if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) return -3;
|
||||
@@ -1194,14 +1247,18 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws
|
||||
const dim3 grid((uint32_t)(nout / 128), 1, 1);
|
||||
|
||||
#define R4D_F8G_NT(f, nt_) \
|
||||
hipLaunchKernelGGL((gemm_fp8a8_kernel<f, nt_, kGmw, kFKNarrow, true>), grid, \
|
||||
hipLaunchKernelGGL((chain ? r4dchain_gemm_fp8a8<f, nt_, kGmw, kFKNarrow, true> \
|
||||
: gemm_fp8a8_kernel<f, nt_, kGmw, kFKNarrow, true>), grid, \
|
||||
dim3(kGmw * kWave), \
|
||||
0, (hipStream_t)stream, (const uint8_t*)wq, (const void*)ws, \
|
||||
(const uint8_t*)a, (const void*)ascale, nullptr, nullptr, nullptr, \
|
||||
(uint32_t)N, (uint32_t)K, \
|
||||
(uint32_t)M, (uint32_t)w_ld, (uint32_t)a_ld, (uint32_t)sw_ld, \
|
||||
(uint32_t)sa_ld, 0u, (uint8_t*)q, (float*)s, (uint16_t*)y, \
|
||||
(uint32_t)q_ld, (uint32_t)s_ld, (uint32_t)y_ld)
|
||||
(uint32_t)q_ld, (uint32_t)s_ld, (uint32_t)y_ld, \
|
||||
/* the bias's two, spelled out: a kernel chosen through a pointer takes \
|
||||
* no default arguments */ \
|
||||
(const uint16_t*)nullptr, 0u)
|
||||
#define R4D_F8G(f) \
|
||||
do { if (nt == 4u) R4D_F8G_NT(f, 4u); \
|
||||
else if (nt == 3u) R4D_F8G_NT(f, 3u); \
|
||||
@@ -1289,7 +1346,7 @@ extern "C" int r4d_rad_gemm_fp8a8_m16(const RadArgs* a, RadStream stream) {
|
||||
r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld,
|
||||
(long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, false,
|
||||
(int)r4d_geti_or(a, "split_n", 0));
|
||||
(int)r4d_geti_or(a, "split_n", 0), r4d_geti_or(a, "chain", 0) != 0);
|
||||
return e == 0 ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
@@ -1380,11 +1437,11 @@ extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) {
|
||||
const char* act = r4d_gets(a, "act");
|
||||
if (!act || std::strcmp(act, "silu")) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
|
||||
const int e = r4d_gemm_fp8a8_gated_nt_m16(
|
||||
const int e = gemm_fp8a8_gated_launch(
|
||||
r4d_addr(x), r4d_addr(xs), r4d_addr(w), r4d_addr(wsc),
|
||||
r4d_addr(q), r4d_addr(sc), y ? r4d_addr(y) : 0, 0,
|
||||
(int)M, (int)K, (int)nout, (int)ap, (int)asp, (int)wp, (int)wsp,
|
||||
(int)qp, (int)sp, (int)yp, (long)(uintptr_t)s);
|
||||
(int)qp, (int)sp, (int)yp, (long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0);
|
||||
return e == 0 ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
@@ -1404,7 +1461,7 @@ extern "C" int r4d_rad_gemm_i8a8_m16(const RadArgs* a, RadStream stream) {
|
||||
r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld,
|
||||
(long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, true,
|
||||
(int)r4d_geti_or(a, "split_n", 0));
|
||||
(int)r4d_geti_or(a, "split_n", 0), r4d_geti_or(a, "chain", 0) != 0);
|
||||
return e == 0 ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
#include "r4d_chain.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
@@ -95,12 +96,15 @@ __device__ __forceinline__ v8i mmai(v2i a, v2i b, v8i c) {
|
||||
// limit, so the host checks WV*SK against the same expression.
|
||||
#define R4D_W4A8_BOUNDS(NPW) ((NPW) >= 8 ? 256 : ((NPW) >= 4 ? 512 : 1024))
|
||||
|
||||
template <int MT, int NPW, bool NT, bool ASYM>
|
||||
__global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_kernel(
|
||||
// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); every block runs
|
||||
// to the end. The two kernels below are the plain form and the chained one (r4dchain*).
|
||||
template <int MT, int NPW, bool NT, bool ASYM, bool CHAIN>
|
||||
__device__ __forceinline__ void r4d_gemm_w4a8_nt_m64_body(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws,
|
||||
const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int WV, int SK) {
|
||||
if (CHAIN) r4d_chain_wait();
|
||||
extern __shared__ float red[];
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
@@ -252,11 +256,25 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker
|
||||
if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m] * 0.0625f);
|
||||
}
|
||||
}
|
||||
if (CHAIN) r4d_chain_done();
|
||||
}
|
||||
|
||||
#define R4D_W4A8_PARAMS const signed char* __restrict__ A, const float* __restrict__ Ascale, \
|
||||
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws, \
|
||||
const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK
|
||||
template <int MT, int NPW, bool NT, bool ASYM>
|
||||
__global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_kernel(R4D_W4A8_PARAMS) {
|
||||
r4d_gemm_w4a8_nt_m64_body<MT, NPW, NT, ASYM, false>(A, Ascale, Wq, Ws, Asum, C, M, K, N, WV, SK);
|
||||
}
|
||||
template <int MT, int NPW, bool NT, bool ASYM>
|
||||
__global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4dchain_gemm_w4a8_nt_m64(R4D_W4A8_PARAMS) {
|
||||
r4d_gemm_w4a8_nt_m64_body<MT, NPW, NT, ASYM, true>(A, Ascale, Wq, Ws, Asum, C, M, K, N, WV, SK);
|
||||
}
|
||||
#undef R4D_W4A8_PARAMS
|
||||
|
||||
static void r4d_gemm_w4a8_impl(long a, long ascale, long wq, long ws, long asum, long c,
|
||||
int M, int K, int N, int WV, int SK, int MB, int NPW, int NT,
|
||||
bool asym, long stream) {
|
||||
bool asym, long stream, bool chain = false) {
|
||||
if (M < 1 || M > R4D_GEMM_W4A8_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_w4a8_nt_m64: M out of range");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_w4a8_nt_m64: N must be a multiple of 16");
|
||||
@@ -279,8 +297,11 @@ static void r4d_gemm_w4a8_impl(long a, long ascale, long wq, long ws, long asum,
|
||||
auto Up = (const float*)asum;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(MT, NP, TT, AS) hipLaunchKernelGGL((r4d_gemm_w4a8_nt_m64_kernel<MT, NP, TT, AS>), \
|
||||
grid, block, smem, st, Ap, Sp, Wp, Zp, Up, Cp, M, K, N, WV, SK)
|
||||
#define LAUNCH(MT, NP, TT, AS) do { if (chain) \
|
||||
hipLaunchKernelGGL((r4dchain_gemm_w4a8_nt_m64<MT, NP, TT, AS>), \
|
||||
grid, block, smem, st, Ap, Sp, Wp, Zp, Up, Cp, M, K, N, WV, SK); else \
|
||||
hipLaunchKernelGGL((r4d_gemm_w4a8_nt_m64_kernel<MT, NP, TT, AS>), \
|
||||
grid, block, smem, st, Ap, Sp, Wp, Zp, Up, Cp, M, K, N, WV, SK); } while (0)
|
||||
#define LAUNCH_MB(NP, TT, AS) switch (MB) { \
|
||||
case 1: LAUNCH(1, NP, TT, AS); break; \
|
||||
case 2: LAUNCH(2, NP, TT, AS); break; \
|
||||
@@ -340,20 +361,22 @@ extern "C" int r4d_rad_gemm_w4a8_m64(const RadArgs* a, RadStream s) {
|
||||
rc = cfg_for(a, g.K, g.M, group, BR_NPW, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
|
||||
/* the engine's chained launch (RadKernelChainFn), at decode heights only */
|
||||
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && g.M <= 64;
|
||||
if (is_asym(a)) {
|
||||
if (!g.asum) return R4D_NO(RAD_E_INVAL); /* the entry point throws "asum is required" */
|
||||
R4D_TRY("gemm_w4a8_asym_nt_m64",
|
||||
r4d_gemm_w4a8_asym_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
|
||||
r4d_addr(g.bscale), r4d_addr(g.asum), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
|
||||
c.nt, (long)(uintptr_t)s));
|
||||
r4d_gemm_w4a8_impl(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
|
||||
r4d_addr(g.bscale), r4d_addr(g.asum), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
|
||||
c.nt, true, (long)(uintptr_t)s, chain));
|
||||
return RAD_OK;
|
||||
}
|
||||
R4D_TRY("gemm_w4a8_nt_m64",
|
||||
r4d_gemm_w4a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
|
||||
r4d_addr(g.bscale), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
|
||||
(long)(uintptr_t)s));
|
||||
r4d_gemm_w4a8_impl(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
|
||||
r4d_addr(g.bscale), 0, r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
|
||||
false, (long)(uintptr_t)s, chain));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
#include "r4d_chain.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <cstdint>
|
||||
@@ -68,8 +69,10 @@ __device__ __forceinline__ v8i mmai8(v2i a, v2i b, v8i c) {
|
||||
// VGPRs. The bound is a hard launch limit, so the host checks WV*SK against the same expression.
|
||||
#define R4D_W8A8_BOUNDS(MT, NPW) ((MT) * (NPW) >= 8 ? 256 : ((MT) * (NPW) >= 4 ? 512 : 1024))
|
||||
|
||||
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. Its early returns
|
||||
// sit after its last barrier, so every block still reaches the wrapper's add.
|
||||
template <int MT, int NPW, bool NT>
|
||||
__global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64_kernel(
|
||||
__device__ __forceinline__ void r4d_gemm_w8a8_nt_m64_body(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned short* __restrict__ Ws,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
@@ -219,9 +222,34 @@ __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64
|
||||
}
|
||||
}
|
||||
}
|
||||
template <int MT, int NPW, bool NT>
|
||||
__global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64_kernel(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned short* __restrict__ Ws,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
r4d_gemm_w8a8_nt_m64_body<MT, NPW, NT>(A, Ascale, Wq, Ws, C, M, K, N, WV, SK);
|
||||
}
|
||||
template <int MT, int NPW, bool NT>
|
||||
__global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4dchain_gemm_w8a8_nt_m64(
|
||||
const signed char* __restrict__ A, const float* __restrict__ Ascale,
|
||||
const unsigned* __restrict__ Wq, const unsigned short* __restrict__ Ws,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) {
|
||||
r4d_chain_wait();
|
||||
r4d_gemm_w8a8_nt_m64_body<MT, NPW, NT>(A, Ascale, Wq, Ws, C, M, K, N, WV, SK);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
/* `chain`: the chained form (the plugin entry, where the row resolved with `chain`). */
|
||||
static void gemm_w8a8_m64_impl(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, int NT, long stream, bool chain);
|
||||
|
||||
void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, int NT, long stream) {
|
||||
gemm_w8a8_m64_impl(a, ascale, wq, ws, c, M, K, N, WV, SK, MB, NPW, NT, stream, false);
|
||||
}
|
||||
|
||||
static void gemm_w8a8_m64_impl(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, int NT, long stream, bool chain) {
|
||||
if (M < 1 || M > R4D_GEMM_W8A8_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_w8a8_nt_m64: M out of range");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_w8a8_nt_m64: N must be a multiple of 16");
|
||||
@@ -244,7 +272,8 @@ void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M,
|
||||
auto Zp = (const unsigned short*)ws;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH8(MT, NP, TT) hipLaunchKernelGGL((r4d_gemm_w8a8_nt_m64_kernel<MT, NP, TT>), \
|
||||
#define LAUNCH8(MT, NP, TT) hipLaunchKernelGGL((chain ? r4dchain_gemm_w8a8_nt_m64<MT, NP, TT> \
|
||||
: r4d_gemm_w8a8_nt_m64_kernel<MT, NP, TT>), \
|
||||
grid, block, smem, st, Ap, Sp, Wp, Zp, Cp, M, K, N, WV, SK)
|
||||
// Only tiles with MT*NPW <= 8 are built: a tile costs about 16*MT*NPW + 40 VGPRs against the 256
|
||||
// cap.
|
||||
@@ -293,11 +322,13 @@ extern "C" int r4d_rad_gemm_w8a8_m64(const RadArgs* a, RadStream s) {
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, group, BR_MBNPW, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
/* the engine's chained launch (RadKernelChainFn), at decode heights only */
|
||||
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && g.M <= 64;
|
||||
R4D_TRY("gemm_w8a8_nt_m64",
|
||||
r4d_gemm_w8a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
|
||||
r4d_addr(g.bscale), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
|
||||
(long)(uintptr_t)s));
|
||||
gemm_w8a8_m64_impl(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
|
||||
r4d_addr(g.bscale), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt,
|
||||
(long)(uintptr_t)s, chain));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// r4d_kv_len_trim.hip - r4d_rad_kv_len_trim: a batch's per-sequence context lengths less `trim`.
|
||||
//
|
||||
// The 31B's prefill overlap runs attention per slice of a one-sequence step: slice A's rows are the
|
||||
// step's first rows, so its attention must see the context ending at its own last row, not the
|
||||
// step's (rows past it are not yet in the cache, and their positions are counted from the end).
|
||||
// `trim` is the rows after the slice, a runtime count. A launch sees its op's parameters collapsed
|
||||
// to the band's upper bound (RadArgs.p), so the count is the extent of operand `tail`, those rows'
|
||||
// positions, whose values are never read; the ranged parameter only picks the band.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include <cstdint>
|
||||
|
||||
namespace {
|
||||
|
||||
__global__ __launch_bounds__(64) void kv_len_trim_kernel(const int32_t* __restrict__ in,
|
||||
int32_t* __restrict__ out, int n,
|
||||
int trim) {
|
||||
const int i = (int)threadIdx.x;
|
||||
if (i < n) {
|
||||
const int v = in[i] - trim;
|
||||
out[i] = v > 0 ? v : 0;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int r4d_rad_kv_len_trim(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* in = r4d_opt(a, 0);
|
||||
const RadTensor* tail = r4d_opt(a, 1);
|
||||
const RadTensor* out = r4d_opt(a, 2);
|
||||
if (!in || !tail || !out || !in->data || !out->data) return R4D_NO(RAD_E_INVAL);
|
||||
if (in->dtype != RAD_I32 || out->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_numel(in);
|
||||
if (n < 1 || n > 64 || r4d_numel(out) < n) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long trim = tail->rank ? r4d_numel(tail) : 0;
|
||||
if (trim < 0 || trim > 0x7fffffffLL) return R4D_NO(RAD_E_SHAPE);
|
||||
return R4D_EMIT(stream, kv_len_trim_kernel, dim3(1), dim3(64), 0, (const int32_t*)in->data,
|
||||
(int32_t*)out->data, (int)n, (int)trim);
|
||||
}
|
||||
+157
-31
@@ -28,6 +28,7 @@
|
||||
#include "r4d_common.h"
|
||||
#include "rad_yarn.h"
|
||||
#include "r4d_fp8_wmma.h"
|
||||
#include "r4d_chain.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
@@ -61,7 +62,9 @@ __device__ __forceinline__ float block_sum(float v, float* lds) {
|
||||
// ids stay global, a rank subtracts the offset, and another rank's token takes the zero-row path.
|
||||
// Summing the ranks reconstructs x. `mult` scales every entry with one rounding (Gemma's
|
||||
// sqrt(hidden)); 1 is a plain copy.
|
||||
__global__ __launch_bounds__(kThreads) void embed_lookup_kernel(
|
||||
//
|
||||
// The body; embed_lookup_kernel and its chained form wrap it (its blocks return early).
|
||||
__device__ __forceinline__ void embed_lookup_body(
|
||||
const int32_t* __restrict__ tok, const uint16_t* __restrict__ wte, uint16_t* __restrict__ x,
|
||||
uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld, float mult) {
|
||||
const uint32_t m = blockIdx.x;
|
||||
@@ -79,6 +82,19 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_kernel(
|
||||
for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = f32_to_bf16(bf16_to_f32(src[i]) * mult);
|
||||
}
|
||||
|
||||
#define R4D_EL_PARAMS const int32_t* __restrict__ tok, const uint16_t* __restrict__ wte, \
|
||||
uint16_t* __restrict__ x, uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld, \
|
||||
float mult
|
||||
__global__ __launch_bounds__(kThreads) void embed_lookup_kernel(R4D_EL_PARAMS) {
|
||||
embed_lookup_body(tok, wte, x, n_embd, n_vocab, vocab_off, x_ld, mult);
|
||||
}
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_embed_lookup(R4D_EL_PARAMS) {
|
||||
r4d_chain_wait();
|
||||
embed_lookup_body(tok, wte, x, n_embd, n_vocab, vocab_off, x_ld, mult);
|
||||
r4d_chain_done();
|
||||
}
|
||||
#undef R4D_EL_PARAMS
|
||||
|
||||
// ---------------------------------------------------------------------------- embed_lookup_q
|
||||
// ref_embed_lookup_q. x[m] = bf16(wte[id] * scale), from a table of E4M3 codes with one scale (Q)
|
||||
// or plain bf16; an absent scale is one. This is the n-gram table's gather
|
||||
@@ -137,7 +153,9 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_q_kernel(
|
||||
// ref_gather_rows. Like the embedding gather, with the same negative-index rule, but the source
|
||||
// row pitch is the caller's: it gathers from padded activation buffers (one logits row per
|
||||
// sequence out of a prefill chunk).
|
||||
__global__ __launch_bounds__(kThreads) void gather_rows_kernel(
|
||||
//
|
||||
// The body; gather_rows_kernel and its chained form wrap it (its blocks return early).
|
||||
__device__ __forceinline__ void gather_rows_body(
|
||||
const uint16_t* __restrict__ x, const int32_t* __restrict__ idx, uint16_t* __restrict__ y,
|
||||
uint32_t n, int32_t src_rows, uint32_t x_ld, uint32_t y_ld) {
|
||||
const uint32_t m = blockIdx.x;
|
||||
@@ -150,6 +168,17 @@ __global__ __launch_bounds__(kThreads) void gather_rows_kernel(
|
||||
const uint16_t* __restrict__ src = x + (size_t)r * x_ld;
|
||||
for (uint32_t i = threadIdx.x; i < n; i += kThreads) dst[i] = src[i];
|
||||
}
|
||||
#define R4D_GR_PARAMS const uint16_t* __restrict__ x, const int32_t* __restrict__ idx, \
|
||||
uint16_t* __restrict__ y, uint32_t n, int32_t src_rows, uint32_t x_ld, uint32_t y_ld
|
||||
__global__ __launch_bounds__(kThreads) void gather_rows_kernel(R4D_GR_PARAMS) {
|
||||
gather_rows_body(x, idx, y, n, src_rows, x_ld, y_ld);
|
||||
}
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_gather_rows(R4D_GR_PARAMS) {
|
||||
r4d_chain_wait();
|
||||
gather_rows_body(x, idx, y, n, src_rows, x_ld, y_ld);
|
||||
r4d_chain_done();
|
||||
}
|
||||
#undef R4D_GR_PARAMS
|
||||
|
||||
// ---------------------------------------------------------------- byte row gather / scatter
|
||||
//
|
||||
@@ -206,8 +235,9 @@ __global__ __launch_bounds__(kThreads) void scatter_rows_u8_kernel(
|
||||
__device__ __forceinline__ float act_f32(uint16_t v) { return bf16_to_f32(v); }
|
||||
__device__ __forceinline__ float act_f32(float v) { return v; }
|
||||
|
||||
// The body; rmsnorm_kernel and its chained form wrap it below (the cliff rows return early).
|
||||
template <bool WF32, uint32_t THR, typename TX = uint16_t>
|
||||
__global__ __launch_bounds__(THR) void rmsnorm_kernel(
|
||||
__device__ __forceinline__ void rmsnorm_body(
|
||||
const TX* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y,
|
||||
uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld, uint32_t M) {
|
||||
__shared__ float lds[THR / kWave];
|
||||
@@ -226,13 +256,28 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
#define R4D_RN_PARAMS const TX* __restrict__ x, const void* __restrict__ w, \
|
||||
uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, \
|
||||
uint32_t y_ld, uint32_t M
|
||||
template <bool WF32, uint32_t THR, typename TX = uint16_t>
|
||||
__global__ __launch_bounds__(THR) void rmsnorm_kernel(R4D_RN_PARAMS) {
|
||||
rmsnorm_body<WF32, THR, TX>(x, w, y, n, eps, wadd, mult, x_ld, y_ld, M);
|
||||
}
|
||||
template <bool WF32, uint32_t THR, typename TX = uint16_t>
|
||||
__global__ __launch_bounds__(THR) void r4dchain_rmsnorm(R4D_RN_PARAMS) {
|
||||
r4d_chain_wait();
|
||||
rmsnorm_body<WF32, THR, TX>(x, w, y, n, eps, wadd, mult, x_ld, y_ld, M);
|
||||
r4d_chain_done();
|
||||
}
|
||||
#undef R4D_RN_PARAMS
|
||||
|
||||
// ---------------------------------------------------------------------------- add_rmsnorm
|
||||
// x = x + a, rounded as `add` rounds it, then y = rmsnorm(x) over the x just written, computed as
|
||||
// rmsnorm_kernel computes it: the same width (r4d_act_threads), the same columns a thread, the same
|
||||
// block_sum. A thread re-reads only the x it wrote itself, so no barrier separates the passes.
|
||||
// Byte-identical to `add` followed by `rmsnorm`, on x and on y.
|
||||
template <bool WF32, uint32_t THR>
|
||||
__global__ __launch_bounds__(THR) void add_rmsnorm_kernel(
|
||||
__device__ __forceinline__ void add_rmsnorm_body(
|
||||
uint16_t* __restrict__ x, const uint16_t* __restrict__ a, const void* __restrict__ w,
|
||||
uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld,
|
||||
uint32_t a_ld, uint32_t y_ld, uint32_t M) {
|
||||
@@ -258,6 +303,21 @@ __global__ __launch_bounds__(THR) void add_rmsnorm_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
#define R4D_ARN_PARAMS uint16_t* __restrict__ x, const uint16_t* __restrict__ a, \
|
||||
const void* __restrict__ w, uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, \
|
||||
float mult, uint32_t x_ld, uint32_t a_ld, uint32_t y_ld, uint32_t M
|
||||
template <bool WF32, uint32_t THR>
|
||||
__global__ __launch_bounds__(THR) void add_rmsnorm_kernel(R4D_ARN_PARAMS) {
|
||||
add_rmsnorm_body<WF32, THR>(x, a, w, y, n, eps, wadd, mult, x_ld, a_ld, y_ld, M);
|
||||
}
|
||||
template <bool WF32, uint32_t THR>
|
||||
__global__ __launch_bounds__(THR) void r4dchain_add_rmsnorm(R4D_ARN_PARAMS) {
|
||||
r4d_chain_wait();
|
||||
add_rmsnorm_body<WF32, THR>(x, a, w, y, n, eps, wadd, mult, x_ld, a_ld, y_ld, M);
|
||||
r4d_chain_done();
|
||||
}
|
||||
#undef R4D_ARN_PARAMS
|
||||
|
||||
// ---------------------------------------------------------------------------- rmsnorm_p
|
||||
// ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps), rmsnorm with no gain. Gemma's attention applies
|
||||
// it to V (llama.cpp's ggml_rms_norm(V, eps)), which has no checkpoint gain. Accumulates exactly as
|
||||
@@ -388,6 +448,30 @@ __global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32(
|
||||
yr[i] = cap * tanhf(xr[i] / cap);
|
||||
}
|
||||
|
||||
/* The chained forms of both legs (RadKernelChainFn): the same loop between the wait and the add. */
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_logit_softcap(
|
||||
const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
|
||||
uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) {
|
||||
r4d_chain_wait();
|
||||
const uint32_t m = blockIdx.x;
|
||||
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
|
||||
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
|
||||
for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads)
|
||||
yr[i] = f32_to_bf16(cap * tanhf(bf16_to_f32(xr[i]) / cap));
|
||||
r4d_chain_done();
|
||||
}
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_logit_softcap_f32(
|
||||
const float* __restrict__ x, float* __restrict__ y,
|
||||
uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) {
|
||||
r4d_chain_wait();
|
||||
const uint32_t m = blockIdx.x;
|
||||
const float* __restrict__ xr = x + (size_t)m * x_ld;
|
||||
float* __restrict__ yr = y + (size_t)m * y_ld;
|
||||
for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads)
|
||||
yr[i] = cap * tanhf(xr[i] / cap);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
/* Blocks per softcap row: eight elements a thread, at most 64 blocks. */
|
||||
static uint32_t softcap_blocks_per_row(int n) {
|
||||
uint32_t b = (uint32_t)((n + kThreads * 8 - 1) / (kThreads * 8));
|
||||
@@ -693,11 +777,13 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8v4_kernel(
|
||||
|
||||
/* The plugin entry and r4d.h's long-stream entry share this body. */
|
||||
static int embed_lookup_bf16_emit(long tok, long wte, long x, int M, int n_embd, int n_vocab,
|
||||
int vocab_off, int x_ld, float mult, RadStream stream) {
|
||||
int vocab_off, int x_ld, float mult, RadStream stream,
|
||||
bool chain = false) {
|
||||
if (!tok || !wte || !x) return -1;
|
||||
if (M <= 0 || n_embd <= 0 || n_vocab <= 0 || vocab_off < 0) return -2;
|
||||
if (!x_ld) x_ld = n_embd;
|
||||
return R4D_EMIT(stream, embed_lookup_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
return R4D_EMIT(stream, (chain ? r4dchain_embed_lookup : embed_lookup_kernel),
|
||||
dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
(const int32_t*)tok, (const uint16_t*)wte,
|
||||
(uint16_t*)x, (uint32_t)n_embd, (int32_t)n_vocab, (int32_t)vocab_off,
|
||||
(uint32_t)x_ld, mult) == RAD_OK ? 0 : -4;
|
||||
@@ -736,12 +822,13 @@ extern "C" int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, i
|
||||
}
|
||||
|
||||
static int gather_rows_bf16_emit(long x, long idx, long y, int M, int n, int src_rows,
|
||||
int x_ld, int y_ld, RadStream stream) {
|
||||
int x_ld, int y_ld, RadStream stream, bool chain = false) {
|
||||
if (!x || !idx || !y) return -1;
|
||||
if (M <= 0 || n <= 0 || src_rows <= 0) return -2;
|
||||
if (!x_ld) x_ld = n;
|
||||
if (!y_ld) y_ld = n;
|
||||
return R4D_EMIT(stream, gather_rows_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
return R4D_EMIT(stream, (chain ? r4dchain_gather_rows : gather_rows_kernel),
|
||||
dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
(const uint16_t*)x, (const int32_t*)idx,
|
||||
(uint16_t*)y, (uint32_t)n, (int32_t)src_rows,
|
||||
(uint32_t)x_ld, (uint32_t)y_ld) == RAD_OK ? 0 : -4;
|
||||
@@ -794,8 +881,18 @@ extern "C" int r4d_scatter_rows_u8(long v, long idx, long x, int M, int n, int d
|
||||
|
||||
// `w_f32` selects an f32 or bf16 gain; a null `w` is a gain of one. `mult` scales the row before
|
||||
// its single rounding.
|
||||
/* `chain`: the chained form, at decode heights (r4d_rad_rmsnorm passes the row's resolved
|
||||
* parameter; every other caller none). */
|
||||
static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, float wadd,
|
||||
float mult, int w_f32, int x_ld, int y_ld, long stream,
|
||||
bool chain);
|
||||
extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float eps, float wadd,
|
||||
float mult, int w_f32, int x_ld, int y_ld, long stream) {
|
||||
return rmsnorm_mult_launch(x, w, y, M, n, eps, wadd, mult, w_f32, x_ld, y_ld, stream, false);
|
||||
}
|
||||
static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, float wadd,
|
||||
float mult, int w_f32, int x_ld, int y_ld, long stream,
|
||||
bool chain) {
|
||||
if (!x || !y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!x_ld) x_ld = n;
|
||||
@@ -806,8 +903,10 @@ extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float
|
||||
// to this one followed by the quantiser.
|
||||
const int thr = r4d_act_threads(M, n);
|
||||
// A drafter's 256-row head norm at 256 threads is exactly a full card; step past the cliff.
|
||||
const bool ch = chain && M <= 64;
|
||||
#define R4D_RN_T(wf, T) \
|
||||
hipLaunchKernelGGL((rmsnorm_kernel<wf, T>), dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), \
|
||||
hipLaunchKernelGGL((ch ? r4dchain_rmsnorm<wf, T> : rmsnorm_kernel<wf, T>), \
|
||||
dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), \
|
||||
dim3(T), 0, \
|
||||
(hipStream_t)stream, (const uint16_t*)x, (const void*)w, (uint16_t*)y, \
|
||||
(uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M)
|
||||
@@ -910,14 +1009,16 @@ extern "C" int r4d_fill_f32(long y, int M, int n, int y_ld, float value, long st
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap,
|
||||
int x_ld, int y_ld, long stream) {
|
||||
/* `chain`: the chained form (the plugin entry, where the row resolved with `chain`). */
|
||||
static int logit_softcap_bf16_emit(long x, long y, int M, int n, float cap,
|
||||
int x_ld, int y_ld, long stream, bool chain) {
|
||||
if (!x || !y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!(cap > 0.0f)) return -3;
|
||||
if (!x_ld) x_ld = n;
|
||||
if (!y_ld) y_ld = n;
|
||||
hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M, softcap_blocks_per_row(n)),
|
||||
hipLaunchKernelGGL((chain ? r4dchain_logit_softcap : logit_softcap_kernel),
|
||||
dim3((uint32_t)M, softcap_blocks_per_row(n)),
|
||||
dim3(kThreads), 0,
|
||||
(hipStream_t)stream,
|
||||
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n, cap,
|
||||
@@ -925,14 +1026,20 @@ extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap,
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap,
|
||||
int x_ld, int y_ld, long stream) {
|
||||
extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap,
|
||||
int x_ld, int y_ld, long stream) {
|
||||
return logit_softcap_bf16_emit(x, y, M, n, cap, x_ld, y_ld, stream, false);
|
||||
}
|
||||
|
||||
static int logit_softcap_f32_emit(long x, long y, int M, int n, float cap,
|
||||
int x_ld, int y_ld, long stream, bool chain) {
|
||||
if (!x || !y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!(cap > 0.0f)) return -3;
|
||||
if (!x_ld) x_ld = n;
|
||||
if (!y_ld) y_ld = n;
|
||||
hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M, softcap_blocks_per_row(n)),
|
||||
hipLaunchKernelGGL((chain ? r4dchain_logit_softcap_f32 : logit_softcap_kernel_f32),
|
||||
dim3((uint32_t)M, softcap_blocks_per_row(n)),
|
||||
dim3(kThreads), 0,
|
||||
(hipStream_t)stream,
|
||||
(const float*)x, (float*)y, (uint32_t)n, cap,
|
||||
@@ -940,6 +1047,11 @@ extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap,
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap,
|
||||
int x_ld, int y_ld, long stream) {
|
||||
return logit_softcap_f32_emit(x, y, M, n, cap, x_ld, y_ld, stream, false);
|
||||
}
|
||||
|
||||
extern "C" int r4d_scale_bf16(long x, long s, uint32_t s_dt, long y, int M, int n,
|
||||
int x_ld, int y_ld, long stream) {
|
||||
if (!x || !s || !y) return -1;
|
||||
@@ -1199,9 +1311,11 @@ extern "C" int r4d_rad_embed_lookup(const RadArgs* a, RadStream stream) {
|
||||
if (M <= 0 || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
const float mult = (float)r4d_getf(a, "mult", 1.0);
|
||||
/* The chained form at decode heights, where the row resolved with `chain`. */
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return embed_lookup_bf16_emit(r4d_addr(tok), r4d_addr(wte), r4d_addr(x),
|
||||
(int)M, (int)n_embd, (int)n_vocab, (int)voff, (int)x_ld,
|
||||
mult, stream) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
mult, stream, ch) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ embed_lookup_q */
|
||||
@@ -1264,9 +1378,10 @@ extern "C" int r4d_rad_gather_rows(const RadArgs* a, RadStream stream) {
|
||||
if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || src <= 0 || r4d_numel(idx) < M) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return gather_rows_bf16_emit(r4d_addr(x), r4d_addr(idx), r4d_addr(y),
|
||||
(int)M, (int)n, (int)src, (int)x_ld, (int)y_ld,
|
||||
stream) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
stream, ch) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ byte rows */
|
||||
@@ -1421,10 +1536,11 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
|
||||
const long long y_ld = r4d_rows_pitch(y, n, &My);
|
||||
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
|
||||
return r4d_rmsnorm_mult_bf16(r4d_addr(x), 0, r4d_addr(y), (int)M, (int)n,
|
||||
return rmsnorm_mult_launch(r4d_addr(x), 0, r4d_addr(y), (int)M, (int)n,
|
||||
(float)r4d_getf(a, "eps", 1e-6), 0.0f,
|
||||
(float)r4d_getf(a, "mult", 1.0), 0, (int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
(long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0) == 0
|
||||
? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE);
|
||||
/* The gain may be f32 (as plugins declare norm gains) or bf16; its width is read off the
|
||||
@@ -1446,10 +1562,10 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
|
||||
return rmsnorm_x_f32((const float*)x->data, w->data, (uint16_t*)y->data, (int)M, (int)n,
|
||||
eps, wadd, (float)r4d_getf(a, "mult", 1.0), w_f32, (int)x_ld,
|
||||
(int)y_ld, s);
|
||||
return r4d_rmsnorm_mult_bf16(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd,
|
||||
return rmsnorm_mult_launch(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd,
|
||||
(float)r4d_getf(a, "mult", 1.0),
|
||||
w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK
|
||||
: RAD_E_DEVICE;
|
||||
w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s,
|
||||
r4d_geti_or(a, "chain", 0) != 0) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ add_rmsnorm */
|
||||
@@ -1482,12 +1598,20 @@ extern "C" int r4d_rad_add_rmsnorm(const RadArgs* a, RadStream s) {
|
||||
const float mult = (float)r4d_getf(a, "mult", 1.0);
|
||||
/* rmsnorm's width, from the same table (see r4d_rmsnorm_mult_bf16) */
|
||||
const int thr = r4d_act_threads((int)M, (int)n);
|
||||
/* The chained form at decode heights, where the row resolved with `chain`. */
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
#define R4D_AN_T(wf, T) \
|
||||
emit_rc = R4D_EMIT(s, (add_rmsnorm_kernel<wf, T>), \
|
||||
dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \
|
||||
(uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \
|
||||
(uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \
|
||||
(uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M)
|
||||
emit_rc = ch \
|
||||
? R4D_EMIT(s, (r4dchain_add_rmsnorm<wf, T>), \
|
||||
dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \
|
||||
(uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \
|
||||
(uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \
|
||||
(uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M) \
|
||||
: R4D_EMIT(s, (add_rmsnorm_kernel<wf, T>), \
|
||||
dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \
|
||||
(uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \
|
||||
(uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \
|
||||
(uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M)
|
||||
#define R4D_AN(wf) \
|
||||
do { if (thr == 1024) R4D_AN_T(wf, 1024); \
|
||||
else if (thr == 512) R4D_AN_T(wf, 512); \
|
||||
@@ -1704,11 +1828,13 @@ extern "C" int r4d_rad_logit_softcap(const RadArgs* a, RadStream s) {
|
||||
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* The chained form at decode heights, where the row resolved with `chain`. */
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
const int rc = leg_bf16
|
||||
? r4d_logit_softcap_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
|
||||
(int)x_ld, (int)y_ld, (long)(uintptr_t)s)
|
||||
: r4d_logit_softcap_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
|
||||
(int)x_ld, (int)y_ld, (long)(uintptr_t)s);
|
||||
? logit_softcap_bf16_emit(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
|
||||
(int)x_ld, (int)y_ld, (long)(uintptr_t)s, ch)
|
||||
: logit_softcap_f32_emit(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
|
||||
(int)x_ld, (int)y_ld, (long)(uintptr_t)s, ch);
|
||||
return rc == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
|
||||
@@ -469,7 +469,11 @@ int64_t r4d_rad_moe_gather_scratch (const RadArgs*);
|
||||
/* -- quantisation, norms and the fusions (r4d_*quant*.hip, r4d_qk_norm_rope_gate.hip) -- */
|
||||
int r4d_rad_quant_act_i8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream);
|
||||
int r4d_rad_kv_len_trim (const RadArgs*, RadStream);
|
||||
int r4d_rad_add_rmsnorm (const RadArgs*, RadStream);
|
||||
int r4d_rad_prefetch (const RadArgs*, RadStream);
|
||||
int r4d_rad_layout_any(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, RadLayout*);
|
||||
int r4d_rad_qkv_norm_rope_kv_store(const RadArgs*, RadStream);
|
||||
int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream);
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// r4d_prefetch.hip - r4d_rad_prefetch: read a weight's leading bytes into the on-die cache.
|
||||
//
|
||||
// A decode step at a few rows streams each weight once from memory, and the all-reduce between two
|
||||
// GEMMs leaves memory idle for its whole round trip: ~20 us at a DFlash2 verify's 8 rows on 4x
|
||||
// R9700. A read issued on the second lane in that window puts the next GEMM's first bytes in the
|
||||
// 64 MB Infinity Cache, and the GEMM then streams them from there. On four cards (a microbenchmark
|
||||
// of the 8-row two-shot and a GEMM-like stream of a cold 29 MB weight, 2026-10-17) 16 MB read beside
|
||||
// the all-reduce took a layer from 84.0 us to 70.1; the same read on the same stream gained nothing.
|
||||
//
|
||||
// It writes nothing at all. Each lane folds its loads into one word and hands it to an empty
|
||||
// `asm volatile`, which the compiler can neither drop nor see into, so the loads stay.
|
||||
//
|
||||
// Nothing here reaches HIP's runtime. The fold once went to a word hipMalloc'ed on the first
|
||||
// launch, in the middle of a pass; then to a `__device__` word, which HIP's runtime registers and
|
||||
// places itself (the engine records only fat binaries and functions). That word cost ~8% of a
|
||||
// DFlash2 step (321 tok/s against 348 in one A/B on 4x R9700, 2026-10-17, every prefetch size
|
||||
// alike), not through extra hardware queues (every image held 16 on the four cards); the
|
||||
// mechanism is not pinned down. Neither form was the cause of the fresh-server divergence the
|
||||
// reads beside a prefill bring (rad_arch.h, kPrefetchRows): with no word at all it is still there.
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_chain.h"
|
||||
#include "r4d_emit.h"
|
||||
#include <cstdint>
|
||||
|
||||
namespace {
|
||||
|
||||
__global__ __launch_bounds__(256) void prefetch_kernel(const int4* __restrict__ p, size_t n16) {
|
||||
const size_t tid = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
|
||||
const size_t nt = (size_t)gridDim.x * blockDim.x;
|
||||
unsigned acc = 0;
|
||||
for (size_t i = tid; i < n16; i += nt) {
|
||||
const int4 v = p[i];
|
||||
acc ^= (unsigned)(v.x ^ v.y ^ v.z ^ v.w);
|
||||
}
|
||||
asm volatile("" ::"v"(acc));
|
||||
}
|
||||
|
||||
/* The chained form (RadKernelChainFn): it waits for the kernels before it on its queue, as every
|
||||
* chained form does, but adds its blocks to the counter at once, before reading: nothing after it
|
||||
* reads anything it writes, so the next kernel need not wait for its reads. Issued on lane 0
|
||||
* between a GEMM and the collective after it (where launches chain), it starts reading as the
|
||||
* GEMM's last block ends, with no event between the queues and no barrier bit on the GEMM. */
|
||||
__global__ __launch_bounds__(256) void r4dchain_prefetch(const int4* __restrict__ p, size_t n16) {
|
||||
r4d_chain_wait();
|
||||
r4d_chain_done();
|
||||
const size_t tid = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
|
||||
const size_t nt = (size_t)gridDim.x * blockDim.x;
|
||||
unsigned acc = 0;
|
||||
for (size_t i = tid; i < n16; i += nt) {
|
||||
const int4 v = p[i];
|
||||
acc ^= (unsigned)(v.x ^ v.y ^ v.z ^ v.w);
|
||||
}
|
||||
asm volatile("" ::"v"(acc));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int r4d_rad_layout_any(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, RadLayout*) {
|
||||
return RAD_LAYOUT_ANY;
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_prefetch(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* w = r4d_opt(a, 0);
|
||||
if (!w || !w->data) return R4D_NO(RAD_E_INVAL);
|
||||
long long bytes = r4d_geti_or(a, "bytes", 0);
|
||||
if (bytes <= 0) return RAD_OK;
|
||||
// Never past what the tensor says it holds, where its dtype says how wide an element is.
|
||||
const int bits = rad_dtype_bits(w->dtype);
|
||||
if (bits > 0) {
|
||||
long long n = 1;
|
||||
for (uint32_t i = 0; i < w->rank; ++i) n *= w->shape[i];
|
||||
const long long have = n * bits / 8;
|
||||
if (have > 0 && bytes > have) bytes = have;
|
||||
}
|
||||
if ((uintptr_t)w->data % 16) return R4D_NO(RAD_E_ALIGN);
|
||||
int nb = r4d_cfg_prefetch_nb(a);
|
||||
if (nb < 1) nb = 64;
|
||||
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));
|
||||
}
|
||||
@@ -34,6 +34,7 @@
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_chain.h"
|
||||
#include <cstdint>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
@@ -118,8 +119,10 @@ __device__ __forceinline__ void kv_put(void* __restrict__ kv, size_t off,
|
||||
// KV 1 or 2 also stores each k and v head into the paged cache [n_blocks, nkv, block_size, 2*HD]
|
||||
// at slot[m] (k at column 0, v at HD), for rows m < n_slot whose slot is in range; KV 0 stores
|
||||
// nothing and ignores the cache arguments.
|
||||
// The body: its blocks return early (rows past the cliff, value heads), so the chained form
|
||||
// (r4d_chain.h) wraps it below rather than bracketing it in place.
|
||||
template <uint32_t HD, bool WF32, bool VK, int KV>
|
||||
__global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(
|
||||
__device__ __forceinline__ void qkv_norm_rope_body(
|
||||
uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v,
|
||||
const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw,
|
||||
uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv,
|
||||
@@ -201,6 +204,29 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
#define R4D_QNR_PARAMS uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v, \
|
||||
const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw, \
|
||||
uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv, \
|
||||
uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, \
|
||||
uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos, \
|
||||
uint32_t m_rows, const int32_t* __restrict__ slot, void* __restrict__ kvc, uint32_t n_slot, \
|
||||
uint32_t block_size, uint32_t n_blocks, float k_inv, float v_inv, uint32_t vnorm
|
||||
#define R4D_QNR_ARGS q, k, v, pos, qw, kw, nq, nkv, pq, pk, pv, q_ld, k_ld, v_ld, eps, wadd, rot, nfreq, \
|
||||
den, theta, rscale, n_pos, m_rows, slot, kvc, n_slot, block_size, n_blocks, k_inv, v_inv, vnorm
|
||||
// The plain kernel, and the chained one (r4dchain*, r4d_chain.h) wrapping the same body.
|
||||
template <uint32_t HD, bool WF32, bool VK, int KV>
|
||||
__global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(R4D_QNR_PARAMS) {
|
||||
qkv_norm_rope_body<HD, WF32, VK, KV>(R4D_QNR_ARGS);
|
||||
}
|
||||
template <uint32_t HD, bool WF32, bool VK, int KV>
|
||||
__global__ __launch_bounds__(HD) void r4dchain_qkv_norm_rope(R4D_QNR_PARAMS) {
|
||||
r4d_chain_wait();
|
||||
qkv_norm_rope_body<HD, WF32, VK, KV>(R4D_QNR_ARGS);
|
||||
r4d_chain_done();
|
||||
}
|
||||
#undef R4D_QNR_ARGS
|
||||
#undef R4D_QNR_PARAMS
|
||||
|
||||
} // namespace
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
@@ -270,6 +296,7 @@ static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store)
|
||||
// A tp-4 verify of the 31B is 16 rows x 16 heads of 8 wavefronts: exactly a full card, the
|
||||
// cliff r4d_cliff_rows steps past with one idle row.
|
||||
const dim3 grid(r4d_cliff_rows((uint32_t)M, heads, (uint32_t)(hd / kWave)), heads);
|
||||
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; /* RadKernelChainFn, decode */
|
||||
|
||||
// The store's geometry, checked as kv_store_geom checks it (r4d_model_bf16.hip).
|
||||
int kvw = 0; // 0 none, 1 E4M3, 2 bf16
|
||||
@@ -302,7 +329,8 @@ static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store)
|
||||
}
|
||||
}
|
||||
|
||||
#define R4D_QNR_T(HD, WF, VK, KV) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel<HD, WF, VK, KV>), grid, dim3(HD), 0, \
|
||||
#define R4D_QNR_T(HD, WF, VK, KV) emit_rc = chain ? R4D_QNR_C(HD, WF, VK, KV, true) : R4D_QNR_C(HD, WF, VK, KV, false)
|
||||
#define R4D_QNR_C(HD, WF, VK, KV, CH) R4D_EMIT(stream, (CH ? r4dchain_qkv_norm_rope<HD, WF, VK, KV> : qkv_norm_rope_kernel<HD, WF, VK, KV>), grid, dim3(HD), 0, \
|
||||
(uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \
|
||||
r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \
|
||||
(uint32_t)v_ld, eps, wadd, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp, \
|
||||
@@ -320,6 +348,7 @@ static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store)
|
||||
#undef R4D_QNR
|
||||
#undef R4D_QNR_KV
|
||||
#undef R4D_QNR_T
|
||||
#undef R4D_QNR_C
|
||||
return emit_rc;
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
#include "r4d_fp8_args.h"
|
||||
#include "r4d_fp8_wmma.h"
|
||||
#include "r4d_fwht.h"
|
||||
#include "r4d_chain.h"
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -43,10 +44,14 @@ constexpr uint32_t kGroup = 128;
|
||||
//
|
||||
// I8 is the same quantiser at int8 codes (quant_act_i8g, had_quant_act_i8g): scale amax/127,
|
||||
// round-to-nearest-even into -127..127, same row-major layout and per-(row, 128) scales.
|
||||
template <bool ROT, bool I8 = false>
|
||||
__global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel(
|
||||
//
|
||||
// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); no block returns
|
||||
// early. quant_act_fp8_kernel and r4dchain_quant_act_fp8 below are the plain and chained forms.
|
||||
template <bool ROT, bool I8 = false, bool CHAIN = false>
|
||||
__device__ __forceinline__ void quant_act_fp8_body(
|
||||
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s,
|
||||
uint32_t K, uint32_t nkb, uint32_t x_ld, uint32_t q_ld, uint32_t s_ld) {
|
||||
if (CHAIN) r4d_chain_wait();
|
||||
const uint32_t row = blockIdx.x;
|
||||
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
|
||||
const size_t xrow = (size_t)row * x_ld;
|
||||
@@ -92,8 +97,21 @@ __global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel(
|
||||
// of the accumulators. The caller must own K rounded up to 4 bytes of `q`.
|
||||
if (c0 < K) *(uint32_t*)(q + qrow + c0) = (uint32_t)pk;
|
||||
}
|
||||
if (CHAIN) r4d_chain_done();
|
||||
}
|
||||
|
||||
#define R4D_QAF_PARAMS const uint16_t* __restrict__ x, uint8_t* __restrict__ q, \
|
||||
float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t x_ld, uint32_t q_ld, uint32_t s_ld
|
||||
template <bool ROT, bool I8 = false>
|
||||
__global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel(R4D_QAF_PARAMS) {
|
||||
quant_act_fp8_body<ROT, I8, false>(x, q, s, K, nkb, x_ld, q_ld, s_ld);
|
||||
}
|
||||
template <bool ROT, bool I8 = false>
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_quant_act_fp8(R4D_QAF_PARAMS) {
|
||||
quant_act_fp8_body<ROT, I8, true>(x, q, s, K, nkb, x_ld, q_ld, s_ld);
|
||||
}
|
||||
#undef R4D_QAF_PARAMS
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int r4d_quant_act_fp8_group(void) { return (int)kGroup; }
|
||||
@@ -105,7 +123,7 @@ extern "C" int r4d_quant_act_fp8_group(void) { return (int)kGroup; }
|
||||
// `rot` runs the 128-wide Hadamard first and additionally requires K % 128 == 0 (see the kernel).
|
||||
static int quant_act_fp8_launch(long a, long q, long s, int M, int K,
|
||||
int x_ld, int q_ld, int s_ld, RadStream stream, bool rot,
|
||||
bool i8 = false) {
|
||||
bool i8 = false, bool chain = false) {
|
||||
int emit_rc = RAD_OK;
|
||||
if (!a || !q || !s) return -1;
|
||||
if (M <= 0 || K <= 0) return -2;
|
||||
@@ -115,10 +133,15 @@ static int quant_act_fp8_launch(long a, long q, long s, int M, int K,
|
||||
if (!q_ld) q_ld = K;
|
||||
const int nkb = (K + (int)kGroup - 1) / (int)kGroup;
|
||||
if (!s_ld) s_ld = nkb;
|
||||
/* The chained form at decode heights, where the row resolved with `chain`. */
|
||||
const bool ch = chain && M <= 64;
|
||||
#define R4D_QA(ROT_, I8_) \
|
||||
R4D_EMIT(stream, (quant_act_fp8_kernel<ROT_, I8_>), dim3((uint32_t)M), dim3(kThreads), 0, \
|
||||
(const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, (uint32_t)nkb, \
|
||||
(uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld)
|
||||
(ch ? R4D_EMIT(stream, (r4dchain_quant_act_fp8<ROT_, I8_>), dim3((uint32_t)M), \
|
||||
dim3(kThreads), 0, (const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, \
|
||||
(uint32_t)nkb, (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld) \
|
||||
: R4D_EMIT(stream, (quant_act_fp8_kernel<ROT_, I8_>), dim3((uint32_t)M), \
|
||||
dim3(kThreads), 0, (const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, \
|
||||
(uint32_t)nkb, (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld))
|
||||
if (i8) emit_rc = rot ? R4D_QA(true, true) : R4D_QA(false, true);
|
||||
else emit_rc = rot ? R4D_QA(true, false) : R4D_QA(false, false);
|
||||
#undef R4D_QA
|
||||
@@ -163,7 +186,8 @@ static int rad_quant_act_fp8(const RadArgs* a, RadStream stream, bool rot, bool
|
||||
const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
|
||||
if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
const int e = quant_act_fp8_launch(r4d_addr(x), r4d_addr(q), r4d_addr(sc), (int)M, (int)K,
|
||||
(int)xp, (int)qp, (int)sp, stream, rot, i8);
|
||||
(int)xp, (int)qp, (int)sp, stream, rot, i8,
|
||||
r4d_geti_or(a, "chain", 0) != 0);
|
||||
return e == 0 ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,13 +11,17 @@
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_chain.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
|
||||
template <int THR>
|
||||
__global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel(
|
||||
/* CHAIN: the chained form's wait and add (r4d_chain.h) around the same body; no block returns
|
||||
* early. */
|
||||
template <int THR, bool CHAIN = false>
|
||||
__device__ __forceinline__ void r4d_quant_act_i8_body(
|
||||
const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S,
|
||||
int K) {
|
||||
if (CHAIN) r4d_chain_wait();
|
||||
const int row = blockIdx.x;
|
||||
const __hip_bfloat16* a = A + (size_t)row * K;
|
||||
signed char* q = Q + (size_t)row * K;
|
||||
@@ -47,6 +51,20 @@ __global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel(
|
||||
const int t = __float2int_rn(v);
|
||||
q[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
|
||||
}
|
||||
if (CHAIN) r4d_chain_done();
|
||||
}
|
||||
|
||||
template <int THR>
|
||||
__global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel(
|
||||
const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S,
|
||||
int K) {
|
||||
r4d_quant_act_i8_body<THR, false>(A, Q, S, K);
|
||||
}
|
||||
template <int THR>
|
||||
__global__ __launch_bounds__(THR) void r4dchain_quant_act_i8(
|
||||
const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S,
|
||||
int K) {
|
||||
r4d_quant_act_i8_body<THR, true>(A, Q, S, K);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
@@ -126,9 +144,15 @@ extern "C" int r4d_rad_quant_act_i8(const RadArgs* args, RadStream stream) {
|
||||
const int thr = r4d_act_threads((int)M, (int)K); // the workgroup width, from M
|
||||
|
||||
if (!as) {
|
||||
#define R4D_QAI8_LAUNCH(T) emit_rc = R4D_EMIT(stream, (r4d_quant_act_i8_kernel<T>), \
|
||||
dim3((int)M), dim3(T), 0, (const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), \
|
||||
(float*)r4d_wp(sc), (int)K)
|
||||
/* The chained form where the row resolved with `chain`, at decode heights. */
|
||||
const bool chain = r4d_geti_or(args, "chain", 0) != 0 && M <= 64;
|
||||
#define R4D_QAI8_LAUNCH(T) emit_rc = chain \
|
||||
? R4D_EMIT(stream, (r4dchain_quant_act_i8<T>), dim3((int)M), dim3(T), 0, \
|
||||
(const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), (float*)r4d_wp(sc), \
|
||||
(int)K) \
|
||||
: R4D_EMIT(stream, (r4d_quant_act_i8_kernel<T>), dim3((int)M), dim3(T), 0, \
|
||||
(const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), (float*)r4d_wp(sc), \
|
||||
(int)K)
|
||||
switch (thr) {
|
||||
case 128: R4D_QAI8_LAUNCH(128); break;
|
||||
case 256: R4D_QAI8_LAUNCH(256); break;
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
// pass reads its own writes back.
|
||||
//
|
||||
// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip.
|
||||
#include "r4d_chain.h"
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
@@ -468,8 +469,11 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_wide_kernel(
|
||||
//
|
||||
// tail[0] counts the transport blocks done, tail[1] the junction blocks done; both start at zero
|
||||
// (the counter allocation is zeroed at init) and the last junction block returns them there.
|
||||
// The body: transport blocks return after their part, so the chained form (r4d_chain.h) wraps
|
||||
// it below. The last junction block resets the tail counters inside the body, before the chained
|
||||
// form's add, so the next launch on the instance never sees them mid-reset.
|
||||
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t EPT, int WS>
|
||||
__global__ __launch_bounds__(1024) void ar_rmsnorm_quant_i8_tail_kernel(
|
||||
__device__ __forceinline__ void ar_rmsnorm_quant_i8_tail_body(
|
||||
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
|
||||
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
|
||||
signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo,
|
||||
@@ -585,6 +589,31 @@ __global__ __launch_bounds__(1024) void ar_rmsnorm_quant_i8_tail_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
#define R4D_ARQ8T_PARAMS uint16_t* __restrict__ x, uint16_t* __restrict__ res, \
|
||||
const void* __restrict__ w, const void* __restrict__ wp, const void* __restrict__ sc, \
|
||||
uint32_t sc_f32, signed char* __restrict__ q, float* __restrict__ S, \
|
||||
uint16_t* __restrict__ yo, R4DArWidePeers<int4, WS - 1> peers, \
|
||||
const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \
|
||||
unsigned int* __restrict__ seq_ctrs, unsigned int* __restrict__ tail, int M, uint32_t n, \
|
||||
float eps, float wadd, uint32_t r_ld, uint32_t y_ld, int slot_stride16, int rank, int nbt, \
|
||||
int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr
|
||||
#define R4D_ARQ8T_ARGS x, res, w, wp, sc, sc_f32, q, S, yo, peers, my_base, my_flags, seq_ctrs, tail, \
|
||||
M, n, eps, wadd, r_ld, y_ld, slot_stride16, rank, nbt, drain, acq, pub, gate, gate_ctr
|
||||
// The plain kernel, and the chained one (r4dchain*): its wait comes before anything, the sequence
|
||||
// take included, so a block of the next launch on the instance never starts ahead of this one's.
|
||||
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t EPT, int WS>
|
||||
__global__ __launch_bounds__(1024) void ar_rmsnorm_quant_i8_tail_kernel(R4D_ARQ8T_PARAMS) {
|
||||
ar_rmsnorm_quant_i8_tail_body<WF32, RES, POST, SCL, EPT, WS>(R4D_ARQ8T_ARGS);
|
||||
}
|
||||
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t EPT, int WS>
|
||||
__global__ __launch_bounds__(1024) void r4dchain_ar_rmsnorm_quant_i8_tail(R4D_ARQ8T_PARAMS) {
|
||||
r4d_chain_wait();
|
||||
ar_rmsnorm_quant_i8_tail_body<WF32, RES, POST, SCL, EPT, WS>(R4D_ARQ8T_ARGS);
|
||||
r4d_chain_done();
|
||||
}
|
||||
#undef R4D_ARQ8T_ARGS
|
||||
#undef R4D_ARQ8T_PARAMS
|
||||
|
||||
} // namespace
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
@@ -742,7 +771,7 @@ extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scrat
|
||||
float eps, float wadd, int w_f32, int r_ld, int y_ld,
|
||||
int rank, long stream, int nblocks, int drain, int acq,
|
||||
int pub, long gate, long gate_ctr,
|
||||
long tail_ctr, int tail_nbt) {
|
||||
long tail_ctr, int tail_nbt, int chain) {
|
||||
constexpr int WS = 4, NPEERS = WS - 1;
|
||||
const long ps[NPEERS] = { peer_scratch0, peer_scratch1, peer_scratch2 };
|
||||
const long pf[NPEERS] = { peer_flags0, peer_flags1, peer_flags2 };
|
||||
@@ -803,7 +832,8 @@ extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scrat
|
||||
return -8;
|
||||
}
|
||||
#define R4D_ARQ8T_K(WF, RS, PO, SC, E) \
|
||||
hipLaunchKernelGGL((ar_rmsnorm_quant_i8_tail_kernel<WF, RS, PO, SC, E, WS>), \
|
||||
hipLaunchKernelGGL((chain ? r4dchain_ar_rmsnorm_quant_i8_tail<WF, RS, PO, SC, E, WS> \
|
||||
: ar_rmsnorm_quant_i8_tail_kernel<WF, RS, PO, SC, E, WS>), \
|
||||
dim3((uint32_t)(tail_nbt + M)), dim3(1024), lds, (hipStream_t)stream, \
|
||||
(uint16_t*)x, (uint16_t*)res, (const void*)w, (const void*)wp, \
|
||||
(const void*)sc, (uint32_t)sc_f32, (signed char*)q, (float*)s, \
|
||||
|
||||
@@ -743,6 +743,25 @@ static const RadOperandSpec oAddRmsNorm[] = {
|
||||
{ "w", RAD_OPD_WEIGHT, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
/* `kv_len_trim`: a batch's per-sequence context lengths less `trim` (docs/OPS.md). */
|
||||
static const RadParamSpec pKvLenTrim[] = {
|
||||
{ "trim", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "max_seqs", RAD_P_INT, RAD_REQUIRED },
|
||||
};
|
||||
/* `tail` is the rows past the slice (their positions); its extent is the trim, its values unread.
|
||||
* A launch's `trim` is the band's upper bound, not the issued count (RadArgs.p). */
|
||||
static const RadOperandSpec oKvLenTrim[] = {
|
||||
{ "seqused", RAD_OPD_IN, 0 },
|
||||
{ "tail", RAD_OPD_IN, 0 },
|
||||
{ "out", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
/* `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 },
|
||||
};
|
||||
static const RadOperandSpec oPrefetch[] = {
|
||||
{ "w", RAD_OPD_WEIGHT, 0 },
|
||||
};
|
||||
static const RadParamSpec pGemmNtQ[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED },
|
||||
@@ -3150,6 +3169,13 @@ static const RadOpSchema kSchemas[] = {
|
||||
"x = x + a, then y = rmsnorm(x) * (w + wadd) * mult over the x written: a residual add "
|
||||
"and the next norm in one pass, byte-identical to add then rmsnorm. The norm is taken "
|
||||
"over the bf16 sum it stores; rmsnorm_add normalises the unrounded one."),
|
||||
SCHEMA("kv_len_trim", pKvLenTrim, oKvLenTrim,
|
||||
"out[s] = max(seqused[s] - trim, 0), trim the extent of `tail` (the rows past the "
|
||||
"slice): the context a slice of a step's rows ends at, for an attention over that "
|
||||
"slice alone."),
|
||||
SCHEMA("prefetch", pPrefetch, oPrefetch,
|
||||
"read a weight's leading bytes so they are in the cache when the next kernel streams "
|
||||
"them; writes nothing."),
|
||||
SCHEMA("qkv_norm_rope", pQkvNormRope, oQkvNormRope,
|
||||
"per-head q and k RMS norms, the weightless v norm and the rotary of q and k over separate "
|
||||
"q, k and v projections, in one dispatch; v from the raw k under v_from_k. n_head 0 "
|
||||
@@ -4553,6 +4579,12 @@ static const RadConstraint cRmsNormQuantI8[] = {
|
||||
static const RadConstraint cAddRmsNorm[] = {
|
||||
C_GE("n", 1), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cKvLenTrim[] = {
|
||||
C_GE("trim", 0), C_LE("max_seqs", 64),
|
||||
};
|
||||
static const RadConstraint cPrefetch[] = {
|
||||
C_GE("bytes", 1),
|
||||
};
|
||||
static const RadConstraint cQkvNormRope[] = {
|
||||
C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"),
|
||||
};
|
||||
@@ -4970,6 +5002,13 @@ static const RadConstraint cLogitsGemmFp8[] = { C_DIV("n_embd", 128), C_IN("dtyp
|
||||
/* No tunable axes. */
|
||||
#define NOTUNE nullptr, 0, nullptr
|
||||
|
||||
/* The prefetch's workgroups. It runs beside a collective or a latency-bound kernel and should fill
|
||||
* that window's memory bandwidth without taking the compute units the other lane needs. */
|
||||
static const int64_t kPrefetchNb[] = { 64, 32, 128, 256, 16, 24, 48 };
|
||||
static const RadTunable tPrefetch[] = {
|
||||
{ "nb", kPrefetchNb, NELEM(kPrefetchNb), 64, "workgroups of 256 lanes reading the weight" },
|
||||
};
|
||||
|
||||
/* ---- image generation ------------------------------------------------------------------- */
|
||||
/* Rows read 16 bytes at a time, so the widths are whole eights. */
|
||||
static const RadConstraint cGenRows8[] = { C_IN("dtype", "bf16"), C_DIV("n", 8) };
|
||||
@@ -7837,6 +7876,24 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, nullptr, r4d_rad_add_rmsnorm, nullptr, nullptr, nullptr,
|
||||
r4d_shape_add_rmsnorm, nullptr, r4d_fuse_add_rmsnorm },
|
||||
|
||||
{ "kv_len_trim", "kv_len_trim", "misc",
|
||||
"a batch's per-sequence context lengths less a runtime trim, one workgroup",
|
||||
"at most 64 sequences; the trim is the extent of `tail`",
|
||||
"int32 in, int32 out, clamped at zero",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cKvLenTrim), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_kv_len_trim, nullptr, nullptr, nullptr, nullptr, nullptr },
|
||||
|
||||
/* Reads its weight's stored bytes, whatever form the weight's GEMM gave them (RAD_LAYOUT_ANY). */
|
||||
{ "prefetch", "prefetch", "misc",
|
||||
"read a weight's leading bytes, 16 a lane over 64 workgroups, so the next kernel streaming the "
|
||||
"weight finds them in the 64 MB on-die cache; meant for a second lane beside a collective",
|
||||
"any weight, any stored form; `bytes` clamped to what the tensor states",
|
||||
"any",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cPrefetch), ROW(tPrefetch), nullptr,
|
||||
nullptr, nullptr, r4d_rad_prefetch, nullptr, r4d_rad_layout_any, nullptr, nullptr, nullptr },
|
||||
|
||||
{ "gelu_mul_quant_i8", "gelu_mul_quant_i8", "quant",
|
||||
"gelu(gate) * up, the tanh form, and quant_act_i8's quantiser in one pass over the row",
|
||||
"n a multiple of 16 and n*2 bytes within LDS; one workgroup per row",
|
||||
@@ -9084,6 +9141,52 @@ extern "C" int rad_kernel_concurrent(int i) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Which rows can chain (RadKernelChainFn, rad_abi.h): every kernel their launch emits has a
|
||||
* chained form (r4d_chain.h) the launch selects from the `chain` parameter. A row joins this list
|
||||
* only once all of its kernels have one. */
|
||||
extern "C" int rad_kernel_chain(int i) {
|
||||
const RadKernelInfo* k = rad_kernel_at(i);
|
||||
if (!k) return 0;
|
||||
static const char* const kChained[] = {
|
||||
"gemm_w4a8_nt_m64", "gelu_mul_quant_i8", "qkv_norm_rope_bf16",
|
||||
"qkv_norm_rope_kv_store_fp8", "qkv_norm_rope_kv_store_bf16",
|
||||
/* the split-KV decode and its merge (r4d_decode_launch_win); their prefill kernel stays
|
||||
* plain, and the backend chains only the kernels named r4dchain* */
|
||||
"attn_decode_h256_gqa2_fp8kv", "attn_decode_h256_gqa2_bf16kv",
|
||||
"attn_qrow_decode_h256_gqa2_fp8kv", "attn_qrow_decode_h256_gqa2_bf16kv",
|
||||
/* the fused junction: its tail form (the two-shot with the junction after it) only */
|
||||
"ar_rmsnorm_quant_i8", "ar_rmsnorm_quant_i8_4rank",
|
||||
/* the 31B's full layers: the windowed attention and its merge (r4d_attn_paged_window.hip,
|
||||
* at decode heights) and the int8 quantiser before o_proj; h512 at every TP's gqa */
|
||||
"attn_qrow_h512_gqa2_fp8kv", "attn_qrow_h512_gqa2_bf16kv",
|
||||
"attn_qrow_h512_gqa4_fp8kv", "attn_qrow_h512_gqa4_bf16kv",
|
||||
"attn_qrow_h512_gqa8_fp8kv", "attn_qrow_h512_gqa8_bf16kv",
|
||||
"quant_act_i8",
|
||||
/* DFlash2's query and context passes: the narrow fp8 GEMMs (the gated gate_up among
|
||||
* them), the activation quantiser, the norms, the conv projection, the opening
|
||||
* convolution and the verify-height reductions */
|
||||
"gemm_fp8a8_nt_m16", "gemm_fp8a8_gated_nt_m16",
|
||||
"gemm_i8a8_nt_m16", "quant_act_fp8", "rmsnorm_bf16", "add_rmsnorm_bf16",
|
||||
"gemm_bf16_nt_m16", "gemm_bf16_nt_m64", "dflash_conv_t2_g16_bf16",
|
||||
"ar_oneshot_4rank_exact", "ar_twoshot_4rank_exact",
|
||||
/* the decode tail: the embedding, the sampled rows' gather, the lm_head's WMMA pass (the
|
||||
* matvec below three rows stays plain) and the soft-cap */
|
||||
"embed_lookup_bf16", "gather_rows_bf16", "logits_gemm_fp8", "logits_gemm_i8",
|
||||
"logit_softcap_bf16", "logit_softcap_f32",
|
||||
/* the vocab-parallel sampler's candidate chain (temperature, top-k, the gathered sets'
|
||||
* merge, the pick) and its all-gather, and DFlash2's draft head, row top-k, merge and
|
||||
* selector */
|
||||
"sample_temp_f32", "sample_topk_f32", "sample_merge_topk_f32", "sample_pick_f32",
|
||||
"ar_gather_4rank", "gemm_w8a8_nt_m64", "rowtopk_bf16", "rowtopk_merge",
|
||||
"dflash_select_bf16",
|
||||
/* the weight read beside a collective (its blocks add before reading, r4d_prefetch.hip) */
|
||||
"prefetch",
|
||||
};
|
||||
for (const char* p : kChained)
|
||||
if (std::strcmp(k->name, p) == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Which rows are collectives (rad_abi.h): every row whose init builds the all-reduce family's
|
||||
* exchange buffers, peer flags and handshake (standalone all-reduces and gathers, and norms and hc
|
||||
* writes with one folded in), plus each `_host` twin. Keyed on the init, since a cross-rank kernel
|
||||
@@ -9221,6 +9324,9 @@ extern "C" void r4d_cfg_ar(const RadArgs* a, R4dArCfg* out) {
|
||||
extern "C" int r4d_cfg_ar_tail(const RadArgs* a) {
|
||||
return TUNE(a, tArQ84, "tail");
|
||||
}
|
||||
extern "C" int r4d_cfg_prefetch_nb(const RadArgs* a) {
|
||||
return TUNE(a, tPrefetch, "nb");
|
||||
}
|
||||
extern "C" long r4d_cfg_ar_ts_min(const RadArgs* a) {
|
||||
return (long)tune_i(a, tAr, NELEM(tAr), "ts_min");
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_fp8_wmma.h"
|
||||
#include "r4d_fp8_lm.h"
|
||||
#include "r4d_chain.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
|
||||
@@ -120,8 +121,10 @@ __device__ __forceinline__ unsigned long long tk_round(unsigned long long* t) {
|
||||
return m;
|
||||
}
|
||||
|
||||
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. A wave past the
|
||||
// chunks returns early; there is no barrier in it.
|
||||
template <int PT>
|
||||
__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stage1_kernel(
|
||||
__device__ __forceinline__ void r4d_rowtopk_stage1_body(
|
||||
const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P,
|
||||
int N, int RC, int NCH, int CH) {
|
||||
// WPB independent waves per block, each on its own chunk, sharing nothing. Grouping them only
|
||||
@@ -179,6 +182,20 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stag
|
||||
if (lane == 0) out[r] = w;
|
||||
}
|
||||
}
|
||||
template <int PT>
|
||||
__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stage1_kernel(
|
||||
const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P,
|
||||
int N, int RC, int NCH, int CH) {
|
||||
r4d_rowtopk_stage1_body<PT>(Y, P, N, RC, NCH, CH);
|
||||
}
|
||||
template <int PT>
|
||||
__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4dchain_rowtopk_stage1(
|
||||
const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P,
|
||||
int N, int RC, int NCH, int CH) {
|
||||
r4d_chain_wait();
|
||||
r4d_rowtopk_stage1_body<PT>(Y, P, N, RC, NCH, CH);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
// `off` is the first global column this rank's plane stands for, and `OP` the optional (id, value)
|
||||
// pair plane an all-gather moves: eight bytes an entry, an int32 id in the first float slot, the
|
||||
@@ -188,7 +205,8 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stag
|
||||
// An empty slot is not token `off`. A chunk that ran out of candidates leaves a zero key; OI gets
|
||||
// column 0 for it, without the offset, so a pad cannot look like this rank's first real token. The
|
||||
// pair plane writes -1, the sentinel the merge drops (not -INFINITY, a valid masked logit).
|
||||
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel(
|
||||
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
|
||||
__device__ __forceinline__ void r4d_rowtopk_stage2_body(
|
||||
const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI,
|
||||
float* __restrict__ OP, int off, int R, int n) {
|
||||
const int m = blockIdx.x;
|
||||
@@ -220,6 +238,18 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel(
|
||||
}
|
||||
}
|
||||
}
|
||||
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel(
|
||||
const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI,
|
||||
float* __restrict__ OP, int off, int R, int n) {
|
||||
r4d_rowtopk_stage2_body(P, OV, OI, OP, off, R, n);
|
||||
}
|
||||
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_stage2(
|
||||
const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI,
|
||||
float* __restrict__ OP, int off, int R, int n) {
|
||||
r4d_chain_wait();
|
||||
r4d_rowtopk_stage2_body(P, OV, OI, OP, off, R, n);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
// Chunks are a multiple of eight columns so stage 1 stays on the vector load; the last one is
|
||||
// clamped to N rather than padded (a padded tail would need a mask per element). The caller sizes
|
||||
@@ -239,7 +269,7 @@ int r4d_rowtopk_bf16_chunks(int N, int NCH) {
|
||||
// so ranks can agree on a global top-R without gathering the plane.
|
||||
static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi, long outp,
|
||||
int M, int N, int R, int RC, int NCH, int PT1, int off,
|
||||
RadStream stream) {
|
||||
RadStream stream, bool chain = false) {
|
||||
int emit_rc = RAD_OK;
|
||||
// R <= PT2 is what makes stage 2 exact for any candidates; a real limit, so checked, not
|
||||
// clamped.
|
||||
@@ -248,7 +278,8 @@ static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi,
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const int CH = rowtopk_chunk_width(N, NCH);
|
||||
const int nch = (N + CH - 1) / CH;
|
||||
#define R4D_TK_S1(PT) emit_rc = R4D_EMIT(stream, (r4d_rowtopk_stage1_kernel<PT>), \
|
||||
#define R4D_TK_S1(PT) emit_rc = R4D_EMIT(stream, (chain ? r4dchain_rowtopk_stage1<PT> \
|
||||
: r4d_rowtopk_stage1_kernel<PT>), \
|
||||
dim3((nch + R4D_TOPK_WPB - 1) / R4D_TOPK_WPB, M), \
|
||||
dim3(R4D_TOPK_WAVE * R4D_TOPK_WPB), 0, \
|
||||
(const unsigned short*)y, (unsigned long long*)partial, N, RC, nch, CH)
|
||||
@@ -261,7 +292,8 @@ static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi,
|
||||
}
|
||||
#undef R4D_TK_S1
|
||||
if (emit_rc != RAD_OK) return emit_rc;
|
||||
return R4D_EMIT(stream, r4d_rowtopk_stage2_kernel, dim3(M), dim3(R4D_TOPK_WAVE), 0,
|
||||
return R4D_EMIT(stream, (chain ? r4dchain_rowtopk_stage2 : r4d_rowtopk_stage2_kernel), dim3(M),
|
||||
dim3(R4D_TOPK_WAVE), 0,
|
||||
(const unsigned long long*)partial, (float*)outv, (int*)outi,
|
||||
(float*)outp, off, R, nch * RC);
|
||||
}
|
||||
@@ -284,7 +316,8 @@ __device__ __forceinline__ unsigned long long tk_key_f32(float v, unsigned id) {
|
||||
return ((unsigned long long)u << 32) | (unsigned)(0xFFFFFFFFu - id);
|
||||
}
|
||||
|
||||
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel(
|
||||
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
|
||||
__device__ __forceinline__ void r4d_rowtopk_merge_body(
|
||||
const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) {
|
||||
const int m = blockIdx.x;
|
||||
const int lane = threadIdx.x;
|
||||
@@ -309,6 +342,16 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel(
|
||||
}
|
||||
}
|
||||
}
|
||||
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel(
|
||||
const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) {
|
||||
r4d_rowtopk_merge_body(G, OV, OI, R, n);
|
||||
}
|
||||
__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_merge(
|
||||
const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) {
|
||||
r4d_chain_wait();
|
||||
r4d_rowtopk_merge_body(G, OV, OI, R, n);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
// ============================================================== logit_rerank
|
||||
//
|
||||
@@ -490,9 +533,11 @@ extern "C" int r4d_rad_rowtopk(const RadArgs* a, RadStream stream) {
|
||||
if (r4d_numel(pairs) < M * R * 2) return R4D_NO(RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* The chained forms at decode heights, where the row resolved with `chain`. */
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return rowtopk_bf16_sharded_emit(r4d_addr(x), (long)(uintptr_t)a->scratch, r4d_addr(val),
|
||||
r4d_addr(idx), pairs ? r4d_addr(pairs) : 0,
|
||||
(int)M, (int)N, (int)R, RC, NCH, PT1, (int)off, stream);
|
||||
(int)M, (int)N, (int)R, RC, NCH, PT1, (int)off, stream, ch);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ row_topk_merge
|
||||
@@ -519,7 +564,8 @@ extern "C" int r4d_rad_rowtopk_merge(const RadArgs* a, RadStream s) {
|
||||
if (r4d_numel(idx) < M * R || r4d_numel(val) < M * R) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* R <= PT2 makes the merge exact for any candidates (one lane can hold the whole answer). */
|
||||
return R4D_EMIT(s, r4d_rowtopk_merge_kernel, dim3((unsigned)M),
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return R4D_EMIT(s, (ch ? r4dchain_rowtopk_merge : r4d_rowtopk_merge_kernel), dim3((unsigned)M),
|
||||
dim3(R4D_TOPK_WAVE), 0, (const float*)g->data, (float*)val->data,
|
||||
(int*)idx->data, (int)R, (int)(W * R));
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_chain.h"
|
||||
|
||||
#include <cfloat>
|
||||
|
||||
@@ -140,7 +141,8 @@ __device__ __forceinline__ float block_max(float v, float* lds) {
|
||||
// ---------------------------------------------------------------------------- sample_temp
|
||||
// ref_sample_temp. temp <= 0 leaves the row alone: greedy is `sample_argmax`, and a temperature of
|
||||
// zero silently meaning something else would make the chain unreadable.
|
||||
__global__ __launch_bounds__(kThreads) void temp_kernel(
|
||||
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
|
||||
__device__ __forceinline__ void temp_body(
|
||||
float* __restrict__ lg, const SP* __restrict__ sp, uint32_t n_vocab, uint32_t lg_ld) {
|
||||
const uint32_t m = blockIdx.x;
|
||||
const float t = sp[m].temp;
|
||||
@@ -150,6 +152,16 @@ __global__ __launch_bounds__(kThreads) void temp_kernel(
|
||||
for (uint32_t i = threadIdx.x + blockIdx.y * kThreads; i < n_vocab; i += kThreads * gridDim.y)
|
||||
row[i] *= inv;
|
||||
}
|
||||
__global__ __launch_bounds__(kThreads) void temp_kernel(
|
||||
float* __restrict__ lg, const SP* __restrict__ sp, uint32_t n_vocab, uint32_t lg_ld) {
|
||||
temp_body(lg, sp, n_vocab, lg_ld);
|
||||
}
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_sample_temp(
|
||||
float* __restrict__ lg, const SP* __restrict__ sp, uint32_t n_vocab, uint32_t lg_ld) {
|
||||
r4d_chain_wait();
|
||||
temp_body(lg, sp, n_vocab, lg_ld);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- sample_mask
|
||||
// ref_sample_mask. A set bit means allowed: the mask is the grammar's admissible set. Word w bit b
|
||||
@@ -461,7 +473,9 @@ __device__ uint32_t radix_select(const float* __restrict__ row, uint32_t n, uint
|
||||
return prefix;
|
||||
}
|
||||
|
||||
__global__ __launch_bounds__(kTopkThreads) void topk_kernel(
|
||||
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. A greedy row's whole
|
||||
// block returns early, together.
|
||||
__device__ __forceinline__ void topk_body(
|
||||
const float* __restrict__ lg, const SP* __restrict__ sp,
|
||||
int32_t* __restrict__ ci, float* __restrict__ cv, uint32_t* __restrict__ pr,
|
||||
uint32_t n_vocab, uint32_t n_cand, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld,
|
||||
@@ -630,6 +644,22 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel(
|
||||
}
|
||||
}
|
||||
}
|
||||
__global__ __launch_bounds__(kTopkThreads) void topk_kernel(
|
||||
const float* __restrict__ lg, const SP* __restrict__ sp,
|
||||
int32_t* __restrict__ ci, float* __restrict__ cv, uint32_t* __restrict__ pr,
|
||||
uint32_t n_vocab, uint32_t n_cand, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld,
|
||||
uint32_t pr_ld, int32_t vocab_off, uint32_t pad) {
|
||||
topk_body(lg, sp, ci, cv, pr, n_vocab, n_cand, lg_ld, ci_ld, cv_ld, pr_ld, vocab_off, pad);
|
||||
}
|
||||
__global__ __launch_bounds__(kTopkThreads) void r4dchain_sample_topk(
|
||||
const float* __restrict__ lg, const SP* __restrict__ sp,
|
||||
int32_t* __restrict__ ci, float* __restrict__ cv, uint32_t* __restrict__ pr,
|
||||
uint32_t n_vocab, uint32_t n_cand, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld,
|
||||
uint32_t pr_ld, int32_t vocab_off, uint32_t pad) {
|
||||
r4d_chain_wait();
|
||||
topk_body(lg, sp, ci, cv, pr, n_vocab, n_cand, lg_ld, ci_ld, cv_ld, pr_ld, vocab_off, pad);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- sample_logprobs
|
||||
// ref_sample_logprobs. For a row with RAD_SP_LOGPROBS: [max, sum of exp(l - max), k (id, logit)
|
||||
@@ -909,7 +939,9 @@ __global__ __launch_bounds__(kThreads) void narrow_kernel(
|
||||
// the comparison never chooses one, and the fallback must not either.
|
||||
//
|
||||
// A greedy row is not touched: its token is the argmax's, written before the chain ran.
|
||||
__global__ __launch_bounds__(kThreads) void pick_kernel(
|
||||
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. Its returns are
|
||||
// a whole block's, or every thread but the walker's after the last barrier.
|
||||
__device__ __forceinline__ void pick_body(
|
||||
const int32_t* __restrict__ ci, const float* __restrict__ cv, const SP* __restrict__ sp,
|
||||
int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) {
|
||||
__shared__ float red[kWaves];
|
||||
@@ -947,6 +979,18 @@ __global__ __launch_bounds__(kThreads) void pick_kernel(
|
||||
}
|
||||
tok[m] = chosen >= 0 ? chosen : last;
|
||||
}
|
||||
__global__ __launch_bounds__(kThreads) void pick_kernel(
|
||||
const int32_t* __restrict__ ci, const float* __restrict__ cv, const SP* __restrict__ sp,
|
||||
int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) {
|
||||
pick_body(ci, cv, sp, tok, n_cand, ci_ld, cv_ld);
|
||||
}
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_sample_pick(
|
||||
const int32_t* __restrict__ ci, const float* __restrict__ cv, const SP* __restrict__ sp,
|
||||
int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) {
|
||||
r4d_chain_wait();
|
||||
pick_body(ci, cv, sp, tok, n_cand, ci_ld, cv_ld);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- sample_merge_topk
|
||||
// The vocab-parallel merge. Each rank runs top-k over its own lm_head shard and the candidate sets
|
||||
@@ -956,7 +1000,8 @@ __global__ __launch_bounds__(kThreads) void pick_kernel(
|
||||
//
|
||||
// One block per row, with the top-k's packed (key, ~id) word, so descending order and the lower-id
|
||||
// tie rule come from the same code. n_in is world_size * n_cand, a few thousand.
|
||||
__global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel(
|
||||
// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below.
|
||||
__device__ __forceinline__ void merge_topk_body(
|
||||
const uint32_t* __restrict__ gt, const SP* __restrict__ sp,
|
||||
int32_t* __restrict__ ci, float* __restrict__ cv,
|
||||
uint32_t n_in, uint32_t n_cand, uint32_t gt_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pad) {
|
||||
@@ -1020,6 +1065,20 @@ __global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel(
|
||||
ov[r] = __builtin_bit_cast(float, (key & 0x80000000u) ? (key & 0x7fffffffu) : ~key);
|
||||
}
|
||||
}
|
||||
__global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel(
|
||||
const uint32_t* __restrict__ gt, const SP* __restrict__ sp,
|
||||
int32_t* __restrict__ ci, float* __restrict__ cv,
|
||||
uint32_t n_in, uint32_t n_cand, uint32_t gt_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pad) {
|
||||
merge_topk_body(gt, sp, ci, cv, n_in, n_cand, gt_ld, ci_ld, cv_ld, pad);
|
||||
}
|
||||
__global__ __launch_bounds__(kTopkThreads) void r4dchain_sample_merge_topk(
|
||||
const uint32_t* __restrict__ gt, const SP* __restrict__ sp,
|
||||
int32_t* __restrict__ ci, float* __restrict__ cv,
|
||||
uint32_t n_in, uint32_t n_cand, uint32_t gt_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pad) {
|
||||
r4d_chain_wait();
|
||||
merge_topk_body(gt, sp, ci, cv, n_in, n_cand, gt_ld, ci_ld, cv_ld, pad);
|
||||
r4d_chain_done();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -1031,12 +1090,13 @@ __global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel(
|
||||
static uint32_t host_pow2(uint32_t v) { uint32_t p = 1; while (p < v) p <<= 1; return p; }
|
||||
|
||||
static int r4d_sample_temp_f32(long lg, long params, int M, int n_vocab, int lg_ld,
|
||||
long stream) {
|
||||
long stream, bool chain = false) {
|
||||
if (!lg || !params) return R4D_NO(RAD_E_INVAL);
|
||||
if (M <= 0 || n_vocab <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!lg_ld) lg_ld = n_vocab;
|
||||
const uint32_t gy = ((uint32_t)n_vocab + kThreads - 1) / kThreads;
|
||||
hipLaunchKernelGGL(temp_kernel, dim3((uint32_t)M, gy > 256u ? 256u : gy), dim3(kThreads), 0,
|
||||
hipLaunchKernelGGL((chain ? r4dchain_sample_temp : temp_kernel),
|
||||
dim3((uint32_t)M, gy > 256u ? 256u : gy), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (float*)lg, (const SP*)params,
|
||||
(uint32_t)n_vocab, (uint32_t)lg_ld);
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
|
||||
@@ -1120,7 +1180,7 @@ static int r4d_sample_logprobs_f32(long lg, long params, long stats, int M, int
|
||||
static int r4d_sample_topk_f32(long lg, long params, long cand_idx, long cand_val, long pairs,
|
||||
int M, int n_vocab, int n_cand,
|
||||
int lg_ld, int ci_ld, int cv_ld, int pr_ld, int vocab_off,
|
||||
long stream) {
|
||||
long stream, bool chain = false) {
|
||||
if (!lg || !params || !cand_idx || !cand_val) return R4D_NO(RAD_E_INVAL);
|
||||
if (M <= 0 || n_vocab <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
if ((uint32_t)n_cand > kMaxCand) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -1129,7 +1189,8 @@ static int r4d_sample_topk_f32(long lg, long params, long cand_idx, long cand_va
|
||||
if (!cv_ld) cv_ld = n_cand;
|
||||
if (!pr_ld) pr_ld = 2 * n_cand;
|
||||
const uint32_t pad = host_pow2((uint32_t)n_cand);
|
||||
hipLaunchKernelGGL(topk_kernel, dim3((uint32_t)M), dim3(kTopkThreads),
|
||||
hipLaunchKernelGGL((chain ? r4dchain_sample_topk : topk_kernel), dim3((uint32_t)M),
|
||||
dim3(kTopkThreads),
|
||||
pad * sizeof(unsigned long long), (hipStream_t)stream,
|
||||
(const float*)lg, (const SP*)params, (int32_t*)cand_idx, (float*)cand_val,
|
||||
(uint32_t*)pairs,
|
||||
@@ -1154,12 +1215,14 @@ static int r4d_sample_narrow_f32(long cand_idx, long cand_val, long params, int
|
||||
}
|
||||
|
||||
static int r4d_sample_pick_f32(long cand_idx, long cand_val, long params, long tok,
|
||||
int M, int n_cand, int ci_ld, int cv_ld, long stream) {
|
||||
int M, int n_cand, int ci_ld, int cv_ld, long stream,
|
||||
bool chain = false) {
|
||||
if (!cand_idx || !cand_val || !params || !tok) return R4D_NO(RAD_E_INVAL);
|
||||
if (M <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!ci_ld) ci_ld = n_cand;
|
||||
if (!cv_ld) cv_ld = n_cand;
|
||||
hipLaunchKernelGGL(pick_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
hipLaunchKernelGGL((chain ? r4dchain_sample_pick : pick_kernel), dim3((uint32_t)M),
|
||||
dim3(kThreads), 0, (hipStream_t)stream,
|
||||
(const int32_t*)cand_idx, (const float*)cand_val, (const SP*)params,
|
||||
(int32_t*)tok, (uint32_t)n_cand, (uint32_t)ci_ld, (uint32_t)cv_ld);
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
|
||||
@@ -1167,7 +1230,8 @@ static int r4d_sample_pick_f32(long cand_idx, long cand_val, long params, long t
|
||||
|
||||
static int r4d_sample_merge_topk_f32(long gathered, long params, long cand_idx, long cand_val,
|
||||
int M, int n_in, int n_cand,
|
||||
int gt_ld, int ci_ld, int cv_ld, long stream) {
|
||||
int gt_ld, int ci_ld, int cv_ld, long stream,
|
||||
bool chain = false) {
|
||||
if (!gathered || !params || !cand_idx || !cand_val) return R4D_NO(RAD_E_INVAL);
|
||||
if (M <= 0 || n_in <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
if ((uint32_t)n_in > kMaxCand) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -1175,7 +1239,8 @@ static int r4d_sample_merge_topk_f32(long gathered, long params, long cand_idx,
|
||||
if (!ci_ld) ci_ld = n_cand;
|
||||
if (!cv_ld) cv_ld = n_cand;
|
||||
const uint32_t pad = host_pow2((uint32_t)n_in);
|
||||
hipLaunchKernelGGL(merge_topk_kernel, dim3((uint32_t)M), dim3(kTopkThreads),
|
||||
hipLaunchKernelGGL((chain ? r4dchain_sample_merge_topk : merge_topk_kernel), dim3((uint32_t)M),
|
||||
dim3(kTopkThreads),
|
||||
pad * sizeof(unsigned long long), (hipStream_t)stream,
|
||||
(const uint32_t*)gathered, (const SP*)params,
|
||||
(int32_t*)cand_idx, (float*)cand_val,
|
||||
@@ -1243,8 +1308,10 @@ extern "C" int r4d_rad_sample_temp(const RadArgs* a, RadStream s) {
|
||||
R4D_NEED(logits_of(a, &lg, &M, &nv, &ld));
|
||||
const RadTensor* pr = r4d_opt(a, V_PARAMS);
|
||||
R4D_NEED(params_ok(pr, M));
|
||||
/* The chained form at decode heights, where the row resolved with `chain`. */
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return r4d_sample_temp_f32(r4d_addr(lg), r4d_addr(pr), (int)M, (int)nv, (int)ld,
|
||||
(long)(uintptr_t)s);
|
||||
(long)(uintptr_t)s, ch);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_sample_mask(const RadArgs* a, RadStream s) {
|
||||
@@ -1378,10 +1445,11 @@ extern "C" int r4d_rad_sample_topk(const RadArgs* a, RadStream s) {
|
||||
}
|
||||
const long long voff = r4d_pgeti_or(a->p, a->n_p, "vocab_off", 0);
|
||||
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return r4d_sample_topk_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(ci), r4d_addr(cv),
|
||||
pp ? r4d_addr(pp) : 0,
|
||||
(int)M, (int)nv, (int)n_cand, (int)ld, (int)ci_ld, (int)cv_ld,
|
||||
(int)pr_ld, (int)voff, (long)(uintptr_t)s);
|
||||
(int)pr_ld, (int)voff, (long)(uintptr_t)s, ch);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the narrowing stages */
|
||||
@@ -1439,9 +1507,10 @@ extern "C" int r4d_rad_sample_pick(const RadArgs* a, RadStream s) {
|
||||
if (M <= 0 || Mv < M || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE);
|
||||
R4D_NEED(params_ok(pr, M));
|
||||
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return r4d_sample_pick_f32(r4d_addr(ci), r4d_addr(cv), r4d_addr(pr), r4d_addr(tok),
|
||||
(int)M, (int)n_cand, (int)ci_ld, (int)cv_ld,
|
||||
(long)(uintptr_t)s);
|
||||
(long)(uintptr_t)s, ch);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ merge_topk */
|
||||
@@ -1474,7 +1543,8 @@ extern "C" int r4d_rad_sample_merge_topk(const RadArgs* a, RadStream s) {
|
||||
const long long n_in = per_row / 2;
|
||||
if (n_in <= 0 || n_in > (int)kMaxCand) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
|
||||
return r4d_sample_merge_topk_f32(r4d_addr(gt), r4d_addr(pr), r4d_addr(ci), r4d_addr(cv),
|
||||
(int)M, (int)n_in, (int)n_cand, (int)per_row, (int)ci_ld,
|
||||
(int)cv_ld, (long)(uintptr_t)s);
|
||||
(int)cv_ld, (long)(uintptr_t)s, ch);
|
||||
}
|
||||
@@ -764,6 +764,7 @@ static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int6
|
||||
run_case(r, ts, ps);
|
||||
}
|
||||
|
||||
|
||||
static void gemm_case(const Plugin& pl, const char* name, const char* dtype, int64_t M,
|
||||
int64_t N, int64_t K, uint32_t adt, int need_ascale, int need_asum,
|
||||
int need_bref, int64_t wbytes, int64_t sbytes) {
|
||||
@@ -940,6 +941,102 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8
|
||||
for (int64_t d = 0; d < head_dim; ++d) out[d] *= inv;
|
||||
}
|
||||
|
||||
/* kv_len_trim takes its trim from `tail`'s extent: a launch sees the op's ranged parameter at its
|
||||
* band's upper bound (RadArgs.p), so `trim` here is 4096 while the issued count, and `tail`'s
|
||||
* extent, is 1024. 90ede42 read the parameter, trimmed a 2048-key context to 0, and the attention
|
||||
* over slice A's rows wrote nothing. */
|
||||
static void kv_len_trim_case(const Plugin& pl) {
|
||||
const char* name = "kv_len_trim";
|
||||
if (!sel(name)) return;
|
||||
const RadKernelInfo* r = find(pl, name);
|
||||
if (!r) { ok(name, false, "row absent"); return; }
|
||||
const std::vector<int32_t> used = { 2048, 1500, 1024, 7 };
|
||||
void* d_out = dalloc(16);
|
||||
if (!d_out) { ok(name, false, "hipMalloc failed"); return; }
|
||||
std::vector<RadTensor> ts = {
|
||||
TI32({ 4 }, used),
|
||||
TI32({ 1024 }, iota_i32(1024)),
|
||||
T(d_out, RAD_I32, { 4 }),
|
||||
};
|
||||
std::vector<RadParam> ps = { PI("trim", 4096), PI("max_seqs", 4) };
|
||||
run_case(r, ts, ps);
|
||||
int32_t h[4] = { -1, -1, -1, -1 };
|
||||
st_memcpy(h, d_out, sizeof h, hipMemcpyDeviceToHost);
|
||||
const bool good = h[0] == 1024 && h[1] == 476 && h[2] == 0 && h[3] == 0;
|
||||
ok("kv_len_trim: the trim is tail's extent, not the collapsed parameter", good,
|
||||
good ? std::string() : "out " + std::to_string(h[0]) + " " + std::to_string(h[1]) + " " +
|
||||
std::to_string(h[2]) + " " + std::to_string(h[3]) +
|
||||
", want 1024 476 0 0");
|
||||
}
|
||||
|
||||
/* An attention over a slice of a step's rows against the whole step's (the 31B's prefill overlap,
|
||||
* attention per slice): one sequence, `nt` query rows ending a context of `ctx`, run whole and as
|
||||
* rows [0, cut) with seqused ctx - (T - cut) and rows [cut, nt) with seqused ctx. Every output
|
||||
* byte must match, since each row attends to the same keys. Reports the first differing row. */
|
||||
static void attn_slice_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa,
|
||||
int64_t kv_heads, int64_t nt, int64_t cut, int64_t ctx, int window) {
|
||||
if (!sel(name) && !sel("attn_slice")) return;
|
||||
const RadKernelInfo* r = find(pl, name);
|
||||
if (!r) { ok(name, false, "row absent"); return; }
|
||||
const int64_t bs = 16, q_heads = kv_heads * gqa;
|
||||
const int64_t blocks = (ctx + bs - 1) / bs;
|
||||
const bool fp8 = std::strstr(name, "fp8kv") != nullptr;
|
||||
const uint32_t kvdt = fp8 ? RAD_F8E4M3 : RAD_BF16;
|
||||
const int64_t ew = fp8 ? 1 : 2;
|
||||
const int64_t qn = nt * q_heads * head_dim, kvn = blocks * kv_heads * bs * 2 * head_dim;
|
||||
std::vector<uint16_t> hq((size_t)qn);
|
||||
for (int64_t i = 0; i < qn; ++i) hq[(size_t)i] = st_rand_bf16((uint32_t)i);
|
||||
std::vector<uint8_t> hkv((size_t)(kvn * ew));
|
||||
if (fp8) for (int64_t i = 0; i < kvn; ++i) hkv[(size_t)i] = st_rand_e4m3((uint32_t)i);
|
||||
else for (int64_t i = 0; i < kvn; ++i) ((uint16_t*)hkv.data())[i] = st_rand_bf16((uint32_t)i + 7u);
|
||||
void* d_q = dalloc((size_t)qn * 2);
|
||||
void* d_kv = dalloc((size_t)(kvn * ew));
|
||||
void* d_ow = dalloc((size_t)qn * 2);
|
||||
void* d_os = dalloc((size_t)qn * 2);
|
||||
if (!d_q || !d_kv || !d_ow || !d_os) { ok(name, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_q, hq.data(), hq.size() * 2, hipMemcpyHostToDevice);
|
||||
st_memcpy(d_kv, hkv.data(), hkv.size(), hipMemcpyHostToDevice);
|
||||
auto run = [&](int64_t r0, int64_t n, int32_t used, void* out) {
|
||||
std::vector<RadTensor> ts = {
|
||||
T((char*)d_q + (size_t)(r0 * q_heads * head_dim * 2), RAD_BF16, { n, q_heads, head_dim }),
|
||||
T(d_kv, kvdt, { blocks, kv_heads, bs, 2 * head_dim }),
|
||||
TI32({ 1, blocks }, iota_i32(blocks)),
|
||||
TI32({ 1 }, rep_i32(1, used)),
|
||||
TF32({ 1, kv_heads }, 1.0f),
|
||||
TF32({ 1, kv_heads }, 1.0f),
|
||||
T(nullptr, RAD_I32, { 2 }),
|
||||
T((char*)out + (size_t)(r0 * q_heads * head_dim * 2), RAD_BF16, { n, q_heads, head_dim }),
|
||||
};
|
||||
if (!fp8) { absent(ts[4]); absent(ts[5]); }
|
||||
absent(ts[6]);
|
||||
std::vector<RadParam> ps = {
|
||||
PI("q_len", n), PI("head_dim", head_dim), PI("gqa", gqa), PI("block_size", bs),
|
||||
PI("causal", 1), PI("window", window), PS("q_dtype", "bf16"),
|
||||
PS("kv_dtype", fp8 ? "fp8_e4m3" : "bf16"),
|
||||
};
|
||||
run_case(r, ts, ps);
|
||||
};
|
||||
st_memset(d_ow, 0, (size_t)qn * 2);
|
||||
st_memset(d_os, 0, (size_t)qn * 2);
|
||||
run(0, nt, (int32_t)ctx, d_ow);
|
||||
run(0, cut, (int32_t)(ctx - (nt - cut)), d_os);
|
||||
run(cut, nt - cut, (int32_t)ctx, d_os);
|
||||
std::vector<uint16_t> ow((size_t)qn), os((size_t)qn);
|
||||
st_memcpy(ow.data(), d_ow, ow.size() * 2, hipMemcpyDeviceToHost);
|
||||
st_memcpy(os.data(), d_os, os.size() * 2, hipMemcpyDeviceToHost);
|
||||
int64_t first = -1, ndiff = 0;
|
||||
const int64_t rowsz = q_heads * head_dim;
|
||||
for (int64_t i = 0; i < qn; ++i)
|
||||
if (ow[(size_t)i] != os[(size_t)i]) { if (first < 0) first = i / rowsz; ++ndiff; }
|
||||
std::string why;
|
||||
if (ndiff)
|
||||
why = std::to_string((long long)ndiff) + " elements differ, first at row " +
|
||||
std::to_string((long long)first);
|
||||
ok((std::string(name) + ": a slice's rows equal the whole step's, T " + std::to_string((long long)nt) +
|
||||
" cut " + std::to_string((long long)cut) + " ctx " + std::to_string((long long)ctx)).c_str(),
|
||||
ndiff == 0, why);
|
||||
}
|
||||
|
||||
/* Numeric attention check: fill q and the paged k/v with avalanche-random data, run the row, and
|
||||
* compare the bf16 output against the oracle above. A negative control corrupts part of the
|
||||
* reference and requires the comparison to fail. */
|
||||
@@ -23954,6 +24051,23 @@ static void device_phase(const Plugin& pl) {
|
||||
embed_lookup_q_case(pl);
|
||||
lora_case(pl);
|
||||
|
||||
/* --- a weight read into the cache (prefetch): it runs, and takes any stored form --- */
|
||||
if (sel("prefetch")) {
|
||||
const RadKernelInfo* r = find(pl, "prefetch");
|
||||
if (!r) {
|
||||
ok("prefetch", false, "row absent");
|
||||
} else {
|
||||
void* d = dalloc((size_t)1 << 20);
|
||||
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);
|
||||
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,
|
||||
"returned " + std::to_string(st));
|
||||
}
|
||||
}
|
||||
|
||||
/* --- the paged cache's write side --- */
|
||||
kv_store_case(pl, "kv_store_bf16", "bf16");
|
||||
kv_store_case(pl, "kv_store_bf16", "bf16", true);
|
||||
@@ -23997,6 +24111,14 @@ static void device_phase(const Plugin& pl) {
|
||||
/* Gemma 4 dense global: head_dim 512, full attention, on the windowed kernel (one row for every
|
||||
* q_len): a prefill-shaped launch (q_len 32) and a decode one (1); numeric checks follow. */
|
||||
attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1);
|
||||
/* The 31B's prefill overlap at tp 4: sliding h256 gqa 2 (4 kv heads a rank, window 1024) and
|
||||
* global h512 gqa 8 (1 kv head), a 2048-row chunk cut at 1024, first chunk and a later one. */
|
||||
kv_len_trim_case(pl);
|
||||
for (const int64_t ctx : { (int64_t)2048, (int64_t)4096 }) {
|
||||
attn_slice_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 4, 2048, 1024, ctx, 1024);
|
||||
attn_slice_case(pl, "attn_qrow_h512_gqa8_fp8kv", 512, 8, 1, 2048, 1024, ctx, 0);
|
||||
attn_slice_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 1, 2048, 1024, ctx, 0);
|
||||
}
|
||||
attn_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 1);
|
||||
attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0);
|
||||
attn_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0);
|
||||
|
||||
@@ -17,6 +17,7 @@ ABI_FIELD(RadArchProbe, gen_audio)
|
||||
ABI_FIELD(RadArchProbe, gen_ctx)
|
||||
ABI_FIELD(RadArchProbe, gen_video)
|
||||
ABI_FIELD(RadArchProbe, kv_quant_ok)
|
||||
ABI_FIELD(RadArchProbe, chain_pays)
|
||||
ABI_STRUCT(RadArgs)
|
||||
ABI_FIELD(RadArgs, t)
|
||||
ABI_FIELD(RadArgs, n_t)
|
||||
|
||||
@@ -341,6 +341,14 @@ extern "C" int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) {
|
||||
b->drafter_pos = pos_offset;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The core's chaining decision as the recorder answers it (it has no chaining backend): 0 unless a
|
||||
* test holds a ChainOn, to see where a plugin places work when launches chain. */
|
||||
static int g_chain_on = 0;
|
||||
extern "C" int rad_chain_on(void) { return g_chain_on; }
|
||||
struct ChainOn {
|
||||
explicit ChainOn(int on) { g_chain_on = on; }
|
||||
~ChainOn() { g_chain_on = 0; }
|
||||
};
|
||||
extern "C" int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
|
||||
if (!b || !d || !d->name || !d->modalities) return RAD_E_INVAL;
|
||||
if (d->modalities == RAD_MM_AUDIO) {
|
||||
|
||||
+222
-43
@@ -3515,15 +3515,19 @@ static std::vector<std::string> gemma4_w4_step(const std::set<std::string>& refu
|
||||
|
||||
/* At two ranks the all-reduce before each junction is folded into it; only the embedding's and
|
||||
* the last feed-forward's (which feeds the final norm, not a quantiser) remain standalone. Without
|
||||
* the fused collective, junctions keep their preceding all-reduces. */
|
||||
* the fused collective, junctions keep their preceding all-reduces. Beside each reduction a
|
||||
* prefetch of the next GEMM's weight (the lm_head after the last), and down_proj's beside the
|
||||
* attention (prefetch_beside). */
|
||||
TEST(a_gemma4_w4a8_step_at_two_ranks_folds_the_all_reduce_into_the_junction) {
|
||||
std::vector<std::string> want = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" };
|
||||
for (int l = 0; l < 12; ++l) {
|
||||
const bool global = (l + 1) % 6 == 0;
|
||||
for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q");
|
||||
for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q",
|
||||
"ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" })
|
||||
for (const char* s : { "prefetch", "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8",
|
||||
"gemm_nt_q", "prefetch", "ar_rmsnorm_quant_i8", "gemm_nt_q",
|
||||
"gelu_mul_quant_i8", "gemm_nt_q" })
|
||||
want.push_back(s);
|
||||
want.push_back("prefetch");
|
||||
if (l < 11) want.push_back("ar_rmsnorm_quant_i8");
|
||||
else for (const char* s : { "all_reduce", "rmsnorm", "add", "scale" }) want.push_back(s);
|
||||
}
|
||||
@@ -3535,10 +3539,12 @@ TEST(a_gemma4_w4a8_step_at_two_ranks_folds_the_all_reduce_into_the_junction) {
|
||||
for (int l = 0; l < 12; ++l) {
|
||||
const bool global = (l + 1) % 6 == 0;
|
||||
for (int i = 0; i < (global ? 2 : 3); ++i) plain.push_back("gemm_nt_q");
|
||||
for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q",
|
||||
"all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8",
|
||||
"gemm_nt_q", "all_reduce" })
|
||||
for (const char* s : { "prefetch", "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8",
|
||||
"gemm_nt_q", "prefetch", "all_reduce", "rmsnorm_quant_i8", "gemm_nt_q",
|
||||
"gelu_mul_quant_i8", "gemm_nt_q" })
|
||||
plain.push_back(s);
|
||||
plain.push_back("prefetch");
|
||||
plain.push_back("all_reduce");
|
||||
if (l < 11) plain.push_back("rmsnorm_quant_i8");
|
||||
else for (const char* s : { "rmsnorm", "add", "scale" }) plain.push_back(s);
|
||||
}
|
||||
@@ -3811,6 +3817,7 @@ TEST(gemma4_probe_names_the_heads_operating_depth) {
|
||||
CHECK_OK(gemma4_bf16::probe(&with, &p));
|
||||
CHECK_EQ(p.draft_depth, gemma4_bf16::kHeadDepth);
|
||||
CHECK_EQ(p.draft_depth_fixed, 0);
|
||||
CHECK_EQ(p.chain_pays, 0); /* chained launches never measured with the head */
|
||||
RadArchProbe q{};
|
||||
RadModelMeta without = gemma4_meta();
|
||||
CHECK_OK(gemma4_bf16::probe(&without, &q));
|
||||
@@ -4033,6 +4040,7 @@ TEST(gemma4_probe_names_the_dflash_blocks_depth) {
|
||||
CHECK_OK(gemma4::probe(&meta, &p));
|
||||
CHECK_EQ(p.draft_depth, 15);
|
||||
CHECK_EQ(p.draft_depth_fixed, 1);
|
||||
CHECK_EQ(p.chain_pays, 1); /* chained launches measured a gain with DFlash */
|
||||
|
||||
for (size_t i = 0; i < keys.size(); ++i)
|
||||
if (!std::strcmp(keys[i], "draft.architectures")) vals[i] = "[\"DFlash2DraftModel\"]";
|
||||
@@ -4610,30 +4618,56 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_
|
||||
const int L = 12;
|
||||
std::vector<std::string> folded = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" };
|
||||
std::vector<std::string> apart = folded;
|
||||
/* beside each reduction, up to a step of 16 rows: a prefetch (prefetch_beside) */
|
||||
auto pf = [](std::vector<std::string>& v, std::vector<std::string> s, bool next) {
|
||||
std::vector<std::string> out = { "prefetch" }; /* o_proj's, beside the attention */
|
||||
for (const auto& x : s) {
|
||||
if ((x == "ar_rmsnorm_quant_i8" || x == "all_reduce") && (next || &x != &s.back()))
|
||||
out.push_back("prefetch");
|
||||
out.push_back(x);
|
||||
}
|
||||
v.insert(v.end(), out.begin(), out.end());
|
||||
};
|
||||
std::vector<std::string> apart_tall = folded, folded_bare = folded;
|
||||
for (int l = 0; l < L; ++l) {
|
||||
const bool global = (l + 1) % 6 == 0;
|
||||
for (int i = 0; i < (global ? 2 : 3); ++i) { folded.push_back("gemm_nt_q"); apart.push_back("gemm_nt_q"); }
|
||||
for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q",
|
||||
"ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" })
|
||||
folded.push_back(s);
|
||||
for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q",
|
||||
"all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8",
|
||||
"gemm_nt_q", "all_reduce" })
|
||||
apart.push_back(s);
|
||||
for (int i = 0; i < (global ? 2 : 3); ++i)
|
||||
for (auto* v : { &folded, &apart, &apart_tall, &folded_bare }) v->push_back("gemm_nt_q");
|
||||
const std::vector<std::string> fs = { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8",
|
||||
"gemm_nt_q", "ar_rmsnorm_quant_i8", "gemm_nt_q",
|
||||
"gelu_mul_quant_i8", "gemm_nt_q" };
|
||||
const std::vector<std::string> as = { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8",
|
||||
"gemm_nt_q", "all_reduce", "rmsnorm_quant_i8",
|
||||
"gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q",
|
||||
"all_reduce" };
|
||||
pf(folded, fs, true);
|
||||
folded_bare.insert(folded_bare.end(), fs.begin(), fs.end());
|
||||
pf(apart, as, true);
|
||||
apart_tall.insert(apart_tall.end(), as.begin(), as.end());
|
||||
if (l < L - 1) {
|
||||
folded.push_back("prefetch");
|
||||
apart_tall.push_back("rmsnorm_quant_i8");
|
||||
folded_bare.push_back("ar_rmsnorm_quant_i8");
|
||||
folded.push_back("ar_rmsnorm_quant_i8");
|
||||
apart.push_back("rmsnorm_quant_i8");
|
||||
} else {
|
||||
for (const char* s : { "all_reduce", "rmsnorm", "add", "scale" }) folded.push_back(s);
|
||||
for (const char* s : { "rmsnorm", "add", "scale" }) apart.push_back(s);
|
||||
folded.push_back("prefetch"); /* the lm_head's */
|
||||
for (const char* s : { "all_reduce", "rmsnorm", "add", "scale" }) {
|
||||
folded.push_back(s);
|
||||
folded_bare.push_back(s);
|
||||
}
|
||||
for (const char* s : { "rmsnorm", "add", "scale" }) {
|
||||
apart.push_back(s);
|
||||
apart_tall.push_back(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) {
|
||||
folded.push_back(s);
|
||||
apart.push_back(s);
|
||||
}
|
||||
for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" })
|
||||
for (auto* v : { &folded, &apart, &apart_tall, &folded_bare }) v->push_back(s);
|
||||
/* a decode step folds */
|
||||
CHECK_EQ(join(gemma4_w4_step({}, 4)), join(folded));
|
||||
/* where the library refuses `prefetch`, no reads */
|
||||
CHECK_EQ(join(gemma4_w4_step({ "prefetch" }, 4)), join(folded_bare));
|
||||
|
||||
auto declare4 = [](RadBuilder& b) {
|
||||
const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128);
|
||||
@@ -4662,14 +4696,35 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_
|
||||
CHECK_EQ(fold_hi(b, &n_ar), 16);
|
||||
CHECK_EQ(n_ar, 2 * L - 1);
|
||||
|
||||
/* a verify's height folds (libr4d's tail form) and a step past 16 rows issues the pair */
|
||||
/* 20 MB of gate_up beside the attention's reduction and of the next layer's q beside the
|
||||
* feed-forward's, and 9 MB of down_proj beside the attention */
|
||||
int n_pf = 0, n_pf9 = 0;
|
||||
for (const auto& o : b.ops)
|
||||
if (o.op == "prefetch") {
|
||||
++n_pf;
|
||||
if (pint(&o, "bytes") == (int64_t)9 << 20) ++n_pf9;
|
||||
else CHECK_EQ(pint(&o, "bytes"), (int64_t)20 << 20);
|
||||
}
|
||||
CHECK_EQ(n_pf, 3 * L);
|
||||
CHECK_EQ(n_pf9, (int)L);
|
||||
|
||||
/* a verify's height folds (libr4d's tail form) and a step past 16 rows issues the pair; the
|
||||
* prefetches ride a decode step's (a verify's) 16 rows, never a prompt's rows and not a step
|
||||
* past 16 */
|
||||
const int32_t out[1] = { 127 };
|
||||
for (int rows : { 16, 128 }) {
|
||||
RadBatch tall = one_prompt(rows, out);
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 4; c.batch = &tall;
|
||||
gemma4_bf16::step(&c, &tall);
|
||||
CHECK(c.step_fail.empty());
|
||||
CHECK_EQ(join(issued_ops(b, c)), join(rows <= 16 ? folded : apart));
|
||||
/* a prompt's rows: no reads */
|
||||
CHECK_EQ(join(issued_ops(b, c)), join(rows <= 16 ? folded_bare : apart_tall));
|
||||
/* the same rows as a decode step (a verify's) take them, up to 16 */
|
||||
tall.phase = RAD_PHASE_DECODE;
|
||||
RadCtx d; d.b = &b; d.rank = 0; d.world = 4; d.batch = &tall;
|
||||
gemma4_bf16::step(&d, &tall);
|
||||
CHECK(d.step_fail.empty());
|
||||
CHECK_EQ(join(issued_ops(b, d)), join(rows <= 16 ? folded : apart_tall));
|
||||
}
|
||||
|
||||
|
||||
@@ -4841,6 +4896,7 @@ TEST(gemma4_31b_declares_dflash_as_a_block_drafter_past_its_trunk) {
|
||||
CHECK_OK(gemma4_bf16::probe(&meta, &p));
|
||||
CHECK_EQ(p.draft_depth, 15);
|
||||
CHECK_EQ(p.draft_depth_fixed, 1);
|
||||
CHECK_EQ(p.chain_pays, 1);
|
||||
|
||||
/* no speculation: no drafter, no taps */
|
||||
RadBuilder b0;
|
||||
@@ -5133,8 +5189,12 @@ TEST(a_gemma4_31b_prefill_step_runs_as_two_slices_with_its_reductions_on_the_sec
|
||||
RadBuilder b;
|
||||
CHECK_OK(model(b, false));
|
||||
CHECK(noted(b, "prefill overlap: a step of 1024 rows or more runs as two slices"));
|
||||
REQUIRE(b.concurrent.size() == 1);
|
||||
/* `h`, and slice A's context end a KV group the attention reads (per-slice
|
||||
* attention: the sliding and the global class) */
|
||||
REQUIRE(b.concurrent.size() == 3);
|
||||
CHECK_EQ(b.concurrent[0], (rad_buf)buf_named(b, "h"));
|
||||
CHECK_EQ(b.concurrent[1], (rad_buf)buf_named(b, "slice_used_0"));
|
||||
CHECK_EQ(b.concurrent[2], (rad_buf)buf_named(b, "slice_used_1"));
|
||||
RadBatch batch = one_prompt(k.T, out);
|
||||
RadCtx c;
|
||||
run(b, c, batch);
|
||||
@@ -5148,8 +5208,13 @@ TEST(a_gemma4_31b_prefill_step_runs_as_two_slices_with_its_reductions_on_the_sec
|
||||
if (i.lane != 1) continue;
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
REQUIRE(o != nullptr);
|
||||
if (o->op == "all_reduce") lane1.push_back(i.n);
|
||||
else ++other1;
|
||||
if (o->op == "all_reduce") {
|
||||
lane1.push_back(i.n);
|
||||
/* the narrow launch beside compute, not the wide one op_ar resolves to */
|
||||
CHECK_EQ(pint(o, "overlap"), 1);
|
||||
} else {
|
||||
++other1;
|
||||
}
|
||||
}
|
||||
CHECK_EQ(other1, 0);
|
||||
if (k.cut == 0) {
|
||||
@@ -5177,6 +5242,14 @@ TEST(a_gemma4_31b_prefill_step_runs_as_two_slices_with_its_reductions_on_the_sec
|
||||
CHECK(wc.step_fail.empty());
|
||||
for (const auto& i : wc.issues) CHECK_EQ(i.lane, 0);
|
||||
std::map<std::string, int64_t> sliced = rows_by_op(b, c, k.T), whole = rows_by_op(w, wc, k.T);
|
||||
if (k.cut) {
|
||||
/* attention once a slice, slice A's over its context end: one kv_len_trim a KV
|
||||
* group, which the whole step has no use for */
|
||||
CHECK_EQ((int)ns_of(b, c, "kv_len_trim").size(), 2);
|
||||
CHECK_EQ((int)ns_of(b, c, "attn_paged").size() + (int)ns_of(b, c, "attn_paged_qrow").size(),
|
||||
2 * (int)L);
|
||||
sliced.erase("kv_len_trim");
|
||||
}
|
||||
if (world == 2 && k.cut == 0) {
|
||||
/* At two ranks on the exact wire a step that runs whole folds all but two of its
|
||||
* reductions -- the embedding's and the last layer's feed-forward -- into its
|
||||
@@ -5190,21 +5263,53 @@ TEST(a_gemma4_31b_prefill_step_runs_as_two_slices_with_its_reductions_on_the_sec
|
||||
CHECK_EQ((int)ns_of(b, c, "cast").size(), k.cut ? 6 : 3); /* three taps, a slice each */
|
||||
}
|
||||
|
||||
/* a decode step runs whole: every reduction on lane 0, nothing on lane 1 */
|
||||
RadBuilder b;
|
||||
CHECK_OK(model(b, false));
|
||||
RadBatch d = decode_batch();
|
||||
RadCtx c;
|
||||
run(b, c, d);
|
||||
CHECK(c.step_fail.empty());
|
||||
CHECK(c.joins.empty());
|
||||
for (const auto& i : c.issues) CHECK_EQ(i.lane, 0);
|
||||
/* folded where the plugin declares the fold at this rank count (two ranks; four with the
|
||||
* four-rank junction), every junction but the last layer's feed-forward one */
|
||||
bool fold = false;
|
||||
for (const auto& o : b.ops) fold = fold || o.op == "ar_rmsnorm_quant_i8";
|
||||
CHECK(fold || world == 4);
|
||||
CHECK_EQ(count_issued(issued_ops(b, c), "ar_rmsnorm_quant_i8"), fold ? 2 * (int)L - 1 : 0);
|
||||
/* a library without kv_len_trim: the slices keep each layer's attention whole between them,
|
||||
* with only `h` out of the arena's sharing and the reductions still on lane 1 */
|
||||
{
|
||||
const int32_t out[1] = { 4095 };
|
||||
RadBuilder b;
|
||||
b.undeclared.insert("kv_len_trim");
|
||||
CHECK_OK(model(b, false));
|
||||
REQUIRE(b.concurrent.size() == 1);
|
||||
CHECK_EQ(b.concurrent[0], (rad_buf)buf_named(b, "h"));
|
||||
RadBatch batch = one_prompt(4096, out);
|
||||
RadCtx c;
|
||||
run(b, c, batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
CHECK_EQ(races(b, c), 0);
|
||||
CHECK(ns_of(b, c, "kv_len_trim").empty());
|
||||
CHECK_EQ((int)ns_of(b, c, "attn_paged").size() + (int)ns_of(b, c, "attn_paged_qrow").size(),
|
||||
(int)L);
|
||||
int lane1 = 0;
|
||||
for (const auto& i : c.issues) lane1 += i.lane == 1;
|
||||
CHECK_EQ(lane1, 4 * (int)L);
|
||||
}
|
||||
|
||||
/* a decode step runs whole: every reduction on lane 0; the prefetches beside them
|
||||
* (prefetch_beside) follow lane 0's GEMM before each -- on lane 0 itself where launches
|
||||
* chain (prefetch_lane0), else on lane 1 behind a join from that GEMM */
|
||||
for (const bool pf_lane0 : { false, true }) {
|
||||
const ChainOn chain(pf_lane0);
|
||||
RadBuilder b;
|
||||
CHECK_OK(model(b, false));
|
||||
RadBatch d = decode_batch();
|
||||
RadCtx c;
|
||||
run(b, c, d);
|
||||
CHECK(c.step_fail.empty());
|
||||
const std::vector<std::string> ops = issued_ops(b, c);
|
||||
int n_pf = 0;
|
||||
for (size_t i = 0; i < c.issues.size(); ++i) {
|
||||
const bool pf = ops[i] == "prefetch";
|
||||
CHECK_EQ(c.issues[i].lane, pf && !pf_lane0 ? 1 : 0);
|
||||
if (!pf) continue;
|
||||
++n_pf;
|
||||
CHECK(i > 0 && ops[i - 1] == "gemm_nt_q" && ordered(c, i - 1, i));
|
||||
}
|
||||
CHECK_EQ(n_pf, 3 * (int)L);
|
||||
CHECK_EQ((int)c.joins.size(), pf_lane0 ? 0 : n_pf);
|
||||
CHECK_EQ(races(b, c), 0);
|
||||
CHECK_EQ(count_issued(ops, "ar_rmsnorm_quant_i8"), 2 * (int)L - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* the overlap needs the fused junctions: a bf16 trunk keeps its chain and runs whole */
|
||||
@@ -5389,6 +5494,7 @@ TEST(gemma4_31b_declares_redhats_dflash2_from_the_speculators_layout) {
|
||||
CHECK_OK(gemma4_bf16::probe(&meta, &p));
|
||||
CHECK_EQ(p.draft_depth, 7);
|
||||
CHECK_EQ(p.draft_depth_fixed, 1);
|
||||
CHECK_EQ(p.chain_pays, 1); /* and with DFlash2 */
|
||||
|
||||
for (int world : { 1, 4 })
|
||||
for (int head8 = 0; head8 < 2; ++head8) {
|
||||
@@ -5516,6 +5622,74 @@ TEST(gemma4_31b_dflash2_folds_each_residual_add_into_the_next_norm) {
|
||||
}
|
||||
}
|
||||
|
||||
/* DFlash2's query pass reads the next GEMM's weight into the cache beside each of its all-reduces
|
||||
* (prefetch_beside, rad_arch.h): the layer's gate_up beside the attention's, the next layer's q --
|
||||
* after the last layer, the draft head -- beside the feed-forward's, and o's beside the attention,
|
||||
* 20 MB each, after the GEMM before it: on lane 0 where launches chain (prefetch_lane0), else on
|
||||
* lane 1 behind a join. One rank has no reduction to sit beside and declares none, and neither
|
||||
* does a library without `prefetch`. */
|
||||
TEST(gemma4_31b_dflash2_query_pass_prefetches_beside_its_all_reduces) {
|
||||
G431Df2 f;
|
||||
const RadModelMeta meta = f.meta();
|
||||
const int L = 5;
|
||||
for (int world : { 1, 4 })
|
||||
for (int k = 0; k < 4; ++k) {
|
||||
const int off = k & 1, pf_lane = k < 2 ? 1 : 0; /* lane 0 where launches chain */
|
||||
const ChainOn chain(pf_lane == 0);
|
||||
RadBuilder b;
|
||||
g431df2_encs(b, true);
|
||||
if (off) b.undeclared.insert("prefetch");
|
||||
RadBuildCtx ctx = build_ctx(0, world);
|
||||
ctx.max_tok = 2048;
|
||||
ctx.max_spec = 7;
|
||||
const int rc = gemma4_bf16::declare(&b, &meta, &ctx);
|
||||
REQUIRE_EQ(rc, RAD_OK);
|
||||
const auto qry = query_pass(b, 1, 8, 7);
|
||||
const auto v = run_passes(b, gemma4_bf16::step, { qry.get() }, 0, world);
|
||||
REQUIRE(steps_ok(v));
|
||||
const RadCtx& c = *v[0];
|
||||
const std::vector<std::string> ops = issued_ops(b, c);
|
||||
std::vector<std::string> read;
|
||||
for (size_t i = 0; i < c.issues.size(); ++i) {
|
||||
if (ops[i] != "prefetch") {
|
||||
CHECK_EQ(c.issues[i].lane, 0);
|
||||
continue;
|
||||
}
|
||||
CHECK_EQ(c.issues[i].lane, pf_lane);
|
||||
size_t g = i; /* the GEMM before this read (and any read issued with it) */
|
||||
while (g > 0 && ops[g - 1] == "prefetch") --g;
|
||||
CHECK(g > 0 && ops[g - 1] == "gemm_nt_q" &&
|
||||
ordered(c, g - 1, i));
|
||||
CHECK(i + 1 < ops.size() &&
|
||||
(ops[i + 1] == "all_reduce" || ops[i + 1] == "qkv_norm_rope_kv_store" ||
|
||||
ops[i + 1] == "prefetch"));
|
||||
const RecOp* o = b.op_of(c.issues[i].op);
|
||||
REQUIRE(o != nullptr && o->w.size() == 1);
|
||||
CHECK_EQ(pint(o, "bytes"), (int64_t)20 << 20);
|
||||
read.push_back(b.weights[o->w[0] - 1].name);
|
||||
}
|
||||
CHECK_EQ(races(b, c), 0);
|
||||
if (world == 1 || off) {
|
||||
CHECK(read.empty());
|
||||
continue;
|
||||
}
|
||||
/* a layer: o; the feed-forward's coefficient projection and gate_up; the next
|
||||
* layer's attention coefficient projection and q -- after the last, the draft head */
|
||||
REQUIRE_EQ((int)read.size(), 5 * L - 1);
|
||||
std::vector<std::string> want;
|
||||
for (int l = 0; l < L; ++l) {
|
||||
const std::string bl = "dflash.blk." + std::to_string(l) + ".";
|
||||
const std::string nx = "dflash.blk." + std::to_string(l + 1) + ".";
|
||||
for (const std::string& s : { bl + "attn_output", bl + "ffn_conv_proj",
|
||||
bl + "ffn_gate_up" })
|
||||
want.push_back(s);
|
||||
if (l + 1 < L) { want.push_back(nx + "attn_conv_proj"); want.push_back(nx + "attn_q"); }
|
||||
else want.push_back("dflash.draft_head");
|
||||
}
|
||||
for (size_t k = 0; k < want.size(); ++k) CHECK(read[k].find(want[k]) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Every engine step with RedHatAI's DFlash2 behind the trunk lints clean at one, two and four ranks:
|
||||
* decode, a mixed step, a prefill chunk, and a verify step with the drafter's context and query
|
||||
* passes behind it (block 8). */
|
||||
@@ -6106,6 +6280,7 @@ TEST(qwen35_fp8_dflash2_drafter_takes_a_power_of_two_block) {
|
||||
CHECK_OK(qwen35_fp8::probe(mk.meta(), &p));
|
||||
CHECK_EQ(p.draft_depth, 7);
|
||||
CHECK_EQ(p.draft_depth_fixed, 1);
|
||||
CHECK_EQ(p.chain_pays, 0); /* chained launches measured even here */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6342,6 +6517,7 @@ TEST(gemma3_dflash2_drafter_taps_and_block) {
|
||||
CHECK_OK(gemma3::probe(mk.meta(), &p));
|
||||
CHECK_EQ(p.draft_depth, 7);
|
||||
CHECK_EQ(p.draft_depth_fixed, 1);
|
||||
CHECK_EQ(p.chain_pays, 0); /* a block drafter, but chained launches never measured */
|
||||
MetaKV plain = gemma3_meta();
|
||||
RadArchProbe q{};
|
||||
CHECK_OK(gemma3::probe(plain.meta(), &q));
|
||||
@@ -6840,6 +7016,7 @@ TEST(llama_reads_its_drafters_taps_and_refuses_what_dspark_does_not_implement) {
|
||||
CHECK_OK(llama_fp8::probe(mk.meta(), &p));
|
||||
CHECK_EQ(p.draft_depth, 7);
|
||||
CHECK_EQ(p.draft_depth_fixed, 1);
|
||||
CHECK_EQ(p.chain_pays, 0);
|
||||
}
|
||||
|
||||
/* One graph, two descriptors: llama_dense_fp8 serves the dense checkpoint a recipe quantises
|
||||
@@ -7934,7 +8111,9 @@ struct ArchCases {
|
||||
lfm2_bf16::step, 0, {}, 0x1775b188dc4a5120ull);
|
||||
/* The first three moved only by the attn_qkv name map each layer declares to ask whether
|
||||
* the container holds q, k and v as one linear: with those maps left out of the hash they
|
||||
* are the earlier pins, 0xafc23087c634a537, 0x719fa07788f8b98a and 0x93b174ab52cc0d31. */
|
||||
* are the earlier pins, 0xafc23087c634a537, 0x719fa07788f8b98a and 0x93b174ab52cc0d31.
|
||||
* The two-rank ones moved with the weight reads beside the reductions (prefetch_beside;
|
||||
* from 0xade9c0ccfad1fd47 and 0x8808d46c04f12205). */
|
||||
add("gemma4_bf16", [this, sc](RadBuilder* b) {
|
||||
auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); },
|
||||
gemma4_bf16::step, 0, {}, 0x2ba2f4943031468full);
|
||||
@@ -7943,13 +8122,13 @@ struct ArchCases {
|
||||
gemma4_bf16::step, 0, {}, 0x2e4c6e3235dd3802ull);
|
||||
add("gemma4_bf16, w4a8, two ranks", [this, sc, g4w4](RadBuilder* b) {
|
||||
g4w4(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); },
|
||||
nullptr, 0, {}, 0xade9c0ccfad1fd47ull);
|
||||
nullptr, 0, {}, 0x3a160b13b3a80d4eull);
|
||||
add("gemma4_bf16, w4a8, fused qkv", [this, sc, g4qkv](RadBuilder* b) {
|
||||
g4qkv(b); auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); },
|
||||
gemma4_bf16::step, 0, {}, 0x3913aca59733d0e2ull);
|
||||
add("gemma4_bf16, w4a8, fused qkv, two ranks", [this, sc, g4qkv](RadBuilder* b) {
|
||||
g4qkv(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); },
|
||||
nullptr, 0, {}, 0x8a9935e773f546efull);
|
||||
nullptr, 0, {}, 0x7be4844610b039d8ull);
|
||||
add("gemma4", [this, sc](RadBuilder* b) {
|
||||
auto c = sc(1, 0); return gemma4::declare(b, &g4m, &c); },
|
||||
gemma4::step, 0, {}, 0x0f227f5853b6488cull);
|
||||
|
||||
@@ -1566,6 +1566,46 @@ TEST(a_two_plane_weight_needs_a_kernel_that_joins_its_planes) {
|
||||
}
|
||||
}
|
||||
|
||||
/* A kernel that reads a weight's stored bytes without interpreting them (libr4d's prefetch into
|
||||
* the cache) answers RAD_LAYOUT_ANY: it takes the form another kernel chose, declared before it or
|
||||
* after, and claims none, so it never conflicts; a weight only it reads is stored as it is. */
|
||||
TEST(a_kernel_that_reads_any_stored_form_claims_none) {
|
||||
NEED_EXTRA(reg)
|
||||
const RadParam p[] = { RAD_RANGE("M", 1, 16), RAD_INT("N", 256), RAD_INT("K", 256),
|
||||
RAD_STR("dtype", "bf16") };
|
||||
auto weight = [](Builder& b) {
|
||||
RadWeightDecl d{};
|
||||
d.dtype = RAD_BF16;
|
||||
d.rank = 2;
|
||||
d.shape[0] = 256;
|
||||
d.shape[1] = 256;
|
||||
d.access = RAD_ACCESS_PER_TOKEN;
|
||||
d.group = rad_group_layer(0);
|
||||
return b.decl_weight("w.bf16", &d);
|
||||
};
|
||||
for (bool any_first : { false, true }) {
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
const rad_weight w = weight(b);
|
||||
rad_op a = 0, t = 0;
|
||||
if (any_first) a = b.decl_op("t_any", p, 4, &w, 1);
|
||||
t = b.decl_op("t_lay", p, 4, &w, 1);
|
||||
if (!any_first) a = b.decl_op("t_any", p, 4, &w, 1);
|
||||
REQUIRE(a != 0 && t != 0);
|
||||
CHECK_EQ(std::string(device_row(b.program().op(a), 0)), "t_any_read");
|
||||
CHECK_EQ(std::string(device_row(b.program().op(t), 0)), "t_lay_tiled");
|
||||
CHECK_OK(b.finish());
|
||||
CHECK(b.errors().empty());
|
||||
CHECK_EQ(b.program().weight(w)->layout_tag, std::string("tiled"));
|
||||
}
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
const rad_weight w = weight(b);
|
||||
REQUIRE(b.decl_op("t_any", p, 4, &w, 1) != 0);
|
||||
CHECK_OK(b.finish());
|
||||
CHECK(b.errors().empty());
|
||||
CHECK(b.program().weight(w)->layout_tag.empty());
|
||||
CHECK(b.program().weight(w)->identity);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* A [256, 256] E4M3 weight with one f32 scale per 128x128 tile, declared over both planes. */
|
||||
|
||||
Reference in new issue
Block a user