Archived
radiance 1.13.0
New models: - Tencent Hy-Memory (HYV3) from its BF16, FP8 and GGUF checkpoints, with its native tool calls - M2XFP4: metadata-augmented MXFP4 weights for Qwen3.8-27B and its DFlash2 drafter (top-1 89.1% -> 92.4% against plain MXFP4), its quantiser and recipe, and ParoQuant's M2XFP4 checkpoints - Gemma 4 E2B/E4B audio input; NVIDIA-Nemotron-3.5-Bolt-E4B in int8 and 4-bit, on two cards by default; Ornith-1.5-122B compose files Speed: - Weight reads beside the decode all-reduces (qwen35_fp8, gemma3; --weight-prefetch, on by default): the 27B MXFP4 with DFlash2 61.2 -> 67.9 tok/s at c1, TranslateGemma 27B +13% - Head-256 split-KV decode attention at 256 workgroups and without bank conflicts (27B: +3-5% a step at 25-41K context), and the prefill KV split for small launches (a short turn over a long context decodes the other sequences 27% faster in that step) - MXFP4 decode gate_up, activation and fp8 quantiser in one launch (27B, Gemma 3 up to 64 rows: TranslateGemma +2-5% at 2-8 streams) - ParoQuant int4/int5 tiled GEMMs 6-9% faster - Speculation: a step's tokens are sent before the drafter's passes end, no step waits behind one that ends its requests, and the MTP head's first draft no longer collapses after short chats in the prefix cache Features: - --kv-resident N: KV streaming for a context bigger than VRAM (qwen4exp_fp8, GLM-5.3) - MiniMax-H3: reference media and keyframe conditioning with the VAE encoders - Krea 2 rebalance presets balanced, detail and subtle - The dashboard's request history; a stall watch that reports a frozen step's thread and stack - rad-tune at the served configuration, collectives measured as the exchange; Gemma 4 E2B/E4B's per-layer embeddings read ahead off the step path - A GPTQ calibration tap and recipe for Gemma 4 31B's w4a8 container Fixes: - The two-rank all-reduce checks that a peer's push has landed before reducing it - z-lab's DFlash drafter on Gemma 4 31B keeps drafting after a prefix-cache hit - MiniMax-H3's modulation rows Changes: Plugin ABI 31: out-of-tree plugins must be rebuilt. RADIANCE_PREFETCH_BESIDE is --weight-prefetch now; RADIANCE_NO_HUGE_PAGES, RADIANCE_IDS_EARLY, RADIANCE_ATTN_BAND_SPLIT, R4D_PREFILL_SPLITS, RAD_PLE_TIMING and RAD_PLE_CACHE_ROWS are gone.
This commit is contained in:
commit
6645337f69
198 files changed
+20904
-3240
No files matched your search
+10
-11
@@ -205,12 +205,10 @@ with the decode row at those rows. Within the family a row's bits do not depend
|
||||
`gemv`'s K order), the bf16 product and row amaxes in the op's scratch; the last of a 128-column
|
||||
group's blocks to arrive (a counter keyed on the output) writes the group's codes and scales. Byte
|
||||
for byte `gemm_mxfp4a8_gemv` followed by `gated_quant_fp8`, or by `gelu_mul` and `quant_act_fp8`
|
||||
(`r4d_selftest`, M = 1..8, Qwen's and TranslateGemma's gate_up). A decode step of Qwen3.8-27B
|
||||
at TP2 issues 631 kernels a card, and a dependent kernel costs 3.5-6.4 µs in a replayed graph on
|
||||
gfx1201 however little it does, so the launch it saves is the point. TranslateGemma 27B alone,
|
||||
one stream at speculation 7: 144.5 / 144.9 → 151.5 / 150.5 tok/s, measured with the first form of
|
||||
this row (a block per 128-column group, the same bytes); the tile-pair form, Qwen3.8-27B without
|
||||
speculation x1 / x4 / x8 +1.4 / +1.8 / +1.5 %.
|
||||
(`r4d_selftest`, M = 1..8, Qwen's and TranslateGemma's gate_up). It saves a launch: a dependent
|
||||
kernel costs 3.5-6.4 µs in a replayed graph on gfx1201 however little it does, and a Qwen3.8-27B
|
||||
TP2 decode step issues 631 a card. About +1.5 % at one to eight streams on Qwen3.8-27B, +4.5 % on
|
||||
TranslateGemma 27B at speculation 7.
|
||||
|
||||
**`gemm_mxfp4a8_gated_gemv_wide`** (`gemm_nt_q_gated_mx`, 9 ≤ M ≤ 64, K a multiple of 128 and at
|
||||
least 2688, N of 256, the same `act` rule). The fold over `gemv_wide`, the GEMM row of that band:
|
||||
@@ -223,13 +221,14 @@ then the narrow row's epilogue. Byte for byte `gemm_mxfp4a8_gemv_wide` followed
|
||||
or by `gelu_mul` and `quant_act_fp8` (`r4d_selftest`, M = 9..64). No spills: 101 / 137 / 166 / 196
|
||||
VGPRs at one to four row tiles (per-(row, 128) activation scale), against `gemv_wide`'s 131 / 160 / 190
|
||||
at two to four tiles and two columns. K from 2688 keeps it out of `decode_shortk`'s corner, where the
|
||||
unfused GEMM sums 33..64 rows in the decode kernel's order. gemma3 declares it up to
|
||||
RADIANCE_G3_FOLD_ROWS rows (default 8, i.e. not at all).
|
||||
unfused GEMM sums 33..64 rows in the decode kernel's order. gemma3 declares the fold up to 64 rows
|
||||
where K reaches it, which at two to eight TranslateGemma streams with speculation 7 is 2-5 % more
|
||||
throughput than the unfused three past 8 rows.
|
||||
|
||||
**Tunables.** `gemv`, `gemv_wide` and `gated_gemv` have none, so a `RADIANCE_TUNE` pin on
|
||||
`gemm_nt_q` passes them by. `decode_shortk` shares the decode row's axes (`ks`, `bk`, `nt`; 0 the rule), so a pin of
|
||||
those reaches both. A pin applies to every row serving the op, and an axis a serving row lacks
|
||||
stops startup by name.
|
||||
`gemm_nt_q` passes them by. `decode_shortk` shares the decode row's axes (`ks`, `bk`, `nt`; 0 the
|
||||
rule), so a pin of those reaches both. A pin applies to every row serving the op, and an axis a
|
||||
serving row lacks stops startup by name.
|
||||
|
||||
## The OCP-MXFP4 tiled GEMM (prefill)
|
||||
|
||||
|
||||
@@ -693,6 +693,10 @@ void r4d_mla_matrix_pin_form(int form);
|
||||
// key loads where aligned; the matrix row's kernel under 32 rows), 1 the element-wise key load
|
||||
// (bit-identical to 3), 2 32 heads a workgroup, 3 the rows kernel of the rule at any row count.
|
||||
void r4d_mla_rows_pin_form(int form);
|
||||
// Test hook: 1 makes every r4d_ar_oneshot_2rank_exact launch send its flags before its pushes and
|
||||
// push ~20 us later, so each reader finds a flag whose bytes have not landed; the push check
|
||||
// (r4d_ar_seq.h) must still give exact sums. 0 is the normal order.
|
||||
void r4d_ar_late_push_pin(int on);
|
||||
// Test hook: records the function each launch dispatches into `fns[0..cap)`, in order, until the
|
||||
// next call, and returns how many launches the previous recording saw (which may exceed its cap).
|
||||
// Null `fns` stops recording. r4d_selftest uses it to show that a pinned form dispatches a kernel
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
// * Fine-grained memory (hipDeviceMallocFinegrained) is uncached and posted straight to the
|
||||
// fabric, so system-scope release/acquire skip the L2 writeback. The drain/acq fences are
|
||||
// selectable (default drain=1/acq=0 on fine-grained).
|
||||
#include <cstdlib>
|
||||
#include "r4d.h"
|
||||
#include "r4d_ar_seq.h"
|
||||
#include "r4d_ar_hc.h" // the gather word and the hc write word, shared with the rotated wire
|
||||
@@ -79,7 +78,7 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
|
||||
int end = start + w; if (end > n16) end = n16;
|
||||
unsigned int hck = 0u; // the push check (r4d_ar_seq.h)
|
||||
|
||||
// drain 4, tests only (R4D_AR_TEST_LATE_PUSH, r4d_selftest): the flag goes out before the push
|
||||
// drain 4, tests only (r4d_ar_late_push_pin, r4d_selftest): the flag goes out before the push
|
||||
// and the push ~20 us after it, so the peer sees a flag whose bytes have not landed -- what a
|
||||
// push over PCIe P2P now and then does on its own -- on every launch.
|
||||
if (drain == 4) {
|
||||
@@ -536,6 +535,11 @@ void r4d_ar_ipc_enable_peer(long peer) {
|
||||
throw std::runtime_error(std::string("enable_peer: ") + hipGetErrorString(e));
|
||||
}
|
||||
|
||||
/* r4d_ar_late_push_pin: 1 makes every 2-rank exact all-reduce send its flags before its pushes
|
||||
* (drain 4). A test hook (r4d_selftest); nothing else sets it. */
|
||||
static int g_ar_late_push = 0;
|
||||
extern "C" void r4d_ar_late_push_pin(int on) { g_ar_late_push = on; }
|
||||
|
||||
void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_flags,
|
||||
long my_flags, long seq_ctrs, long slot_stride16,
|
||||
long inp, long out, long n_elem, long dtype,
|
||||
@@ -561,7 +565,7 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl
|
||||
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
|
||||
// Tests only: every push lands after its flag (drain 4 above). Not in the tuning table, so no
|
||||
// tuner can pick it.
|
||||
if (const char* e = std::getenv("R4D_AR_TEST_LATE_PUSH"); e && *e == '1') drain = 4;
|
||||
if (g_ar_late_push) drain = 4;
|
||||
#define L(T, LN) r4d_ar_oneshot_2rank_exact_kernel<T, LN><<<nb, nt, 0, st>>>( \
|
||||
(const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, \
|
||||
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, \
|
||||
|
||||
+9
-10
@@ -92,17 +92,16 @@ __device__ __forceinline__ bool r4d_ar_seq_behind(unsigned int flag, unsigned in
|
||||
// R9700: the reader sometimes found the slot's previous contents right after the handshake, and
|
||||
// the new bytes ~1 us later), so the flag alone does not say the bytes are there. The pushed bytes
|
||||
// wait in the writer's L2 for the release's writeback, and that writeback and the flag store reach
|
||||
// the peer by different paths. The writer sums
|
||||
// mix(dword, index) over what it pushes and stores the block's sum, salted with its handshake
|
||||
// value, into the peer's check word for (slot, block): fine-grained words after the flags
|
||||
// (r4d_ar_entry.hip sizes the allocation). The reader sums the same over the bytes it is about to
|
||||
// read and reads again until the two agree. A stale element and a stale check word (an older
|
||||
// handshake value) both disagree, so only the landed push passes; the order the two land in does
|
||||
// not matter. The sum is order-free, so writer and reader may split the bytes differently.
|
||||
// the peer by different paths. The writer sums mix(dword, index) over what it pushes and stores the
|
||||
// block's sum, salted with its handshake value, into the peer's check word for (slot, block):
|
||||
// fine-grained words after the flags (r4d_ar_entry.hip sizes the allocation). The reader sums the
|
||||
// same over the bytes it is about to read and reads again until the two agree. A stale element and
|
||||
// a stale check word (an older handshake value) both disagree, so only the landed push passes; the
|
||||
// order the two land in does not matter. The sum is order-free, so writer and reader may split the
|
||||
// bytes differently.
|
||||
#define R4D_ARCHK_SALT 0x6C8E9CF5u
|
||||
#ifndef R4D_ARCHK_DEADLINE
|
||||
#define R4D_ARCHK_DEADLINE 200000000ull // wall_clock64 ticks (100 MHz): 2 s; a push that never lands is a lockstep fault
|
||||
#endif
|
||||
// wall_clock64 ticks (100 MHz): 2 s. A push that never lands is a lockstep fault, so the reader traps.
|
||||
#define R4D_ARCHK_DEADLINE 200000000ull
|
||||
#define R4D_ARCHK_U16 0x80000000u // index space of 16-bit fields (wire scales), apart from dwords
|
||||
|
||||
// MurmurHash3's finalizer over (value, index): every bit of the value reaches every bit of the term,
|
||||
|
||||
@@ -232,7 +232,7 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
|
||||
constexpr int NP4 = (TILE / 2) * (HEAD_DIM / 8);
|
||||
constexpr int U4 = V4 ? (NP4 + NTHR - 1) / NTHR : 1;
|
||||
// The pair's two scales stay apart until storeV4 packs them: packed here, the fetch is waited on
|
||||
// right after it is issued. fp8_v4 packs here as before, as the prefill kernel keeps it.
|
||||
// right after it is issued. fp8_v4 packs here, as the prefill kernel does.
|
||||
constexpr int OLDV4 = V4 && !K6;
|
||||
uint32_t v4c[U4][2], v4s[U4][2];
|
||||
auto fetchV4 = [&](int k0, const int* blks) {
|
||||
@@ -651,11 +651,10 @@ void r4dchain_attn_decode(const R4DArgs a, int splits)
|
||||
// each lane HEAD_DIM/32 dims, so a segment is one 16-byte load per lane; a block carries JPB rows.
|
||||
// No barrier and no LDS, so rows in one block may have different contexts and segment counts.
|
||||
//
|
||||
// SPAN: merge only rows [cu_q[0], cu_q[num_seqs]). A launch over part of a step (the prefill
|
||||
// kernel's split under ArPieces, or a band-split step's prefill half) gets q and out whole with
|
||||
// cu_q at its own first row; every other row belongs to another launch, and r4d_q_seq would map it
|
||||
// onto this launch's first or last sequence and overwrite it. The decode launchers never offset
|
||||
// cu_q and do not instantiate it.
|
||||
// SPAN: merge only rows [cu_q[0], cu_q[num_seqs]). A launch over part of a step (ArPieces' pieces,
|
||||
// a mixed step's prefill half) gets q and out whole with cu_q at its own first row; r4d_q_seq
|
||||
// would map any other row onto this launch's first or last sequence and overwrite it. The decode
|
||||
// launchers never offset cu_q and do not instantiate it.
|
||||
template<int HEAD_DIM, int CHAINS, int PF16, int JPB, int WIN, int GQ, int SPAN = 0>
|
||||
__device__ __forceinline__
|
||||
void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DGateQuant& gq)
|
||||
@@ -998,16 +997,13 @@ void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile,
|
||||
// 8, 19% of a 16K step's KV but 1.2% at 128K. The effect fades with depth, never enough to need a
|
||||
// context term.
|
||||
//
|
||||
// The target is 256 workgroups where a workgroup has one or two waves (q_len * gqa <= 32: a plain decode,
|
||||
// or a 4-row verify of the DFlash2 short block), 128 otherwise. A one- or two-wave workgroup keeps too
|
||||
// few KV bytes in flight for the card's DRAM at 128 (about one a CU); twice as many reach it. Qwen3.8-27B
|
||||
// at TP2 on the R9700, k6_v4: r4d_selftest --perfdecattn (2 rounds) 4 x 1 row over 100k 582 -> 464 us,
|
||||
// 1 x 1 row over 100k 264 -> 175, 16 x 4 rows over 41k 985 -> 801 (x4 and x8 the target were worse
|
||||
// than x2); the server's decode step at speculation 7 (three rounds, medians, the steps carrying every
|
||||
// sequence) 8 x 41k 34.01 -> 32.48 ms, 16 x 25k 44.65 -> 43.19. At three waves (an 8-row verify) more
|
||||
// workgroups only add contention: 4 x 8 rows over 100k +9 % at x2, so those keep 128. The split
|
||||
// count already moves with the batch (8 sequences at 256 split like 4 at 128), so this adds no
|
||||
// partition the merge did not already see.
|
||||
// The target is 256 workgroups where a workgroup has one or two waves (q_len * gqa <= 32: a plain
|
||||
// decode, or a 4-row verify of the DFlash2 short block), 128 otherwise: a one- or two-wave
|
||||
// workgroup keeps too few KV bytes in flight to load the card's DRAM at 128 (Qwen3.8-27B TP2,
|
||||
// k6_v4: one row over 100k 264 -> 175 us, a decode step at speculation 7 -4.5 %; 4x and 8x the
|
||||
// target were worse than 2x). At three waves (an 8-row verify) more workgroups only add
|
||||
// contention (+9 %). The split count already moves with the batch, so the merge sees no new
|
||||
// partition.
|
||||
static inline int r4d_decode_splits(const R4DArgs* a, int tile) {
|
||||
if (a->splits > 0) return a->splits;
|
||||
const int tiles = (a->max_ctx + tile - 1) / tile;
|
||||
|
||||
@@ -304,6 +304,7 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
// ---- launch ----------------------------------------------------------------------------------
|
||||
// One instantiation per (head_dim, gqa), at a workgroup shape picked for it:
|
||||
// h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads)
|
||||
// h256 gqa1: 8 query blocks of 16, tiles of 32 (LDS: 37 KiB)
|
||||
// h256 gqa2, 4, 8: 8, 4, 2 query blocks x the heads, tiles of 32 (LDS: 37 KiB)
|
||||
// h512 gqa2, 4, 8: 4, 2, 1 query blocks x the heads x 2 head halves, tiles of 16 (LDS: 57 KiB)
|
||||
// The LDS holds one K/V tile, so the query heads a workgroup carries change its waves, not it.
|
||||
@@ -358,6 +359,7 @@ extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v,
|
||||
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s, krep)
|
||||
if (head_dim == 256) {
|
||||
switch (gqa) {
|
||||
case 1: R4D_DENSE(256, 1, 8, 1, 32);
|
||||
case 2: R4D_DENSE(256, 2, 8, 1, 32);
|
||||
case 4: R4D_DENSE(256, 4, 4, 1, 32);
|
||||
case 8: R4D_DENSE(256, 8, 2, 1, 32);
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
// groups. Without the barrier PF has no effect.
|
||||
// DOT2 v_dot2_f32_f16 row sum from the packed f16 P: 4 instructions instead of 8, and the
|
||||
// denominator uses the p values the PV matmul used.
|
||||
// BTS/KWIDE/GPREV tile staging; see each define.
|
||||
// BTS/KWIDE/GPREV/KLATE tile staging; see each define.
|
||||
// QK8 Lossy. Q rounded to e4m3 once at load, after the folded scale; K as e4m3 bytes in LDS
|
||||
// (half the tile) and Q.K^T runs as fp8 WMMA at twice the f16 rate.
|
||||
// PV8 Lossy. P rounded to e4m3 and V as e4m3 bytes in LDS, P.V as fp8 WMMA. GROW is 8
|
||||
@@ -66,6 +66,14 @@
|
||||
// LDSB: an LDS-scoped barrier instead of __syncthreads() (lds_barrier() in r4d_common.h). The
|
||||
// default fence invalidates the vector cache twice per tile, though only LDS needs ordering.
|
||||
#define O_LDSB 2097152
|
||||
// KLATE: on the fp8 and k6_v4 caches (the wide K fetch), tile ti+1's K is fetched once tile ti's
|
||||
// last m-tile has its scores (its K fragments are dead there, so kreg adds no live range across the
|
||||
// WMMAs), and the staging between the barriers only widens and stores. Otherwise every wave of the
|
||||
// workgroup (the only one on its WGP) waits out a global round trip each tile. With the branch-free
|
||||
// K fetch and the V scales packed at the store, k6_v4 over 100k keys runs 25.96 -> 21.48 ms (2048
|
||||
// queries, r4d_selftest --perfpaged) and fp8 24.6 -> 22.7; the gain is largest once the KV no
|
||||
// longer fits the 64 MB Infinity Cache.
|
||||
#define O_KLATE 4194304
|
||||
// O_V4: the fp8_v4 cache, O_V4 | O_K6 the k6_v4 cache (see r4d_attn_decode_h256_gqa6.hip).
|
||||
#define O_V4 33554432
|
||||
#define O_K6 67108864
|
||||
@@ -147,6 +155,10 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
constexpr int GPREV = ((OPT & O_GPREV) && !V4) ? 1 : 0;
|
||||
constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0;
|
||||
constexpr int KWIDE = (OPT & O_KWIDE) ? 1 : 0;
|
||||
// fp8_v4 takes none of the three (KLATE, the assume, the scale pack): they gain at 100k but lose
|
||||
// 3-7 % at 25k and 50k.
|
||||
constexpr int OLDV4 = V4 && !K6;
|
||||
constexpr int KLATE = ((OPT & O_KLATE) && KWIDE && !KVP && !OLDV4) ? 1 : 0;
|
||||
constexpr int QK8 = ((OPT & O_QK8) && !KVP) ? 1 : 0;
|
||||
constexpr int PV8 = ((OPT & O_PV8) && !KVP) ? 1 : 0;
|
||||
static_assert(!(OPT & (O_QK8 | O_PV8)) || !KVP,
|
||||
@@ -184,6 +196,10 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
uint8_t* const sV8 = (uint8_t*)sV16;
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
// The launch is NTHR threads. Stated, so the wide K fetch's `key >= TILE` test (never true:
|
||||
// KITEMS == NTHR) folds: as a branch its join made the compiler wait on every load in flight right
|
||||
// after the K fetch, the V stores' cover included.
|
||||
if constexpr (!OLDV4) __builtin_assume(tid < NTHR);
|
||||
const int c = lane & 15, h = lane >> 4;
|
||||
|
||||
// SPLIT: blockIdx.x = qtile * splits + segment; wave-uniform, so the divide is scalar.
|
||||
@@ -208,14 +224,12 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
|
||||
const int* __restrict__ bt = a.block_table + (size_t)seq * a.max_blocks;
|
||||
|
||||
// SPLIT: tps tiles a segment, as r4d_attn_tps (decode unit, included after this one) cuts
|
||||
// tiles(ctx). A segment at or past the merge's segment count u = ceil(tiles / tps) is never
|
||||
// read: exit. One the merge reads but that lies wholly past this workgroup's causal end (an
|
||||
// early query tile of a multi-tile chunk) must still be written: the merge reads all u segments
|
||||
// of every row. It is, by the ordinary path: its walk below is empty, so the epilogue stores
|
||||
// the empty partial (O = 0, m_ref = -3e38, l = 0); the prologue's prefetch of tile tstart reads
|
||||
// inside the sequence (tstart < tiles) and is dropped. A separate early store measured worse:
|
||||
// its extra live range spilled k6_v4's next-tile fetch addresses inside the tile loop.
|
||||
// SPLIT: tps tiles a segment, as r4d_attn_tps cuts tiles(ctx). A segment at or past the merge's
|
||||
// segment count u = ceil(tiles / tps) is never read: exit. One wholly past this workgroup's
|
||||
// causal end must still be written, since the merge reads all u segments of every row: its walk
|
||||
// is empty, so the epilogue stores the empty partial (O = 0, m_ref = -3e38, l = 0), and the
|
||||
// prologue's prefetch of tile tstart stays inside the sequence. (A separate early store spills
|
||||
// k6_v4's next-tile fetch addresses inside the tile loop.)
|
||||
const int sp_tps = SPLIT ? ((ctx + TILE - 1) / TILE + a.splits - 1) / a.splits : 0;
|
||||
if constexpr (SPLIT) {
|
||||
if (sp * sp_tps >= (ctx + TILE - 1) / TILE) return;
|
||||
@@ -291,7 +305,9 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
static_assert(!V4 || F16, "fp8_v4 widens V to f16");
|
||||
constexpr int NP4 = (TILE / 2) * (HEAD_DIM / 8);
|
||||
constexpr int U4 = V4 ? (NP4 + NTHR - 1) / NTHR : 1;
|
||||
uint32_t v4c[U4][2], v4s[U4];
|
||||
// The pair's two scales stay apart until storeV4 packs them: packed here, the prefetch a tile
|
||||
// ahead would be waited on right after it is issued (fp8_v4 packs here, see KLATE).
|
||||
uint32_t v4c[U4][2], v4s[U4][2];
|
||||
auto fetchV4 = [&](int k0, const int* blks) {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < U4; ++r) {
|
||||
@@ -308,7 +324,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4);
|
||||
sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2);
|
||||
}
|
||||
v4s[r] = sc[0] | (sc[1] << 16);
|
||||
if constexpr (OLDV4) { v4s[r][0] = sc[0] | (sc[1] << 16); v4s[r][1] = 0; }
|
||||
else { v4s[r][0] = sc[0]; v4s[r][1] = sc[1]; }
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -324,7 +341,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
const uint32_t m0 = ((v4c[r][0] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
|
||||
const uint32_t n1 = (v4c[r][1] & 0x0F0F0F0Fu) ^ 0x08080808u;
|
||||
const uint32_t m1 = ((v4c[r][1] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
|
||||
const h2 s2 = __builtin_bit_cast(h2, v4s[r]);
|
||||
const h2 s2 = __builtin_bit_cast(h2, OLDV4 ? v4s[r][0] : (v4s[r][0] | (v4s[r][1] << 16)));
|
||||
const h2 bias = { (_Float16)1032.0f, (_Float16)1032.0f };
|
||||
uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp];
|
||||
uint8_t* dst8 = &sV8[(o * 8) * VSTR8 + 2 * kp];
|
||||
@@ -502,6 +519,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
if (BTS) load_bt(tstart * NB, blk);
|
||||
if (GPREV) fetchV(tstart * TILE, blk);
|
||||
if (V4) fetchV4(tstart * TILE, blk);
|
||||
if (KLATE) fetchK(tstart * TILE, blk);
|
||||
|
||||
for (int ti = tstart; ti < ntiles; ++ti) {
|
||||
const int k0 = ti * TILE;
|
||||
@@ -510,8 +528,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
load_bt((ti + 1) * NB, blkn);
|
||||
}
|
||||
if (LDSB) lds_barrier(); else __syncthreads();
|
||||
fetchK(k0, blk);
|
||||
// V first: already in registers, so it covers K's load latency.
|
||||
if (!KLATE) fetchK(k0, blk);
|
||||
// V first: already in registers.
|
||||
if constexpr (V4) { storeV4(); } else { if (!GPREV) fetchV(k0, blk); storeV(); }
|
||||
storeK();
|
||||
if (LDSB) lds_barrier(); else __syncthreads();
|
||||
@@ -559,6 +577,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
|
||||
for (int j = 0; j < PF; ++j) s = D::wmma(kb[j], qf[g + j], s);
|
||||
}
|
||||
}
|
||||
if (KLATE && mt == MT - 1 && ti + 1 < ntiles) fetchK(k0 + TILE, blkn);
|
||||
float sc[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[e] : s[e] * mul;
|
||||
|
||||
@@ -4,19 +4,15 @@
|
||||
// r4d_attn_prefill_h256_gqa6.hip. Include after r4d_attn_decode_h256_gqa6.hip, whose partial
|
||||
// layout and merges it reuses. No entry points here: each unit defines its own, with its geometry.
|
||||
//
|
||||
// Why. The query-tiled grid is ceil(q_len / BQ) x kv_heads x num_seqs, one 768-thread workgroup a
|
||||
// WGP (BQ = NWARPS * 16 / gqa query positions: 192 at gqa 2, 96 at 4, 64 at 6, 48 at 8, 32 at 12),
|
||||
// and each workgroup walks its whole causal range serially. So below one workgroup per WGP a launch
|
||||
// costs one full walk of the context whatever its row count: Qwen3.8-27B at TP2 (gqa 6, kv_heads 2)
|
||||
// runs a 53-row tail over 188k keys as 2 workgroups on 32 WGPs, ~17.7 ms a layer, against ~21 ms a
|
||||
// workgroup for a 1024-row piece filling all 32 (profiled tails, attention: 63 ms at 41k / 80 rows,
|
||||
// 152 at 97k / 345, 283 at 188k / 53). The geometries with one KV head a rank are worse off:
|
||||
// Flash-Next's gqa 12 at TP2 runs 53 rows as 2 workgroups as well, and any chunk up to 32 rows as
|
||||
// one. Such launches split the KV and finish in the split-KV merge.
|
||||
// The query-tiled grid is ceil(q_len / BQ) x kv_heads x num_seqs, one 768-thread workgroup a WGP
|
||||
// (BQ = NWARPS * 16 / gqa query positions: 192 at gqa 2, 96 at 4, 64 at 6, 48 at 8, 32 at 12), and
|
||||
// each workgroup walks its whole causal range serially. Below one workgroup per WGP a launch
|
||||
// therefore costs one full walk of the context whatever its row count: at gqa 6 with 2 KV heads a
|
||||
// 53-row tail over 188k keys is 2 workgroups on 32 WGPs and takes about as long as a 1024-row
|
||||
// chunk, and with one KV head a rank (gqa 12 at TP2) any chunk up to 32 rows is one workgroup.
|
||||
// Such launches split the KV and finish in the split-KV merge.
|
||||
#pragma once
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
// Workgroups the card runs at once: one a WGP. HIP's multiProcessorCount counts WGPs on RDNA (32 on
|
||||
// the R9700, see want_wg in r4d_hc_bf16.hip); 32 if it cannot be read.
|
||||
static inline int r4d_prefill_wgps() {
|
||||
@@ -32,21 +28,16 @@ static inline int r4d_prefill_wgps() {
|
||||
|
||||
// The split law, at the launch's own geometry: `bq` query positions a workgroup, `tile` keys a KV
|
||||
// tile. `units` counts the workgroups that do work: a ragged batch's grid is sized from its longest
|
||||
// sequence (q_len), but a shorter sequence's query tiles past its end exit at once, so the count is
|
||||
// bounded by sum ceil(q_s / bq) <= (total_q + (bq - 1) n) / bq as well (exact for one sequence), so a
|
||||
// ragged launch's longest sequence does not make its others look like full tiles. One S applies to
|
||||
// every sequence of the launch; a mixed step's decode rows reach the split-KV decode row instead, by
|
||||
// the arch's per-band issue (AttnGatedFP8::step). A launch over part of a step (q and out whole, cu
|
||||
// past row 0) counts the step's rows in total_q, so the bound is loose there and may keep it
|
||||
// unsplit.
|
||||
// sequence (q_len), but a shorter sequence's tiles past its end exit at once, so the count is also
|
||||
// bounded by sum ceil(q_s / bq) <= (total_q + (bq - 1) n) / bq. One S applies to every sequence of
|
||||
// the launch. A launch over part of a step (cu past row 0) counts the step's rows in total_q, so
|
||||
// the bound is loose there and may keep it unsplit.
|
||||
// At `wgps` units or more the card is full: no split. Otherwise S rounds of equal workgroups cost
|
||||
// rounds / S walks, so take one round (S1 = wgps / units) or two (S2 = 2 wgps / units), whichever
|
||||
// is faster, the smaller S on a tie (fewer partials). At gqa 6 with 2 KV heads: 53 rows (2 units)
|
||||
// -> 16 splits, 80 -> 8, 345 (12 units) -> 5 (60 workgroups, 0.4 walks against 0.5 at 2), 576 -> 3,
|
||||
// 1024 and up -> 1. At gqa 12 with 1 KV head: up to 32 rows (1 unit) -> 32, 53 -> 16, 345 (11) -> 5.
|
||||
// Each split keeps at least 8 tiles of max_ctx, the only context the host sees (the engine passes
|
||||
// the model's bound, so in serving this caps nothing; a short context's splits past its tiles exit
|
||||
// at once). At most 64, the vectorised merge's limit.
|
||||
// is faster, the smaller S on a tie (fewer partials). At 32 WGPs, gqa 6 with 2 KV heads: 53 rows
|
||||
// -> 16 splits, 80 -> 8, 345 -> 5, 576 -> 3, 1024 and up -> 1; gqa 12 with 1 KV head: up to 32
|
||||
// rows -> 32, 53 -> 16, 345 -> 5. Each split keeps at least 8 tiles of max_ctx, the only context
|
||||
// the host sees. At most 64, the vectorised merge's limit.
|
||||
static inline int r4d_prefill_splits_law(int bq, int tile, int q_len, int total_q, int num_seqs,
|
||||
int kv_heads, int max_ctx, int wgps) {
|
||||
const long n = std::max(1, num_seqs);
|
||||
@@ -61,24 +52,16 @@ static inline int r4d_prefill_splits_law(int bq, int tile, int q_len, int total_
|
||||
return std::max(1, std::min(sp, 64));
|
||||
}
|
||||
|
||||
// The split count the last prefill launch of this unit used, 1 unsplit. Read by each unit's test
|
||||
// hook (r4d_selftest), which tells a split launch from an unsplit one whose bytes happen to agree.
|
||||
// Not atomic.
|
||||
// The split count of this unit's last prefill launch, 1 unsplit: read by the unit's test hook, which
|
||||
// tells r4d_selftest a split launch from an unsplit one with the same bytes. Not atomic.
|
||||
static int g_prefill_last_splits = 0;
|
||||
|
||||
/* The KV split's count before the scratch bound: the case's `splits` parameter when it names one
|
||||
* (r4d_selftest; the prefill rows declare no such axis, so the engine passes none), else
|
||||
* R4D_PREFILL_SPLITS, else the law. R4D_PREFILL_SPLITS is a tuning and A/B knob, not
|
||||
* configuration: 0 or unset = the law, 1 = never split, N = N splits for every launch (at most 64,
|
||||
* and at most what the scratch holds, see r4d_prefill_splits). Read once. */
|
||||
* (r4d_selftest; the prefill rows declare no such axis, so the engine passes none), else the law,
|
||||
* at most 64. */
|
||||
static inline int r4d_prefill_splits_want(const RadArgs* a, const R4DArgs* r, int bq, int tile) {
|
||||
const int sp = split_of(a);
|
||||
if (sp > 0) return std::min(sp, 64);
|
||||
static const int env = [] {
|
||||
const char* e = getenv("R4D_PREFILL_SPLITS");
|
||||
return e && *e ? atoi(e) : 0;
|
||||
}();
|
||||
if (env > 0) return std::min(env, 64);
|
||||
return r4d_prefill_splits_law(bq, tile, r->q_len, r4d_q_total(*r), r->num_seqs, r->kv_heads,
|
||||
r->max_ctx, r4d_prefill_wgps());
|
||||
}
|
||||
@@ -95,21 +78,18 @@ static inline int r4d_prefill_splits(const RadArgs* a, const R4DArgs* r, int bq,
|
||||
return std::max(1, sp);
|
||||
}
|
||||
|
||||
/* Bytes of the split's f32 partials, at declare the most any launch in the band can take.
|
||||
/* Bytes of the split's f32 partials: at declare, the most any launch in the band can take.
|
||||
*
|
||||
* Declare passes the band's upper bound as q_len and no tensors, so the worst case is swept over
|
||||
* every sequence count up to max_seqs and every row count up to the band, in both the uniform form
|
||||
* (q_len = rows / n) and the ragged one (q_len = min(band, rows), as fill_paged takes it). Only
|
||||
* launches with fewer than one workgroup a WGP split, and the units of a launch of `t` rows are at
|
||||
* least kv_heads * ceil(t / bq), so the sweep stops there. The law keeps units * S <= 2 wgps, so
|
||||
* rows * S * q_heads <= bq * gqa * 2 wgps = NWARPS * 16 * 2 wgps, the same for every ratio at 24
|
||||
* waves: 24576 (row, head) pairs of 1032 bytes at head_dim 256, 25.4 MB, for any kv_heads. Not
|
||||
* monotone in the rows, hence the sweep. A launch over part of a step's rows counts the whole
|
||||
* step's in its partial layout (total_q), more than this covers when it is long; r4d_prefill_splits
|
||||
* then cuts S to what fits, down to the plain form.
|
||||
* every sequence count up to max_seqs and every row count up to the band, uniform (q_len = rows /
|
||||
* n) and ragged (q_len = min(band, rows), as fill_paged takes it); the law is not monotone in the
|
||||
* rows. The sweep stops where a launch fills the card. The law keeps units * S <= 2 wgps, so
|
||||
* rows * S * q_heads <= NWARPS * 16 * 2 wgps for every ratio: 24576 (row, head) pairs of 1032
|
||||
* bytes at head_dim 256 and 32 WGPs, 25.4 MB. A launch over part of a long step counts the whole
|
||||
* step's rows and may need more; r4d_prefill_splits then cuts S to what fits.
|
||||
*
|
||||
* Never an error: a refusal would unseat the prefill row, which ran without scratch before the
|
||||
* split. A shape it cannot read gets none, and its launches run the plain form. */
|
||||
* Never an error, so the prefill row never loses its place: a shape it cannot read gets no
|
||||
* scratch, and its launches run the plain form. */
|
||||
static inline int64_t r4d_prefill_scratch(const RadArgs* a, int head_dim, long long row, int bq,
|
||||
int tile) {
|
||||
R4DArgs r;
|
||||
@@ -142,9 +122,8 @@ static inline int64_t r4d_prefill_scratch(const RadArgs* a, int head_dim, long l
|
||||
|
||||
// The split's merge: the decode merge over f32 partials (PF16 0), at the prefill tile, so it
|
||||
// recomputes the kernel's partition; one wave a row from VECMIN rows (JPB rows a block), else the
|
||||
// LDS-tree form, on the decode launchers' terms. SPAN: the launch may cover part of a step's rows
|
||||
// (ArPieces' pieces, a band-split step's prefill half: cu_q starts past row 0, or ends before
|
||||
// total_q), and the rest are another launch's.
|
||||
// LDS-tree form, on the decode launchers' terms. SPAN, since the launch may cover part of a step's
|
||||
// rows (ArPieces' pieces, a mixed step's prefill half).
|
||||
template <int HEAD_DIM, int JPB, int VECMIN>
|
||||
static inline int r4d_prefill_combine(const R4DArgs* a, int splits, int tile, hipStream_t s) {
|
||||
const int jobs3 = r4d_q_total(*a) * a->q_heads;
|
||||
|
||||
+27
-11
@@ -72,6 +72,7 @@ __device__ __forceinline__ float conv_act(float v, int act) {
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Output row `row` reads input row row * st + tap * dil - pad, zero outside its sequence. */
|
||||
template <int TP, int TC>
|
||||
__global__ __launch_bounds__(256) void conv1d_igemm_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
|
||||
@@ -1218,26 +1219,38 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0);
|
||||
const long long k = r4d_geti_or(a, "k", 0), dil = r4d_geti_or(a, "dil", 1);
|
||||
const long long causal = r4d_geti_or(a, "causal", 0), st = r4d_geti_or(a, "stride", 1);
|
||||
const long long causal = r4d_geti_or(a, "causal", 0);
|
||||
/* Two strided forms: the causal one (its own left pad, `cu_div` bounds) and, with `pad`, a
|
||||
* zero-padded one over one sequence of all of x (an audio encoder's downsample). */
|
||||
const long long st = r4d_geti_or(a, "stride", 1), pp = r4d_geti_or(a, "pad", -1);
|
||||
const long long cd = r4d_geti_or(a, "cu_div", 1);
|
||||
const int act = conv1d_act(r4d_gets(a, "act"));
|
||||
if (act < 0) return R4D_NO(RAD_E_INVAL);
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 ||
|
||||
causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
|
||||
const bool padded = pp >= 0 && st > 1;
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) || dil <= 0 ||
|
||||
causal < 0 || causal > 1 || st < 1 || (pp >= 0 && (st <= 1 || causal || cd != 1)) ||
|
||||
(st > 1 && pp < 0 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
long long rx = 0, ry = 0, rr = 0;
|
||||
const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry);
|
||||
const long long rl = res ? r4d_rows_pitch(res, cout, &rr) : 0;
|
||||
if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
const long long n_seq = r4d_numel(cu) - 1;
|
||||
if (n_seq <= 0 || ry <= 0 || rx < ry * st || (res && rr < ry) ||
|
||||
if (n_seq <= 0 || ry <= 0 || (!padded && rx < ry * st) || (res && rr < ry) ||
|
||||
r4d_numel(w) < cout * cin * k || (b && r4d_numel(b) < cout))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
/* The padded form's output rows are PyTorch's (rx and ry are rows, xl and yl pitches); libref
|
||||
* checks that the sequence covers x. */
|
||||
if (padded) {
|
||||
if (n_seq != 1 || rx + 2 * pp < dil * (k - 1) + 1 ||
|
||||
ry != (rx + 2 * pp - dil * (k - 1) - 1) / st + 1)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
}
|
||||
const uint16_t* bp = b ? (const uint16_t*)b->data : nullptr;
|
||||
/* Both kernels read input row row * stride + tap * dil - pad: half the reach a side, or for
|
||||
* the causal form all of it on the left less the stride (the sequences' bounds whole
|
||||
* strides, as the op requires). */
|
||||
const int pad = (int)(causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2);
|
||||
/* Both kernels read input row row * stride + tap * dil - pad: half the reach a side, all of
|
||||
* it on the left less the stride for the causal form, or the explicit `pad`. */
|
||||
const int pad = (int)(padded ? pp : (causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2));
|
||||
const int cdiv = (int)(padded ? 1 : cd);
|
||||
const bool tiled = (cin % 8) == 0 && cout >= 16 && (xl % 8) == 0 &&
|
||||
((uintptr_t)x->data & 15) == 0 && ((uintptr_t)w->data & 15) == 0;
|
||||
const uint16_t* rp = res ? (const uint16_t*)res->data : nullptr;
|
||||
@@ -1250,7 +1263,7 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
|
||||
dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data,
|
||||
(const uint16_t*)w->data, bp, rp,
|
||||
(const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry,
|
||||
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)cd,
|
||||
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)cdiv,
|
||||
(int)xl, (int)yl, (int)rl, act);
|
||||
} else {
|
||||
constexpr int TP = 4, TC = 1, BP = 128, BC = 64;
|
||||
@@ -1259,7 +1272,7 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
|
||||
dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data,
|
||||
(const uint16_t*)w->data, bp, rp,
|
||||
(const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry,
|
||||
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)cd,
|
||||
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)cdiv,
|
||||
(int)xl, (int)yl, (int)rl, act);
|
||||
}
|
||||
} else {
|
||||
@@ -1267,7 +1280,7 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
|
||||
(hipStream_t)s, (const uint16_t*)x->data, (const uint16_t*)w->data,
|
||||
bp, rp, (const int*)cu->data, (uint16_t*)y->data,
|
||||
(int)n_seq, 0, (int)ry, (int)cin, (int)cout, (int)k, (int)dil, pad,
|
||||
(int)st, (int)cd, (int)xl, (int)yl, (int)rl, act);
|
||||
(int)st, (int)cdiv, (int)xl, (int)yl, (int)rl, act);
|
||||
}
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
@@ -1335,6 +1348,9 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) {
|
||||
const long long cd = r4d_geti_or(a, "cu_div", 1);
|
||||
const int act = conv1d_act(r4d_gets(a, "act"));
|
||||
if (act < 0) return R4D_NO(RAD_E_INVAL);
|
||||
/* The strided forms are bf16 only. */
|
||||
if (r4d_geti_or(a, "stride", 1) != 1 || r4d_geti_or(a, "pad", -1) >= 0)
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 ||
|
||||
causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
@@ -338,6 +338,22 @@ __global__ __launch_bounds__(kThreads) void pool_rows_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- pool_cols
|
||||
// ref_pool_cols: column c of row m of y is the mean of x[m]'s columns [c*k, c*k + k), summed in
|
||||
// f32 and rounded to bf16, then times `mult` and rounded again. A thread an output column.
|
||||
__global__ __launch_bounds__(kThreads) void pool_cols_kernel(
|
||||
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t k, float mult,
|
||||
uint32_t x_ld, uint32_t y_ld, uint32_t M) {
|
||||
const uint32_t i = blockIdx.x * kThreads + threadIdx.x;
|
||||
if (i >= n / k) return;
|
||||
for (uint32_t r = blockIdx.y; r < M; r += gridDim.y) {
|
||||
float acc = 0.0f;
|
||||
for (uint32_t j = 0; j < k; ++j) acc += bf2f(x[(size_t)r * x_ld + (size_t)i * k + j]);
|
||||
const float mean = bf2f(f32_to_bf16(acc * (1.0f / (float)k)));
|
||||
y[(size_t)r * y_ld + i] = f32_to_bf16(mean * mult);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- cast bf16 -> f32
|
||||
__global__ __launch_bounds__(kThreads) void widen_kernel(
|
||||
const uint16_t* __restrict__ x, float* __restrict__ y, uint32_t n, uint32_t x_ld,
|
||||
@@ -860,6 +876,18 @@ extern "C" int r4d_pool_rows_bf16(long x, long y, int rows, int n, int k, float
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_pool_cols_bf16(long x, long y, int rows, int n, int k, float mult, int x_ld,
|
||||
int y_ld, long stream) {
|
||||
if (!x || !y) return -1;
|
||||
if (rows <= 0 || n <= 0 || k <= 0 || n % k) return -2;
|
||||
hipLaunchKernelGGL(pool_cols_kernel,
|
||||
dim3((uint32_t)((n / k + kThreads - 1) / kThreads), grid_rows(rows)),
|
||||
dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (uint16_t*)y,
|
||||
(uint32_t)n, (uint32_t)k, mult, (uint32_t)x_ld, (uint32_t)y_ld,
|
||||
(uint32_t)rows);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_widen_bf16_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream) {
|
||||
if (!x || !y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
@@ -1206,6 +1234,25 @@ extern "C" int r4d_rad_pool_rows(const RadArgs* a, RadStream s) {
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pool_cols */
|
||||
extern "C" int r4d_rad_pool_cols(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* X = r4d_opt(a, 0);
|
||||
const RadTensor* Y = r4d_opt(a, 1);
|
||||
if (!X || !Y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(X));
|
||||
R4D_NEED(dt_bf16(Y));
|
||||
const long long n = r4d_geti_or(a, "n", 0), k = r4d_geti_or(a, "k", 0);
|
||||
if (n <= 0 || k <= 0 || n % k) return R4D_NO(RAD_E_SHAPE);
|
||||
long long M = 0, My = 0;
|
||||
const long long x_ld = r4d_rows_pitch(X, n, &M);
|
||||
const long long y_ld = r4d_rows_pitch(Y, n / k, &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 enc_status(r4d_pool_cols_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)k,
|
||||
(float)r4d_getf(a, "mult", 1.0), (int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ cast bf16 -> f32 */
|
||||
extern "C" int r4d_rad_cast_widen(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = r4d_opt(a, 0);
|
||||
|
||||
+2
-2
@@ -647,8 +647,8 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* qk_norm_rope_gate_kv_store_streamed -- the same prologue with the STREAMED store folded on.
|
||||
* (row: qk_norm_rope_gate_kv_store_streamed_fp8; kernel: r4d_qk_norm_rope_gate.hip under
|
||||
* qk_norm_rope_gate_kv_store_streamed -- the same prologue with the streamed store folded on.
|
||||
* (rows: qk_norm_rope_gate_kv_store_streamed_{fp8,bf16}; kernel: r4d_qk_norm_rope_gate.hip under
|
||||
* QK_KV_STREAMED)
|
||||
*
|
||||
* Operands: [0] q_gate? [1] k [2] cos_sin [3] positions [4] q_w? [5] k_w [6] q_out?
|
||||
|
||||
@@ -366,16 +366,11 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs* a, RadStream s) {
|
||||
// to arrive (an agent-scope counter per group, keyed on the output as the decode row's) takes the
|
||||
// group's amax and writes its codes and scales.
|
||||
//
|
||||
// Why a tile pair a block: one block a 128-column group, each wave running every K partial of one of
|
||||
// its sixteen tiles, left the grid at n / 128 blocks, 68 at Qwen's per-rank gate_up on 32 WGPs, so a
|
||||
// few WGPs ran a third block while the rest idled, and the fold (97..101 us) lost to the gemv row and
|
||||
// gated_quant_fp8 it replaces (78 + 7 us). Splitting K across a group's blocks instead moved an fp32
|
||||
// partial of the whole product per split through memory (4.4 MB at eight rows; 106 us). A tile pair
|
||||
// a block is the gemv row's own grid and K order; what crosses blocks is the bf16 product and the
|
||||
// amaxes, M * n * 2 bytes and n / 16 * M floats: Qwen 78..81 us, TranslateGemma 99 (as before), at
|
||||
// TP1 148 against the pair's 152 (r4d_selftest --perfmx). End to end the gain is smaller, since a
|
||||
// replayed step overlaps the old fold's idle WGPs with other work: Qwen without speculation x1 / x4 /
|
||||
// x8 +1.4 / +1.8 / +1.5 % (three alternating rounds).
|
||||
// Why a tile pair a block: a block per 128-column group leaves too few blocks (68 for Qwen's
|
||||
// per-rank gate_up on 32 WGPs), and splitting K across a group's blocks moves an fp32 partial of
|
||||
// the whole product through memory; both lost to the gemv row plus gated_quant_fp8. A tile pair a
|
||||
// block is the gemv row's own grid and K order, and only the bf16 product and the amaxes cross
|
||||
// blocks: Qwen 78..81 us against the pair's 85 (r4d_selftest --perfmx), about +1.5 % end to end.
|
||||
//
|
||||
// Byte-identical to the WMMA form above followed by gated_quant_fp8. Wave v of a tile runs what wave
|
||||
// v of that form runs (partial v sums chunks v, v + KW, .. in order), and the partials are added
|
||||
@@ -511,14 +506,13 @@ void r4d_gemm_mxfp4a8_gated_kernel(
|
||||
// (gemm_mxfp4a8_gated_gemv_wide)
|
||||
//
|
||||
// From 9 rows the GEMM the fold replaces is gemv_wide's (r4d_gemm_mxfp4a8_gemvw_kernel, RT row tiles).
|
||||
// This is that kernel over a tile PAIR, gate tile j and up tile n / 16 + j, in place of two adjacent
|
||||
// This is that kernel over a tile pair, gate tile j and up tile n / 16 + j, in place of two adjacent
|
||||
// tiles (its TN = 2): eight K waves, each loading both tiles' words of its chunks and running one WMMA
|
||||
// chain per row tile over each, so a chunk's activation fragments are read once for both halves. The
|
||||
// narrow form's sixteen waves (eight a half, each reading the activation for its own tile) would be
|
||||
// gemv_wide at TN = 1, which at 25..64 rows took TranslateGemma's gate_up 21504 x 5376 from 111 to 154
|
||||
// us at 32 rows and from 150 to 183 at 64 (the comment above r4d_gemm_mxfp4a8_gemvw_kernel). Then the
|
||||
// narrow form's epilogue: a thread a (row, column) of the pair, the GeGLU or SwiGLU product rounded to
|
||||
// bf16, each row's amax over the tile, and the 128-column group's last block quantising it.
|
||||
// chain per row tile over each, so a chunk's activation fragments are read once for both halves.
|
||||
// (The narrow form's sixteen waves, eight a half, would be gemv_wide at TN = 1: 20-40 % slower at
|
||||
// 32-64 rows on TranslateGemma's gate_up.) Then the narrow form's epilogue: a thread a (row, column)
|
||||
// of the pair, the GeGLU or SwiGLU product rounded to bf16, each row's amax over the tile, and the
|
||||
// 128-column group's last block quantising it.
|
||||
//
|
||||
// Byte-identical to gemv_wide followed by gelu_mul and quant_act_fp8 (or gated_quant_fp8). A row's sum
|
||||
// in gemv_wide is its row tile's chain alone, the same at every RT and TN; wave v here sums chunks v,
|
||||
|
||||
+44
-6
@@ -261,9 +261,9 @@ __device__ __forceinline__ void st1(float* p, float v) { *p = v; }
|
||||
template <typename TY>
|
||||
__global__ __launch_bounds__(kT) void timestep_kernel(
|
||||
const float* __restrict__ t, TY* __restrict__ y, int h, float scale, float coef,
|
||||
int round, int y_ld) {
|
||||
int round, float clamp_min, int y_ld) {
|
||||
const int m = blockIdx.x;
|
||||
const float tv = t[m];
|
||||
const float tv = fmaxf(t[m], clamp_min);
|
||||
const float tt = round == 3 ? bfr(scale * bfr(tv)) : round == 2 ? scale * bfr(tv)
|
||||
: round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv;
|
||||
for (int i = threadIdx.x; i < h; i += kT) {
|
||||
@@ -274,6 +274,26 @@ __global__ __launch_bounds__(kT) void timestep_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// The curve form: y[m] is the table [grid, n] f32 at clamp01(max(t[m], clamp_min)) (grid - 1),
|
||||
// between the two rows around it.
|
||||
template <typename TY>
|
||||
__global__ __launch_bounds__(kT) void timestep_curve_kernel(
|
||||
const float* __restrict__ t, const float* __restrict__ table, TY* __restrict__ y,
|
||||
int grid, int n, float clamp_min, int y_ld) {
|
||||
const int m = blockIdx.x;
|
||||
const float tv = fmaxf(t[m], clamp_min);
|
||||
const float pos = fminf(fmaxf(tv, 0.0f), 1.0f) * (float)(grid - 1);
|
||||
float i0f = floorf(pos);
|
||||
if (i0f > (float)(grid - 2)) i0f = (float)(grid - 2); /* as torch clamps it */
|
||||
const float fr = pos - i0f;
|
||||
const int i0 = (int)i0f;
|
||||
for (int i = threadIdx.x; i < n; i += kT) {
|
||||
const float a0 = table[(size_t)i0 * n + i];
|
||||
const float a1 = table[(size_t)(i0 + 1) * n + i];
|
||||
st1(y + (size_t)m * y_ld + i, a0 + fr * (a1 - a0));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- row moves
|
||||
__global__ __launch_bounds__(kT) void gather2_kernel(
|
||||
const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, const int* __restrict__ idx,
|
||||
@@ -1123,30 +1143,48 @@ extern "C" int r4d_rad_chan_stats(const RadArgs* a, RadStream s) {
|
||||
}
|
||||
|
||||
/* Both rows: a bf16 embedding (timestep_embed_bf16) or an f32 one (timestep_embed_f32, a timestep
|
||||
* MLP kept in f32). */
|
||||
* MLP kept in f32); with `curve`, the table form. */
|
||||
extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *t = r4d_opt(a, 0), *y = r4d_opt(a, 1);
|
||||
if (!t || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if (t->dtype != RAD_F32 || !r4d_contig(t) || (!is_bf16(y) && y->dtype != RAD_F32))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", 0);
|
||||
if (n <= 0 || (n & 1)) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long grid = r4d_geti_or(a, "curve", 0);
|
||||
if (n <= 0 || (!grid && (n & 1))) return R4D_NO(RAD_E_SHAPE);
|
||||
long long ry = 0;
|
||||
const long long yl = r4d_rows_pitch(y, n, &ry);
|
||||
if (yl < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (ry <= 0 || r4d_numel(t) < ry) return R4D_NO(RAD_E_SHAPE);
|
||||
if (grid > 0) {
|
||||
const RadTensor* tab = r4d_opt(a, 2);
|
||||
if (!tab) return R4D_NO(RAD_E_INVAL);
|
||||
if (tab->dtype != RAD_F32 || !r4d_contig(tab) || r4d_numel(tab) < grid * n)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const float clamp = (float)r4d_getf(a, "clamp_min", 0.0);
|
||||
if (y->dtype == RAD_F32)
|
||||
hipLaunchKernelGGL(timestep_curve_kernel<float>, dim3((unsigned)ry), dim3(kT), 0,
|
||||
(hipStream_t)s, (const float*)t->data, (const float*)tab->data,
|
||||
(float*)y->data, (int)grid, (int)n, clamp, (int)yl);
|
||||
else
|
||||
hipLaunchKernelGGL(timestep_curve_kernel<uint16_t>, dim3((unsigned)ry), dim3(kT), 0,
|
||||
(hipStream_t)s, (const float*)t->data, (const float*)tab->data,
|
||||
(uint16_t*)y->data, (int)grid, (int)n, clamp, (int)yl);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
const float mp = (float)r4d_getf(a, "max_period", 10000.0);
|
||||
const float coef = (float)(-std::log((double)mp));
|
||||
const float scale = (float)r4d_getf(a, "scale", 1000.0);
|
||||
const int round = (int)r4d_geti_or(a, "round", 0);
|
||||
const float clamp = (float)r4d_getf(a, "clamp_min", 0.0);
|
||||
if (y->dtype == RAD_F32)
|
||||
hipLaunchKernelGGL(timestep_kernel<float>, dim3((unsigned)ry), dim3(kT), 0,
|
||||
(hipStream_t)s, (const float*)t->data, (float*)y->data, (int)(n / 2),
|
||||
scale, coef, round, (int)yl);
|
||||
scale, coef, round, clamp, (int)yl);
|
||||
else
|
||||
hipLaunchKernelGGL(timestep_kernel<uint16_t>, dim3((unsigned)ry), dim3(kT), 0,
|
||||
(hipStream_t)s, (const float*)t->data, (uint16_t*)y->data, (int)(n / 2),
|
||||
scale, coef, round, (int)yl);
|
||||
scale, coef, round, clamp, (int)yl);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
|
||||
+119
-293
@@ -1,155 +1,59 @@
|
||||
// kv_resolve: turn a streamed KV group's selected block ids into the ring slots that hold them,
|
||||
// copy a block in from the pinned host mirror when it is not resident, and rewrite the selection
|
||||
// in place (docs/OPS.md "kv_resolve", docs/KV-STREAMING.md §3.4 and §4.2).
|
||||
// copy a block in from the pinned host mirror when it is absent, and rewrite the selection in place
|
||||
// (docs/OPS.md "kv_resolve", docs/KV-STREAMING.md §3.4). `sel` is the only place the sparse path
|
||||
// names KV storage, so after this op the attention reads ring slots unchanged.
|
||||
//
|
||||
// `qsa_select` already writes the group's pool page id into `sel`, and `attn_paged` reads every
|
||||
// entry as a raw pool index. A streamed group's device pool is `slots` blocks deep while the id
|
||||
// space is `blocks`, so an id is no longer an address; after this op each entry is a slot of
|
||||
// `kv_cache` and the attention is unchanged. `sel` is the only place the sparse path names KV
|
||||
// storage, which is why one op between select and attention suffices.
|
||||
// libref/ref_kvstream.cpp is the contract and its seven steps are kept, so both place the same
|
||||
// blocks in the same slots. Here:
|
||||
//
|
||||
// The order is the contract (libref/ref_kvstream.cpp), because two implementations must place the
|
||||
// same blocks in the same slots and so produce the same table:
|
||||
// 1. the epoch is bumped;
|
||||
// 2. one lookup per entry below nsel[q]. A hit stamps its slot with the epoch; the thread whose
|
||||
// exchange stamps it first bumps its heat counter and counts it into the union. A miss claims
|
||||
// its map entry once (atomicCAS -1 -> -2) and appends the block to the claim list, so the CAS
|
||||
// count is the distinct-claim count. The value read is kept for step 7 (the entry cache);
|
||||
// 3. the claim list is sorted ascending (bitonic, in LDS), so atomic claim order never reaches
|
||||
// the placement;
|
||||
// 4. one victim per miss from the hand: the block's own slot when free, else a free slot, else
|
||||
// CLOCK over the heat counter. Phase 3b counts the free slots once in parallel, so a full ring
|
||||
// goes straight to CLOCK;
|
||||
// 5. both maps are re-pointed as each victim is taken;
|
||||
// 6. each placed block is copied, one warp a miss, so every miss's host read is in flight at once;
|
||||
// 7. every valid entry is rewritten as its slot.
|
||||
//
|
||||
// 1. bump the epoch (ctl[0] + 1);
|
||||
// 2. one lookup per entry below nsel[q]: a hit takes the epoch and, the first time this call
|
||||
// stamps that slot, bumps its two-bit heat counter by one (clamped at 3) -- one bump a slot a
|
||||
// call, not one an entry, so a block many rows name gains one step of heat, the same as one a
|
||||
// single row names. A miss claims its map entry once (-1 -> -2, atomicCAS), so the map is its
|
||||
// own set. That CAS is also the distinct-claim count: it succeeds exactly once per block,
|
||||
// which is the
|
||||
// `s_distinct` step 3 would otherwise have to scan the map for. The value read is kept, one
|
||||
// int an entry, for step 7 below;
|
||||
// 3. compact the claimed blocks out of `res` in ASCENDING block id. The claims are made by
|
||||
// whichever thread reaches them first, but this scan is what fixes the miss order, so
|
||||
// atomic claim order never reaches the placement. A thread owns one contiguous chunk of the
|
||||
// map and reads it four ids at a time, so the list is still ascending by construction. Only
|
||||
// taken when the call claimed something: with no claim there is no `-2` and nothing to
|
||||
// place (step 2's count says so);
|
||||
// 4. one victim per miss, in the hand order from ctl[1]: a FREE slot (slot_block < 0) first, so
|
||||
// no resident block is evicted while the ring has room (the free count is taken in parallel
|
||||
// once per call); only a call with no free slot falls back to CLOCK's second chance, where a
|
||||
// slot stamped with this call's epoch is passed and keeps its counter, a warm slot (counter
|
||||
// non-zero) has its counter HALVED and is passed, and a cold slot (counter 0) is taken. The
|
||||
// hand PICKS the victim: this is a per-visit decision, so the policy costs no reduction, no
|
||||
// barrier and no extra traffic -- an add-and-clamp and a shift where a constant store and a
|
||||
// zero store would do. An exact LRU would need the minimum over the ring per miss, a
|
||||
// collective reduction that pays more than the choice is worth. The hand ends just past the
|
||||
// last slot taken; the sweep visits at most 3*slots, because every write clamps the counter
|
||||
// to 3 and two halvings take any value to 0;
|
||||
// 5. re-point both maps as each victim is taken (`res[old] = -1`, then slot -> b and b -> slot,
|
||||
// with the slot's counter bumped by one as a use: the victim's is 0 by construction, so it is
|
||||
// 1 in the common case, and the clamp keeps a slot taken by identity or from the free region
|
||||
// inside [0, 3]);
|
||||
// 6. copy `block_bytes` of host[b] into kv_cache[s] for each placed miss, as bytes, in this one
|
||||
// launch;
|
||||
// 7. rewrite every entry below nsel[q] whose block is resident as its slot; entries past nsel[q]
|
||||
// keep qsa_select's -1 padding. An entry step 2 saw resident uses the slot it read there, so
|
||||
// `res` is read once a selection entry, not twice (see "THE ENTRY CACHE").
|
||||
// Overflow: unplaced claims revert to -1, ctl[3] latches, and their entries are rewritten as slot 0
|
||||
// (the id would be an address past the ring, which attn_paged dereferences unchecked). The row is
|
||||
// stateful, so it is not in r4d_rows.cpp's concurrent list; it is recordable, since the maps, ring
|
||||
// and mirror never move.
|
||||
//
|
||||
// OVERFLOW. The ring must hold the union of the call's selection (`hits + misses <= slots`). When it
|
||||
// does not, the sweep cannot place every miss: the unplaced claims are reverted to -1 (so a later
|
||||
// call may claim them again), ctl[3] is latched to 1, and their selection entries are rewritten to
|
||||
// SLOT 0 rather than left holding the block id. The id would be an address past the ring, which
|
||||
// attn_paged dereferences with no bounds check, so an overflow would fault or read another layer;
|
||||
// slot 0 is defined memory, wrong numbers the caller discards on ctl[3].
|
||||
// Cost. A decode step issues this once per QSA layer, so a launch's cost is its misses (tens a
|
||||
// launch at 16K-160K of history), and nothing it does is sized by `blocks`: the claim list comes
|
||||
// out of the lookup pass, the union is counted on first stamps, and the copies run in parallel.
|
||||
// What remains is the host read, PCIe transactions on mirror pages the card has not touched. The
|
||||
// sweep visits about one slot a miss, since each launch halves the counters it passes.
|
||||
//
|
||||
// STATE. The epoch, the hand, the two-bit heat counters and the counters live between launches, so
|
||||
// this row is not concurrent (r4d_rows.cpp's kStateful[]): two launches must never overlap, and the
|
||||
// engine orders them. It is still recordable: the maps, the ring and the mirror are fixed-size
|
||||
// from the group's declaration, so addresses and pitches never move.
|
||||
// The claim list. A call claims at most `M * sel_pitch` blocks (in fact at most `lookups`), so the
|
||||
// list is `next_pow2(min(M * sel_pitch, LDS room))` ids of dynamic LDS (kv_claim_cap): 4096 for
|
||||
// four sequences at `sel_pitch` 513. Only the first `slots` claims can be placed. A launch wider
|
||||
// than the list (28 rows or more at pitch 513) gathers its claims from the selection into the row's
|
||||
// scratch, padded to a power of two, and sorts them there: still `lookups` entries, never `blocks`.
|
||||
// Only a call claiming more blocks than the ring holds, which has overflowed, walks the map to put
|
||||
// the smallest `slots` claims in order. ctl[12] records the largest claim count.
|
||||
//
|
||||
// COST. A decode step issues this once per QSA layer -- twelve launches, in a step whose whole
|
||||
// budget is ~33 ms -- so a launch's own cost is the miss path, not the dispatch: ~20 to ~60 misses
|
||||
// a launch at 16k-160k of history. Everything that path touches is therefore sized from the call's
|
||||
// own entries and not from `blocks`:
|
||||
// The entry cache. Steps 2 and 7 both read `res[b]` for every entry, scattered over the map. A
|
||||
// hit's slot cannot move during the call, because the sweep never takes a slot stamped with this
|
||||
// call's epoch, so step 2 keeps what it read (one int an entry, dynamic LDS after the claim list,
|
||||
// when it fits) and step 7 reads the map again only for entries that were absent. Same entry index,
|
||||
// same thread, so no barrier between them.
|
||||
//
|
||||
// - the claim list comes out of the lookup pass, which already sees every claim, so no pass walks
|
||||
// `res` over `blocks`;
|
||||
// - the union is a metric (`ctl[10]`), counted on the first stamp per slot, so no pass walks
|
||||
// `slot_state` over `slots`: a ring is sized by misses and not by slots, and a ring larger than
|
||||
// the history does not cost more than a small one;
|
||||
// - the copies are independent, so each miss has a warp of its own and every miss's read is in
|
||||
// flight at once.
|
||||
// Scratch: `next_pow2(slots)` block ids, then `slots` slots. State faults: libref refuses them
|
||||
// before writing; a kernel cannot return a status, so here an out-of-range hand starts at 0, a map
|
||||
// value outside its domain addresses nothing, an out-of-range id stays in `sel` and nsel is clamped
|
||||
// to `sel_pitch`. A legal call is bit-identical to the reference.
|
||||
//
|
||||
// What is left is the host read itself: a miss copies 2 KiB from a pinned mirror page the card has
|
||||
// not touched, so it is PCIe transactions with a page walk behind them, and no arrangement of the
|
||||
// copy loop changes that. The CLOCK sweep is not the cost either: each launch halves the counters
|
||||
// of the slots it passes, so the ring arrives at the next launch mostly cold and a sweep visits
|
||||
// about one slot a miss. The free-slot scan ahead of it costs a visit per slot it passes, and the
|
||||
// count that says whether to scan at all (phase 3b) is one coalesced pass over the two slot maps per
|
||||
// call, so a ring with no free slot -- where every eviction is unavoidable -- pays neither a full
|
||||
// turn of scanning per miss nor one serial scan per launch.
|
||||
//
|
||||
// SCRATCH. `next_pow2(slots)` block ids then `slots` slots (the row's scratch hook sizes it). The
|
||||
// miss list is a per-call temporary and would cost the arena planner, the recorded pass and the
|
||||
// tape key bytes nothing outside this launch reads. The claim list is dynamic LDS (`cap` ids) while
|
||||
// it fits -- the sort reads every element from every thread, so it wants shared memory -- and the
|
||||
// scratch's first plane when it does not, which is why that plane is padded to a power of two. The
|
||||
// entry cache is dynamic LDS too, after the claim list, and absent when it does not fit.
|
||||
//
|
||||
// THE CLAIM LIST'S SIZE IS DERIVED, NOT WRITTEN DOWN. A claim is a distinct absent block the
|
||||
// selection names, so one call makes at most `M * sel_pitch` of them -- and at most `lookups =
|
||||
// sum_q nsel[q]` in fact -- which is a fact about the call and not about the cache: `blocks` is the
|
||||
// id space, `max_seqs * ceil(max_ctx / block_size)` and never the size of a launch. So the
|
||||
// launcher sizes the list at `next_pow2(min(M * sel_pitch, the room a workgroup has))`, and for
|
||||
// `--max-num-seqs 4` at `sel_pitch` 513 that is 4096 ids, where a constant would have to be chosen
|
||||
// for the largest configuration or hand that one the map walk below. Nothing here mentions
|
||||
// `max_seqs`: the engine declares `sel_pitch` and launches `M` rows, and any --max-num-seqs follows
|
||||
// from those two. `ctl[12]` records the largest claim count one call has made, so a list that is
|
||||
// ever too shallow is visible in the counters rather than only in the launch's time.
|
||||
//
|
||||
// Only the first `slots` claimed blocks are needed: the sweep cannot place more than `slots`, and
|
||||
// every claim past that is still reverted to -1 by the final pass, so a capped list changes no
|
||||
// placement.
|
||||
//
|
||||
// ABOVE THE LIST. A launch wider than the list -- 28 or more rows at `sel_pitch` 513, since a
|
||||
// workgroup has tens of thousands of ids of room -- gathers its claims from the selection into the
|
||||
// scratch and sorts them there (phase 3). The walk is over the call's entries, `lookups` of them,
|
||||
// never over `blocks`: the map is only the set that says whether an id is a claim and that keeps a
|
||||
// block four rows name out of the list four times. Same ids, same ascending order, same placements
|
||||
// as the fast path. The one call this cannot serve is one claiming more blocks than the ring holds:
|
||||
// no structure there can hold the whole claim set, so that call -- which has overflowed and whose
|
||||
// step the caller discards -- keeps the map walk that puts the smallest `slots` claims in order.
|
||||
//
|
||||
// THE ENTRY CACHE. Step 2 and step 7 each read `res[b]` for every selection entry, and those reads
|
||||
// are scattered over `blocks` i32: at decode that is two 513-load waves over a map the launch has
|
||||
// already touched once. But step 7's answer for a HIT is step 2's
|
||||
// answer: the only thing that clears a `res` entry in a call is an eviction, and the sweep never
|
||||
// takes a slot stamped with this call's epoch (the `slot_state` test in both the free scan and the
|
||||
// CLOCK sweep), which is exactly the stamp step 2 puts on every hit's slot. So a hit's slot cannot move, and only an entry step 2 saw absent can
|
||||
// change -- a claimed block becomes its placed slot, or stays -1 when the sweep could not place it
|
||||
// (step 6a's revert), or in the above-the-list path passes through -3 and back. Step 2 therefore
|
||||
// stores the value it read, one int an entry, and step 7 uses it when it is >= 0 and reads the map
|
||||
// only otherwise: the same slots, the same `sel`, one scattered wave instead of two.
|
||||
//
|
||||
// The cache is `M * sel_pitch` ints of dynamic LDS, the launch's whole entry count, and only while
|
||||
// the workgroup has that room beside the claim list; a prefill-shaped launch that has not gets
|
||||
// zero and step 7 reads the map instead. Nothing outside the launch sees it: no operand,
|
||||
// no scratch, no contract. Entries whose block id is out of range are skipped in both steps and
|
||||
// never reach the cache, and the read is by `sel`'s entry index, which is the same index -- and the
|
||||
// same thread -- in both steps, so no barrier is needed between them.
|
||||
//
|
||||
// STATE FAULTS. libref refuses a `res` entry outside [-1, slots), a `slot_block` outside
|
||||
// [-1, blocks), a hand outside [0, slots) and a selection entry outside [0, blocks) before it
|
||||
// writes anything. A device launch cannot return a host status from inside its kernel, so this
|
||||
// kernel guards instead: an out-of-range hand starts at 0, a map value outside its domain is not
|
||||
// used to address memory, an out-of-range block id is left in `sel`, and nsel is clamped to
|
||||
// `sel_pitch` so a bad count cannot steer a row into its neighbour. Those paths are the state
|
||||
// fault libref refuses; a legal call never takes them and is bit-identical to the reference.
|
||||
//
|
||||
// The shape checks (ranks, dtypes, pitches, byte extent per block) belong to the shim below. Like
|
||||
// every step-sized kernel it takes the launch's row count and row pitch from `sel`'s own extent,
|
||||
// not from the ranged `M`/`sel_pitch` parameters: `M` arrives as the band's ceiling, so a one-row
|
||||
// decode and a 625-token prefill would otherwise be refused (arch/common/rad_arch.h's "step-sized
|
||||
// operands"). `M` is still checked as the ceiling it is, so a genuinely over-wide launch is refused.
|
||||
// The ring depth is the operand's for the same reason: `slot_block`'s extent is the ring this call
|
||||
// may address, and the declared `slots` is the ceiling it may not pass -- the pool is planned after
|
||||
// declare, so a ring the engine sized smaller (--kv-resident) arrives shorter.
|
||||
// It reads the two byte planes by row pitch in bytes, as libref does, so the same kernel serves
|
||||
// every cache layout (`fp8`, `fp8_v4`, `k6_v4`, `bf16`) and the copy converts nothing.
|
||||
//
|
||||
// Returns a RAD status rather than throwing, for the reason given in r4d_gemm_fp8a8.hip.
|
||||
// The shim takes the row count, row pitch and ring depth from the operands (`sel`, `slot_block`),
|
||||
// with the ranged `M`, `sel_pitch` and `slots` as ceilings (arch/common/rad_arch.h, "step-sized
|
||||
// operands"), and addresses the byte planes by row pitch, so one kernel serves every cache layout.
|
||||
// It returns a RAD status rather than throwing, for the reason given in r4d_gemm_fp8a8.hip.
|
||||
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
@@ -162,8 +66,8 @@ namespace {
|
||||
|
||||
constexpr int kThreads = 1024;
|
||||
|
||||
/* A 16-byte vector as a builtin type, not `uint4`: the class copies through a memcpy call, and the
|
||||
* miss copy needs its four loads to stay four loads (phase 6). */
|
||||
/* A 16-byte vector as a builtin type: `uint4` copies through a memcpy call, which keeps a load and
|
||||
* its store adjacent, and the miss copy needs its four loads issued first (step 6). */
|
||||
typedef unsigned int kv_v16 __attribute__((ext_vector_type(4)));
|
||||
|
||||
/* The next power of two at or above `n`, clamped to what an i32 can index: the sort pads to one and
|
||||
@@ -174,10 +78,9 @@ static long long kv_pow2ceil(long long n) {
|
||||
return p;
|
||||
}
|
||||
|
||||
/* The claim list's capacity, in ids, from the launch's own operands and the device's LDS room (the
|
||||
* header above, "the claim list's size is derived"). `0` means a workgroup has no room at all, which
|
||||
* the shim refuses. `*room_out` is the dynamic LDS room in ints, so the entry cache can take what the
|
||||
* claim list leaves (header, "the entry cache"). */
|
||||
/* The claim list's capacity in ids, from the launch's operands and the device's LDS room (header,
|
||||
* "The claim list"); 0 when a workgroup has no room, which the shim refuses. `*room_out` is the
|
||||
* dynamic LDS room in ints, for the entry cache. */
|
||||
static int kv_claim_cap(long long M, long long pitch, int* room_out) {
|
||||
/* Static LDS: the two reduction arrays and the scalars. Everything else is dynamic. */
|
||||
const size_t stat = (size_t)kThreads * 2 * sizeof(int) + 64;
|
||||
@@ -195,8 +98,7 @@ static int kv_claim_cap(long long M, long long pitch, int* room_out) {
|
||||
}();
|
||||
*room_out = room;
|
||||
if (room < 1) return 0;
|
||||
/* The largest power of two the room holds: `cap` is always one, because the sort pads the list
|
||||
* to a power of two and must not pad past the buffer. */
|
||||
/* The largest power of two the room holds: the sort pads the list to one. */
|
||||
int top = 1;
|
||||
while (top <= room / 2) top *= 2;
|
||||
const long long bound = M * pitch; /* the call's claim ceiling */
|
||||
@@ -205,16 +107,13 @@ static int kv_claim_cap(long long M, long long pitch, int* room_out) {
|
||||
return p;
|
||||
}
|
||||
|
||||
/* The heat counter's two writes, the same function in all three implementations (libref's
|
||||
* heat_up/heat_down): a use bumps by one and saturates at 3, a sweep pass halves, and a negative
|
||||
* value -- never written by a legal call -- reads as cold rather than surviving every pass. */
|
||||
/* The heat counter's two writes, as libref's heat_up/heat_down: a use bumps by one and saturates
|
||||
* at 3, a sweep pass halves, and a negative value (never written by a legal call) reads as cold. */
|
||||
__device__ __forceinline__ int kv_heat_up(int h) { return h < 0 ? 1 : (h < 3 ? h + 1 : 3); }
|
||||
__device__ __forceinline__ int kv_heat_down(int h) { return h > 0 ? (h >> 1) : 0; }
|
||||
|
||||
/* Ascending order of `n` distinct claim ids in the claim list, padded to a power of two with
|
||||
* INT32_MAX, which sorts past every block id. A caller's buffer, because both paths sort: the whole
|
||||
* claim set when it fits the list and one window of the id space when it does not. Block ids are
|
||||
* distinct, so no equal pair decides anything. */
|
||||
/* Sort `n` distinct claim ids ascending, padded to a power of two with INT32_MAX. The caller's
|
||||
* buffer: LDS for the claim list, the row's scratch for a launch wider than it. */
|
||||
__device__ __forceinline__ void kv_sort_claims(int* list, int n, int tid) {
|
||||
int n2 = 1;
|
||||
while (n2 < n) n2 <<= 1;
|
||||
@@ -248,11 +147,9 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
__shared__ int s_epoch, s_lookups, s_nmiss, s_distinct, s_placed, s_overflow, s_claims, s_hits;
|
||||
__shared__ int s_free;
|
||||
__shared__ int s_cnt[kThreads], s_off[kThreads];
|
||||
/* The claim list, before the sort, `cap` ids of dynamic LDS (kv_claim_cap). Shared rather than
|
||||
* the row's scratch because the sort reads every element from every thread; the scratch still
|
||||
* holds the placed miss list, which is what the row declares and what the sweep and the copies
|
||||
* walk in order. `ecache` ints follow it: the value this call's lookup read for each selection
|
||||
* entry, which step 7 reuses (header, "the entry cache"). */
|
||||
/* The claim list, `cap` ids of dynamic LDS (kv_claim_cap), in LDS because the sort reads every
|
||||
* element from every thread; the placed miss list stays in the row's scratch. The entry cache
|
||||
* follows it (header, "The entry cache"). */
|
||||
R4D_DYN_LDS(int, s_dyn);
|
||||
int* const s_list = s_dyn;
|
||||
int* const s_ent = s_dyn + cap;
|
||||
@@ -272,8 +169,7 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
s_placed = 0;
|
||||
s_overflow = 0;
|
||||
s_free = 0;
|
||||
/* This call's miss count. A call that claims nothing returns it as zero below without
|
||||
* reaching the sweep, so it is cleared here rather than left as the last call's. */
|
||||
/* This call's miss count, cleared here: a call that claims nothing returns before the sweep. */
|
||||
ctl[2] = 0;
|
||||
}
|
||||
__syncthreads();
|
||||
@@ -291,24 +187,18 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
const int b = sel[e];
|
||||
if ((unsigned)b >= (unsigned)blocks) continue;
|
||||
const int s = res[b];
|
||||
/* The value this lookup saw, for step 7: a hit's slot cannot move in this call (the
|
||||
* sweep passes every slot this pass stamps with the epoch), so only an entry that was
|
||||
* absent here needs the map read again. Header, "the entry cache". */
|
||||
/* The value this lookup saw, for step 7 (header, "The entry cache"). */
|
||||
if (ecache > 0) s_ent[e] = s;
|
||||
if (s >= 0 && s < slots) {
|
||||
/* The stamp is this call's mark on the slot and the union's counter at once: the
|
||||
* exchange says whether this thread was the first to stamp it, so the ring is
|
||||
* counted here instead of walked after the fact. */
|
||||
/* The first thread to stamp the slot counts it into the union. */
|
||||
if (atomicExch(&slot_state[(size_t)s * sst_ld], epoch) != epoch) {
|
||||
/* One bump a slot a call: the exchange says this thread was the first to stamp
|
||||
* it, so a block twenty rows name gains one step of heat, not twenty. */
|
||||
/* One heat bump a slot a call, by the first stamper. */
|
||||
slot_state[(size_t)s * sst_ld + 1] =
|
||||
kv_heat_up(slot_state[(size_t)s * sst_ld + 1]);
|
||||
++hits;
|
||||
}
|
||||
} else if (s == -1) {
|
||||
/* One CAS wins per block, so this is the distinct-claim count, and the claim list
|
||||
* needs no walk over `res` to find them. */
|
||||
/* One CAS wins per block: the distinct-claim count and the list's fill, without a map walk. */
|
||||
if (atomicCAS(&res[b], -1, -2) == -1) {
|
||||
const int k = atomicAdd(&s_claims, 1);
|
||||
if (k < cap) s_list[k] = b;
|
||||
@@ -316,8 +206,7 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
}
|
||||
}
|
||||
}
|
||||
/* The launch's hit count: a per-thread total, then the same warp-first reduction the union
|
||||
* ends with. */
|
||||
/* The launch's hit count: per-thread totals, then the warp-first reduction the union uses. */
|
||||
s_cnt[tid] = hits;
|
||||
__syncthreads();
|
||||
if (tid < 32) {
|
||||
@@ -340,19 +229,12 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
const int want = claims < slots ? claims : slots;
|
||||
if (claims > 0) {
|
||||
if (claims <= cap) {
|
||||
/* The list holds every claim, so sorting it says exactly what walking `res` said --
|
||||
* ascending block id -- over `claims` elements instead of `blocks`. */
|
||||
kv_sort_claims(s_list, claims, tid);
|
||||
for (int i = tid; i < want; i += kThreads) miss_block[i] = s_list[i];
|
||||
} else {
|
||||
/* Above the list: the launch is wide enough that `M * sel_pitch` -- the claim ceiling
|
||||
* it declares -- passes the workgroup's LDS room, so the list is not held in shared
|
||||
* memory. The claims are gathered from the selection into the row's scratch instead and
|
||||
* sorted there, over `lookups` entries: the same ids, the same ascending order, and
|
||||
* still nothing about `blocks` in the cost. Only a call that fits its ring takes this
|
||||
* path; a call with more claims than the ring has slots cannot be listed at all and
|
||||
* keeps the map walk below, because a sorted list of the smallest `slots` claims has to
|
||||
* come from the whole claim set. */
|
||||
/* Above the list (header, "The claim list"): the claims are gathered from the selection
|
||||
* into the row's scratch and sorted there. A call with more claims than slots keeps
|
||||
* the map walk below, since the smallest `slots` claims need the whole claim set. */
|
||||
if (claims <= slots) {
|
||||
if (tid == 0) s_wc = 0;
|
||||
__syncthreads();
|
||||
@@ -363,8 +245,7 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
for (int i = tid; i < n; i += kThreads) {
|
||||
const int b = sel[(size_t)q * pitch + i];
|
||||
if ((unsigned)b >= (unsigned)blocks) continue;
|
||||
/* One claim per distinct block: the map is the set, so a block four rows
|
||||
* name enters the list once. -3 is "collected", restored below. */
|
||||
/* The map is the set: -3 marks a block already collected, restored below. */
|
||||
if (atomicCAS(&res[b], -2, -3) == -2) {
|
||||
const int k = atomicAdd(&s_wc, 1);
|
||||
if (k < slots) miss_block[k] = b;
|
||||
@@ -383,15 +264,13 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
/* `claims` ids, padded to a power of two: the row's scratch is sized for exactly
|
||||
* that (r4d_rad_kv_resolve_scratch). */
|
||||
/* Padded to a power of two, as the row's scratch is sized (r4d_rad_kv_resolve_scratch). */
|
||||
kv_sort_claims(miss_block, claims, tid);
|
||||
} else {
|
||||
/* More claims than the ring can hold: this call has overflowed whatever it places,
|
||||
* so the sweep stops at its first unplaceable miss and `ctl[3]` latches. The list
|
||||
* here is `blocks`-wide because the ascending order of the WHOLE claim set is the
|
||||
* contract, and with no structure able to hold it the map is where it lives. A legal
|
||||
* call -- one the ring can hold -- never reaches this. */
|
||||
/* More claims than slots: the call has overflowed, the sweep stops at its first
|
||||
* unplaceable miss and ctl[3] latches. The ascending order of the whole claim set
|
||||
* is the contract and nothing can hold it, so the map is walked. A call the ring can
|
||||
* hold never comes here. */
|
||||
const int chunk = (blocks + kThreads - 1) / kThreads;
|
||||
const int lo = (int)((long long)tid * chunk);
|
||||
const int hi = lo + chunk < blocks ? lo + chunk : blocks;
|
||||
@@ -434,7 +313,6 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
}
|
||||
}
|
||||
if (tid == 0) {
|
||||
/* The list is the first `want` claims in ascending order whichever path built it. */
|
||||
s_nmiss = want;
|
||||
s_overflow = claims > slots;
|
||||
s_placed = 0;
|
||||
@@ -443,12 +321,9 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
}
|
||||
|
||||
/* ---- 3b. how many slots are free ---- */
|
||||
/* A free slot is claimed before any resident block is evicted (phase 4), and this is what says
|
||||
* whether there is one to claim: a call whose ring is full -- where every slot holds a block --
|
||||
* must not pay a turn of scanning per miss to discover it, and above that a full ring never
|
||||
* becomes free again during the call. Counting in parallel costs one coalesced pass over the
|
||||
* two slot maps; the sweep then reads the count and, when it is zero, goes straight to CLOCK.
|
||||
* A slot this call stamped is not free whatever it holds: it is the call's own. */
|
||||
/* Free slots are taken before any resident block is evicted (step 4). One coalesced pass over
|
||||
* the slot maps counts them, so a full ring goes straight to CLOCK instead of scanning a turn
|
||||
* per miss. A slot this call stamped is not free: it is the call's own. */
|
||||
if (claims > 0) {
|
||||
int nf = 0;
|
||||
for (int s = tid; s < slots; s += kThreads)
|
||||
@@ -458,31 +333,15 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
__syncthreads();
|
||||
|
||||
/* ---- 4. one victim per miss: the block's own slot first, else a free slot, else CLOCK ---- */
|
||||
/* Identity first: a block whose id fits the ring and whose own slot is free goes there, so
|
||||
* res[b] = b for a context shorter than the ring. The attention's gather is a long run of
|
||||
* adjacent block ids, and a layer's slots are 2 KiB apart inside one stripe, so identity turns
|
||||
* that run into a sequential walk of one stripe instead of the order the blocks entered the
|
||||
* selection.
|
||||
*
|
||||
* It is only a placement preference, never a replacement one: it takes a slot only when that
|
||||
* slot is free, and it does not move the hand, so a ring that cannot give identity the slot
|
||||
* falls through to the walk below with the hand exactly where it was. The fallback is free slot
|
||||
* first, then CLOCK, so a depth where most ids are past `slots` places the same blocks in the
|
||||
* same slots.
|
||||
*
|
||||
* A free slot (nothing resident in it) is not a victim at all: taking it costs no block, so
|
||||
* every free slot is claimed before a live one is even considered. CLOCK's second chance over
|
||||
* the heat counter is what a ring with no free slot falls back to, and the free scan has no
|
||||
* side effect when it finds nothing (it halves no counter and leaves the hand where it
|
||||
* started), so a full ring takes exactly the victim the sweep below names.
|
||||
*
|
||||
* `free_left` is the call's free-slot count from phase 3b, decremented as the sweep fills one.
|
||||
* Once it is zero nothing can free a slot -- a placement makes a free slot live and an eviction
|
||||
* re-points a live one -- so a full ring pays the count once, not a scan per miss. */
|
||||
/* Identity first: a block whose id fits the ring and whose own slot is free goes there, so a
|
||||
* context shorter than the ring has res[b] = b and the attention's run of adjacent ids walks
|
||||
* one stripe in order. It never evicts and leaves the hand alone, so the fallback (free slot,
|
||||
* then CLOCK) is unchanged. The free scan changes nothing when it finds nothing, and
|
||||
* `free_left` (step 3b) only falls during the call, so a full ring pays the count once. */
|
||||
if (tid == 0 && claims > 0) {
|
||||
int hand = ctl[1];
|
||||
/* A hand outside the ring is a state fault libref refuses; start at the beginning
|
||||
* rather than address outside it. */
|
||||
/* A hand outside the ring is a state fault libref refuses; start at 0 rather than address
|
||||
* outside it. */
|
||||
if (hand < 0 || hand >= slots) hand = 0;
|
||||
int placed = 0;
|
||||
bool overflow = s_overflow;
|
||||
@@ -491,17 +350,14 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
for (int k = 0; k < nmiss; ++k) {
|
||||
const int b = miss_block[k];
|
||||
int victim = -1;
|
||||
/* Identity: the block's own slot, if the id fits the ring and the slot is free (or
|
||||
* already holds it). Leaving the hand alone is what keeps the fallback identical. */
|
||||
/* Identity, if the id fits and the slot is free or already holds it. */
|
||||
if (b < slots) {
|
||||
const int want = b;
|
||||
if (slot_state[(size_t)want * sst_ld] != epoch &&
|
||||
(slot_block[want] < 0 || slot_block[want] == b))
|
||||
victim = want;
|
||||
}
|
||||
/* Free first, in the same hand order CLOCK walks, so a ring with frees to give
|
||||
* places every miss identically in both implementations. A stamp of this call's epoch
|
||||
* is never taken, free or not: it is a slot the call itself already uses. */
|
||||
/* Free slots first, in CLOCK's hand order; a slot stamped this call is never taken. */
|
||||
if (victim < 0 && free_left > 0) {
|
||||
int h = hand;
|
||||
for (int scanned = 0; scanned < slots; ++scanned) {
|
||||
@@ -552,12 +408,9 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
/* A miss the sweep could not place is not resident: undo every remaining claim, so the next
|
||||
* call may claim them again. A `res` entry still -2 here is by definition such a claim (a
|
||||
* placed one holds its slot), and every claim is named by at least one selection entry, so the
|
||||
* selection reaches all of them: `lookups` entries instead of `blocks` map entries, and the
|
||||
* write is idempotent, so an entry repeating a block is harmless. The list is the shorter pass
|
||||
* when it holds every claim, which is the normal case. */
|
||||
/* Unplaced claims (still -2) revert to -1 so a later call may claim them. Every claim is named
|
||||
* by a selection entry, so the selection reaches all of them; the list is the shorter pass when
|
||||
* it holds every claim. */
|
||||
if (claims > 0) {
|
||||
if (s_distinct <= slots) {
|
||||
for (int k = tid; k < s_distinct; k += kThreads)
|
||||
@@ -578,27 +431,15 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
__syncthreads();
|
||||
|
||||
/* ---- 6. the copies, one block each, in miss order, in this launch ---- */
|
||||
/* One warp a miss, so every miss's host read is in flight at once and each warp's lanes are
|
||||
* independent. One 2 KiB copy out of the host mirror is PCIe transactions at ~1 us of latency
|
||||
* each, and a decode launch takes tens of them: a loop that waits out one miss at a time, or a
|
||||
* flattened loop that re-reads `miss_block`/`miss_slot` from the scratch for every lane, spends
|
||||
* the launch waiting. The copies are independent -- each writes its own slot -- so the order
|
||||
* between them is the miss order only for the record.
|
||||
/* One warp a miss, so every miss's host read is in flight at once: a 2 KiB copy from the
|
||||
* mirror is PCIe transactions at about 1 us each, and a decode launch has tens of misses.
|
||||
*
|
||||
* Four loads per thread, issued before any of them is stored from. A wave issues in order and a
|
||||
* store waits on its load, so `dst[i] = src[i]` at a stride of 32 makes the next iteration's load
|
||||
* wait behind the previous iteration's store and the 2 KiB copy pays the mirror's read latency
|
||||
* four times over instead of once (the trip count is `block_bytes`, a runtime value, so the
|
||||
* compiler cannot unroll it). Loading the four vectors of one thread's quarter of the block
|
||||
* first puts four requests in flight, and a block is
|
||||
* a whole number of them at the declared geometry (2 KiB = 128 vectors = one full turn of the
|
||||
* group), so the common path never takes the tail. Four more VGPRs: the kernel goes 32 -> 36
|
||||
* with no spill, and it runs one workgroup by design.
|
||||
*
|
||||
* The vectors are `kv_v16`, not `uint4`: that class's assignment is a 16-byte memcpy call, and a
|
||||
* memcpy is a load and a store that are adjacent by construction however the four are written in
|
||||
* the source, which is the serialised shape this loop exists to avoid. Builtin vectors leave the
|
||||
* four as four loads and four stores, which is what the scheduler needs. Same bytes either way. */
|
||||
* Four loads per thread before any store. A wave issues in order and a store waits on its
|
||||
* load, so `dst[i] = src[i]` at a stride of 32 would pay the read latency once per iteration;
|
||||
* the trip count is runtime, so the compiler cannot unroll it. A 2 KiB block is one full turn
|
||||
* of the group (128 vectors), so the common path never takes the tail. Four more VGPRs
|
||||
* (32 -> 36, no spill); the kernel runs one workgroup. `kv_v16` rather than `uint4` keeps
|
||||
* the loads apart from their stores. */
|
||||
const int placed = s_placed;
|
||||
const int lane = tid & 31;
|
||||
if (bbytes >= 16 && bbytes % 16 == 0) {
|
||||
@@ -615,9 +456,7 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
dst[i + 64] = c;
|
||||
dst[i + 96] = d;
|
||||
}
|
||||
/* A block that is not a whole number of four-wide turns -- `block_bytes` not a multiple
|
||||
* of 2048 -- finishes at the original one-vector stride, so every lane sequence is
|
||||
* covered exactly once whatever the pitch. */
|
||||
/* A block that is not a whole number of four-wide turns finishes one vector at a time. */
|
||||
for (; i < vec; i += 32) dst[i] = src[i];
|
||||
}
|
||||
} else {
|
||||
@@ -637,25 +476,21 @@ __global__ __launch_bounds__(kThreads) void kv_resolve_kernel(
|
||||
const size_t e = (size_t)q * pitch + i;
|
||||
const int b = sel[e];
|
||||
if ((unsigned)b >= (unsigned)blocks) continue;
|
||||
/* A hit's slot is the one step 2 read; anything absent then (-1, -2, -3) only the map
|
||||
* knows where the sweep placed it. Same index, same thread, so no barrier is needed. */
|
||||
/* A hit's slot is the one step 2 read; for an entry absent then, only the map knows where the
|
||||
* sweep placed it. */
|
||||
int s = ecache > 0 ? s_ent[e] : -1;
|
||||
if (s < 0) s = res[b];
|
||||
sel[e] = s >= 0 ? s : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* The distinct blocks this call touched, for the union the caller reports: the slots this call
|
||||
* hit or filled (counted in phase 2 and by the sweep) plus the claims it could not place. Both
|
||||
* halves are known by now -- distinct hit slots and distinct claimed blocks -- and an entry
|
||||
* count would overcount them, because many of a launch's rows share swaths of the history.
|
||||
* Nothing walks the ring for it. */
|
||||
/* The union: the distinct slots this call hit or filled, plus the claims it could not place. */
|
||||
if (tid == 0) {
|
||||
const int placed = s_placed;
|
||||
const int uni = s_hits + s_distinct;
|
||||
if (uni > ctl[10]) ctl[10] = uni;
|
||||
if (placed > ctl[11]) ctl[11] = placed;
|
||||
/* The depth the claim list had to hold, which is what the next size of it is derived from. */
|
||||
/* The depth the claim list had to hold. */
|
||||
if (s_distinct > ctl[12]) ctl[12] = s_distinct;
|
||||
uint64_t* const ctr = (uint64_t*)(ctl + 4);
|
||||
ctr[0] += (uint64_t)placed;
|
||||
@@ -691,15 +526,13 @@ static int r4d_kv_resolve_emit(long sel, long nsel, long res, long slot_block, l
|
||||
return R4D_NO(RAD_E_INVAL);
|
||||
if (M <= 0 || blocks <= 0 || slots <= 0 || pitch <= 0 || bbytes <= 0 || sst_ld < 2)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
/* The list is sized from this launch's own operands. A workgroup with no LDS room for even one
|
||||
* id cannot run the op at all, which is a shape the caller cannot satisfy rather than a slow
|
||||
* launch: refuse it. */
|
||||
/* A workgroup with no LDS room for one id cannot run the op: a shape the caller cannot satisfy,
|
||||
* so refuse. */
|
||||
int room = 0;
|
||||
const int cap = kv_claim_cap(M, pitch, &room);
|
||||
if (cap < 1) return R4D_NO(RAD_E_SHAPE);
|
||||
/* One int a selection entry for the entry cache (the header), while the room the claim list
|
||||
* leaves holds them all: a decode launch caches its 513, a prefill this wide does not and step 7
|
||||
* reads the map again. */
|
||||
/* The entry cache, one int an entry, while it fits beside the claim list: a decode launch caches
|
||||
* its 513, a wide prefill does not and step 7 reads the map. */
|
||||
const long long entries = (long long)M * pitch;
|
||||
const int ecache = entries <= (long long)(room - cap) ? (int)entries : 0;
|
||||
return R4D_EMIT(stream, kv_resolve_kernel, dim3(1), dim3(kThreads),
|
||||
@@ -736,21 +569,17 @@ extern "C" int r4d_rad_kv_resolve(const RadArgs* a, RadStream stream) {
|
||||
if (!se || !ns || !re || !sb || !st || !ct || !ho || !ca)
|
||||
return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
/* `M` is a RANGED parameter, so the resolved geometry carries the band's ceiling (max_tok),
|
||||
* not this launch's rows: a 625-token prefill and a one-row decode both arrive with 2048 here.
|
||||
* The operand names the call, as arch/common/rad_arch.h's "step-sized operands" rule says, so
|
||||
* the row count is `sel`'s own extent and the parameter is only the ceiling it may not pass. */
|
||||
/* `M` is ranged, so the geometry carries the band's ceiling (max_tok), not this launch's rows: the
|
||||
* row count is `sel`'s extent, and `M` the ceiling it may not pass. */
|
||||
const long long band = r4d_geti_or(a, "M", 0);
|
||||
const long long M = se->shape[0];
|
||||
const long long blocks = r4d_geti_or(a, "blocks", 0);
|
||||
/* The ring depth is the operand's, for the same reason: the pool is planned after declare, so
|
||||
* the declared `slots` is the context bound and a ring the engine sized smaller
|
||||
* (--kv-resident) arrives as a shorter `slot_block`. The parameter is the ceiling a
|
||||
* call may not pass (libref/ref_kvstream.cpp, "The parameters"). */
|
||||
/* The ring depth is `slot_block`'s: the pool is planned after declare, so a ring --kv-resident
|
||||
* sized smaller arrives shorter than the declared `slots`, its ceiling. */
|
||||
const long long slots_decl = r4d_geti_or(a, "slots", 0);
|
||||
const long long slots = sb->shape[0];
|
||||
/* The row pitch is the operand's too. Reading it from `sel_pitch` would let a view whose rows
|
||||
* are wider or narrower than its declared geometry be rewritten into its neighbour. */
|
||||
/* The row pitch is `sel`'s too: one different from the geometry would rewrite a row into its
|
||||
* neighbour. */
|
||||
const long long declared_pitch = r4d_geti_or(a, "sel_pitch", 0);
|
||||
const long long pitch = r4d_row_pitch(se);
|
||||
const long long bbytes = r4d_geti_or(a, "block_bytes", 0);
|
||||
@@ -763,8 +592,7 @@ extern "C" int r4d_rad_kv_resolve(const RadArgs* a, RadStream stream) {
|
||||
if (band > 0 && M > band) return R4D_NO(RAD_E_SHAPE);
|
||||
if (declared_pitch > 0 && pitch != declared_pitch) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
/* The map and the counts are one format, written by one op and read by the writer and the
|
||||
* sweep: i32, dense. */
|
||||
/* The maps and counts are one format: i32, dense. */
|
||||
const RadTensor* state[] = { se, ns, re, sb, st, ct };
|
||||
for (const RadTensor* t : state)
|
||||
if (t->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE);
|
||||
@@ -779,9 +607,8 @@ extern "C" int r4d_rad_kv_resolve(const RadArgs* a, RadStream stream) {
|
||||
if (ho->rank < 2 || ca->rank < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
if (ho->shape[0] < blocks || ca->shape[0] < slots) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* One block of one layer: the mirror's row and the pool's slot are the same bytes, and the
|
||||
* copy length `block_bytes` is both pitches. The pool arrives as a KV group's cache, so its
|
||||
* dtype is the cache layout's, not u8; only the byte pitch is fixed. */
|
||||
/* The mirror's row and the pool's slot are both `block_bytes`. The pool is a KV group's cache, so
|
||||
* its dtype is the cache layout's; only its byte pitch is fixed. */
|
||||
long long hdense = 0, pdense = 0;
|
||||
if (r4d_kv_block_row_bytes(ho, &hdense) != RAD_OK || hdense != bbytes)
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
@@ -790,8 +617,8 @@ extern "C" int r4d_rad_kv_resolve(const RadArgs* a, RadStream stream) {
|
||||
/* The counters are read as u64 in an i32 block. */
|
||||
if (((uintptr_t)ct->data & 7u) != 0) return R4D_NO(RAD_E_STRIDE);
|
||||
|
||||
/* The row's scratch: `nlist` ids (the miss list, padded to a power of two when a wide launch
|
||||
* sorts it there), then `slots` slots. */
|
||||
/* The row's scratch: `nlist` ids (the miss list, a power of two when a wide launch sorts there),
|
||||
* then `slots` slots. */
|
||||
const int64_t nlist = kv_pow2ceil(slots);
|
||||
const long long need = (nlist + slots) * 4;
|
||||
if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_INVAL);
|
||||
@@ -805,8 +632,7 @@ extern "C" int r4d_rad_kv_resolve(const RadArgs* a, RadStream stream) {
|
||||
(int)st->stride[0], stream);
|
||||
}
|
||||
|
||||
/* The miss list -- `next_pow2(slots)` block ids, because a launch too wide for the shared claim list
|
||||
* sorts the list in this scratch -- then `slots` slots (the header above). */
|
||||
/* `next_pow2(slots)` block ids (a wide launch sorts its claims here), then `slots` slots. */
|
||||
extern "C" int64_t r4d_rad_kv_resolve_scratch(const RadArgs* a) {
|
||||
const long long slots = r4d_geti_or(a, "slots", 0);
|
||||
if (slots <= 0 || slots > INT32_MAX) return 0;
|
||||
|
||||
+11
-35
@@ -688,28 +688,13 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// The store of a streamed KV group: `kv_store_fp8` into the group's two copies.
|
||||
//
|
||||
// A streamed group's ring is `slots` blocks deep while its block-id space is `blocks`, so a block's
|
||||
// id is not an address. Its host mirror is:
|
||||
//
|
||||
// host[blocks, kv_heads, block_size, 2 * head_dim] one block a row, identity layout
|
||||
//
|
||||
// and this kernel writes a token's k and v into the mirror's block `slot / block_size` ALWAYS, and
|
||||
// into the ring at `res[block]` only when the map says the block is resident. Both planes have the
|
||||
// same row pitch, so one offset serves both and the two copies cannot disagree.
|
||||
//
|
||||
// The residency test is here, not in the resolve, because the block a decode step writes is
|
||||
// usually the one the previous step already made resident: a mirror-only writer would leave the
|
||||
// ring's copy of that block short of this step's tokens, and the resolve does not re-copy a
|
||||
// resident block. The caller orders store, then resolve, then attention, so a block that is NOT
|
||||
// resident yet gets this step's bytes through the mirror and is copied in whole by the resolve.
|
||||
//
|
||||
// STATE FAULTS. libref refuses a slot naming a block past the id space and a map entry outside
|
||||
// [-1, slots) before writing anything. A device launch cannot return a host status, so this kernel
|
||||
// guards: a token whose block is out of range stores nothing, and a map entry outside its domain
|
||||
// reads as not resident (the mirror is still written, and the resolve refuses the step). A legal
|
||||
// call never takes either path and is bit-identical to the reference.
|
||||
// The store of a streamed KV group (docs/OPS.md "kv_store_streamed"): kv_store into the group's
|
||||
// two copies. A token's k and v go to its block's row of the host mirror always, and to the ring at
|
||||
// `res[block]` only when that block is resident; both planes have the same row pitch, so one offset
|
||||
// serves both. libref refuses a slot past the id space or a map entry outside [-1, slots); a kernel
|
||||
// cannot return a status, so here such a token stores nothing and such an entry reads as absent
|
||||
// (the mirror is still written and the resolve refuses the step). A legal call is bit-identical to
|
||||
// the reference.
|
||||
template <int BF16>
|
||||
__global__ __launch_bounds__(kThreads) void kv_store_streamed_kernel(
|
||||
const uint16_t* __restrict__ k, const uint16_t* __restrict__ v,
|
||||
@@ -2308,19 +2293,10 @@ static int kv_store_q4(const RadArgs* a, RadStream stream, int k6) {
|
||||
extern "C" int r4d_rad_kv_store_fp8v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 0); }
|
||||
extern "C" int r4d_rad_kv_store_k6v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 1); }
|
||||
|
||||
/* The store of a streamed group: `kv_store`'s geometry and E4M3 conversion, plus the group's
|
||||
* residency map (`res`) and its host mirror (`host`). The mirror is the truth and is written for
|
||||
* every token with a slot; the ring is written only when `res[block] >= 0`. Both are one block a
|
||||
* row of the same byte pitch, so the row arithmetic is the cache's, unchanged.
|
||||
*
|
||||
* `res` is read, never written: residency is the resolve's decision, and this op must not move the
|
||||
* map under a selection the indexer already resolved. A block id past the mirror's extent or a map
|
||||
* entry outside [-1, slots) is a state fault that libref refuses; the kernel guards instead (see
|
||||
* kv_store_streamed_kernel), since a device launch cannot return a host status.
|
||||
*
|
||||
* The cache is E4M3 or bf16. Streaming is dtype-agnostic beyond the two writers: the mirror and the
|
||||
* ring are byte planes of one paged layout whose pitch is `block_bytes`, so a bf16 group doubles
|
||||
* every offset and stores the values kv_store_bf16 stores. */
|
||||
/* The store of a streamed group: kv_store's geometry and conversion (E4M3, or bf16 with no
|
||||
* descales), plus the residency map `res` (read, never written: residency is the resolve's) and the
|
||||
* host mirror `host`. Both are one block a row of the same byte pitch. State faults are guarded,
|
||||
* not refused (see kv_store_streamed_kernel). */
|
||||
extern "C" int r4d_rad_kv_store_streamed(const RadArgs* a, RadStream stream) {
|
||||
KvStoreGeom g{};
|
||||
const int rc = kv_store_geom(a, &g);
|
||||
|
||||
@@ -260,10 +260,15 @@ int r4d_rad_sub_i32 (const RadArgs*, RadStream);
|
||||
/* r4d_video.hip */
|
||||
int r4d_rad_rms_mod (const RadArgs*, RadStream);
|
||||
int r4d_rad_rms_mod_quant_fp8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_rms_mod_quant_i8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_flow_x0_step (const RadArgs*, RadStream);
|
||||
int r4d_rad_flow_res_multistep (const RadArgs*, RadStream);
|
||||
int r4d_rad_patch_unfold (const RadArgs*, RadStream);
|
||||
int r4d_rad_vtile_gather (const RadArgs*, RadStream);
|
||||
int r4d_rad_vtile_stitch (const RadArgs*, RadStream);
|
||||
int r4d_rad_vtile_plan (const RadArgs*, RadStream);
|
||||
int r4d_rad_vtile_crop (const RadArgs*, RadStream);
|
||||
int r4d_rad_vtile_join (const RadArgs*, RadStream);
|
||||
int r4d_rad_grid_pos3 (const RadArgs*, RadStream);
|
||||
int r4d_rad_snake_aa (const RadArgs*, RadStream);
|
||||
/* r4d_upscaler.hip: a video latent upscaler's 3D convolution, group norm, temporal depthwise
|
||||
@@ -274,6 +279,7 @@ int r4d_rad_tconv_dw (const RadArgs*, RadStream);
|
||||
int r4d_rad_resize_bilinear (const RadArgs*, RadStream);
|
||||
int r4d_rad_patch_fold (const RadArgs*, RadStream);
|
||||
int r4d_rad_flow_renoise (const RadArgs*, RadStream);
|
||||
int r4d_rad_cond_aug (const RadArgs*, RadStream);
|
||||
int r4d_rad_rope_split (const RadArgs*, RadStream);
|
||||
int r4d_rad_head_gate (const RadArgs*, RadStream);
|
||||
int r4d_rad_ltx_guide (const RadArgs*, RadStream);
|
||||
@@ -733,6 +739,7 @@ int r4d_rad_cast_widen (const RadArgs*, RadStream);
|
||||
int r4d_rad_cast_f16 (const RadArgs*, RadStream);
|
||||
int r4d_rad_cast_bf16 (const RadArgs*, RadStream);
|
||||
int r4d_rad_pool_rows (const RadArgs*, RadStream);
|
||||
int r4d_rad_pool_cols (const RadArgs*, RadStream);
|
||||
int r4d_rad_relu (const RadArgs*, RadStream);
|
||||
int r4d_rad_silu (const RadArgs*, RadStream);
|
||||
int r4d_rad_gelu (const RadArgs*, RadStream);
|
||||
|
||||
@@ -58,8 +58,8 @@ struct QkKvStore {
|
||||
int blocks;
|
||||
};
|
||||
|
||||
/* The cache forms KV selects. The two STREAMED forms are the same store with two destination
|
||||
* planes: E4M3 (the fp8 QSA family) and bf16 (the default cache dtype). */
|
||||
/* The cache forms KV selects. The two streamed forms are the same store into two planes, E4M3
|
||||
* and bf16. */
|
||||
enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4 = 4,
|
||||
QK_KV_STREAMED = 5, QK_KV_STREAMED_BF16 = 6 };
|
||||
|
||||
@@ -443,17 +443,11 @@ extern "C" int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs* args, RadStream
|
||||
: qk_body<QK_KV_FP8>(args, stream, kvs);
|
||||
}
|
||||
|
||||
/* The prologue with the STREAMED store folded in: a streamed group's cache is a ring of
|
||||
* `n_blocks` slots over a `blocks`-wide block-id space, and its truth is the pinned host mirror.
|
||||
* Each token's rotated k and its v go to the mirror's block row ALWAYS and to `kv_cache[res[block]]`
|
||||
* only when the residency map calls the block resident (docs/OPS.md "kv_store_streamed"), so this
|
||||
* row replaces `qk_norm_rope_gate` + `kv_store_streamed` with one launch a layer and one chain
|
||||
* between store, resolve and attention.
|
||||
*
|
||||
* The bytes are the pair's exactly: `k_out`'s bf16 value is the one the E4M3 conversion reads, and
|
||||
* both planes are the same dense rows of the same paged layout, so the folded write and the split
|
||||
* write are the same arithmetic. The cache is E4M3 (the fp8 QSA family) or bf16 (the default
|
||||
* `--kv-cache-dtype`, where both planes are the value itself, as kv_store_bf16 writes it). */
|
||||
/* The prologue with the streamed store folded in (docs/OPS.md "kv_store_streamed"): each token's
|
||||
* rotated k and its v go to the mirror's block row always and to `kv_cache[res[block]]` only where
|
||||
* the block is resident, one launch where qk_norm_rope_gate + kv_store_streamed were two. The bytes
|
||||
* are the pair's: `k_out`'s bf16 value is what the conversion reads, and both planes share one
|
||||
* layout. E4M3, or bf16 storing the values themselves. */
|
||||
extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_streamed(const RadArgs* args, RadStream stream) {
|
||||
const RadTensor* k = r4d_opt(args, QK_K);
|
||||
const RadTensor* qg = r4d_opt(args, QK_QGATE);
|
||||
|
||||
+165
-39
@@ -291,9 +291,8 @@ static const RadOperandSpec oQkNormRopeGateKv[] = {
|
||||
{ "slot_mapping", RAD_OPD_IN, 0 },
|
||||
{ "kv_cache", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
/* The prologue with a streamed group's store folded in: the same parameters and operands, then the
|
||||
* residency map and the layer's host mirror, which the store needs and the ring does not. The cache
|
||||
* is E4M3 only (streaming ships for the fp8 QSA family). */
|
||||
/* The prologue with a streamed group's store folded in: the same parameters and operands, then
|
||||
* the residency map and the layer's host mirror. */
|
||||
static const RadOperandSpec oQkNormRopeGateKvStreamed[] = {
|
||||
{ "q_gate", RAD_OPD_IN, 1 },
|
||||
{ "k", RAD_OPD_IN, 0 },
|
||||
@@ -1351,13 +1350,10 @@ static const RadOperandSpec oQsaSelect[] = {
|
||||
{ "seqused", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
/* `kv_resolve`, a new op whose schema this plugin fixes: the residency map of a streamed KV
|
||||
* group, between `qsa_select` and the attention. `sel` is block ids in and ring slots out;
|
||||
* `res`, `slot_block`, `slot_state` and `ctl` are the state it keeps between calls, so its row is
|
||||
* not concurrent. The miss list is the row's scratch, not an operand: nothing outside the launch
|
||||
* reads it. `block_bytes` is a byte extent, not `block_size`: the op only moves bytes, and a
|
||||
* `block_size` key would make it the KV group's consumer, taking the block size the resolved
|
||||
* attention kernel must read. */
|
||||
/* `kv_resolve`: the residency map of a streamed KV group, between `qsa_select` and the attention
|
||||
* (docs/OPS.md). `sel` is block ids in, ring slots out; the maps and `ctl` are state kept between
|
||||
* calls, so the row is not concurrent. The miss list is the row's scratch. `block_bytes`, not
|
||||
* `block_size`, so the op does not become the KV group's consumer (libref/ref_kvstream.cpp). */
|
||||
static const RadParamSpec pKvResolve[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "blocks", RAD_P_INT, RAD_REQUIRED },
|
||||
@@ -1628,9 +1624,8 @@ static const RadOperandSpec oGemmNtQGated[] = {
|
||||
{ "out_bf16", RAD_OPD_OUT, 1 },
|
||||
};
|
||||
/* The same fold over an OCP-MXFP4 gate_up weight, which gemm_nt_q reads with a per-row reference
|
||||
* exponent (`b_ref`) beside its scale plane. A schema of its own rather than an optional operand on
|
||||
* gemm_nt_q_gated: an op's operand count is part of its contract with the plugins already built
|
||||
* against it. */
|
||||
* exponent (`b_ref`). A schema of its own, since an op's operand count is fixed for the plugins
|
||||
* built against it. */
|
||||
static const RadOperandSpec oGemmNtQGatedMx[] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "a_scale", RAD_OPD_IN, 0 },
|
||||
@@ -2100,10 +2095,8 @@ static const RadOperandSpec oKvStore[] = {
|
||||
{ "slot_mapping", RAD_OPD_IN, 0 },
|
||||
{ "kv_cache", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
/* `kv_store` for a streamed group. `host` is the group's authoritative mirror and is always
|
||||
* written, `res` is the residency map that says whether the block is in the ring (the ring slot is
|
||||
* written only when `res[block] >= 0`). The parameters are kv_store's: the layout and the E4M3
|
||||
* conversion are the same, only the destination set differs. */
|
||||
/* `kv_store` for a streamed group: `host`, the authoritative mirror, always written; the ring slot
|
||||
* only when `res[block] >= 0`. kv_store's parameters, layout and conversion. */
|
||||
static const RadParamSpec pKvStoreStreamed[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "head_dim", RAD_P_INT, RAD_REQUIRED },
|
||||
@@ -2498,9 +2491,11 @@ static const RadOperandSpec oGateAdd[] = {
|
||||
{ "y", RAD_OPD_IN, 0 }, { "g", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
|
||||
{ "x", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"),
|
||||
P_F64("max_period"), P_INTO("round"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTimestep[] = { { "t", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
|
||||
P_INTO("round"), P_F64O("clamp_min"), P_INTO("curve"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oTimestep[] = { { "t", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
{ "table", RAD_OPD_WEIGHT, 1 } };
|
||||
static const RadOperandSpec oGather2[] = {
|
||||
{ "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
@@ -2577,7 +2572,7 @@ static const RadOperandSpec oAttnPS[] = {
|
||||
/* ---- audio generation (r4d_audio.hip); the same specs as libref's (ref_registry.cpp). */
|
||||
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
|
||||
P_INTO("causal"), P_INTO("stride"),
|
||||
P_INTO("causal"), P_INTO("stride"), P_INTO("pad"),
|
||||
P_INTO("cu_div") };
|
||||
static const RadOperandSpec oConv1d[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
|
||||
@@ -2698,7 +2693,7 @@ static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_
|
||||
static const RadOperandSpec oRmsMod[] = {
|
||||
{ "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 },
|
||||
{ "w", RAD_OPD_WEIGHT, 1 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
{ "z", RAD_OPD_OUT, 0 },
|
||||
{ "z", RAD_OPD_OUT, 0 }, { "colmap", RAD_OPD_IN, 1 },
|
||||
};
|
||||
static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
|
||||
P_INT("gated"), P_STR("dtype"), P_F64O("wadd"),
|
||||
@@ -2707,11 +2702,17 @@ static const RadOperandSpec oRmsModQ[] = {
|
||||
{ "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 },
|
||||
{ "w", RAD_OPD_WEIGHT, 1 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
{ "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "z", RAD_OPD_OUT, 1 },
|
||||
{ "colmap", RAD_OPD_IN, 1 },
|
||||
};
|
||||
static const RadOperandSpec oFlowX0[] = {
|
||||
{ "v", RAD_OPD_IN, 0 }, { "t", RAD_OPD_IN, 0 }, { "sigma", RAD_OPD_IN, 0 },
|
||||
{ "sigma_next", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec oFlowRM[] = {
|
||||
{ "v", RAD_OPD_IN, 0 }, { "x0", RAD_OPD_INOUT, 0 }, { "sigma", RAD_OPD_IN, 0 },
|
||||
{ "r", RAD_OPD_IN, 0 }, { "hb1", RAD_OPD_IN, 0 }, { "hb2", RAD_OPD_IN, 0 },
|
||||
{ "order", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pPatchUnfold[] = { P_INT("M"), P_INT("C"), P_INT("pt"), P_INT("ph"),
|
||||
P_INT("pw"), P_STR("mul"), P_STR("add"),
|
||||
P_STR("dtype") };
|
||||
@@ -2733,6 +2734,23 @@ static const RadOperandSpec oVtileStitch[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "prev", RAD_OPD_INOUT, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
/* The tiled encoder (r4d_video.hip): the plan, the cut and the blend. `geom` is the request's
|
||||
* (clip, H, W); plan and crop take it in pixels, join in latent units. */
|
||||
static const RadParamSpec pVtilePlan[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"),
|
||||
P_INT("ratio") };
|
||||
static const RadOperandSpec oVtilePlan[] = {
|
||||
{ "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pVtileCrop[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"),
|
||||
P_INT("ratio"), P_STR("dtype") };
|
||||
static const RadOperandSpec oVtileCrop[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pVtileJoin[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"),
|
||||
P_INT("n"), P_STR("dtype") };
|
||||
static const RadOperandSpec oVtileJoin[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_INT("W"),
|
||||
P_INT("period"), P_F64("scale") };
|
||||
static const RadOperandSpec oGridPos3[] = { { "y", RAD_OPD_OUT, 0 } };
|
||||
@@ -2740,8 +2758,9 @@ static const RadOperandSpec oGridPos3[] = { { "y", RAD_OPD_OUT, 0 } };
|
||||
/* ---- a video latent upscaler (r4d_upscaler.hip); the same specs as libref's. `geom` is the
|
||||
* request's volume, i32 on the device; patch_fold takes patch_unfold's specs. */
|
||||
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("kt"), P_STR("dtype"), P_STRO("tpad"),
|
||||
P_INTO("tpre") };
|
||||
P_INT("kt"), P_STR("dtype"), P_INTO("stride"),
|
||||
P_INTO("stride_t"), P_INTO("causal"), P_STRO("pad"),
|
||||
P_INTO("reflect"), P_STRO("tpad"), P_INTO("tpre") };
|
||||
static const RadOperandSpec oConv3d[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
|
||||
{ "geom", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 },
|
||||
@@ -2765,6 +2784,11 @@ static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stre
|
||||
static const RadOperandSpec oFlowRenoise[] = {
|
||||
{ "sigma", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pCondAug[] = { P_INT("M"), P_INT("n"), P_INT("stream"), P_F64("aug"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oCondAug[] = {
|
||||
{ "seed", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
|
||||
/* ---- LTX-2 (r4d_ltx.hip); the same specs as libref's. */
|
||||
static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
|
||||
@@ -2915,6 +2939,10 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("pool_rows", pPoolRows, oUnary,
|
||||
"Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded, then "
|
||||
"times `mult` and rounded again."),
|
||||
SCHEMA("pool_cols", pPoolRows, oUnary,
|
||||
"Column c of row m of y is the mean of x[m]'s columns [c*k, c*k + k), summed in f32 and "
|
||||
"rounded, then times `mult` and rounded again. n, the input width, is a multiple of k; "
|
||||
"y has n / k columns."),
|
||||
SCHEMA("sigmoid", pMnDtype, oUnary, "y = 1 / (1 + exp(-x))."),
|
||||
SCHEMA("relu", pMnDtype, oUnary, "y = max(x, 0)."),
|
||||
SCHEMA("silu", pMnDtype, oUnary, "y = x * sigmoid(x)."),
|
||||
@@ -3574,7 +3602,10 @@ static const RadOpSchema kSchemas[] = {
|
||||
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual through its sequence's gate; "
|
||||
"with `act` none the gate is g itself, x = bf16(x + bf16(g[seq] * y))."),
|
||||
SCHEMA("timestep_embed", pTimestep, oTimestep,
|
||||
"the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2))."),
|
||||
"the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2)). "
|
||||
"With `curve` > 0 and a `table` [curve, n] f32 operand instead: y[m] is `table` sampled at "
|
||||
"pos = clamp01(max(t[m], clamp_min)) * (curve - 1), linearly between the two rows around "
|
||||
"pos -- an adaln time-embedding curve precomputed at convert."),
|
||||
SCHEMA("gather_rows2", pGenMn, oGather2,
|
||||
"y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]."),
|
||||
SCHEMA("lane_gather", pLane, oLaneGather, "y[cu[e] + k] = src[lane[e] * stride + k]."),
|
||||
@@ -3619,7 +3650,10 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("conv1d", pConv1d, oConv1d,
|
||||
"a 1-D convolution over the sequences cu_seqlens bounds, channels innermost, zeros outside "
|
||||
"each; dilation `dil`, padding dil (k - 1) / 2 a side or, with `causal`, dil (k - 1) on "
|
||||
"the left; `res` added after the bias, then `act`."),
|
||||
"the left; `res` added after the bias, then `act`. bf16 only with `stride` > 1: one "
|
||||
"sequence [0, rows of x], an explicit `pad` and any k, output row m reading "
|
||||
"x[m * stride + tap * dil - pad], the output rows (rows + 2 pad - dil (k - 1) - 1) / "
|
||||
"stride + 1."),
|
||||
SCHEMA("conv_t1d", pConvT1d, oConvT1d,
|
||||
"a transposed 1-D convolution of kernel `k` (2 stride by default, or stride), padding "
|
||||
"`pad` ((k - stride) / 2 by default, 0 the causal form): each sequence grows `stride` "
|
||||
@@ -3672,9 +3706,15 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("rms_mod_quant_fp8", pRmsModQ, oRmsModQ,
|
||||
"rms_mod with the chain in bf16, then (q, scale) = quant_act_fp8(z, group); z written "
|
||||
"when bound."),
|
||||
SCHEMA("rms_mod_quant_i8", pRmsModQ, oRmsModQ,
|
||||
"rms_mod with the chain in bf16, then (q, scale) = quant_act_i8g(z, group) -- int8 codes "
|
||||
"a quarter of E4M3's error on the same byte; z written when bound."),
|
||||
SCHEMA("flow_x0_step", pGenMn, oFlowX0,
|
||||
"x = r x + (1 - r) (x + (1 - t) v), r = sigma_next / sigma, each step one f32 "
|
||||
"rounding."),
|
||||
SCHEMA("flow_res_multistep", pGenMn, oFlowRM,
|
||||
"x = r x + hb1 (x + sigma v) + hb2 x0, r = sigma_next / sigma, x0 the previous estimate; "
|
||||
"order<2 is Euler."),
|
||||
SCHEMA("patch_unfold", pPatchUnfold, oPatchUnfold,
|
||||
"patch rows unfolded to voxel rows and denormalised with f32 lists."),
|
||||
SCHEMA("vtile_gather", pVtileGather, oVtileGather,
|
||||
@@ -3683,12 +3723,29 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("vtile_stitch", pVtileStitch, oVtileStitch,
|
||||
"a decoded chunk's tiles stitched into RGB bytes, blended with the previous chunk's "
|
||||
"tail."),
|
||||
SCHEMA("vtile_plan", pVtilePlan, oVtilePlan,
|
||||
"the tiled encoder's plan for one frame of geom = (clip, H, W) pixels: the encoder's "
|
||||
"tile split over the spatial axes in latent units, tiles row-major; row t of the "
|
||||
"i32 [M, 22] y is the tile's first pixel, its pixel extent and the six level "
|
||||
"volumes (1, th / 2^min(L, 4), tw / 2^min(L, 4)); M is the tile count."),
|
||||
SCHEMA("vtile_crop", pVtileCrop, oVtileCrop,
|
||||
"one frame's pixel plane [>= H W, 3] (geom = (clip, H, W) pixels) cut into "
|
||||
"vtile_plan's tiles: y [M, 3] the tiles' pixels tile-major, M the tiles' pixel "
|
||||
"count."),
|
||||
SCHEMA("vtile_join", pVtileJoin, oVtileJoin,
|
||||
"the tiled encoder's per-tile moments blended into the canvas y [M, n] of "
|
||||
"geom = (clip, lat_h, lat_w): each position blended with the tile above and then "
|
||||
"the tile to the left, both RAW, the products and sums rounding to x's dtype."),
|
||||
SCHEMA("grid_pos3", pGridPos3, oGridPos3,
|
||||
"a video decoder's rotary positions over tiles of `period` rows, f32 [3, M]."),
|
||||
SCHEMA("conv3d_ndhwc", pConv3d, oConv3d,
|
||||
"a stride-1 `same` 3D convolution over NDHWC voxel rows of the device volume geom = "
|
||||
"(T, H, W), PyTorch's [cout, cin, kt, k, k] weight, f32 accumulation; with `res`, "
|
||||
"y = rd(rd(acc + b) + res), res may alias y."),
|
||||
"a 3D convolution over NDHWC voxel rows of the device volume geom = (T, H, W), "
|
||||
"PyTorch's [cout, cin, kt, k, k] weight, f32 accumulation; default stride 1 with "
|
||||
"`same` zero padding; `stride`/`stride_t` > 1 (3x3x3 only) pad first then stride, "
|
||||
"`causal` 1 takes the temporal padding front-only (kt - 1 zeros, none behind), `pad` "
|
||||
"`down` pads none above and left and one below and right, `reflect` 1 mirrors the "
|
||||
"spatial padding instead of zeroing it; with `res`, y = rd(rd(acc + b) + res), res "
|
||||
"may alias y."),
|
||||
SCHEMA("group_norm", pGroupNorm, oGroupNorm,
|
||||
"nn.GroupNorm over all of y's rows (biased variance, rstd in f32), then the optional "
|
||||
"modulation v (1 + mod[0:n]) + mod[n:2n] and `act` (none or silu), one rounding; "
|
||||
@@ -3704,6 +3761,10 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("flow_renoise", pFlowRenoise, oFlowRenoise,
|
||||
"x = (1 - sigma) x + sigma z, z the (seed, stream) normal stream at element k n + c, "
|
||||
"each step one f32 rounding."),
|
||||
SCHEMA("cond_aug", pCondAug, oCondAug,
|
||||
"x = a x + oma z, a the `aug` parameter, oma the f32 of the f64 1 - aug, z the "
|
||||
"(seed, stream) normal stream at element k n + c, each step one f32 rounding: the "
|
||||
"reference's condition-noise augmentation."),
|
||||
SCHEMA("rope_split", pRopeSplit, oRopeSplit,
|
||||
"LTX-2's split rotary over fractional coordinates: the pairs of all heads on one "
|
||||
"ladder, the first `pad` unrotated, the axes interleaved; each head's halves turned "
|
||||
@@ -4204,6 +4265,10 @@ static const RadConstraint cCastNarrow[] = {
|
||||
static const RadConstraint cAttnDenseH64[] = {
|
||||
C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"),
|
||||
};
|
||||
/* head_dim 256 without GQA, sequences past the small kernel's. */
|
||||
static const RadConstraint cAttnDenseH256G1[] = {
|
||||
C_EQ("head_dim", 256), C_EQ("gqa", 1), C_GE("max_seqlen", 33), C_IN("dtype", "bf16"),
|
||||
};
|
||||
/* Unlimited-OCR's SAM tower (r4d_sam_attn_bf16.hip): one block per (segment, tile, head), a thread
|
||||
* a query row, q and the output accumulator in registers; only head_dim 64 is instantiated and a
|
||||
* rel_pos table that is not 2*tile-1 rows is linear-resampled on read (get_rel_pos), so the 127-row
|
||||
@@ -4827,8 +4892,8 @@ static const RadConstraint cGemmNtQGatedFp8[] = {
|
||||
C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), C_IN("act", "silu"),
|
||||
};
|
||||
/* r4d_gemm_mxfp4a8_gated_gemv: the gemv row's WMMA form (K a multiple of 128, M <= 8) with a block
|
||||
* per 16-column tile pair of the gated output; N/2 a multiple of 128, so each 128-column group's eight
|
||||
* blocks meet at its last arriver, which quantises the group. */
|
||||
* per 16-column tile pair of the gated output. N/2 is a multiple of 128, so each 128-column
|
||||
* group's eight blocks meet at its last arriver, which quantises the group. */
|
||||
static const RadConstraint cGemmNtQGatedMx[] = {
|
||||
C_LE("M", 8), C_DIV("K", 128), C_DIV("N", 256), C_EQ("group", 32), C_IN("dtype", "mxfp4a8"),
|
||||
C_IN("act", "silu gelu_tanh"),
|
||||
@@ -5380,8 +5445,9 @@ static const RadConstraint cGeluQuick[] = { C_IN("dtype", "bf16 f32") };
|
||||
/* The two lists are kernel arguments, 64 floats each at most (r4d_gen.hip). */
|
||||
static const RadConstraint cGenAffine[] = { C_IN("dtype", "bf16"), C_LE("n", 64) };
|
||||
static const RadConstraint cGenAffineF32[] = { C_IN("dtype", "f32"), C_LE("n", 64) };
|
||||
static const RadConstraint cGenTimestep[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) };
|
||||
static const RadConstraint cGenTimestepF32[] = { C_IN("dtype", "f32"), C_DIV("n", 2) };
|
||||
/* No parity on `n`, which a curve table's need not have: the shim checks the sinusoid's. */
|
||||
static const RadConstraint cGenTimestep[] = { C_IN("dtype", "bf16") };
|
||||
static const RadConstraint cGenTimestepF32[] = { C_IN("dtype", "f32") };
|
||||
/* The paged prefix at libr4d's block of 16, both caches bf16, up to eight query heads a KV head
|
||||
* (the shim takes 1, 2, 4 and 8). */
|
||||
static const RadConstraint cAttnPrefixSelf[] = {
|
||||
@@ -5695,6 +5761,15 @@ static const RadKernelInfo kKernels[] = {
|
||||
ROW(cBf16Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_pool_rows },
|
||||
|
||||
{ "pool_cols_bf16", "pool_cols", "elem",
|
||||
"mean of every k consecutive columns within a row, then a multiplier: an encoder posterior's "
|
||||
"adaptive-average pooling over the feature axis",
|
||||
"any n and k with n % k == 0; a thread an output column",
|
||||
"bf16 in and out, f32 sum, two roundings",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cBf16Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_pool_cols },
|
||||
|
||||
{ "rmsnorm_bf16", "rmsnorm", "norm",
|
||||
"root-mean-square norm with a gain, two passes over the row",
|
||||
"any n; the sum of squares accumulates in f32 and only the store narrows",
|
||||
@@ -7089,6 +7164,16 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
ROW(cAttnDenseH64), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h256_bf16", "attn_dense", "attn",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window or "
|
||||
"blocks, or causal with an optional window behind",
|
||||
"head_dim 256, multi-head (no GQA), q/k/v/o at their own token pitches (column slices of a "
|
||||
"fused projection allowed), sequences past the small kernel's 32-row LDS bound",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH256G1), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h256_gqa2_bf16", "attn_dense", "attn",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
@@ -8297,9 +8382,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, nullptr, r4d_rad_qsa_select, r4d_rad_qsa_select_scratch, nullptr, nullptr,
|
||||
r4d_shape_qsa_select },
|
||||
|
||||
/* The residency map of a streamed KV group. One workgroup: the CLOCK hand is serial state, and the
|
||||
* phases are barriers over the entries, the block-id space and the ring. The copy is the same
|
||||
* launch, so one step is one dispatch rather than one per claim. */
|
||||
/* The residency map of a streamed KV group, in one workgroup: the CLOCK hand is serial state and
|
||||
* the phases are barriers. The copies run in the same launch. */
|
||||
{ "kv_resolve_i32", "kv_resolve", "attn",
|
||||
"turn selected KV block ids into ring slots, evict by CLOCK and copy misses in from the host",
|
||||
"any block count, ring depth and block byte extent; the mirror and the ring are read by byte "
|
||||
@@ -8785,9 +8869,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, nullptr, r4d_rad_qk_norm_rope_gate_kv_store, nullptr, nullptr, nullptr,
|
||||
r4d_shape_qk_norm_rope_gate_kv_store, nullptr, r4d_fuse_qk_norm_rope_gate_kv_store },
|
||||
|
||||
/* The prologue and the STREAMED cache store in one launch: the mirror for every token, the ring
|
||||
* only where the residency map says the block is resident. The operands are the pair's, plus the
|
||||
* map and the mirror. */
|
||||
/* The prologue and the streamed store in one launch: the mirror for every token, the ring only
|
||||
* where the block is resident. The pair's operands, plus the map and the mirror. */
|
||||
{ "qk_norm_rope_gate_kv_store_streamed_fp8", "qk_norm_rope_gate_kv_store_streamed", "attn",
|
||||
"qk_norm_rope_gate, and kv_store_streamed (host mirror always, resident ring slot too) from the "
|
||||
"same launch",
|
||||
@@ -9527,6 +9610,14 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
ROW(cRmsModQ), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_rms_mod_quant_fp8 },
|
||||
|
||||
{ "rms_mod_quant_i8_bf16", "rms_mod_quant_i8", "norm",
|
||||
"gated residual, modulated RMS norm and quant_act_i8g in one pass: a workgroup a row",
|
||||
"n % 128 == 0, n <= 8192, group 128; s a column slice at its own pitch",
|
||||
"bf16 rows, gain and table, int8 codes and f32 scales",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cRmsModQ), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_rms_mod_quant_i8 },
|
||||
|
||||
{ "flow_x0_step_f32", "flow_x0_step", "elem",
|
||||
"a sampler step toward the clean estimate", "any M, row pitches honoured",
|
||||
"f32 state, f32 or bf16 velocity",
|
||||
@@ -9534,6 +9625,13 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
ROW(cGenF32), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_flow_x0_step },
|
||||
|
||||
{ "flow_res_multistep_f32", "flow_res_multistep", "elem",
|
||||
"a second-order sampler step on the clean estimate", "any M, row pitches honoured",
|
||||
"f32 state and estimate history, f32 or bf16 velocity",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenF32), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_flow_res_multistep },
|
||||
|
||||
{ "patch_unfold_f32", "patch_unfold", "elem",
|
||||
"patch rows to denormalised voxel rows, the geometry read on the device",
|
||||
"C <= 64, row pitches honoured", "f32",
|
||||
@@ -9557,6 +9655,27 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_vtile_stitch },
|
||||
|
||||
{ "vtile_plan", "vtile_plan", "elem",
|
||||
"the tiled encoder's per-tile geometry table: a thread a (tile, entry)",
|
||||
"any M; the split reads geom on the device", "i32 table, i32 geom",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_vtile_plan },
|
||||
|
||||
{ "vtile_crop", "vtile_crop", "elem",
|
||||
"a frame's pixel plane cut into the encode tiles: a thread a tile pixel row",
|
||||
"row pitches honoured", "f32 or bf16 plane and tiles",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_vtile_crop },
|
||||
|
||||
{ "vtile_join", "vtile_join", "elem",
|
||||
"the encode tiles' moments blended into the latent canvas: a thread a canvas row",
|
||||
"row pitches honoured", "f32 or bf16 moments and canvas",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_vtile_join },
|
||||
|
||||
{ "grid_pos3", "grid_pos3", "elem",
|
||||
"a video decoder's rotary positions over its tiles", "a [3, M] view at its own pitch", "f32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
@@ -9621,6 +9740,13 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
ROW(cGenF32), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_flow_renoise },
|
||||
|
||||
{ "cond_aug_f32", "cond_aug", "elem",
|
||||
"condition rows blended with fresh noise at the declared aug: a thread a value",
|
||||
"any M and n, row pitches honoured", "f32 rows, u32 seed words",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenF32), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_cond_aug },
|
||||
|
||||
{ "rope_split", "rope_split", "elem",
|
||||
"LTX-2's rotary: a workgroup a (head, 64 rows), the head's ladder in LDS, sincosf a pair",
|
||||
"any M, row pitches honoured; head_dim / 2 dividing 256; up to four axes",
|
||||
|
||||
+1428
-54
File diff suppressed because it is too large.
Load diff
+9
-18
@@ -754,10 +754,9 @@ extern "C" int r4d_shape_kv_store(const RadParam* p, int n_p, int operand,
|
||||
R4D_PICK(l);
|
||||
}
|
||||
|
||||
/* The streamed store: kv_store's geometry with the group's two copies beside the ring. One block
|
||||
* and one ring slot, with every token on its own position of that block: the draw vocabulary cannot
|
||||
* express an injective residency map, and two blocks drawing one slot would be a race between two
|
||||
* tokens on one ring byte. The partly resident map and the mirror-only step are built by hand. */
|
||||
/* The streamed store: kv_store's geometry plus the mirror and the residency map. One block, one ring
|
||||
* slot, every token on its own position (libref/ref_shapes.cpp says why); the partly resident map
|
||||
* and the mirror-only step are built by hand. */
|
||||
extern "C" int r4d_shape_kv_store_streamed(const RadParam* p, int n_p, int operand,
|
||||
RadOpdDesc* out) {
|
||||
const int64_t M = pi(p, n_p, "M");
|
||||
@@ -1160,12 +1159,9 @@ extern "C" int r4d_shape_qkv_norm_rope_kv_store(const RadParam* p, int n_p, int
|
||||
R4D_PICK(l);
|
||||
}
|
||||
|
||||
/* qk_norm_rope_gate_kv_store_streamed -- the prologue's operands, then the streamed store's: `v`,
|
||||
* `slot_mapping`, the ring, the residency map and the layer's mirror. One block, one ring slot and
|
||||
* every token on its own position of it, exactly as kv_store_streamed's shape says (the draw
|
||||
* vocabulary cannot express an injective block -> slot map, and two blocks in one slot would race).
|
||||
* E4M3 or bf16: both planes are byte planes whose pitch is one block, so a bf16 mirror row is twice
|
||||
* the fp8 row. */
|
||||
/* qk_norm_rope_gate_kv_store_streamed: the prologue's operands, then the streamed store's (`v`,
|
||||
* `slot_mapping`, the ring, the map and the mirror), on one block as kv_store_streamed's shape is.
|
||||
* A bf16 mirror row is twice the fp8 one. */
|
||||
extern "C" int r4d_shape_qk_norm_rope_gate_kv_store_streamed(const RadParam* p, int n_p,
|
||||
int operand, RadOpdDesc* out) {
|
||||
if (operand < 9) return r4d_shape_qk_norm_rope_gate(p, n_p, operand, out);
|
||||
@@ -1925,14 +1921,9 @@ extern "C" int r4d_shape_qsa_select(const RadParam* p, int n_p, int operand, Rad
|
||||
R4D_PICK(l);
|
||||
}
|
||||
|
||||
/* The residency map and the two byte planes. `sel` is described as block ids, which is what
|
||||
* `qsa_select` leaves there; past `nsel` it is -1 padding the op does not touch.
|
||||
*
|
||||
* A described residency map can only be an all-resident one: the description vocabulary draws an
|
||||
* index in [0, idx_max) or a constant, and a cold entry is -1, which no draw expresses. So a tool
|
||||
* that calls this op cold sees every map entry at 0, which exercises the epoch, the rewrite and
|
||||
* the bookkeeping but never a miss, an eviction or a copy. The service-shaped cases are built by
|
||||
* hand in tests/ref_test.cpp and in this plugin's selftest, against libref. */
|
||||
/* The residency map and the two byte planes: `sel` is block ids, -1 past `nsel`. A described map
|
||||
* is all-resident (no draw expresses -1), so a cold call never misses; the service-shaped cases
|
||||
* are built by hand in tests/ref_test.cpp and this plugin's selftest. */
|
||||
extern "C" int r4d_shape_kv_resolve(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
|
||||
const int64_t M = pi(p, n_p, "M"), blocks = pi(p, n_p, "blocks");
|
||||
|
||||
+149
-36
@@ -95,7 +95,6 @@ template <int CW> __device__ __forceinline__ void ldcw(const void* p, bool f32,
|
||||
if (f32) ldc<CW>((const float*)p + c, f);
|
||||
else ldc<CW>((const uint16_t*)p + c, f);
|
||||
}
|
||||
|
||||
// The volume a request runs at: (T, H, W) and its row count, or false for a geometry the operands
|
||||
// cannot hold (`rows` rows of the input).
|
||||
__device__ __forceinline__ bool volume_of(const int* geom, long long rows, int* T, int* H, int* W,
|
||||
@@ -175,15 +174,25 @@ __device__ __forceinline__ unsigned short conv_finish(float acc, float bv, unsig
|
||||
return t;
|
||||
}
|
||||
|
||||
/* Floor division by b > 0 of a possibly negative a. */
|
||||
__device__ __forceinline__ int idiv_dev(int a, int b) {
|
||||
return a >= 0 ? a / b : -((-a + b - 1) / b);
|
||||
}
|
||||
|
||||
/* `vec` (host-checked): y, res and the bias take 16-byte accesses at every eight-column boundary.
|
||||
* `xrows` bounds the volume the device geometry may name, `xbytes` is x's extent (at most kOob)
|
||||
* and `Mcap` bounds the rows written; `tpad` and `tpre` as above. */
|
||||
template <bool C64, bool RES, bool BF32>
|
||||
* and `Mcap` bounds the rows written; `tpad` and `tpre` as above.
|
||||
*
|
||||
* `GEN`, for any stride, `causal`, `down` or reflect (the encoder's forms): a staged voxel is one
|
||||
* of the (T2, H2, W2) output, its base source coordinate the stride less the pad, and with `refl`
|
||||
* a tap is mirrored into the volume (torch's reflect, the volume checked by the launcher). */
|
||||
template <bool C64, bool RES, bool BF32, bool GEN>
|
||||
__global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
|
||||
const unsigned short* __restrict__ X, const unsigned short* __restrict__ Wt,
|
||||
const void* __restrict__ bias, const unsigned short* R, unsigned short* C,
|
||||
const int* __restrict__ geom, unsigned ldx, unsigned ldr, unsigned ldc, int Mcap, int xrows,
|
||||
unsigned xbytes, int cin, int N, unsigned vec, int tpad, int tpre) {
|
||||
unsigned xbytes, int cin, int N, unsigned vec, int st, int sp, int ft, int bk, int pt,
|
||||
int pb, int pl, int pr, int refl, int tpad, int tpre) {
|
||||
typedef r4d_u32x4 U4;
|
||||
__shared__ __attribute__((aligned(16))) unsigned char s_a[2][kCBM * kCPB];
|
||||
|
||||
@@ -191,8 +200,17 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
|
||||
long long vol;
|
||||
if (!volume_of(geom, xrows, &gT, &gH, &gW, &vol)) return;
|
||||
const int HW = gH * gW;
|
||||
const long long ovol = vol + (long long)tpre * HW;
|
||||
const int Mv = ovol < (long long)Mcap ? (int)ovol : Mcap;
|
||||
int H2 = gH, W2 = gW;
|
||||
long long Mv64 = vol + (long long)tpre * HW;
|
||||
if constexpr (GEN) {
|
||||
const int T2 = idiv_dev(gT + ft + bk - 3, st) + 1;
|
||||
H2 = idiv_dev(gH + pt + pb - 3, sp) + 1;
|
||||
W2 = idiv_dev(gW + pl + pr - 3, sp) + 1;
|
||||
if (T2 <= 0 || H2 <= 0 || W2 <= 0) return;
|
||||
Mv64 = (long long)T2 * H2 * W2;
|
||||
}
|
||||
const int OHW = H2 * W2;
|
||||
const int Mv = Mv64 < (long long)Mcap ? (int)Mv64 : Mcap;
|
||||
|
||||
const uint32_t tid = threadIdx.x, lane = tid & 31u;
|
||||
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid >> 5);
|
||||
@@ -213,6 +231,7 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
|
||||
if (m0 >= (uint32_t)Mv) return;
|
||||
|
||||
// This thread's staged rows and their voxels; a row past the volume sits outside every frame.
|
||||
// The voxel's row, or with GEN its base source coordinate.
|
||||
const uint32_t ch = tid % kCCPR;
|
||||
int vm[kCSPT], vt[kCSPT], vy[kCSPT], vx[kCSPT];
|
||||
uint32_t adst[kCSPT];
|
||||
@@ -221,15 +240,27 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
|
||||
const uint32_t r = tid / kCCPR + kCRS * i;
|
||||
const int m = (int)(m0 + r);
|
||||
adst[i] = r * kCPB + ch * 16u;
|
||||
vm[i] = m;
|
||||
vt[i] = -4;
|
||||
vy[i] = 0;
|
||||
vx[i] = 0;
|
||||
if (m < Mv) {
|
||||
vt[i] = m / HW;
|
||||
const int rem = m - vt[i] * HW;
|
||||
vy[i] = rem / gW;
|
||||
vx[i] = rem - vy[i] * gW;
|
||||
if constexpr (GEN) {
|
||||
vm[i] = -4; // frame: fails every tap's bounds
|
||||
vt[i] = 0; // row
|
||||
vy[i] = 0; // column
|
||||
if (m < Mv) {
|
||||
const int t = m / OHW, rem = m - t * OHW, yy = rem / W2;
|
||||
vm[i] = t * st - ft;
|
||||
vt[i] = yy * sp - pt;
|
||||
vy[i] = (rem - yy * W2) * sp - pl;
|
||||
}
|
||||
} else {
|
||||
vm[i] = m;
|
||||
vt[i] = -4;
|
||||
vy[i] = 0;
|
||||
vx[i] = 0;
|
||||
if (m < Mv) {
|
||||
vt[i] = m / HW;
|
||||
const int rem = m - vt[i] * HW;
|
||||
vy[i] = rem / gW;
|
||||
vx[i] = rem - vy[i] * gW;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The four neighbours' byte offsets at a tap, kOob outside the volume; with C64 they include
|
||||
@@ -238,18 +269,38 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
|
||||
__builtin_amdgcn_make_buffer_rsrc(const_cast<unsigned short*>(X), 0, (int)xbytes, kBufWord3);
|
||||
uint32_t off[kCSPT];
|
||||
auto at_tap = [&](int tap) {
|
||||
const int dt = tap / 9 - 1, dy = (tap / 3) % 3 - 1, dx = tap % 3 - 1;
|
||||
const int delta = dt * HW + dy * gW + dx;
|
||||
if constexpr (GEN) {
|
||||
const int dt = tap / 9, dy = (tap / 3) % 3, dx = tap % 3; // the base has the pads
|
||||
#pragma unroll
|
||||
for (uint32_t i = 0; i < kCSPT; ++i) {
|
||||
int ft = vt[i] + dt;
|
||||
if (tpad == 1) ft = min(max(ft, 0), gT - 1);
|
||||
else if (tpad == 2) ft = max(ft - 1 - tpre, 0);
|
||||
const bool ok = tap < kTaps && vt[i] >= 0 && (unsigned)ft < (unsigned)gT &&
|
||||
(unsigned)(vy[i] + dy) < (unsigned)gH &&
|
||||
(unsigned)(vx[i] + dx) < (unsigned)gW;
|
||||
const int src = tpad ? (ft * gH + vy[i] + dy) * gW + vx[i] + dx : vm[i] + delta;
|
||||
off[i] = ok ? (uint32_t)src * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob;
|
||||
for (uint32_t i = 0; i < kCSPT; ++i) {
|
||||
int tz = vm[i] + dt;
|
||||
int sy = vt[i] + dy, sx = vy[i] + dx;
|
||||
if (tpad) tz = min(max(tz, 0), gT - 1);
|
||||
if (refl) { // a mirror with no repeated edge
|
||||
if (sy < 0) sy = -sy; else if (sy >= gH) sy = 2 * gH - 2 - sy;
|
||||
if (sx < 0) sx = -sx; else if (sx >= gW) sx = 2 * gW - 2 - sx;
|
||||
}
|
||||
const bool ok = tap < kTaps && (unsigned)tz < (unsigned)gT &&
|
||||
(unsigned)sy < (unsigned)gH && (unsigned)sx < (unsigned)gW;
|
||||
off[i] = ok
|
||||
? (uint32_t)(((long long)tz * gH + sy) * gW + sx) * ldx * 2u +
|
||||
(C64 ? ch * 16u : 0u)
|
||||
: kOob;
|
||||
}
|
||||
} else {
|
||||
const int dt = tap / 9 - 1, dy = (tap / 3) % 3 - 1, dx = tap % 3 - 1;
|
||||
const int delta = dt * HW + dy * gW + dx;
|
||||
#pragma unroll
|
||||
for (uint32_t i = 0; i < kCSPT; ++i) {
|
||||
int ft = vt[i] + dt;
|
||||
if (tpad == 1) ft = min(max(ft, 0), gT - 1);
|
||||
else if (tpad == 2) ft = max(ft - 1 - tpre, 0);
|
||||
const bool ok = tap < kTaps && vt[i] >= 0 && (unsigned)ft < (unsigned)gT &&
|
||||
(unsigned)(vy[i] + dy) < (unsigned)gH &&
|
||||
(unsigned)(vx[i] + dx) < (unsigned)gW;
|
||||
const int src = tpad ? (ft * gH + vy[i] + dy) * gW + vx[i] + dx : vm[i] + delta;
|
||||
off[i] = ok ? (uint32_t)src * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -421,7 +472,7 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
|
||||
// 2. final: block g merges group g's parts, 256 strided runs then a fixed tree, and writes
|
||||
// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps), the count the
|
||||
// group's exact M n / groups.
|
||||
// 3. apply: a thread an 8-channel chunk, v = (x - mean) rstd w + b, the modulation and SiLU in
|
||||
// 3. apply: a thread a CW-channel chunk, v = (x - mean) rstd w + b, the modulation and SiLU in
|
||||
// f32, one rounding.
|
||||
//
|
||||
// The scratch beyond the 2 groups leading values holds part p of group g at 3 (g kGnParts + p).
|
||||
@@ -720,6 +771,24 @@ __global__ __launch_bounds__(kT) void flow_renoise_kernel(
|
||||
*p = a + bz;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- cond_aug
|
||||
// x = a x + oma z, a the aug parameter, oma the f32 of the f64 1 - a, z element k n + c of the
|
||||
// (seed, stream) normal stream: a thread a value, each product and the sum one f32 rounding.
|
||||
__global__ __launch_bounds__(kT) void cond_aug_kernel(
|
||||
const uint32_t* __restrict__ seed, float* __restrict__ x, float a, float oma,
|
||||
int n, int ldx, long long total, unsigned long long stream) {
|
||||
const long long id = (long long)blockIdx.x * kT + threadIdx.x;
|
||||
if (id >= total) return;
|
||||
const long long k = id / n;
|
||||
const int c = (int)(id % n);
|
||||
const uint64_t sd = (uint64_t)seed[0] | ((uint64_t)seed[1] << 32);
|
||||
const float z = rad_philox_normal_s(sd, stream, (uint64_t)id);
|
||||
float* p = x + k * ldx + c;
|
||||
const float av = a * *p;
|
||||
const float bz = oma * z;
|
||||
*p = av + bz;
|
||||
}
|
||||
|
||||
inline bool is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; }
|
||||
inline bool is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; }
|
||||
inline bool is_i32(const RadTensor* t) { return t && t->dtype == RAD_I32; }
|
||||
@@ -764,6 +833,18 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) {
|
||||
/* 3 x 3 x 3 only: the tap decode is the kernel's constant. */
|
||||
if (r4d_geti_or(a, "k", 3) != 3 || r4d_geti_or(a, "kt", 3) != 3) return R4D_NO(RAD_E_SHAPE);
|
||||
if (cin <= 0 || cout <= 0 || (cin & 7)) return R4D_NO(RAD_E_SHAPE);
|
||||
/* The encoder's CausalConv3d forms (GEN above); the pads are k / 2 = 1, or kt - 1 = 2 in
|
||||
* front with `causal`. */
|
||||
const long long sp = r4d_geti_or(a, "stride", 1), st = r4d_geti_or(a, "stride_t", 1);
|
||||
const long long causal = r4d_geti_or(a, "causal", 0), reflect = r4d_geti_or(a, "reflect", 0);
|
||||
const char* pads = r4d_gets(a, "pad");
|
||||
if (pads && std::strcmp(pads, "same") && std::strcmp(pads, "down")) return R4D_NO(RAD_E_SHAPE);
|
||||
const bool down = pads && !std::strcmp(pads, "down");
|
||||
if (sp <= 0 || st <= 0 || sp > (1ll << 30) || st > (1ll << 30) || (causal && causal != 1) ||
|
||||
(reflect && reflect != 1))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const bool gen = sp != 1 || st != 1 || causal || down || reflect;
|
||||
const int pt = down ? 0 : 1, pl = down ? 0 : 1, pb = 1, pr = 1;
|
||||
const long long K = (long long)kTaps * cin;
|
||||
if (r4d_numel(w) < cout * K || r4d_numel(b) < cout || r4d_numel(geom) < 3)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -776,7 +857,11 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) {
|
||||
else if (std::strcmp(tp, "zero")) return R4D_NO(RAD_E_INVAL);
|
||||
}
|
||||
const long long tpre = r4d_geti_or(a, "tpre", 0);
|
||||
if (tpre < 0 || tpre > 64 || (tpre && tpad != 2)) return R4D_NO(RAD_E_INVAL);
|
||||
if (tpre < 0 || tpre > 64 || (tpre && tpad != 2) || (causal && tpad))
|
||||
return R4D_NO(RAD_E_INVAL);
|
||||
/* GEN's time pads: `causal` and `tpad` causal pad the front only, `tpre` frames more. */
|
||||
const int ft = causal ? 2 : tpad == 2 ? 2 + (int)tpre : 1;
|
||||
const int bk = causal || tpad == 2 ? 0 : 1;
|
||||
long long rx = 0, ldx = 0, ry = 0, rr = 0;
|
||||
if (!rows8(x, cin, &rx, &ldx) || !r4d_aligned(r4d_p(w), 16)) return R4D_NO(RAD_E_STRIDE);
|
||||
const long long ldy = r4d_rows_pitch(y, cout, &ry);
|
||||
@@ -801,15 +886,18 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) {
|
||||
(!res || ((ldr % 8) == 0 && r4d_aligned(Rp, 16)));
|
||||
const dim3 grid((unsigned)((Mcap + kCBM - 1) / kCBM), (unsigned)((cout + kCBN - 1) / kCBN));
|
||||
const bool c64 = cin % kCFK == 0, bf32 = is_f32(b);
|
||||
#define C3_L(C6, RS, BF) \
|
||||
return R4D_EMIT(stream, (conv3d_kernel<C6, RS, BF>), grid, dim3(kCThreads), 0, Xp, Wp, Bp, Rp, \
|
||||
Cp, (const int*)r4d_p(geom), (unsigned)ldx, (unsigned)ldr, (unsigned)ldy, \
|
||||
(int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, vec, tpad, \
|
||||
#define C3_L(G, C6, RS, BF) \
|
||||
return R4D_EMIT(stream, (conv3d_kernel<C6, RS, BF, G>), grid, dim3(kCThreads), 0, Xp, Wp, \
|
||||
Bp, Rp, Cp, (const int*)r4d_p(geom), (unsigned)ldx, (unsigned)ldr, \
|
||||
(unsigned)ldy, (int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, \
|
||||
vec, (int)st, (int)sp, ft, bk, pt, pb, pl, pr, (int)reflect, tpad, \
|
||||
(int)tpre)
|
||||
#define C3_RES(C6, BF) do { if (res) C3_L(C6, true, BF); C3_L(C6, false, BF); } while (0)
|
||||
#define C3_BF(C6) do { if (bf32) C3_RES(C6, true); C3_RES(C6, false); } while (0)
|
||||
if (c64) C3_BF(true);
|
||||
C3_BF(false);
|
||||
#define C3_RES(G, C6, BF) do { if (res) C3_L(G, C6, true, BF); C3_L(G, C6, false, BF); } while (0)
|
||||
#define C3_BF(G, C6) do { if (bf32) C3_RES(G, C6, true); C3_RES(G, C6, false); } while (0)
|
||||
#define C3_C6(G) do { if (c64) C3_BF(G, true); C3_BF(G, false); } while (0)
|
||||
if (gen) C3_C6(true);
|
||||
C3_C6(false);
|
||||
#undef C3_C6
|
||||
#undef C3_BF
|
||||
#undef C3_RES
|
||||
#undef C3_L
|
||||
@@ -1012,3 +1100,28 @@ extern "C" int r4d_rad_flow_renoise(const RadArgs* a, RadStream stream) {
|
||||
0, (const float*)r4d_p(sg), (const uint32_t*)r4d_p(seed), (float*)r4d_wp(x),
|
||||
(int)n, (int)ldx, total, (unsigned long long)sm);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ cond_aug */
|
||||
enum { CA_SEED = 0, CA_X };
|
||||
|
||||
extern "C" int r4d_rad_cond_aug(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor *seed = r4d_opt(a, CA_SEED), *x = r4d_opt(a, CA_X);
|
||||
if (!seed || !x) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_f32(x) || (seed->dtype != RAD_U32 && seed->dtype != RAD_I32))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", 0), sm = r4d_geti_or(a, "stream", 0);
|
||||
const double aug = r4d_getf(a, "aug", -1.0);
|
||||
if (n <= 0 || sm < 0 || !(aug >= 0.0 && aug < 1.0) || r4d_numel(seed) < 2)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
long long rx = 0;
|
||||
const long long ldx = r4d_rows_pitch(x, n, &rx);
|
||||
if (ldx < 0 || !r4d_contig(seed)) return R4D_NO(RAD_E_STRIDE);
|
||||
/* Every row of x, as libref's; M is not read. */
|
||||
const long long M = rx;
|
||||
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long total = M * n;
|
||||
const float av = (float)aug, omv = (float)(1.0 - aug);
|
||||
return R4D_EMIT(stream, cond_aug_kernel, dim3((unsigned)((total + kT - 1) / kT)), dim3(kT),
|
||||
0, (const uint32_t*)r4d_p(seed), (float*)r4d_wp(x), av, omv,
|
||||
(int)n, (int)ldx, total, (unsigned long long)sm);
|
||||
}
|
||||
+303
-28
@@ -1,7 +1,8 @@
|
||||
// R4D -- the video generator's ops (docs/OPS.md, "Video generation"): a diffusion transformer's
|
||||
// modulated RMS norm and its sampler step, the video decoder's patch unfold, the tiles it runs
|
||||
// over, their stitch back into frames and their rotary positions; and its soundtrack decoder's
|
||||
// alias-free SnakeBeta (docs/OPS.md, "Audio generation").
|
||||
// over, their stitch back into frames and their rotary positions; the video encoder's plan, cut
|
||||
// and blend for a picture bigger than one volume; and its soundtrack decoder's alias-free
|
||||
// SnakeBeta (docs/OPS.md, "Audio generation").
|
||||
//
|
||||
// Each kernel rounds where its libref function does (libref/ref_gen.cpp, libref/ref_video.cpp,
|
||||
// libref/ref_audio.cpp), under the library's -ffp-contract=off. The norm's sum of squares is a
|
||||
@@ -77,16 +78,21 @@ __device__ __forceinline__ float rdv(const float*, float v) { return v; }
|
||||
// r4d_q8.h's. `s` is a column slice of the modulation table, [shift | scale] in each entry's row.
|
||||
constexpr int kRmChunks = 4; // 8-wide chunks a thread keeps: n <= kT * 8 * 4 = 8192
|
||||
|
||||
template <bool GATED, bool QUANT>
|
||||
// QMODE: 0 writes the bf16 chain to `z`, 1 also quantises it to E4M3 (q, scale), 2 to int8, the
|
||||
// two differing only in r4d_q8.h's `q8_top` and `q8_pack4`.
|
||||
template <bool GATED, int QMODE>
|
||||
__global__ __launch_bounds__(kT) void rms_mod_kernel(
|
||||
const uint16_t* __restrict__ yd, const uint16_t* __restrict__ g, const uint16_t* __restrict__ s,
|
||||
const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ x,
|
||||
uint8_t* __restrict__ q, float* __restrict__ qs, uint16_t* __restrict__ z, int n, int n_seq,
|
||||
float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld, float wadd,
|
||||
int once, int layer, int none) {
|
||||
int once, int layer, int none, const int* __restrict__ colmap) {
|
||||
__shared__ float sh[kT / 32];
|
||||
const int r = blockIdx.x;
|
||||
const int e = seq_of(cu, n_seq, r);
|
||||
int e = seq_of(cu, n_seq, r);
|
||||
// Optional: `cu` may bound more groups than the modulation table has rows (groups that share
|
||||
// a cell share a row), so the map turns a group into its row; without it the group is the row.
|
||||
if (colmap) e = colmap[e];
|
||||
uint16_t* xr = x + (size_t)r * x_ld;
|
||||
float v[kRmChunks][8];
|
||||
float ss = 0.0f;
|
||||
@@ -152,7 +158,7 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel(
|
||||
o[j] = bfr(bfr(n2 * bfr(1.0f + scf[j])) + shf[j]);
|
||||
}
|
||||
if (z) st8(z + (size_t)r * z_ld + i, o);
|
||||
if (QUANT) {
|
||||
if (QMODE) {
|
||||
float m = 0.0f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) m = fmaxf(m, fabsf(o[j]));
|
||||
@@ -160,12 +166,12 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel(
|
||||
m = fmaxf(m, r4d_xor_lane<4>(m));
|
||||
m = fmaxf(m, r4d_xor_lane<2>(m));
|
||||
m = fmaxf(m, r4d_xor_lane<1>(m));
|
||||
const float sc = m > 0.0f ? m * (1.0f / q8_top<false>()) : 1.0f;
|
||||
const float sc = m > 0.0f ? m * (1.0f / q8_top<QMODE == 2>()) : 1.0f;
|
||||
const float inv = 1.0f / sc;
|
||||
if ((threadIdx.x & 15) == 0) qs[(size_t)r * qs_ld + i / 128] = sc;
|
||||
*(uint2*)(q + (size_t)r * q_ld + i) =
|
||||
make_uint2(q8_pack4<false>(o[0], o[1], o[2], o[3], inv),
|
||||
q8_pack4<false>(o[4], o[5], o[6], o[7], inv));
|
||||
make_uint2(q8_pack4<QMODE == 2>(o[0], o[1], o[2], o[3], inv),
|
||||
q8_pack4<QMODE == 2>(o[4], o[5], o[6], o[7], inv));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -190,6 +196,33 @@ __global__ __launch_bounds__(kT) void flow_x0_kernel(
|
||||
*xp = ra * xv + omr * d;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- flow_res_multistep
|
||||
// The second-order step on the clean estimate d = x + sigma v: x' = r x + hb1 d + hb2 x0, x0 the
|
||||
// last step's estimate, which d then replaces. With order < 2 it is Euler, x' = r x + (1 - r) d.
|
||||
template <typename TV>
|
||||
__global__ __launch_bounds__(kT) void flow_rm_kernel(
|
||||
const TV* __restrict__ v, float* __restrict__ x0, const float* __restrict__ sg,
|
||||
const float* __restrict__ rr, const float* __restrict__ hb1, const float* __restrict__ hb2,
|
||||
const float* __restrict__ ord, float* __restrict__ x, int n, int v_ld, int x_ld, int x0_ld,
|
||||
int64_t total) {
|
||||
const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x;
|
||||
if (id >= total) return;
|
||||
const int64_t r = id / n;
|
||||
const int c = (int)(id % n);
|
||||
const float sgv = sg[0];
|
||||
const float ra = rr[0];
|
||||
const float b1 = hb1[0];
|
||||
const float b2 = hb2[0];
|
||||
const bool two = ord[0] >= 1.5f;
|
||||
const float omr = 1.0f - ra;
|
||||
float* xp = x + r * x_ld + c;
|
||||
float* op = x0 + r * x0_ld + c;
|
||||
const float xv = *xp;
|
||||
const float d = xv + sgv * ldv(v, r * v_ld + c);
|
||||
*xp = two ? ra * xv + b1 * d + b2 * (*op) : ra * xv + omr * d;
|
||||
*op = d;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- patch_unfold
|
||||
// The two parameter lists of the latent's statistics, f32 kernel arguments.
|
||||
constexpr int kMaxChan = 64;
|
||||
@@ -242,6 +275,20 @@ __device__ __forceinline__ Tiles split_tiles(int len, int tile, int overlap) {
|
||||
return t;
|
||||
}
|
||||
|
||||
// The encoder's split over one axis (libref's split_tiles_axis): the decoder's split above, except
|
||||
// that an axis no longer than a tile is one tile, short if need be. A lone tile starts at 0 with no
|
||||
// overlap, which the closed form already gives at n = 1.
|
||||
__device__ __forceinline__ Tiles split_tiles_axis(int len, int tile, int overlap) {
|
||||
if (tile >= len && len > 0 && tile > 0 && overlap >= 0 && overlap < tile) {
|
||||
Tiles t;
|
||||
t.n = 1;
|
||||
t.tile = tile;
|
||||
t.overlap = overlap;
|
||||
return t;
|
||||
}
|
||||
return split_tiles(len, tile, overlap);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- vtile_gather
|
||||
// A workgroup a tile row: its voxel from x, a register token from `reg`, or zeros.
|
||||
template <typename TX, typename TR, typename TY>
|
||||
@@ -348,6 +395,118 @@ __global__ __launch_bounds__(kT) void vtile_stitch_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- the tiled encoder
|
||||
// A one-frame media larger than a tile is encoded as vae.py's `tiled_encode` does: the plan, the
|
||||
// cut and the blend (libref's ref_vtile_plan/crop/join); the encoder is the per-level ops, issued
|
||||
// per tile.
|
||||
|
||||
// A thread a (tile, entry): the tile's first pixel, its pixel extent and the six level volumes,
|
||||
// as ref_vtile_plan's row of 22 i32.
|
||||
__global__ __launch_bounds__(kT) void vtile_plan_kernel(
|
||||
const int* __restrict__ geom, int* __restrict__ y, int tile, int overlap, int ratio, int y_ld,
|
||||
int64_t M, int64_t y_rows) {
|
||||
const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x;
|
||||
const int H = geom[1], W = geom[2];
|
||||
if (id >= M * 22 || id >= y_rows * 22 || H <= 0 || W <= 0 || H % ratio || W % ratio) return;
|
||||
const Tiles ty = split_tiles_axis(H / ratio, tile, overlap);
|
||||
const Tiles tx = split_tiles_axis(W / ratio, tile, overlap);
|
||||
if (ty.n == 0 || tx.n == 0) return;
|
||||
const int64_t t = id / 22;
|
||||
const int c = (int)(id % 22);
|
||||
const int nh = ty.n, nw = tx.n;
|
||||
if (t >= (int64_t)nh * nw) return;
|
||||
const int i = (int)(t / nw), j = (int)(t % nw);
|
||||
const int th = min(tile, H / ratio - ty.start(i)) * ratio;
|
||||
const int tw = min(tile, W / ratio - tx.start(j)) * ratio;
|
||||
int v;
|
||||
if (c < 4) {
|
||||
v = c == 0 ? ty.start(i) * ratio : c == 1 ? tx.start(j) * ratio : c == 2 ? th : tw;
|
||||
} else {
|
||||
const int L = (c - 4) / 3, k = (c - 4) % 3, d = 1 << min(L, 4);
|
||||
v = k == 0 ? 1 : k == 1 ? th / d : tw / d;
|
||||
}
|
||||
y[t * y_ld + c] = v;
|
||||
}
|
||||
|
||||
// A thread a tile pixel row: its plane row copied. The tile is found by walking the tiles' sizes,
|
||||
// at most a hundred of them (libref's upper_bound over the same prefix sums).
|
||||
template <typename T>
|
||||
__global__ __launch_bounds__(kT) void vtile_crop_kernel(
|
||||
const T* __restrict__ x, const int* __restrict__ geom, T* __restrict__ y, int tile,
|
||||
int overlap, int ratio, int x_ld, int y_ld, int64_t M, int64_t x_rows, int64_t y_rows) {
|
||||
const int64_t r = (int64_t)blockIdx.x * kT + threadIdx.x;
|
||||
const int H = geom[1], W = geom[2];
|
||||
if (r >= M || r >= y_rows || H <= 0 || W <= 0 || H % ratio || W % ratio) return;
|
||||
const Tiles ty = split_tiles_axis(H / ratio, tile, overlap);
|
||||
const Tiles tx = split_tiles_axis(W / ratio, tile, overlap);
|
||||
if (ty.n == 0 || tx.n == 0 || (int64_t)H * W > x_rows) return;
|
||||
const int nh = ty.n, nw = tx.n;
|
||||
int t = -1;
|
||||
int64_t acc = 0, k = 0;
|
||||
for (int tt = 0; tt < nh * nw; ++tt) {
|
||||
const int64_t sz = (int64_t)min(tile, H / ratio - ty.start(tt / nw)) * ratio *
|
||||
min(tile, W / ratio - tx.start(tt % nw)) * ratio;
|
||||
if (r < acc + sz) { t = tt; k = r - acc; break; }
|
||||
acc += sz;
|
||||
}
|
||||
if (t < 0) return; // r past the tiles' sum: M was not it
|
||||
const int tw = min(tile, W / ratio - tx.start(t % nw)) * ratio;
|
||||
const int64_t src = ((int64_t)ty.start(t / nw) * ratio + k / tw) * W +
|
||||
(int64_t)tx.start(t % nw) * ratio + k % tw;
|
||||
for (int c = 0; c < 3; ++c) stv(y + r * (int64_t)y_ld, c, ldv(x + src * (int64_t)x_ld, c));
|
||||
}
|
||||
|
||||
// A thread a canvas row: its tile's moments blended with the unblended top, then left neighbour,
|
||||
// every product and sum rounded to x's dtype (ref_vtile_join). A thread a (row, channel) would
|
||||
// repeat the tile walk n times.
|
||||
template <typename T>
|
||||
__global__ __launch_bounds__(kT) void vtile_join_kernel(
|
||||
const T* __restrict__ x, const int* __restrict__ geom, T* __restrict__ y, int tile,
|
||||
int overlap, int n, int x_ld, int y_ld, int64_t M, int64_t x_rows, int64_t y_rows) {
|
||||
const int64_t r = (int64_t)blockIdx.x * kT + threadIdx.x;
|
||||
const int H = geom[1], W = geom[2];
|
||||
if (r >= M || r >= y_rows || r >= (int64_t)H * W || H <= 0 || W <= 0) return;
|
||||
const Tiles ty = split_tiles_axis(H, tile, overlap), tx = split_tiles_axis(W, tile, overlap);
|
||||
if (ty.n == 0 || tx.n == 0) return;
|
||||
const int nh = ty.n, nw = tx.n;
|
||||
// The tiles' row extents and their prefix sums, in tile-major order.
|
||||
const int64_t ext_y = nh == 1 ? H : (int64_t)tile * nh, ext_x = nw == 1 ? W : (int64_t)tile * nw;
|
||||
if (ext_y * ext_x > x_rows) return;
|
||||
auto sz = [&](int ii, int jj) {
|
||||
return (int64_t)min(tile, H - ty.start(ii)) * min(tile, W - tx.start(jj));
|
||||
};
|
||||
auto off = [&](int ii, int jj) {
|
||||
int64_t a = 0;
|
||||
for (int t = 0; t < ii * nw + jj; ++t) a += sz(t / nw, t % nw);
|
||||
return a;
|
||||
};
|
||||
const int Y = (int)(r / W), X = (int)(r % W);
|
||||
int i = 0;
|
||||
while (i + 1 < nh && Y >= ty.start(i + 1)) ++i;
|
||||
int j = 0;
|
||||
while (j + 1 < nw && X >= tx.start(j + 1)) ++j;
|
||||
const int ly = Y - ty.start(i), lx = X - tx.start(j);
|
||||
const int ev = i > 0 ? ty.ov(i - 1) : 0, eh = j > 0 ? tx.ov(j - 1) : 0;
|
||||
const int64_t own = off(i, j), up = i > 0 ? off(i - 1, j) : 0, left = j > 0 ? off(i, j - 1) : 0;
|
||||
// A tile's width: this tile and the one above share a column (`own_w`, short only in the last
|
||||
// column); the left neighbour's column is never the last, so it is `tile` wide.
|
||||
const int own_w = min(tile, W - tx.start(j));
|
||||
const auto fetch = [&](int64_t base, int w, int ay, int ax, int c) {
|
||||
return ldv(x, (base + (int64_t)ay * w + ax) * x_ld + c);
|
||||
};
|
||||
auto rd = [&](float v) { return rdv(x, v); };
|
||||
auto wb = [&](int p, int e) { return rd((float)p / (float)e); };
|
||||
auto wa = [&](int p, int e) { return rd(1.0f - rd((float)p / (float)e)); };
|
||||
for (int c = 0; c < n; ++c) {
|
||||
float v = fetch(own, own_w, ly, lx, c);
|
||||
if (ly < ev)
|
||||
v = rd(rd(fetch(up, own_w, ly + tile - ev, lx, c) * wa(ly, ev)) + rd(v * wb(ly, ev)));
|
||||
if (lx < eh)
|
||||
v = rd(rd(fetch(left, tile, ly, lx + tile - eh, c) * wa(lx, eh)) + rd(v * wb(lx, eh)));
|
||||
stv(y + r * (int64_t)y_ld, c, v);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- grid_pos3
|
||||
// A thread a row: its token's three centred, scaled coordinates, or zeros past the tile's tokens.
|
||||
__global__ __launch_bounds__(kT) void grid_pos3_kernel(
|
||||
@@ -452,22 +611,25 @@ int parse_f32_list(const char* s, float* out, int max) {
|
||||
|
||||
// rms_mod (QUANT false: y, g, s, w, cu, x, z) and rms_mod_quant_fp8 (y, g, s, w, cu, x, q, scale,
|
||||
// z), one shim.
|
||||
static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) {
|
||||
static int rms_mod_launch(const RadArgs* a, RadStream st, int qmode) {
|
||||
const RadTensor *y = r4d_opt(a, 0), *g = r4d_opt(a, 1), *sc = r4d_opt(a, 2);
|
||||
const RadTensor *w = r4d_opt(a, 3), *cu = r4d_opt(a, 4), *x = r4d_opt(a, 5);
|
||||
const RadTensor* q = quant ? r4d_opt(a, 6) : nullptr;
|
||||
const RadTensor* qs = quant ? r4d_opt(a, 7) : nullptr;
|
||||
const RadTensor* z = r4d_opt(a, quant ? 8 : 6);
|
||||
if (!sc || !cu || !x || (quant ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL);
|
||||
const RadTensor* q = qmode ? r4d_opt(a, 6) : nullptr;
|
||||
const RadTensor* qs = qmode ? r4d_opt(a, 7) : nullptr;
|
||||
const RadTensor* z = r4d_opt(a, qmode ? 8 : 6);
|
||||
// The optional group->row map, after the last operand of either form (slot 9 quantising,
|
||||
// slot 7 plain).
|
||||
const RadTensor* cm = r4d_opt(a, qmode ? 9 : 7);
|
||||
if (!sc || !cu || !x || (qmode ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL);
|
||||
const bool gated = r4d_geti_or(a, "gated", 0) != 0;
|
||||
if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_bf16(x) || !is_bf16(sc) || (w && !is_bf16(w)) || !is_i32(cu) ||
|
||||
(gated && (!is_bf16(y) || !is_bf16(g))) || (z && !is_bf16(z)) ||
|
||||
(quant && (q->dtype != RAD_F8E4M3 || qs->dtype != RAD_F32)))
|
||||
(qmode && (q->dtype != (qmode == 2 ? RAD_I8 : RAD_F8E4M3) || qs->dtype != RAD_F32)))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", 0);
|
||||
if (n <= 0 || (n & 7) || n > (long long)kT * 8 * kRmChunks ||
|
||||
(quant && (n % 128 || r4d_geti_or(a, "group", 0) != 128)))
|
||||
(qmode && (n % 128 || r4d_geti_or(a, "group", 0) != 128)))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
long long rx = 0, xl = 0, ry = 0, yl = 0, rg = 0, gl = 0, rs = 0, sl = 0, rz = 0, zl = 0;
|
||||
long long rq = 0, rqs = 0, ql = 0, qsl = 0;
|
||||
@@ -476,14 +638,18 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) {
|
||||
(gated && (!rows8(y, n, &ry, &yl) || !rows8(g, n, &rg, &gl))) ||
|
||||
(z && !rows8(z, n, &rz, &zl)))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (quant) {
|
||||
if (qmode) {
|
||||
ql = r4d_rows_pitch(q, n, &rq);
|
||||
qsl = r4d_rows_pitch(qs, n / 128, &rqs);
|
||||
if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
}
|
||||
const long long n_seq = r4d_numel(cu) - 1, rows = quant ? rq : rz;
|
||||
if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || (w && r4d_numel(w) < n) ||
|
||||
(quant && rqs < rows) || (gated && (ry < rows || rg < n_seq)) || (z && rz < rows))
|
||||
const long long n_seq = r4d_numel(cu) - 1, rows = qmode ? rq : rz;
|
||||
if (cm && (!is_i32(cm) || !r4d_contig(cm) || r4d_numel(cm) < n_seq))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
// With the map the table may hold fewer rows than groups; the issuer keeps every mapped row
|
||||
// inside it.
|
||||
if (rows <= 0 || n_seq <= 0 || rx < rows || (!cm && rs < n_seq) || (w && r4d_numel(w) < n) ||
|
||||
(qmode && rqs < rows) || (gated && (ry < rows || (!cm && rg < n_seq))) || (z && rz < rows))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const float eps = (float)r4d_getf(a, "eps", 1e-6);
|
||||
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
|
||||
@@ -501,22 +667,29 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) {
|
||||
Q ? (uint8_t*)q->data : nullptr, Q ? (float*)qs->data : nullptr, \
|
||||
z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, eps, (int)yl, \
|
||||
(int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl, wadd, once, layer, \
|
||||
none)
|
||||
if (quant) {
|
||||
if (gated) R4D_RMQ(true, true);
|
||||
else R4D_RMQ(false, true);
|
||||
none, cm ? (const int*)cm->data : nullptr)
|
||||
if (qmode == 2) {
|
||||
if (gated) R4D_RMQ(true, 2);
|
||||
else R4D_RMQ(false, 2);
|
||||
} else if (qmode == 1) {
|
||||
if (gated) R4D_RMQ(true, 1);
|
||||
else R4D_RMQ(false, 1);
|
||||
} else {
|
||||
if (gated) R4D_RMQ(true, false);
|
||||
else R4D_RMQ(false, false);
|
||||
if (gated) R4D_RMQ(true, 0);
|
||||
else R4D_RMQ(false, 0);
|
||||
}
|
||||
#undef R4D_RMQ
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_rms_mod(const RadArgs* a, RadStream s) { return rms_mod_launch(a, s, false); }
|
||||
extern "C" int r4d_rad_rms_mod(const RadArgs* a, RadStream s) { return rms_mod_launch(a, s, 0); }
|
||||
|
||||
extern "C" int r4d_rad_rms_mod_quant_fp8(const RadArgs* a, RadStream s) {
|
||||
return rms_mod_launch(a, s, true);
|
||||
return rms_mod_launch(a, s, 1);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_rms_mod_quant_i8(const RadArgs* a, RadStream s) {
|
||||
return rms_mod_launch(a, s, 2);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_flow_x0_step(const RadArgs* a, RadStream s) {
|
||||
@@ -543,6 +716,36 @@ extern "C" int r4d_rad_flow_x0_step(const RadArgs* a, RadStream s) {
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_flow_res_multistep(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *v = r4d_opt(a, 0), *x0 = r4d_opt(a, 1), *sg = r4d_opt(a, 2);
|
||||
const RadTensor *rr = r4d_opt(a, 3), *hb1 = r4d_opt(a, 4), *hb2 = r4d_opt(a, 5);
|
||||
const RadTensor *ord = r4d_opt(a, 6), *x = r4d_opt(a, 7);
|
||||
if (!v || !x0 || !sg || !rr || !hb1 || !hb2 || !ord || !x) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_f32(x) || !is_f32(x0) || !is_f32(sg) || !is_f32(rr) || !is_f32(hb1) || !is_f32(hb2) ||
|
||||
!is_f32(ord) || (!is_f32(v) && !is_bf16(v)))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", 0);
|
||||
long long rx = 0, rv = 0, rx0 = 0;
|
||||
const long long xl = n > 0 ? r4d_rows_pitch(x, n, &rx) : -1;
|
||||
const long long vl = n > 0 ? r4d_rows_pitch(v, n, &rv) : -1;
|
||||
const long long x0l = n > 0 ? r4d_rows_pitch(x0, n, &rx0) : -1;
|
||||
if (xl < 0 || vl < 0 || x0l < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (rx <= 0 || rv < rx || rx0 < rx || r4d_numel(sg) < 1 || r4d_numel(rr) < 1 ||
|
||||
r4d_numel(hb1) < 1 || r4d_numel(hb2) < 1 || r4d_numel(ord) < 1)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const int64_t total = (int64_t)rx * n;
|
||||
#define R4D_FRM(TV) \
|
||||
hipLaunchKernelGGL(flow_rm_kernel<TV>, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, \
|
||||
(const TV*)v->data, (float*)x0->data, (const float*)sg->data, \
|
||||
(const float*)rr->data, (const float*)hb1->data, (const float*)hb2->data, \
|
||||
(const float*)ord->data, (float*)x->data, (int)n, (int)vl, (int)xl, \
|
||||
(int)x0l, total)
|
||||
if (is_f32(v)) R4D_FRM(float);
|
||||
else R4D_FRM(uint16_t);
|
||||
#undef R4D_FRM
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_patch_unfold(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *geom = r4d_opt(a, 1), *y = r4d_opt(a, 2);
|
||||
if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL);
|
||||
@@ -642,6 +845,78 @@ extern "C" int r4d_rad_vtile_stitch(const RadArgs* a, RadStream s) {
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_vtile_plan(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *geom = r4d_opt(a, 0), *y = r4d_opt(a, 1);
|
||||
if (!geom || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_i32(geom) || !is_i32(y)) return R4D_NO(RAD_E_DTYPE);
|
||||
const long long M = r4d_geti_or(a, "M", 0), tile = r4d_geti_or(a, "tile", 0);
|
||||
const long long overlap = r4d_geti_or(a, "overlap", 0), ratio = r4d_geti_or(a, "ratio", 0);
|
||||
if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 ||
|
||||
r4d_numel(geom) < 3)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
/* The tile count comes from y; the ranged `M` is the band's bound, a ceiling only
|
||||
* (ref_common.h, band_rows). */
|
||||
long long ry = 0;
|
||||
const long long yl = r4d_rows_pitch(y, 22, &ry);
|
||||
if (yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE);
|
||||
if (ry <= 0 || (M > 0 && ry > M)) return R4D_NO(RAD_E_SHAPE);
|
||||
const int64_t total = ry * 22;
|
||||
hipLaunchKernelGGL(vtile_plan_kernel, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s,
|
||||
(const int*)geom->data, (int*)y->data, (int)tile, (int)overlap, (int)ratio,
|
||||
(int)yl, ry, ry);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_vtile_crop(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *geom = r4d_opt(a, 1), *y = r4d_opt(a, 2);
|
||||
if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if ((!is_f32(x) && !is_bf16(x)) || x->dtype != y->dtype || !is_i32(geom))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long M = r4d_geti_or(a, "M", 0), tile = r4d_geti_or(a, "tile", 0);
|
||||
const long long overlap = r4d_geti_or(a, "overlap", 0), ratio = r4d_geti_or(a, "ratio", 0);
|
||||
if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 ||
|
||||
r4d_numel(geom) < 3)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
long long rx = 0, ry = 0;
|
||||
/* y's rows are the tiles' pixel rows; the ranged `M` is a ceiling only (band_rows). Rows past
|
||||
* the tiles' sum write nothing. */
|
||||
const long long xl = r4d_rows_pitch(x, 3, &rx), yl = r4d_rows_pitch(y, 3, &ry);
|
||||
if (xl < 0 || yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE);
|
||||
if (ry <= 0 || (M > 0 && ry > M)) return R4D_NO(RAD_E_SHAPE);
|
||||
#define R4D_VTC(T) \
|
||||
hipLaunchKernelGGL((vtile_crop_kernel<T>), dim3(blocks_for(ry)), dim3(kT), 0, (hipStream_t)s, \
|
||||
(const T*)x->data, (const int*)geom->data, (T*)y->data, (int)tile, \
|
||||
(int)overlap, (int)ratio, (int)xl, (int)yl, ry, rx, ry)
|
||||
if (is_f32(x)) R4D_VTC(float);
|
||||
else R4D_VTC(uint16_t);
|
||||
#undef R4D_VTC
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_vtile_join(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *geom = r4d_opt(a, 1), *y = r4d_opt(a, 2);
|
||||
if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if ((!is_f32(x) && !is_bf16(x)) || x->dtype != y->dtype || !is_i32(geom))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long M = r4d_geti_or(a, "M", 0), tile = r4d_geti_or(a, "tile", 0);
|
||||
const long long overlap = r4d_geti_or(a, "overlap", 0), n = r4d_geti_or(a, "n", 0);
|
||||
if (M <= 0 || tile <= 0 || overlap < 0 || overlap >= tile || n <= 0 || r4d_numel(geom) < 3)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
long long rx = 0, ry = 0;
|
||||
/* A thread a row of the canvas y; the ranged `M` is a ceiling only (band_rows). */
|
||||
const long long xl = r4d_rows_pitch(x, n, &rx), yl = r4d_rows_pitch(y, n, &ry);
|
||||
if (xl < 0 || yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE);
|
||||
if (ry <= 0 || (M > 0 && ry > M)) return R4D_NO(RAD_E_SHAPE);
|
||||
#define R4D_VTJ(T) \
|
||||
hipLaunchKernelGGL((vtile_join_kernel<T>), dim3(blocks_for(ry)), dim3(kT), 0, (hipStream_t)s, \
|
||||
(const T*)x->data, (const int*)geom->data, (T*)y->data, (int)tile, \
|
||||
(int)overlap, (int)n, (int)xl, (int)yl, ry, rx, ry)
|
||||
if (is_f32(x)) R4D_VTJ(float);
|
||||
else R4D_VTJ(uint16_t);
|
||||
#undef R4D_VTJ
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_grid_pos3(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* y = r4d_opt(a, 0);
|
||||
if (!y) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
Reference in new issue
Block a user