diff --git a/README.md b/README.md index f88b4648..f18fcb0d 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ prefix-cache tiers: | model | flags | |---|---| | Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | +| Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | | Qwen3.8-27B FP8, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` | | Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` | | MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` | @@ -93,6 +94,14 @@ sequence holds its own recurrent state and 32 of them leave the attention cache keeps the 200K request and costs single-stream decode about 15%) and the 27B in bf16. See [`docs/GUIDE.md`](docs/GUIDE.md) §4.4. +`--tp 4` runs the unfused all-reduce chain, so it is slower per step than `--tp 2` on the same +cards (unmeasured) — it is a capacity configuration, not a speed one, and it takes no `--tp-wire`: +`wht6` is a two-rank wire and four ranks run the exact one. The tiering flags above are the tp2 +recipe carried over, and at four ranks a rank owns a quarter of the experts WHOLE instead of half +the width of every one, so the resident expert bytes per rank are smaller and the elastic window +is a different shape: read the boot log's `elastic` line and re-derive `--expert-vs-cache-ratio` +and `--host-pool-mib` before trusting them. + Add `--api-key KEY` to require `Authorization: Bearer KEY`. Add `--debug-graph` to print every op and the kernel it resolved to, then exit without serving. Then: diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index cf96d903..01997a18 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -570,6 +570,12 @@ struct Geom { int64_t n_head_kv = 0; /* per rank */ int64_t n_head_all = 0; int64_t n_head_kv_all = 0; + /* THIS RANK'S FIRST KV ROW inside the checkpoint's UNSHARDED k/v projection rows, used only + * when the KV heads are replicated over ranks instead of split (world > n_head_kv_all, see + * geom_from). It is in container rows, the same unit a LinearFP8 span takes, so a block that + * declares a row-sharded k/v passes it straight through as `span_lo`. Zero on every split + * deployment, which is what keeps TP2 reading the projection exactly as it always did. */ + int64_t kv_off = 0; int64_t n_ff = 0; /* per rank */ int64_t n_ff_all = 0; int64_t max_tok = 0; @@ -760,10 +766,38 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c, int s; if ((s = divide_or_fail(g.n_head_all, g.world, "n_head", &g.n_head)) < 0) return s; - /* A world size larger than n_head_kv would need the KV heads replicated across ranks rather - * than split, which is a different attention declaration and not a rounding decision. Refuse - * it here rather than have the block quietly produce a zero-width KV projection. */ - if ((s = divide_or_fail(g.n_head_kv_all, g.world, "n_head_kv", &g.n_head_kv)) < 0) return s; + /* THE KV HEADS ARE REPLICATED WHEN THERE ARE NOT ENOUGH TO SPLIT. There is one row-span per KV + * head and no way to hand four ranks half a head, so `divide_or_fail` on n_head_kv is the + * wrong verb once world exceeds the head count -- the question is not rounding, it is whether + * the declaration is allowed to say one KV head per rank. It is, when world is a multiple of + * the KV head count: query heads 0-11 belong to KV head 0 and 12-23 to KV head 1, so ranks + * {0,1} need only KV head 0 and ranks {2,3} only KV head 1. Each rank then declares + * n_head_kv 1 and reads its own head's row-span of k/v, which `kv_off` locates; the attention + * declaration comes out at gqa 6 over a page of 4 instead of gqa 12 over a page of 2, and + * kv_dim(), gqa() and every block that reads them need no new branch because from here down a + * replicated rank and a split rank look the same. + * + * THE COST IS HONEST AND IT IS MEMORY, NOT MATH: the replicating ranks hold BYTE-IDENTICAL KV + * weights, a replicated read that costs no extra VRAM per rank versus the TP2 split it + * replaces (Flash-Next: 2 KV heads x 5120 x 256 rows read twice instead of once). What it buys + * is that world 4 is declarable at all. + * + * When world <= n_head_kv_all the split below is untouched: TP2 stays byte-identical, the + * geometry paro is served on cannot regress. */ + if (g.world > g.n_head_kv_all) { + if (g.world % g.n_head_kv_all != 0) { + fprintf(stderr, "radiance: world_size = %d cannot replicate n_head_kv = %lld; " + "replication needs world to be a multiple of the KV head count\n", + g.world, (long long)g.n_head_kv_all); + return RAD_E_INVAL; + } + g.n_head_kv = 1; /* world / n_head_kv_all ranks share each KV head */ + g.kv_off = (g.rank / (g.world / g.n_head_kv_all)) * g.head_dim; + } else if ((s = divide_or_fail(g.n_head_kv_all, g.world, "n_head_kv", &g.n_head_kv)) < 0) { + return s; + } else { + g.kv_off = 0; /* a split rank reads the rows the plain row-shard already gives it */ + } if ((s = divide_or_fail(g.n_ff_all, g.world, "n_ff", &g.n_ff)) < 0) return s; /* THE VOCABULARY IS SPLIT. r4d_sample_topk_f32 takes a vocabulary offset and packs its * candidates as (u32 GLOBAL id, f32 logit) pairs, and the all-gather places every rank's diff --git a/arch/common/rad_block_attn_fp8.h b/arch/common/rad_block_attn_fp8.h index 935c01ed..121d0364 100644 --- a/arch/common/rad_block_attn_fp8.h +++ b/arch/common/rad_block_attn_fp8.h @@ -99,6 +99,17 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r return RAD_E_INVAL; } + /* NO KV-HEAD REPLICATION HERE. The fused [q|k|v] row-shards by head with the plain even shard, + * so above the KV head count a rank would get a slice of one KV head and declare fine while + * reading the wrong rows. rad_block_attn_gated.h refuses for the same reason; the block that + * plumbs geom_from's `kv_off` is rad_block_attn_gated_fp8.h. */ + if (g.world > g.n_head_kv_all) { + fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d " + "with n_head_kv = %lld.\n", __func__, g.world, + (long long)g.n_head_kv_all); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm)); w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); diff --git a/arch/common/rad_block_attn_gated.h b/arch/common/rad_block_attn_gated.h index d59bde61..cb5c04f0 100644 --- a/arch/common/rad_block_attn_gated.h +++ b/arch/common/rad_block_attn_gated.h @@ -103,6 +103,21 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in return RAD_E_INVAL; } + /* KV-HEAD REPLICATION IS NOT PLUMBLED HERE. `geom_from` answers a world size above the KV head + * count by giving every rank ONE kv head and a `kv_off` row span into a projection that stays + * `n_head_kv_all * head_dim` rows in the container -- and this block declares its k and v with + * the plain even row-shard, which at four ranks would hand a rank half of one KV head. The + * shapes would declare, the numbers would be wrong, and the text would be fluent. Refuse by + * name instead: rad_block_attn_gated_fp8.h is the block that passes the span, and a bf16 model + * that needs TP4 plumbs it the same way. */ + if (g.world > g.n_head_kv_all) { + fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d " + "with n_head_kv = %lld; the KV-head replication in geom_from needs the " + "span passed to its k/v weights.\n", __func__, g.world, + (long long)g.n_head_kv_all); + return RAD_E_UNSUPPORTED; + } + /* ---- weights. Shapes are [out, in]: gemm_nt is A[M,K] times B transposed [N,K], the layout * every transformer weight already has, so nothing is transposed at load. * diff --git a/arch/common/rad_block_attn_gated_fp8.h b/arch/common/rad_block_attn_gated_fp8.h index 16d8945e..0fe5282a 100644 --- a/arch/common/rad_block_attn_gated_fp8.h +++ b/arch/common/rad_block_attn_gated_fp8.h @@ -180,6 +180,22 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int const int64_t kv_dim = g.kv_dim(); const int64_t qg_dim = 2 * q_dim; + /* THE KV ROW SPAN, AND IT ONLY EXISTS ABOVE THE KV HEAD COUNT. + * A world size larger than `n_head_kv_all` cannot divide the KV heads, so rad_arch.h's + * `geom_from` replicates them in PAIRS: two ranks serve the same head, `g.n_head_kv` is 1 on + * each, and the checkpoint entry they both read is still `n_head_kv_all * head_dim` rows -- 512 + * for 2 KV heads at head_dim 256. This rank wants ONE head's row-span of that entry, which the + * even shard would cut up instead (at 4 ranks it would hand rank 2 rows [256, 384), half of one + * head), so the span `[g.kv_off, g.kv_off + kv_dim)` is declared in the CONTAINER's unsharded + * units -- [0, 256) on ranks 0 and 1, [256, 512) on ranks 2 and 3 -- and the scale plane takes + * the same span in 128-blocks. `kv_off` is a multiple of head_dim, so it is whole blocks and + * never cuts one, and share.cpp's `shard_hi <= cpart` holds with cpart = 512 / 1 part. + * AT WORLD <= n_head_kv_all the ordinary even shard already selects exactly these rows, so the + * span stays 0/0 and the default path runs as before -- TP2 declares identically. */ + const bool kv_spanned = g.world > g.n_head_kv_all; + const int64_t kv_span_lo = kv_spanned ? g.kv_off : 0; + const int64_t kv_span_hi = kv_spanned ? g.kv_off + kv_dim : 0; + if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) { fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n", (long long)n_rot, (long long)g.head_dim); @@ -221,9 +237,11 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int RAD_ARCH_TRY(qg.declare(b, nm, g, nm.f("blk.%d.attn_qg", l), qg_dim, g.n_embd, RAD_SHARD_ROW, grp_layer(l), { src.qg }, w.h, w.qg)); RAD_ARCH_TRY(kp.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd, - RAD_SHARD_ROW, grp_layer(l), { src.k }, w.h, w.k)); + RAD_SHARD_ROW, grp_layer(l), { src.k }, w.h, w.k, + 0, {}, kv_span_lo, kv_span_hi)); RAD_ARCH_TRY(vp.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd, - RAD_SHARD_ROW, grp_layer(l), { src.v }, w.h, w.v)); + RAD_SHARD_ROW, grp_layer(l), { src.v }, w.h, w.v, + 0, {}, kv_span_lo, kv_span_hi)); /* THE FUSED PROLOGUE, AND IT IS A PROBE: the four ops below are declared either way and are * what runs when nothing serves this one. rad_block_attn_gated.h does not make the probe, diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index 5123c29c..47133651 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -479,26 +479,31 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c g.w_bf16 = mc.expert_bf16 != 0; /* ...and the connections in front of the blocks emit no codes, since nothing reads any. */ m.hccfg.quant = g.w_bf16 ? 0 : 1; - /* ============================== EVERY RANK HOLDS A SLICE OF EVERY EXPERT ============================== + /* ================= THE RANKS EITHER SLICE EVERY EXPERT, OR OWN WHOLE ONES ================= * * An expert of this model is 640 columns, five 128-column blocks -- the fp8 scale block, * the 4-bit plane's scale group and the rotation's width all at once -- so two ranks - * cannot halve one. Each rank takes three blocks of the experts of one parity and two of - * the other's: rank r's slice of expert e is the first three blocks when e % 2 == r and - * the last two otherwise (MoeFP8::Config::ff_lo says why by parity). The router stays - * replicated, every rank computes its slice of every routed expert, and the block's - * all-reduce sums the partials. + * cannot halve one. * - * WHY NOT EXPERT PARALLELISM, which splits the EXPERTS: rank r owns [r*E/W, (r+1)*E/W) - * whole. The bytes a rank reads are the same on average either way, but which rank a - * routed expert lands on is a coin flip, and a verify step's forty routed slots leave one - * rank about five experts ahead -- which the all-reduce turns into the other rank waiting, - * about a millisecond a step at one sequence. Split by parity the ranks differ by a fifth - * of an expert per unit of the even/odd difference instead. + * AT TWO RANKS EVERY EXPERT IS SLICED BY PARITY: each rank takes three blocks of the + * experts of one parity and two of the other's -- rank r's slice of expert e is the first + * three blocks when e % 2 == r and the last two otherwise (MoeFP8::Config::ff_lo says why + * by parity). The router stays replicated, every rank computes its slice of every routed + * expert, and the block's all-reduce sums the partials. * - * A width that divides into whole blocks at the rank count is split evenly and has one - * slice; five blocks at more than two ranks would need more slices than two parities, and - * is refused by name. + * ABOVE TWO RANKS THE RANKS OWN WHOLE EXPERTS: rank r owns [r*E/W, (r+1)*E/W). A width + * that divides into whole blocks at the rank count is still split evenly and has one + * slice, but five blocks cannot be cut into four even whole-block slices, and the parity + * trick is by construction a two-rank rule. So the block's all-reduce sums whole-expert + * partials instead. + * + * THE TRADE IS ROUTING BALANCE FOR A WORKING TP4. The bytes a rank reads are the same on + * average either way, but which rank a routed expert lands on is a coin flip, and a verify + * step's forty routed slots leave one rank about five experts ahead -- which the all-reduce + * turns into the other ranks waiting, about a millisecond a step at one sequence. Split by + * parity the ranks differ by a fifth of an expert per unit of the even/odd difference + * instead. This is correctness-first v1: the follow-up is a 4-way block split, an + * ff_lo[4]/ff_hi[4] generalising the parity tables, which keeps that balance at four. * * A CALIBRATION RUN SPLITS THE EXPERTS INSTEAD, whole experts per rank. The down * projection's Hessian is over an expert's whole K, and a rank holding a slice of each @@ -510,16 +515,28 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * is two row ranges and a column range of the container, which the file tier cannot read * as one run, and nothing about bf16 needs the parity split's balance -- a bf16 model is * served to calibrate and to compare, not for its decode rate. */ - if (g.world > 1 && (mc.calib || mc.expert_bf16)) { + if (g.world > 2 || (g.world > 1 && (mc.calib || mc.expert_bf16))) { int s; int64_t per = 0; if ((s = divide_or_fail(mc.n_expert_all, g.world, "expert_count", &per)) < 0) return s; mc.n_ff_exp = g.n_ff_all; mc.n_expert = per; mc.expert_base = (int64_t)g.rank * per; + /* WHY this run owns whole experts: whichever of the three reasons applies. The parity + * case says so by the block count, because that is the number that refuses the split. */ + char why[192]; + if (mc.calib) + snprintf(why, sizeof why, + "calibration (each expert's Hessian is over its whole width)"); + else if (mc.expert_bf16) + snprintf(why, sizeof why, "bf16 experts"); + else + snprintf(why, sizeof why, + "%lld blocks of %d split %d ways are not whole blocks, so the ranks own " + "whole experts", (long long)(g.n_ff_all / RAD_FP8_BLOCK), + RAD_FP8_BLOCK, g.world); rad_note(b, "%s: rank %d owns experts [%lld, %lld) of %lld whole.", - mc.calib ? "calibration (each expert's Hessian is over its whole width)" - : "bf16 experts", g.rank, + why, g.rank, (long long)mc.expert_base, (long long)(mc.expert_base + mc.n_expert), (long long)mc.n_expert_all); } else if (g.world > 1) { diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index e68ee8f4..1e3a15e8 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -286,15 +286,53 @@ block), the router, `shared_expert_gate` and `embed_tokens` stay bf16. ten protected experts left bf16, int8 block linears and lm_head, E4M3 mixing and MTP fc matrices, and the n-gram table at one fixed E4M3 scale. -**Tensor parallel splits every expert's width, unevenly.** `moe_intermediate_size` is 640 = 5 x 128, -so an even share at tp2 is 320, which is not a whole number of 128-column blocks — and the fp8 -scale block, the four-bit scale group and the rotation all sit on them. So each rank takes three -blocks of the experts of one parity and two of the other's (`moe_gemm_q`'s two tables in +**Tensor parallel at two ranks splits every expert's width, unevenly.** `moe_intermediate_size` is +640 = 5 x 128, so an even share at tp2 is 320, which is not a whole number of 128-column blocks — +and the fp8 scale block, the four-bit scale group and the rotation all sit on them. So each rank +takes three blocks of the experts of one parity and two of the other's (`moe_gemm_q`'s two tables in `docs/OPS.md`), the router stays replicated so both ranks agree on the routing, each rank computes its slice of every routed expert, and the block's existing end-of-block all-reduce sums the partials. No all-to-all, no extra collective. The shared expert's 640 columns split the same way, three blocks on rank 0 and two on rank 1. +**Five blocks is why that split stops at two ranks.** 5 is odd, so no world above 2 cuts it into +equal whole blocks — at tp4 an even share is 160 columns, 1.25 blocks. Above two ranks the routed +experts split by expert instead: each rank owns 128 whole experts of the 512, reads them through the +same `n_ff_exp` 640, the router stays replicated so every rank agrees on the routing, and the same +end-of-block all-reduce sums the partials. A slot whose expert is not local is dropped by +`moe_scatter`, which is how the split is expressed; the parity tables stay two-rank. The shared +expert's 640 columns take the uneven-block branch as they always did: five blocks over four ranks +is rank 0 `[0, 256)` and ranks 1, 2 and 3 one block each. The known cost is expert-selection imbalance — a token's top-10 lands +locally 2.5 times out of 10 — and removing it is exactly what the parity split buys at two ranks. +A whole-block width split is the follow-up. + +**Attention splits by KV head, and replicates once the ranks outrun the heads.** There are 2 KV +heads of 256 rows, so each rank declares `n_head_kv 1` and reads one head's row-span of `k_proj` and +`v_proj`. At tp2 that is the ordinary row shard. At tp4 the heads cannot divide four ways, so they +are replicated in rank pairs: ranks {0,1} carry KV head 0, ranks {2,3} carry KV head 1, and both +ranks of a pair hold byte-identical KV weights — more read traffic, no extra VRAM. `n_head` is 12 a +rank at tp2 and 6 at tp4, so gqa is 12 at tp2 and 6 at tp4 and the attention kernel is a different +instantiation (`attn_{prefill,decode}_h256_gqa6_bs4`, the QSA page of 4) than the gqa12 pair tp2 +resolves to, not the same kernel over fewer heads. Any world size above the KV head count must be a +multiple of it: 4 is a multiple of 2, 3 and 5 are not, and those widths are refused at declare +time. + +**The fused all-reduce forms are two-rank.** At four ranks nothing fuses: the hyper-connection pair +runs the standalone sequence — `all_reduce` (libr4d's 4-rank oneshot/twoshot), then +`hc_write_bf16`, then `moe_gather` — 2 to 3 extra launches per pair against the two-rank fused +form, and the fused attention ops have no bs4/gqa6 instantiation either. The unfused sequence is +declared beside the probe, so nothing is unresolved at boot. The per-step cost against tp2 on the +same cards is unmeasured. + +**One collective does generalise, because it has to.** The lm_head is vocab-sharded, so the sampler +gathers the ranks' candidate sets rather than their logits (`core/sample/sampler.cpp`) and an +`all_gather` is on every step's sample path at any world size above one. libr4d shipped a two-rank +form only — one peer flag, a `1 - rank` peer index, a destination stride of `2 * row16` — so the +N-rank gather is a new kernel, not a fallback: at four ranks nothing but the reference +implementation resolves and the engine refuses to serve rather than run a naive gather. It is the +same one-shot push as the N-rank all-reduce with the reduction removed, and it moves the +(u32 id, f32 logit) pairs without ever adding them. + **Four-bit experts are what make it fit.** 512 experts of 640 over 48 layers is 112.8 GiB of expert weight at E4M3 and twice that at bf16. `--weights-disk-tier` serves what fits neither VRAM nor the host pool from the container file, but a routed expert is then read a layer at a time and a step is diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 7d103c89..baadce64 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -63,6 +63,9 @@ set(R4D_UNITS # Twelve, head_dim 256 only: Qwen3.8-Flash-Next's QSA layers are 24 over 2. Four lines that # set the ratio and include the unit above, which is the parameterised body. "r4d_attn_paged_h256_gqa12|" + # Six, head_dim 256 and the same 4-token page: the same QSA layers at four ranks, where each KV + # head is replicated across a rank pair. Again four lines that set the ratio and include the body. + "r4d_attn_paged_h256_gqa6_bs4|" "r4d_attn_vit_h72_bf16|" # The vision tower's own small ops: layer norm, the learned-grid position embedding, and the # biased GEMM with a linear layer's activation and residual in its store. @@ -87,6 +90,7 @@ set(R4D_UNITS # copy of it, which is the one thing it must not have. "r4d_ar_entry|" "r4d_ar_gather_2rank|" + "r4d_ar_gather_Nrank|" "r4d_ar_oneshot_2rank_exact|" "r4d_ar_oneshot_2rank_wht6|" "r4d_ar_oneshot_Nrank_exact|" diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index f948eaf1..7b0b3b5b 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -527,6 +527,112 @@ extern "C" int r4d_rad_ar_gather_2rank(const RadArgs* a, RadStream s) { return RAD_OK; } +/* ------------------------------------------------------------------ wide (4 / 8 rank) all-gather + * The gather the 2-rank one cannot be at width: its handshake is one peer flag per block, so the + * wide form takes the wide family's peer arrays and r4d_ar_handshake instead (r4d_ar_wide.h), and + * it rides the SAME instance, scratch, flags and counters as the wide one-shots above -- a slot + * holds a full message here exactly as it does there, and this message is the INPUT. The two + * launchers live in r4d_ar_gather_Nrank.hip, which is the only family unit whose caller is inside + * the plugin, so they are declared here rather than in r4d.h. */ +extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, + long peer_flags0, long peer_flags1, long peer_flags2, + long my_scratch, long my_flags, long seq_ctrs, + long slot_stride16, long inp, long out, long n_elem, + long dtype, long rank, long row_elems, long stream, + long nblocks, long nthreads, long drain, long acq, long pub); +extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, + long peer_scratch3, long peer_scratch4, long peer_scratch5, + long peer_scratch6, long peer_flags0, long peer_flags1, + long peer_flags2, long peer_flags3, long peer_flags4, + long peer_flags5, long peer_flags6, long my_scratch, + long my_flags, long seq_ctrs, long slot_stride16, long inp, + long out, long n_elem, long dtype, long rank, long row_elems, + long stream, long nblocks, long nthreads, long drain, long acq, + long pub); + +/* Every check the 2-rank gather makes, and the same `row` rule: an all-gather's output is + * world_size times its input, so this is not ar_setup either. */ +static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in, ArCall* c, + long long* row_out) { + const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); + if (!in) return RAD_E_STATE; /* init did not run: a core sequencing bug */ + if (in->world != ws) return RAD_E_SHAPE; /* the peer bundle is compiled for this width */ + + const RadTensor* x = r4d_opt(a, AR_X); + const RadTensor* y = r4d_opt(a, AR_Y); + if (!x || !y) return RAD_E_INVAL; /* the gather has no in-place form */ + if (!r4d_contig(x) || !r4d_contig(y)) return RAD_E_STRIDE; + if (y->data == x->data) return RAD_E_INVAL; + + const long n = (long)r4d_numel(x); + if (n <= 0 || n > in->max_numel) return RAD_E_SHAPE; + /* "y is [world_size * numel] with rank r's contribution at offset r * numel" (docs/OPS.md). + * A y of any other extent is a caller that means something this kernel does not do. */ + if ((long long)r4d_numel(y) != (long long)n * in->world) return RAD_E_SHAPE; + + /* The row width, if the caller asked for the row-interleaved placement. It has to divide the + * message and be a whole number of 16-byte words, both of which libr4d rechecks. */ + const long long row = r4d_pgeti_or(a->p, a->n_p, "row", 0); + if (row < 0 || (row > 0 && (n % row || (row * in->esize) % 16))) return RAD_E_SHAPE; + + /* 16-byte vector stores, and libr4d throws on a message that is not a whole number of them. */ + if (((long long)n * in->esize) % 16) return RAD_E_ALIGN; + if (!r4d_aligned(x->data, 16) || !r4d_aligned(y->data, 16)) return RAD_E_ALIGN; + + R4dArCfg cfgv; + r4d_cfg_ar(a, &cfgv); + const long words16 = (long)n * in->esize / 16; + int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, in->nb_cap); + if (nblocks > in->max_blocks) nblocks = in->max_blocks; + + *out_in = in; + c->in = in; + c->inp = r4d_addr(x); + c->out = r4d_addr(y); + c->numel = n; + c->nblocks = nblocks; + c->nthreads = cfgv.nthreads; + c->drain = cfgv.drain; + c->acq = cfgv.acq; + c->pub = cfgv.pub; + *row_out = row; + return RAD_OK; +} + +extern "C" int r4d_rad_ar_gather_4rank(const RadArgs* a, RadStream s) { + const ArInst* in = nullptr; + ArCall c; + long long row = 0; + int rc = ar_gather_wide_setup(a, 4, &in, &c, &row); + if (rc != RAD_OK) return rc; + R4D_TRY("ar_gather_4rank", + r4d_ar_gather_4rank(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], + in->peer_flags[0], in->peer_flags[1], in->peer_flags[2], + in->my_scratch, in->my_flags, in->my_seq, in->slot16, + c.inp, c.out, c.numel, in->dtype, in->rank, (long)row, + (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub)); + return RAD_OK; +} + +extern "C" int r4d_rad_ar_gather_8rank(const RadArgs* a, RadStream s) { + const ArInst* in = nullptr; + ArCall c; + long long row = 0; + int rc = ar_gather_wide_setup(a, 8, &in, &c, &row); + if (rc != RAD_OK) return rc; + R4D_TRY("ar_gather_8rank", + r4d_ar_gather_8rank(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], + in->peer_scratch[3], in->peer_scratch[4], in->peer_scratch[5], + in->peer_scratch[6], + in->peer_flags[0], in->peer_flags[1], in->peer_flags[2], + in->peer_flags[3], in->peer_flags[4], in->peer_flags[5], + in->peer_flags[6], + in->my_scratch, in->my_flags, in->my_seq, in->slot16, + c.inp, c.out, c.numel, in->dtype, in->rank, (long)row, + (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub)); + return RAD_OK; +} + /* ------------------------------------------------------------------ 2-rank one-shot */ extern "C" int r4d_rad_ar_oneshot_2rank_exact(const RadArgs* a, RadStream s) { diff --git a/libr4d/r4d_ar_gather_Nrank.hip b/libr4d/r4d_ar_gather_Nrank.hip new file mode 100644 index 00000000..d89c504e --- /dev/null +++ b/libr4d/r4d_ar_gather_Nrank.hip @@ -0,0 +1,243 @@ +// r4d_ar_gather_Nrank.hip: r4d_ar_gather_4rank, r4d_ar_gather_8rank -- one-shot P2P all-GATHER, +// 4 or 8 ranks, gfx1201. WS is compile-time; the 2-rank gather keeps its own file, exactly as the +// one-shot all-reduce's does. +// +// WHY IT EXISTS. r4d_ar_gather_2rank.hip is the engine's only device all-gather and its handshake +// is ONE PEER FLAG per block, not a tree (r4d_ar_entry.hip:492), so it is compiled for two ranks +// and refuses every other width. The vocab-parallel sampler declares an all_gather whenever the +// vocabulary is sharded, so at world 4 nothing but libref's host ref_all_gather resolves and the +// serve is refused by name. This is the wide one-shot all-reduce with the reduction REMOVED: same +// push, same per-block handshake, same double-buffered (parity, source) scratch, and the fp32 sum +// replaced by placement. +// +// THE PAYLOAD IS MOVED AND NEVER SUMMED. What the sampler gathers is (u32 global token id, f32 +// logit) pairs; a token id's bit pattern read as f32 is a denormal, so adding two lanes would +// work on the logit and destroy the id. `dtype` is taken for symmetry with the family and used +// only to turn n_elem into bytes. +// +// THE PLACEMENT. row16 is one ROW of this rank's contribution in 16-byte words and r4d_g_dst_ws +// says where a rank's words land: the plain concatenation when there is one row, and otherwise +// ROW-INTERLEAVED -- input [rows][row16], output [rows][WS][row16] -- because the merge that +// consumes this reads one row of gathered candidates per sampled position at a single row stride. +// See r4d_ar_gather_2rank.hip, whose comment states why that is not a convenience. +// +// The IPC helpers and the handshake live in r4d_ar_wide.h; this unit links beside r4d_ar_entry.hip, +// which owns the instance and the peer arrays. +#include "r4d.h" +#include "r4d_ar_wide.h" +#include +#include +#include + +// The launchers this unit provides, in the family's shape: the peer arguments are ascending global +// rank with the current rank removed, and `out` is world_size * n_elem elements. Declared extern +// "C" here, at arm's length from the definitions below, so those definitions get C linkage; the +// caller is r4d_ar_entry.hip, which owns the instance and repeats the two prototypes at its call +// site (r4d.h declares the rest of the family and is not this unit's file). +extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, + long peer_flags0, long peer_flags1, long peer_flags2, + long my_scratch, long my_flags, long seq_ctrs, + long slot_stride16, long inp, long out, long n_elem, + long dtype, long rank, long row_elems, long stream, + long nblocks, long nthreads, long drain, long acq, long pub); +extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, + long peer_scratch3, long peer_scratch4, long peer_scratch5, + long peer_scratch6, long peer_flags0, long peer_flags1, + long peer_flags2, long peer_flags3, long peer_flags4, + long peer_flags5, long peer_flags6, long my_scratch, + long my_flags, long seq_ctrs, long slot_stride16, long inp, + long out, long n_elem, long dtype, long rank, long row_elems, + long stream, long nblocks, long nthreads, long drain, long acq, + long pub); + +// WHERE A RANK'S WORDS LAND -- the 2-rank r4d_g_dst at a compile-time width. Named apart from it +// on purpose: same rule, different WS, and two __device__ definitions of one name would be an ODR +// violation between the two units. +__device__ __forceinline__ int r4d_g_dst_ws(int k, int row16, int n16, int WS, int who) { + if (row16 <= 0 || row16 >= n16) return who * n16 + k; + const int m = k / row16, c = k - m * row16; + return m * (WS * row16) + who * row16 + c; +} + +// Block b owns words [start,end) of the 16B-word space and drives its own handshake; no cross-block +// sync, exactly as in the all-reduce this rides beside. +template +__global__ void r4d_ar_gather_wide_kernel( + const int4* __restrict__ in4, R4DArWidePeers peers, + const int4* __restrict__ my_base, int4* __restrict__ out4, + unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, + int n16, int slot_stride16, int rank, int row16, int drain, int acq, int pub) { + constexpr int NPEERS = WS - 1; + // The placement holds WS source words live per output word, so the 2x unroll spills at ws=8 -- + // the same ceiling the one-shot all-reduce draws for the same reason. + constexpr int RU = (WS <= 4) ? 2 : 1; + + const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; + __shared__ unsigned int s_seq, s_slot; + r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe + const unsigned int s = s_seq; + const int parity = (int)s_slot; + + const int w = (n16 + nb - 1) / nb; + const int start = b * w; + int end = start + w; if (end > n16) end = n16; + + // Every peer lays its scratch out identically, so one index serves all of them: the slot that + // NAMES THE SOURCE RANK. We write our own words into the same slot number of every peer's + // scratch, and every peer reads them out of the slot numbered by OUR rank. + int4* ps[NPEERS]; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) + ps[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16; + + // push: 4x-unrolled, and the loaded words are reused across peers so the input is read once. + // This rank's own slice is NOT placed here -- the pass after the handshake places every rank's + // slice from one src[] table, and duplicating the local store to hide it here would be the only + // thing the all-reduce's shape does not carry over. + { + int k = start + tid; + for (; k + 3 * nt < end; k += 4 * nt) { + const int4 v0 = in4[k], v1 = in4[k + nt], v2 = in4[k + 2 * nt], v3 = in4[k + 3 * nt]; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) { + ps[p][k] = v0; ps[p][k + nt] = v1; ps[p][k + 2 * nt] = v2; ps[p][k + 3 * nt] = v3; + } + } + for (; k < end; k += nt) { + const int4 v = in4[k]; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) ps[p][k] = v; + } + } + + // The wide family's own protocol: publish 2*seq to every peer's flag word [b][our rank], then + // wait on our own [b][source] for every source. Flag values, parity and the slot guard are + // r4d_ar_wide.h's, shared with the all-reduces this instance's buffers serve, and a handshake + // that cannot complete traps rather than pass stale bytes on as a peer's. + r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + + // The peers' slices, now staged in this rank's scratch, into the places that name them. Slot + // [parity][our rank] of my own scratch is written by nobody, so -- exactly as in the all-reduce + // -- the source that names OUR rank is the input itself and every lane is branch-free. + const int4* src[WS]; +#pragma unroll + for (int r = 0; r < WS; ++r) + src[r] = (r == rank) ? in4 + : (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16); + { + int k = start + tid; + if (RU == 2) { + for (; k + nt < end; k += 2 * nt) { +#pragma unroll + for (int r = 0; r < WS; ++r) { + out4[r4d_g_dst_ws(k, row16, n16, WS, r)] = src[r][k]; + out4[r4d_g_dst_ws(k + nt, row16, n16, WS, r)] = src[r][k + nt]; + } + } + } + for (; k < end; k += nt) { +#pragma unroll + for (int r = 0; r < WS; ++r) + out4[r4d_g_dst_ws(k, row16, n16, WS, r)] = src[r][k]; + } + } +} + +// --- host side --- +// `row_elems` is the row width in ELEMENTS, 0 for the plain concatenation; the entry point has +// already checked that it divides the message and is a whole number of 16-byte words, and it is +// rechecked here because this is the half that throws. +template +static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_flags, long my_scratch, + long my_flags, long seq_ctrs, long slot_stride16, long inp, + long out, long n_elem, long dtype, long rank, long row_elems, + long stream_i, long nblocks, long nthreads, long drain, long acq, + long pub) { + constexpr int NPEERS = WS - 1; + static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound"); + + if (rank < 0 || rank >= WS) + throw std::runtime_error("all_gather: rank " + std::to_string(rank) + + " out of range for the " + std::to_string(WS) + + " ranks this entry point is compiled for"); + + const int esize = (dtype == 2) ? 4 : 2; + const long nbytes = (long)n_elem * esize; + if (nbytes % 16 != 0) throw std::runtime_error("all_gather: n_elem*esize not 16B-aligned"); + const long n16l = nbytes / 16; + if (n16l > (long)slot_stride16) + throw std::runtime_error("all_gather: message (" + std::to_string(n16l) + + " 16B words) exceeds the per-source slot stride (" + + std::to_string(slot_stride16) + ")"); + const int n16 = (int)n16l; + + long rowb = (long)row_elems * esize; + if (row_elems > 0 && (rowb % 16 != 0 || nbytes % rowb != 0)) + throw std::runtime_error("all_gather: row is not a whole number of 16B words"); + const int row16 = row_elems > 0 ? (int)(rowb / 16) : 0; + + int nb = (int)nblocks; + if (nb < 1) nb = R4D_AR_NB_DESIGN; + if (nb > n16) nb = n16; + if (nb > R4D_AR_WIDE_MAX_BLOCKS) nb = R4D_AR_WIDE_MAX_BLOCKS; + int nt = (int)nthreads; + if (nt < 64) nt = 64; + if (nt > 1024) nt = 1024; + + R4DArWidePeers peers{}; + for (int i = 0; i < NPEERS; ++i) { + if (!peer_scratch[i] || !peer_flags[i]) + throw std::runtime_error("all_gather: null peer scratch/flag pointer at index " + + std::to_string(i)); + peers.scratch[i] = (int4*)peer_scratch[i]; + peers.flags[i] = (unsigned int*)peer_flags[i]; + peers.rank[i] = (i < (int)rank) ? i : i + 1; + } + + // Same buffers, same rule as the all-reduce this shares an instance with: scratch backs 2*WS + // slots of the declared stride, flags one word per (block, source rank), seq a handshake and a + // parity word per block of capacity -- checked against the allocations, not the arguments. + const long slot_bytes = 2L * WS * (long)slot_stride16 * 16; + const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int); + r4d_ar_check_extent(my_scratch, slot_bytes, "all_gather", "my_scratch"); + r4d_ar_check_extent(my_flags, flag_bytes, "all_gather", "my_flags"); + r4d_ar_check_extent(seq_ctrs, 2L * R4D_AR_WIDE_MAX_BLOCKS * (long)sizeof(unsigned int), + "all_gather", "seq_ctrs"); + for (int i = 0; i < NPEERS; ++i) { + r4d_ar_check_extent(peer_scratch[i], slot_bytes, "all_gather", "peer scratch"); + r4d_ar_check_extent(peer_flags[i], flag_bytes, "all_gather", "peer flags"); + } + + hipStream_t st = (hipStream_t)stream_i; + r4d_ar_gather_wide_kernel<<>>( + (const int4*)inp, peers, (const int4*)my_scratch, (int4*)out, (unsigned int*)my_flags, + (unsigned int*)seq_ctrs, n16, (int)slot_stride16, (int)rank, row16, (int)drain, (int)acq, + (int)pub); +} + +void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, + long peer_flags0, long peer_flags1, long peer_flags2, long my_scratch, + long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, + long n_elem, long dtype, long rank, long row_elems, long stream, + long nblocks, long nthreads, long drain, long acq, long pub) { + const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; + const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; + ar_gather_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, + dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub); +} + +void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, + long peer_scratch3, long peer_scratch4, long peer_scratch5, + long peer_scratch6, long peer_flags0, long peer_flags1, long peer_flags2, + long peer_flags3, long peer_flags4, long peer_flags5, long peer_flags6, + long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, + long inp, long out, long n_elem, long dtype, long rank, long row_elems, + long stream, long nblocks, long nthreads, long drain, long acq, + long pub) { + const long ps[7] = {peer_scratch0, peer_scratch1, peer_scratch2, peer_scratch3, + peer_scratch4, peer_scratch5, peer_scratch6}; + const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3, + peer_flags4, peer_flags5, peer_flags6}; + ar_gather_wide_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, + dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub); +} diff --git a/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip b/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip new file mode 100644 index 00000000..956f63ec --- /dev/null +++ b/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip @@ -0,0 +1,43 @@ +// R4D attention at SIX queries per KV head, head_dim 256 -- the same QSA layers of +// Qwen3.8-Flash-Next that r4d_attn_paged_h256_gqa12.hip serves at two ranks, served at FOUR: the +// two KV heads are replicated across the rank pairs, so each rank answers 6 queries for the one KV +// head it holds and the ratio the constraint table gates on is 6 rather than 12. +// +// Four lines of geometry and the dispatch itself, because r4d_attn_paged_gqa8.hip's kernels are +// templates on `gqa` and that unit is the parameterised body. What the ratio changes is +// exactly two bounds, and both are in the ROW table rather than here: +// +// the decode verify width 64 / gqa = 10, against 5 at gqa 12 and 8 at gqa 8. A workgroup holds +// 64 (query, head) rows and carries q_len * gqa of them, so this is +// the WIDEST of the three legs: MTP's K=3 verify is q_len 4 and fits +// either ratio, and a draft block of six or seven positions -- which +// the gqa12 leg has to send to the prefill kernel -- fits the decode +// kernel here. +// a prefill block's width 384 / gqa = 64 query positions, against 32 at gqa 12 and 48 at +// gqa 8. +// +// NO head_dim 128 LEG, for the gqa12 file's reason: nothing in scope is gqa 6 at 128, and an +// instantiation nothing resolves is a kernel nobody has run. R4D_ATTN_H128 leaves those four entry +// points out of this translation unit entirely rather than shipping them untested. +#define R4D_ATTN_GQA 6 +#define R4D_ATTN_H128 0 +// THE KV PAGE IS FOUR TOKENS HERE, AND IT IS THE ONLY GEOMETRY IN THIS LIBRARY WHERE IT IS NOT 16. +// +// Qwen3.8-Flash-Next's QSA indexer selects 4-TOKEN BLOCKS of the key history. With a page of 4 a +// selected block IS a page, so the selection is a paged block table and the sparse attention is +// this kernel with a different table -- instead of a new attention kernel, which is the most +// expensive kind of kernel in this tree to get right. docs/QSA.md is the decomposition. The page +// is 4 at this ratio for exactly the reason it is 4 at gqa 12 -- the model's page, not the +// parallelism's; what TP4 changes is the queries a head, not the storage. +// +// IT COSTS NOTHING. A page size is pure storage, so the only thing it can move is the block-table +// walk -- `NB = TILE / BS` entries a tile instead of one, four instead of one at TILE 16 -- and at +// a realistic context that is inside the noise of the step, with identical output either way. +// +// THE ROWS HAVE TO AGREE. `C_EQ("block_size", 4)` on all four gqa6-bs4 rows is what makes the core +// size the pages at 4 (RadKVGroupDecl carries no block size on purpose -- it is taken off the +// resolved kernel). A row that says 16 against this define is a kernel that refuses at issue +// rather than at declare. +#define G8_BLOCK_SIZE 4 + +#include "r4d_attn_paged_gqa8.hip" diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 37143a16..336a7cd3 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -119,6 +119,18 @@ int r4d_rad_attn_decode_gq_h256_gqa12_bf16(const RadArgs*, RadStream); int r4d_rad_attn_decode_gq_h256_gqa12_bf16_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int64_t r4d_rad_attn_decode_h256_gqa12_scratch(const RadArgs*); +/* Six queries a KV head, head_dim 256, paged block 4 -- the same QSA layers at four ranks, where + * the KV head is replicated across a rank pair. Same body again; the verify width is 64/6 = 10 + * against gqa12's 5, which is the decode rows' constraint value. */ +int r4d_rad_attn_prefill_h256_gqa6_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_prefill_h256_gqa6_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_decode_h256_gqa6_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_decode_h256_gqa6_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, + int, int*); +int r4d_rad_attn_decode_h256_gqa6_bf16 (const RadArgs*, RadStream); +int r4d_rad_attn_decode_h256_gqa6_bf16_describe(const RadArgs*, RadStream, RadLaunchDesc*, + int, int*); +int64_t r4d_rad_attn_decode_h256_gqa6_scratch(const RadArgs*); /* -- gated delta net (r4d_gdn_*.hip) -- */ int r4d_rad_gdn_chunk_scan (const RadArgs*, RadStream); @@ -149,6 +161,9 @@ int r4d_rad_ar_init(const RadParam*, int, int rank, int world, void** out); void r4d_rad_ar_fini(void*); int r4d_rad_ar_oneshot_2rank_exact(const RadArgs*, RadStream); int r4d_rad_ar_gather_2rank (const RadArgs*, RadStream); +/* The gather at a wide group's handshake (r4d_ar_gather_Nrank.hip launches it). */ +int r4d_rad_ar_gather_4rank (const RadArgs*, RadStream); +int r4d_rad_ar_gather_8rank (const RadArgs*, RadStream); int r4d_rad_ar_oneshot_2rank_wht6 (const RadArgs*, RadStream); int r4d_rad_ar_oneshot_4rank_exact(const RadArgs*, RadStream); int r4d_rad_ar_oneshot_8rank_exact(const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 4ceb31ea..28d30147 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2206,6 +2206,35 @@ static const RadConstraint cAttnDecodeGqH256G12Bf16[] = { C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), C_EQ("group", 128), C_IN("act", "sigmoid"), }; +/* SIX QUERIES PER KV HEAD, head_dim 256, paged block 4 (r4d_attn_paged_h256_gqa6_bs4.hip) -- the + * SAME QSA layers as the gqa12 leg above, at four ranks. The model has two KV heads; a world of + * four replicates each across a rank pair, so a rank declares 6 queries over the 1 kv head it + * holds and `gqa` is 6 where the TP2 leg reads 12. What the ratio changes is the two bounds, as + * ever: `q_len <= 10` is the same `q_len * gqa <= 64` at 6 queries a position rather than 12, so + * this leg's bucket boundary sits where the plain h256/gqa6 leg's does, and a draft block of six or + * seven positions -- which gqa12 hands to the prefill kernel -- is a decode launch here. The page + * stays 4 because it is the model's indexer's block size, not a consequence of the parallelism. + * + * NO `attn_paged_gate_quant` ROW AT THIS GEOMETRY. The body instantiates the `_gq` entry points at + * every ratio, but v1 of this port registers none of them as a row, so the sparse path's gate and + * quantiser resolve to the standalone pair declared beside the probe. That is the design, not an + * omission. */ +static const RadConstraint cAttnPrefillH256G6Bs4Fp8[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnPrefillH256G6Bs4Bf16[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; +static const RadConstraint cAttnDecodeH256G6Bs4Fp8[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), + C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnDecodeH256G6Bs4Bf16[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), + C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; static const RadConstraint cAttnPrefillH128G8Fp8[] = { C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -2304,6 +2333,14 @@ static const RadConstraint cArGather2[] = { C_EQ("world_size", 2), C_IN("dtype", "bf16 fp16 f16 fp32 f32"), C_P2P, }; +/* The same gather at a width whose handshake is the wide family's tree and not one peer flag. The + * dtype set is cArGather2's verbatim for the same reason -- the two callers' synonyms. */ +static const RadConstraint cArGather4[] = { + C_EQ("world_size", 4), C_IN("dtype", "bf16 fp16 f16 fp32 f32"), +}; +static const RadConstraint cArGather8[] = { + C_EQ("world_size", 8), C_IN("dtype", "bf16 fp16 f16 fp32 f32"), +}; static const RadConstraint cArExact[] = { C_EQ("world_size", 2), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), @@ -3530,6 +3567,48 @@ static const RadKernelInfo kKernels[] = { r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant, r4d_rad_attn_decode_gq_h256_gqa12_bf16_describe }, +/* The TP4 leg of Flash-Next's sparse attention: the same kernels the gqa12 rows above resolve, at + * the ratio a four-rank world hands a rank (see cAttnPrefillH256G6Bs4Fp8). The two are not + * alternatives -- `gqa` is a per-rank parameter, so world 2 resolves gqa 12 and these four rows + * never win there, and world 4 resolves gqa 6 and the gqa12 rows never win. */ +{ "attn_prefill_h256_gqa6_bs4_fp8kv", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 256, 6 queries per kv head, paged block 4, varlen", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH256G6Bs4Fp8), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa6_fp8, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_prefill_h256_gqa6_bs4_bf16kv", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 256, 6 queries per kv head, paged block 4, varlen", + "bf16 query, bf16 kv cache, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH256G6Bs4Bf16), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa6_bf16, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h256_gqa6_bs4_fp8kv", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", + "head_dim 256, 6 queries per kv head, paged block 4, q_len*gqa <= 64, no window", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256G6Bs4Fp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_fp8, r4d_rad_attn_decode_h256_gqa6_scratch, + nullptr, nullptr, + r4d_shape_attn_paged, nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_fp8_describe }, + +{ "attn_decode_h256_gqa6_bs4_bf16kv", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", + "head_dim 256, 6 queries per kv head, paged block 4, q_len*gqa <= 64, no window", + "bf16 query, bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256G6Bs4Bf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_bf16, r4d_rad_attn_decode_h256_gqa6_scratch, + nullptr, nullptr, + r4d_shape_attn_paged, nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_bf16_describe }, + { "attn_prefill_h128_gqa8_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 128, 8 queries per kv head, paged block 16, varlen", @@ -3750,6 +3829,30 @@ static const RadKernelInfo kKernels[] = { r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_gather_2rank, nullptr, nullptr, nullptr, r4d_shape_all_gather }, +{ "ar_gather_4rank", "all_gather", "ar", + "all-gather, one-shot push over P2P IPC scratch, per-block handshake", + "exactly 4 ranks, all peer-accessible; y is [4 * numel] with rank r's input at r * numel; one " + "scratch slot per (parity, source rank); shares the wide family's flag/seq/scratch set; " + "cudagraph-safe", + "any payload -- the bytes are moved, never summed, so the (u32 id, f32 logit) pairs the " + "vocab-parallel sampler gathers survive intact", + RAD_DOMAIN_DEVICE, R4D_PRIO_AR_ONESHOT, + ROW(cArGather4), ROW(tAr), nullptr, + r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_gather_4rank, nullptr, nullptr, nullptr, + r4d_shape_all_gather }, + +{ "ar_gather_8rank", "all_gather", "ar", + "all-gather, one-shot push over P2P IPC scratch, per-block handshake", + "exactly 8 ranks, all peer-accessible; y is [8 * numel] with rank r's input at r * numel; one " + "scratch slot per (parity, source rank); shares the wide family's flag/seq/scratch set; " + "cudagraph-safe", + "any payload -- the bytes are moved, never summed, so the (u32 id, f32 logit) pairs the " + "vocab-parallel sampler gathers survive intact", + RAD_DOMAIN_DEVICE, R4D_PRIO_AR_ONESHOT, + ROW(cArGather8), ROW(tAr), nullptr, + r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_gather_8rank, nullptr, nullptr, nullptr, + r4d_shape_all_gather }, + { "ar_oneshot_2rank_exact", "all_reduce", "ar", "all-reduce (sum), one-shot push over P2P IPC scratch", "exactly 2 ranks, peer-accessible; scratch sized by the full message; cudagraph-safe", diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 8389d3ed..850c7a84 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -36,7 +36,16 @@ struct RecParam { std::string sval; }; -struct RecWeight { std::string name; RadWeightDecl d{}; }; +struct RecWeight { + std::string name; + RadWeightDecl d{}; + /* The uneven slice this weight was handed, in the CONTAINER's unsharded units + * (rad_weight_shard_span). Recorded rather than dropped: "which rows of the checkpoint's k/v + * projection does rank 3 read" is a declare-time fact and this file is where declare is + * checked. A weight with no span -- every even shard -- has `span_set` false. */ + bool span_set = false; + int64_t span_lo = 0, span_hi = 0; +}; struct RecBuf { std::string name; RadBufDecl d{}; }; struct RecOp { std::string op; @@ -198,8 +207,15 @@ extern "C" int rad_declare_logits(RadBuilder* b, rad_buf logits) { /* Recorded as calls and nothing else: no test here reads a lane or a drafter declaration. */ extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { (void)b; (void)buf; return RAD_OK; } extern "C" int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) { - (void)b; (void)w; - return (lo >= 0 && hi > lo) ? RAD_OK : RAD_E_INVAL; + if (!b || w == 0 || w > b->weights.size()) return RAD_E_INVAL; + if (lo < 0 || hi <= lo) return RAD_E_INVAL; + /* The real Builder also checks the declared extent against hi-lo (core/build/rad_builder.cpp); + * the fake checks what it always did and records the answer so a test can read it back. */ + RecWeight& rw = b->weights[w - 1]; + rw.span_set = true; + rw.span_lo = lo; + rw.span_hi = hi; + return RAD_OK; } extern "C" int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { (void)b; (void)d; @@ -1816,6 +1832,229 @@ TEST(a_sizing_declare_leaves_the_step_state_alone_and_shrinks_only_rows) { } +/* FOUR RANKS: THE KV HEADS REPLICATE, THE EXPERTS SPLIT WHOLE, THE FUSED COLLECTIVES STOP. + * + * This is the tensor-parallel test above's sibling for the other model in the tree, and it exists + * because world 4 was not declarable at all: `geom_from` refused any world larger than the KV head + * count, and qwen4exp's parity split of a 640-column expert "serves two ranks" by name. Both are + * now answered by a DIFFERENT declaration rather than a rounding rule, and the point of this test + * is to pin which one: + * + * - the KV heads cannot be cut four ways, so they are REPLICATED in pairs: one KV head a rank, + * ranks {0,1} reading rows [0,256) of the checkpoint's k/v projection and {2,3} reading + * [256,512). That is a span, not a shard index, and it is the only place in the engine where a + * rank names the container rows it wants -- so it is asserted here as a pair of agreeing spans + * whose union is the whole projection. + * - the experts go WHOLE, rank r owning [r*128, (r+1)*128) of 512, with the router REPLICATED at + * the model's full 512 logits. A rank that disagreed with the router about the expert count + * would route to a different model. + * - the FUSED all-reduces are world-2 kernels (`ar_wire_is_exact` and `ar_fused_ok` both return + * false off two, and `HyperConn` declares `ar_hc_write` only at world 2), so at four the chain + * is unfused: a standalone `all_reduce` where the collective happens. The contrast with world 2 + * in the same test is the contract -- it fails loudly if a fused declare is ever gated on the + * wrong condition. + * + * Every expected number is derived from the meta this file builds (n_head 24, n_head_kv 2, head_dim + * 256, num_experts 512), so the fixture and the assertions cannot drift apart. Where a number is + * really the PRODUCTION container's -- the unsharded k_proj entry's 512 rows -- the relation is + * asserted instead of the literal. */ +TEST(flashnext_tp4_replicates_kv_heads_and_owns_whole_experts) { + RadModelMeta meta = qwen4exp_meta(); + const int world = 4; + const int64_t n_head = meta.n_head; /* 24 query heads */ + const int64_t n_head_kv = meta.n_head_kv; /* 2 KV heads -- fewer than the ranks */ + const int64_t head_dim = meta.head_dim; /* 256 */ + const int64_t ne_all = atoll(rad_meta_gets(&meta, "num_experts", "0")); + REQUIRE(n_head % world == 0); + REQUIRE_EQ(world % n_head_kv, (int64_t)0); /* replication needs the multiple */ + REQUIRE(ne_all % world == 0); + + /* Full-attention layers of the eight-layer fixture: 3 and 7 (interval 4). */ + const int lfull = 3; + const std::string kq = "blk." + std::to_string(lfull) + ".attn_k.weight"; + const std::string kv = "blk." + std::to_string(lfull) + ".attn_v.weight"; + + RadBuilder b[world]; + RadBuildCtx c[world]; + for (int r = 0; r < world; ++r) { + c[r] = build_ctx(r, world); + c[r].max_tok = 2048; + c[r].max_seqs = 8; + c[r].max_spec = 3; + c[r].max_ctx = 200000; + /* THE DISCRIMINATOR: on the unpatched tree this returns RAD_E_INVAL from geom_from's + * divide_or_fail(n_head_kv, 4) and nothing below it runs. */ + REQUIRE_EQ(qwen4exp_fp8::declare(&b[r], &meta, &c[r]), RAD_OK); + } + + for (int r = 0; r < world; ++r) { + /* (1) ONE QUARTER OF THE QUERY HEADS, ONE KV HEAD, so gqa is 6 and the page is the QSA + * compress block of 4 (qwen4exp_fp8.cpp sets lay.attn.kv_block = 4, and the row's + * C_EQ("block_size", 4) has to agree with it or nothing resolves). */ + const RecOp* at = find_op(b[r], "attn_paged"); + REQUIRE(at != nullptr); + CHECK_EQ(pint(at, "n_head"), n_head / world); + CHECK_EQ(pint(at, "gqa"), n_head / world); /* n_head_kv is 1, so gqa == the rank's heads */ + CHECK_EQ(pint(at, "block_size"), 4); + /* The full-attention KV group holds the one head this rank serves. Group 0 is kv_attn -- + * the first declared (qwen4exp_fp8.cpp's three groups, RAD_KV_FULL first). */ + REQUIRE(b[r].kv_groups.size() > 0); + CHECK_EQ(b[r].kv_groups[0].name, std::string("kv_attn")); + CHECK_EQ(b[r].kv_groups[0].d.n_head_kv, 1); + CHECK_EQ(b[r].kv_groups[0].d.head_dim, head_dim); + + /* (2) ONE KV HEAD'S ROWS, and the SPAN that locates them in the entry. shape[0] is + * n_head_kv * head_dim = 256 per rank; the pair of ranks reading it declares the SAME span, + * and the two spans together are the checkpoint's whole k_proj -- n_head_kv_all * head_dim + * = 512 rows, which is a CONTAINER fact this file cannot read, so it is asserted as the + * relation below rather than as a literal. */ + for (const std::string& wn : {kq, kv}) { + const RecWeight* w = find_w(b[r], wn); + REQUIRE(w != nullptr); + CHECK_EQ(w->d.shape[0], head_dim); /* one head */ + CHECK_EQ(w->d.shape[1], meta.n_embd); /* the projection's K is not sharded */ + CHECK_EQ(w->d.shard, RAD_SHARD_ROW); + CHECK(w->span_set); + CHECK_EQ(w->span_hi - w->span_lo, w->d.shape[0]); + CHECK_EQ(w->span_lo, (int64_t)(r / (world / n_head_kv)) * head_dim); + CHECK_EQ(w->span_hi, w->span_lo + head_dim); + } + /* (3) THE EXPERTS THIS RANK OWNS, whole, and a router that still names every one. */ + const RecOp* sc = find_op(b[r], "moe_scatter"); + REQUIRE(sc != nullptr); + CHECK_EQ(pint(sc, "n_expert"), ne_all / world); + CHECK_EQ(pint(sc, "expert_base"), (int64_t)r * (ne_all / world)); + const RecOp* tk = find_op(b[r], "router_topk"); + REQUIRE(tk != nullptr); + CHECK_EQ(pint(tk, "n_expert"), ne_all); /* replicated: one routing per token */ + if (const RecOp* ts = find_op(b[r], "router_topk_scatter")) { + CHECK_EQ(pint(ts, "n_expert"), ne_all); + CHECK_EQ(pint(ts, "n_local"), ne_all / world); + CHECK_EQ(pint(ts, "expert_base"), (int64_t)r * (ne_all / world)); + } + /* The experts declared by name are the ones in that range -- the weight manifest is the + * rank's ownership, and the numbering is the CHECKPOINT's (rad_block_moe_fp8.h's + * `expert_base + e`), so a slip here routes the wrong tensor. */ + const std::string pre = "blk.0.ffn_gate_up_exps."; + int64_t lo = -1, hi = -1; + for (const RecWeight& w : b[r].weights) { + if (w.name.rfind(pre, 0) != 0 || w.name.size() < pre.size() + 8) continue; + if (w.name.compare(w.name.size() - 7, 7, ".weight") != 0) continue; + const int64_t ge = atoll(w.name.c_str() + pre.size()); + if (lo < 0) { lo = ge; hi = ge; } + if (ge < lo) lo = ge; + if (ge > hi) hi = ge; + } + REQUIRE(lo >= 0); + CHECK_EQ(lo, (int64_t)r * (ne_all / world)); + CHECK_EQ(hi, (int64_t)r * (ne_all / world) + ne_all / world - 1); + /* And NO expert weight carries a span: whole experts and a slice of every one are + * exclusive (rad_block_moe_fp8.h refuses "whole experts OR a slice of every one"), which in + * the declaration means the parity tables ff_lo/ff_hi stay 0 and `span()` is never called. + * The shared arm is the one exception and it is sliced by columns, not by parity -- asserted + * by its own span below. */ + int expert_spanned = 0; + for (const RecWeight& w : b[r].weights) + if (w.name.find("ffn_gate_up_exps.") != std::string::npos && w.span_set) + ++expert_spanned; + CHECK_EQ(expert_spanned, 0); + + /* (4) THE UNFUSED CHAIN: a standalone collective per reduction, and none of the three + * fused world-2 forms. */ + CHECK(count_op(b[r], "all_reduce") > 0); + CHECK_EQ(pint(find_op(b[r], "all_reduce"), "world_size"), world); + CHECK_EQ(count_op(b[r], "ar_hc_write"), 0); + CHECK_EQ(count_op(b[r], "ar_gather_hc_write"), 0); + CHECK_EQ(count_op(b[r], "ar_rmsnorm_quant_fp8"), 0); + } + + /* THE PAIRS AGREE AND THEIR UNION IS THE WHOLE PROJECTION. 2 * head_dim is the container's + * k_proj entry height (n_head_kv_all rows of head_dim each) -- the relation, not the literal, + * because the rows belong to the model file and not to this fixture. */ + for (const std::string& wn : {kq, kv}) { + CHECK_EQ(find_w(b[0], wn)->span_hi, find_w(b[1], wn)->span_hi); + CHECK_EQ(find_w(b[2], wn)->span_lo, find_w(b[3], wn)->span_lo); + CHECK_EQ(find_w(b[0], wn)->span_lo, find_w(b[2], wn)->span_hi - n_head_kv * head_dim); + const int64_t lo = find_w(b[0], wn)->span_lo; + const int64_t hi = find_w(b[2], wn)->span_hi; + CHECK_EQ(hi - lo, n_head_kv * head_dim); + CHECK_EQ(hi - lo, world * find_w(b[0], wn)->d.shape[0] / (world / n_head_kv)); + } + + /* (5) THE FOUR GRAPHS ARE THE SAME GRAPH. A rank's shard differs in a parameter or a weight's + * span, never in which ops it declares -- a graph that varied by rank would be a plan that + * varied by rank. */ + for (int r = 1; r < world; ++r) { + if (op_names(b[r]) != op_names(b[0])) { + fprintf(stderr, " rank %d differs from rank 0 in its op list (%zu vs %zu)\n", r, + b[r].ops.size(), b[0].ops.size()); + for (size_t i = 0; i < b[0].ops.size() && i < b[r].ops.size(); ++i) + if (b[0].ops[i].op != b[r].ops[i].op) { + fprintf(stderr, " first at %zu: '%s' vs '%s'\n", i, + b[0].ops[i].op.c_str(), b[r].ops[i].op.c_str()); + break; + } + } + CHECK_EQ(join(op_names(b[r])), join(op_names(b[0]))); + } + + /* THE SHARED ARM IS SPLIT BY WHOLE BLOCKS AND IS UNEVEN AT FOUR: 640 is five blocks of 128, so + * the rank taking the extra block is rank 0 -- [0,256) [256,384) [384,512) [512,640) in the + * model's column numbering, the same rule that gives rank 0 three of five blocks at two ranks + * (qwen4exp_fp8.cpp's uneven-block branch). This is the one world-4 span that is NOT a KV head. */ + for (int r = 0; r < world; ++r) { + const RecWeight* sg = find_w(b[r], "blk.0.ffn_gate_up_shexp.weight"); + REQUIRE(sg != nullptr); + CHECK(sg->span_set); + const int64_t want_lo[] = { 0, 256, 384, 512 }; + const int64_t want_hi[] = { 256, 384, 512, 640 }; + CHECK_EQ(sg->span_lo, want_lo[r]); + CHECK_EQ(sg->span_hi, want_hi[r]); + CHECK_EQ(sg->d.shape[0], 2 * (want_hi[r] - want_lo[r])); /* gate's rows and up's */ + if (r) CHECK_EQ(sg->span_lo, find_w(b[r - 1], "blk.0.ffn_gate_up_shexp.weight")->span_hi); + } + + /* AT TWO, THE OLD DECLARATION: the KV heads split, so the even shard already selects the right + * rows and NO SPAN is declared at all -- TP2 is byte-identical to the tree this fork started + * from. The fused forms are the tell that world 2 is a different deployment and not the same + * one stretched: they resolve there and nowhere else. */ + { + RadBuilder h[2]; + for (int r = 0; r < 2; ++r) { + RadBuildCtx c2 = build_ctx(r, 2); + c2.max_tok = 2048; + c2.max_seqs = 8; + c2.max_spec = 3; + c2.max_ctx = 200000; + REQUIRE_EQ(qwen4exp_fp8::declare(&h[r], &meta, &c2), RAD_OK); + const RecWeight* w = find_w(h[r], kq); + REQUIRE(w != nullptr); + CHECK_EQ(w->d.shape[0], n_head_kv / 2 * head_dim); /* one of two heads */ + CHECK(!w->span_set); + CHECK_EQ(h[r].kv_groups[0].d.n_head_kv, n_head_kv / 2); + CHECK_EQ(pint(find_op(h[r], "attn_paged"), "gqa"), (n_head / 2) / (n_head_kv / 2)); + CHECK_EQ(pint(find_op(h[r], "moe_scatter"), "n_expert"), ne_all); + CHECK_EQ(pint(find_op(h[r], "moe_scatter"), "expert_base"), 0); + CHECK(count_op(h[r], "ar_hc_write") > 0); + CHECK(count_op(h[r], "ar_gather_hc_write") > 0); + /* Not ar_rmsnorm_quant_fp8: qwen4exp hands every block's norm `kArNone`, because here + * the reduction rides in the gated residual's WRITE rather than in the norm that + * follows it (qwen4exp_fp8.cpp's block declares). So this one is absent at BOTH world + * sizes -- asserted so, rather than claimed as part of the contrast. */ + CHECK_EQ(count_op(h[r], "ar_rmsnorm_quant_fp8"), 0); + } + } + + /* A WORLD THAT CANNOT REPLICATE -- not a multiple of the KV head count -- is refused by name, + * not rounded into a half head. */ + { + RadBuilder b3; + RadBuildCtx c3 = build_ctx(0, 3); + c3.max_tok = 2048; c3.max_seqs = 8; c3.max_spec = 3; c3.max_ctx = 200000; + CHECK(qwen4exp_fp8::declare(&b3, &meta, &c3) != RAD_OK); + } +} + /* ==================================================================== media */ namespace {