diff --git a/Dockerfile b/Dockerfile index d0c0c375..8963f833 100644 --- a/Dockerfile +++ b/Dockerfile @@ -140,9 +140,12 @@ ARG JOBS= # libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which # mawk lacks. libdav1d7, libwebp7 and libopenh264-7 are the runtime libraries of the ffmpeg stage's # AV1 decoder, WebP encoder and H.264 encoder; busybox-static goes into the runtime image. +# libopenblas-dev: libquant's GPTQ factorises its Hessians through LAPACK where it finds OpenBLAS +# (libquant/CMakeLists.txt); without it rad-convert's gptq rule runs single-threaded loops. RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \ + libopenblas-dev \ && rm -rf /var/lib/apt/lists/* COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg diff --git a/README.md b/README.md index 1a40b6a9..3d641ddb 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,10 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` | | Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` | | Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` | +| Ornith-1.5-122B FP8, MTP, vision, four cards | `ornith-1.5-122b-fp8.rad` (118 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-fp8) | `ornith-1.5-122b.yaml` | +| Ornith-1.5-122B FP8, DFlash2 drafter, vision, four cards | `ornith-1.5-122b-fp8-dflash2.rad` (116 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-fp8-dflash2) | `ornith-1.5-122b-df2.yaml` | +| Ornith-1.5-122B w4a8: 4-bit experts (GPTQ), MTP, vision, four cards | `ornith-1.5-122b-w4a8.rad` (65 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-w4a8) | `ornith-1.5-122b-w4a8.yaml` | +| Ornith-1.5-122B w4a8: 4-bit experts (GPTQ), DFlash2 drafter, vision, four cards | `ornith-1.5-122b-w4a8-dflash2.rad` (64 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-122b-w4a8-dflash2) | `ornith-1.5-122b-w4a8-df2.yaml` | | Sage-A1.5 FP8, MTP, vision | `sage-a1.5-fp8.rad` (35 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8) | `sage-a1.5.yaml`, `sage-a1.5-tp1.yaml` | | Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.yaml` | | MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` | @@ -36,6 +40,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` | | NVIDIA-Nemotron-3.5-Bolt-E4B bf16 (Gemma 4 E4B), NVIDIA's DFlash drafter, vision, one card | `nemotron-3.5-bolt-e4b-bf16.rad` (16 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-bf16) | `nemotron-3.5-bolt-e4b-bf16.yaml` | | NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, one card | `nemotron-3.5-bolt-e4b-i8g.rad` (12 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-i8g) | `nemotron-3.5-bolt-e4b-i8g.yaml` | +| NVIDIA-Nemotron-3.5-Bolt-E4B 4-bit (int4 feed-forward, GPTQ, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, one card | `nemotron-3.5-bolt-e4b-a4.rad` (11 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-a4) | `nemotron-3.5-bolt-e4b-a4.yaml` | | Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | | Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | | Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` | diff --git a/abi/rad_device.h b/abi/rad_device.h index 0bfbfa59..72a12511 100644 --- a/abi/rad_device.h +++ b/abi/rad_device.h @@ -42,6 +42,11 @@ int rad_dev_count(void); int rad_dev_set(int device); int rad_dev_props(int device, RadDeviceProps* out); int rad_dev_enable_peer(int self, int peer); +/* Whether the driver reports that `self` can reach `peer`'s memory, 1 or 0, asked before anything + * is enabled: this is the fact collectives constrain (rad_types.h's RAD_FACT_P2P), so a tool that + * declares a multi-rank graph must measure it and set the fact as Engine does. Negative on a + * device error. */ +int rad_dev_peer_access(int self, int peer); void* rad_dev_alloc(int64_t bytes, int kind); void rad_dev_free(void* p, int kind); diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index e9460530..077e6cfc 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -119,18 +119,27 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false, swiglu_limit)); - /* The fold (decl_gated_fold), an fp8a8 tile, so bf16, f32-scaled, MXFP4, rotated 5-bit, 4-bit - * and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product. - * Declared over int8 codes, only a host kernel would take it, and that would pin the layer's - * weights to the host. */ - if (swiglu_limit <= 0 && !gate_up.bf16 && !gate_up.f32_scale && !gate_up.mx && - !gate_up.paro5 && !gate_up.w4 && !gate_up.i8) + /* The fold: decl_gated_fold, an fp8a8 tile, for block-fp8 weights; decl_gated_fold_mx for a + * plain MXFP4 one at one to eight rows. bf16, f32-scaled, rotated MXFP4, rotated 5-bit, 4-bit + * and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product, which + * neither fold computes. Declared over int8 codes, only a host kernel would take it, and that + * would pin the layer's weights to the host. */ + const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale; + if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.paro5 && !gate_up.w4 && !gate_up.i8) op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws, { w.h.q, w.h.s }, gq_ffn.want_x ? std::initializer_list{ w.ffn.q, w.ffn.s, w.ffn.x } : std::initializer_list{ w.ffn.q, w.ffn.s }, &gated_rows); + else if (fold_ok && gate_up.mx && !gate_up.paro) + op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws, + gate_up.wref, { w.h.q, w.h.s }, + gq_ffn.want_x + ? std::initializer_list{ w.ffn.q, w.ffn.s, + w.ffn.x } + : std::initializer_list{ w.ffn.q, w.ffn.s }, + &gated_rows); RAD_ARCH_TRY(down.declare(b, nm, g, down_base, g.n_embd, g.n_ff, RAD_SHARD_COL, grp_layer(l), { src.down }, w.ffn, w.h.x)); @@ -179,7 +188,13 @@ inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const } inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const { - if (op_gated && rows <= gated_rows) { + if (op_gated && rows <= gated_rows && gate_up.mx) { + RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd), + brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w), + RAD_W(gate_up.ws), RAD_W(gate_up.wref), brow_slice(w.ffn.q, r0, rows, g.n_ff), + brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK), + gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE); + } else if (op_gated && rows <= gated_rows) { RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd), brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w), RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff), diff --git a/arch/common/rad_block_ple.h b/arch/common/rad_block_ple.h index a09f2f78..446504fa 100644 --- a/arch/common/rad_block_ple.h +++ b/arch/common/rad_block_ple.h @@ -106,10 +106,18 @@ struct PleLayer { rad_op op_gate = 0, op_conv = 0, op_add = 0; int64_t hn() const { return c.hc * g.n_embd; } + /* The read-ahead queue's depth, in steps: the scheduler stages this many steps of the + * following prompt per step (batch.cpp, k_ahead_chunks) and the gather hands them to the + * reader thread, which prefetches their rows off the step path while the current chunk runs. + * Clamped to what `b_ids` was declared to hold, so a scheduler that offers more degrades the + * queue's depth, never an overflow. */ + static constexpr int64_t kAheadChunks = 8; /* The prompt that follows the step, bounded by what `b_ids` holds after the step's rows. */ int64_t ahead_rows(const RadBatch* batch) const { const int64_t a = batch->n_ahead; - return a <= 0 ? 0 : (a < g.max_tok ? a : g.max_tok); + if (a <= 0) return 0; + const int64_t cap = kAheadChunks * g.max_tok; + return a < cap ? a : cap; } int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg, int layer, @@ -275,10 +283,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C * follows declared order, where the two ops are adjacent, so a transient could be overwritten * in between. */ { - /* Twice the step's rows: the step's ids, then those of the prompt that follows - * (RadBatch::n_ahead), which the gather's reader prefetches while the step runs. */ + /* The step's rows, then the read-ahead queue's: up to kAheadChunks further steps of the + * following prompt (RadBatch::n_ahead), which the gather's reader prefetches while the + * step runs, so a prefill's table rows are read at disk speed off the step path. */ RadBufDecl d{}; - d.dtype = RAD_I32; d.rank = 2; d.shape[0] = 2 * g.max_tok; d.shape[1] = c.heads; + d.dtype = RAD_I32; d.rank = 2; + d.shape[0] = (1 + kAheadChunks) * g.max_tok; d.shape[1] = c.heads; d.kind = RAD_BUF_PERSIST; d.domain = RAD_DOMAIN_HOST; b_ids = rad_decl_buffer(b, nm.f("ple_ids"), &d); diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 4cdbb459..9af9c854 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -1692,6 +1692,28 @@ inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K, return op; } +/* The same fold over an OCP-MXFP4 [2n, K] gate_up weight (`gemm_nt_q_gated_mx`: codes, the E8M0 + * plane and that plane again as the per-row reference), declared for M up to min(rows, 8), the band + * of libr4d's one-to-eight-row GEMM it is built on. Optional like decl_gated_fold, and asked for + * only when a loaded library declares the op: libref does not, so a CPU-only engine takes the pair + * without ever naming it. */ +inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, + rad_weight ws, rad_weight wref, + std::initializer_list reads, + std::initializer_list writes, int64_t* gated_rows) { + const int64_t hi = rows < 8 ? rows : 8; + if (hi <= 0 || N % 256 || K % RAD_FP8_BLOCK) return 0; + if (!rad_op_declared(b, "gemm_nt_q_gated_mx")) return 0; + const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated_mx", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"), + RAD_STR("act", "silu")), + RAD_WEIGHTS(w, ws, wref)), + reads, writes); + if (op) *gated_rows = hi; + return op; +} + } /* namespace arch */ } /* namespace rad */ diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index f9efb790..35164a5b 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -655,6 +655,11 @@ struct Gemma3Mlp { G3Linear ln_gu{}, ln_down{}; rad_op op_norm = 0, op_act = 0, op_post = 0, op_ar = 0, op_add = 0; rad_op op_gq = 0; + /* gate|up, the GeGLU and down's E4M3 quantiser in one launch (libr4d gemm_nt_q_gated_mx at + * gelu_tanh) at up to `fold_rows` rows, when both linears are MXFP4: byte-identical to the + * GEMM, gelu_mul and quant_act_fp8 it replaces. */ + rad_op op_fold = 0; + int64_t fold_rows = 0; /* Calibration: gate|up's input and down's (this rank's columns). */ G3Tap tap_gu{}, tap_dn{}; const bool* tap_live = nullptr; @@ -725,6 +730,22 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), {w.gu}, {ln_down.q8, ln_down.s8}); + // Not under calibration either: the down tap reads the bf16 product, which the fold never writes. + { + const int64_t hi = g.max_tok < 8 ? g.max_tok : 8; + // G3Linear's mx is linear_is_mxfp4, never a rotated (ParoQuant) weight, so one part. + if (ln_gu.mx && ln_down.mx && !ln_down.shared_in && !calib_dir() && hi > 0 && + ln_gu.N % 256 == 0 && ln_gu.K % RAD_FP8_BLOCK == 0 && + rad_op_declared(b, "gemm_nt_q_gated_mx")) { + op_fold = rw(b, RAD_OP(b, "gemm_nt_q_gated_mx", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", ln_gu.N), RAD_INT("K", ln_gu.K), + RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"), + RAD_STR("act", "gelu_tanh")), + RAD_WEIGHTS(ln_gu.w, ln_gu.ws, ln_gu.wref)), + {ln_gu.q8, ln_gu.s8}, {ln_down.q8, ln_down.s8}); + if (op_fold) fold_rows = hi; + } + } if (g.world > 1) op_ar = rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), @@ -754,14 +775,23 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused, bool ar_fused) const { const int64_t T = batch->n_tok; + const bool fold = op_fold && T <= fold_rows; if (entry_done) { - ln_gu.gemm(c, w.gu, T); + if (!fold) ln_gu.gemm(c, w.gu, T); } else { RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); - ln_gu.step(c, w.h, w.gu, T); + if (!fold) + ln_gu.step(c, w.h, w.gu, T); + else if (!ln_gu.shared_in) + RAD_ISSUE_N(c, ln_gu.op_q, T, brows(w.h, T), brows(ln_gu.q8, T), brows(ln_gu.s8, T)); tap_gu.step(c, w.h, T, tap_live); } - if (op_gq) { + if (fold) { + RAD_ISSUE_N(c, op_fold, T, brows(ln_gu.q8, T), brows(ln_gu.s8, T), RAD_W(ln_gu.w), + RAD_W(ln_gu.ws), RAD_W(ln_gu.wref), brows(ln_down.q8, T), brows(ln_down.s8, T), + RAD_NONE); + ln_down.gemm(c, w.h, T); + } else if (op_gq) { RAD_ISSUE_N(c, op_gq, T, brows(w.gu, T), brows(ln_down.q8, T), brows(ln_down.s8, T), RAD_NONE); ln_down.gemm(c, w.h, T); } else { @@ -884,12 +914,28 @@ struct G3JunctionFP8 { } }; +/* The weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h): a weight's first + * kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows (a verify of four sequences at + * speculation 7, as qwen35_fp8's). TranslateGemma-27B MXFP4 + DFlash2 at tp 2 on 2x R9700 (Gen5 x8), + * no speculation, two rounds each, x1 / x4 / x8 tok/s against none (56.8 / 182.0 / 325.0): 8 MB 63.3 / + * 203.1 / 354.9; 12 MB 63.0 / 202.6 / 354.9; 16 MB 63.5 / 203.9 / 356.6; 20 MB 64.1 / 204.0 / 359.4; + * 24 MB 64.4 / 206.4 / 359.3; 32 MB 63.1 / 201.4 / 351.9. Larger than qwen35_fp8's 12 MB: this + * model's hidden width (5376) and weights are larger, so its all-reduces take longer and its GEMMs + * read more; past ~24 MB the read outlasts the reduction and takes bandwidth from the GEMM it should + * feed. With speculation 7 (three rounds, greedy, medians) x1 / x4 / x8 / x16 158.1 / 409.0 / 592.0 / 710.8 -> 177.3 / 428.4 / 592.3 / 717.6. The drafter's reads (Dflash2::Config::prefetch) take the same size. */ +constexpr int64_t kPrefetchBytes = (int64_t)24 << 20; +constexpr int64_t kPrefetchStepRows = 32; + struct Layer { bool global = false; Gemma3Attn attn{}; Gemma3Mlp mlp{}; G3Junction j_am{}, j_ma{}; G3JunctionFP8 jf_am{}, jf_ma{}; + /* The reads beside the decode all-reduces: gate|up's leading bytes beside the attention block's + * reduction, the next layer's q's beside the feed-forward's. 0 where none is declared. */ + rad_op op_pf_gu = 0, op_pf_next = 0; + rad_weight pf_gu_w = 0, pf_next_w = 0; }; struct Model { @@ -974,6 +1020,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui Dflash2::Config dc{}; dc.short_block = 1; /* rad_drafter_short_block below */ + dc.prefetch = kPrefetchBytes; /* reads beside the drafter's all-reduces (at tp > 1) */ dc.n_taps = m.n_taps; dc.block = ctx->max_spec + 1; dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2); @@ -1325,6 +1372,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } m.fuse_mx_ar = ar; } + /* ---- the weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h). Only at + * more than one rank; RADIANCE_PREFETCH_BESIDE=0 issues none (prefetch_beside). */ + if (g.world > 1 && rad_op_declared(b, "prefetch")) { + for (int64_t l = 0; l < g.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.pf_gu_w = lay.mlp.ln_gu.w; + lay.op_pf_gu = decl_prefetch(b, lay.pf_gu_w, kPrefetchBytes); + if (l + 1 < g.n_layer) { + lay.pf_next_w = m.layers[(size_t)l + 1].attn.ln_q.w; + lay.op_pf_next = decl_prefetch(b, lay.pf_next_w, kPrefetchBytes); + } + } + } /* The pipeline needs the fused fp8 junctions and every block's overlap all-reduce. */ if (m.pipe_on) { bool ok = m.fuse_mx; @@ -1642,6 +1702,9 @@ static void step(RadCtx* c, const RadBatch* batch) { if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, T * m.g.n_embd, brows(m.b_x, T), RAD_NONE); + /* The reads beside the reductions go on decode steps of up to kPrefetchStepRows rows, none on a + * step that carries a prompt's rows (as qwen35_fp8's). */ + const int64_t pf_h = batch->phase == RAD_PHASE_DECODE && T <= kPrefetchStepRows ? 1 : INT64_MAX; if (m.fuse_mx) { /* MXFP4 trunk: [post-norm, then add + next norm + quantiser as one op] at every junction; * the last block's tail runs unfused into the final norm. */ @@ -1652,9 +1715,11 @@ static void step(RadCtx* c, const RadBatch* batch) { /* Per step: the fused junction sends the exact wire only (G3JunctionFP8::op_ar). */ const bool far = m.fuse_mx_ar && ar_wire_is_exact(m.g, T); l.attn.step(c, batch, true, true, far); + prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h); if (!far) l.attn.post(c, T); l.jf_am.step(c, T, far); l.mlp.step(c, batch, true, !last, far); + prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h); if (!last) { if (!far) l.mlp.post(c, T); l.jf_ma.step(c, T, far); @@ -1668,8 +1733,10 @@ static void step(RadCtx* c, const RadBatch* batch) { const bool last = li + 1 == m.layers.size(); const bool ar = m.fuse_ar && ar_wire_is_exact(m.g, T); /* exact wire only, as above */ l.attn.step(c, batch, m.fuse, m.fuse, ar); + prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h); if (m.fuse) l.j_am.step(c, T, ar); l.mlp.step(c, batch, m.fuse, m.fuse && !last, ar); + prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h); if (m.fuse && !last) l.j_ma.step(c, T, ar); tap(li); } diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index 25570fed..4700ad48 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -106,11 +106,30 @@ using Ffn = MlpFP8; using MtpHead = MtpFP8; #endif +/* The weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h): a weight's first + * kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows. Qwen3.8-27B MXFP4 + DFlash2 at tp 2 + * on 2x R9700 (Gen5 x8), one round each, no speculation, x1 / x4 / x8 / x16 tok/s against none + * (61.2 / 225.0 / 403.7 / 650.8): 8 MB 65.1 / 246.4 / 410.9 / 663.3; 10 MB 66.0 / 250.1 / 425.0 / + * 668.5; 12 MB 67.9 / 251.2 / 438.6 / 668.1; 14 MB 67.8 / 249.5 / 432.4 / 659.1; 16 MB 67.0 / 244.9 / + * 422.7 / 649.4; 20 MB 63.4 / 232.0 / 408.1 / 630.7; 32 MB 57.9 / 210.2 / 372.8 / 605.9 -- past + * ~12 MB the read outlasts the reduction and takes bandwidth from the GEMM it should feed. Reads up + * to 128 rows: x32 963.8 against 956.0, x64 1206.7 against 1216.6, so the ceiling is 32 rows (a + * verify of four sequences at speculation 7). With speculation 7 (three rounds) x1..x16 +0.1..+1.9 %. + * The drafter's reads (Dflash2::Config::prefetch) take the same size: speculation 7, eight rounds, + * median x1 +6 %, x16 unchanged. */ +constexpr int64_t kPrefetchBytes = (int64_t)12 << 20; +constexpr int64_t kPrefetchStepRows = 32; + struct Layer { int full = 0; AttnGatedFP8 attn; GdnFP8 gdn; Ffn mlp; + /* The reads beside the decode all-reduces (prefetch_beside, rad_arch.h): gate_up's leading + * bytes beside the mixer's reduction, the next layer's first projection's beside the + * feed-forward's. 0 where none is declared. */ + rad_op op_pf_gu = 0, op_pf_next = 0; + rad_weight pf_gu_w = 0, pf_next_w = 0; }; struct Model { @@ -283,6 +302,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui Dflash2::Config dc{}; dc.short_block = 1; /* rad_drafter_short_block below */ + dc.prefetch = kPrefetchBytes; /* reads beside the drafter's all-reduces (at tp > 1) */ dc.n_taps = m.n_taps; dc.block = ctx->max_spec + 1; dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2); @@ -1026,6 +1046,27 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c for (int64_t l = 0; l + 1 < m.n_main; ++l) m.layers[(size_t)l].mlp.xp_next = &m.layers[(size_t)l + 1].mlp; #endif +#if !QWEN35_MOE + /* ---- the weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h). At decode + * heights each block's reduction leaves the card's memory idle for its round trip over the link, + * so the GEMM behind it has its weight's leading bytes read into the on-die cache there: gate_up + * behind the mixer's reduction, the next layer's first projection (the delta net's in-projection, + * an attention layer's q|gate) behind the feed-forward's. Only at more than one rank; + * RADIANCE_PREFETCH_BESIDE=0 issues none (prefetch_beside). */ + if (g.world > 1 && rad_op_declared(b, "prefetch")) { + for (int64_t l = 0; l < m.n_main; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.pf_gu_w = lay.mlp.gate_up.w; + lay.op_pf_gu = decl_prefetch(b, lay.pf_gu_w, kPrefetchBytes); + if (l + 1 < m.n_main) { + const Layer& nx = m.layers[(size_t)l + 1]; + lay.pf_next_w = nx.full ? nx.attn.qg.w : nx.gdn.in.w; + lay.op_pf_next = decl_prefetch(b, lay.pf_next_w, kPrefetchBytes); + } + } + } +#endif + m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_F64("eps", g.eps), RAD_F64("wadd", final_wadd), RAD_STR("dtype", g.dtype)), @@ -1497,12 +1538,19 @@ static void step(RadCtx* c, const RadBatch* batch) { RAD_ISSUE_N(c, m.op_rope_cs, batch->n_tok, rope_pos1(batch, batch->n_tok), RAD_B(m.b_rope_cs)); + /* The reads beside the reductions go on decode steps of up to kPrefetchStepRows rows, none on a + * step that carries a prompt's rows. This ceiling, not prefetch_beside's own (16), decides: it + * is passed a height of 1 where the step qualifies. */ + const int64_t pf_h = + batch->phase == RAD_PHASE_DECODE && batch->n_tok <= kPrefetchStepRows ? 1 : INT64_MAX; for (int64_t li = 0; li < (int64_t)m.layers.size(); ++li) { const Layer& l = m.layers[(size_t)li]; if (l.full) l.attn.step(c, batch); else l.gdn.step(c, batch); + prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h); dbg_resid(c, (int)li, "mix", m.g.n_embd, m.b_x, m.a_h.x); l.mlp.step(c, batch); + prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h); dbg_resid(c, (int)li, "ffn", m.g.n_embd, m.b_x, m.a_h.x); /* The tap, after the layer: the drafter conditions on this layer's output, which the next diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 4e18e73a..3ce95204 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -199,6 +199,7 @@ private: /* init() for every surviving instance, after the whole graph has resolved, so a failing init * cannot abort declare before the miss report is assembled. */ void finish_instances(); + void fill_tune_instances(); int32_t find_kv_consumer(rad_kvgroup g); void finish_layouts(); void finish_kv_groups(); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 6c78295d..dae2aed2 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -501,6 +501,7 @@ void Builder::record_tune_request(const Resolved& r) { req.geom = r.geom; req.geom_key = r.geom_key; req.info = r.row->info; + req.instance = r.instance; prog_.tune_requests.push_back(std::move(req)); } @@ -611,6 +612,29 @@ void Builder::finish_instances() { } } } + +/* The instances are made in finish_instances(), after record_tune_request ran, so the requests + * now carry the instance their kernel will launch with. A collective's launch cannot be formed + * without it -- the peer bundle (scratch, flags, sequence counters) is what init() builds and + * RadArgs reaches the exchange through nothing else -- so the tuner forms its launches from this. + * Keyed exactly as record_tune_request keyed. */ +void Builder::fill_tune_instances() { + for (size_t i = 1; i < prog_.ops.size(); ++i) { + const OpInfo& oi = prog_.ops[i]; + for (const Band& b : oi.bands) + for (int d = 0; d < RAD_N_DOMAINS; ++d) { + const Resolved& r = b.dom[d]; + if (!r || !r.row || !r.row->info) continue; + const std::string key = r.row->info->name + std::string("\x1f") + r.row->plugin + + std::string("\x1f") + r.geom_key; + for (auto& t : prog_.tune_requests) + if (t.kernel + std::string("\x1f") + t.plugin + std::string("\x1f") + + t.geom_key == key) + t.instance = r.instance; + } + } +} + rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, const rad_weight* w, int n_w) { if (finished_) return err(RAD_E_STATE, "decl_op('%s') after declare finished", opname ? opname : ""); @@ -2410,6 +2434,7 @@ int Builder::finish() { } if (instances_) finish_instances(); + fill_tune_instances(); finish_weight_uses(); finish_layouts(); finish_kv_groups(); diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index 16b20d6f..8855e3f9 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -535,6 +535,7 @@ int dev_code_runs(size_t from, size_t to, int device, std::string* why) { extern "C" { +int rad_dev_peer_access(int self, int peer) { return rad::dev_peer_access(self, peer); } int rad_event_create_as(RadEvent* out, unsigned flags) { const int s = dev()->event_create(out, flags); diff --git a/core/engine.cpp b/core/engine.cpp index 07dd4b19..e7bf014a 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -425,6 +425,10 @@ int Engine::step_loop() { /* The next step's forward pass when already issued behind the previous step, before its * readback (Scheduler::step_next). */ const RadBatch* ahead = nullptr; + /* Names where the step loop waits when nothing has been logged for a while: a freeze reports + * the blocked thread, its syscall and its stack; long quiet generations report sparsely (the + * silence doubles) and the reports read as the ordinary GPU wait. */ + rad::StallWatch step_watch("step", 20000); while (!stopping_.load(std::memory_order_acquire)) { lora_epoch_.fetch_add(1, std::memory_order_acq_rel); phase_t_ = std::chrono::steady_clock::now(); diff --git a/core/rad_core.h b/core/rad_core.h index dcb22f55..c310e9fa 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -508,6 +508,13 @@ public: Geometry geom; std::string geom_key; const RadKernelInfo* info = nullptr; + /* The instance init() produced for this instantiation, null for a kernel with no init. + * A collective's launch cannot be formed without it: the peer bundle -- the scratch, the + * flags and the sequence counters, published to every rank and made peer-accessible at + * init -- is what makes the exchange addressable, and RadArgs carries no other route to + * it. The instance belongs to the rank this Program was declared for (Program::ctx), and + * the Registry that made it must outlive the launch (spec §1, §15). */ + void* instance = nullptr; }; std::vector tune_requests; diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 5baf187c..154f12b3 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -595,8 +595,12 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { : "has no device kernel for this band"); /* The second lane's window (rad_lane1_window_begin): its concurrent buffers are live only across * it, so lane 1 runs nothing outside it, and lane 0 joins lane 1 before it runs an op outside - * it, on either side: a transient of such an op may share bytes with a concurrent buffer. */ - if (program_ && program_->lane1_w1 >= 0) { + * it, on either side: a transient of such an op may share bytes with a concurrent buffer. An op + * that names no buffer (a weight read into the cache, prefetch_beside) touches nothing the window + * keeps live and has no transient: it runs on lane 1 anywhere and leaves no window work to join. */ + bool names_buf = false; + for (int i = 0; i < n_opd && !names_buf; ++i) names_buf = opd[i].kind == RAD_OPK_BUF; + if (program_ && program_->lane1_w1 >= 0 && names_buf) { const bool outside = p.order < program_->lane1_w0 || p.order > program_->lane1_w1; if (lane_ == 1 && outside) return abort_step_msg(h, RAD_E_STATE, @@ -610,7 +614,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { return abort_step_msg(h, js, "joining the second lane outside its window failed"); } } - if (lane_ == 1) lane1_pending_ = true; + if (lane_ == 1 && names_buf) lane1_pending_ = true; /* The row's DIV on the ranged parameter held at the band's upper bound, maybe not here. */ if (ip.ranged_div > 1 && n % ip.ranged_div != 0) diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index 9f814835..30b2f6ca 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -13,6 +13,13 @@ namespace rad { +/* How many steps of the following prompt the PLE read-ahead queue stages (RadBatch::n_ahead): + * the arch's reader thread drains the queue at disk speed, off the step path, so a prefill + * chunk's table rows are already cached when its gather runs. Keep in step with rad_block_ple.h + * (kAheadChunks), which clamps to the buffer it declared; a mismatch degrades to a smaller queue, + * never an overflow. */ +static constexpr int64_t k_ahead_chunks = 8; + /* Alignment of each staging array carved from a set's slab. One slab per set means a couple of * allocations at init instead of two dozen, with every array sharing one mapping. */ static const int64_t k_carve_align = 256; @@ -98,9 +105,10 @@ void BatchBuilder::carve(Set& s, char* h) { *ph = ::rad::carve(h, oh, n); *pd = ::rad::carve(d, od, n); }; - /* Twice the step: its own tokens, then up to a step of the following prompt - * (RadBatch::n_ahead). */ - pair(&s.h_tok, &s.d_tok, 2 * T); + /* The step's tokens, then the PLE read-ahead queue -- k_ahead_chunks steps of the following + * prompt (RadBatch::n_ahead), which the arch's reader thread prefetches off the step path + * (rad_block_ple.h, which clamps to the same count). */ + pair(&s.h_tok, &s.d_tok, (1 + k_ahead_chunks) * T); pair(&s.h_pos, &s.d_pos, T); pair(&s.h_parent, &s.d_parent, T); pair(&s.h_cu, &s.d_cu, S + 1); @@ -1052,17 +1060,18 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, } } - /* Up to a step of the last sequence's following tokens, after this step's own - * (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, bounded by - * the tokens the request has; like token_at, a re-prefill after preemption continues into its - * own output. */ + /* Up to the read-ahead queue's worth of the last sequence's following tokens, after this + * step's own (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, + * bounded by the tokens the request has; like token_at, a re-prefill after preemption + * continues into its own output. The arch clamps to the rows it declared. */ int64_t n_ahead = 0; if (n_seq > 0 && plan.draft_pass == 0 && plan.tok_shift == 0) { const StepEntry& e = plan.e[(size_t)(n_seq - 1)]; if (e.req && e.is_prefill) { const int64_t next = (int64_t)e.ctx_len + e.n_tokens; const int64_t have = (int64_t)e.req->prompt.size() + (int64_t)e.req->output.size(); - n_ahead = std::min(std::max(have - next, 0), max_tok_); + n_ahead = std::min(std::max(have - next, 0), + k_ahead_chunks * max_tok_); for (int64_t j = 0; j < n_ahead; ++j) s.h_tok[n_tok + j] = token_at(e, next + j); } } diff --git a/deploy/compose/nemotron-3.5-bolt-e4b-a4.yaml b/deploy/compose/nemotron-3.5-bolt-e4b-a4.yaml new file mode 100644 index 00000000..0b61c0ca --- /dev/null +++ b/deploy/compose/nemotron-3.5-bolt-e4b-a4.yaml @@ -0,0 +1,17 @@ +# NVIDIA-Nemotron-3.5-Bolt-E4B (Gemma 4 E4B, post-trained by NVIDIA) at 4 bits on one card: the +# feed-forward as asymmetric int4 (GPTQ; w4a8i8_asym, w4a16_asym at decode heights), attention and +# layers 19-23 at i8a8, NVIDIA's DFlash drafter (7 tokens a pass) and the bf16 vision tower in pinned +# host memory. bf16 KV. Thinking is off, as in NVIDIA's template; switch it per request +# (chat_template_kwargs). Sampling as NVIDIA states it (temperature 1.0, top_p 0.95) and the +# checkpoint's top_k 64. +name: radiance-nemotron-3.5-bolt-e4b-a4 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-nemotron-3.5-bolt-e4b-a4 + command: > + --model /models/nemotron-3.5-bolt-e4b-a4.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 --max-num-seqs 8 --max-model-len 65536 --kv-cache-dtype bf16 + --num-speculative-tokens 7 --mm-max-patches 2520 --vision-tower-placement ram + --temp 1.0 --top-p 0.95 --top-k 64 --chat-template-kwargs '{"enable_thinking":false}' diff --git a/deploy/compose/ornith-1.5-122b-df2.yaml b/deploy/compose/ornith-1.5-122b-df2.yaml new file mode 100644 index 00000000..dfae8855 --- /dev/null +++ b/deploy/compose/ornith-1.5-122b-df2.yaml @@ -0,0 +1,18 @@ +# Ornith-1.5-122B FP8 with incoai's DFlash2 drafter in place of the MTP head, on four cards with the +# host pool and the vision tower of ornith-1.5-122b.yaml. The drafter proposes 15 tokens in one pass, +# the depth radiance reads from the container. On four R9700s: 183 tok/s combined (BetterBench) +# against 165 with MTP, 342 against 194 on JSON, but 81 against 120 on prose; for chat, prose and +# many users take the MTP file. At 8 sequences the cache holds 690,992 tokens. Sampling as +# ornith-1.5-35b-a3b.yaml. +name: radiance-ornith-1.5-122b-df2 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-122b-df2 + command: > + --model /models/ornith-1.5-122b-fp8-dflash2.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 4 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --placement expert_tiered --host-pool-mib 3072 --vision-tower-placement ram + --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/deploy/compose/ornith-1.5-122b-w4a8-df2.yaml b/deploy/compose/ornith-1.5-122b-w4a8-df2.yaml new file mode 100644 index 00000000..4f47d9d3 --- /dev/null +++ b/deploy/compose/ornith-1.5-122b-w4a8-df2.yaml @@ -0,0 +1,16 @@ +# Ornith-1.5-122B w4a8 (the weights of ornith-1.5-122b-w4a8.yaml) with incoai's DFlash2 drafter in +# place of the MTP head, every weight in VRAM on four cards. The drafter proposes 15 tokens in one +# pass, the depth radiance reads from the container. On four R9700s: 279 tok/s combined +# (BetterBench) against 217 with MTP, 556 against 256 on JSON, but 108 against 157 on prose; for +# chat, prose and many users take the MTP file. Sampling as ornith-1.5-35b-a3b.yaml. +name: radiance-ornith-1.5-122b-w4a8-df2 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-122b-w4a8-df2 + command: > + --model /models/ornith-1.5-122b-w4a8-dflash2.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 4 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/deploy/compose/ornith-1.5-122b-w4a8.yaml b/deploy/compose/ornith-1.5-122b-w4a8.yaml new file mode 100644 index 00000000..8bfcfa8a --- /dev/null +++ b/deploy/compose/ornith-1.5-122b-w4a8.yaml @@ -0,0 +1,15 @@ +# Ornith-1.5-122B with four-bit experts (w4nl64, GPTQ), the trunk block-FP8, an int8 lm_head, its own +# MTP head and the vision tower: 65 GiB, every weight in VRAM on four cards, no host pool. At 8 +# sequences the cache holds 2,097,280 tokens, eight full 262,144-token sessions. Sampling as +# ornith-1.5-35b-a3b.yaml. +name: radiance-ornith-1.5-122b-w4a8 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-122b-w4a8 + command: > + --model /models/ornith-1.5-122b-w4a8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 4 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --num-speculative-tokens 3 --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/deploy/compose/ornith-1.5-122b.yaml b/deploy/compose/ornith-1.5-122b.yaml new file mode 100644 index 00000000..75c1ce3e --- /dev/null +++ b/deploy/compose/ornith-1.5-122b.yaml @@ -0,0 +1,18 @@ +# Ornith-1.5-122B, FP8 with one scale per 128x128 block, its own MTP head and the vision tower, on +# four cards. The 118 GiB of weights fill the cards: a pinned host pool of 3 GiB per card +# (--host-pool-mib counts per card) holds the experts that do not fit, and the vision tower sits in +# host memory. At 8 sequences the cache holds 614,208 tokens, two full 262,144-token sessions; a +# 16 GiB pool holds 2,097,280, but moves more experts over PCIe and decodes far slower. Sampling as +# ornith-1.5-35b-a3b.yaml. +name: radiance-ornith-1.5-122b +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-122b + command: > + --model /models/ornith-1.5-122b-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 4 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --placement expert_tiered --host-pool-mib 3072 --vision-tower-placement ram + --num-speculative-tokens 3 --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/docs/DOCKER.md b/docs/DOCKER.md index bbfd6099..a2e12dd3 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -133,6 +133,10 @@ the cards the engine runs on. | `ornith-1.5-35b-a3b.yaml` | `ornith-1.5-35b-a3b-fp8.rad` | Ornith-1.5-35B-A3B, FP8, MTP, vision | | `ornith-1.5-35b-a3b-w4a8.yaml` | `ornith-1.5-35b-a3b-w4a8.rad` | Ornith-1.5-35B-A3B with four-bit experts (GPTQ), a block-FP8 trunk, MTP, vision | | `ornith-1.5-35b-a3b-w4a8-tp1.yaml` | `ornith-1.5-35b-a3b-w4a8.rad` | The same on one card, every weight in VRAM | +| `ornith-1.5-122b.yaml` | `ornith-1.5-122b-fp8.rad` | Ornith-1.5-122B, FP8, MTP, vision, on four cards with a 3 GiB pinned host pool per card and the vision tower in host memory | +| `ornith-1.5-122b-df2.yaml` | `ornith-1.5-122b-fp8-dflash2.rad` | The same with incoai's DFlash2 drafter in place of the MTP head | +| `ornith-1.5-122b-w4a8.yaml` | `ornith-1.5-122b-w4a8.rad` | Ornith-1.5-122B with four-bit experts (GPTQ), a block-FP8 trunk, MTP, vision, every weight in VRAM on four cards | +| `ornith-1.5-122b-w4a8-df2.yaml` | `ornith-1.5-122b-w4a8-dflash2.rad` | The same with incoai's DFlash2 drafter in place of the MTP head | | `sage-a1.5.yaml` | `sage-a1.5-fp8.rad` | Sage-A1.5, FP8, MTP, vision | | `sage-a1.5-tp1.yaml` | `sage-a1.5-fp8.rad` | The same on one card: the expert plane partly in an 8 GiB pinned host pool, one 262,144-token session | | `sage-a1.5-df2.yaml` | `sage-a1.5-fp8-df2.rad` | Sage-A1.5 with incoai's Qwen3.6-35B-A3B DFlash2 drafter in place of the MTP head, vision | @@ -143,6 +147,9 @@ the cards the engine runs on. | `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 | | `gemma4-31b-w4a8.yaml` | `gemma4-31b-w4a8.rad` | Gemma 4 31B, int4 trunk with int8 activations, its assistant head as the MTP drafter, vision tower | | `gemma4-31b-heretic-ara-w4a8.yaml` | `gemma4-31b-heretic-ara-w4a8.rad` | The same for Gemma 4 31B heretic-ara (refusals removed) | +| `nemotron-3.5-bolt-e4b-bf16.yaml` | `nemotron-3.5-bolt-e4b-bf16.rad` | NVIDIA-Nemotron-3.5-Bolt-E4B (Gemma 4 E4B) in bf16 with NVIDIA's DFlash drafter, the vision tower in pinned host memory, on one card | +| `nemotron-3.5-bolt-e4b-i8g.yaml` | `nemotron-3.5-bolt-e4b-i8g.rad` | The same with the trunk at int8 (i8a8) | +| `nemotron-3.5-bolt-e4b-a4.yaml` | `nemotron-3.5-bolt-e4b-a4.rad` | The same with the feed-forward at four bits (GPTQ), attention and layers 19-23 at i8a8 | | `translategemma-27b.yaml` | `translategemma-27b-mxfp4-gptq.rad` | TranslateGemma 27B MXFP4 with its chat template (`gemma3.jinja`) | | `glm53-flash.yaml` | `glm53-flash-mxfp4.rad` | GLM-5.3-Flash, MXFP4 experts and block-FP8 attention, on eight cards | | `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter | @@ -178,7 +185,7 @@ docker compose -f flashnext.yaml down # stop ``` Every model listens on the same port and most take both cards (`flashnext-tp1.yaml`, -`ornith-1.5-35b-a3b-w4a8-tp1.yaml`, `qwen3.8-27b-paro.yaml` and the files that read `RADIANCE_GPU` take one, `glm53-flash.yaml` -eight), so run one at a time: `down` one before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and +`ornith-1.5-35b-a3b-w4a8-tp1.yaml`, `qwen3.8-27b-paro.yaml`, the `nemotron-3.5-bolt-e4b-*.yaml` files and the files that read `RADIANCE_GPU` take one, the +`ornith-1.5-122b*.yaml` files four, `glm53-flash.yaml` eight), so run one at a time: `down` one before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and the dashboard page answer without the API key, and the health check fetches `/health` with busybox's `wget`. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 1bb8efed..b536efbc 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -3475,6 +3475,8 @@ minutes of concurrent long prompts on both without a stall. The ceiling costs pr reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapped, 9.8 s at 64, 10.3 s at 32. Give the engine started first its `--gpu-headroom-mib` for the second. A model whose decode reads weights ahead on a second queue (Gemma 4 without chained launches) slows sharply beside a second server: an R9700 has four compute queue slots and the two servers hold eight, so every decode step waits for a queue switch. Gemma 4 31B at TP4 beside an idle Qwen3.8-Flash-Next went from 13 ms to 41 ms a step; with `RADIANCE_PREFETCH_BESIDE=0` in the Gemma engine it took 13.8 ms. +The four slots are what the amdgpu kernel driver leaves to user queues. It keeps compute queues of its own for submissions through the graphics stack (Vulkan and OpenGL in Mesa), four of the eight on the card's two compute pipes by default (`num_cp_queues 4` in `/sys/class/kfd/kfd/topology/nodes/*/properties`). A machine that drives its cards through ROCm alone can give them back with the module option `amdgpu.num_kcq=0` (a line `options amdgpu num_kcq=0` in `/etc/modprobe.d/`, then `update-initramfs -u` and a reboot): `num_cp_queues` reads 8 and `dmesg` shows `compute_hqd_mask 0x0000000f` (`num_kcq=1` leaves `0x0000000e`, three queues a pipe, though `num_cp_queues` reads 7). An engine holds up to four queues a card (the step's lane, the second lane, the mover's and the runtime's own), so two engines then fit and the weight reads can stay on. Start them one after the other and send the first a short request before starting the second: an engine creates its second-lane queue at the first step that uses it (a decode step where the weight reads or another second-lane op run), and a queue created after the other engine's queues lands where both run slower (TranslateGemma one stream 120 t/s instead of 181, Qwen beside a busy TranslateGemma 50 ms a step instead of 43). Qwen3.8-27B and TranslateGemma 27B on two R9700s, the reads on in both: TranslateGemma one stream 180.6-180.9 t/s and Qwen beside a busy TranslateGemma 42.9 ms a step, against 152-154 t/s and 41.0-42.8 ms with the default slots and `RADIANCE_PREFETCH_BESIDE=0` in both; Qwen beside an idle TranslateGemma 18.3 ms a step, against 19.8-20.5. Mesa then finds no compute ring of its own on those cards. + **Tooling** | | | diff --git a/docs/OPS.md b/docs/OPS.md index 19db01f8..e318ea90 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -591,6 +591,7 @@ and is optional. | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | | `swiglu_clamped_quant_fp8` | `M`(range) `n` `limit`:f64 `group` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? | | `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | +| `gemm_nt_q_gated_mx` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w, `b_ref`w → `q`, `scale`, `out_bf16`? | `quant_cols_fp8` is the same E4M3 quantiser with one scale per column over all `M` rows, `scale[c] = amax_r |x[r, c]| * (1/448)` (1 for an all-zero column), `scale` `[n]` f32: an @@ -604,6 +605,11 @@ it does not produce that op's `y`. `act` is required here, unlike on the quantis implementation may compile one gate only, and an optional parameter would let it resolve for another. +`gemm_nt_q_gated_mx` is the same fold over an OCP-MXFP4 weight (`dtype` `mxfp4a8`, `group` 32), which +`gemm_nt_q` reads with the per-row reference exponent `b_ref` after `b_scale`. A schema of its own +because an op's operand count is fixed for the plugins built against it. `act` `gelu_tanh` is the +GeGLU form, `gemm_nt_q` then `gelu_mul` then `quant_act_fp8`; it writes no `out_bf16`. + `swiglu_clamped_quant_fp8` (device-only) is `swiglu_clamped` then `quant_act_fp8` over its product in one pass. The product is rounded to bf16 before the quantiser reads it, as the pair reads it from its bf16 tensor, so the codes, scales and `out_bf16` are the pair's bytes, NaN and diff --git a/docs/TOOLS.md b/docs/TOOLS.md index 83eefecd..08d11452 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -655,6 +655,16 @@ Declare at the shapes you serve: At `--tp > 1` every rank declares at once, each on its own thread and device, as the engine does: a collective's `init` is a rendezvous, so declaring rank 0 alone at world size 2 hangs. +A collective is then measured as the exchange, not as one rank's copy of it. Each rank gets its own +operands -- drawn with its own seed, so a fold of two identical halves cannot pass a correctness +check -- its own scratch, its own stream, and the instance its own declare made: `init` is what +publishes the peer bundle (scratch, flags, sequence counters) and a launch with no instance is +refused before it starts. The candidate's launches are fired on every rank at once and the clock +stops when the last stream drains, so the reported time is the round trip through the peer, which +is what the served step pays; timing rank 0 alone would time a local copy. Candidates are still +judged against the defaults on rank 0's output. A row that is not collective runs on rank 0 alone, +as it always did. + Before trusting a cache, check that the tuned variants beat the defaults. `RADIANCE_TUNE` pins a kernel's axes for such a comparison; it is a measurement aid, not a deployment setting. @@ -743,7 +753,7 @@ The `--perf*` modes time rows at one shape on a card. Two that cover the dense G | | | |---|---| | `--perf N K M [iters]` | the fp8 decode GEMMs, and the fp8 head (`logits_gemm_fp8`) | -| `--perfmxd N K M [iters]` | the dense OCP-MXFP4 rows (`gemm_mxfp4a8_gemv`, `_decode`, `_nt_m64`, `_tiled`) at one shape, with the weight bandwidth each reaches | +| `--perfmxd N K M [iters]` | the dense OCP-MXFP4 rows (`gemm_mxfp4a8_gemv`, `_decode`, `_nt_m64`, `_tiled`) at one shape, with the weight bandwidth each reaches; at a gate_up shape (N a multiple of 256, K of 128) also `gated_quant_fp8` and the fold that replaces the pair, `gemm_mxfp4a8_gated_gemv` | `--perfmx` is the MXFP4 expert GEMM (`M`, experts, `top_k`, skew), not the dense rows. `--cold MIB` times each launch alone behind a cache flush instead of back to back. diff --git a/libavx/avx_ngram.cpp b/libavx/avx_ngram.cpp index ccb735d4..66e2bb4f 100644 --- a/libavx/avx_ngram.cpp +++ b/libavx/avx_ngram.cpp @@ -40,6 +40,7 @@ #include #include +#include #include #include #include @@ -60,6 +61,16 @@ namespace { +/* Phase timers for one rank's gather, when RAD_PLE_TIMING is set: accumulated on the issuing + * thread and printed by avx::row_gather. The ahead-reader thread accumulates and never prints. */ +struct PleTiming { + bool on = std::getenv("RAD_PLE_TIMING") != nullptr; + double find_ms = 0, pub_ms = 0, read_ms = 0, wait_ms = 0, dec_ms = 0, again_ms = 0; + uint64_t enters = 0, bytes = 0; + size_t spans = 0, hits = 0, claimed = 0, none = 0, theirs = 0; +}; +thread_local PleTiming t_ple; + /* Prefetch distance, in rows, for cache lookups and decodes. Rows are scattered over an 80 MiB * cache and the set words over 4 MiB, so each is an L3 or DRAM miss. */ constexpr long long kPrefetchRows = 8; @@ -281,7 +292,12 @@ const TableFile* table_file(const uint8_t* p, long long n, int* err) { * committed only as slots fill. */ struct RowCache { static constexpr int kWays = 8; - static constexpr uint64_t kRows = 1ull << 19; + /* Slot count, overridable with RAD_PLE_CACHE_ROWS (rows, clamped to [2^16, 2^25]). Data cost + * is `rows` * row bytes (160 at E4M3), so the shipped 2^19 rows is 80 MiB. The table's row + * popularity is Zipfian: a larger cache holds a longer hot head of the distribution and + * trades RAM directly for a lower miss rate on repeated traffic. Size it from measurement, + * not the model -- RAD_PLE_TIMING prints the per-call hit counts the sweep reads. */ + static const uint64_t kRows; enum : uint64_t { EMPTY = 0, LOADING = 1, READY = 2 }; const TableFile* tf = nullptr; @@ -351,6 +367,28 @@ struct RowCache { /* The set changed between the scan and the claim: retry. */ } } + + /* Where `key` sits, without claiming it: READY in *slot (decode from it), LOADING in *slot + * (someone is reading it -- wait on the word), or ABSENT (*slot = -1; nobody has claimed the + * row, so whoever wants it must hand it to a producer or claim it themselves). */ + Found lookup(uint64_t key, int64_t* slot) const { + const uint64_t set = mix(key) & set_mask; + const uint64_t s0 = set * kWays; + for (int w = 0; w < kWays; ++w) { + const uint64_t x = word[s0 + w].load(std::memory_order_acquire); + if (x != EMPTY && (x >> 10) == key) { + *slot = (int64_t)(s0 + w); + return (x & 3) == READY ? HIT : THEIRS; + } + } + *slot = -1; + return NONE; + } + + /* Read batches that failed outright (the ring refused, the disk errored): the consumers + * waiting on those rows re-hand them to a producer, and this counter is how they notice that + * their wait has a cause. */ + std::atomic failed_reads{0}; }; template @@ -361,6 +399,21 @@ T* anon_array(size_t count) { } /* The cache for `n`-byte rows of `tf`, created on first use and kept for the process lifetime. */ +/* Defined out of line so the environment is read once, at first use. */ +const uint64_t RowCache::kRows = [] { + unsigned long long v = 1ull << 19; + if (const char* s = std::getenv("RAD_PLE_CACHE_ROWS")) { + char* end = nullptr; + const long long n = std::strtoll(s, &end, 10); + if (end != s && n > 0) v = (uint64_t)n; + } + if (v < 1ull << 16) v = 1ull << 16; + if (v > 1ull << 25) v = 1ull << 25; + /* Whole sets: the set index is `mix(key) & set_mask` over kWays-way sets. */ + v -= v % kWays; + return v; +}(); + RowCache* row_cache(const TableFile* tf, long long n) { static std::mutex mu; static std::vector> caches; @@ -470,6 +523,16 @@ struct ReadRing { * one span per `stride` bytes, submitting and waiting in one call. Short reads fail. */ int read_spans(const TableFile& tf, const SpanRead* r, unsigned count, long long n, long long stride, uint8_t* bounce) { + if (!t_ple.on) return read_spans_now(tf, r, count, n, stride, bounce); + const auto t0 = std::chrono::steady_clock::now(); + const int s = read_spans_now(tf, r, count, n, stride, bounce); + t_ple.read_ms += + std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + t_ple.spans += count; + return s; + } + int read_spans_now(const TableFile& tf, const SpanRead* r, unsigned count, long long n, + long long stride, uint8_t* bounce) { const long long A = tf.align; unsigned tail = __atomic_load_n(sq_tail, __ATOMIC_RELAXED); for (unsigned i = 0; i < count; ++i) { @@ -486,6 +549,7 @@ struct ReadRing { s->user_data = (uint64_t)(e - a); sq_array[idx] = idx; ++tail; + t_ple.bytes += (uint64_t)(e - a); } __atomic_store_n(sq_tail, tail, __ATOMIC_RELEASE); int status = RAD_OK; @@ -493,6 +557,7 @@ struct ReadRing { while (got < count) { const long rc = syscall(__NR_io_uring_enter, fd, to_submit, count - got, IORING_ENTER_GETEVENTS, nullptr, (size_t)0); + ++t_ple.enters; if (rc < 0 && errno != EINTR && errno != EAGAIN && errno != EBUSY) return RAD_E_IO; if (rc > 0) to_submit -= (unsigned)rc < to_submit ? (unsigned)rc : to_submit; unsigned h = __atomic_load_n(cq_head, __ATOMIC_RELAXED); @@ -569,6 +634,8 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, uint8_t* bounce = g.bounce_for((size_t)cnt * (size_t)stride, (size_t)A); const int rs = bounce ? rr.read_spans(tf, &reads[b], cnt, n, stride, bounce) : RAD_E_NOMEM; if (rs != RAD_OK) { + rc.failed_reads.fetch_add(1, std::memory_order_release); + rc.failed_reads.notify_all(); for (size_t i = b; i < total; ++i) if (reads[i].slot >= 0) rc.word[reads[i].slot].store(RowCache::EMPTY, std::memory_order_release); @@ -589,6 +656,9 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, std::memcpy(rc.data + (size_t)r.slot * (size_t)n, row, (size_t)n); rc.ref[r.slot].store(1, std::memory_order_relaxed); rc.word[r.slot].store(RowCache::ready(r.key), std::memory_order_release); + /* Per-slot wakeup: a consumer waiting on THIS row proceeds now, without waiting for + * the batch or the queue. Notify on a word nobody waits on costs a no-op futex wake. */ + rc.word[r.slot].notify_one(); } rc.published.fetch_add(1, std::memory_order_release); rc.published.notify_all(); @@ -598,11 +668,64 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g, return RAD_OK; } +/* The on-demand regime: decode steps want a hundred-odd rows now. The session's hot rows are + * READY in the cache and decode from it; anything else is read straight from the file into its + * output row -- no claims, no eviction bookkeeping, no queue round trip, no waiting on anybody. + * Misses read here are deliberately not cached: the chunked prefill before decode has already + * cached the prompt's rows, and a decode step's occasional new trigram is not worth a claim. */ +constexpr long long kOnDemandMaxRows = 4096; + +int gather_ondemand(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowGather& q, + avx::RowDecode decode, const uint16_t* lut) { + Gather& g = gather_state(); + const long long M = q.M, n = q.row_bytes, ne = q.n_embd, x_ld = q.x_ld; + const long long base = tf.off + (long long)(q.tab - tf.lo); + auto row_of = [&](long long m) { return (long long)q.ids[m] - q.voff; }; + auto pad = [&](long long id) { return id < 0 || id >= q.n_vocab; }; + auto key_of = [&](long long m) { return (uint64_t)(base + row_of(m) * n); }; + + g.src.clear(); + g.dst.clear(); + g.reads.clear(); + const auto tf0 = std::chrono::steady_clock::now(); + for (long long m = 0; m < M; ++m) { + uint16_t* dst = q.out + m * x_ld; + if (pad(row_of(m))) { std::memset(dst, 0, (size_t)ne * sizeof(uint16_t)); continue; } + const uint64_t key = key_of(m); + int64_t s = -1; + if (rc.lookup(key, &s) == RowCache::HIT) { + g.src.push_back(rc.data + (size_t)s * (size_t)n); + g.dst.push_back(dst); + ++t_ple.hits; + continue; + } + g.reads.push_back({m, key, -1}); /* direct read, no claim */ + ++t_ple.none; + } + t_ple.find_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tf0).count(); + if (!g.reads.empty()) { + const auto tr0 = std::chrono::steady_clock::now(); + const int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + t_ple.pub_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tr0).count(); + if (rs != RAD_OK) return rs; + } + const auto td0 = std::chrono::steady_clock::now(); + if (!g.src.empty()) decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), ne, lut); + t_ple.dec_ms += + std::chrono::duration(std::chrono::steady_clock::now() - td0).count(); + return RAD_OK; +} + /* out[m] = decoded row ids[m] - voff for every m < M, through the cache: find or claim each row * starting at row `first`, read this thread's claims, wait for rows other threads are reading, then * decode from the cache. A row whose slot is taken over during the decode is read again directly. */ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowGather& q, long long first, avx::RowDecode decode, const uint16_t* lut) { + /* Two regimes. A decode step wants a hundred-odd rows now: on-demand, direct, no queue. A + * prefill chunk wants tens of thousands and has a known future: the producer-consumer queue. */ + if (q.M <= kOnDemandMaxRows) return gather_ondemand(tf, rc, rr, q, decode, lut); Gather& g = gather_state(); const uint64_t me = owner_tag(); if (!me) return RAD_E_UNSUPPORTED; @@ -620,6 +743,7 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG g.waits.clear(); g.again.clear(); + const auto tf0 = std::chrono::steady_clock::now(); for (long long j = 0; j < M; ++j) { if (j + kPrefetchRows < M) { const long long mp = at(j + kPrefetchRows); @@ -632,17 +756,27 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG const RowCache::Found f = rc.find_or_claim(key, me, &s); g.slot[m] = s; g.kind[m] = (uint8_t)f; + if (f == RowCache::HIT) ++t_ple.hits; + else if (f == RowCache::CLAIMED) ++t_ple.claimed; + else if (f == RowCache::NONE) ++t_ple.none; + else if (f == RowCache::THEIRS) ++t_ple.theirs; if (f == RowCache::CLAIMED) g.reads.push_back({m, key, s}); else if (f == RowCache::NONE) { g.reads.push_back({m, key, -1}); g.kind[m] = Gather::DONE; } else if (f == RowCache::THEIRS) g.waits.push_back(m); } + t_ple.find_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tf0).count(); + const auto tp0 = std::chrono::steady_clock::now(); int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + t_ple.pub_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tp0).count(); if (rs != RAD_OK) return rs; /* Wait for rows other threads claimed to turn READY. `published` is read before the words, so * a batch landing after the scan makes the wait return at once. Released claims (failed reads) * and reused slots are read by this thread instead. */ + const auto tw0 = std::chrono::steady_clock::now(); while (!g.waits.empty()) { const uint32_t e = rc.published.load(std::memory_order_acquire); size_t keep = 0; @@ -657,9 +791,12 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG g.waits.resize(keep); if (keep) rc.published.wait(e, std::memory_order_acquire); } + t_ple.wait_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tw0).count(); /* Decode all READY rows in one batch: each word is read before the bytes and again after the * batch (the seqlock), and rows whose word changed are read again. */ + const auto td0 = std::chrono::steady_clock::now(); g.src.clear(); g.dst.clear(); g.dm.clear(); @@ -682,22 +819,35 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG for (size_t i = 0; i < g.dm.size(); ++i) if (rc.word[g.slot[g.dm[i]]].load(std::memory_order_relaxed) != g.dw[i]) g.again.push_back(g.dm[i]); + t_ple.dec_ms += + std::chrono::duration(std::chrono::steady_clock::now() - td0).count(); if (g.again.empty()) return RAD_OK; + const auto ta0 = std::chrono::steady_clock::now(); g.reads.clear(); for (long long m : g.again) g.reads.push_back({m, key_of(m), -1}); - return read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + const int ra = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + t_ple.again_ms += + std::chrono::duration(std::chrono::steady_clock::now() - ta0).count(); + return ra; } /* ============================== the reader that runs a step ahead ============================== * * A prefill chunk gathers `heads` rows per token (32,768 for a 2048-token chunk); on unseen text * most are file reads (~30 ms per chunk on NVMe), during which the issuing thread waits and the card - * idles. The next chunk's ids are known a step early (RadBatch::n_ahead, ngram_ids' `ahead_ids`), so + * idles. The next chunks' ids are known a step early (RadBatch::n_ahead, ngram_ids' `ahead_ids`), so * the call hands them to one process-wide reader thread, which claims, reads and publishes the * missing rows while the chunk runs. The next call waits for LOADING rows as it would for the other * rank's. * + * The queue is handed over sliced: each job carries at most `kJobRows` keys, claimed and published + * one job at a time, in order. Claims are promises the consumer waits on (a slot LOADING for a row + * it needs blocks the gather on the reader's progress), so a job must stay small: bounded claims + * keep the promise horizon near, and a consumer that outruns the reader finds unclaimed rows it + * can read itself instead of waiting behind the whole queue. Jobs keep the list's order, so the + * nearest chunk's rows are always the reader's first work. + * * Both ranks hand over the same ids; a repeated list is dropped. A failed read releases its claims * and the next call reads those rows itself. The reader is detached and never destroyed. */ struct AheadJob { @@ -707,10 +857,15 @@ struct AheadJob { std::vector keys; }; +/* One producer job's claim-read-publish sweep: ~2 ring batches, so the promise a job makes to a + * consuming gather is paid in well under a second on any disk that can stream the table. */ +constexpr size_t kJobRows = 8192; + struct AheadReader { std::mutex mu; std::condition_variable cv; - std::deque q; + std::deque urgent; /* a waiting consumer's own misses: served first */ + std::deque q; /* the run-ahead queue: future chunks, in order */ uint64_t last = 0; /* hash of the last id list accepted */ void run() { @@ -721,22 +876,43 @@ struct AheadReader { AheadJob j; { std::unique_lock lk(mu); - cv.wait(lk, [&] { return !q.empty(); }); - j = std::move(q.front()); - q.pop_front(); + cv.wait(lk, [&] { return !urgent.empty() || !q.empty(); }); + if (!urgent.empty()) { j = std::move(urgent.front()); urgent.pop_front(); } + else { j = std::move(q.front()); q.pop_front(); } } if (!rr || !me) continue; + const auto t0 = t_ple.on ? std::chrono::steady_clock::now() + : std::chrono::steady_clock::time_point(); g.reads.clear(); + std::vector retry; /* sets full of LOADING: claim again after a wave */ for (size_t i = 0; i < j.keys.size(); ++i) { if (i + kPrefetchRows < j.keys.size()) __builtin_prefetch(j.rc->set_line(j.keys[i + kPrefetchRows])); int64_t slot = -1; - if (j.rc->find_or_claim(j.keys[i], me, &slot) == RowCache::CLAIMED) + const auto f = j.rc->find_or_claim(j.keys[i], me, &slot); + if (f == RowCache::CLAIMED) g.reads.push_back({0, j.keys[i], slot}); + else if (f == RowCache::NONE) + retry.push_back(j.keys[i]); + /* READY/HIT: already there (a rank's gather, or an earlier pass). MINE: ours + * from an earlier pass -- published when its read lands. */ } /* Every read has a slot, so nothing is decoded and there is no output. */ (void)read_and_publish(*j.tf, *j.rc, *rr, g, g.reads, j.n, 0, nullptr, nullptr, nullptr, 0); + if (!retry.empty()) { + std::lock_guard lk(mu); + AheadJob r; + r.tf = j.tf; r.rc = j.rc; r.n = j.n; r.keys = std::move(retry); + urgent.push_front(std::move(r)); + cv.notify_one(); + } + if (t_ple.on) { + const double ms = std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(); + std::fprintf(stderr, "ple[reader] keys %zu reads %zu %.1fms\n", j.keys.size(), + g.reads.size(), ms); + } } } }; @@ -750,7 +926,9 @@ AheadReader* ahead_reader() { return r; } -/* Hands the rows of `q.ahead` (to be gathered by a later call) to the reader. */ +/* Hands the rows of `q.ahead` (to be gathered by later calls) to the reader, sliced into + * `kJobRows`-key jobs in list order: the reader claims, reads and publishes one job at a time, so + * the nearest chunk's rows are its first work and a claim's promise horizon stays short. */ void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) { uint64_t h = 1469598103934665603ull ^ (uint64_t)(uintptr_t)&rc; for (long long m = 0; m < q.n_ahead; ++m) { h ^= (uint32_t)q.ahead[m]; h *= 1099511628211ull; } @@ -760,17 +938,26 @@ void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) { if (h == r->last) return; r->last = h; } + const long long base = tf.off + (long long)(q.tab - tf.lo); AheadJob j; j.tf = &tf; j.rc = &rc; j.n = q.row_bytes; - const long long base = tf.off + (long long)(q.tab - tf.lo); - j.keys.reserve((size_t)q.n_ahead); + j.keys.reserve(kJobRows); for (long long m = 0; m < q.n_ahead; ++m) { const long long id = (long long)q.ahead[m] - q.voff; - if (id >= 0 && id < q.n_vocab) j.keys.push_back((uint64_t)(base + id * q.row_bytes)); + if (id < 0 || id >= q.n_vocab) continue; + j.keys.push_back((uint64_t)(base + id * q.row_bytes)); + if (j.keys.size() == kJobRows) { + { + std::lock_guard lk(r->mu); + r->q.push_back(j); + } + r->cv.notify_one(); + j.keys.clear(); + } } - { + if (!j.keys.empty()) { std::lock_guard lk(r->mu); r->q.push_back(std::move(j)); } @@ -806,6 +993,7 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { if (!tfile) return ferr; #if defined(__linux__) if (tfile->fd >= 0) { + const auto t0 = std::chrono::steady_clock::now(); int why = 0; ReadRing* rr = read_ring(&why); if (!rr) { @@ -819,6 +1007,18 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { const long long first = q.rank > 0 && q.rank < ws ? q.M * q.rank / ws : 0; const int rs = gather_rows(*tfile, *rc, *rr, q, first, decode, lut); if (rs != RAD_OK) return rs; + const double wall = + std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (t_ple.on) + std::fprintf(stderr, + "ple[rank %lld] rows %lld: find %.1fms (hit %zu claimed %zu none %zu " + "theirs %zu) pub %.1fms (ring %.1fms, %llu enters, %zu spans, " + "%.1f MiB) wait %.1fms dec %.1fms again %.1fms | wall %.1fms\n", + (long long)q.rank, (long long)q.M, t_ple.find_ms, t_ple.hits, + t_ple.claimed, t_ple.none, t_ple.theirs, t_ple.pub_ms, t_ple.read_ms, + (unsigned long long)t_ple.enters, t_ple.spans, t_ple.bytes / 1048576.0, + t_ple.wait_ms, t_ple.dec_ms, t_ple.again_ms, wall); + t_ple = {}; /* Queue the rows a later call will gather, after this call's own rows. */ if (q.ahead && q.n_ahead > 0) read_ahead(*tfile, *rc, q); return RAD_OK; diff --git a/libr4d/README.md b/libr4d/README.md index 27a2ff9a..f3e7598b 100644 --- a/libr4d/README.md +++ b/libr4d/README.md @@ -54,6 +54,7 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set. | `gemm_mxfp4a8_nt_m64` | OCP-MXFP4 weight, fp8 activation, skinny | | `gemm_mxfp4a8_gemv` | the same operands for one to eight rows: the weight streamed straight to registers, no LDS staging; WMMA when K is a multiple of 128, `v_dot4` otherwise, chosen from K alone so a row's bits do not depend on M | | `gemm_mxfp4a8_gemv_wide` | its WMMA form at 9..64 rows: up to four 16-row tiles a wave over each weight word, two 16-column tiles a block on wide, deep weights | +| `gemm_mxfp4a8_gated_gemv` | `gemm_nt_q_gated_mx`: the gemv WMMA form over a gate_up weight with `gated_quant_fp8`'s pass (or GeGLU's `gelu_mul` and `quant_act_fp8`) in its epilogue, M ≤ 8; the [M, 2n] product is never written | | `gemm_mxfp4a8_decode` | the same operands for the decode band (M ≤ 128): split-K across workgroups with a last-arriver reduction, the partial in the op's scratch | | `gemm_mxfp4a8_decode_shortk` | the decode kernel at 33..64 rows of a wide, short weight (N ≥ 8192, K ≤ 2560), above `gemm_mxfp4a8_gemv_wide`, which loses there | | `gemm_mxfp4a8_tiled` | the prefill sibling: the activation re-tiled into fragment order in the op's scratch and read straight into registers, the weight unpacked once per K slab for a 256-row block | @@ -197,8 +198,21 @@ rows their outputs differ from the decode row's in the last bf16 place on a few thousand (within the selftest's bound). A greedy text can therefore differ from one produced with the decode row at those rows. Within the family a row's bits do not depend on M, as above. -**Tunables.** `gemv` and `gemv_wide` 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 +**`gemm_mxfp4a8_gated_gemv`** (`gemm_nt_q_gated_mx`, M ≤ 8, K a multiple of 128, N of 256, `act` +`silu`, or `gelu_tanh` without `out_bf16`). The `gemv` WMMA form over a gate_up weight, a block per +16-column tile pair of the gated output (eight K waves on the gate tile, eight on the up tile, in +`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 %. + +**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. diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 17458f71..6faed029 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -343,10 +343,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE; if (host) { sc = r4d_ar_host_alloc((long)nslots * in->slot_bytes); - fl = r4d_ar_host_alloc(flag_words * 4); + fl = r4d_ar_host_alloc((flag_words + 2L * maxb) * 4); } else { sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen); - fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen); + fl = r4d_ar_ipc_alloc((flag_words + 2L * maxb) * 4, 1, handle, &hlen); } sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen)); diff --git a/libr4d/r4d_ar_gather_2rank.hip b/libr4d/r4d_ar_gather_2rank.hip index fdbacfd3..d6fb113f 100644 --- a/libr4d/r4d_ar_gather_2rank.hip +++ b/libr4d/r4d_ar_gather_2rank.hip @@ -72,6 +72,7 @@ __global__ void r4d_ar_gather_2rank_kernel( const int w = (n16 + nb - 1) / nb; const int start = b * w; int end = start + w; if (end > n16) end = n16; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) // Push the chunk to the peer slot and place this rank's own slice (a local store, no handshake) // while the push is in flight. @@ -82,6 +83,8 @@ __global__ void r4d_ar_gather_2rank_kernel( v2 = in4[r4d_g_src(k + 2 * nt, row16, n16, sp16)], v3 = in4[r4d_g_src(k + 3 * nt, row16, n16, sp16)]; ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3; + hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + nt)) + + r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * nt)); out4[r4d_g_dst(k, row16, n16, rank, dp16)] = v0; out4[r4d_g_dst(k + nt, row16, n16, rank, dp16)] = v1; out4[r4d_g_dst(k + 2 * nt, row16, n16, rank, dp16)] = v2; @@ -90,11 +93,13 @@ __global__ void r4d_ar_gather_2rank_kernel( for (; k < end; k += nt) { int4 v = in4[r4d_g_src(k, row16, n16, sp16)]; ps[k] = v; + hck += r4d_archk_u4(v, 4u * (unsigned)k); out4[r4d_g_dst(k, row16, n16, rank, dp16)] = v; } } // Drain modes, as in the all-reduce: order the pushes before the release flag so the peer cannot // see the flag before the data. + r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -110,6 +115,9 @@ __global__ void r4d_ar_gather_2rank_kernel( } __syncthreads(); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { + for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + }); // Place the peer's slice, now staged in this rank's scratch. { @@ -165,6 +173,7 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo int nt = (int)nthreads; if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; + nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes r4d_ar_gather_2rank_kernel<<>>( (const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, diff --git a/libr4d/r4d_ar_ln_had_quant_i8.hip b/libr4d/r4d_ar_ln_had_quant_i8.hip index 98d548ba..ccf5c776 100644 --- a/libr4d/r4d_ar_ln_had_quant_i8.hip +++ b/libr4d/r4d_ar_ln_had_quant_i8.hip @@ -163,6 +163,7 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( float* Lsc = (float*)(Lpk + (size_t)cpb * ARN_WV * ARN_NWORD); const int lig = lane & (ARN_LPG - 1), gw = lane / ARN_LPG; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) if constexpr (WIRE == 0) { // Push my rows to the peer slot. A row is K/8 16B words and rows are contiguous, so a row // range is a word range. @@ -173,8 +174,10 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( for (; k + 3 * THR < wend; k += 4 * THR) { int4 v0 = in4[k], v1 = in4[k + THR], v2 = in4[k + 2 * THR], v3 = in4[k + 3 * THR]; ps[k] = v0; ps[k + THR] = v1; ps[k + 2 * THR] = v2; ps[k + 3 * THR] = v3; + hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + THR)) + + r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * THR)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * THR)); } - for (; k < wend; k += THR) ps[k] = in4[k]; + for (; k < wend; k += THR) { const int4 v = in4[k]; ps[k] = v; hck += r4d_archk_u4(v, 4u * (unsigned)k); } } else { // Rotate, amax, quantise and pack straight into the peer's slot, keeping the same words in // LDS. A wave owns whole chunks, so every lane emits exactly ARN_NWORD dwords per chunk and the @@ -201,8 +204,10 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( float scl = (a > 0.f) ? arn_bf16_round(a * (1.0f / (float)ARN_QMAX)) : 1.0f; if (!(scl > 0.f)) scl = 1.0f; if (lig == 0) { - p_sc[c * ARN_CG + gl] = (unsigned short)(__float_as_uint(scl) >> 16); + const unsigned short sc16 = (unsigned short)(__float_as_uint(scl) >> 16); + p_sc[c * ARN_CG + gl] = sc16; Lsc[(size_t)ci * ARN_CG + gl] = scl; + hck += r4d_archk_mix(sc16, R4D_ARCHK_U16 + (unsigned)(c * ARN_CG + gl)); } const float inv = 1.0f / scl; #pragma unroll @@ -217,20 +222,30 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( // Flush lane-contiguously region by region, widest first, so each region is one coalesced // store of ARN_WV x width bytes (ARN_NWORD is 3). char* pb = p_pay + (size_t)c * ARN_CBYTES; + const unsigned int cd = (unsigned)c * (ARN_CBYTES / 4); // the chunk's first dword #pragma unroll - for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) + for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) { *(uint4*)(pb + w4 * 4 * ARN_WV + lane * 16) = make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]); - if constexpr (ARN_NWORD % 4 >= 2) + hck += r4d_archk_u4(make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]), + cd + (unsigned)(w4 * ARN_WV + lane * 4)); + } + if constexpr (ARN_NWORD % 4 >= 2) { *(uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8) = make_uint2(acc[ARN_NWORD & ~3], acc[(ARN_NWORD & ~3) + 1]); - if constexpr (ARN_NWORD % 2 == 1) + const unsigned int e = cd + (unsigned)((ARN_NWORD & ~3) * ARN_WV + lane * 2); + hck += r4d_archk_mix(acc[ARN_NWORD & ~3], e) + r4d_archk_mix(acc[(ARN_NWORD & ~3) + 1], e + 1u); + } + if constexpr (ARN_NWORD % 2 == 1) { *(unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4) = acc[ARN_NWORD - 1]; + hck += r4d_archk_mix(acc[ARN_NWORD - 1], cd + (unsigned)((ARN_NWORD - 1) * ARN_WV + lane)); + } #pragma unroll for (int w = 0; w < ARN_NWORD; ++w) Lpk[((size_t)ci * ARN_NWORD + w) * ARN_WV + lane] = acc[w]; } } + r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, sq); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -245,6 +260,35 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( } __syncthreads(); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) { + if constexpr (WIRE == 0) { + const int wpr = K >> 3; + for (int k = r0 * wpr + tid; k < r1 * wpr; k += THR) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + } else { + for (int ci = wave; ci < cpb; ci += NW) { + const int c = c00 + ci; + const char* pb = m_pay + (size_t)c * ARN_CBYTES; + const unsigned int cd = (unsigned)c * (ARN_CBYTES / 4); +#pragma unroll + for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) + h += r4d_archk_u4(*(const uint4*)(pb + w4 * 4 * ARN_WV + lane * 16), + cd + (unsigned)(w4 * ARN_WV + lane * 4)); + if constexpr (ARN_NWORD % 4 >= 2) { + const uint2 u = *(const uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8); + const unsigned int e = cd + (unsigned)((ARN_NWORD & ~3) * ARN_WV + lane * 2); + h += r4d_archk_mix(u.x, e) + r4d_archk_mix(u.y, e + 1u); + } + if constexpr (ARN_NWORD % 2 == 1) + h += r4d_archk_mix(*(const unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4), + cd + (unsigned)((ARN_NWORD - 1) * ARN_WV + lane)); +#pragma unroll + for (int t = 0; t < ARN_ITERS; ++t) { + const int gl = t * ARN_GPW + gw; + if (lig == 0) h += r4d_archk_mix(m_sc[c * ARN_CG + gl], R4D_ARCHK_U16 + (unsigned)(c * ARN_CG + gl)); + } + } + } + }); // The peer's rows are now in my scratch, in the same [M, K] layout as X. const __hip_bfloat16* P = (const __hip_bfloat16*)ms; @@ -404,9 +448,10 @@ static size_t ar_ln_lds_bytes(int rows_max, int K, int thr, int wire) { } return b; } -// Dynamic LDS ceiling: a workgroup's 64 KiB less the kernel's static words (seq and slot), which -// the runtime places in front of it. -static constexpr size_t kArnLdsCap = 65536 - 16; +// Dynamic LDS ceiling: a workgroup's 64 KiB less the kernel's static words, which the runtime places +// in front of it: seq and slot, and the push check's (r4d_ar_seq.h: two 32-word sums and a flag, +// 260 bytes), rounded up. +static constexpr size_t kArnLdsCap = 65536 - 16 - 512; // Fewest blocks at which this shape fits: each block owns ceil(M / nb) rows, and on the compressed // wire each row costs a staging slice and its chunks' packed half. -1 when no block count fits (a diff --git a/libr4d/r4d_ar_oneshot_2rank_exact.hip b/libr4d/r4d_ar_oneshot_2rank_exact.hip index 37bbd373..773389b8 100644 --- a/libr4d/r4d_ar_oneshot_2rank_exact.hip +++ b/libr4d/r4d_ar_oneshot_2rank_exact.hip @@ -18,6 +18,7 @@ // * 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 #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 @@ -76,15 +77,26 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( const int w = (n16 + nb - 1) / nb; // 16B words per block const int start = b * w; 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 + // 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) { + if (tid == 0) store_sys_rel(&peer_flags[b], s); + const unsigned long long t0 = wall_clock64(); + while (wall_clock64() - t0 < 2000ull) __builtin_amdgcn_s_sleep(8); // 100 MHz: 20 us + } // Push the chunk to the peer slot, 4x unrolled for memory-level parallelism. { int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { int4 v0 = in4[k], v1 = in4[k + nt], v2 = in4[k + 2 * nt], v3 = in4[k + 3 * nt]; ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3; + hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + nt)) + + r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * nt)); } - for (; k < end; k += nt) ps[k] = in4[k]; + for (; k < end; k += nt) { const int4 v = in4[k]; ps[k] = v; hck += r4d_archk_u4(v, 4u * (unsigned)k); } } // Drain modes, ordering the pushes before the release flag so the peer sees data first: // 0 = none (relies on PCIe posted-write ordering and the release flag) @@ -94,12 +106,13 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( // 3 = all-thread s_wait_storecnt 0: every wave drains its posted writes with no L2 // writeback-invalidate; PCIe keeps posted writes to one peer ordered, so the release flag // lands after the data. Correct only for fine-grained memory (coarse leaves data in L2). + r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s, drain == 4); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); if (tid == 0) { if (drain == 2) __threadfence_system(); - store_sys_rel(&peer_flags[b], s); + if (drain != 4) store_sys_rel(&peer_flags[b], s); unsigned long long z = 0; // A handshake that cannot complete is a lockstep violation; trap rather than sum stale bytes. while (r4d_ar_seq_behind(load_sys_acq(&my_flags[b]), s)) { @@ -108,6 +121,9 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( } __syncthreads(); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { + for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + }); // Reduce the chunk, 4x unrolled: out = local input + peer input (staged in local scratch). { int k = start + tid; @@ -147,15 +163,19 @@ __global__ void r4d_ar_hc_write_kernel( const int w = (n16 + nb - 1) / nb; // 16B words per block const int start = b * w; int end = start + w; if (end > n16) end = n16; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) { int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { int4 v0 = y4[k], v1 = y4[k + nt], v2 = y4[k + 2 * nt], v3 = y4[k + 3 * nt]; ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3; + hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + nt)) + + r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * nt)); } - for (; k < end; k += nt) ps[k] = y4[k]; + for (; k < end; k += nt) { const int4 v = y4[k]; ps[k] = v; hck += r4d_archk_u4(v, 4u * (unsigned)k); } } + r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -168,8 +188,11 @@ __global__ void r4d_ar_hc_write_kernel( } } __syncthreads(); - r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { + for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + }); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); const int wpr = n >> 3; // 16B words a row for (int k = start + tid; k < end; k += nt) { @@ -231,6 +254,7 @@ __global__ void r4d_ar_gather_hc_write_kernel( const int w = (n16 + nb - 1) / nb; // 16B words per block const int start = b * w; int end = start + w; if (end > n16) end = n16; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) const int wpr = n >> 3; // 16B words a row const int row_lo = start / wpr; const int nrow = end > start ? (end - 1) / wpr - row_lo + 1 : 0; @@ -264,7 +288,9 @@ __global__ void r4d_ar_gather_hc_write_kernel( const int4 out = r4d_ar_gather_word(G, inv, s_i, s_w, s_g, row, row - row_lo, i0); y4[k] = out; ps[k] = out; + hck += r4d_archk_u4(out, 4u * (unsigned)k); } + r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -277,8 +303,11 @@ __global__ void r4d_ar_gather_hc_write_kernel( } } __syncthreads(); - r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { + for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + }); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); for (int k = start + tid; k < end; k += nt) { const int4 r = vadd<__hip_bfloat16, 8>(y4[k], ms[k]); @@ -398,6 +427,7 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m int nt = (int)nthreads; if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; + nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes r4d_ar_hc_write_kernel<<>>( (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, @@ -436,6 +466,7 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, int nt = (int)nthreads; if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; + nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes /* Zeroed including padding: the struct is passed by value, so its tail padding is part of the * kernel-argument bytes a recorded pass's audit compares. */ R4dArGather G; @@ -527,6 +558,10 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl int nt = (int)nthreads; if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; + 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; #define L(T, LN) r4d_ar_oneshot_2rank_exact_kernel<<>>( \ (const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, \ (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, \ diff --git a/libr4d/r4d_ar_oneshot_2rank_wht6.h b/libr4d/r4d_ar_oneshot_2rank_wht6.h index 576747dc..0a2844cc 100644 --- a/libr4d/r4d_ar_oneshot_2rank_wht6.h +++ b/libr4d/r4d_ar_oneshot_2rank_wht6.h @@ -129,7 +129,8 @@ struct Wht6Chunk { template __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_groups, int lane, int lig, int gw, uint4* p_pay, - unsigned short* p_sc, uint4* l_pay, float* l_sc) { + unsigned short* p_sc, uint4* l_pay, float* l_sc, + unsigned int& hck) { using Ch = Wht6Chunk; const int qmin = -(1 << (BITS - 1)), qmax = (1 << (BITS - 1)) - 1; unsigned int acc[Ch::NW]; @@ -157,8 +158,10 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group float sc = (a > 0.f) ? bf16_round(a * (1.0f / (float)qmax)) : 1.0f; if (!(sc > 0.f)) sc = 1.0f; if (lig == 0 && live) { - p_sc[g] = (unsigned short)(__float_as_uint(sc) >> 16); + const unsigned short sc16 = (unsigned short)(__float_as_uint(sc) >> 16); + p_sc[g] = sc16; l_sc[g] = sc; + hck += r4d_archk_mix(sc16, R4D_ARCHK_U16 + (unsigned)g); } const float inv = 1.0f / sc; #pragma unroll @@ -177,6 +180,7 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane; p_pay[o] = q; l_pay[o] = q; + hck += r4d_archk_u4(q, 4u * (unsigned)o); } } else { unsigned int* pp = reinterpret_cast(p_pay); @@ -186,6 +190,7 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane; pp[o] = acc[u]; lp[o] = acc[u]; + hck += r4d_archk_mix(acc[u], (unsigned)o); } } } @@ -209,6 +214,34 @@ __device__ __forceinline__ void wht6_handshake(unsigned int* peer_flags, unsigne if (acq) __threadfence_system(); } +// The push check's re-hash of one chunk (r4d_ar_seq.h): the payload words and live scales the +// reduce below reads, at the indices wht6_push_chunk hashed them. +template +__device__ __forceinline__ void wht6_rehash_chunk(unsigned int& h, int c, int n_groups, int lane, + int lig, int gw, const uint4* m_pay, + const unsigned short* m_sc) { + using Ch = Wht6Chunk; + if constexpr (Ch::U4) { +#pragma unroll + for (int u = 0; u < Ch::NW / 4; ++u) { + const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane; + h += r4d_archk_u4(m_pay[o], 4u * (unsigned)o); + } + } else { + const unsigned int* mp = reinterpret_cast(m_pay); +#pragma unroll + for (int u = 0; u < Ch::NW; ++u) { + const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane; + h += r4d_archk_mix(mp[o], (unsigned)o); + } + } +#pragma unroll + for (int t = 0; t < Ch::ITERS; ++t) { + const int g = c * CG + t * GPW + gw; + if (lig == 0 && g < n_groups) h += r4d_archk_mix(m_sc[g], R4D_ARCHK_U16 + (unsigned)g); + } +} + // Reduce: unpack both halves, add in fp32, inverse-rotate, pass each live group's EPL elements to st. template __device__ __forceinline__ void wht6_reduce_chunk(const St& st, int c, int n_groups, int lane, @@ -300,10 +333,16 @@ __global__ void r4d_ar_oneshot_2rank_wht6_kernel( #pragma unroll for (int i = 0; i < EPL; ++i) v[i] = rd_to_f(in[off + i]); }; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) for (int c = c0 + wid; c < c1; c += nwarp) - wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc); + wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc, hck); + r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, s); wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq); + r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) { + for (int c = c0 + wid; c < c1; c += nwarp) + wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc); + }); const auto st = [&](long off, const float* v) { #pragma unroll diff --git a/libr4d/r4d_ar_oneshot_2rank_wht6.hip b/libr4d/r4d_ar_oneshot_2rank_wht6.hip index 67a2575a..0047c121 100644 --- a/libr4d/r4d_ar_oneshot_2rank_wht6.hip +++ b/libr4d/r4d_ar_oneshot_2rank_wht6.hip @@ -139,10 +139,16 @@ __global__ void r4d_ar_hc_write_wht6_kernel( r4d_ar_hc_write_word(inj, h, row, i0, n, hc, irow, hrow, reinterpret_cast(&q)); }; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) for (int c = c0 + wid; c < c1; c += nwarp) - wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc); + wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc, hck); + r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, s); wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq); + r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) { + for (int c = c0 + wid; c < c1; c += nwarp) + wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc); + }); r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); for (int c = c0 + wid; c < c1; c += nwarp) diff --git a/libr4d/r4d_ar_seq.h b/libr4d/r4d_ar_seq.h index e9ae425c..2ce45081 100644 --- a/libr4d/r4d_ar_seq.h +++ b/libr4d/r4d_ar_seq.h @@ -87,3 +87,114 @@ __device__ __forceinline__ void r4d_ar_link_landed(long long* gate, long long wo __device__ __forceinline__ bool r4d_ar_seq_behind(unsigned int flag, unsigned int want) { return (int)(flag - want) < 0; } + +// ---- The push check. A peer's push over PCIe P2P can land after its release flag (measured on 2x +// 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. +#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 +#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, +// so a sum of terms changes when any value does. A linear mix is not enough: (v ^ c_e) summed over +// a run of indices can lose v entirely, and a message of one repeated value (a test pattern, a +// zero-filled row) would then pass whatever the slot held. +__device__ __forceinline__ unsigned int r4d_archk_mix(unsigned int v, unsigned int e) { + unsigned int x = v ^ (e * 0x9E3779B9u); + x ^= x >> 16; x *= 0x85EBCA6Bu; + x ^= x >> 13; x *= 0xC2B2AE35u; + x ^= x >> 16; + return x; +} +// A 16B word at dword index `e`. +__device__ __forceinline__ unsigned int r4d_archk_u4(int4 v, unsigned int e) { + return r4d_archk_mix((unsigned int)v.x, e) + r4d_archk_mix((unsigned int)v.y, e + 1u) + + r4d_archk_mix((unsigned int)v.z, e + 2u) + r4d_archk_mix((unsigned int)v.w, e + 3u); +} +__device__ __forceinline__ unsigned int r4d_archk_u4(uint4 v, unsigned int e) { + return r4d_archk_mix(v.x, e) + r4d_archk_mix(v.y, e + 1u) + r4d_archk_mix(v.z, e + 2u) + + r4d_archk_mix(v.w, e + 3u); +} +// The check word of (slot, block) in a flags allocation: two parity slots of nbw words after the +// nbw flags. +__device__ __forceinline__ unsigned int* r4d_archk_word(unsigned int* flags, unsigned int nbw, + unsigned int slot, unsigned int b) { + return flags + nbw + slot * nbw + b; +} +__device__ __forceinline__ unsigned int r4d_archk_wave_sum(unsigned int h) { + for (int o = 16; o > 0; o >>= 1) h += __shfl_xor(h, o, 32); + return h; +} + +// Writer: every thread of the block calls this after its pushes, before the handshake's barrier. +// Thread 0 stores the block's sum into the peer's check word. +__device__ __forceinline__ void r4d_archk_put(unsigned int h, unsigned int* peer_flags, + unsigned int nbw, unsigned int slot, + unsigned int b, unsigned int seq, + bool release = false) { + __shared__ unsigned int s_ckp[32]; + const unsigned int tid = threadIdx.x, nt = blockDim.x; + h = r4d_archk_wave_sum(h); + if ((tid & 31u) == 0u) s_ckp[tid >> 5] = h; + __syncthreads(); + if (tid == 0) { + unsigned int t = 0u; + for (unsigned int w = 0; w < (nt + 31u) / 32u; ++w) t += s_ckp[w]; + /* The pushed bytes sit in this card's L2 until a system-scope release writes them back. The + * flag's release, right after this, does that, so the word itself can be relaxed (the reader + * re-reads until the bytes agree with it). Where the flag went out before the push (the test + * mode, drain 4) nothing else would write them back before the kernel ends: a release. */ + unsigned int* const cw = r4d_archk_word(peer_flags, nbw, slot, b); + if (release) + __hip_atomic_store(cw, t + seq * R4D_ARCHK_SALT, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM); + else + __hip_atomic_store(cw, t + seq * R4D_ARCHK_SALT, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); + } +} + +// Reader: every thread of the block calls this after the handshake; `rehash(h)` adds the thread's +// share of the bytes the block is about to read, with the same loads the kernel then makes. +template +__device__ __forceinline__ void r4d_archk_wait(unsigned int* my_flags, unsigned int nbw, + unsigned int slot, unsigned int b, + unsigned int seq, const F& rehash) { + __shared__ unsigned int s_ckw[32]; + __shared__ unsigned int s_ckok; + const unsigned int tid = threadIdx.x, nt = blockDim.x; + const unsigned long long t0 = tid == 0 ? wall_clock64() : 0ull; + for (;;) { + /* The check word first, so its round trip overlaps the re-hash's loads. Read before the bytes + * it is compared with, it can only be older than them, and an older word just fails this try. */ + const unsigned int want = tid == 0 ? __hip_atomic_load(r4d_archk_word(my_flags, nbw, slot, b), + __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM) + : 0u; + unsigned int h = 0u; + rehash(h); + h = r4d_archk_wave_sum(h); + if ((tid & 31u) == 0u) s_ckw[tid >> 5] = h; + __syncthreads(); + if (tid == 0) { + unsigned int t = 0u; + for (unsigned int w = 0; w < (nt + 31u) / 32u; ++w) t += s_ckw[w]; + const bool ok = t + seq * R4D_ARCHK_SALT == want; + if (!ok && wall_clock64() - t0 > R4D_ARCHK_DEADLINE) __builtin_trap(); + s_ckok = ok ? 1u : 0u; + } + __syncthreads(); + if (s_ckok) return; + __syncthreads(); // s_ckw and s_ckok are rewritten by the next try + /* Drop the vector caches, so the next try reads the bytes from where the push lands. */ + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, ""); + __builtin_amdgcn_s_sleep(2); + } +} diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index 90851dc5..3371b952 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -132,13 +132,25 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) constexpr float PGROW = D::GROW; __shared__ uint16_t sK[KLDS ? TILE * KSTR : 1]; - __shared__ uint16_t sV16[V8 ? 1 : HEAD_DIM * VSTR]; + // V4 at TILE 16: dim octet o's 8 rows start S(o) = 16 (o & 3) + 8 ((o >> 2) & 1) + 128 (o >> 2) + // halfwords later, so the 4 (8) octets of a storeV4 store land on distinct banks (unskewed they + // share them: 8 rows = 96 dwords = 0 mod 32). The 128 (o >> 2) term (64 dwords, unseen by the + // banks) keeps octet o's last row clear of octet o + 1's first; multiples of 8 halfwords keep the + // b128 PV read aligned. NWARPS 1 keeps the plain tile: its 10 workgroups a WGP would not fit. + constexpr int VSK = (V4 && TILE == 16 && CTG && NWARPS >= 2) ? 1 : 0; + constexpr int VSKN = HEAD_DIM / 8 - 1; + constexpr int VSKX = VSK ? 16 * (VSKN & 3) + 8 * ((VSKN >> 2) & 1) + 128 * (VSKN >> 2) : 0; + __shared__ uint16_t sV16[V8 ? 1 : HEAD_DIM * VSTR + VSKX]; /* A code-tile row is 16 keys + 8 padding = 24 bytes (six dwords): the sixteen lanes of a * fragment read hit distinct banks, and a lane's eight codes are one aligned 8-byte load. */ constexpr int VSTR8 = TILE + 8; __shared__ uint8_t sV8[V8 ? HEAD_DIM * VSTR8 : 1]; const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + // The launch is NTHR threads. Stated (k6_v4), so the V4 rounds wholly below NP4 lose their range + // test: as exec-masked blocks, each round's loads issued only after the previous round's returned. + // fp8_v4 keeps the tested rounds: batched there, its 4-row steps ran 6 % slower. + if constexpr (K6) __builtin_assume(tid < NTHR); const int c = lane & 15, h = lane >> 4; const int sp = blockIdx.x, kvh = blockIdx.y, seq = blockIdx.z; @@ -219,12 +231,19 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) // scale, widened with packed f16 into one dword a dim), fetched in the tile: no prefetch. 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 fetch is waited on + // right after it is issued. fp8_v4 packs here as before, as the prefill kernel keeps it. + constexpr int OLDV4 = V4 && !K6; + uint32_t v4c[U4][2], v4s[U4][2]; auto fetchV4 = [&](int k0, const int* blks) { #pragma unroll for (int r = 0; r < U4; ++r) { const int u = tid + r * NTHR; - if (NP4 % NTHR == 0 || u < NP4) { + // k6_v4, a partial round (NWARPS 3: the third, warps 0-1): u < NP4 <=> warp < (NP4 - r NTHR) + // / 32 when NP4 is a multiple of 32, tested on the wave-uniform warp: a scalar branch. + if (NP4 % NTHR == 0 || (K6 ? ((r + 1) * NTHR <= NP4 + || (NP4 % 32 == 0 ? __builtin_amdgcn_readfirstlane(warp) * 32 < NP4 - r * NTHR + : u < NP4)) : u < NP4)) { const int kp = u % (TILE / 2), o = u / (TILE / 2); uint32_t sc[2]; #pragma unroll @@ -237,7 +256,8 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) 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]; } } } }; @@ -246,16 +266,21 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) #pragma unroll for (int r = 0; r < U4; ++r) { const int u = tid + r * NTHR; - if (NP4 % NTHR == 0 || u < NP4) { + // k6_v4, a partial round (NWARPS 3: the third, warps 0-1): u < NP4 <=> warp < (NP4 - r NTHR) + // / 32 when NP4 is a multiple of 32, tested on the wave-uniform warp: a scalar branch. + if (NP4 % NTHR == 0 || (K6 ? ((r + 1) * NTHR <= NP4 + || (NP4 % 32 == 0 ? __builtin_amdgcn_readfirstlane(warp) * 32 < NP4 - r * NTHR + : u < NP4)) : u < NP4)) { const int kp = u % (TILE / 2), o = u / (TILE / 2); // Two's complement nibbles; ^ 8 makes them offset binary (value + 8). const uint32_t n0 = (v4c[r][0] & 0x0F0F0F0Fu) ^ 0x08080808u; 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]; + uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp + + (VSK ? 16 * (o & 3) + 8 * ((o >> 2) & 1) + 128 * (o >> 2) : 0)]; #pragma unroll for (int b = 0; b < 4; ++b) { const uint32_t sel = (uint32_t)b | 0x0c00u | ((uint32_t)(4 + b) << 16) | 0x0c000000u; @@ -507,13 +532,18 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) const uint2 y = swap16_u2p((h == 0) ? hi2 : lo); p16 = (h == 0) ? D::mk(lo, y) : D::mk(y, hi2); } - const uint16_t* vbase = &sV16[c * VSTR + mt * 16] + (CTG ? 8 * h : 0); + // Skewed tile: row 16 G + c is in octet 2 G + (c >> 3), so its S is 16 (c >> 3) here + // plus 32 (G & 1) + 8 ((G >> 1) & 1) + 128 (G >> 1), a compile-time offset below. + const uint16_t* vbase = &sV16[c * VSTR + mt * 16] + (CTG ? 8 * h : 0) + + (VSK ? 16 * (c >> 3) : 0); #pragma unroll for (int g = 0; g < NKS; g += PF) { frag16 vb[PF]; #pragma unroll for (int j = 0; j < PF; ++j) { - const uint16_t* vp = vbase + (g + j) * 16 * VSTR; + const uint16_t* vp = vbase + (g + j) * 16 * VSTR + + (VSK ? 32 * ((g + j) & 1) + 8 * (((g + j) >> 1) & 1) + 128 * ((g + j) >> 1) + : 0); if (V8) { uint32_t w4[4]; fp8x8_to_16x4w(*(const uint2*)&sV8[(c + (g + j) * 16) * VSTR8 + @@ -958,11 +988,23 @@ void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile, // head_dim f16, written once and read once): at eight requests 12.8 MB at splits 32 vs 3.2 MB at // 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. 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; const int units = std::max(1, a->kv_heads * a->num_seqs); - int s = 128 / units; + const int gqa = a->kv_heads > 0 ? std::max(1, a->q_heads / a->kv_heads) : 1; + int s = (a->q_len * gqa <= 32 ? 256 : 128) / units; const int cap = tiles / 2; if (s > cap) s = cap; if (s > tiles) s = tiles; diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index 447d76b6..f86f0726 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -510,6 +510,64 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre } } +/* ========================================================================================== + * gemm_nt_q_gated_mx -- the same fold over an OCP-MXFP4 weight. + * (row: gemm_mxfp4a8_gated_gemv; kernel: libr4d/r4d_gemm_mxfp4a8_gemv.hip, the gated form) + * + * Operands: [0] a [1] a_scale [2] b [3] b_scale [4] b_ref [5] q [6] scale [7] out_bf16 + * + * The GEMM step is gemm_nt_q at dtype mxfp4a8 with `b_ref` in its last operand. `group` is the + * weight's 32 on the GEMM and the activation's 128 on the quantiser, so the quantiser's is set, not + * mirrored. At act gelu_tanh the chain is three steps, gelu_mul into a second temporary and + * quant_act_fp8 over it; that form refuses `out_bf16` (the shim), so operand 7 is not wired. + */ +extern "C" int r4d_fuse_gemm_nt_q_gated_mx(const RadParam* p, int n_p, uint64_t present, int step, + RadFuseStep* out) { + if (!out) return RAD_E_INVAL; + const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K"); + const char* dt = r4d_pgets(p, n_p, "dtype"); + if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED; + if (pi(p, n_p, "group", 32) != 32) return RAD_E_UNSUPPORTED; + if (!dt || std::strcmp(dt, "mxfp4a8")) return RAD_E_UNSUPPORTED; + const bool gelu = act_is(p, n_p, "silu", "gelu_tanh"); + if (!gelu && !act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED; + /* The GeGLU chain leaves its bf16 plane in a temporary, so a caller asking for out_bf16 there + * has no chain (the shim refuses the operand too). */ + if (gelu && RAD_FUSE_HAS(present, 7)) return RAD_E_UNSUPPORTED; + + if (step == 0) { + Step s(out, "gemm_nt_q"); + s.mirror(p, n_p, "M").mirror(p, n_p, "N").mirror(p, n_p, "K") + .mirror(p, n_p, "group").mirror(p, n_p, "dtype"); + /* a, a_scale, b, b_scale, y, a_sum, b_ref */ + return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, 4 }); + } + if (gelu) { + if (step == 1) { + Step s(out, "gelu_mul"); + s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pstr("dtype", "bf16"); + return s.wire({ RAD_FUSE_TMP(0), RAD_FUSE_TMP(1) }); /* gate_up, y */ + } + if (step == 2) { + Step s(out, "quant_act_fp8"); + s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128) + .pstr("dtype", "bf16"); + return s.wire({ RAD_FUSE_TMP(1), 5, 6 }); /* x, q, scale */ + } + return RAD_E_NOTFOUND; + } + switch (step) { + case 1: { + Step s(out, "gated_quant_fp8"); + s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128) + .pstr("dtype", "bf16").mirror(p, n_p, "act"); + return s.wire({ RAD_FUSE_TMP(0), 5, 6, 7 }); /* gate_up, q, scale, out_bf16 */ + } + default: + return RAD_E_NOTFOUND; + } +} + /* ========================================================================================== * gdn_conv_recurrent_update -- the decode convolution folded into the recurrent update's prologue. * (row: gdn_conv_recurrent_update_k128_v128_bf16; kernel: libr4d/ diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index 4f9853f0..23c615d6 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -415,13 +415,18 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( unsigned int* const Lpk = (unsigned int*)loc_pack; float* const Lsc = (float*)(loc_pack + loc_scale_off); + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) if constexpr (WIRE == 0) { /* Push my rows into the peer's slot. `x` is a tight [M][n] of bf16 (the launcher refuses a * pitched one), so a row range is a 16B-word range. */ const int wpr = (int)(n >> 3); const int wend = r1 * wpr; const int4* const in4 = (const int4*)x; - for (int k = r0 * wpr + (int)tid; k < wend; k += (int)THR) ps[k] = in4[k]; + for (int k = r0 * wpr + (int)tid; k < wend; k += (int)THR) { + const int4 v = in4[k]; + ps[k] = v; + hck += r4d_archk_u4(v, 4u * (unsigned)k); + } } else { /* Rotate, amax, quantise and pack straight into the peer's slot. A wave owns whole chunks, * so every lane emits ARQ_NWORD dwords per chunk and the flush is lane-uniform. No group is @@ -449,8 +454,10 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( float sc = (a > 0.0f) ? bf2f(f2bf(a * (1.0f / (float)ARQ_QMAX))) : 1.0f; if (!(sc > 0.0f)) sc = 1.0f; if (lig == 0) { - p_sc[g] = (unsigned short)(__float_as_uint(sc) >> 16); + const unsigned short sc16 = (unsigned short)(__float_as_uint(sc) >> 16); + p_sc[g] = sc16; Lsc[g] = sc; + hck += r4d_archk_mix(sc16, R4D_ARCHK_U16 + (unsigned)g); } const float inv = 1.0f / sc; #pragma unroll @@ -464,21 +471,33 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( } /* Flush lane-contiguously, widest region first, so each is one coalesced store. */ char* const pb = p_pay + (size_t)c * ARQ_CBYTES; + const unsigned int cd = (unsigned)c * (ARQ_CBYTES / 4); // the chunk's first dword #pragma unroll - for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4) + for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4) { *(uint4*)(pb + w4 * 4 * ARQ_WV + lane * 16) = make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]); - if constexpr (ARQ_NWORD % 4 >= 2) + hck += r4d_archk_u4(make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]), + cd + (unsigned)(w4 * ARQ_WV) + lane * 4u); + } + if constexpr (ARQ_NWORD % 4 >= 2) { *(uint2*)(pb + (ARQ_NWORD & ~3) * 4 * ARQ_WV + lane * 8) = make_uint2(acc[ARQ_NWORD & ~3], acc[(ARQ_NWORD & ~3) + 1]); - if constexpr (ARQ_NWORD % 2 == 1) + const unsigned int e = cd + (unsigned)((ARQ_NWORD & ~3) * ARQ_WV) + lane * 2u; + hck += r4d_archk_mix(acc[ARQ_NWORD & ~3], e) + + r4d_archk_mix(acc[(ARQ_NWORD & ~3) + 1], e + 1u); + } + if constexpr (ARQ_NWORD % 2 == 1) { *(unsigned int*)(pb + (ARQ_NWORD - 1) * 4 * ARQ_WV + lane * 4) = acc[ARQ_NWORD - 1]; + hck += r4d_archk_mix(acc[ARQ_NWORD - 1], + cd + (unsigned)((ARQ_NWORD - 1) * ARQ_WV) + lane); + } #pragma unroll for (int wi = 0; wi < ARQ_NWORD; ++wi) Lpk[((size_t)c * ARQ_NWORD + wi) * ARQ_WV + lane] = acc[wi]; } } + r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, sq); /* The drain modes are r4d_ar_oneshot_2rank_exact's, selected by the same variant table. */ if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); @@ -495,6 +514,37 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( } __syncthreads(); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) { + if constexpr (WIRE == 0) { + const int wpr = (int)(n >> 3); + const int4* const m4 = (const int4*)ms; + for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) + h += r4d_archk_u4(m4[k], 4u * (unsigned)k); + } else { + for (int ci = (int)wave; ci < cpb; ci += (int)(THR / ARQ_WV)) { + const int c = c00 + ci; + const char* const pb = m_pay + (size_t)c * ARQ_CBYTES; + const unsigned int cd = (unsigned)c * (ARQ_CBYTES / 4); +#pragma unroll + for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4) + h += r4d_archk_u4(*(const uint4*)(pb + w4 * 4 * ARQ_WV + lane * 16), + cd + (unsigned)(w4 * ARQ_WV) + lane * 4u); + if constexpr (ARQ_NWORD % 4 >= 2) { + const uint2 u = *(const uint2*)(pb + (ARQ_NWORD & ~3) * 4 * ARQ_WV + lane * 8); + const unsigned int e = cd + (unsigned)((ARQ_NWORD & ~3) * ARQ_WV) + lane * 2u; + h += r4d_archk_mix(u.x, e) + r4d_archk_mix(u.y, e + 1u); + } + if constexpr (ARQ_NWORD % 2 == 1) + h += r4d_archk_mix(*(const unsigned int*)(pb + (ARQ_NWORD - 1) * 4 * ARQ_WV + lane * 4), + cd + (unsigned)((ARQ_NWORD - 1) * ARQ_WV) + lane); +#pragma unroll + for (int t = 0; t < ARQ_ITERS; ++t) { + const int g = c * ARQ_CG + t * ARQ_GPW + gw; + if (lig == 0) h += r4d_archk_mix(m_sc[g], R4D_ARCHK_U16 + (unsigned)g); + } + } + } + }); if constexpr (WIRE == 6) { /* Reduce: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate, diff --git a/libr4d/r4d_gemm_mxfp4a8_gemv.hip b/libr4d/r4d_gemm_mxfp4a8_gemv.hip index 0972c411..151e84e0 100644 --- a/libr4d/r4d_gemm_mxfp4a8_gemv.hip +++ b/libr4d/r4d_gemm_mxfp4a8_gemv.hip @@ -30,19 +30,25 @@ // shuffles. TN only widens a block; the sum order of a column is fixed by KW, which is constant. // // The column's 2^(ref - 127) is applied once, as in the decode kernel's epilogue. No scratch and no -// counters: there is no split across blocks. +// counters: there is no split across blocks (the gated fold at the end of the file has both). #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_common.h" #include "r4d_mxfp4.h" +#include "r4d_q8.h" #include #include +#include +#include +#include #include +#include #define R4D_MXG_MAX_M 8 #define R4D_MXG_WMMA_MAX_M 64 // the WMMA form's bound: four 16-row tiles a wave #define R4D_MXG_KW 8 // waves on a block's K, both forms; a constant, so the sum order is too +#define R4D_MXGG_MAX_GROUPS 1024 // the gated fold's counter block: a gated width up to 131072 typedef unsigned mxg_u4 __attribute__((ext_vector_type(4))); typedef unsigned mxg_u2 __attribute__((ext_vector_type(2))); @@ -346,3 +352,284 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs* a, RadStream s) { } return RAD_OK; } + +// ============================================================== the gated form (gemm_nt_q_gated_mx) +// +// The gate_up GEMM with gated_quant_fp8's pass in its epilogue, so the [M, 2n] bf16 product is never +// written and the quantiser is not a launch of its own. A block is one 16-column tile of the gated +// output: sixteen waves, the WMMA form's eight K waves over the gate tile (weight rows 16 j ..) and +// eight over the up tile (rows n + 16 j ..), each tile's partials met in LDS in that form's order. +// The block forms silu(gate) * up in bf16 for its sixteen columns and each row's amax over them. The +// quantiser's scale is per 128 columns (one activation scale group of the down projection's input), +// so the eight blocks of a group leave their products and amaxes in the op's scratch, and the last +// 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). +// +// 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 +// v = 0, 1, .. from zero, as that form's epilogue adds its waves' rows of sP. The scaled sum is +// rounded to bf16 by the same conversion, and from there the arithmetic is r4d_fused_quant_fp8.hip's +// gated_quant_fp8_kernel: silu(gate) * up rounded to bf16, the group's amax (a max, so the blocks' +// order does not matter), scale amax / 448, codes through q8_pack4. ACT 1 is the GeGLU form: gelu_mul's +// tanh GELU with its constants (r4d_model_bf16.hip), the product rounded to bf16 as gelu_mul stores +// it, then quant_act_fp8's quantiser, which is the same arithmetic as gated_quant_fp8's. +namespace { +__device__ __forceinline__ float mxg_bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } +__device__ __forceinline__ uint16_t mxg_f2bf(float f) { // as r4d_fused_quant_fp8.hip's f2bf + const uint32_t u = __float_as_uint(f); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} +} // namespace + +template +__global__ __launch_bounds__(2 * R4D_MXG_KW * 32) +void r4d_gemm_mxfp4a8_gated_kernel( + const unsigned char* __restrict__ A, const float* __restrict__ As, + const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, + const unsigned char* __restrict__ Wref, uint8_t* __restrict__ Q, float* __restrict__ S, + uint16_t* __restrict__ Y, uint16_t* __restrict__ H, float* __restrict__ X, + unsigned* __restrict__ cnt, int M, int K, int n, int as_rs, int lda, int ldws, int q_ld, + int s_ld, int y_ld) { + constexpr int KW = R4D_MXG_KW; + __shared__ float sP[2][KW][R4D_MXG_MAX_M][16]; // gate (0) and up (1) partials, a K wave each + __shared__ unsigned s_last; + const int lane = threadIdx.x & 31; + const int wave = __builtin_amdgcn_readfirstlane(threadIdx.x >> 5); + const int half = wave >> 3, kv = wave & 7; // gate or up, and this wave's K partial + const int j = blockIdx.x; // the gated output's 16-column tile + const int nt = half * (n >> 4) + j; // this wave's weight tile + const int col = lane & 15, khalf = lane >> 4; + const int row = col; + const bool live = row < M; + const int ksteps = K >> 4, chunks = K >> 7; + const unsigned* __restrict__ Wp = (const unsigned*)W; + const int ref = (int)Wref[nt * 16 + col]; + mxg_v8f tot = (mxg_v8f)(0.f); + for (int ch = kv; ch < chunks; ch += KW) { + unsigned wv[8]; +#pragma unroll + for (int s = 0; s < 8; ++s) + wv[s] = __builtin_nontemporal_load(&Wp[((size_t)nt * ksteps + ch * 8 + s) * 32 + lane]); + int e8[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) e8[q] = (int)Ws[(size_t)(ch * 4 + q) * ldws + nt * 16 + col]; + mxg_v2i af[8]; +#pragma unroll + for (int s = 0; s < 8; ++s) { + if (live) { + const unsigned* pa = (const unsigned*)(A + (size_t)row * lda + (ch * 8 + s) * 16 + khalf * 8); + af[s][0] = (int)pa[0]; af[s][1] = (int)pa[1]; + } else { + af[s][0] = 0; af[s][1] = 0; + } + } + mxg_v8f acc = (mxg_v8f)(0.f); +#pragma unroll + for (int s = 0; s < 8; ++s) { + unsigned lo, hi; + r4d_mxfp4_unpack8(wv[s], r4d_mxfp4_fold_d(ref, e8[s >> 1]), &lo, &hi); + mxg_v2i wf; + wf[0] = (int)lo; wf[1] = (int)hi; + acc = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[s], acc); + } + const float sc = ABLK ? (live ? As[(size_t)row * as_rs + ch] : 0.f) : 1.f; +#pragma unroll + for (int e = 0; e < 8; ++e) tot[e] = fmaf(acc[e], sc, tot[e]); + } + // tot[e]: row (lane & 15), column khalf * 8 + e of the tile. + if (live) { +#pragma unroll + for (int e = 0; e < 8; ++e) sP[half][kv][row][khalf * 8 + e] = tot[e]; + } + __syncthreads(); + // The tile pair's product: a thread a (row, column), sixteen lanes a row, so a row's amax is a + // shuffle within its sixteen. + const int g = j >> 3; // the 128-column group + const int tid = threadIdx.x; + if (tid < M * 16) { + const int m = tid >> 4, c = tid & 15; + float sg = 0.f, su = 0.f; +#pragma unroll + for (int w = 0; w < KW; ++w) sg += sP[0][w][m][c]; +#pragma unroll + for (int w = 0; w < KW; ++w) su += sP[1][w][m][c]; + const int cg = j * 16 + c, cu = n + j * 16 + c; + const float rg = __int_as_float((int)Wref[cg] << 23), ru = __int_as_float((int)Wref[cu] << 23); + const float am = ABLK ? 1.f : As[(size_t)m * as_rs]; + const __hip_bfloat16 hg = (__hip_bfloat16)(ABLK ? sg * rg : sg * rg * am); + const __hip_bfloat16 hu = (__hip_bfloat16)(ABLK ? su * ru : su * ru * am); + const float gv = mxg_bf2f(*(const uint16_t*)&hg); + const float a = ACT == 0 ? gv / (1.0f + expf(-gv)) + : 0.5f * gv * (1.0f + tanhf(0.7978845608028654f * (gv + 0.044715f * gv * gv * gv))); + const uint16_t h = mxg_f2bf(a * mxg_bf2f(*(const uint16_t*)&hu)); + if (Y) Y[(size_t)m * y_ld + cg] = h; + H[(size_t)m * n + cg] = h; + float mx = fabsf(mxg_bf2f(h)); +#pragma unroll + for (int o = 8; o > 0; o >>= 1) mx = fmaxf(mx, __shfl_xor(mx, o, 16)); + if (c == 0) X[(size_t)j * M + m] = mx; + } + // Every thread's stores are ordered before the counter; then the group's last arriver quantises. + __threadfence(); + __syncthreads(); + if (tid == 0) + s_last = __hip_atomic_fetch_add(&cnt[g], 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT); + __syncthreads(); + if (s_last != 7u) return; + if (tid == 0) cnt[g] = 0u; // reset for the next launch + __threadfence(); // acquire, before reading the other blocks' + // gated_quant_fp8: one wave a row, a lane four consecutive columns of the group. + if (wave < M) { + const int m = wave, c0 = lane * 4; + const size_t gcol = (size_t)g * 128 + c0; + float mx = 0.f; +#pragma unroll + for (int t = 0; t < 8; ++t) mx = fmaxf(mx, X[(size_t)(g * 8 + t) * M + m]); + float vq[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) vq[i] = mxg_bf2f(H[(size_t)m * n + gcol + i]); + const float sc = mx > 0.0f ? mx * (1.0f / q8_top()) : 1.0f; + if (lane == 0) S[(size_t)m * s_ld + g] = sc; + const float inv = 1.0f / sc; + *(uint32_t*)(Q + (size_t)m * q_ld + gcol) = q8_pack4(vq[0], vq[1], vq[2], vq[3], inv); + } +} + +namespace { +// The arrival counters, one block per output buffer, as the decode row's (mxd_out_ctr): not in the +// scratch, which other ops overwrite, since they must be zero at entry. One allocation per (device, +// output), kept zero by the reducer and never freed (a recorded pass replays the pointer). +unsigned* mxgg_out_ctr(const void* out) { + static std::mutex mu; + static std::map, unsigned*> blocks; + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess) return nullptr; + std::lock_guard lk(mu); + const auto key = std::make_pair(dev, out); + if (auto it = blocks.find(key); it != blocks.end()) return it->second; + unsigned* p = nullptr; + if (hipMalloc((void**)&p, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess) return nullptr; + // Zero before any launch reads it: the memset is on the null stream, which the engine's streams + // need not wait for, so wait here (as mxd_out_ctr and r4d_moe.hip's router counters do). + if (hipMemset(p, 0, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess || + hipDeviceSynchronize() != hipSuccess) { + (void)hipFree(p); + return nullptr; + } + blocks.emplace(key, p); + return p; +} + +// The scratch: the bf16 product [M, n], then each tile's per-row amax [n / 16][M] fp32. +long long mxgg_h_bytes(long long M, long long n) { return (M * n * 2 + 255) / 256 * 256; } +long long mxgg_scratch_bytes(long long M, long long n) { + return mxgg_h_bytes(M, n) + (n / 16) * M * (long long)sizeof(float); +} + +void mxgg_launch(bool ablk, int act, const void* a, const void* as, const void* w, const void* ws, + const void* wr, void* q, void* s, void* y, void* scratch, unsigned* cnt, int M, + int K, int n, int as_rs, int lda, int ldws, int q_ld, int s_ld, int y_ld, + RadStream stream) { + const dim3 grid((uint32_t)(n / 16)), block(2 * R4D_MXG_KW * 32); + hipStream_t st = (hipStream_t)stream; + uint16_t* h = (uint16_t*)scratch; + float* x = (float*)((char*)scratch + mxgg_h_bytes(M, n)); +#define MXGG_L(AB_, ACT_) \ + hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel), grid, block, 0, st, \ + (const unsigned char*)a, (const float*)as, (const unsigned char*)w, \ + (const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, \ + (uint16_t*)y, h, x, cnt, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld) + if (act == 0) { if (ablk) MXGG_L(true, 0); else MXGG_L(false, 0); } + else { if (ablk) MXGG_L(true, 1); else MXGG_L(false, 1); } +#undef MXGG_L +} +} // namespace + +/* The gated GEMM's shim. Operand indices are `gemm_nt_q_gated_mx`'s (oGemmNtQGatedMx in + * r4d_rows.cpp): gemm_nt_q_gated's with the per-row reference `b_ref` after `b_scale`. The weight + * is one [N, K] plane, gate rows then up rows, N = 2 * the gated width; no parts. */ +enum { MXGG_A = 0, MXGG_AS = 1, MXGG_B = 2, MXGG_BS = 3, MXGG_BR = 4, MXGG_Q = 5, MXGG_S = 6, + MXGG_Y = 7 }; + +extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) { + const RadTensor* x = r4d_opt(a, MXGG_A); + const RadTensor* xs = r4d_opt(a, MXGG_AS); + const RadTensor* w = r4d_opt(a, MXGG_B); + const RadTensor* ws = r4d_opt(a, MXGG_BS); + const RadTensor* wr = r4d_opt(a, MXGG_BR); + const RadTensor* q = r4d_opt(a, MXGG_Q); + const RadTensor* sc = r4d_opt(a, MXGG_S); + const RadTensor* y = r4d_opt(a, MXGG_Y); + if (!x || !xs || !w || !ws || !wr || !q || !sc) return R4D_NO(RAD_E_INVAL); + if (x->dtype != RAD_F8E4M3 || xs->dtype != RAD_F32 || q->dtype != RAD_F8E4M3 || + sc->dtype != RAD_F32 || (y && y->dtype != RAD_BF16)) + return R4D_NO(RAD_E_DTYPE); + if (q->rank != 2 || sc->rank != 2 || x->rank != 2) return R4D_NO(RAD_E_SHAPE); + if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE); + if (r4d_geti_or(a, "group", 32) != 32) return R4D_NO(RAD_E_SHAPE); + /* silu (the SwiGLU MLP) or gelu_tanh (GeGLU, gelu_mul's). The GeGLU chain's bf16 plane is + * gelu_mul's output, which the fold's replaces-hook cannot hand to the optional `out_bf16`, so + * that form writes none. */ + const char* act = r4d_gets(a, "act"); + const int actm = !act ? -1 : !std::strcmp(act, "silu") ? 0 : !std::strcmp(act, "gelu_tanh") ? 1 : -1; + if (actm < 0) return R4D_NO(RAD_E_UNSUPPORTED); + if (actm == 1 && y) return R4D_NO(RAD_E_UNSUPPORTED); + + /* The gated width from `q`, the buffer written; N and K from the op's parameters, since the + * weight operands are packed bytes. */ + const long long M = q->shape[0], nout = q->shape[1]; + const long long N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0); + if (M < 1 || M > R4D_MXG_MAX_M || nout < 128 || nout % 128 || nout / 128 > R4D_MXGG_MAX_GROUPS) + return R4D_NO(RAD_E_SHAPE); + if (N != 2 * nout || K < 128 || K % 128) return R4D_NO(RAD_E_SHAPE); + if (x->shape[0] != M || r4d_numel(x) != M * K) return R4D_NO(RAD_E_SHAPE); + if (sc->shape[0] != M || sc->shape[1] != nout / 128) return R4D_NO(RAD_E_SHAPE); + if (y && (y->shape[0] != M || y->shape[1] != nout)) return R4D_NO(RAD_E_SHAPE); + /* The activation scale grid as the gemm_nt_q rows read it (mx_ascale_grid), so the fold and the + * GEMM it replaces take every scale plane the same way. */ + GemmOps go{}; + go.ascale = xs; go.M = M; go.K = K; + int as_group = 0, as_rs_i = 1; + if (mx_ascale_grid(go, &as_group, &as_rs_i) != RAD_OK) return R4D_NO(RAD_E_SHAPE); + const bool ablk = as_group == 128; + const long long as_rs = as_rs_i; + /* Row pitches; r4d_row_pitch is -1 for a tensor not contiguous past its leading axis. A is read + * a dword at a time. */ + const long long lda = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); + const long long yp = y ? r4d_row_pitch(y) : 0; + if (lda < K || lda % 4 || qp < nout || sp < nout / 128 || (y && yp < nout)) + return R4D_NO(RAD_E_STRIDE); + if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16) || !r4d_aligned(q->data, 4) || + !r4d_aligned(ws->data, 4) || !r4d_aligned(wr->data, 4) || qp % 4) + return R4D_NO(RAD_E_ALIGN); + /* The cross-block product and amaxes are the op's scratch (sized by the hook below); a + * shorter one is refused. */ + if (!a->scratch || a->scratch_bytes < mxgg_scratch_bytes(M, nout)) return R4D_NO(RAD_E_SCRATCH); + unsigned* cnt = mxgg_out_ctr(q->data); + if (!cnt) return R4D_NO(RAD_E_NOMEM); + + R4D_TRY("gemm_mxfp4a8_gated", + mxgg_launch(ablk, actm, x->data, xs->data, w->data, ws->data, wr->data, q->data, sc->data, + y ? y->data : nullptr, a->scratch, cnt, (int)M, (int)K, (int)nout, (int)as_rs, + (int)lda, (int)N, (int)qp, (int)sp, (int)yp, s)); + return RAD_OK; +} + +/* The op's scratch: the product and amaxes at the band's widest M, from N (twice the gated + * width). */ +extern "C" int64_t r4d_rad_gemm_mxfp4a8_gated_scratch(const RadArgs* a) { + const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0); + if (M < 1 || M > R4D_MXG_MAX_M || N < 256 || N % 256) return 0; + return (int64_t)mxgg_scratch_bytes(M, N / 2); +} diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 6ef46f6f..c435b90e 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -939,6 +939,29 @@ extern "C" int r4d_rad_relayout_mxfp4(const RadParam* p, int n_p, int operand, return RAD_OK; } +/* gemm_nt_q_gated_mx's weights are gemm_nt_q's mxfp4a8 planes in the same stored forms, but its + * `b_ref` is operand 4, where gemm_nt_q has `y`: mapped to gemm_nt_q's index, so both ops ask for + * the reference plane in one form and the loader stores it once. */ +static int mx_gated_operand(int operand) { + return operand == Q_B || operand == Q_BSCALE ? operand : operand == 4 ? Q_BREF : -1; +} + +extern "C" int r4d_rad_layout_mxfp4_gated(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + const int o = mx_gated_operand(operand); + return o < 0 ? RAD_E_UNSUPPORTED : r4d_rad_layout_mxfp4(p, n_p, o, enc, sel, pl, n, out); +} + +extern "C" int r4d_rad_relayout_mxfp4_gated(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + const int o = mx_gated_operand(operand); + return o < 0 ? RAD_E_UNSUPPORTED + : r4d_rad_relayout_mxfp4(p, n_p, o, enc, sel, pl, n, dst, dst_bytes); +} + /* ---- the MoE experts. The weight is staged through LDS, so it is not permuted: the int4 plane is * the canonical one with each dword's nibbles reordered for the expansion (byte b holds element b * low and element b+4 high), and the fp8 plane is the canonical one unchanged. `w4a8h` is the same diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 61da0830..73d6bc3c 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -459,6 +459,8 @@ int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs*); int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream); int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*); int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs*, RadStream); +int r4d_rad_gemm_mxfp4a8_gated(const RadArgs*, RadStream); +int64_t r4d_rad_gemm_mxfp4a8_gated_scratch(const RadArgs*); int r4d_rad_dequant_w4 (const RadArgs*, RadStream); int r4d_rad_rowtopk (const RadArgs*, RadStream); int64_t r4d_rad_rowtopk_scratch(const RadArgs*); @@ -665,6 +667,10 @@ int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const in const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, void*, int64_t); +int r4d_rad_layout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); int r4d_rad_layout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*, @@ -917,6 +923,7 @@ int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam*, int, uint64_t, int, RadFu int r4d_fuse_router_sigmoid_topk_scatter(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_gemm_nt_q_gated_mx (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index b7b7596b..ef4371cf 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -324,7 +324,13 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel( /* push my rows into the peer's slot; `x` is a tight [M][n] of bf16 */ const int wpr = (int)(n >> 3); const int4* const in4 = (const int4*)x; - for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) ps[k] = in4[k]; + unsigned int hck = 0u; // the push check (r4d_ar_seq.h) + for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) { + const int4 v = in4[k]; + ps[k] = v; + hck += r4d_archk_u4(v, 4u * (unsigned)k); + } + r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, sq); if (drain == 1) __threadfence_system(); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); __syncthreads(); @@ -338,6 +344,10 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel( } __syncthreads(); if (acq) __threadfence_system(); + r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) { + for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) + h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + }); const uint16_t* __restrict__ P = (const uint16_t*)ms; /* the peer's rows, in my scratch */ const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f; diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 5e611270..a6fbb78d 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1627,6 +1627,20 @@ static const RadOperandSpec oGemmNtQGated[] = { { "scale", RAD_OPD_OUT, 0 }, { "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. */ +static const RadOperandSpec oGemmNtQGatedMx[] = { + { "a", RAD_OPD_IN, 0 }, + { "a_scale", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_WEIGHT, 0 }, + { "b_scale", RAD_OPD_WEIGHT, 0 }, + { "b_ref", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 }, +}; /* The gate in a separate operand, as in a gated attention: the gate is a column slice of the * [q|gate] projection and `x` the attention output, two buffers with different pitches. A row is a @@ -3363,6 +3377,10 @@ static const RadOpSchema kSchemas[] = { "columns) and optionally the bf16 product, and no [M, 2n] tensor is ever written. " "Byte-identical to the two ops it replaces, which is what makes it substitutable " "rather than a second numerical path."), + SCHEMA("gemm_nt_q_gated_mx", pGemmNtQGated, oGemmNtQGatedMx, + "gemm_nt_q_gated over an OCP-MXFP4 [2n, K] gate_up weight: gemm_nt_q at dtype mxfp4a8 " + "(`b_ref` the per-row reference exponent) with gated_quant_fp8's pass folded into the " + "epilogue, byte-identical to the two ops it replaces."), SCHEMA("gate_quant_fp8", pGateQuantFp8, oGateQuantFp8, "the same, with the gate in its own operand rather than packed beside x."), SCHEMA("quant_act_fp8", pQuantActFp8, oQuantActFp8, @@ -4808,6 +4826,13 @@ static const RadConstraint cGemmNtQGatedFp8[] = { C_LE("M", 64), C_DIV("K", 256), C_DIV("N", 256), C_GE("N", 2048), 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. */ +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"), +}; static const RadConstraint cGateQuantFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; @@ -7742,6 +7767,26 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gemv, nullptr, r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 }, +{ "gemm_mxfp4a8_gated_gemv", "gemm_nt_q_gated_mx", "gemm", + "the gemv row's WMMA form over a gate_up weight with gated_quant_fp8's pass in its epilogue: a " + "block per 16-column tile of the gated output, that form's eight K waves on the gate tile and " + "eight on the up tile, the block's bf16 product and row amaxes in the op's scratch and the last " + "of a 128-column group's blocks to arrive writing its codes and scales, so the [M, 2n] bf16 " + "product is never written", + "M <= 8; K a multiple of 128; N a multiple of 256 (the gated width a multiple of the 128-column " + "scale group); act silu, or gelu_tanh without out_bf16; the skinny kernel's fragment-order weight, [K/32][N] E8M0 " + "exponents and per-row reference exponent, gate rows then up rows", + "e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K, and the " + "QUANTISER's outputs: E4M3 codes, an f32 scale per (row, 128 columns) and an optional bf16 " + "product. Byte-identical to gemm_mxfp4a8_gemv followed by gated_quant_fp8 (silu), or by gelu_mul " + "and quant_act_fp8 (gelu_tanh)", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGemmNtQGatedMx), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gated, r4d_rad_gemm_mxfp4a8_gated_scratch, + r4d_rad_layout_mxfp4_gated, r4d_rad_relayout_mxfp4_gated, nullptr, nullptr, + /* The byte-identity claim above, as a chain of two rows of this plugin (r4d_fuse.cpp). */ + r4d_fuse_gemm_nt_q_gated_mx }, + { "gemm_mxfp4a8_decode", "gemm_nt_q", "gemm", "the OCP-MXFP4 GEMM for the DECODE band: split-K across workgroups with a fused last-arriver " "reduction, the weight unpacked through LDS, streaming weight loads", @@ -9704,11 +9749,11 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { * every collective the peer flags and exchange buffers the all-reduces own * * gemm_fp8a8_nt_m16's finisher counters are keyed on the stream and the output; - * gemm_mxfp4a8_decode's (and gemm_mxfp4a8_decode_shortk's, the same entry) split partial is the - * op's scratch and its arrival counters are keyed on the output alone; - * router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance (taken at init, one - * per declared op and band). Concurrent launches never share these, so those four rows are - * concurrent. A new row with stream-ordered state belongs in the list above. + * gemm_mxfp4a8_decode's (and gemm_mxfp4a8_decode_shortk's, the same entry) and + * gemm_mxfp4a8_gated_gemv's split partials are the op's scratch and their arrival counters are keyed + * on the output alone; router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance + * (taken at init, one per declared op and band). Concurrent launches never share these, so those + * five rows are concurrent. A new row with stream-ordered state belongs in the list above. * * lora_* ordered on purpose: the core appends them behind the GEMM whose `y` they * update and refills the pools they read between steps with its own copies, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 95408d58..615ea471 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -5999,6 +5999,15 @@ static int launch_row(const RadKernelInfo* r, std::vector ts, a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; + if (r->scratch) { + const int64_t need = r->scratch(&a); + if (need < 0) return (int)need; + if (need > 0) { + a.scratch = dalloc((size_t)need); + a.scratch_bytes = need; + if (!a.scratch) return RAD_E_NOMEM; + } + } const int rc = r->launch(&a, (RadStream)nullptr); if (rc != RAD_OK) return rc; return st_stream_sync(nullptr) == hipSuccess ? RAD_OK : RAD_E_STATE; @@ -6073,6 +6082,162 @@ static void w4a8_multi_user_exact(const Plugin& pl) { } } +/* ---- the MXFP4 gated fold, against the pair it replaces ------------------------------------- + * + * gemm_mxfp4a8_gated_gemv (gemm_nt_q_gated_mx) against gemm_mxfp4a8_gemv followed by + * gated_quant_fp8, on the same weight bytes (one relayout, through the gemv row's hooks, which the + * gated row shares) and activation. Codes, scales and the bf16 product must be identical, and the + * codes mostly non-zero (zeroed buffers compare equal). Run twice: with `out_bf16`, and without it, + * where the codes and scales must still match. */ +static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K, bool ablk, + bool gelu = false) { + const char* row = "gemm_mxfp4a8_gated_gemv"; + if (!sel(row)) return; + char nm[192]; + std::snprintf(nm, sizeof nm, "%s byte-identical to gemv + %s, M=%lld N=%lld K=%lld%s", row, + gelu ? "gelu_mul + quant_act_fp8" : "gated_quant_fp8", (long long)M, (long long)N, + (long long)K, ablk ? " ascale=row x 128" : ""); + const RadKernelInfo* rg = find(pl, row); + const RadKernelInfo* rv = find(pl, "gemm_mxfp4a8_gemv"); + const RadKernelInfo* rq = find(pl, gelu ? "quant_act_fp8" : "gated_quant_fp8"); + const RadKernelInfo* rm = find(pl, "gelu_mul_bf16"); + if (!rg || !rv || !rq || (gelu && !rm) || !rg->layout || !rg->relayout) { + ok(nm, false, "row or hooks absent"); + return; + } + + Planes p; + p.enc = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + p.size(N, K); + const int ic = p.find("codes"), is = p.find("scale"); + if (ic < 0 || is < 0) { ok(nm, false, "encoding has no codes/scale plane"); return; } + mxfp4_fill(p, ic, is, N, K, 0x51u, true); + std::vector lp = { PI("N", N), PI("K", K), PI("group", 32) }; + std::vector wq, ws, wr; + /* Stored through the gated row's own hooks (its `b_ref` is operand 4), so the gemv row reading + * the same bytes also checks that both ops store the planes in one form. */ + if (stored(rg, lp, 2, p, { "codes" }, &wq) != RAD_OK || stored(rg, lp, 3, p, { "scale" }, &ws) != RAD_OK || + stored(rg, lp, 4, p, { "scale" }, &wr) != RAD_OK) { + ok(nm, false, "relayout refused"); + return; + } + /* The reference plane through the gemv row's own hook (its operand 6) must be the same bytes: + * a remap that handed the gated row's b_ref another form would otherwise pass, both kernels + * reading the same wrong plane. */ + { + std::vector wr_gemv; + if (stored(rv, lp, 6, p, { "scale" }, &wr_gemv) != RAD_OK || wr_gemv != wr) { + ok(nm, false, "b_ref stored differently by the gated and gemv rows"); + return; + } + } + const int64_t nkb = K / 128, n = N / 2, gkb = n / 128; + std::vector ha((size_t)(M * K)); + std::vector as((size_t)(M * (ablk ? nkb : 1))); + for (int64_t i = 0; i < M; ++i) { + if (ablk) + for (int64_t c = 0; c < nkb; ++c) + as[(size_t)(i * nkb + c)] = 0.002f * (float)(1 + st_mix32((uint32_t)(i * nkb + c)) % 97); + else + as[(size_t)i] = 0.0125f * (float)(1 + st_mix32((uint32_t)i ^ 0xa5u) % 5); + for (int64_t k = 0; k < K; ++k) rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, mxfp4_act(i, k, 0x3cu)); + } + void* d_a = dalloc(ha.size()); + void* d_s = dalloc(as.size() * 4); + void* d_w = dalloc(wq.size()); + void* d_e = dalloc(ws.size()); + void* d_r = dalloc(wr.size()); + void* d_y = dalloc((size_t)(M * N * 2)); + void* d_q[3] = { dalloc((size_t)(M * n)), dalloc((size_t)(M * n)), dalloc((size_t)(M * n)) }; + void* d_z[3] = { dalloc((size_t)(M * gkb * 4)), dalloc((size_t)(M * gkb * 4)), dalloc((size_t)(M * gkb * 4)) }; + void* d_b[2] = { dalloc((size_t)(M * n * 2)), dalloc((size_t)(M * n * 2)) }; + if (!d_a || !d_s || !d_w || !d_e || !d_r || !d_y || !d_q[2] || !d_z[2] || !d_b[1]) { + ok(nm, false, "hipMalloc failed"); + return; + } + st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice); + st_memcpy(d_s, as.data(), as.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice); + st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice); + st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice); + const RadTensor ta = T(d_a, RAD_F8E4M3, { M, K }); + const RadTensor tas = ablk ? T(d_s, RAD_F32, { M, nkb }) : T(d_s, RAD_F32, { M }); + const RadTensor tw = T(d_w, RAD_U8, { (int64_t)wq.size() }), te = T(d_e, RAD_U8, { (int64_t)ws.size() }); + const RadTensor tr = T(d_r, RAD_U8, { (int64_t)wr.size() }); + + /* The pair. */ + RadTensor none = T(nullptr, RAD_F32, { 1 }); + absent(none); + int rc = launch_row(rv, { ta, tas, tw, te, T(d_y, RAD_BF16, { M, N }), none, tr }, + { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8") }); + if (rc == RAD_OK && !gelu) + rc = launch_row(rq, { T(d_y, RAD_BF16, { M, N }), T(d_q[0], RAD_F8E4M3, { M, n }), + T(d_z[0], RAD_F32, { M, gkb }), T(d_b[0], RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") }); + if (rc == RAD_OK && gelu) { + rc = launch_row(rm, { T(d_y, RAD_BF16, { M, N }), T(d_b[0], RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(rq, { T(d_b[0], RAD_BF16, { M, n }), T(d_q[0], RAD_F8E4M3, { M, n }), + T(d_z[0], RAD_F32, { M, gkb }) }, + { PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16") }); + } + if (rc != RAD_OK) { ok(nm, false, "the chain: rc=" + std::to_string(rc)); return; } + + /* The fold, with and without the bf16 product (the GeGLU form refuses it, asserted). */ + const std::vector gp = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), + PS("dtype", "mxfp4a8"), PS("act", gelu ? "gelu_tanh" : "silu") }; + for (int v = 1; v <= 2; ++v) { + st_memset(d_q[v], 0, (size_t)(M * n)); + st_memset(d_z[v], 0, (size_t)(M * gkb * 4)); + } + st_memset(d_b[1], 0, (size_t)(M * n * 2)); + rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[1], RAD_F8E4M3, { M, n }), + T(d_z[1], RAD_F32, { M, gkb }), T(d_b[1], RAD_BF16, { M, n }) }, gp); + if (gelu) { + if (rc == RAD_OK) { ok(nm, false, "the GeGLU fold served out_bf16"); return; } + rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[1], RAD_F8E4M3, { M, n }), + T(d_z[1], RAD_F32, { M, gkb }), none }, gp); + st_memcpy(d_b[1], d_b[0], (size_t)(M * n * 2), hipMemcpyDeviceToDevice); + } + /* Twice into one output, cleared between: the split's arrival counters are keyed on the output, + * so the second launch reduces only if the first left them zero. */ + for (int rep = 0; rep < 2 && rc == RAD_OK; ++rep) { + st_memset(d_q[2], 0, (size_t)(M * n)); + st_memset(d_z[2], 0, (size_t)(M * gkb * 4)); + rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[2], RAD_F8E4M3, { M, n }), + T(d_z[2], RAD_F32, { M, gkb }), none }, gp); + } + if (rc != RAD_OK) { ok(nm, false, "the fold: rc=" + std::to_string(rc)); return; } + + std::vector c[3]; + std::vector z[3]; + for (int v = 0; v < 3; ++v) { + c[v].resize((size_t)(M * n)); + z[v].resize((size_t)(M * gkb)); + st_memcpy(c[v].data(), d_q[v], c[v].size(), hipMemcpyDeviceToHost); + st_memcpy(z[v].data(), d_z[v], z[v].size() * 4, hipMemcpyDeviceToHost); + } + std::vector b0((size_t)(M * n)), b1((size_t)(M * n)); + st_memcpy(b0.data(), d_b[0], b0.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(b1.data(), d_b[1], b1.size() * 2, hipMemcpyDeviceToHost); + int nc = 0, nz = 0, nb = 0, nc2 = 0, nz2 = 0, live = 0; + for (size_t i = 0; i < c[0].size(); ++i) { + nc += c[0][i] != c[1][i]; + nc2 += c[0][i] != c[2][i]; + live += c[1][i] != 0; + } + for (size_t i = 0; i < z[0].size(); ++i) { + nz += std::memcmp(&z[0][i], &z[1][i], 4) != 0; + nz2 += std::memcmp(&z[0][i], &z[2][i], 4) != 0; + } + for (size_t i = 0; i < b0.size(); ++i) nb += b0[i] != b1[i]; + ok(nm, nc == 0 && nz == 0 && nb == 0 && nc2 == 0 && nz2 == 0 && live > (int)c[1].size() / 2, + "codes differ " + std::to_string(nc) + "/" + std::to_string(nc2) + ", scales " + + std::to_string(nz) + "/" + std::to_string(nz2) + ", bf16 " + std::to_string(nb) + + ", nonzero " + std::to_string(live) + " of " + std::to_string(c[1].size())); +} + /* ---- the audio generator's ops and their optional forms, against libref's arithmetic ---------- * * Each case builds its operands on the host, runs the row, and compares with the host port of the @@ -13140,6 +13305,31 @@ static void mx_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8") }; perf_row(pl, row, ts, ps, d_w, wq.size(), copies, (double)(wq.size() + ws.size()), iters); + /* At a gate_up shape the gemv row's GEMM is half of a pair: time the other half + * (gated_quant_fp8 over its output) and the fold that replaces both. */ + if (!std::strcmp(row, "gemm_mxfp4a8_gemv") && N % 256 == 0 && K % 128 == 0) { + const int64_t n = N / 2; + void* d_q = dalloc((size_t)(M * n)); + void* d_z = dalloc((size_t)(M * (n / 128) * 4)); + if (!d_q || !d_z) { std::printf(" gated: hipMalloc failed\n"); continue; } + RadTensor nob = T(nullptr, RAD_BF16, { M, n }); + absent(nob); + perf_row(pl, "gated_quant_fp8", { T(d_y, RAD_BF16, { M, N }), T(d_q, RAD_F8E4M3, { M, n }), + T(d_z, RAD_F32, { M, n / 128 }), nob }, + { PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") }, + d_y, (size_t)(M * N * 2), 1, (double)(M * N * 2), iters, 0); + const RadKernelInfo* rg = find(pl, "gemm_mxfp4a8_gated_gemv"); + std::vector gr; + if (rg && stored(rg, lp, 4, p, { "scale" }, &gr) == RAD_OK && gr == wr) + perf_row(pl, "gemm_mxfp4a8_gated_gemv", + { T(d_a, RAD_F8E4M3, { M, K }), T(d_s, RAD_F32, { M, nkb }), + T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }), + T(d_r, RAD_U8, { (int64_t)wr.size() }), T(d_q, RAD_F8E4M3, { M, n }), + T(d_z, RAD_F32, { M, n / 128 }), nob }, + { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8"), + PS("act", "silu") }, + d_w, wq.size(), copies, (double)(wq.size() + ws.size()), iters); + } } } @@ -23517,6 +23707,32 @@ static void ar_two_rank_sweep(const Plugin& pl, const std::vector& devs, co if (row->fini) { row->fini(a.inst); row->fini(b.inst); } } +/* Every peer push landing after its flag (the kernel's test mode, R4D_AR_TEST_LATE_PUSH): a push + * over PCIe P2P sometimes lands a microsecond or more after the release flag that follows it, so a + * reader that trusted the flag would sum the slot's previous contents. The push check + * (r4d_ar_seq.h) makes the reader wait for the bytes; here every launch of the sweep needs it. */ +static void ar_two_rank_late(const Plugin& pl, const std::vector& devs, const char* name) { + const RadKernelInfo* row = find(pl, name); + if (!row) { ok(name, false, "row absent"); return; } + if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; } + setenv("R4D_AR_TEST_LATE_PUSH", "1", 1); + ArSweep a{ row, 0, devs[0] }, b{ row, 1, devs[1] }; + std::thread ta(ar_sweep_worker, &a), tb(ar_sweep_worker, &b); + ta.join(); + tb.join(); + unsetenv("R4D_AR_TEST_LATE_PUSH"); + ok("2-rank all-reduce init, pushes landing after their flags", + a.rc_init == RAD_OK && b.rc_init == RAD_OK, + "rc " + std::to_string(a.rc_init) + "/" + std::to_string(b.rc_init)); + if (a.rc_init != RAD_OK || b.rc_init != RAD_OK) return; + ok("2-rank all-reduce, every push landing ~20 us after its flag, 32 rounds, every sum exact on " + "both ranks", + a.rc_launch == RAD_OK && b.rc_launch == RAD_OK && a.bad == 0 && b.bad == 0, + "rc " + std::to_string(a.rc_launch) + "/" + std::to_string(b.rc_launch) + ", " + + std::to_string(a.bad + b.bad) + " elements wrong"); + if (row->fini) { row->fini(a.inst); row->fini(b.inst); } +} + /* ------------------------------------------------------------------ the two-rank all-gather */ /* The payload is what the vocab-parallel sampler gathers: (u32 global token id, f32 logit) pairs. * A token id's bit pattern read as f32 is a denormal, so an all-gather emulated by an all-reduce @@ -27888,6 +28104,16 @@ static void device_phase(const Plugin& pl) { mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_gemv", 1088, 576, true); mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_gemv", 1056, 576, false); mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_decode", 5120, 5120, true); + /* The gated fold against the pair it replaces (gemv + gated_quant_fp8): Qwen's and + * TranslateGemma's per-rank gate_up at every M of the band, one group of 128 at the smallest + * K, and the per-row activation scale. */ + for (const int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8 }) mxfp4a8_gated_case(pl, m, 17408, 5120, true); + mxfp4a8_gated_case(pl, 8, 21504, 5376, true); + mxfp4a8_gated_case(pl, 3, 256, 256, true); + mxfp4a8_gated_case(pl, 5, 1024, 640, false); + for (const int64_t m : { 1, 4, 8 }) mxfp4a8_gated_case(pl, m, 21504, 5376, true, true); + mxfp4a8_gated_case(pl, 3, 256, 256, true, true); + mxfp4a8_gated_case(pl, 2, 1024, 640, false, true); /* Parts (ParoQuant): each weight part against its own activation copy, with bounds off any * kernel's tile, two and three parts, at every band. */ mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 400, 640, 0, true, {}, 144); @@ -29012,6 +29238,7 @@ static void device_phase(const Plugin& pl) { if (!std::strcmp(base, "ar_oneshot_2rank_exact")) { ar_two_rank(pl, devs, n.c_str()); ar_two_rank_sweep(pl, devs, n.c_str()); + ar_two_rank_late(pl, devs, n.c_str()); } else { gather_two_rank(pl, devs, n.c_str()); } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5852e77e..f97453fe 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -176,6 +176,12 @@ foreach(t ${RAD_TESTS}) target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE} ${CMAKE_DL_LIBS}) target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/libr4d) target_compile_options(${n} PRIVATE -ffp-contract=off) + # relayout_parity_test also holds tools/opshapes.cpp's fallback table to these hooks' byte + # totals, so it needs the table's source too. + if(n STREQUAL relayout_parity_test) + target_sources(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools/opshapes.cpp) + target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools) + endif() elseif(n IN_LIST RAD_TESTS_WHOLE_CORE) add_executable(${n} ${t}) target_link_libraries(${n} PRIVATE stdc++ "$") diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 34604542..081ac252 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -9192,7 +9192,7 @@ struct ArchCases { qwen35_fp8::step, 3, {}, 0x7c3df775e4091829ull); add("qwen35_fp8 + MTP, two ranks", [this, sc](RadBuilder* b) { auto c = sc(2, 3); return qwen35_fp8::declare(b, q35.meta(), &c); }, - nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0x8960f76b0bf8e50aull); + nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0x7c11e3c8243c955full); add("qwen35_fp8 + DFlash2", [this, sc](RadBuilder* b) { auto c = sc(1, 7); return qwen35_fp8::declare(b, q35df.meta(), &c); }, qwen35_fp8::step, 7, {}, 0xa980fd70dfca7f04ull); @@ -9201,20 +9201,20 @@ struct ArchCases { qwen35_w8a8::step, 7, {}, 0xb01f0bb2b9898c1dull); add("qwen35_w8a8 + DFlash2, two ranks", [this, sc](RadBuilder* b) { auto c = sc(2, 7); return w8a8_declare(b, q35w8df.meta(), &c); }, - nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0xf60656437356f664ull); + nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0xdc5540151b0d6684ull); add("qwen35moe_fp8 + MTP", [this, sc](RadBuilder* b) { auto c = sc(1, 3); return qwen35moe_fp8::declare(b, q35moe.meta(), &c); }, qwen35moe_fp8::step, 3, {}, 0xb5aaea840d6bf6c2ull); add("qwen4exp_fp8", [this](RadBuilder* b) { auto c = q4_ctx(0, 1); return qwen4exp_fp8::declare(b, &q4, &c); }, - qwen4exp_fp8::step, 3, {}, 0xb00af22d0c1db143ull); + qwen4exp_fp8::step, 3, {}, 0x43048d3448778280ull); add("qwen4exp_fp8, two ranks", [this](RadBuilder* b) { auto c = q4_ctx(0, 2); return qwen4exp_fp8::declare(b, &q4, &c); }, - nullptr, 3, { "ar_hc_write" }, 0x2d685c5f5a068473ull); + nullptr, 3, { "ar_hc_write" }, 0x43d3be2b6d76e470ull); add("qwen4exp_fp8, four-bit experts", [this](RadBuilder* b) { b->encs = { { "ffn_gate_up_exps", w4 }, { "ffn_down_exps", w4 } }; auto c = q4_ctx(0, 1); return qwen4exp_fp8::declare(b, &q4, &c); }, - qwen4exp_fp8::step, 3, {}, 0xa00760f0eb3da078ull); + qwen4exp_fp8::step, 3, {}, 0x08d082fcbef37889ull); /* The cache dtype stated rather than left to the plugin's default. The streamed store and * the prologue that folds it are declared only where the vocabulary has them, and both are * written at the KV group's dtype -- bf16 being the copy-only one, and it is what @@ -9226,7 +9226,7 @@ struct ArchCases { auto c = q4_ctx(0, 1); c.kv_dtype = RAD_BF16; return qwen4exp_fp8::declare(b, &q4, &c); }, - qwen4exp_fp8::step, 3, {}, 0xb00af22d0c1db143ull); + qwen4exp_fp8::step, 3, {}, 0x0000000000000000ull); add("llama_fp8 + DSpark", [this](RadBuilder* b) { auto c = dspark_ctx(0, 1); return llama_fp8::declare(b, lla.meta(), &c); }, llama_fp8::step, 7, {}, 0xdcf36a1d31aba73cull); @@ -9942,15 +9942,15 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { uint64_t graph, steps; }; const Case cases[] = { - { "qwen4exp_fp8", 1, 0, 0x43db8c3ddf237950ull, 0x26a9e2c23cf85696ull }, - { "qwen4exp_fp8", 2, 0, 0x46b814bcc44bdaaaull, 0x889c6b36c014609full }, - { "qwen4exp_fp8", 2, 1, 0xfaef43f1dff09459ull, 0x959ef6b7c6f57d8bull }, - { "qwen4exp_fp8", 4, 0, 0xa6fe7e5732760f4cull, 0xfbe74f2b9d7020bfull }, - { "qwen4exp_fp8", 4, 3, 0x9281597b6738d9a4ull, 0x36df57cac613c6cfull }, - { "qwen35_fp8", 1, 0, 0xf5ea9e1795b08134ull, 0x4d6fca823d1e97efull }, - { "qwen35_fp8", 2, 1, 0x803113b1ae0276e3ull, 0xb297654cef04bf08ull }, - { "qwen35moe_fp8", 1, 0, 0x3979c928377bd5fcull, 0x3fcf71676e558d79ull }, - { "qwen35moe_fp8", 2, 0, 0x5ef9a8b68cb03cf1ull, 0x05e0778848bf416cull }, + { "qwen4exp_fp8", 1, 0, 0x23ec76c443e2cb6full, 0x26a9e2c23cf85696ull }, + { "qwen4exp_fp8", 2, 0, 0x88290524cfd7714full, 0x889c6b36c014609full }, + { "qwen4exp_fp8", 2, 1, 0xa4268bda72739be8ull, 0x959ef6b7c6f57d8bull }, + { "qwen4exp_fp8", 4, 0, 0xaa5abead708b106full, 0xfbe74f2b9d7020bfull }, + { "qwen4exp_fp8", 4, 3, 0x9ffc4cf1b074a153ull, 0x36df57cac613c6cfull }, + { "qwen35_fp8", 1, 0, 0xcfc82ca915ec549dull, 0x4d6fca823d1e97efull }, + { "qwen35_fp8", 2, 1, 0xcaf28466af9e917dull, 0x0bcf5833fce11a86ull }, + { "qwen35moe_fp8", 1, 0, 0x7fa7b015e1bc8873ull, 0x3fcf71676e558d79ull }, + { "qwen35moe_fp8", 2, 0, 0xf60c9508dd197370ull, 0x05e0778848bf416cull }, }; for (const Case& cs : cases) { RadBuilder b; diff --git a/tests/relayout_parity_test.cpp b/tests/relayout_parity_test.cpp index 427a428f..b5a3a364 100644 --- a/tests/relayout_parity_test.cpp +++ b/tests/relayout_parity_test.cpp @@ -9,10 +9,13 @@ * see. Where the kernel has an inverse, it must give the planes back exactly. * * libr4d needs a HIP toolchain to build but its layouts do not, so their host sources are compiled - * into this test (tests/CMakeLists.txt). The n-gram table's hook is libavx's, from the plugin. + * into this test (tests/CMakeLists.txt). The n-gram table's hook is libavx's, from the plugin. One + * test here therefore reaches back into tools/opshapes.cpp: the fallback table sizes the packed + * weights these hooks own, and only this file can hold both sides of that claim. */ #include "quant_fixture.h" #include "r4d_plugin.h" +#include "opshapes.h" #include #include @@ -346,6 +349,87 @@ TEST(mxfp4_codes_exponents_and_the_row_reference) { 0xc35d26b146836d77ull); } +/* tools/opshapes.cpp sizes a packed weight from the kernel's stored form, because no schema states + * an extent and libref declines every grid with a zero point (ref_planes.h joins scale and zero + * into one operand a description cannot state). A stale entry is not a failed check: rad-tune + * allocates what the table says and hands the kernel the short buffer, which is a read past the + * allocation on the card, not a refusal. So the table's byte total and the hook's `bytes` must + * agree. The table's shapes are the tool's own view -- mxfp4's exponents are [K/32][N] there and + * [N][K/32] in the store -- so the totals, not the shapes, are the contract. */ +TEST(the_tool_table_sizes_packed_weights_as_the_kernel_stores_them) { + NEED_LIBQUANT(); + const int64_t N = 128, K = 512, M = 8; + auto check = [&](const char* dtype, int64_t group, const Hooks& hk, + const std::vector& bscale_roles, Opts qo) { + const std::vector w = weight(N, K, 21, 1, group); + const Quantised q = quantise(quantizer("rtn"), qo, "output.weight", N, K, w); + if (q.status != RAD_OK) { + CHECK_EQ(q.status, RAD_OK); + return; + } + Opts kp; + kp.i("N", N).i("K", K); + rad::Geometry g; + g.set_i("M", M); g.set_i("N", N); g.set_i("K", K); g.set_i("group", group); + g.set_s("dtype", dtype); + std::vector tab; + if (rad::rad_operand_shapes("gemm_nt_q", g, 7, M, &tab) != RAD_OK) { + std::fprintf(stderr, " %s: the table refuses the geometry\n", dtype); + CHECK(false); + return; + } + CHECK_EQ((int)tab.size(), 7); + struct P { int operand; size_t opd; std::vector roles; }; + const std::vector

ops = { { B, 2, { "codes" } }, { BSCALE, 3, bscale_roles } }; + for (const P& o : ops) { + const Selection s = select(q, N, K, o.roles); + RadLayout L{}; + CHECK_EQ(hk.layout(kp.data(), kp.n(), o.operand, &q.enc, s.sel.data(), s.t.data(), + (int)s.t.size(), &L), RAD_OK); + const rad::OpdShape& t = tab[o.opd]; + const int64_t got = t.absent ? 0 : rad_dtype_bytes(t.dtype, rad::rad_numel(t.shape)); + if (got != (int64_t)L.bytes) + std::fprintf(stderr, " %s operand %d: the table sizes %lld byte(s), the kernel " + "stores %lld\n", dtype, o.operand, (long long)got, + (long long)L.bytes); + CHECK_EQ(got, (int64_t)L.bytes); + } + }; + { + Opts qo; + qo.s("codes", "u2").s("zero", "u8").i("group", 128).s("scale", "f16"); + check("w2a8", 128, nW2, { "scale", "zero" }, qo); + } + { + Opts qo; + qo.s("codes", "fp4_e2m1").i("group", 32).s("scale", "e8m0"); + check("mxfp4a8", 32, nMx, { "scale" }, qo); + } + /* The guards are the kernel's own: K a whole number of 128-column blocks + * (r4d_layout.cpp refuses a weight whose K is not), N a whole number of 16-row tiles (the + * row's constraint), and the group the stored form has. A geometry the kernel would refuse has + * to be refused here too, or rad-tune would size buffers for a launch that never happens. */ + auto refuses = [&](int64_t n, int64_t k, int64_t group) { + rad::Geometry g; + g.set_i("M", M); g.set_i("N", n); g.set_i("K", k); g.set_i("group", group); + g.set_s("dtype", "w2a8"); + std::vector tab; + CHECK_EQ(rad::rad_operand_shapes("gemm_nt_q", g, 7, M, &tab), RAD_E_UNSUPPORTED); + }; + refuses(128, 500, 128); /* K leaves a partial block */ + refuses(120, 512, 128); /* N leaves a partial tile */ + refuses(128, 512, 64); /* a group the stored form does not have */ + /* The shape the DFlash2 draft head tunes at on a two-rank serve, which the kernel takes. */ + { + rad::Geometry g; + g.set_i("M", M); g.set_i("N", 124160); g.set_i("K", 2560); g.set_i("group", 128); + g.set_s("dtype", "w2a8"); + std::vector tab; + CHECK_EQ(rad::rad_operand_shapes("gemm_nt_q", g, 7, M, &tab), RAD_OK); + CHECK_EQ((int)tab.size(), 7); + } +} + TEST(moe_int4_experts_plain_and_rotated_both_classes) { NEED_LIBQUANT(); const int64_t N = 64, K = 256, N1 = 48, K1 = 128; diff --git a/tests/runtime_test.cpp b/tests/runtime_test.cpp index f315ab6a..9ae3a63c 100644 --- a/tests/runtime_test.cpp +++ b/tests/runtime_test.cpp @@ -996,6 +996,26 @@ TEST(an_op_outside_the_window_on_lane_0_joins_the_second_lane_first) { })); } +/* An op that names no buffer -- a weight read into the cache (prefetch_beside) -- touches nothing the + * window keeps live, so on lane 1 it runs outside the window too (a drafter's reads beside its + * all-reduces come after the trunk's window). */ +TEST(an_op_naming_no_buffer_runs_on_the_second_lane_outside_its_window) { + Fixture f; + f.P.scratch_regions = 2; + rad_weight w = f.add_weight("blk.0.w", RAD_BF16, 8, 4, g_weight_bytes); + rad_op a0 = f.add_op("gemm_nt", "M", { 8192 }, { k_scr_seen0 }, { "s0" }, nullptr, {}); + rad_op a1 = f.add_op("gemm_nt", "M", { 8192 }, { k_scr_seen1 }, { "s1" }, nullptr, { w }); + f.P.lane1_w0 = f.P.lane1_w1 = (int32_t)a0; + CHECK_OK(f.start()); + + CHECK_OK(f.step(4, 0, [&](Ctx& c) { + RadOperand opd[1] = { RAD_W(w) }; + CHECK_OK(c.set_lane(1)); + CHECK_OK(c.issue(a1, opd, 1, RAD_N_BATCH)); + CHECK_OK(c.set_lane(0)); + })); +} + /* Operands are positional (spec §2.3), so a miscount is silent numerical garbage at the kernel, * not a diagnosable failure. The runtime checks the given arity against the schema. */ TEST(operand_arity_is_checked_against_the_schema) { diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 10c32f90..19a406dc 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -5733,8 +5733,8 @@ uint64_t scripted_steps(int64_t max_tok, int64_t interval, int64_t busy, int* n_ TEST(without_a_span_the_scheduler_plans_and_stages_the_pinned_steps) { struct Case { int64_t max_tok, interval, busy; uint64_t want; }; const Case cases[] = { - { 256, 256, -1, 0x17b8231a20db9d46ull }, { 512, 256, -1, 0xe155e72b6a4cc94full }, { 1024, 256, -1, 0x54ba52dac3f4f61cull }, - { 1024, 256, 0, 0x54ba52dac3f4f61cull }, { 1024, 256, 128, 0x3d9cbbf533e3c4b5ull }, { 2048, 512, -1, 0x400205b7b9afcf12ull }, + { 256, 256, -1, 0x9b2fe92b1919355cull }, { 512, 256, -1, 0xdae73489249b5339ull }, { 1024, 256, -1, 0x44975a352e78619aull }, + { 1024, 256, 0, 0x44975a352e78619aull }, { 1024, 256, 128, 0x3c0b9b1a1f864e4aull }, { 2048, 512, -1, 0xd6c184d0563159eeull }, }; for (const Case& c : cases) { int n = 0; diff --git a/tools/opshapes.cpp b/tools/opshapes.cpp index 72769ed7..32953917 100644 --- a/tools/opshapes.cpp +++ b/tools/opshapes.cpp @@ -154,11 +154,15 @@ int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int6 add((uint32_t)RAD_F32, {M, (n + group - 1) / group}); } else if (op == "gemm_nt_q") { - /* Block-scaled fp8 and mxfp4 only. `gemm_nt_q` covers six weight formats whose scale grids - * (per row, per row-group, per output-row-block, e8m0 exponents, zero points, reference - * exponents) belong to the reading kernel, not the schema. The fp8 grid is fixed by the - * checkpoint: E4M3 [N][K] with a bf16 [ceil(N/128)][ceil(K/128)] scale plane, `group` - * being the 128. Other formats are skipped and counted. + /* Block-scaled fp8, mxfp4 and the 2-bit asymmetric grid. `gemm_nt_q` covers six weight + * formats whose scale grids (per row, per row-group, per output-row-block, e8m0 exponents, + * zero points, reference exponents) belong to the reading kernel, not the schema. The fp8 + * grid is fixed by the checkpoint: E4M3 [N][K] with a bf16 [ceil(N/128)][ceil(K/128)] + * scale plane, `group` being the 128. libref describes the symmetric integer grids, so a + * tool takes those from its hook and never reaches this table for them; every grid with a + * zero point is declined there (ref_planes.h joins scale and zero into one operand a + * description cannot state), and the ones named here are sized from the kernel's own + * stored layout instead. Anything else is skipped and counted. * * `a_sum` and `b_ref` belong to the asymmetric-integer and mxfp4 grids. */ const char* q = g.get_s("dtype"); @@ -175,6 +179,24 @@ int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int6 add((uint32_t)RAD_BF16, {M, N}); /* y */ skip_opd(); /* a_sum */ add((uint32_t)RAD_U8, {N}); /* b_ref -- the per-row reference */ + } else if (q && std::strcmp(q, "w2a8") == 0) { + /* The DFlash2 draft head's grid (libr4d/r4d_gemm_w2a8_nt.hip): unsigned 2-bit codes in + * the kernel's fragment order, N*K/4 bytes (`r4d.w2a8.frag.g128`), and one dword per + * row and `group` of K holding that group's f16 scale and integer zero, tile-major, + * N*K/group of them (`r4d.w2a8.sz.g128`) -- both extents owned by + * libr4d/r4d_layout.cpp's r4d_rad_layout_w2a8, which is what sizes the real weight. + * The activation pair and the group sums are quant_act_i8's own outputs above, and the + * grid is asymmetric, so the kernel refuses the case without `a_sum`. `b_ref` is + * mxfp4's. Sizes are the stored bytes; random bytes suffice for timing. */ + if (N <= 0 || K <= 0 || group != 128 || (K % 128) || (N % 16)) + return RAD_E_UNSUPPORTED; + add((uint32_t)RAD_I8, {M, K}); /* a -- int8 codes */ + add((uint32_t)RAD_F32, {M, 1}); /* a_scale -- one f32 per row */ + add((uint32_t)RAD_U8, {N, K / 4}); /* b -- u2 codes, fragment order */ + add((uint32_t)RAD_U32, {N, K / group}); /* b_scale -- scale+zero dwords */ + add((uint32_t)RAD_BF16, {M, N}); /* y */ + add((uint32_t)RAD_F32, {K / group, (M + 15) / 16 * 16}); /* a_sum, group-major */ + skip_opd(); /* b_ref */ } else { const bool a8 = q && std::strcmp(q, "fp8a8") == 0; const bool a16 = q && std::strcmp(q, "fp8a16") == 0; diff --git a/tools/rad_tune.cpp b/tools/rad_tune.cpp index f478b47f..bcb7ede8 100644 --- a/tools/rad_tune.cpp +++ b/tools/rad_tune.cpp @@ -45,8 +45,14 @@ void usage() { " --iters N launches per rep (default 32). One launch is short enough that\n" " launch overhead and clock ramp would otherwise dominate.\n" " --max-tok N the max_tok declare is run at (default 8192)\n" + " --max-seqs N the max_seqs declare is run at (default 256)\n" " --tp N tensor-parallel width to declare at (default 1). The shapes a\n" " sharded deployment runs are not the shapes tp=1 runs.\n" + " --kv-cache-dtype T bf16 (default) or fp8 -- attention bands are gated on it.\n" + " Declare what the served engine runs, or the tune rows will not\n" + " match the bands it selects.\n" + " --tp-wire MODE exact (default) or wht6 -- selects the all-reduce family.\n" + " --tp-wire-min-kb N the message size from which the lossy wire is used.\n" " --num-speculative-tokens N|auto\n" " draft depth to declare at (default auto: the container's own). It puts\n" " the drafter's kernels in the measured graph.\n" @@ -55,9 +61,16 @@ void usage() { " -h, --help\n"); } -/* A device allocation that frees itself, because the timing path has several ways out. */ +/* A device allocation that frees itself, because the timing path has several ways out. Neither + * copyable nor movable: a rank holds a vector of these, and a second handle to the same + * allocation would free the buffer out from under a launch still reading it. */ struct DevBuf { void* p = nullptr; + DevBuf() = default; + DevBuf(const DevBuf&) = delete; + DevBuf& operator=(const DevBuf&) = delete; + DevBuf(DevBuf&&) = delete; + DevBuf& operator=(DevBuf&&) = delete; ~DevBuf() { if (p) rad_dev_free(p, RAD_MEM_DEVICE); } }; @@ -121,37 +134,120 @@ tune_candidates(const RadKernelInfo* k, const Geometry& g, int64_t* space_size, return out; } -/* Every OUT and INOUT operand's bytes after one launch at `g`, which carries the candidate point as - * ordinary parameters. Used to compare a candidate with the defaults. */ -int capture_outputs(const KernelRow& row, std::vector& t, - const Geometry& g, const RadOpSchema* schema, - const std::vector& sh, RadStream stream, - std::vector* out) { - RadArgs a{}; - a.t = t.data(); a.n_t = (int)t.size(); - a.p = g.params(); a.n_p = g.n_params(); - a.rank = 0; a.world_size = 1; - DevBuf scratch; - if (row.info->scratch) { - const int64_t need = row.info->scratch(&a); - if (need > 0) { - scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE); - if (!scratch.p) return RAD_E_NOMEM; - rad_memset_async(scratch.p, 0, need, stream); - a.scratch = scratch.p; - a.scratch_bytes = need; - } - } - if (row.info->launch(&a, stream) < 0) return RAD_E_SHAPE; - if (stream && rad_stream_sync(stream) < 0) return RAD_E_STATE; +/* One rank's side of one candidate's launch: the instance declare made for it, the operands it + * owns on its own card, its scratch, and the stream it runs on. A row that is not a collective + * has exactly one of these, as an engine step's local op does. A collective has one per rank, and + * they are fired together: a rank that launches alone waits for a peer flag nobody raises. + * + * The instance is the reason this exists. init() is what builds the peer bundle -- the scratch and + * the flags and the sequence counters, published to every rank and made peer-accessible -- and + * RadArgs reaches the exchange through nothing else, so a tool that leaves it null cannot form a + * collective's launch at all. Every `ar_*` row used to end here that way: declared tunable + * (nblocks, nthreads, drain, acq), requested by the declared graph, and refused at the entry + * point before a single launch, so the served card ran the axis defaults for every all-reduce. */ +struct Rank { + int rank = 0, world = 1; + void* instance = nullptr; + RadStream stream = nullptr; /* owned by the request's StreamSet */ + std::vector t; /* the operands, as the kernel sees them */ + std::vector buf; /* ...and the allocations behind them */ + std::vector> host; /* the draw, only ever a copy source */ + DevBuf scratch; + int64_t scratch_bytes = 0; +}; +/* Streams die with the request, every way out of it, skips included. */ +struct StreamSet { + std::vector s; + ~StreamSet() { for (RadStream x : s) if (x) rad_stream_destroy(x); } +}; + +/* The RadArgs a rank's launch takes. The candidate's axes ride in `g` exactly as at issue, so the + * kernel reads `sk` with rad_args_geti() like `M`. */ +void fill_args(const KernelRow& row, Rank& r, const Geometry& g, RadArgs* a) { + std::memset(a, 0, sizeof(*a)); + a->t = r.t.data(); a->n_t = (int)r.t.size(); + a->p = g.params(); a->n_p = g.n_params(); + a->instance = r.instance; + a->rank = r.rank; + a->world_size = r.world; + if (r.scratch.p) { a->scratch = r.scratch.p; a->scratch_bytes = r.scratch_bytes; } +} + +/* Every rank's stream drained. A stream's device has to be current to sync it. */ +int sync_all(std::vector& rs) { + int st = RAD_OK; + for (Rank& r : rs) { + if (!r.stream) continue; + if (rad_dev_set(r.rank) < 0) return RAD_E_DEVICE; + if (rad_stream_sync(r.stream) < 0) st = RAD_E_STATE; + } + return st; +} + +/* Scratch zeroed before a candidate starts, outside the timed region: a candidate must not be + * timed -- or judged -- on the leftovers of the one before it. */ +int zero_scratch(std::vector& rs) { + for (Rank& r : rs) { + if (!r.scratch.p) continue; + if (rad_dev_set(r.rank) < 0) return RAD_E_DEVICE; + if (rad_memset_async(r.scratch.p, 0, (uint64_t)r.scratch_bytes, r.stream) < 0) + return RAD_E_STATE; + } + return RAD_OK; +} + +/* `iters` launches on every rank, from one thread each: the exchange only pipelines once both + * cards have work queued, so enqueuing rank 1's whole batch after rank 0's would charge every + * iteration for the enqueue of the batch, not just the first. + * + * A refusal comes back before anything is waited on. It is symmetric by construction -- every + * rank resolved the same kernel for the same geometry, and the launch's checks read only the + * geometry and the instance -- so a refusal means no rank queued work and there is nothing to + * drain. Were it ever asymmetric, the peers would be left spinning on a flag; that is why the + * caller treats any refusal as fatal for the candidate instead of retrying it. */ +int launch_all(const KernelRow& row, std::vector& rs, const Geometry& g, int iters) { + std::vector st(rs.size(), (int)RAD_E_STATE); + std::vector th; + th.reserve(rs.size()); + for (size_t i = 0; i < rs.size(); ++i) + th.emplace_back([&, i] { + Rank& r = rs[i]; + if (rad_dev_set(r.rank) < 0) { st[i] = RAD_E_DEVICE; return; } + RadArgs a; + fill_args(row, r, g, &a); + for (int k = 0; k < iters; ++k) { + const int s = row.info->launch(&a, r.stream); + if (s < 0) { st[i] = s; return; } + } + st[i] = RAD_OK; + }); + for (std::thread& t : th) t.join(); + for (int s : st) if (s < 0) return s; + return RAD_OK; +} + +/* Rank 0's OUT and INOUT bytes after one launch at `g`, which carries the candidate point as + * ordinary parameters. Every candidate saw the same bytes on every rank, so a variant that + * reorders a reduction, drops a peer's term, or writes the wrong slice differs from the defaults + * here. */ +int capture_outputs(const KernelRow& row, std::vector& rs, const Geometry& g, + const RadOpSchema* schema, const std::vector& sh, + std::vector* out) { + if (const int z = zero_scratch(rs)) return z; + const int w = launch_all(row, rs, g, 1); + if (w < 0) return w; + if (const int s = sync_all(rs)) return s; + + Rank& r = rs[0]; + if (rad_dev_set(r.rank) < 0) return RAD_E_DEVICE; /* Size the destination before copying: growing it between async copies would reallocate it * under copies still in flight. */ size_t total = 0; for (size_t k = 0; k < sh.size() && k < (size_t)schema->n_operands; ++k) { const int role = schema->operands[k].role; if (role != RAD_OPD_OUT && role != RAD_OPD_INOUT) continue; - if (!t[k].data) continue; + if (!r.t[k].data) continue; const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape)); if (bytes > 0) total += (size_t)bytes; } @@ -160,13 +256,14 @@ int capture_outputs(const KernelRow& row, std::vector& t, for (size_t k = 0; k < sh.size() && k < (size_t)schema->n_operands; ++k) { const int role = schema->operands[k].role; if (role != RAD_OPD_OUT && role != RAD_OPD_INOUT) continue; - if (!t[k].data) continue; + if (!r.t[k].data) continue; const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape)); if (bytes <= 0) continue; - if (rad_memcpy_async(out->data() + at, t[k].data, bytes, stream) < 0) return RAD_E_STATE; + if (rad_memcpy_async(out->data() + at, r.t[k].data, bytes, r.stream) < 0) + return RAD_E_STATE; at += (size_t)bytes; } - if (stream && rad_stream_sync(stream) < 0) return RAD_E_STATE; + if (rad_stream_sync(r.stream) < 0) return RAD_E_STATE; return RAD_OK; } @@ -203,43 +300,30 @@ double max_rel_diff(const std::vector& a, const std::vector& b return worst; } -/* Median microseconds per launch at `g` (which carries the candidate point). Negative means the - * kernel refused the shape at its entry point (spec 2.1), which is allowed: tune_valid prunes only - * what the geometry alone can rule out. */ -double time_point(const KernelRow& row, std::vector& t, - const Geometry& g, int reps, int iters, - RadStream stream, double* spread_pct) { - RadArgs a{}; - a.t = t.data(); a.n_t = (int)t.size(); - a.p = g.params(); a.n_p = g.n_params(); - a.rank = 0; a.world_size = 1; - /* Scratch must be device memory: e.g. a split-K GEMM writes its partial planes there. */ - DevBuf scratch; - if (row.info->scratch) { - const int64_t need = row.info->scratch(&a); - if (need > 0) { - scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE); - if (!scratch.p) return (double)RAD_E_NOMEM; - rad_memset_async(scratch.p, 0, need, stream); - a.scratch = scratch.p; - a.scratch_bytes = need; - } - } +/* Median microseconds per iteration at `g` (which carries the candidate point): the wall time of + * `iters` launches on every rank, from the first launch to the last stream drained. Negative + * means the kernel refused the shape at its entry point (spec 2.1), which is allowed: tune_valid + * prunes only what the geometry alone can rule out. + * + * The clock stops only after the devices finish: launches are asynchronous, so without the sync + * this would time host submission. For a collective that is doubly true -- the exchange's cost is + * the wait for the peer, and the wait happens on the card, so a rank timed alone would report a + * local copy. */ +double time_point(const KernelRow& row, std::vector& rs, const Geometry& g, + int reps, int iters, double* spread_pct) { + if (const int z = zero_scratch(rs)) return (double)z; /* A warm-up launch; its status decides whether this candidate serves the shape at all. */ - const int s = row.info->launch(&a, stream); - if (s < 0) return (double)s; - if (stream && rad_stream_sync(stream) < 0) return (double)RAD_E_STATE; + const int w = launch_all(row, rs, g, 1); + if (w < 0) return (double)w; + if (const int s = sync_all(rs)) return (double)s; - /* Stop the clock only after the device finishes: launches are asynchronous, so without the - * sync this would time host submission only. */ std::vector us; us.reserve((size_t)reps); for (int r = 0; r < reps; ++r) { const auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < iters; ++i) - if (row.info->launch(&a, stream) < 0) return (double)RAD_E_SHAPE; - if (stream && rad_stream_sync(stream) < 0) return (double)RAD_E_STATE; + if (const int s = launch_all(row, rs, g, iters)) return (double)s; + if (const int s = sync_all(rs)) return (double)s; const auto t1 = std::chrono::steady_clock::now(); us.push_back(std::chrono::duration(t1 - t0).count() / iters); } @@ -257,7 +341,11 @@ int main(int argc, char** argv) { std::vector hierarchy = rad_hierarchy_from_env(); int reps = 5, iters = 32; int64_t max_tok = 8192; + int64_t max_seqs = 256; int tp = 1, spec = -1; /* -1 = the container's own drafter depth */ + int kv_dtype = RAD_DT_INVALID; /* RAD_F8E4M3 = the engine's --kv-cache-dtype fp8 */ + int wire_lossy = 0; /* the engine's --tp-wire wht6 */ + int64_t wire_min_kb = 128; /* the engine's --tp-wire-min-kb */ bool dry = false, verbose = false; for (int i = 1; i < argc; ++i) { @@ -279,7 +367,24 @@ int main(int argc, char** argv) { else if (a == "--reps") reps = (int)num("--reps", 1, INT32_MAX); else if (a == "--iters") iters = (int)num("--iters", 1, INT32_MAX); else if (a == "--max-tok") max_tok = num("--max-tok", 1, INT64_MAX); + else if (a == "--max-seqs") max_seqs = num("--max-seqs", 1, INT64_MAX); else if (a == "--tp") tp = (int)num("--tp", 1, INT32_MAX); + else if (a == "--kv-cache-dtype") { + const char* v = next("--kv-cache-dtype"); + if (!std::strcmp(v, "fp8")) kv_dtype = RAD_F8E4M3; + else if (!std::strcmp(v, "bf16")) kv_dtype = RAD_DT_INVALID; + else { std::fprintf(stderr, "rad-tune: --kv-cache-dtype: '%s' is not one of " + "bf16, fp8 (the tuner tunes the bands it declares; other " + "encodings are the engine's)\n", v); return 2; } + } + else if (a == "--tp-wire") { + const char* v = next("--tp-wire"); + if (!std::strcmp(v, "wht6")) wire_lossy = 1; + else if (!std::strcmp(v, "exact")) wire_lossy = 0; + else { std::fprintf(stderr, "rad-tune: --tp-wire: '%s' is not one of exact, wht6\n", + v); return 2; } + } + else if (a == "--tp-wire-min-kb") wire_min_kb = num("--tp-wire-min-kb", 0, INT64_MAX); else if (a == "--num-speculative-tokens") { /* `auto` is the container's own depth, as the engine's flag of this name reads it. */ const char* v = next("--num-speculative-tokens"); @@ -332,17 +437,44 @@ int main(int argc, char** argv) { * the speculative depth decides whether the drafter (and its shapes) is in the graph. */ RadBuildCtx ctx{}; ctx.rank = 0; ctx.world_size = tp; ctx.max_tok = max_tok; + ctx.max_seqs = max_seqs; + ctx.tp_wire_lossy = wire_lossy; + ctx.tp_wire_min_bytes = wire_min_kb * 1024; + ctx.kv_dtype = kv_dtype; RadArchProbe probe{}; (void)rad_tools_probe(plugins, meta, &probe); ctx.max_spec = spec >= 0 ? spec : probe.draft_depth; - ctx.max_seqs = 256; ctx.max_ctx = meta.n_ctx_train; ctx.scope = ""; + ctx.max_seqs = max_seqs; ctx.max_ctx = meta.n_ctx_train; ctx.scope = ""; + + /* Peer access, measured before selection, as Engine does: collectives constrain device.p2p + * (abi/rad_types.h), and with the fact unset neither the peer-to-peer row nor its host-memory + * twin can match, so every collective resolves to nothing -- silently, with no tune request + * for it ever reaching the loop below. Every ordered pair is asked, since access is granted + * one way at a time. */ + long long p2p = 1; + for (int i = 0; i < tp; ++i) + for (int j = 0; j < tp; ++j) { + if (i == j) continue; + const int a = rad_dev_peer_access(i, j); + if (a < 0) { + std::fprintf(stderr, "rad-tune: could not ask whether card %d can reach card %d's " + "memory: %s\n", i, j, rad_dev_last_error()); + return 1; + } + if (a == 0) p2p = 0; + } + rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p); + const char* p2p_note = p2p ? "peer to peer" : "the collectives run through pinned host memory"; /* Every rank declares concurrently on its own thread and device, as Engine does: kernel init() - * runs from declare, and a collective's init is a rendezvous (libr4d's all-reduce waits for - * its peers), so declaring rank 0 alone would hang. Only rank 0's program is measured. */ - Program prog; + * runs from declare, and a collective's init is a rendezvous (libr4d's all-reduce waits for its + * peers), so declaring rank 0 alone would hang. + * + * All the programs stay alive, not only rank 0's. A collective's launch needs the instance each + * rank's own declare made, and an instance is reachable only through the program that declared + * it, so rank 0's program is the one measured while the others supply the peers. */ + std::vector progs((size_t)tp); { - std::vector progs((size_t)tp); std::vector st((size_t)tp, 0); std::vector th; for (int ri = 0; ri < tp; ++ri) { @@ -362,7 +494,16 @@ int main(int argc, char** argv) { for (auto& t : th) t.join(); if (tp > 1) rad_dev_set(0); for (int ri = 0; ri < tp; ++ri) if (st[(size_t)ri] < 0) return 1; - prog = std::move(progs[0]); + } + Program& prog = progs[0]; + + /* Name what resolved to nothing, so a hole is a printed line instead of a tune request that + * never appears: the engine's declare counts the misses, and this is the count's detail. */ + if (!prog.misses.empty()) { + RadDeviceProps dp{}; + const bool host_backend = rad_dev_props(0, &dp) >= 0 && dp.is_host_backend; + for (const Program::Miss* m : prog.device_holes(host_backend)) + std::printf(" unresolved %s\n", m->line().c_str()); } if (machine.empty()) machine = rad_machine_key(); @@ -378,6 +519,7 @@ int main(int argc, char** argv) { std::printf("rad-tune %s\n", model.c_str()); std::printf(" machine %s\n", machine.c_str()); + if (tp > 1) std::printf(" p2p %s\n", p2p_note); std::printf(" cache %s (%zu existing row(s))\n", src.c_str(), before); std::printf(" requests %zu (kernel, shape) pair(s) the declared graph reaches\n\n", prog.tune_requests.size()); @@ -393,14 +535,6 @@ int main(int argc, char** argv) { int measured = 0, skipped = 0, single = 0; std::map skip_why; - /* One explicit stream for the run; timing on the null stream would measure host submission. - * Without ROCm the device layer is a synchronous host stub, so the same path works. */ - RadStream stream = nullptr; - if (rad_stream_create(&stream, 0) < 0) { - std::fprintf(stderr, "rad-tune: could not create a stream: %s\n", rad_dev_last_error()); - return 1; - } - for (const Program::TuneRequest& tr : prog.tune_requests) { const KernelRow* row = row_for(tr.plugin, tr.kernel); if (!row || !row->info || !row->info->launch) { @@ -480,31 +614,118 @@ int main(int argc, char** argv) { } const int64_t vocab_rows = kf_vocab_rows(kop); - /* One set of device buffers shared by all candidates, so they all see the same bytes. - * `store` is the host-side draw, only ever a copy source; RadTensor::data must be the - * device allocation (a host address would fail silently). */ - std::vector> store(sh.size()); - std::vector dev(sh.size()); - std::vector t(sh.size()); + /* One set of operands per rank that takes part. A collective's ranks each contribute their + * own bytes on their own card -- peers write into each other's scratch, never into each + * other's input -- so rank 1's x has to be its own allocation, and each rank needs the + * instance its own declare made. Ranks draw different bytes on purpose: a fold of two + * identical halves would let a kernel that read its own contribution twice pass. + * + * `rs` is sized up front and never grown: DevBuf frees what it points at, so moving one + * into new storage would leave the old handle to free the buffer as well. */ + const int world = row->collective && tp > 1 ? tp : 1; + std::string scale; + if (world > 1) scale = ", " + std::to_string(world) + " ranks"; + std::vector rs((size_t)world); + StreamSet streams; bool ok = true; - for (size_t k = 0; k < sh.size() && ok; ++k) { - const int64_t n = rad_numel(sh[k].shape); - const int64_t bytes = rad_dtype_bytes(sh[k].dtype, n); - if (bytes <= 0) { ok = false; break; } - kf_draw(kop, k, M, vocab_rows, rad_case_seed(1, op, 0, row->info->domain, (int)k), - &store[k]); - dev[k].p = rad_dev_alloc(bytes, RAD_MEM_DEVICE); - if (!dev[k].p) { ok = false; break; } - if (rad_memcpy_async(dev[k].p, store[k].data(), bytes, stream) < 0) { ok = false; break; } - t[k].data = dev[k].p; - t[k].dtype = sh[k].dtype; - t[k].rank = (uint32_t)sh[k].shape.size(); - for (size_t d = 0; d < sh[k].shape.size() && d < RAD_MAX_RANK; ++d) - t[k].shape[d] = sh[k].shape[d]; - rad_tensor_pack(&t[k]); + for (int ri = 0; ri < world && ok; ++ri) { + Rank& r = rs[(size_t)ri]; + r.rank = ri; r.world = world; + /* The instance is found by the key the cache uses, not by position: a rank that + * resolved a different kernel for this band has no peer to exchange with. A + * collective cannot launch without it; a plain kernel has none, and null is exactly + * what its launch expects. */ + const Program::TuneRequest* q = &tr; + if (ri > 0) { + q = nullptr; + for (const auto& p : progs[(size_t)ri].tune_requests) + if (p.kernel == tr.kernel && p.plugin == tr.plugin && + p.geom_key == tr.geom_key) { q = &p; break; } + } + if (world > 1 && (!q || !q->instance)) { + skip_why[op + " (rank " + std::to_string(ri) + " declared no instance for this " + "instantiation: no exchange to launch)"]++; + ++skipped; ok = false; break; + } + r.instance = q ? q->instance : nullptr; + if (rad_dev_set(ri) < 0) { + skip_why[op + " (no device to put rank " + std::to_string(ri) + " on)"]++; + ++skipped; ok = false; break; + } + /* An explicit stream per rank; timing on the null stream would measure host + * submission. Without ROCm the device layer is a synchronous host stub, and the + * same path still works. */ + RadStream s = nullptr; + if (rad_stream_create(&s, 0) < 0) { + std::fprintf(stderr, "rad-tune: could not create a stream for rank %d: %s\n", ri, + rad_dev_last_error()); + return 1; + } + streams.s.push_back(s); + r.stream = s; + /* Inputs come from kf_draw, the same draw rad-kbench checks with, so each operand + * stays in the domain its recipe states (constant `seqused`, cumulative lengths, + * distinct scatter destinations, in-range block tables). */ + r.host.resize(sh.size()); + r.buf = std::vector(sh.size()); + r.t = std::vector(sh.size()); + for (size_t k = 0; k < sh.size(); ++k) { + /* An absent operand (attn's descales and cu_seqlens) is a zeroed tensor: no + * draw, no allocation, data null -- what kbench passes and the kernel checks. */ + if (sh[k].absent) continue; + const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape)); + if (bytes <= 0) { + skip_why[op + " (an operand has a plugin-private dtype the core cannot " + "size)"]++; + ++skipped; ok = false; break; + } + kf_draw(kop, k, M, vocab_rows, + rad_case_seed(1, op, ri, row->info->domain, (int)k), &r.host[k]); + r.buf[k].p = rad_dev_alloc(bytes, RAD_MEM_DEVICE); + if (!r.buf[k].p) { + skip_why[op + " (no device memory for an operand on rank " + + std::to_string(ri) + ")"]++; + ++skipped; ok = false; break; + } + if (rad_memcpy_async(r.buf[k].p, r.host[k].data(), bytes, r.stream) < 0) { + skip_why[op + " (the operands would not copy onto rank " + + std::to_string(ri) + ")"]++; + ++skipped; ok = false; break; + } + /* RadTensor::data must be the device allocation; a host address fails silently. */ + RadTensor& t = r.t[k]; + t = RadTensor{}; + t.data = r.buf[k].p; + t.dtype = sh[k].dtype; + t.rank = (uint32_t)sh[k].shape.size(); + for (size_t d = 0; d < sh[k].shape.size() && d < RAD_MAX_RANK; ++d) + t.shape[d] = sh[k].shape[d]; + rad_tensor_pack(&t); + } } - if (!ok) { skip_why[op + " (an operand has a plugin-private dtype the core cannot " - "size)"]++; ++skipped; continue; } + /* Scratch sized from each rank's own arguments: a split kernel writes its partials to + * device memory, and every card needs its own. */ + if (ok && row->info->scratch) { + for (Rank& r : rs) { + if (rad_dev_set(r.rank) < 0) { + skip_why[op + " (no device to size scratch on for rank " + + std::to_string(r.rank) + ")"]++; + ++skipped; ok = false; break; + } + RadArgs a; + fill_args(*row, r, tr.geom, &a); + const int64_t need = row->info->scratch(&a); + if (need <= 0) continue; + r.scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE); + if (!r.scratch.p) { + skip_why[op + " (no device memory for the scratch it asks for)"]++; + ++skipped; ok = false; break; + } + r.scratch_bytes = need; + } + } + if (!ok) continue; /* the reason is already counted */ + if (world > 1) rad_dev_set(0); /* One geometry per candidate, built up front. As at issue, the chosen values are appended * to the resolved geometry, so a launch reads `sk` via rad_args_geti() like `M`. */ @@ -518,7 +739,7 @@ int main(int argc, char** argv) { std::vector best_us((size_t)n_var, -1.0), spread((size_t)n_var, 0.0); for (int v = 0; v < n_var; ++v) { double sp = 0; - best_us[(size_t)v] = time_point(*row, t, gv[(size_t)v], reps, iters, stream, &sp); + best_us[(size_t)v] = time_point(*row, rs, gv[(size_t)v], reps, iters, &sp); spread[(size_t)v] = sp; } @@ -530,7 +751,7 @@ int main(int argc, char** argv) { * kVariantTol allows the last-bit changes of a reordered reduction. */ std::vector ref; std::vector verr((size_t)n_var, 0.0); - if (best_us[0] <= 0 || capture_outputs(*row, t, gv[0], schema, sh, stream, &ref) < 0) { + if (best_us[0] <= 0 || capture_outputs(*row, rs, gv[0], schema, sh, &ref) < 0) { skip_why[tr.plugin + "/" + tr.kernel + " (the defaults refused the shape: no " "reference to check candidates against)"]++; ++skipped; @@ -539,7 +760,7 @@ int main(int argc, char** argv) { for (int v = 1; v < n_var; ++v) { if (best_us[(size_t)v] <= 0) continue; std::vector got; - if (capture_outputs(*row, t, gv[(size_t)v], schema, sh, stream, &got) < 0) { + if (capture_outputs(*row, rs, gv[(size_t)v], schema, sh, &got) < 0) { best_us[(size_t)v] = (double)RAD_E_STATE; continue; } @@ -589,8 +810,9 @@ int main(int argc, char** argv) { cache.put(tr_out); ++measured; - std::printf(" %-22s %-46s %-28s %9.3f us (%d of %lld)\n", op.c_str(), - tr.geom.str().c_str(), wname.c_str(), tr_out.us, n_var, (long long)space); + std::printf(" %-22s %-46s %-28s %9.3f us (%d of %lld%s)\n", op.c_str(), + tr.geom.str().c_str(), wname.c_str(), tr_out.us, n_var, (long long)space, + scale.c_str()); } if (dry) { @@ -607,8 +829,6 @@ int main(int argc, char** argv) { std::printf("\n%d request(s) had one point or none: nothing to choose, and the kernel's\n" "own axis defaults are already what it runs.\n", single); - rad_stream_destroy(stream); - cache.set_machine(machine); if (cache.save(save_home) < 0) return 1;