diff --git a/CMakeLists.txt b/CMakeLists.txt index 41a39124..c85afeac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is what /version reports and what a client checks compatibility against. It is NOT the # ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because # a plugin contract and a server release do not move together. -project(radiance VERSION 1.0.9 LANGUAGES C CXX) +project(radiance VERSION 1.0.10 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/NOTICE b/NOTICE index f9c8a359..ca83c120 100644 --- a/NOTICE +++ b/NOTICE @@ -3,7 +3,9 @@ Copyright 2026 Deadcode and the radiance contributors Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14 (the MXFP4 GEMM and the GDN kernels' overflow guards), goodman-b (four-rank tensor parallelism -for Qwen3.8-Flash-Next) and keptn42 (the four-rank all-reduce served in place). +for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the fused four-rank +writes, the n-gram table in RAM and the four-class expert split) and mechkbfan (the token +embedding in the pinned host pool). This product includes software from the following projects, each under the MIT License. The license text is in the file named beside each. diff --git a/README.md b/README.md index 0e3048ef..be911149 100644 --- a/README.md +++ b/README.md @@ -94,9 +94,10 @@ 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, because the fused forms are two-rank. Its exact -all-reduce is one-shot up to 1 MiB a message, which covers decode, and two-shot above that, which -sends half the bytes on a prefill chunk; both produce the same bits. The row above runs exact. +At `--tp 4` the gated residual's write carries the exact all-reduce, with the MoE gather in front +of it, on decode and verify steps; a prefill chunk runs the unfused chain. That chain's exact +all-reduce is one-shot up to 1 MiB a message and two-shot above that, which sends half the bytes +on a prefill chunk; both produce the same bits. The row above runs exact. `--tp-wire wht6` at four ranks selects a different lossy wire, tiered int8 over the two-shot, above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate against diff --git a/abi/rad_builder.h b/abi/rad_builder.h index feb360a3..21da7125 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -130,17 +130,6 @@ typedef struct RadBuildCtx { * * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ int64_t max_out_rows; - - /* WHERE A HOST GATHER OVER A FILE-BACKED TABLE READS ITS ROWS. 0 -- what a zero-initialised - * context gives -- reads them from the container through the kernel's own row cache, holding - * no more of the table than that. Nonzero asks for the whole table copied into locked host - * memory and read from there: a deployment choice, because it costs the table's size in RAM - * (Qwen3.8-Flash-Next's n-gram table is 47.7 GiB) and buys prefill and throughput, and it - * changes no result. The plugin passes it to `embed_lookup_q` as `resident`; a kernel that - * cannot hold the copy says so and reads the file. --ngram-table disk|ram. - * - * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ - int ngram_table_ram; } RadBuildCtx; /* ================================================================== weights */ diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index 2f43630a..6b06bfbf 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -595,9 +595,6 @@ struct Geom { * message anyway. Straight through to `all_reduce`'s `min_bytes`; 0 leaves the choice to * the kernel plugin, which has the measured default. */ int64_t wire_min_bytes = 0; - /* 1 = keep a file-backed table a host gather reads in RAM (--ngram-table ram). Straight - * through to `embed_lookup_q`'s `resident`; RadBuildCtx says what it costs and buys. */ - int ngram_ram = 0; float eps = 1e-6f; /* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and * store `w` around 0.1, not around 1.0 -- so reading the gain as a plain RMSNorm gain shrinks @@ -735,7 +732,6 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c, g.world = c->world_size ? c->world_size : 1; g.wire_exact= c->tp_wire_lossy ? 0 : 1; g.wire_min_bytes = c->tp_wire_min_bytes; - g.ngram_ram = c->ngram_table_ram ? 1 : 0; g.eps = m->rms_eps; g.theta = m->rope_theta; g.rope_scale= m->rope_scale ? m->rope_scale : 1.0f; diff --git a/arch/common/rad_block_hc.h b/arch/common/rad_block_hc.h index c8deb89f..c19c8b6d 100644 --- a/arch/common/rad_block_hc.h +++ b/arch/common/rad_block_hc.h @@ -295,15 +295,21 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const if (!op_write) return RAD_E_INVAL; /* A handle that did not resolve is 0 and not an error: a backend without the fused kernel * keeps the pair, and takes_ar() then answers no on every step. At four ranks only the - * exact form exists, and it takes a step only where ar_wide_write_exact says the - * standalone collective would have been the exact one-shot. */ - if (c.reduce && (g.world == 2 || g.world == 4)) + * exact form exists, declared over the decode and verify steps' rows and taken where + * ar_wide_write_exact says so. The exact form states `wire` 0 rather than leaving it out: + * a row that serves one wire only says so with a constraint on `wire`, and a constraint on + * an absent key does not hold. */ + const int64_t ar_rows = ar_exact_write_rows(g); + if (c.reduce && ar_rows >= 1) op_ar_write = rw(b, RAD_OP(b, "ar_hc_write", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_PARAMS(RAD_RANGE("M", 1, ar_rows), RAD_INT("n", g.n_embd), RAD_INT("hc", c.hc), RAD_INT("world_size", g.world), - RAD_STR("dtype", g.dtype)), + RAD_STR("dtype", g.dtype), RAD_INT("wire", 0)), RAD_NOWEIGHTS), {w.x.x, w.inj, w.h}, {w.x.x, w.h}); + /* The rotated form at two ranks only: the op has no four-rank form on that wire + * (docs/OPS.md), and an op declared that nothing resolves is reported at startup as a + * band a request cannot run in. */ if (op_ar_write && !g.wire_exact && g.world == 2) op_ar_write6 = rw(b, RAD_OP(b, "ar_hc_write", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), @@ -323,11 +329,14 @@ inline int HyperConn::declare_gather(RadBuilder* b, const GatherSrc& src) { if (g.world != 2 && g.world != 4) return RAD_OK; const bool shared = src.sh && src.sg; gsrc = src; - /* EVERY ROW COUNT ONE PASS CARRIES, prefill chunks included: the kernel reads its slots from - * an LDS table at a decode step and from an inverse table at a chunk, where the gather's reads - * then run beside the reduction's push instead of in a launch of their own. */ + /* EVERY ROW COUNT ONE PASS CARRIES, up to the rows the write itself was declared for + * (ar_exact_write_rows): prefill chunks included at two ranks, the decode and verify steps at + * four. The kernel reads its slots from an LDS table at a decode step and from an inverse + * table at a chunk, where the gather's reads then run beside the reduction's push instead of + * in a launch of their own. */ int64_t rows = src.rows; - if (rows > g.max_tok) rows = g.max_tok; + const int64_t ar_rows = ar_exact_write_rows(g); + if (rows > ar_rows) rows = ar_rows; if (rows < 1) return RAD_OK; const rad_buf rd[8] = { src.ye, src.ew, src.sorted, w.x.x, w.inj, w.h, src.sh, src.sg }; const rad_buf wr[2] = { w.x.x, w.h }; @@ -339,7 +348,8 @@ inline int HyperConn::declare_gather(RadBuilder* b, const GatherSrc& src) { RAD_INT("hc", c.hc), RAD_INT("top_k", src.top_k), RAD_INT("world_size", g.world), RAD_STR("dtype", g.dtype), - RAD_STR("act", shared ? "sigmoid" : "none")), + RAD_STR("act", shared ? "sigmoid" : "none"), + RAD_INT("wire", 0)), RAD_NOWEIGHTS); if (op_ar_gather_write) { RAD_ARCH_TRY(rad_op_reads (b, op_ar_gather_write, rd, shared ? 8 : 6)); diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h index 48772c1d..8cdadd25 100644 --- a/arch/common/rad_block_moe_fp8.h +++ b/arch/common/rad_block_moe_fp8.h @@ -198,12 +198,6 @@ struct MoeFP8 { * The arm's stages run behind the routed ones on the same queue (see pass()): a routed * GEMM's tail leaves compute units idle, and the arm fills them. */ int64_t shared_lo = 0, shared_hi = 0; - /* THIS RANK'S PLACE WHERE THE PLAIN EXPERTS' 64-WIDE TILES DO NOT DIVIDE over the ranks: - * the first places take one tile more. -1 is the rank's own index. A permutation of the - * ranks, the same on every rank, so every tile still has exactly one owner; the - * architecture sets it above two ranks to keep the extra tiles off the ranks that already - * take the routed experts' extra blocks. */ - int64_t extra_place = -1; int norm_topk = 1; /* renormalise the kept routing weights to sum to one */ /* THE EXPERT WEIGHT AT FOUR BITS rather than E4M3, which for Qwen3.8-Flash-Next is the * difference between a model that fits two cards and one that does not (the registry row @@ -1144,12 +1138,12 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, /* ONE SLICE A RANK, and it does not have to be the same size on every rank: an uneven * share of the 64-wide tiles is still whole tiles, and an uneven share is the only * kind available when the width does not divide -- this family's 640 columns are ten - * tiles, which four ranks take as 2, 2, 3, 3 (Config::extra_place puts ranks 2 and 3 - * first, the ranks without a routed extra block). Every tile has exactly one owner, - * each rank writes its own columns of gate/up and reads its own of down, and the - * block's all-reduce sums the partials exactly as it does for the quantised experts - * and for the shared arm. The even case keeps the even-split declaration verbatim -- - * no span at all -- so a rank count that divides declares exactly as it did before. */ + * tiles, which four ranks take as 3, 3, 2, 2, the first ranks by index taking the + * extra ones. Every tile has exactly one owner, each rank writes its own columns of + * gate/up and reads its own of down, and the block's all-reduce sums the partials + * exactly as it does for the quantised experts and for the shared arm. The even case + * keeps the even-split declaration verbatim -- no span at all -- so a rank count that + * divides declares exactly as it did before. */ psh_row = RAD_SHARD_ROW; psh_col = RAD_SHARD_COL; pparts = 2; @@ -1161,16 +1155,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, return RAD_E_INVAL; } else { const int64_t nt = full / 64, base = nt / g.world, extra = nt % g.world; - /* Cut by the rank's place (Config::extra_place), not necessarily its index -- - * except in a layer served at four classes. The place exists to keep these tiles - * off the ranks holding the routed extra blocks, and at four classes every rank - * holds one; the shared expert's extra block is cut by the same place, so the - * rank's own index keeps the two remainders apart instead. */ - const int64_t pr = (c.extra_place >= 0 && ncls != 4) ? c.extra_place - : (int64_t)g.rank; - if (pr >= g.world) return RAD_E_INVAL; - const int64_t t0 = pr * base + std::min(pr, extra); - const int64_t t1 = t0 + base + (pr < extra ? 1 : 0); + const int64_t t0 = (int64_t)g.rank * base + std::min(g.rank, extra); + const int64_t t1 = t0 + base + ((int64_t)g.rank < extra ? 1 : 0); plo = t0 * 64; phi = t1 * 64; wp = phi - plo; diff --git a/arch/common/rad_block_ple.h b/arch/common/rad_block_ple.h index cfa39213..8a82cfc5 100644 --- a/arch/common/rad_block_ple.h +++ b/arch/common/rad_block_ple.h @@ -367,18 +367,19 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C {}, {b_ids}); /* M IS T * heads HERE, not T: the gather fetches one table row per HEAD per token, and the - * band this op resolves on is that count. `resident` only when the deployment asked for the - * table in RAM (--ngram-table ram), so the default declares exactly the op it always has. */ - const RadParam gp[] = { RAD_RANGE("M", 1, g.max_tok * c.heads), RAD_INT("n_embd", HD), - RAD_INT("n_vocab", c.rows), RAD_STR("dtype", g.dtype), - RAD_INT("resident", 1) }; - const int n_gp = g.ngram_ram ? 5 : 4; + * band this op resolves on is that count. */ if (table_bf16) - op_gather = rw(b, RAD_OP(b, "embed_lookup_q", gp, n_gp, RAD_WEIGHTS(w_table)), - {b_ids}, {b_emb}); + op_gather = rw(b, RAD_OP(b, "embed_lookup_q", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * c.heads), RAD_INT("n_embd", HD), + RAD_INT("n_vocab", c.rows), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_table)), + {b_ids}, {b_emb}); else - op_gather = rw(b, RAD_OP(b, "embed_lookup_q", gp, n_gp, RAD_WEIGHTS(w_table, w_scale)), - {b_ids}, {b_emb}); + op_gather = rw(b, RAD_OP(b, "embed_lookup_q", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * c.heads), RAD_INT("n_embd", HD), + RAD_INT("n_vocab", c.rows), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_table, w_scale)), + {b_ids}, {b_emb}); op_embd = rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim), diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index ed84f41b..ac21e9b4 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -324,33 +324,53 @@ inline bool ar_fused_ok(const Geom& g, int64_t T) { return ar_wire_is_exact(g, T) || (g.n_embd % kArWire6Chunk) == 0; } +/* THE FOUR-RANK LOSSY WIRE'S TILE: tiered int8 in groups of 32, and a group may not straddle one + * of the four shards, so a message whose element count is not a multiple of 128 goes out exact. + * Stated here for the reason the rotation's group of 64 is stated in ar_wire_is_exact: the + * architecture has to decide, identically on every rank, which wire a step's message takes. */ +static const int64_t kArWideWireTile = 128; + +/* THE MOST ROWS A DECODE OR SPECULATIVE-VERIFY STEP CARRIES: one a sequence, and 1 + max_spec a + * sequence at a verify (max_spec is 0 with speculation off), never more than max_tok. It is a fact + * about this engine's own steps, which is why the architecture holds it. The four-rank fused write + * and its gather are declared over M up to this, and ar_wide_write_exact takes no step above it, so + * a step sent to them is always inside the range they were resolved for. */ +inline int64_t ar_wide_write_rows(const Geom& g) { + const int64_t r = g.max_seqs * (1 + (g.max_spec > 0 ? g.max_spec : 0)); + return r < g.max_tok ? r : g.max_tok; +} + +/* THE ROWS THE EXACT FUSED WRITE IS DECLARED FOR: every step at two ranks, the decode and verify + * steps at four (ar_wide_write_rows), and none at any other width. */ +inline int64_t ar_exact_write_rows(const Geom& g) { + if (g.world == 2) return g.max_tok; + if (g.world == 4) return ar_wide_write_rows(g); + return 0; +} + /* THE FOUR-RANK FUSED WRITE'S STEPS. At four ranks ar_hc_write exists on the exact wire only, and - * it is the exact ONE-SHOT with the write behind it -- so it may take a message only where the - * standalone `all_reduce` would have sent that message exact and as a one-shot: + * it is the exact ONE-SHOT with the write behind it. A step takes it where both of these hold: * - * exact --tp-wire exact, or a message the four-rank lossy row serves exactly itself: its - * tiered-int8 groups of 32 must tile each of the four shards (numel % 128), and below - * `min_bytes` it hands the message to the exact entry. ar_wire_is_exact's three facts, - * with that wire's tile. - * one-shot under 1 MiB. From there libr4d's exact entry runs the two-shot instead - * (R4D_AR_EXACT_TWOSHOT_MIN_BYTES, r4d_ar_entry.hip), which moves half the bytes, so - * the pair stays. Either way the bytes are the same; this bound is a cost, not a - * correctness line. + * rows T is at most ar_wide_write_rows. The fused kernel is a one-shot, and the messages a + * one-shot is for are the decode and verify steps'. A larger step -- a prefill chunk -- + * keeps the pair, and there the standalone `all_reduce`'s own size bands choose the + * one-shot or the two-shot: where that choice falls is the kernel library's to say, + * so the architecture holds no copy of it. The fused one-shot serves any message it was + * declared for with the same bytes, so this bound is a cost, not a correctness line. + * exact --tp-wire exact, or a message the four-rank lossy row serves exactly itself: one + * kArWideWireTile does not tile, or one under `min_bytes`, both of which that row hands + * to the exact sum. ar_wire_is_exact's three facts, with that wire's tile. * * ar_wire_is_exact itself stays false off two ranks: the embedding's collective asks it whether - * layer 0's fused norm absorbs that reduction, and at four no norm does. Both ranks evaluate this - * on the same T, so neither can take a different branch. */ -static const int64_t kArWideWireTile = 128; -static const int64_t kArWideOneshotBytes = 1024 * 1024; - + * layer 0's fused norm absorbs that reduction, and at four no norm does. Every rank evaluates this + * on the same T, so none can take a different branch. */ inline bool ar_wide_write_exact(const Geom& g, int64_t T) { - if (g.world != 4) return false; + if (g.world != 4 || T < 1 || T > ar_wide_write_rows(g)) return false; const int64_t numel = T * g.n_embd; - const int64_t bytes = numel * 2; /* bf16 on the wire */ - if (numel <= 0 || bytes >= kArWideOneshotBytes) return false; + if (numel <= 0) return false; if (g.wire_exact) return true; if (numel % kArWideWireTile) return true; - return bytes < g.wire_min_bytes; + return numel * 2 < g.wire_min_bytes; /* bf16 on the wire */ } /* WHETHER A GATED RESIDUAL'S EXACT FUSED WRITE TAKES THE ALL-REDUCE AT T ROWS: at two ranks on every @@ -367,7 +387,7 @@ inline bool ar_exact_write_takes(const Geom& g, int64_t T) { * (ar_fused_ok); * kArOutExact a gated residual's write with the exact fused form only, so a message that would * go out compressed stays with the block (ar_exact_write_takes -- at four ranks - * also one the standalone row would send as a two-shot); + * also one of a step larger than a decode or verify step); * kArOutBoth a gated residual's write with a fused form on each wire, which takes every * message (HyperConn::ar_take). */ enum ArOut : int { @@ -390,7 +410,8 @@ inline bool ar_taken(const Geom& g, int64_t T, bool out, int take) { * wire, 0 where it was not: at most the tokens one MoE pass carries, so a step it serves is one * pass whose gather is the whole step's. The wire the step's message goes out on picks the bound: * the exact one wherever the exact fused write takes the step (ar_exact_write_takes -- at two - * ranks ar_wire_is_exact itself, at four the exact one-shot's steps, where `rows6` is always 0). + * ranks ar_wire_is_exact itself, at four the decode and verify steps on the exact wire, where + * `rows6` is always 0). * The block that would issue the gather and the write that would absorb it ask this of the same T * and the same bounds, so neither can skip it while the other issues it. */ inline bool gather_taken(const Geom& g, int64_t T, int64_t rows, int64_t rows6) { diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index 4d08c552..cf5778dc 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -292,28 +292,18 @@ static int64_t ngram_table_rows(int64_t base, int64_t heads, int64_t divisor) { return divisor > 1 ? ((total + divisor - 1) / divisor) * divisor : total; } -/* A RANK'S PLACE WHEN A WIDTH THAT DOES NOT DIVIDE IS CUT OVER THE RANKS, the first places taking - * one unit more: the ranks in order of how many 128-column blocks of an even/odd pair of routed - * experts declare()'s parity split gives each, fewest first, by rank among equals. At four ranks - * and five blocks that is ranks 2, 3, 0, 1 -- under parity ranks 0 and 1 hold the routed extra - * blocks, and cutting the shared expert from rank 0 as well would stack its extra columns on the - * ranks every block's all-reduce already waits for. The four-class split that four ranks serve - * gives every rank the same routed width, and the shared expert's extra block stays rank 2's: the - * plain experts' extra tiles are cut by rank there (MoeFP8::declare), so the two do not stack. - * Where the routed width divides it is the rank; declare() asks only above two ranks. */ -static int64_t narrow_place(int64_t n_ff_all, int world, int rank) { - const int64_t nb = n_ff_all / RAD_FP8_BLOCK; - if (n_ff_all % RAD_FP8_BLOCK || nb < world || nb % world == 0) return rank; - auto blocks = [&](int r) { - int64_t n = 0; - for (int q = 0; q < 2; ++q) - n += nb / world + ((r - q + world) % world < nb % world ? 1 : 0); - return n; - }; - int64_t place = 0; - for (int r = 0; r < world; ++r) - if (blocks(r) < blocks(rank) || (blocks(r) == blocks(rank) && r < rank)) ++place; - return place; +/* A RANK'S PLACE WHERE THE SHARED EXPERT'S BLOCKS DO NOT DIVIDE over the ranks, the first places + * taking one block more. A plain expert is a routed expert's width in 64-wide tiles, which need + * not divide either, and MoeFP8::declare hands its extra tiles to the first ranks by index; the + * shared expert's extra blocks start at the rank after the last of those, so the two remainders + * land on different ranks while there are ranks enough for both. The routed experts leave no + * remainder to avoid: at two ranks the parity split and at four the four-class split give every + * rank the same width of them. At four ranks and this family's 640 columns -- ten tiles, five + * blocks -- ranks 0 and 1 take a tile more and rank 2 the block; at two the ten tiles divide and + * the place is the rank. */ +static int64_t shared_place(int64_t n_ff_all, int world, int rank) { + const int64_t first = (n_ff_all / 64) % world; + return (rank - first + world) % world; } static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { @@ -429,15 +419,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c mc.n_ff_exp = g.n_ff; mc.n_ff_shared = meta_int2(meta, "qwen4exp.expert_shared_feed_forward_length", "shared_expert_intermediate_size", 0); - /* This rank's place where a remainder is handed out: the rank itself at one or two ranks, - * and above that the narrow ranks first (narrow_place). The plain experts' tile split in - * MoeFP8 takes the same place. */ - const int64_t place = g.world > 2 ? narrow_place(g.n_ff_all, g.world, g.rank) : g.rank; - mc.extra_place = g.world > 2 ? place : -1; /* THE SHARED ARM IS SPLIT BY WHOLE fp8 SCALE BLOCKS: evenly when its width halves into - * them, and otherwise as evenly as whole blocks allow -- this family's 640 columns are - * five blocks, three on rank 0 and two on rank 1; at four ranks two on rank 2 and one on - * each of the others. See MoeFP8::Config::shared_lo. */ + * them, and otherwise as evenly as whole blocks allow, cut by the rank's place + * (shared_place) -- this family's 640 columns are five blocks, three on rank 0 and two on + * rank 1; at four ranks two on rank 2 and one on each of the others. See + * MoeFP8::Config::shared_lo. */ if (mc.n_ff_shared > 0 && g.world > 1 && (mc.n_ff_shared / g.world) % RAD_FP8_BLOCK == 0) { int s; if ((s = divide_or_fail(mc.n_ff_shared, g.world, @@ -453,6 +439,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } const int64_t nb = mc.n_ff_shared / RAD_FP8_BLOCK; const int64_t base = nb / g.world, extra = nb % g.world; + const int64_t place = shared_place(g.n_ff_all, g.world, g.rank); const int64_t b0 = place * base + std::min(place, extra); const int64_t b1 = b0 + base + (place < extra ? 1 : 0); mc.shared_lo = b0 * RAD_FP8_BLOCK; @@ -528,9 +515,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * the extra block is rotated over four places, by the expert's number mod 4: four slice * tables (`moe_gemm_q_mod4`), and every rank computes five blocks of every four experts. * A layer keeping two experts plain bf16 has 510 quantised ones, and its first two classes - * are one expert longer. What does not divide elsewhere stays apart: the shared expert's - * extra block is rank 2's (narrow_place) and the plain experts' extra tiles ranks 0 and - * 1's (MoeFP8::declare). + * are one expert longer. What does not divide elsewhere stays apart: the plain experts' + * extra tiles are ranks 0 and 1's (MoeFP8::declare) and the shared expert's extra block + * rank 2's (shared_place). * * 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 @@ -592,14 +579,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c mc.ff_hi[q] = b1 * RAD_FP8_BLOCK; } mc.n_ff_exp = std::max(mc.ff_hi[0] - mc.ff_lo[0], mc.ff_hi[1] - mc.ff_lo[1]); - rad_note(b, "routed experts: rank %d computes columns [%lld, %lld) of each even " - "expert and [%lld, %lld) of each odd one, of %lld. The width is %lld " - "blocks of %d, which %lld ranks split unevenly, so the rank taking the " - "extra block alternates with the expert's parity; the block's " - "all-reduce sums the partials.", - g.rank, (long long)mc.ff_lo[0], (long long)mc.ff_hi[0], - (long long)mc.ff_lo[1], (long long)mc.ff_hi[1], (long long)g.n_ff_all, - (long long)nb, RAD_FP8_BLOCK, (long long)g.world); /* AND AT FOUR RANKS FOUR CLASSES, by the expert's number mod 4 (MoeFP8::Config:: * ff_lo4), which every layer then takes instead: the same cut with the rank's place * shifted by the class, so the extra block goes round all four ranks instead of @@ -622,6 +601,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c (long long)mc.ff_lo4[1], (long long)mc.ff_hi4[1], (long long)mc.ff_lo4[2], (long long)mc.ff_hi4[2], (long long)mc.ff_lo4[3], (long long)mc.ff_hi4[3], (long long)nb); + } else { + rad_note(b, "routed experts: rank %d computes columns [%lld, %lld) of each " + "even expert and [%lld, %lld) of each odd one, of %lld. The width " + "is %lld blocks of %d, which %lld ranks split unevenly, so the rank " + "taking the extra block alternates with the expert's parity; the " + "block's all-reduce sums the partials.", + g.rank, (long long)mc.ff_lo[0], (long long)mc.ff_hi[0], + (long long)mc.ff_lo[1], (long long)mc.ff_hi[1], + (long long)g.n_ff_all, (long long)nb, RAD_FP8_BLOCK, + (long long)g.world); } } else { fprintf(stderr, "radiance: qwen4exp: an expert is %lld blocks of %d, which %d ranks " diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 3d63b4e2..fcf5f8f6 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -684,15 +684,17 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, * A RAD_OPD_WTAB position consumes a RUN of declared weights, so the count alone does not * say how the list divides. The rule is EQUAL DIVISION: whatever is left after the fixed * weight positions have taken one each is split evenly across the table positions, in - * declaration order. That is exactly right for the case tables exist for -- `moe_gemm_q`'s + * declaration order. That is exactly right for the case tables exist for -- a grouped GEMM's * codes and scale planes are one of each per expert, always the same count. * * WHERE IT DOES NOT COME OUT WHOLE, THE FIRST POSITIONS TAKE ONE MORE. A grouped GEMM whose - * experts are classes by number mod C -- `moe_gemm_q_mod4` -- gives its first `n % C` classes - * one expert more than the rest, and its tables are each class's codes then its scales, so - * that is exactly the first `2 * (n % C)` positions. Any other grouping is still refused, at - * issue, by the run checks: a table that is not one contiguous run of one shape. A list - * shorter than the tables is refused here. */ + * n experts are C classes by number mod C, declared class by class as a codes table and a + * scales table each, gives its first `n % C` classes one expert more than the rest -- exactly + * the positions this rule lengthens. A list grouped any other way is refused at issue: the + * plugin names each table's run there, and a run other than the one this division bound is + * refused. A bound run must also be contiguous, checked when the tables are bound before the + * first step, and its entries of one shape, checked at its first issue. A list shorter than + * the tables is refused here. */ int per_tab = 0, tab_extra = 0; if (n_tab > 0) { const int rest = n_w - w_max; diff --git a/core/config.cpp b/core/config.cpp index bf3b67a0..5770750b 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -57,16 +57,19 @@ static const Flag g_flags[] = { { "--vram-kv-mib", "N", "the paged KV pool; 0 derives it from the card" }, { "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" }, { "--host-pool-mib", "N", "pinned host tier" }, - { "--host-weights", "NAMES", "embedding tables to keep in the pinned host pool, read in place\n" - " over the link: comma-separated weight names, a trailing *\n" - " matching a prefix (token_embd.weight)" }, + { "--embedding-placement", "WHERE", "auto (default) | vram | ram: where the token embedding lives. ram\n" + " keeps it in the pinned host pool, read over the link in place;\n" + " auto keeps it on the card unless the KV cache could then not\n" + " hold one --max-model-len sequence. disk is refused: the lookup\n" + " writes the card's activations, which no host read can reach" }, + { "--ngram-placement", "WHERE", "auto (default) | ram | disk: where an n-gram embedding table\n" + " lives (Qwen3.8-Flash-Next: 47.7 GiB). disk reads its rows from\n" + " the container; ram copies it into locked memory at load; auto\n" + " takes ram when free memory, the memlock limit and the cgroup\n" + " allow it. vram is refused: only a host kernel reads the table" }, { "--weights-disk-tier", nullptr, "read weights that fit neither VRAM nor the host pool from the\n" " container on disk (O_DIRECT); a routed expert is read a layer\n" " at a time, so a step is paced by the drive" }, - { "--ngram-table", "MODE", "disk (default) or ram: where the n-gram embedding's host gather\n" - " reads its rows. ram copies the table into locked host memory\n" - " in the background from the first request and reads the copy\n" - " (Qwen3.8-Flash-Next: 47.7 GiB; needs a memlock limit that large)" }, { "--prefix-cache-host-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n" " so their VRAM can go to experts and a return restores\n" " instead of re-prefilling. 0 is off. Part of it holds\n" @@ -217,6 +220,17 @@ void config_usage(const char* argv0) { "benchmarks do not reproduce.\n"); } +/* The four names exactly, lower case: what a table's placement costs is the operator's to state, + * so a spelling this build does not know stops the server rather than picking a tier. */ +static bool parse_table_placement(const char* v, TablePlacement* out) { + if (!std::strcmp(v, "auto")) *out = TablePlacement::Auto; + else if (!std::strcmp(v, "vram")) *out = TablePlacement::Vram; + else if (!std::strcmp(v, "ram")) *out = TablePlacement::Ram; + else if (!std::strcmp(v, "disk")) *out = TablePlacement::Disk; + else return false; + return true; +} + static std::vector split_commas(const std::string& s) { std::vector out; size_t i = 0; @@ -384,30 +398,17 @@ int config_parse(int argc, char** argv, Config* c) { } } else if (S("--host-pool-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->host_pool_mib = atoll(v); } - else if (S("--host-weights")) { + else if (S("--embedding-placement") || S("--ngram-placement")) { + const bool emb = S("--embedding-placement"); if (!(v = need(i))) return RAD_E_INVAL; - c->host_weights.clear(); - for (std::string p : split_commas(v)) { - p.erase(0, p.find_first_not_of(" \t")); - p.erase(p.find_last_not_of(" \t") + 1); - if (p.empty() || p == "*") { - RAD_ERR("--host-weights: '%s' is not a weight name", p.c_str()); - return RAD_E_INVAL; - } - c->host_weights.push_back(p); - } - if (c->host_weights.empty()) { - RAD_ERR("--host-weights: no weight names in '%s'", v); + TablePlacement p; + if (!parse_table_placement(v, &p)) { + RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v); return RAD_E_INVAL; } + (emb ? c->embedding_placement : c->ngram_placement) = p; } else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; } - else if (S("--ngram-table")) { - if (!(v = need(i))) return RAD_E_INVAL; - if (!std::strcmp(v, "disk")) c->ngram_table_ram = false; - else if (!std::strcmp(v, "ram")) c->ngram_table_ram = true; - else { RAD_ERR("--ngram-table takes disk or ram, not '%s'", v); return RAD_E_INVAL; } - } else if (S("--prefix-cache-host-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_host_mib = atoll(v); } else if (S("--prefix-cache-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_dir = v; } else if (S("--prefix-cache-disk-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_disk_mib = atoll(v); } diff --git a/core/engine.cpp b/core/engine.cpp index 652e103d..6afcb425 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -80,6 +80,8 @@ Engine::~Engine() { for (auto& r : ranks_) r->ctx.shutdown(); step_state_fini(); ranks_.clear(); + for (TableCopy& c : table_copies_) table_copy_free(&c); + table_copies_.clear(); rad_tools_registry().close(); } @@ -1619,7 +1621,12 @@ std::string Engine::engine_info() const { e["tp_wire_min_kb"] = cfg_.tp_wire_exact ? 0 : cfg_.tp_wire_min_kb; e["max_num_batched_tokens"] = cfg_.max_tok; e["placement"] = cfg_.placement; - e["host_weights"] = cfg_.host_weights; + /* What each lookup table was asked for and where it went: auto's answer is the one a + * dashboard reading this needs, and the request is the one the command line shows. */ + e["embedding_placement"] = { { "asked", table_placement_name(cfg_.embedding_placement) }, + { "resolved", table_placement_name(cfg_.embedding_resolved) } }; + e["ngram_placement"] = { { "asked", table_placement_name(cfg_.ngram_placement) }, + { "resolved", table_placement_name(cfg_.ngram_resolved) } }; e["prefix_cache"] = cfg_.prefix_cache; e["checkpoint_slots"] = cfg_.checkpoint_slots; e["deterministic"] = cfg_.deterministic; diff --git a/core/engine.h b/core/engine.h index 971cd92a..9917e12e 100644 --- a/core/engine.h +++ b/core/engine.h @@ -28,6 +28,7 @@ #include "runtime/rank_barrier.h" #include "text/tokenizer.h" #include "format/radfile.h" +#include "format/table_copy.h" #include #include @@ -44,6 +45,8 @@ struct TierPump; struct TierJob; struct StepSlot; +struct VramFacts; /* mem/vram_budget.h */ + class Engine { public: explicit Engine(Config cfg); @@ -115,6 +118,18 @@ private: int read_checkpoint_metadata(); int declare(); int plan(); + /* --embedding-placement and --ngram-placement, resolved into Config before the card is split + * (engine_bringup.cpp says how auto chooses). */ + int resolve_table_placement(const std::vector& facts, + const std::vector& emb_bytes, int64_t kv_floor, + int64_t ngram_bytes, bool ngram_device); + /* --ngram-placement ram: the locked copy of the container's [src, src + n), file offset `foff`, + * made once and shared by every rank. */ + int lock_table_copy(const uint8_t* src, int64_t n, int64_t foff, void** out, std::string* why); + /* The copies made, each [base, base + bytes), and the container address each one copies. + * Unlocked and unmapped in ~Engine after the ranks that read them are gone. */ + std::vector table_copies_; + std::vector> table_copy_of_; int load_weights(); int configure_kv(); /* One sampled row's worth of bookkeeping, so the step loop can map a logits row back to the diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 91ad4711..a893dfda 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -15,6 +15,7 @@ #include "device/directio.h" #include "format/radfile.h" #include "format/share.h" +#include "format/table_copy.h" #include "rad_plugin.h" #include "mem/vram_budget.h" #include "runtime/arena.h" @@ -23,6 +24,7 @@ #include "text/tokenizer.h" #include +#include #include #include @@ -240,6 +242,261 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const } } +/* ------------------------------------------------------------------ locked host memory */ +/* WHAT EVERYTHING ELSE ON THE HOST STILL NEEDS beside a table locked whole: the process's own + * unpooled allocations, the load's staging windows and the page cache the container's hot pages + * live in. A copy that spends the last of it trades a faster gather for the kernel reclaiming + * the files this engine reads, and then for the OOM killer. */ +static const int64_t kLockMargin = (int64_t)4 << 30; + +/* A cgroup limit and what its members use that reclaim cannot give back: memory.current less its + * file pages (cgroup v2) or usage_in_bytes less its cache (v1), since page cache yields to a + * locked allocation and anonymous memory does not. "max" and v1's near-INT64_MAX sentinel are no + * limit. True with `room` set when `dir` holds one. */ +static bool cgroup_room(const std::string& dir, bool v2, int64_t* room) { + auto read_ll = [](const std::string& f, long long* v) { + std::ifstream in(f); + std::string t; + if (!(in >> t)) return false; + char* e = nullptr; + *v = std::strtoll(t.c_str(), &e, 10); + return e && *e == '\0'; + }; + auto stat_ll = [](const std::string& f, const char* key, long long* v) { + std::ifstream in(f); + std::string k; + long long x = 0; + while (in >> k >> x) if (k == key) { *v = x; return true; } + return false; + }; + long long lim = 0, used = 0, file = 0; + if (v2) { + if (!read_ll(dir + "/memory.max", &lim)) return false; /* "max" fails to parse */ + if (!read_ll(dir + "/memory.current", &used)) return false; + (void)stat_ll(dir + "/memory.stat", "file", &file); + } else { + if (!read_ll(dir + "/memory.limit_in_bytes", &lim) || lim >= ((long long)1 << 62)) + return false; + if (!read_ll(dir + "/memory.usage_in_bytes", &used)) return false; + if (!stat_ll(dir + "/memory.stat", "total_cache", &file)) + (void)stat_ll(dir + "/memory.stat", "cache", &file); + } + const long long hard = used > file ? used - file : 0; + *room = lim > hard ? (int64_t)(lim - hard) : 0; + return true; +} + +/* WHETHER `need` MORE BYTES CAN BE LOCKED IN HOST MEMORY, after `still` more that this process + * will allocate before the copy is made, or why not. Each limit is one a copy would otherwise meet + * part way through: RLIMIT_MEMLOCK (unless the process holds CAP_IPC_LOCK), the memory the kernel + * reports available, and every memory cgroup from the process's own up to the root it can see, + * which is the limit Docker's --memory sets and the kernel enforces by killing the process. A + * limit that cannot be read is not one; a limit that can is never guessed at. */ +static bool lockable_room(int64_t need, int64_t still, std::string* why) { + long long locked_kb = 0; + unsigned long long caps = 0; + { + std::ifstream f("/proc/self/status"); + std::string line; + while (std::getline(f, line)) { + (void)std::sscanf(line.c_str(), "VmLck: %lld", &locked_kb); + (void)std::sscanf(line.c_str(), "CapEff: %llx", &caps); + } + } + struct rlimit rl {}; + if (!((caps >> 14) & 1) && ::getrlimit(RLIMIT_MEMLOCK, &rl) == 0 && + rl.rlim_cur != RLIM_INFINITY && (int64_t)rl.rlim_cur < locked_kb * 1024 + need) { + *why = fmt("RLIMIT_MEMLOCK allows %s locked and the copy locks %s (Docker: --ulimit " + "memlock=-1; systemd: LimitMEMLOCK=infinity)", humanb((int64_t)rl.rlim_cur).c_str(), + humanb(need).c_str()); + return false; + } + { + std::ifstream f("/proc/meminfo"); + std::string line; + long long kb = -1; + while (std::getline(f, line)) + if (std::sscanf(line.c_str(), "MemAvailable: %lld kB", &kb) == 1) break; + if (kb >= 0 && kb * 1024 - still - kLockMargin < need) { + *why = fmt("%s of memory is available, %s more is still to be allocated (the pinned " + "host pools and the prefix cache's host tier), and the copy wants %s with %s " + "to spare", humanb(kb * 1024).c_str(), humanb(still).c_str(), + humanb(need).c_str(), humanb(kLockMargin).c_str()); + return false; + } + } + /* /proc/self/cgroup: "0::/path" on v2, "N:memory:/path" (or a comma list naming memory) on v1. + * Each level up to the root of the hierarchy this process can see is a limit of its own. */ + std::ifstream f("/proc/self/cgroup"); + std::string line; + while (std::getline(f, line)) { + const size_t a = line.find(':'), b = a == std::string::npos ? a : line.find(':', a + 1); + if (b == std::string::npos) continue; + const std::string ctrl = line.substr(a + 1, b - a - 1); + std::string path = line.substr(b + 1); + const bool v2 = ctrl.empty(); + bool memory = v2; + for (size_t i = 0; !memory && i < ctrl.size();) { + const size_t j = std::min(ctrl.find(',', i), ctrl.size()); + memory = ctrl.compare(i, j - i, "memory") == 0; + i = j + 1; + } + if (!memory) continue; + const std::string root = v2 ? "/sys/fs/cgroup" : "/sys/fs/cgroup/memory"; + for (;;) { + const std::string dir = root + (path == "/" ? std::string() : path); + int64_t room = 0; + if (cgroup_room(dir, v2, &room) && room - still - kLockMargin < need) { + *why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, " + "and the copy wants %s with %s to spare", dir.c_str(), + humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(), + humanb(kLockMargin).c_str()); + return false; + } + if (path.empty() || path == "/") break; + const size_t up = path.find_last_of('/'); + path = up == 0 || up == std::string::npos ? "/" : path.substr(0, up); + } + } + return true; +} + +/* --ngram-placement ram: the copy is table_copy_make's (core/format/table_copy.h); this keeps one + * a container address, shared by every rank, and frees them after the ranks in ~Engine. */ +int Engine::lock_table_copy(const uint8_t* src, int64_t n, int64_t foff, void** out, + std::string* why) { + for (const auto& c : table_copy_of_) + if (c.first == src) { *out = c.second; return RAD_OK; } + const auto t0 = std::chrono::steady_clock::now(); + TableCopy tc; + const int rc = table_copy_make(*file_, src, n, foff, &tc, why); + if (rc != RAD_OK) return rc; + RAD_INFO("placement: n-gram table copied into locked memory, %s in %.1f s", + humanb(n).c_str(), + std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + table_copies_.push_back(tc); + table_copy_of_.push_back({ src, tc.base }); + *out = tc.base; + return RAD_OK; +} + +/* WHERE THE TWO LOOKUP TABLES GO (--embedding-placement, --ngram-placement), decided once for every + * rank before the card is split, and written into Config for the planner and the load phase. + * + * THE EMBEDDING: Auto keeps it on the card -- where every other weight a step reads lives -- + * unless that leaves the split unable to hold the fixed weights, or leaves a derived KV pool + * unable to hold one --max-model-len sequence (`kv_floor`); then the pinned host pool takes it if + * --host-pool-mib can, the card's lookup reading it over the link in place. Disk is refused: the + * lookup writes the activations a card reads, which a host kernel reading the container cannot + * reach -- an architecture declares a buffer's domain, and the token embedding's is the device. + * + * THE N-GRAM TABLE: only a host kernel reads one today, so Vram is refused and the choice is + * between a locked copy in RAM and the container. Auto takes RAM when lockable_room says the + * memory, the memlock limit and every cgroup allow it after the pools still to be allocated. */ +int Engine::resolve_table_placement(const std::vector& facts, + const std::vector& emb_bytes, int64_t kv_floor, + int64_t ngram_bytes, bool ngram_device) { + const int64_t MiB = (int64_t)1 << 20; + int64_t emb_max = 0; + for (int64_t b : emb_bytes) emb_max = std::max(emb_max, b); + + TablePlacement emb = cfg_.embedding_placement; + std::string emb_why; + if (emb == TablePlacement::Disk) { + RAD_ERR("--embedding-placement disk: the token embedding's lookup writes activations the " + "card reads, and a host kernel reading the container cannot write them -- the " + "architecture declares that buffer on the device. Use vram, ram or auto."); + return RAD_E_INVAL; + } + if (emb_max == 0) { + if (emb == TablePlacement::Ram) { + RAD_ERR("--embedding-placement ram: this model has no token embedding table that only " + "embed_lookup reads. An output head tied to the table reads it too, and would " + "stream it over the link every step."); + return RAD_E_INVAL; + } + emb = TablePlacement::Vram; + emb_why = "no table only embed_lookup reads"; + } else if (emb == TablePlacement::Auto) { + VramBudget tb; + const int st = vram_budget_trial(cfg_, facts, &tb); + const bool holds = st == RAD_OK && (!tb.derived_kv || tb.kv >= kv_floor); + const bool host = cfg_.host_pool_mib * MiB >= emb_max; + if (holds) { + emb = TablePlacement::Vram; + emb_why = "the card holds it beside the other weights and a KV pool for one " + "--max-model-len sequence"; + } else if (host) { + emb = TablePlacement::Ram; + emb_why = st != RAD_OK + ? "the card cannot hold the other weights with it, and the pinned host pool can" + : fmt("with it on the card the KV pool is %s, short of the %s one --max-model-len " + "sequence needs, and the pinned host pool can hold it", + humanb(tb.kv).c_str(), humanb(kv_floor).c_str()); + } else { + emb = TablePlacement::Vram; + emb_why = fmt("the card is short of room for it, and --host-pool-mib %lld cannot hold " + "%s either", (long long)cfg_.host_pool_mib, humanb(emb_max).c_str()); + } + } else { + emb_why = "as asked"; + } + cfg_.embedding_resolved = emb; + + TablePlacement ng = cfg_.ngram_placement; + std::string ng_why; + if (ngram_device) { + if (ng == TablePlacement::Ram || ng == TablePlacement::Disk) { + RAD_ERR("--ngram-placement %s: a device kernel reads this model's n-gram table, so the " + "placement strategy places it with the other weights; only vram or auto apply", + table_placement_name(ng)); + return RAD_E_INVAL; + } + ng = TablePlacement::Vram; + ng_why = "a device kernel reads it; placed with the other weights"; + } else if (ngram_bytes == 0) { + if (ng != TablePlacement::Auto) + RAD_WARN("--ngram-placement %s: this model has no n-gram table, so there is nothing to " + "place", table_placement_name(ng)); + ng = TablePlacement::Disk; + } else if (ng == TablePlacement::Vram) { + RAD_ERR("--ngram-placement vram: no loaded kernel plugin reads an n-gram table on a card " + "(embed_lookup_q has host kernels only), so it is read from host memory or the " + "container: ram or disk"); + return RAD_E_INVAL; + } else if (ng == TablePlacement::Ram || ng == TablePlacement::Auto) { + const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB + + cfg_.prefix_cache_host_mib * MiB; + const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20); + std::string why; + const bool room = lockable_room(need, still, &why); + if (ng == TablePlacement::Ram && !room) { + RAD_ERR("--ngram-placement ram: the n-gram table (%s) cannot be locked in memory: %s", + humanb(ngram_bytes).c_str(), why.c_str()); + return RAD_E_NOMEM; + } + if (ng == TablePlacement::Auto) + ng_why = room ? "the memory, the memlock limit and the cgroups allow a locked copy" + : "a locked copy does not fit: " + why; + else + ng_why = "as asked"; + ng = room ? TablePlacement::Ram : TablePlacement::Disk; + } else { + ng_why = "as asked"; + } + cfg_.ngram_resolved = ng; + + if (emb_max > 0) + RAD_INFO("placement: token embedding (%s a rank) %s%s: %s", humanb(emb_max).c_str(), + table_placement_name(emb), + cfg_.embedding_placement == TablePlacement::Auto ? " (auto)" : "", emb_why.c_str()); + if (ngram_bytes > 0 || ngram_device) + RAD_INFO("placement: n-gram table (%s) %s%s: %s", humanb(ngram_bytes).c_str(), + table_placement_name(ng), + cfg_.ngram_placement == TablePlacement::Auto ? " (auto)" : "", ng_why.c_str()); + return RAD_OK; +} + /* ================================================================== 2. metadata */ /* The model's metadata ONLY -- architecture id, dimensions, quantisation, vocab. Not the weights: * which weights exist is the architecture plugin's answer, not the container's, and reading them @@ -413,7 +670,6 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const { /* A row at every token of the step and the sampler's row a sequence before them * (core/kld.h); the KL mode has no speculation, so a sequence samples one. */ bc.max_out_rows = cfg_.kld() ? max_tok + cfg_.max_seqs : 0; - bc.ngram_table_ram = cfg_.ngram_table_ram ? 1 : 0; return bc; } @@ -707,6 +963,11 @@ int Engine::plan() { std::vector facts; facts.reserve(ranks_.size()); late_step_bytes_ = late_lazy_bytes_ = 0; + /* The placement flags' tables, per rank where they are sharded (the embedding) and once + * where they are not (the n-gram table every rank reads from the one mapping). */ + std::vector emb_bytes; + int64_t ngram_bytes = 0, kv_floor = 0; + bool ngram_device = false; const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; for (auto& r : ranks_) { RAD_TRY(rad_dev_set(r->device)); @@ -744,9 +1005,23 @@ int Engine::plan() { * already this card's even share of the static weights: declare ran once per rank * with every dimension divided. */ WeightFootprint wf; - weight_footprint(r->program, &wf, cfg_.host_weights); + weight_footprint(r->program, &wf, TablePlacement::Vram); f.statics = wf.statics; f.experts = wf.experts; + emb_bytes.push_back(wf.embedding); + ngram_bytes = std::max(ngram_bytes, wf.ngram); + ngram_device = ngram_device || wf.ngram_device; + /* ONE --max-model-len SEQUENCE'S CACHE: the same groups planned for a single + * sequence, which is the least a KV pool can hold and still serve every request the + * API accepts (configure_kv warns below it). --embedding-placement auto keeps the + * table off the card only to stay above it. */ + { + Config one = cfg_; + one.max_seqs = 1; + KVManager single; + if (single.plan_groups(r->program.kv_groups, one) == RAD_OK) + kv_floor = std::max(kv_floor, single.ceiling(ctx)); + } /* THE STAGING REGION IS SIZED ONLY WHERE THE ARENA LENDS ITS TOP: with no smaller level * nothing gives the region back to the slab at decode, and a deterministic plan moves * nothing, so neither can stage or recover what a region would cost. */ @@ -793,6 +1068,9 @@ int Engine::plan() { late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy); facts.push_back(f); } + RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device)); + if (cfg_.embedding_resolved == TablePlacement::Ram) + for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i]; VramBudget vb; RAD_TRY(vram_budget_resolve(cfg_, facts, &vb)); if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str()); @@ -1812,6 +2090,30 @@ int Engine::load_weights() { } w.ptr = (void*)file_->data(p0); w.host_ptr = w.ptr; + /* --ngram-placement ram: the host kernel reads the locked copy instead of the + * mapping. A copy auto chose and could not make leaves the table where it was, and + * says so; one the operator asked for refuses the start. */ + if (cfg_.ngram_resolved == TablePlacement::Ram && + is_ngram_table(r->program, (rad_weight)i)) { + void* copy = nullptr; + std::string why; + const int cs = lock_table_copy((const uint8_t*)w.ptr, n, (int64_t)p0.offset, + ©, &why); + if (cs == RAD_OK) { + w.ptr = copy; + w.host_ptr = copy; + r->mover.publish_mapped((rad_weight)i, w.ptr); + continue; /* reported once, by lock_table_copy, and not as mapped */ + } + if (cfg_.ngram_placement == TablePlacement::Ram) { + RAD_ERR("--ngram-placement ram: '%s' could not be copied into locked " + "memory: %s", w.name.c_str(), why.c_str()); + return cs; + } + RAD_WARN("--ngram-placement auto: '%s' could not be copied into locked memory " + "(%s); it is read from the container", w.name.c_str(), why.c_str()); + cfg_.ngram_resolved = TablePlacement::Disk; + } /* NO READAHEAD ON A MAPPED WEIGHT. What reads one is a host kernel gathering rows * out of it, and the only reason a weight is on this tier at all is that it is far * too big to be resident -- so a fault is a real read from the file and the pages diff --git a/core/format/table_copy.cpp b/core/format/table_copy.cpp new file mode 100644 index 00000000..29e20e66 --- /dev/null +++ b/core/format/table_copy.cpp @@ -0,0 +1,87 @@ +/* table_copy.cpp -- see table_copy.h. */ +#include "table_copy.h" + +#include "../rad_internal.h" + +#include + +#include +#include +#include +#include +#include +#include + +namespace rad { + +int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff, + TableCopy* out, std::string* why) { + if (!out || !why || !src || n <= 0) return RAD_E_INVAL; + *out = TableCopy{}; + const size_t huge = (size_t)2 << 20; + const size_t sz = ((size_t)n + huge - 1) & ~(huge - 1); + void* m = ::mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, + -1, 0); + if (m == MAP_FAILED) { + *why = fmt("mmap of %s: %s", humanb((int64_t)sz).c_str(), std::strerror(errno)); + return RAD_E_NOMEM; + } + (void)::madvise(m, sz, MADV_HUGEPAGE); + if (::mlock2(m, sz, MLOCK_ONFAULT) != 0) { + *why = fmt("mlock2 of %s: %s", humanb((int64_t)sz).c_str(), std::strerror(errno)); + ::munmap(m, sz); + return RAD_E_NOMEM; + } + uint8_t* buf = static_cast(m); + + /* A reader per hardware thread up to sixteen, each reading its own contiguous span in pieces of + * 64 MiB: a drive serves sixteen queued reads at full rate, and the span keeps each reader's + * reads sequential on the file. */ + const int nt = (int)std::max(1u, std::min(16u, std::thread::hardware_concurrency())); + const int64_t piece = (int64_t)64 << 20; + const int64_t span = ((n + nt - 1) / nt + (int64_t)huge - 1) & ~((int64_t)huge - 1); + std::atomic err{RAD_OK}; + std::vector rd; + for (int i = 0; i < nt; ++i) { + const int64_t lo = (int64_t)i * span, hi = std::min(n, lo + span); + if (lo >= hi) break; + rd.emplace_back([&, lo, hi] { + for (int64_t o = lo; o < hi && err.load() == RAD_OK; o += piece) { + const int64_t b = std::min(piece, hi - o); + const int rc = file.read_at(buf + o, b, foff + o); + if (rc < 0) { err.store(rc); return; } + file.drop_range(foff + o, b); + } + }); + } + for (std::thread& t : rd) t.join(); + + bool same = err.load() == RAD_OK; + if (same) { + const int64_t probe = std::min(n, 4096); + same = std::memcmp(buf, src, (size_t)probe) == 0 && + std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0; + for (int64_t o = 0; same && o + 4096 <= n; o += std::max(n / 64, 4096)) + same = std::memcmp(buf + o, src + o, 4096) == 0; + if (!same) *why = "the copy does not match the container's mapping"; + } else { + *why = fmt("reading the container failed (%s)", rad_strerror(err.load())); + } + if (!same) { + ::munlock(m, sz); + ::munmap(m, sz); + return RAD_E_IO; + } + out->base = m; + out->bytes = sz; + return RAD_OK; +} + +void table_copy_free(TableCopy* c) { + if (!c || !c->base) return; + ::munlock(c->base, c->bytes); + ::munmap(c->base, c->bytes); + *c = TableCopy{}; +} + +} /* namespace rad */ diff --git a/core/format/table_copy.h b/core/format/table_copy.h new file mode 100644 index 00000000..2d2e2354 --- /dev/null +++ b/core/format/table_copy.h @@ -0,0 +1,34 @@ +/* table_copy.h -- a container table copied into locked host memory (--ngram-placement ram). + * + * A COPY IN HUGE PAGES, NOT THE MAPPING LOCKED. Faulting a container's mapping in costs a fault every + * 4 KiB page and leaves every row behind a 4 KiB translation, so a gather of scattered rows walks + * the page tables on nearly every row; an anonymous MADV_HUGEPAGE region covers thousands of rows a + * page. The region is locked as each page is first touched (MLOCK_ONFAULT), so nothing filled is + * swapped out while the rest fills; it is read from the container by parallel positional reads, the + * container's pages dropped behind them so the table is not held twice; and it is checked against + * the mapping before anyone is handed it, because a wrong offset would serve every row from the + * wrong place without an error. A host kernel reads an address no file backs as the memory it is + * (libavx's table_file), so no plugin takes part. */ +#pragma once +#include "radfile.h" + +#include +#include +#include + +namespace rad { + +struct TableCopy { + void* base = nullptr; + size_t bytes = 0; /* the mapping's length: the table rounded up to 2 MiB */ +}; + +/* Copies [src, src + n) of `file`'s mapping, which lies at file offset `foff`, into a new locked + * region. RAD_OK with `out` filled, or a refusal with `why` saying what failed and nothing held. */ +int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff, + TableCopy* out, std::string* why); + +/* Unlocks and unmaps it; a copy never made is a no-op. */ +void table_copy_free(TableCopy* c); + +} /* namespace rad */ diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp index 7c67e403..614890ec 100644 --- a/core/mem/vram_budget.cpp +++ b/core/mem/vram_budget.cpp @@ -33,7 +33,10 @@ static double paged_share(const VramBudget& b) { return ctx > 0 ? std::max(0.0, (double)(b.kv - b.kv_fixed)) / ctx : 0.0; } -int vram_budget_resolve(Config& cfg, const std::vector& per_rank, VramBudget* out) { +/* The resolver, with its three log lines behind `log`: vram_budget_trial asks the same question + * of a configuration it may not use, and a refusal printed for a split nobody takes reads as the + * startup failing. */ +static int resolve(Config& cfg, const std::vector& per_rank, VramBudget* out, bool log) { VramBudget b; if (per_rank.empty()) { if (out) *out = b; return RAD_OK; } @@ -115,7 +118,7 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n", humanb(cfg.vram_kv_mib * kMiB).c_str()).c_str(), humanb(-b.claimable).c_str()); - RAD_ERR("%s", b.report.c_str()); + if (log) RAD_ERR("%s", b.report.c_str()); if (out) *out = b; return RAD_E_NOMEM; } @@ -134,7 +137,7 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra /* Not fatal: the planner will demote what does not fit and the model still serves, * badly. Name it, because "why is this model 8x slower than it should be" has no other * answer at startup. */ - RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to " + if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to " "give. Every expert will stream from host memory and the KV cache has " "nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller " "--max-num-batched-tokens.", @@ -234,7 +237,7 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra * because it is a real limit rather than a ratio, is that ONE max-length sequence fits: a * context no single request can complete is a configuration error however much slack the pool * has (core/engine_bringup.cpp, configure_kv). */ - if (b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0) + if (log && b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0) RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), " "%.1f full-length sessions. That is concurrency at length before the scheduler " "preempts, not a bound on any one request. WITH PREFIX CACHING a finished " @@ -351,4 +354,13 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra return RAD_OK; } +int vram_budget_resolve(Config& cfg, const std::vector& per_rank, VramBudget* out) { + return resolve(cfg, per_rank, out, true); +} + +int vram_budget_trial(const Config& cfg, const std::vector& per_rank, VramBudget* out) { + Config c = cfg; + return resolve(c, per_rank, out, false); +} + } /* namespace rad */ diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h index 150a9dd1..4ec20ea7 100644 --- a/core/mem/vram_budget.h +++ b/core/mem/vram_budget.h @@ -24,7 +24,9 @@ * * THE STATIC WEIGHTS COME OFF THE TOP. Everything that is not an expert -- the attention * projections, the norms, the embedding, the head -- has to be resident for the model to run at a - * sensible speed at all, and under tensor parallel each rank already holds its own even share of + * sensible speed at all (the one exception is a token embedding --embedding-placement puts in the + * pinned host pool, which a lookup reads a few rows of in place; weight_footprint counts it out of + * the statics then), and under tensor parallel each rank already holds its own even share of * them (declare runs per rank with every dimension divided, spec §9). They are a FLOOR, not a * share of anything: applying a ratio to the weights as a whole would let --expert-vs-cache-ratio * 0.3 demote the attention projections to host memory to make room for a cache nothing will fill. @@ -114,4 +116,9 @@ struct VramBudget { * Refuses, by name and by how much, when the fixed terms alone exceed the card. */ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, VramBudget* out); +/* The same split worked out on a copy of `cfg`, written nowhere and printed nowhere: for a caller + * deciding between two programs before it resolves the one it keeps (Engine::plan's table + * placement). */ +int vram_budget_trial(const Config& cfg, const std::vector& per_rank, VramBudget* out); + } /* namespace rad */ diff --git a/core/place/mover.cpp b/core/place/mover.cpp index a0d4dd5b..f29c799f 100644 --- a/core/place/mover.cpp +++ b/core/place/mover.cpp @@ -293,10 +293,10 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P * * A staging slot only ever receives a unit read from the container, so sizing it off every * class charges the host pool for classes that are never staged. The widest class is - * typically the embedding table -- its own class, gigabytes wide, and resident in VRAM for - * the whole run -- so sizing on it reserves several times that in pinned memory to receive - * a weight that never arrives, and the file tier is then refused for want of memory it - * did not need. */ + * typically the embedding table -- its own class, gigabytes wide, and never on the file + * tier: in VRAM, or in the pinned host pool by --embedding-placement -- so sizing on it + * reserves several times that in pinned memory to receive a weight that never arrives, and + * the file tier is then refused for want of memory it did not need. */ int64_t widest = 0; for (const MoveUnit& mu : plan.units) { if (mu.tier != Tier::SSD || mu.slab_class < 0) continue; diff --git a/core/place/planner.cpp b/core/place/planner.cpp index 80139b29..3c005b99 100644 --- a/core/place/planner.cpp +++ b/core/place/planner.cpp @@ -37,6 +37,16 @@ const char* tier_name(Tier t) { return "?"; } +const char* table_placement_name(TablePlacement p) { + switch (p) { + case TablePlacement::Auto: return "auto"; + case TablePlacement::Vram: return "vram"; + case TablePlacement::Ram: return "ram"; + case TablePlacement::Disk: return "disk"; + } + return "?"; +} + const char* site_name(Site s) { switch (s) { case Site::Device: return "device"; @@ -91,8 +101,7 @@ int64_t weight_bytes(const WeightInfo& w) { /* See planner.h. Planner::resolve_sites, Planner::build_units and Planner::pin_mapped, run over * the same program without allocating a Plan -- the budget resolver calls this before a Planner * exists. Kept adjacent to the three so a change to any of them has this in the same diff. */ -void weight_footprint(const Program& prog, WeightFootprint* out, - const std::vector& host_weights) { +void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding) { if (!out) return; *out = WeightFootprint{}; @@ -110,7 +119,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, /* build_units: a model-level weight is its own unit, everything else groups by the declared * (layer, expert). Ordered, for the same reason build_units is. */ struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false; - bool hosted = true; }; + bool emb = false, ngram = false; }; std::map, size_t> by_group; std::vector units; @@ -139,10 +148,11 @@ void weight_footprint(const Program& prog, WeightFootprint* out, mu.bytes = align_up(mu.bytes, a) + weight_bytes(wi); /* pin_mapped: THE WHOLE UNIT GOES, not the one weight. */ if (w < device_ok.size() && !device_ok[w]) mu.mapped = true; - /* pin_host_weights: a named model-level weight only lookups read. */ - if (layer >= 0 || !host_weight_match(host_weights, wi.name) || - !read_only_by_lookups(prog, w)) - mu.hosted = false; + /* The placement flags' tables: model-level, so the unit is this one weight. */ + if (layer < 0) { + mu.emb = is_embedding_table(prog, w); + mu.ngram = is_ngram_table(prog, w); + } } /* And one align_up a unit, because that is how Mover::init spends the slab: `us.static_off = @@ -151,8 +161,12 @@ void weight_footprint(const Program& prog, WeightFootprint* out, std::map layer_experts; for (const U& mu : units) { const int64_t b = align_up(mu.bytes, RAD_ALIGN_UNIT); + /* pin_embedding moves a table out of the statics only where nothing has mapped it. */ + if (mu.emb && !mu.mapped) out->embedding += b; + if (mu.ngram && mu.mapped) out->ngram += b; + if (mu.ngram && !mu.mapped) out->ngram_device = true; if (mu.mapped) out->mapped += b; - else if (mu.hosted && mu.layer < 0) out->hosted += b; + else if (mu.emb && embedding == TablePlacement::Ram) out->hosted += b; else if (mu.expert >= 0) { out->experts += b; layer_experts[mu.layer] += b; } else out->statics += b; } @@ -244,6 +258,14 @@ void Planner::pin_mapped(const Program& prog, Plan* p) { mu.site = Site::Host; mu.movable = false; mu.reason = "no device kernel for its op; read from the container's mapping"; + /* --ngram-placement ram: the load phase copies an n-gram table out of the mapping into + * locked memory and publishes the copy, so the host kernel reads RAM instead of the file. + * Every pool still sees the mapped tier; the report shows what the copy costs. */ + if (in_.config->ngram_resolved == TablePlacement::Ram && mu.layer < 0 && + !mu.weights.empty() && is_ngram_table(prog, mu.weights.front())) { + mu.reason = "--ngram-placement ram: a locked copy in RAM, made at load"; + p->ngram_copy_bytes += mu.bytes; + } /* AND ONLY WHAT LIES IN THE CONTAINER AS THE KERNEL READS IT can be read from the mapping: * a weight its kernel rearranges at load, or a shard of one, has no place in the file * that already looks the way the kernel reads it (spec §5.1). */ @@ -521,8 +543,10 @@ struct HostFall { int Planner::assign_all_vram(Plan* p) { int64_t used = 0; for (MoveUnit& mu : p->units) { - /* A MAPPED UNIT IS ALREADY PLACED and no strategy may move it: there is no device kernel - * that could read it anywhere else. Every assignment pass below begins with this line. */ + /* A PREPLACED UNIT IS ALREADY PLACED and no strategy may move it: a mapped one has no + * device kernel that could read it anywhere else, and a token embedding + * --embedding-placement put in the host pool is read there in place. Every assignment pass + * below begins with this line. */ if (mu.preplaced()) continue; mu.tier = Tier::VRAM; mu.site = Site::Device; @@ -665,6 +689,15 @@ int Planner::assign_expert_tiered(Plan* p) { for (const MoveUnit& mu : p->units) if (mu.access != RAD_ACCESS_CONDITIONAL && mu.tier == Tier::VRAM) fixed += mu.slot_bytes; } + /* WHAT LAYER OFFLOAD ALREADY PUT IN THE HOST POOL: the dense units of the layers it spilled. + * The routed experts below are placed again whatever it did with them, but the dense units + * stay where it put them, so the expert fill spends the pool that is left and not the whole + * of --host-pool-mib a second time. */ + int64_t host_spent = 0; + for (const MoveUnit& mu : p->units) + if (!mu.preplaced() && mu.access != RAD_ACCESS_CONDITIONAL && + (mu.tier == Tier::HostPinned || mu.tier == Tier::HostPageable)) + host_spent += mu.slot_bytes; std::vector order; rank_units(p, &order); @@ -677,7 +710,7 @@ int Planner::assign_expert_tiered(Plan* p) { * Two passes, and the second is enough: the reserve depends only on the first pass's slot * counts, and the first pass over-counts (it had more room), so the reserve it produces is an * upper bound. A third pass can only give slots back, never take more. */ - HostFall fall{0, p->host_budget, ssd_}; + HostFall fall{host_spent, p->host_budget, ssd_}; int rc = RAD_OK; /* ONE FILL: the conditional units in rank order, at most `cap` of them resident and the rest to @@ -695,7 +728,7 @@ int Planner::assign_expert_tiered(Plan* p) { } for (SlabClass& sc : p->classes) sc.n_shadow = 0; p->unfit.clear(); - fall = HostFall{0, p->host_budget, ssd_}; + fall = HostFall{host_spent, p->host_budget, ssd_}; rc = RAD_OK; for (int32_t ui : order) { @@ -967,91 +1000,72 @@ void Planner::finish(const Program& prog, Plan* p) { pl.reason = mu.reason; pl.bytes = weight_bytes(prog.weights[w]); p->totals.bytes[(int)mu.tier] += pl.bytes; + if (mu.host_forced) p->embedding_host_used += pl.bytes; } } } -/* ------------------------------------------------------------------ --host-weights */ -/* AN EMBEDDING TABLE THE OPERATOR NAMED goes to the pinned host pool before any strategy runs, and - * stays there. The site is DeviceZeroCopy: the host pool is mapped (Pools::configure), so the - * lookup kernel is handed the pool's device-side address and reads its M rows of n_embd over the - * link in place -- a few KiB a decode step, against a table that is the largest model-level weight - * a dense model has. Measured on Qwen3.8-27B at tp 2, 1.18 GiB a card: decode and prefill within - * noise of the table in VRAM. - * - * ONLY A LOOKUP'S WEIGHT. A GEMM operand placed this way would stream its whole shard every step, - * so a named weight any other op reads is refused rather than served slowly. And a layer unit is - * never eligible: layers belong to the offload strategies. */ -bool host_weight_match(const std::vector& list, const std::string& name) { - for (const std::string& pat : list) { - if (pat.empty()) continue; - if (pat.back() == '*') { - if (name.compare(0, pat.size() - 1, pat, 0, pat.size() - 1) == 0) return true; - } else if (pat == name) { - return true; - } - } - return false; -} - -bool read_only_by_lookups(const Program& prog, rad_weight w) { +/* ------------------------------------------------------------------ the lookup tables */ +bool read_only_by(const Program& prog, rad_weight w, const char* op) { bool read = false; for (const OpInfo& o : prog.ops) for (rad_weight ow : o.weights) if (ow == w) { - if (o.op.compare(0, 12, "embed_lookup") != 0) return false; + if (o.op != op) return false; read = true; } return read; } -int Planner::pin_host_weights(const Program& prog, const Config& cfg, Plan* p) const { - if (cfg.host_weights.empty()) return RAD_OK; - std::vector hits(cfg.host_weights.size(), 0); - int rc = RAD_OK; +/* --embedding-placement ram: THE TOKEN EMBEDDING goes to the pinned host pool before any strategy + * runs, and stays there. The site is DeviceZeroCopy: the host pool is mapped (Pools::configure), + * so the lookup kernel is handed the pool's device-side address and reads its M rows of n_embd + * over the link in place -- a few KiB a decode step -- while the table, the largest model-level + * weight a dense model has, gives its VRAM to the KV cache. Every strategy and every VRAM total + * skips the unit through MoveUnit::preplaced(), as they skip the mapped tier, and weight_footprint + * has already counted it out of the statics with the same test, so the budget the card was split + * by is the one the planner spends. A layer unit is never one: is_embedding_table asks for a + * model-level weight, and a layer belongs to the offload strategies. */ +int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) const { + if (cfg.embedding_resolved != TablePlacement::Ram) return RAD_OK; + int rc = RAD_OK, found = 0; for (MoveUnit& mu : p->units) { /* build_units gives a model-level weight a unit of its own: it is the unit's one weight. */ - if (mu.layer >= 0 || mu.weights.empty()) continue; + if (mu.layer >= 0 || mu.weights.empty() || mu.tier == Tier::Mapped) continue; const rad_weight w = mu.weights.front(); + if (!is_embedding_table(prog, w)) continue; + ++found; const std::string& name = prog.weights[w].name; - bool named = false; - for (size_t i = 0; i < cfg.host_weights.size(); ++i) - if (host_weight_match({ cfg.host_weights[i] }, name)) { ++hits[i]; named = true; } - if (!named || mu.tier == Tier::Mapped) continue; /* mapped is further off the card */ - if (!read_only_by_lookups(prog, w)) { - RAD_ERR("placement: --host-weights names '%s', which an op other than an embedding " - "lookup reads; it would stream over the link every step", name.c_str()); - p->notes.push_back(fmt("--host-weights: '%s' is not only an embedding lookup's", - name.c_str())); - rc = RAD_E_INVAL; - continue; - } if (mu.slot_bytes > p->host_budget) { - RAD_ERR("placement: --host-weights '%s' needs %s of pinned host pool and %s of " - "--host-pool-mib is left%s", name.c_str(), humanb(mu.slot_bytes).c_str(), - humanb(p->host_budget).c_str(), + RAD_ERR("placement: --embedding-placement ram: '%s' needs %s of the pinned host pool " + "and %s of --host-pool-mib is left%s", name.c_str(), + humanb(mu.slot_bytes).c_str(), humanb(p->host_budget).c_str(), p->file_stage_reserve ? " after the file tier's staging" : ""); - p->notes.push_back(fmt("--host-weights: '%s' (%s) does not fit the host pool", - name.c_str(), humanb(mu.slot_bytes).c_str())); + p->notes.push_back(fmt("--embedding-placement ram: '%s' (%s) does not fit the host " + "pool", name.c_str(), humanb(mu.slot_bytes).c_str())); rc = RAD_E_NOMEM; continue; } p->host_budget -= mu.slot_bytes; - p->host_weights_bytes += mu.slot_bytes; + p->embedding_host_bytes += mu.slot_bytes; mu.tier = Tier::HostPinned; mu.site = Site::DeviceZeroCopy; mu.movable = false; mu.host_forced = true; - mu.reason = "--host-weights; read over the link in place"; - RAD_INFO("placement: '%s' (%s) kept in the pinned host pool by --host-weights", - name.c_str(), humanb(mu.bytes).c_str()); + mu.reason = "--embedding-placement ram; read over the link in place"; + RAD_INFO("placement: '%s' (%s) in the pinned host pool, read in place " + "(--embedding-placement %s)", name.c_str(), humanb(mu.bytes).c_str(), + cfg.embedding_placement == TablePlacement::Auto ? "auto" : "ram"); + } + /* Engine::plan resolves Ram only where weight_footprint found a table with this same test, + * so an empty pass is a plan built from a different program than the budget was: a wiring + * fault, said by name rather than leaving the table on the card the budget split without it. */ + if (!found) { + RAD_ERR("placement: --embedding-placement ram, and this rank's program has no model-level " + "weight that only embed_lookup reads"); + p->notes.push_back("--embedding-placement ram: no token embedding table to place"); + rc = RAD_E_STATE; } - /* A NAME THAT MATCHED NOTHING is the operator's intent lost: with a derived budget the weight - * silently stays on the card. Each one is named. */ - for (size_t i = 0; i < hits.size(); ++i) - if (!hits[i]) - RAD_WARN("placement: --host-weights '%s' matched no model-level weight", - cfg.host_weights[i].c_str()); return rc; } @@ -1129,7 +1143,7 @@ int Planner::plan(Plan* out) { } /* NOT a RAD_TRY: a refusal still leaves `out` filled in far enough to print. */ - const int hrc = pin_host_weights(prog, cfg, out); + const int hrc = pin_embedding(prog, cfg, out); int rc = assign(out); enforce_op_site_agreement(prog, out); @@ -1230,7 +1244,7 @@ std::string Plan::report(const Program& prog) const { humanb(totals.bytes[(int)Tier::VRAM]).c_str()); s += fmt(" host pinned %12s %12s\n", host_budget > 0 ? humanb(host_budget).c_str() : "none", - humanb(totals.bytes[(int)Tier::HostPinned] - host_weights_bytes).c_str()); + humanb(totals.bytes[(int)Tier::HostPinned] - embedding_host_used).c_str()); if (totals.bytes[(int)Tier::HostPageable]) s += fmt(" host pageable %12s %12s\n", "-", humanb(totals.bytes[(int)Tier::HostPageable]).c_str()); @@ -1250,10 +1264,14 @@ std::string Plan::report(const Program& prog) const { s += fmt(" file staging %12s %12s (%d slots%s, pinned)\n", "-", humanb(file_stage_reserve).c_str(), RAD_PLACE_FILE_STAGE_SLOTS, file_windows ? fmt(" and %d read windows", RAD_PLACE_FILE_WINDOWS).c_str() : ""); - /* The same, for --host-weights: out of --host-pool-mib before any strategy, read in place. */ - if (host_weights_bytes) - s += fmt(" host weights %12s %12s (--host-weights, pinned, read in place)\n", "-", - humanb(host_weights_bytes).c_str()); + /* The same, for --embedding-placement ram: out of --host-pool-mib before any strategy, read + * in place. And the n-gram copy, which no pool holds: locked RAM the load phase fills. */ + if (embedding_host_bytes) + s += fmt(" embedding %12s %12s (--embedding-placement ram, pinned, read in place)\n", + "-", humanb(embedding_host_bytes).c_str()); + if (ngram_copy_bytes) + s += fmt(" n-gram copy %12s %12s (--ngram-placement ram, locked RAM, filled at load)\n", + "-", humanb(ngram_copy_bytes).c_str()); /* Out of the VRAM weight budget, beside the residents and not among them: the two buffers a * routed layer's file-tier experts are read into, each sized to the layer that puts the most * there. */ diff --git a/core/place/planner.h b/core/place/planner.h index 0531034b..eef2971c 100644 --- a/core/place/planner.h +++ b/core/place/planner.h @@ -95,10 +95,10 @@ struct MoveUnit { Site site = Site::Device; int32_t slab_slot = -1; bool movable = false; /* may the heat engine relocate it after load */ - bool host_forced = false; /* --host-weights put it in the pinned pool; no strategy moves it */ + bool host_forced = false; /* --embedding-placement ram put it in the pinned pool */ /* PLACED BEFORE ANY STRATEGY RAN, so every assignment pass skips it and no VRAM total counts - * it: the mapped tier (no device kernel can read it) and --host-weights. */ + * it: the mapped tier (no device kernel can read it) and --embedding-placement ram. */ bool preplaced() const { return tier == Tier::Mapped || host_forced; } const char* reason = "fits in vram"; /* a fixed string, so the report never guesses */ @@ -244,9 +244,14 @@ public: int64_t vram_budget = 0, host_budget = 0; int64_t file_stage_reserve = 0; int64_t file_windows = 0; /* the read windows' part of it */ - /* --host-weights: taken out of --host-pool-mib before any strategy ran, like the file staging - * above, and reported beside it rather than among the pooled units. */ - int64_t host_weights_bytes = 0; + /* --embedding-placement ram: the pool slots taken out of --host-pool-mib before any strategy + * ran, like the file staging above, and reported beside it rather than among the pooled units. + * `embedding_host_used` is the same tables' weight bytes, the unit the tier totals count in. */ + int64_t embedding_host_bytes = 0; + int64_t embedding_host_used = 0; + /* --ngram-placement ram: the n-gram tables the load phase copies into locked memory. They stay + * on the mapped tier as far as every pool is concerned; this is what the copy costs in RAM. */ + int64_t ngram_copy_bytes = 0; /* ROUTED EXPERTS ON THE FILE TIER have no address of their own: a routed layer's are read into * one of two VRAM buffers before the layer's first expert op and published there until the next * routed layer starts (place/stager.h, FileStager). `file_layer_max` is the most one layer's @@ -325,7 +330,7 @@ private: void resolve_sites(const Program& prog); void build_units(const Program& prog, Plan* p); void pin_mapped(const Program& prog, Plan* p); - int pin_host_weights(const Program& prog, const Config& cfg, Plan* p) const; + int pin_embedding(const Program& prog, const Config& cfg, Plan* p) const; void build_classes(Plan* p); void rank_units(Plan* p, std::vector* order) const; int assign(Plan* p); @@ -370,20 +375,33 @@ struct WeightFootprint { int64_t experts = 0; /* the elastic plane: what streams from host when it does not fit */ int64_t expert_layer_max = 0; /* the most expert bytes any one routed layer holds */ int64_t mapped = 0; /* no device kernel can read them; they never enter a pool at all */ - int64_t hosted = 0; /* --host-weights: in the pinned host pool, never on the card */ + int64_t hosted = 0; /* --embedding-placement ram: in the pinned host pool, off the card */ + /* The tables the two placement flags move, wherever the buckets above count them: `embedding` + * is inside statics or hosted, `ngram` inside mapped. */ + int64_t embedding = 0; + int64_t ngram = 0; + /* An n-gram table some device kernel reads, which the strategies place like any weight. No + * plugin has one today; it is what makes --ngram-placement vram mean something. */ + bool ngram_device = false; int64_t n_units = 0; }; -void weight_footprint(const Program& prog, WeightFootprint* out, - const std::vector& host_weights = {}); +/* `embedding` is what the token embedding's placement resolved to; only Ram moves it out of the + * statics. Stated by every caller, so the budget and the planner cannot count it differently. */ +void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding); -/* Does `name` match the --host-weights list: comma-separated, a trailing '*' matching a prefix. - * One definition, because Planner::pin_host_weights and weight_footprint must agree on it or the - * budget is resolved for weights the planner then puts somewhere else. */ -bool host_weight_match(const std::vector& list, const std::string& name); - -/* Is every op that reads weight `w` an embedding lookup? Only those read a few rows a step; any - * other reader (a GEMM) would stream the whole weight over the link on every step. */ -bool read_only_by_lookups(const Program& prog, rad_weight w); +/* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight + * that at least one op reads and that only `embed_lookup` reads is a token embedding table, and + * one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what + * makes a tier below the card usable for it at all; a weight a GEMM also reads -- an output head + * tied to the embedding -- would stream whole over the link every step, and is neither. One + * definition, because the budget resolver and the planner must pick the same weights. */ +bool read_only_by(const Program& prog, rad_weight w, const char* op); +inline bool is_embedding_table(const Program& prog, rad_weight w) { + return read_only_by(prog, w, "embed_lookup"); +} +inline bool is_ngram_table(const Program& prog, rad_weight w) { + return read_only_by(prog, w, "embed_lookup_q"); +} /* "blk.12.ffn_gate_exps.3.weight" -> "blk.*.ffn_gate_exps.*.weight". The report's grouping key: * one line per weight class rather than per weight (spec §16). */ diff --git a/core/plugin/testplugin/testplugin.cc b/core/plugin/testplugin/testplugin.cc index c17fe7e8..351e7eb3 100644 --- a/core/plugin/testplugin/testplugin.cc +++ b/core/plugin/testplugin/testplugin.cc @@ -103,6 +103,19 @@ static const RadOperandSpec kOpdNorm[] = { static const RadOperandSpec kOpdAttn[] = { { "q", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_INOUT, 0 }, { "out", RAD_OPD_OUT, 0 }, }; +/* A grouped GEMM's operand list in miniature: one fixed weight, then four classes of experts as + * table pairs -- codes, then scales -- with an activation operand between the first pair and the + * rest, the way `moe_gemm_q_mod4` lays its classes out. It is here for the declaration's division + * of one weight list over several table positions (tests/build_test.cpp). */ +static const RadOperandSpec kOpdMoe[] = { + { "a", RAD_OPD_IN, 0 }, { "g", RAD_OPD_WEIGHT, 0 }, + { "w", RAD_OPD_WTAB, 0 }, { "w_scale", RAD_OPD_WTAB, 0 }, + { "sorted", RAD_OPD_IN, 0 }, + { "w_1", RAD_OPD_WTAB, 0 }, { "w_1_scale", RAD_OPD_WTAB, 0 }, + { "w_2", RAD_OPD_WTAB, 0 }, { "w_2_scale", RAD_OPD_WTAB, 0 }, + { "w_3", RAD_OPD_WTAB, 0 }, { "w_3_scale", RAD_OPD_WTAB, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; /* ------------------------------------------------------------------ schemas */ static const RadParamSpec kPGemm[] = { @@ -206,6 +219,8 @@ static const RadOpSchema kSchemas[] = { "a peer kernel with a fallback beneath it" }, { "t_peer_only", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm), "a peer kernel and nothing else" }, + { "t_moe", kPTie, NELEM(kPTie), kOpdMoe, NELEM(kOpdMoe), + "one weight list over eight table operands" }, }; static const RadKernelInfo kKernels[] = { @@ -298,6 +313,10 @@ static const RadKernelInfo kKernels[] = { .domain = RAD_DOMAIN_DEVICE, .priority = 10, .constraints = kCEqM32, .n_constraints = NELEM(kCEqM32), .init = t_init_fails, .launch = t_launch }, + + { .name = "t_moe_any", .op = "t_moe", .family = "moe", + .computes = "nothing; a registry row", .shape = "any", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch }, }; /* The name is a -D so that two of these can load side by side, and one of them can declare itself diff --git a/core/rad_core.h b/core/rad_core.h index 2b0f72ce..8fc84e3f 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -113,6 +113,20 @@ struct Band { * planner assigns this tier where, and only where, no device kernel for the op exists at all * (embed_lookup_q, libavx/avx_ngram.cpp, is the one such op in this tree). */ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped = 4 }; + +/* WHERE A LOOKUP TABLE LIVES: the token embedding (--embedding-placement) and an n-gram embedding + * (--ngram-placement), each a model-level weight that only a row lookup reads, so a step touches M + * of its rows and never the whole table. That is what makes every tier below the card usable for + * it, and why the operator gets to choose. + * + * Vram resident on the card, a weight like any other. + * Ram in host memory the card or a host kernel reads in place: the embedding in the pinned + * host pool, read over the link; an n-gram table as a locked copy made at load. + * Disk read from the container on demand. + * Auto the fastest of the three that has room once every other weight is placed; Engine::plan + * decides it and writes the answer into Config, so every rank plans from one choice. */ +enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 }; +const char* table_placement_name(TablePlacement p); enum class Site { Device = 0, DeviceStaged = 1, DeviceZeroCopy = 2, Host = 3 }; /* Tier-indexed arrays are sized by this rather than by a literal: the report, the live view and @@ -614,21 +628,14 @@ struct Config { * is a server that is correct and several orders of magnitude slow. The tier needs no directory * of its own; the container is the file. */ bool weights_disk_tier = false; - /* --ngram-table disk|ram: where the host gather of a table too large for any card -- the n-gram - * embedding, 47.7 GiB in Qwen3.8-Flash-Next -- reads its rows. disk, the default, reads them - * from the container through a row cache and holds no more of the table than that. ram copies - * the table once into locked host memory, in the background from the first request, and reads - * the copy: a faster prefill and a few percent of throughput, for the table's size in RAM. A - * process that cannot lock that much says so and stays on disk. A deployment choice and not a - * tuning one, because only the operator knows what else the host's memory is for. */ - bool ngram_table_ram = false; std::string placement = "auto"; /* all_vram | layer_offload | expert_tiered | auto */ - /* MODEL-LEVEL WEIGHTS KEPT IN THE PINNED HOST POOL by name, comma-separated (a trailing '*' - * matches a prefix). The device kernel reads them over the link in place (DeviceZeroCopy), so - * this is for a gather -- the embedding table, of which a step reads a few rows -- and not for - * a GEMM operand. Charged to --host-pool-mib; every strategy leaves them where they are. */ - std::vector host_weights; + /* --embedding-placement and --ngram-placement, as asked (TablePlacement says what each tier + * is), and what Engine::plan resolved them to before any rank planned: never Auto. */ + TablePlacement embedding_placement = TablePlacement::Auto; + TablePlacement ngram_placement = TablePlacement::Auto; + TablePlacement embedding_resolved = TablePlacement::Vram; + TablePlacement ngram_resolved = TablePlacement::Disk; bool deterministic = false; int64_t checkpoint_interval = 2048; /* linear-state checkpoints (spec §7.3) */ /* HOW MANY LINEAR-STATE SNAPSHOTS THE SERVER MAY HOLD AT ONCE -- a CAP and not a charge. diff --git a/core/runtime/oracle.cpp b/core/runtime/oracle.cpp index 0d75695d..2ed5bc37 100644 --- a/core/runtime/oracle.cpp +++ b/core/runtime/oracle.cpp @@ -483,9 +483,12 @@ bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip } RadOpdDesc d{}; if (shape(dip.args.p, dip.args.n_p, i, &d) != RAD_OK || d.rank == 0) { + /* A shape hook declines without a reason (RadShapeFn), so the geometry it declined is + * printed, the dtype with it -- a description refuses a dtype it knows no grid for. */ RAD_WARN("oracle #%lld op '%s': NOT CHECKED. nothing could describe the logical form " - "of '%s' at this geometry, so there is nothing to invert its layout into.", - (long long)seq, oi.op.c_str(), w.name.c_str()); + "of '%s' at this geometry {%s}, so there is nothing to invert its layout " + "into.", (long long)seq, oi.op.c_str(), w.name.c_str(), + oi.base.str().c_str()); return false; } RadTensor lg{}; diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 8c8034ab..f293a544 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -334,17 +334,20 @@ time. **The fused all-reduce forms are two-rank, except the exact write.** At four ranks `ar_hc_write` exists on the exact wire only (`ar_hc_write_4rank`, the 4-rank one-shot with the write as its -epilogue, on the plain all-reduce's buffers), and so does `ar_gather_hc_write` -(`ar_gather_hc_write_4rank`, the same with `moe_gather` as its prologue), which the MoE -connections take wherever the step is one MoE pass. A step takes either where the standalone -`all_reduce` would have been the exact one-shot: under 1 MiB, and with `--tp-wire wht6` also -under `--tp-wire-min-kb`. Larger messages, and every lossy one, keep the standalone sequence — -`moe_gather` on the MoE connections, `all_reduce` (4-rank two-shot or ti8), then -`hc_write_bf16`. The unfused sequence is declared beside the fused one, so nothing is unresolved -at boot. The -attention's own fusion is not a collective and does carry over: the sparse decode with the output -gate and the quantiser in its merge (`attn_paged_gate_quant`) has gqa-6, page-4 rows. The per-step cost against tp2 on the -same cards is unmeasured. +epilogue), and so does `ar_gather_hc_write` (`ar_gather_hc_write_4rank`, the same with +`moe_gather` as its prologue), which the MoE connections take wherever the step is one MoE pass. +Both are declared over the rows of a decode or verify step — `--max-num-seqs` × (1 + +`--num-speculative-tokens`) — because a one-shot is for those messages, and a step within that +bound takes them wherever its message goes out exact: always with `--tp-wire exact`, and with +`--tp-wire wht6` under `--tp-wire-min-kb`. They run on an all-reduce instance keyed by that bound, +not on the standalone all-reduce's unless the two bounds agree; the wide family's flag, sequence +and slot discipline is what makes either safe on one stream. A prefill chunk, and every message +that goes out lossy, keeps the standalone sequence — `moe_gather` on the MoE connections, +`all_reduce` (whose size bands pick the 4-rank one-shot or two-shot, or ti8 on the lossy wire), +then `hc_write_bf16`. The unfused sequence is declared beside the fused one, so nothing is +unresolved at boot. The attention's own fusion is not a collective and does carry over: the sparse +decode with the output gate and the quantiser in its merge (`attn_paged_gate_quant`) has gqa-6, +page-4 rows. 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 diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 2deb9c20..bfbeb558 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -88,14 +88,13 @@ Every one of these options is needed: without this the model cannot serve. The profile also refuses the NUMA binding calls the ROCm runtime makes for host memory. - **`--init`**: the engine is not PID 1. It finishes its step and releases the cards on SIGTERM. +- **`--ulimit memlock=-1`**: `--ngram-placement ram` locks a copy of the n-gram table in RAM + (47.7 GiB for Qwen3.8-Flash-Next), far past Docker's default memlock limit. Without it `auto` + reads the table from the container and `ram` refuses the start. `deploy/compose/common.yaml` + sets it. - **`--network host`**: the server binds the host's addresses directly, IPv4 and IPv6, with no NAT in front of it. -And one more for `--ngram-table ram`: **`--ulimit memlock=-1`**. The copy of the n-gram table is -locked in RAM, and Docker's default memlock limit is far below its 47.7 GiB; without it the server -says so at the first request and reads the table from the container as it does by default. -`deploy/compose/common.yaml` sets it. - The image sets `GPU_MAX_ALLOC_PERCENT=100` and `GPU_MAX_HEAP_SIZE=100`. The HIP runtime's defaults cap one allocation, and the heap, below what the placement plan hands out. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index d320bb8b..66ed5344 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -468,23 +468,47 @@ Related flags: --gpu-headroom-mib 96 # VRAM left unclaimed on every card --kv-cache-dtype fp8 # halve what a token of context costs (a real quantisation) --host-pool-mib 8192 # pinned host tier for weights ---host-weights token_embd.weight # the embedding table off the card (below) +--embedding-placement ram # the token embedding off the card (below) +--ngram-placement ram # an n-gram table in locked RAM instead of read from disk (below) --weights-disk-tier # stream what fits neither from the container; needs O_DIRECT ``` -**`--host-weights` takes the embedding table off the card.** It is the largest model-level weight a -dense model has -- 248320 x 5120 in bf16 is 1.18 GiB a card at `--tp 2` -- and a step reads only its -rows: M of them, a few KiB at decode. Named here, it is placed in the pinned host pool before any -strategy runs and the lookup kernel reads it over the link in place, so it costs no VRAM and the -KV pool gets its share. On Qwen3.8-27B at two 16 GiB cards decode and prefill measured within noise -of the table on the card, against ~73K more tokens of context. The pool must hold it -(`--host-pool-mib`, every rank its own shard), a derived split leaves it out of the weight budget, -and a name any other op reads -- a head, a GEMM operand -- is refused: it would stream every step. +**Two lookup tables have a placement of their own**, because a step reads only M of their rows and +never the whole table, so a tier below the card serves them at little or no cost: + +| | `vram` | `ram` | `disk` | +|---|---|---|---| +| `--embedding-placement` | on the card, with the other weights | the pinned host pool, read over the link in place | refused | +| `--ngram-placement` | refused | a locked copy in RAM, made at load | read from the container through a row cache | + +Both default to `auto`, the fastest tier that has room once every other weight is placed. Startup +prints what each resolved to and why. A tier the flag names that cannot be honoured stops the +server with the reason; nothing falls back quietly. + +**The token embedding** is the largest model-level weight a dense model has -- 248320 x 5120 in bf16 +is 1.18 GiB a card at `--tp 2`. With `ram` it is placed in the pinned host pool before any strategy +runs and the lookup reads it over the link in place, so it costs no VRAM and the KV pool gets its +share. The pool must hold it (`--host-pool-mib`, every rank its own shard). `auto` keeps it on the +card unless the card cannot hold the other weights with it, or a derived KV pool could then not +hold one `--max-model-len` sequence; then it takes `ram` if the host pool can hold it. The table is +found by what reads it: a model-level weight only `embed_lookup` reads. A head tied to it is read by +a GEMM too and is never moved, since it would stream whole every step. `disk` is refused: the lookup +writes activations the card reads, and a host kernel reading the container cannot write them. ```sh -radiance --model m.rad --tp 2 --host-pool-mib 1280 --host-weights token_embd.weight +radiance --model m.rad --tp 2 --host-pool-mib 1280 --embedding-placement ram ``` +**An n-gram table** (Qwen3.8-Flash-Next's is 47.7 GiB) is read by a host kernel only, so it is never +on the card. `disk` reads its rows from the container through a row cache and direct reads; about +half of a step's rows are first-seen, so steps wait on the drive. `ram` copies the whole table into +locked huge pages at load -- 12 to 40 s more startup, depending on the page cache -- and every gather +reads memory. It needs the table's size in memory after the pinned host pools and the prefix +cache's host tier, with 4 GiB to spare, a memlock limit that large (`--ulimit memlock=-1` in Docker, +`LimitMEMLOCK=infinity` under systemd), and room under every memory cgroup the process sits in. +`ram` short of any of them refuses the start and names which; `auto` takes `ram` when all of them +allow it and `disk` otherwise. + **A model larger than the card and the host pool together still serves with `--weights-disk-tier`** -- and every step is then paced by the drive, which is the trade the flag names. A routed expert that fits neither VRAM nor the pinned pool lives in the container and @@ -695,10 +719,14 @@ eight ranks is one-shot up to 1 MiB a message and two-shot above it, which sends bits. On a model with a gated residual (Qwen3.8-Flash-Next) the all-reduce rides inside the residual's -write, with the MoE gather in front of it, on either wire: the rotated forms of `ar_hc_write` and -`ar_gather_hc_write` produce the same bytes as the unfused chain on the same wire. There `wht6` is -worth +5.6–6.3% of prefill at a 2048-token chunk (20K prompt 5556 → 5908 tok/s; a 23K extension at -81K depth 4998 → 5278) and −1.3% of the eight-stream decode step; one-stream decode stays exact. +write, with the MoE gather in front of it. At two ranks that holds on either wire: the rotated +forms of `ar_hc_write` and `ar_gather_hc_write` produce the same bytes as the unfused chain on the +same wire. There `wht6` is worth +5.6–6.3% of prefill at a 2048-token chunk (20K prompt 5556 → +5908 tok/s; a 23K extension at 81K depth 4998 → 5278) and −1.3% of the eight-stream decode step; +one-stream decode stays exact. At four ranks only the exact wire has a fused form, and it takes +the decode and verify steps — up to `--max-num-seqs` × (1 + `--num-speculative-tokens`) rows. A +prefill chunk, and a message that goes out on the tiered-int8 wire, runs the unfused chain, where +the all-reduce's own size choice between one-shot and two-shot applies. **The cards must reach each other's memory directly** (peer to peer, P2P). The all-reduce kernels push into the other card's memory. At launch radiance asks the driver, for every pair of @@ -864,9 +892,9 @@ one line naming each one the command line moved. | `--vram-kv-mib N` | derive | the paged KV pool | | `--kv-cache-dtype T` | bf16 | `bf16` or `fp8` | | `--host-pool-mib N` | 0 | pinned host tier (weights) | -| `--host-weights NAMES` | none | embedding tables kept in the pinned host pool and read in place over the link (comma-separated, a trailing `*` matches a prefix); charged to `--host-pool-mib`, and only a weight embedding lookups alone read is accepted. See §4.3 | +| `--embedding-placement WHERE` | auto | `auto`, `vram` or `ram`: the token embedding on the card or in the pinned host pool, read in place; `disk` is refused. See §4.3 | +| `--ngram-placement WHERE` | auto | `auto`, `ram` or `disk`: an n-gram table as a locked copy in RAM made at load, or read from the container; `vram` is refused. See §4.3 | | `--weights-disk-tier` | off | read weights that fit neither VRAM nor the host pool from the container (O_DIRECT); routed experts a layer at a time | -| `--ngram-table MODE` | disk | where the n-gram embedding's host gather reads its rows: `disk` from the container through a row cache, `ram` from a copy of the whole table in locked host memory (Qwen3.8-Flash-Next: 47.7 GiB), made in the background from the first request. `ram` needs the memory and a memlock limit that large (`--ulimit memlock=-1` in Docker); short of either it says so and stays on `disk` | **Idle session tiers** diff --git a/docs/MOE-W4.md b/docs/MOE-W4.md index e7dc4256..25efe416 100644 --- a/docs/MOE-W4.md +++ b/docs/MOE-W4.md @@ -365,6 +365,10 @@ typo'd directory is a message, not a silent quality regression. - `r4d_selftest --case moe_gemm_w4a8` -- the kernel against an independent host decode of the same planes, both M bands, through the relayout the loader runs. +- `r4d_selftest --case moe_gemm_w4a8_mod4` -- the four-class op against the two-class one byte for + byte, and against a host decode with every class at its own geometry and one of classes 1 to 3 + the only wide one, as ranks 1 to 3 of four hold them; `--case moe_gemm_fp8a8_mod4` is the same + host decode at block fp8. - `quant_test` -- **GPTQ against the objective it minimises**. The metric is `||X (W - W')^T||^2 = sum over rows of e H e^T` and *not* rel_l2 on the weight: error feedback makes the weight worse in the plain sense, deliberately. The control is no Hessian at all, under diff --git a/docs/OPS.md b/docs/OPS.md index b502e61a..0aeed4bf 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -130,9 +130,11 @@ the codes and the scale planes of its even experts and of its odd ones. Whatever is split EVENLY across the table positions, in declaration order, and where it does not come out whole the first positions take one more each: `moe_gemm_q_mod4`'s first `n_expert % 4` classes hold one expert more than the rest, and their codes and scales are its first table positions. A list too -short to give every table an entry is refused at declare, and a run that is not one contiguous, -same-shaped table is refused at issue. That is exactly right for the case tables exist for: every -table of one MoE op takes one weight per expert of its class. +short to give every table an entry is refused at declare. A table whose declared run is not +contiguous is refused when the tables are bound, before the first step; one whose entries disagree +about their shape, or an issue naming a run other than the declared one, is refused at issue. That +is exactly right for the case tables exist for: every table of one MoE op takes one weight per +expert of its class. ## What the loader enforces @@ -772,7 +774,9 @@ and the input, and the reduced sum lands in it. output feeds a gated residual rather than a norm. `y` is INOUT for the same reason `x` is above. It serves both wires, one op a wire: a caller declares the rotated form beside the exact one and issues whichever the step's message goes out on, and a `wire` of 6 is 6 at every size. At four -ranks only the exact form exists. +ranks only the exact form exists. A caller states `wire` 0 on the exact form rather than leaving it +out: a row that serves one wire only says so with a constraint on `wire`, and a constraint on an +absent key does not hold. `ar_gather_hc_write` is `moe_gather` followed by `ar_hc_write`: the gather's output IS the message, so `y` is written by the gather half before it is reduced in place, and the five gather @@ -785,7 +789,7 @@ form exists, as for `ar_hc_write`. | op | params | operands | |---|---|---| | `embed_lookup` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt | `tokens`, `wte`w → `x` | -| `embed_lookup_q` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt `resident`/opt | `tokens`, `wte`w, `scale`w? → `x`, `ahead`? | +| `embed_lookup_q` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt | `tokens`, `wte`w, `scale`w? → `x`, `ahead`? | | `logits_gemm` | `M`(range) `n_vocab` `n_embd` `dtype` | `x`, `lm_head`w → `logits` | | `ngram_ids` | `M`(range) `heads` `ngram` `eos` | `tok`, `state`:inout, `cu`, `mult`w, `vocab_sizes`w, `offsets`w, `cache_idx`?, `has_init`?, `num_accepted`? → `ids`, `ahead_ids`? | | `ple_gate` | `M`(range) `n` `hc` `eps`:f64 `dtype` `wadd`:f64/opt `gate_eps`:f64/opt | `k`, `q`, `v`, `w_key`w, `w_query`w, `w_conv`w → `gv`, `gvn` | @@ -893,12 +897,6 @@ the alignment the filesystem reports for direct I/O, or its block size where it btrfs does; one read of the table proves it before the first row is served. A filesystem with no direct I/O at all cannot hold a container with this table. -**`resident` keeps the table in RAM instead**, for a deployment that has the memory: libavx copies -it once into locked huge pages, in the background from the first gather that carries it, and reads -the copy from then on; until the copy is in place, and wherever the process cannot lock that much, -the rows come from the file as above. The result is the same either way. An architecture sets it -from `RadBuildCtx::ngram_table_ram` (`--ngram-table ram`). - The placement planner runs an op on the host when **every weight operand of it** is `Site::Host`, which is why the table must be a weight operand at all: `gather_rows` takes a plain `IN` operand and would never trigger it. And the host kernel has to live in a production plugin — libavx, the host diff --git a/libavx/README.md b/libavx/README.md index 1dfdfb28..79f2d4f6 100644 --- a/libavx/README.md +++ b/libavx/README.md @@ -30,15 +30,8 @@ codes; below it, one code at a time. The row's layout hook only checks the table E4M3 with one bf16 scale, or the checkpoint's plain bf16 — and asks for no re-layout, because the gather reads the rows from the container file in the layout they are stored in. -With the op's `resident` parameter (`--ngram-table ram`) the first gather instead starts a copy of -the whole table into locked huge pages, in the background, and every gather reads the copy once it -is in place: 47.7 GiB of RAM for Flash-Next, checked against RLIMIT_MEMLOCK, MemAvailable and the -cgroup's memory.max before a byte is read. A process short of any of them says so and keeps -reading the file. - `rad-avx-check` runs the op over a file-backed table with two ranks and the reader racing, at -every level, and compares every row with the file's bytes; and once more with `resident`, before -and after the copy is in place. +every level, and compares every row with the file's bytes. ## The build is the dispatch diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 0bb671c7..64f48f23 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -237,30 +237,32 @@ std::vector build_cases() { for (const char* order : { "token", "sorted" }) { add("moe_gemm", { HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8), HI("top_k", 2), HS("a_order", order), HS("dtype", dt) }); + /* `fp8a8`, the block-fp8 grid: libref describes a grouped GEMM's weight scale plane + * only at a dtype that names its grid. */ add("moe_gemm_q", { HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8), HI("top_k", 2), HI("group", 128), HS("a_order", order), - HS("dtype", "w8a8") }); + HS("dtype", "fp8a8") }); } /* The two classes at different widths: a gate/up pair whose odd experts are half as wide * (the output's second part begins past the odd class's zeros), and a down projection * whose odd experts are half as long. */ add("moe_gemm_q", { HI("M", 9), HI("N", 256), HI("K", 128), HI("N_odd", 128), HI("parts", 2), HI("n_expert", 8), HI("top_k", 2), HI("group", 128), - HS("a_order", "token"), HS("dtype", "w8a8") }); + HS("a_order", "token"), HS("dtype", "fp8a8") }); add("moe_gemm_q", { HI("M", 9), HI("N", 64), HI("K", 256), HI("K_odd", 128), HI("n_expert", 8), HI("top_k", 2), HI("group", 128), - HS("a_order", "sorted"), HS("dtype", "w8a8") }); + HS("a_order", "sorted"), HS("dtype", "fp8a8") }); /* Four classes at three widths -- a four-rank slice of a five-block expert is two blocks * of one class and one of each other -- over ten experts, so classes 2 and 3 hold one * fewer than 0 and 1: the gate/up pair and the down projection. */ add("moe_gemm_q_mod4", { HI("M", 9), HI("N", 128), HI("K", 128), HI("N_1", 256), HI("N_2", 128), HI("N_3", 128), HI("parts", 2), HI("n_expert", 10), HI("top_k", 2), HI("group", 128), - HS("a_order", "token"), HS("dtype", "w8a8") }); + HS("a_order", "token"), HS("dtype", "fp8a8") }); add("moe_gemm_q_mod4", { HI("M", 9), HI("N", 64), HI("K", 128), HI("K_1", 128), HI("K_2", 256), HI("K_3", 128), HI("n_expert", 10), HI("top_k", 2), HI("group", 128), HS("a_order", "sorted"), - HS("dtype", "w8a8") }); + HS("dtype", "fp8a8") }); } add("moe_scatter", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("expert_base", 0) }); diff --git a/libavx/avx_check.cpp b/libavx/avx_check.cpp index 7eaa578e..5a2f6b80 100644 --- a/libavx/avx_check.cpp +++ b/libavx/avx_check.cpp @@ -799,10 +799,9 @@ static bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* return true; } -/* embed_lookup_q over a file-backed table, two ranks and the reader racing, or with the table - * copied into RAM (avx_check_rows.cpp). */ +/* embed_lookup_q over a file-backed table, two ranks and the reader racing (avx_check_rows.cpp). */ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool verbose, - bool bf16, bool resident); + bool bf16); /* embed_lookup_q's init, where io_uring is refused and here (avx_check_rows.cpp). */ bool ngram_init_case(const Lib& avx); @@ -946,16 +945,13 @@ int main(int argc, char** argv) { const std::string at = sl == std::string::npos ? "." : self.substr(0, sl); /* The E4M3 table the quantised containers carry, and the plain bf16 one a checkpoint * served as it ships carries: one path, two row sizes. */ - if (!row_gather_case(avx, at, 1000, verbose, false, false)) rc = 1; - if (!row_gather_case(avx, at, 1000, verbose, true, false)) rc = 1; - /* The copy in RAM is the process's, made once a table, so at one level: the last. */ - if (lvl == hi && !row_gather_case(avx, at, 1000, verbose, false, true)) rc = 1; + if (!row_gather_case(avx, at, 1000, verbose, false)) rc = 1; + if (!row_gather_case(avx, at, 1000, verbose, true)) rc = 1; /* And in TMPDIR, which is a tmpfs on most machines: since Linux 6.6 a tmpfs does * direct reads and reports no alignment for them, as btrfs does, so the gather finds * its granule from the block size there. */ const char* tmp = std::getenv("TMPDIR"); - if (!row_gather_case(avx, tmp && *tmp ? tmp : "/tmp", 1000, verbose, false, false)) - rc = 1; + if (!row_gather_case(avx, tmp && *tmp ? tmp : "/tmp", 1000, verbose, false)) rc = 1; } } if (!declined_ops.empty()) { diff --git a/libavx/avx_check_rows.cpp b/libavx/avx_check_rows.cpp index 75a3a9dd..535c216d 100644 --- a/libavx/avx_check_rows.cpp +++ b/libavx/avx_check_rows.cpp @@ -20,17 +20,10 @@ * takes one full 32-code step and a masked tail. The table is a file in `dir`, and the filesystem * there decides how the gather aligns its direct reads: by the alignment the filesystem reports * (ext4, XFS), or by its block size where it reports none (btrfs, and a tmpfs since Linux 6.6). The - * case says which it ran. - * - * With `resident` the op is asked to copy the table into locked RAM (--ngram-table ram), over a - * table small enough for a default memlock limit. The calls run while the copy is being made, then - * the case waits for the process's locked memory to grow by the table and runs them again, from - * the copy. Where the process may not lock that much the gather says so and keeps reading the file, - * and the case says which of the two it checked; either way every row must be the file's. */ + * case says which it ran. */ #include "avx_harness.h" #include -#include #include #include #include @@ -133,23 +126,10 @@ bool ngram_init_case(const Lib& avx) { return ok && right; } -/* This process's locked memory, in bytes: VmLck. */ -static long long locked_bytes() { - long long kb = 0; - if (std::FILE* f = std::fopen("/proc/self/status", "re")) { - char line[256]; - while (std::fgets(line, sizeof line, f)) (void)std::sscanf(line, "VmLck: %lld", &kb); - std::fclose(f); - } - return kb << 10; -} - bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool verbose, - bool bf16, bool resident) { + bool bf16) { const RadKernelInfo* r = avx.row("embed_lookup_q"); - const char* what = resident ? "embed_lookup_q from a file, resident" - : bf16 ? "embed_lookup_q from a file, bf16 table" - : "embed_lookup_q from a file"; + const char* what = bf16 ? "embed_lookup_q from a file, bf16 table" : "embed_lookup_q from a file"; if (!r || !r->launch) { std::printf(" %s: no row\n", what); return false; @@ -170,8 +150,7 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool } ::close((int)ring); } - /* 2.5 MiB resident, which a default memlock limit of 8 MiB holds. */ - const int64_t n = 40, V = int64_t(1) << (resident ? 16 : 21), M = 512, hot = 4096; + const int64_t n = 40, V = int64_t(1) << 21, M = 512, hot = 4096; const int64_t rb = bf16 ? 2 * n : n; const float scale = 0.375f; @@ -259,14 +238,13 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool tensor(const_cast(tab), bf16 ? RAD_BF16 : RAD_F8E4M3, {V, n}), tensor(bf16 ? nullptr : &sc, RAD_BF16, {1}), tensor(out.data(), RAD_BF16, {M, n}), tensor(nullptr, RAD_I32, {M}) }; - RadParam ps[4] = {}; - ps[0].key = "M"; ps[0].kind = RAD_P_INT; ps[0].ival = M; - ps[1].key = "n_embd"; ps[1].kind = RAD_P_INT; ps[1].ival = n; - ps[2].key = "n_vocab"; ps[2].kind = RAD_P_INT; ps[2].ival = V; - ps[3].key = "resident"; ps[3].kind = RAD_P_INT; ps[3].ival = 1; + RadParam ps[3] = {}; + ps[0].key = "M"; ps[0].kind = RAD_P_INT; ps[0].ival = M; + ps[1].key = "n_embd"; ps[1].kind = RAD_P_INT; ps[1].ival = n; + ps[2].key = "n_vocab"; ps[2].kind = RAD_P_INT; ps[2].ival = V; RadArgs a{}; a.t = ts.data(); a.n_t = (int)ts.size(); - a.p = ps; a.n_p = resident ? 4 : 3; + a.p = ps; a.n_p = 3; a.rank = rk; a.world_size = 2; for (int64_t c = 0; c < calls; ++c) { ts[0].data = &ids[(size_t)(c * M)]; @@ -286,23 +264,9 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool } } }; - const long long locked0 = locked_bytes(); - auto round = [&] { - std::thread t0(rank, 0), t1(rank, 1); - t0.join(); - t1.join(); - }; - round(); - /* The copy is made in the background from the first call. Once the locked memory has grown - * by the table it is in place, or about to be, so a short wait more and every call reads it. */ - bool copied = false; - if (resident) { - for (int i = 0; i < 300 && !copied; ++i) { - copied = locked_bytes() - locked0 >= V * rb; - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - if (copied) round(); - } + std::thread t0(rank, 0), t1(rank, 1); + t0.join(); + t1.join(); /* THE ADDRESS RANGE STAYS RESERVED. libavx resolves a table to its file once, by the address * range of its mapping, for the life of the process (avx_ngram.cpp, table_file) -- the * engine's container mapping is one. A case that unmapped here could have the next case's file @@ -315,16 +279,13 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool ::unlink(path.c_str()); const bool pass = bad[0] + bad[1] + refused[0] + refused[1] == 0; - const char* from = !resident ? "" - : copied ? ", then as many again from the copy in RAM" - : ", all from the file: the copy was not made here (above)"; if (verbose || !pass) - std::printf(" %s in %s (%s): %lld calls x 2 ranks%s, rows wrong %lld/%lld, " + std::printf(" %s in %s (%s): %lld calls x 2 ranks, rows wrong %lld/%lld, " "calls refused %lld/%lld %s\n", what, dir.c_str(), granule, (long long)calls, - from, (long long)bad[0], (long long)bad[1], (long long)refused[0], + (long long)bad[0], (long long)bad[1], (long long)refused[0], (long long)refused[1], pass ? "ok" : "FAIL"); else - std::printf(" %s in %s (%s): %lld calls x 2 ranks%s, every row exact\n", what, - dir.c_str(), granule, (long long)calls, from); + std::printf(" %s in %s (%s): %lld calls x 2 ranks, every row exact\n", what, dir.c_str(), + granule, (long long)calls); return pass; } diff --git a/libavx/avx_gemm.cpp b/libavx/avx_gemm.cpp index 87608b50..63a7b492 100644 --- a/libavx/avx_gemm.cpp +++ b/libavx/avx_gemm.cpp @@ -700,7 +700,6 @@ static bool rows_form(const RadArgs* a, RowGather* g) { g->n_ahead = ahead ? numel(ahd) : 0; g->rank = a->rank; g->world_size = a->world_size; - g->resident = p_int(a, "resident", 0) != 0; return true; } diff --git a/libavx/avx_ngram.cpp b/libavx/avx_ngram.cpp index aa17389a..c300553d 100644 --- a/libavx/avx_ngram.cpp +++ b/libavx/avx_ngram.cpp @@ -57,18 +57,7 @@ * plugin ABI carries no file, so /proc/self/maps says which file and offset back that address, once * a table. A table no file backs -- a test's heap buffer -- is read as the memory it is. A file on a * filesystem that cannot do direct I/O is refused; direct_granule below finds the alignment the - * reads keep, including on a filesystem that does not report one. - * - * ============================== OR THE WHOLE TABLE IN RAM ============================== - * - * All of the above is the default, and it holds no more of the table than the row cache does. - * With `resident` set on the op -- the engine's --ngram-table ram -- the table is copied once into - * locked host memory and every gather reads the copy, so a miss is a load instead of a read: on - * Flash-Next at four ranks a 2k-token prompt prefills 24% faster and 16 to 32 streams gain 4 to 5%, - * for 47.7 GiB of RAM. The first gather that asks starts the copy in the background and, until it - * is in place, every gather reads the file exactly as it does without it, so serving never waits - * for the copy. A process that cannot hold it -- RLIMIT_MEMLOCK, the memory available, a cgroup's - * limit -- says so once and keeps reading the file. make_resident has the detail. */ + * reads keep, including on a filesystem that does not report one. */ #include "avx_rows.h" #include "avx_common.h" @@ -79,9 +68,7 @@ #include #include -#include #include -#include #include #include #include @@ -95,7 +82,6 @@ #include #include #include -#include #include #include #include @@ -172,15 +158,6 @@ struct TableFile { int fd = -1; long long off = 0; long long align = 0; - std::string path; - /* --ngram-table ram: the table's own copy, [copy, copy + copy_n) holding [copy_lo, copy_lo + - * copy_n) of the mapping. `copy` is stored last, once the copy is filled, locked and checked; - * null, the gather reads the file. One copy a file, of the table the first resident gather - * names, which in every container so far is the only table in it. */ - std::once_flag copy_once; - std::atomic copy{nullptr}; - const uint8_t* copy_lo = nullptr; - long long copy_n = 0; }; /* THE GRANULE OF A DIRECT READ of `t`'s file, opened for them as `t.fd`: the alignment a read's @@ -260,12 +237,10 @@ long long direct_granule(const TableFile& t, const uint8_t* p, long long n, unsi /* The file behind [p, p + n): the mapping holding `p`, extended over the mappings that continue it * in the same file (a madvise over a sub-range splits one mapping into several). Looked up once per * table and kept for the life of the process; every rank thread shares the entry and the fd, and a - * read at an explicit offset has no file position to share. The list is never destroyed: a copy - * thread (make_resident) may still be filling an entry when the process exits. */ -TableFile* table_file(const uint8_t* p, long long n, int* err) { - static std::mutex& mu = *new std::mutex; - static std::vector>& known = - *new std::vector>; + * read at an explicit offset has no file position to share. */ +const TableFile* table_file(const uint8_t* p, long long n, int* err) { + static std::mutex mu; + static std::vector> known; std::lock_guard lk(mu); for (const auto& t : known) if (p >= t->lo && p + n <= t->hi) return t.get(); @@ -312,7 +287,6 @@ TableFile* table_file(const uint8_t* p, long long n, int* err) { if (found) { if ((uintptr_t)(p + n) > end) { *err = RAD_E_IO; return nullptr; } t->hi = (const uint8_t*)end; - t->path = path; t->fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_DIRECT); const char* why = t->fd < 0 ? std::strerror(errno) : nullptr; if (t->fd >= 0) t->align = direct_granule(*t, p, n, ino, path.c_str(), &why); @@ -329,155 +303,6 @@ TableFile* table_file(const uint8_t* p, long long n, int* err) { return known.back().get(); } -/* A size for a message: GiB from one up, MiB below. */ -std::string size_str(unsigned long long b) { - char s[32]; - if (b >= 1ull << 30) std::snprintf(s, sizeof s, "%.1f GiB", (double)b / (1ull << 30)); - else std::snprintf(s, sizeof s, "%.1f MiB", (double)b / (1ull << 20)); - return s; -} - -/* WHETHER `bytes` MORE CAN BE LOCKED IN RAM, or why not. Each limit is one the copy would - * otherwise meet after reading the whole table: RLIMIT_MEMLOCK, unless the process has - * CAP_IPC_LOCK; what the kernel says is available, less a margin for everything else; and the - * cgroup's memory.max, which Docker's --memory sets and which the kernel enforces by killing the - * process. A limit that cannot be read is not one. */ -bool room_to_lock(unsigned long long bytes, std::string* why) { - const unsigned long long margin = 4ull << 30; - unsigned long long locked = 0, caps = 0, avail = 0; - bool have_avail = false; - char line[256]; - if (std::FILE* f = std::fopen("/proc/self/status", "re")) { - while (std::fgets(line, sizeof line, f)) { - (void)std::sscanf(line, "VmLck: %llu", &locked); - (void)std::sscanf(line, "CapEff: %llx", &caps); - } - std::fclose(f); - } - struct rlimit rl {}; - if (!(caps >> 14 & 1) && ::getrlimit(RLIMIT_MEMLOCK, &rl) == 0 && - rl.rlim_cur != RLIM_INFINITY && rl.rlim_cur < (locked << 10) + bytes) { - *why = "the copy locks " + size_str(bytes) + " and RLIMIT_MEMLOCK allows " + - size_str(rl.rlim_cur) + " (in Docker, --ulimit memlock=-1 lifts it)"; - return false; - } - if (std::FILE* f = std::fopen("/proc/meminfo", "re")) { - while (!have_avail && std::fgets(line, sizeof line, f)) - have_avail = std::sscanf(line, "MemAvailable: %llu", &avail) == 1; - std::fclose(f); - } - if (have_avail && (avail << 10) < bytes + margin) { - *why = size_str(avail << 10) + " of memory is available, and the copy wants " + - size_str(bytes) + " with " + size_str(margin) + " to spare"; - return false; - } - /* cgroup v2: the process's group is the "0::" line. */ - std::string cg; - if (std::FILE* f = std::fopen("/proc/self/cgroup", "re")) { - while (std::fgets(line, sizeof line, f)) - if (std::strncmp(line, "0::", 3) == 0) { - cg = line + 3; - while (!cg.empty() && cg.back() == '\n') cg.pop_back(); - } - std::fclose(f); - } - auto read_ull = [](const std::string& file, unsigned long long* v) { - std::FILE* f = std::fopen(file.c_str(), "re"); - if (!f) return false; - const bool got = std::fscanf(f, "%llu", v) == 1; /* "max" reads as no limit */ - std::fclose(f); - return got; - }; - unsigned long long max = 0, cur = 0; - const std::string dir = "/sys/fs/cgroup" + (cg == "/" ? std::string() : cg); - if (!cg.empty() && read_ull(dir + "/memory.max", &max) && - read_ull(dir + "/memory.current", &cur) && (cur > max || max - cur < bytes + margin)) { - *why = "the cgroup's memory.max leaves " + size_str(cur > max ? 0 : max - cur) + - ", and the copy wants " + size_str(bytes) + " with " + size_str(margin) + - " to spare"; - return false; - } - return true; -} - -/* --ngram-table ram: KEEP THE WHOLE TABLE IN RAM, [p, p + n) of `t`'s mapping. Called once a table, - * by the first gather whose op carries `resident`. - * - * A COPY IN HUGE PAGES, NOT THE MAPPING LOCKED. Faulting the mapping in costs a fault a 4 KiB page - * -- 12.5 million of them, ~140 s inside a VM -- and leaves every row behind a 4 KiB translation, - * so a gather of scattered rows walks the page tables on nearly every row. Parallel buffered reads - * into an anonymous MADV_HUGEPAGE region fill it in 18.7 s for Flash-Next's 47.7 GiB, a 2 MiB page - * covers 13,000 rows, and the pages read are dropped from the page cache behind them, so the copy - * does not hold the table twice. A thread fills, locks and checks the copy and only then - * stores `copy`; until it does the gather reads the file. Whatever stops it -- a limit checked here - * before a byte is read, or a failure on the way -- leaves the table on the file path and says - * why, once. */ -void make_resident(TableFile* t, const uint8_t* p, long long n) { - auto refuse = [n](const std::string& why) { - std::fprintf(stderr, "libavx: --ngram-table ram: the n-gram table (%s) stays on disk and is " - "read from the container: %s\n", size_str((unsigned long long)n).c_str(), - why.c_str()); - }; - const size_t huge = (size_t)2 << 20; - const size_t sz = ((size_t)n + huge - 1) & ~(huge - 1); - std::string why; - if (!room_to_lock(sz, &why)) { refuse(why); return; } - const long long foff = t->off + (long long)(p - t->lo); - std::thread([t, p, n, sz, foff, refuse] { - const auto t0 = std::chrono::steady_clock::now(); - auto fail = [&](const char* what, int e) { - refuse(std::string(what) + " failed (" + std::strerror(e) + ")"); - }; - void* m = ::mmap(nullptr, sz, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); - if (m == MAP_FAILED) { fail("mmap", errno); return; } - uint8_t* buf = static_cast(m); - (void)::madvise(buf, sz, MADV_HUGEPAGE); - const int fd = ::open(t->path.c_str(), O_RDONLY | O_CLOEXEC); - if (fd < 0) { fail("open", errno); ::munmap(m, sz); return; } - const int nt = 16; - const long long step = (n / nt + (long long)huge - 1) & ~((long long)huge - 1); - std::atomic err{0}; - std::vector fill; - for (int i = 0; i < nt; ++i) { - const long long lo = (long long)i * step, hi = std::min(n, lo + step); - if (lo >= hi) break; - fill.emplace_back([&, lo, hi] { - for (long long o = lo; o < hi && !err.load();) { - const size_t want = (size_t)std::min(hi - o, (long long)(64 << 20)); - const ssize_t r = ::pread(fd, buf + o, want, (off_t)(foff + o)); - if (r <= 0) { err.store(r < 0 ? errno : EIO); return; } - (void)::posix_fadvise(fd, (off_t)(foff + o), (off_t)r, POSIX_FADV_DONTNEED); - o += r; - } - }); - } - for (auto& th : fill) th.join(); - ::close(fd); - if (err.load()) { fail("reading the container", err.load()); ::munmap(m, sz); return; } - if (::mlock(buf, sz) != 0) { fail("mlock", errno); ::munmap(m, sz); return; } - /* The copy has to be the mapping's bytes: a wrong offset would serve every row from the - * wrong place without an error. Both ends and a stride of rows in between. */ - const long long probe = std::min(n, (long long)4096); - bool same = std::memcmp(buf, p, (size_t)probe) == 0 && - std::memcmp(buf + n - probe, p + n - probe, (size_t)probe) == 0; - for (long long o = 0; same && o + 4096 <= n; o += n / 64) - same = std::memcmp(buf + o, p + o, 4096) == 0; - if (!same) { - fail("checking the copy against the mapping", EIO); - ::munlock(buf, sz); - ::munmap(m, sz); - return; - } - t->copy_lo = p; - t->copy_n = n; - t->copy.store(buf, std::memory_order_release); - std::fprintf(stderr, "libavx: n-gram table resident in RAM: %s copied to locked huge pages " - "in %.1f s\n", size_str((unsigned long long)n).c_str(), - std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); - }).detach(); -} - /* ============================== THE ROW CACHE ============================== * * Set-associative: a row's key -- its byte offset in the file -- hashes to a set of kWays slots, and @@ -1036,7 +861,7 @@ inline std::FILE* trace_file() { #else /* not Linux: no file reads; a table is read as memory */ struct TableFile { int fd = -1; }; -inline TableFile* table_file(const uint8_t*, long long, int*) { static TableFile m; return &m; } +inline const TableFile* table_file(const uint8_t*, long long, int*) { static TableFile m; return &m; } inline std::FILE* trace_file() { return nullptr; } #endif @@ -1063,24 +888,14 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { for (int b = 0; b < 256; ++b) lut[b] = rad_f32_to_bf16(rad_fp8e4m3_to_f32((uint8_t)b) * q.scale); - /* The rows: through the shared cache from the file behind the table, or from the table's copy - * in RAM once there is one, or, for a table no file backs, from the table itself. The caller - * has refused an id past the table already; an id turned into a file offset has to be one. */ + /* The rows: through the shared cache from the file behind the table, or, for a table no file + * backs, from the table itself. The caller has refused an id past the table already; an id + * turned into a file offset has to be one. */ int ferr = RAD_OK; - const long long bytes = q.n_vocab * q.row_bytes; - TableFile* tfile = table_file(q.tab, bytes, &ferr); + const TableFile* tfile = table_file(q.tab, q.n_vocab * q.row_bytes, &ferr); if (!tfile) return ferr; - const uint8_t* tab = q.tab; #if defined(__linux__) - bool from_copy = false; - if (q.resident && tfile->fd >= 0) - std::call_once(tfile->copy_once, [&] { make_resident(tfile, q.tab, bytes); }); - if (const uint8_t* copy = tfile->copy.load(std::memory_order_acquire)) - if (q.tab >= tfile->copy_lo && q.tab + bytes <= tfile->copy_lo + tfile->copy_n) { - tab = copy + (q.tab - tfile->copy_lo); - from_copy = true; - } - if (tfile->fd >= 0 && !from_copy) { + if (tfile->fd >= 0) { int why = 0; ReadRing* rr = read_ring(&why); if (!rr) { @@ -1111,7 +926,7 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { std::memset(dst, 0, (size_t)q.n_embd * sizeof(uint16_t)); continue; } - g.src.push_back(tab + id * q.row_bytes); + g.src.push_back(q.tab + id * q.row_bytes); g.dst.push_back(dst); } if (!g.src.empty()) decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), q.n_embd, lut); diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 7b2daebd..718dda0b 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -373,10 +373,6 @@ static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_ P_STR("dtype"), P_INTO("vocab_offset"), P_F64O("wscale") }; static const RadOperandSpec oEmbed[] = { OPD("tokens"), WGT("wte"), OUT("x") }; -/* embed_lookup_q's, and `resident`: keep the table's copy in RAM (avx_ngram.cpp). */ -static const RadParamSpec pEmbedQ[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), - P_STR("dtype"), P_INTO("vocab_offset"), - P_F64O("wscale"), P_INTO("resident") }; static const RadOperandSpec oEmbedQ[] = { OPD("tokens"), WGT("wte"), WGT_O("scale"), OUT("x"), OPD_O("ahead") }; @@ -543,7 +539,7 @@ static const RadOpSchema kSchemas[] = { "sum across ranks, f32, ascending rank order." }, { "all_gather", ARR(pAllGather), ARR(oAllGather), "gather every rank's shard." }, { "embed_lookup", ARR(pEmbed), ARR(oEmbed), "embedding gather, vocab-parallel with an offset." }, -{ "embed_lookup_q", ARR(pEmbedQ), ARR(oEmbedQ), +{ "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ), "embedding gather, one scale for the table; without a scale the table is read as it is." }, { "logits_gemm", ARR(pLogits), ARR(oLogits), "the lm_head projection." }, { "sample_penalties", ARR(pPenal), ARR(oPenalties), @@ -746,13 +742,12 @@ SIMPLE("avx_all_gather", "all_gather", "ar", "gather every rank's shard; world_s SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)), /* THE ONE ROW WITH A LAYOUT HOOK, and it only checks: the table is read as it is stored, and the * hook refuses a table encoded any other way (avx_ngram.cpp). An E4M3 table into bf16 goes through - * the row cache, or with `resident` from a copy in RAM once there is one; every other dtype pair - * takes the general gather. Its init refuses a process that may not make the io_uring ring the - * cache's misses are read through, at declare and not at the first request. */ + * the row cache; every other dtype pair takes the general gather. Its init refuses a process that + * may not make the io_uring ring the cache's misses are read through, at declare and not at the + * first request. */ { "avx_embed_lookup_q", "embed_lookup_q", "vocab", "embedding gather, one scale for the table: an E4M3 table into bf16 through a shared row cache " - "and direct reads of the container, a later call's rows read ahead, or with `resident` from a " - "copy of the table in locked RAM", + "and direct reads of the container, a later call's rows read ahead", SHAPE_ANY, DT_ANY, RAD_DOMAIN_HOST, 0, nullptr, 0, nullptr, 0, nullptr, /* INIT, fini, LAUNCH, scratch, layout, relayout, opd_shape, unrelayout */ diff --git a/libavx/avx_rows.h b/libavx/avx_rows.h index 49c1edc2..d54ccb42 100644 --- a/libavx/avx_rows.h +++ b/libavx/avx_rows.h @@ -26,8 +26,7 @@ typedef void (*RowDecode)(const uint8_t* const* src, uint16_t* const* dst, int64 * elements -- E4M3 codes, or bf16 as stored -- `row_bytes` apart, `out` M rows of n_embd bf16 * `x_ld` elements apart. The row cache and the reads deal in `row_bytes`; the decode in elements. * `ahead` holds n_ahead ids a later call will gather, or is null. rank and world_size are the - * call's. `resident` is the op's parameter of that name: keep a copy of the table in RAM and read - * that, once it is there (avx_ngram.cpp). */ + * call's. */ struct RowGather { const int32_t* ids; int64_t M; @@ -40,12 +39,10 @@ struct RowGather { const int32_t* ahead; int64_t n_ahead; int rank, world_size; - int resident; }; -/* The gather, through the row cache when a file backs the table, from its copy in RAM once - * `resident` has made one, and from the table's memory when no file backs it. Returns a RAD_* - * status; on anything but RAD_OK the output is not complete. */ +/* The gather, through the row cache when a file backs the table and from the table's memory when + * none does. Returns a RAD_* status; on anything but RAD_OK the output is not complete. */ int row_gather(const RowGather& g, RowDecode decode); } /* namespace avx */ diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index ac449bd3..dfe374d8 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -405,11 +405,14 @@ extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int worl return ar_mn_acquire(p, n_p, rank, world, out); } -/* The four-rank ar_hc_write. Its key is the one the plain all_reduce at the same call site builds - * -- {rank, 4, bf16, M_hi * n}, and the blocks declare that all_reduce's numel up to max_tok * n -- - * so the fused write and the standalone collective it stands in for run on the SAME scratch, flags - * and counters, and a step that takes either one keeps a single launch sequence on that set. - * Exact wire only: a declared `wire` 6 is refused here, at declare, rather than at the first step. */ +/* The four-rank ar_hc_write and ar_gather_hc_write. The key is the family's -- {rank, 4, bf16, + * M_hi * n} -- so the instance is sized for the most rows the op was declared for, and it is the + * same instance as a standalone all_reduce band's only where the two bounds agree. Either way is + * safe on one stream: every wide kernel takes its flag value from the instance's seq counters, + * advances them once per all-reduce and writes only the (parity, source) slot that value names + * (r4d_ar_wide.h), so ops sharing an instance interleave in any order every rank issues them in, + * and ops on separate instances touch nothing of each other's. Exact wire only: the rows constrain + * `wire` to 0, and a `wire` 6 that reaches this init anyway is refused. */ extern "C" int r4d_rad_ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world, void** out) { if (!out) return RAD_E_INVAL; @@ -1226,9 +1229,10 @@ extern "C" int r4d_rad_ar_gather_hc_write(const RadArgs* a, RadStream s) { return rc == 0 ? RAD_OK : RAD_E_SHAPE; } -/* AT FOUR RANKS, EXACT WIRE ONLY: r4d_rad_ar_hc_write_4rank with the gather in front, on the same - * instance (r4d_rad_ar_hc_wide_init). The architecture issues it only on a step whose write takes - * the exact one-shot (ar_exact_write_takes, arch/common/rad_fp8.h) and whose gather is one pass's. +/* AT FOUR RANKS, EXACT WIRE ONLY: r4d_rad_ar_hc_write_4rank with the gather in front, on an + * instance from the same init (r4d_rad_ar_hc_wide_init). The architecture issues it only on a step + * whose write takes the exact fused form (ar_exact_write_takes, arch/common/rad_fp8.h) and whose + * gather is one pass's. * The block count is that write's rule, widened by the launcher until a block's slot table fits in * LDS -- or, where that would take more blocks than the rule asks for and the scratch is there, * kept and served from the inverse table, as at two ranks. */ @@ -1350,15 +1354,16 @@ extern "C" int r4d_rad_ar_hc_write(const RadArgs* a, RadStream s) { } /* AT FOUR RANKS, EXACT WIRE ONLY: the wide one-shot with the write as its epilogue. The four-rank - * lossy wire is the ti8 two-shot and has no fused form, so a `wire` 6 is refused (init already - * refuses to build it). The architecture issues this only for a message the standalone row would - * have served with the exact one-shot (ar_wide_write_exact, arch/common/rad_fp8.h); larger exact - * messages are still served correctly here, as a one-shot, which the standalone entry would have - * replaced by the two-shot above R4D_AR_EXACT_TWOSHOT_MIN_BYTES -- same bytes, more traffic. + * lossy wire is the ti8 two-shot and has no fused form: the row constrains `wire` to 0, and a + * `wire` 6 that reaches this entry anyway is refused. Every message up to the instance's bound is + * served correctly here as a one-shot. Which steps take it is the caller's choice -- the + * architecture issues it on decode and verify steps (ar_wide_write_exact, arch/common/rad_fp8.h) -- + * and a message the standalone all_reduce's bands would have sent as a two-shot costs more traffic + * here for the same bytes. * * The block count is the plain one-shot's rule (ar_setup's nb_for over the whole message under * nb_cap); a block's words, flags and slot are the one-shot's, which is what lets the two share an - * instance. */ + * instance where their keys agree. */ extern "C" int r4d_rad_ar_hc_write_4rank(const RadArgs* a, RadStream s) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); if (!in) return RAD_E_STATE; diff --git a/libr4d/r4d_ar_oneshot_Nrank_exact.hip b/libr4d/r4d_ar_oneshot_Nrank_exact.hip index eff9e3a2..ebf329ae 100644 --- a/libr4d/r4d_ar_oneshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_oneshot_Nrank_exact.hip @@ -115,10 +115,10 @@ __global__ void r4d_ar_oneshot_wide_exact_kernel( // THE SAME ONE-SHOT WITH THE GATED RESIDUAL'S WRITE AS ITS EPILOGUE, bf16 only. `y` is the // message and is reduced IN PLACE; everything up to the reduce is the kernel above, step for step, -// because both run on one instance's buffers in one stream: the same seq take, the same handshake -// value 2*s, the same (parity, source) slots and the same block partition of the word space. The -// reduce is the same ar_vsum, so the stored word is the plain all-reduce's to the bit; then -// h[r][c*n + i] += inj[r][c] * y[r][i] in hc_write's arithmetic over that bf16 word +// because the two may run on one instance's buffers in one stream: the same seq take, the same +// handshake value 2*s, the same (parity, source) slots and the same block partition of the word +// space. The reduce is the same ar_vsum, so the stored word is the plain all-reduce's to the bit; +// then h[r][c*n + i] += inj[r][c] * y[r][i] in hc_write's arithmetic over that bf16 word // (r4d_ar_hc_write_word, as the two-rank r4d_ar_hc_write_kernel). // // In place is safe: a thread reads every source of word k before it stores word k, its own block diff --git a/libr4d/r4d_emit.h b/libr4d/r4d_emit.h index b4fa703f..898245f4 100644 --- a/libr4d/r4d_emit.h +++ b/libr4d/r4d_emit.h @@ -67,6 +67,21 @@ inline bool r4d_pack_one(RadLaunchDesc& d, size_t& off, int& i, const T& v) { return true; } +/* A kernel's parameter list as r4d_pack_one lays it out -- each value at its own alignment, in + * declaration order -- so that a kernel whose list runs close to RAD_KPARAM_BLOB or + * RAD_MAX_KPARAMS can assert at compile time that it fits, rather than meet RAD_E_FULL at its + * first launch. `F` is the kernel's function type: `decltype(kernel)`, or for a template + * `decltype(kernel)`. */ +template struct R4dParams; +template struct R4dParams { + static constexpr size_t count = sizeof...(P); + static constexpr size_t bytes() { + size_t off = 0; + ((off = ((off + alignof(P) - 1) & ~(size_t)(alignof(P) - 1)) + sizeof(P)), ...); + return off; + } +}; + /* THE ONE EMIT, AND IT TAKES THE KERNEL TYPED. * * `hipLaunchKernelGGL` type-checks its arguments against the kernel's signature and CONVERTS them diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index 99197259..3ac6b918 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -839,10 +839,14 @@ struct MoeCls { * * FOUR CLASSES AND THE TABLE MUST FIT RAD_KPARAM_BLOB (256 bytes) BESIDE EVERYTHING ELSE, because * a kernel's arguments are packed into one descriptor whether it is launched or described: four - * classes at 40 bytes, the five operand pointers and the map, eight words and this. That is why a - * class carries 32-bit entry strides and no table of its own, and why `mode` packs three small - * values into one word. */ + * classes at 40 bytes, the five operand pointers and the map, eight words and this -- 160 + 48 + + * 32 + 16, exactly 256, with no padding since a class is 8-aligned. That is why a class carries + * 32-bit entry strides and no table of its own, and why `mode` packs three small values into one + * word. The sizes are asserted here and the whole list after the kernel. */ struct MoeTab { uint32_t v[4]; }; +static_assert(sizeof(MoeCls) == 40 && alignof(MoeCls) == 8, + "a class is two pointers and six words: the kernel's argument budget counts 40"); +static_assert(sizeof(MoeTab) == 16, "the code table is four words"); /* W4 IS THE WEIGHT'S FORM: 0 block E4M3, 1 four-bit with one bf16 scale a (row, 128 of K), 2 the * same codes with one E4M3 scale a (row, 64 of K) times the fixed kW4G64Scale (w4nl64a8h), 3 the @@ -1321,6 +1325,13 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( if (ES) break; /* one run a block, and it is done */ } } +/* The whole argument list against the descriptor (see MoeTab): every instantiation takes the same + * parameters, so the decode form stands for all of them. */ +using MoeQArgs = R4dParams)>; +static_assert(MoeQArgs::bytes() <= RAD_KPARAM_BLOB, + "moe_gemm_q_kernel's arguments overflow RAD_KPARAM_BLOB"); +static_assert(MoeQArgs::count <= RAD_MAX_KPARAMS, + "moe_gemm_q_kernel has more arguments than RAD_MAX_KPARAMS"); /* ================================================================== moe_gemm, bf16 * diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 2df69c7f..c368bb7c 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -183,12 +183,13 @@ int r4d_rad_ar_ln_init(const RadParam*, int, int rank, int world, void** out); int r4d_rad_ar_ln_had_quant_i8(const RadArgs*, RadStream); int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs*, RadStream); int r4d_rad_ar_hc_write(const RadArgs*, RadStream); -/* ar_hc_write at four ranks, exact wire only, on the plain four-rank all-reduce's instance. */ +/* ar_hc_write at four ranks, exact wire only, on an instance of the wide family keyed by its own + * M bound. */ int r4d_rad_ar_hc_wide_init(const RadParam*, int, int rank, int world, void** out); int r4d_rad_ar_hc_write_4rank(const RadArgs*, RadStream); int r4d_rad_ar_gather_hc_write(const RadArgs*, RadStream); int64_t r4d_rad_ar_gather_hc_write_scratch(const RadArgs*); -/* ar_gather_hc_write at four ranks, exact wire only, on ar_hc_write_4rank's instance. */ +/* ar_gather_hc_write at four ranks, exact wire only, on an instance from the same init. */ int r4d_rad_ar_gather_hc_write_4rank(const RadArgs*, RadStream); /* -- GEMM (r4d_gemm_*.hip) -- */ diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 9dfa1a38..71151e58 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2726,11 +2726,13 @@ static const RadConstraint cArHcWrite[] = { C_P2P, }; /* The same bounds at four ranks, where the handshake is the wide family's (r4d_ar_wide.h). Exact - * wire only, and that cannot be a constraint here: the exact op declares no `wire` and an absent - * key fails a constraint, so the init and the entry refuse wire 6 instead. */ + * wire only: the four-rank lossy wire is the ti8 two-shot and has no fused form, so a `wire` 6 + * request is a selection miss here and its caller keeps the unfused pair, where an init refusal + * would stop declare. The caller states `wire` 0 on the exact form, because a constraint on an + * absent key does not hold; the init and the entry still refuse any other wire. */ static const RadConstraint cArHcWrite4[] = { C_GE("M", 1), C_DIV("n", 8), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), - C_EQ("world_size", 4), + C_EQ("world_size", 4), C_EQ("wire", 0), C_P2P, }; /* ar_hc_write's bounds and the gather's: top_k up to the 64 slots a row's table holds in LDS. */ @@ -2739,11 +2741,10 @@ static const RadConstraint cArGatherHcWrite[] = { C_EQ("world_size", 2), C_GE("top_k", 1), C_LE("top_k", 64), C_P2P, }; -/* The same at four ranks, exact wire only for cArHcWrite4's reason: the init and the entry refuse a - * declared `wire` 6, since the exact op declares no `wire` and an absent key fails a constraint. */ +/* The same at four ranks, exact wire only and constrained so for cArHcWrite4's reason. */ static const RadConstraint cArGatherHcWrite4[] = { C_GE("M", 1), C_DIV("n", 8), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), - C_EQ("world_size", 4), C_GE("top_k", 1), C_LE("top_k", 64), + C_EQ("world_size", 4), C_EQ("wire", 0), C_GE("top_k", 1), C_LE("top_k", 64), C_P2P, }; static const RadConstraint cGatedQuantFp8[] = { @@ -4796,8 +4797,9 @@ static const RadKernelInfo kKernels[] = { "h[s] += inj[s] * y over the reduced y", "exactly 4 ranks, all peer-accessible; exact wire only; n a multiple of 8 and y unpitched, " "because y is the message and a block pushes it as 16B words; the stream pitch a multiple of 8; " - "hc 2..8; the wide one-shot's handshake, slots and block partition, on the plain four-rank " - "all-reduce's instance; cudagraph-safe", + "hc 2..8; the wide one-shot's handshake, slots and block partition, on an instance keyed by " + "its own M bound -- the wide family's flag/seq/slot discipline is what lets it share a stream, " + "or an instance where the keys agree, with the plain all-reduce; cudagraph-safe", "bf16 throughout; the sum in fp32 in ascending rank order and rounded to bf16 exactly as the " "four-rank exact all-reduce stores it, and the write in hc_write's arithmetic over that bf16 " "value -- byte-identical to the pair it replaces", @@ -4829,10 +4831,10 @@ static const RadKernelInfo kKernels[] = { "reduces and writes exactly as ar_hc_write_4rank does", "exactly 4 ranks, all peer-accessible; exact wire only; n a multiple of 8, y unpitched and " "y_expert's pitch a multiple of 8, because both move as 16B words; top_k <= 64; the stream " - "pitch a multiple of 8; hc 2..8; the wide one-shot's handshake and slots on the plain four-rank " - "all-reduce's instance; the grid widened until a block's slot table fits in LDS, or the " - "inverse table in the scratch where that would take more blocks than the reduction asks for; " - "cudagraph-safe", + "pitch a multiple of 8; hc 2..8; the wide one-shot's handshake and slots, on an instance keyed " + "by its own M bound as ar_hc_write_4rank's is; the grid widened until a block's slot table fits " + "in LDS, or the inverse table in the scratch where that would take more blocks than the " + "reduction asks for; cudagraph-safe", "bf16 throughout; the gather's sums and narrows are moe_gather's (round-to-nearest-even, the " "shared arm's product rounded before the add), the sum in fp32 in ascending rank order and " "rounded to bf16 exactly as the four-rank exact all-reduce stores it, and the write in " diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 2703d344..40f94c62 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -6160,6 +6160,267 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int } } +/* THE FOUR-CLASS GROUPED GEMM, EACH CLASS AT ITS OWN GEOMETRY, AGAINST A HOST DECODE. + * + * moe_w4_gemm's four-class pass reads the two-class op's tables as four, so its classes come in + * geometry pairs -- 0 with 2, 1 with 3 -- and class 0 is always among the wide ones. A rank of four + * holds two blocks of its own class of every five-block expert and one of each other: ONE wide + * class, which is class 0 on rank 0 only. Here every class is built at its own [N_q, K_q], stored + * through the row's own hooks at its own operands (2/3, 6/7, 8/9, 10/11), and checked against the + * planes, so a wide class 1, 2 or 3 has to read its own width and pitch, and a narrow class 0 has + * to write the zeros past its part. `dt` names the format: fp8a8 runs `moe_gemm_fp8a8_mod4`, block + * E4M3 with a bf16 scale a 128x128 tile; the four-bit ones run `moe_gemm_w4a8_mod4`, as + * moe_w4_gemm reads them. Every form, as there. */ +struct MoeQ4Shape { const char* name; int64_t N[4], K[4], parts, ne; }; + +/* A rank of four's slices of a five-block expert: the gate/up pair (two parts) at two 128-column + * blocks a part for the wide class and one for the others, the down projection at 256 and 128 of + * K. The wide class is 1, 2 or 3 -- what the ranks other than 0 hold. Ten experts make classes 0 + * and 1 one expert longer than 2 and 3; three hundred spread a decode step's few runs over + * experts that are mostly empty. Every part is whole 128-row blocks of the fp8 scale grid or lies + * inside one, so no output tile's weight rows straddle two -- block fp8 reads one scale a tile. */ +static const MoeQ4Shape kMoeQ4Shapes[] = { + { "gate/up, class 1 wide", { 256, 512, 256, 256 }, { 256, 256, 256, 256 }, 2, 10 }, + { "gate/up, class 2 wide", { 256, 256, 512, 256 }, { 256, 256, 256, 256 }, 2, 10 }, + { "down, class 3 wide", { 128, 128, 128, 128 }, { 128, 128, 128, 256 }, 1, 10 }, + { "300 experts, gate/up, class 3 wide", { 128, 128, 128, 256 }, { 128, 128, 128, 128 }, 2, + 300 }, +}; + +static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, const char* dt) { + const bool fp8 = std::strcmp(dt, "fp8a8") == 0, w5 = std::strcmp(dt, "w5nl64a8h") == 0; + /* Scale groups a 128 of K at the E4M3-scaled forms (moe_w4_gemm's `sub`), 0 at the others. */ + const int64_t sub = std::strcmp(dt, "w4nl32a8h") == 0 ? 4 + : (w5 || std::strcmp(dt, "w4nl64a8h") == 0) ? 2 : 0; + const bool g64 = sub > 1; + const float* tab = w5 ? kW5nlTable : kW4nlTable; + static const char* const kForm[] = { "rule", "aligned prefill form", "decode form", + "uniform prefill grid" }; + const char* row = fp8 ? "moe_gemm_fp8a8_mod4" : "moe_gemm_w4a8_mod4"; + const std::string what = std::string(row) + " vs a host decode (T=" + std::to_string(Tr) + + ", " + sh.name + ", " + dt + ")"; + const RadKernelInfo* r = find(pl, row); + if (!r || !r->layout || (!fp8 && !r->relayout)) { + ok(what.c_str(), false, "row or hooks absent"); + return; + } + + const int64_t ne = sh.ne, group = 128, top_k = 2; + int64_t N = 0, K = 0; + for (int q = 0; q < 4; ++q) { + N = std::max(N, sh.N[q]); + K = std::max(K, sh.K[q]); + } + const int64_t kb = K / group, M = Tr / top_k, fy = N / sh.parts; + const std::vector lp = { + PI("N", sh.N[0]), PI("K", sh.K[0]), PI("N_1", sh.N[1]), PI("K_1", sh.K[1]), + PI("N_2", sh.N[2]), PI("K_2", sh.K[2]), PI("N_3", sh.N[3]), PI("K_3", sh.K[3]), + PI("group", group), PS("dtype", dt), + }; + + /* Each class's experts e = 4x + q, from moe_w4_gemm's float source; their planes, kept for + * the reference, and the bytes the hooks store for them, asked at the class's own operands. + * Block fp8 is stored as its planes are, in both views; the four-bit codes are re-laid, and so + * is the E4M3 scale view with its second level, while a bf16 scale plane is stored as it is. */ + std::vector wq[4], ws[4]; + std::vector cp[4]; + int64_t nec[4] = { 0, 0, 0, 0 }; + for (int q = 0; q < 4; ++q) { + const int64_t Nq = sh.N[q], Kq = sh.K[q], kbq = Kq / group; + const int ow = q ? 4 + 2 * q : 2, os = ow + 1; + const int64_t wbytes = fp8 ? Nq * Kq : w5 ? Nq * Kq / 8 * 5 : Nq * Kq / 2; + const int64_t sbytes = fp8 ? (Nq + group - 1) / group * kbq * 2 + : Nq * kbq * (g64 ? sub : 2); + nec[q] = (ne + 3 - q) / 4; + std::vector wsrc((size_t)(Nq * Kq)); + for (int64_t x = 0; x < nec[q]; ++x) { + const int64_t e = 4 * x + q; + for (int64_t n = 0; n < Nq; ++n) + for (int64_t k = 0; k < Kq; ++k) + wsrc[(size_t)(n * Kq + k)] = + (float)(((e * 7 + n * 31 + k * 17) % 61) - 30) / 37.0f; + cp[q].push_back(fp8 ? fp8_block_planes(wsrc, Nq, Kq) + : g64 ? nl64_planes(wsrc, Nq, Kq, group / sub, w5) + : int4_planes(wsrc, Nq, Kq, group, RAD_BF16, false)); + std::vector w, sc; + const int rw = g64 ? stored(r, lp, ow, cp[q].back(), { "codes", "table" }, &w) + : stored(r, lp, ow, cp[q].back(), { "codes" }, &w); + const int rs = g64 ? stored(r, lp, os, cp[q].back(), { "scale", "scale.1" }, &sc) + : stored(r, lp, os, cp[q].back(), { "scale" }, &sc); + if (rw != (fp8 ? RAD_E_UNSUPPORTED : RAD_OK) || + rs != (g64 ? RAD_OK : RAD_E_UNSUPPORTED)) { + ok(what.c_str(), false, "class " + std::to_string(q) + " relayout rc " + + std::to_string(rw) + "/" + std::to_string(rs)); + return; + } + if ((int64_t)w.size() != wbytes || (int64_t)sc.size() != sbytes) { + ok(what.c_str(), false, "class " + std::to_string(q) + " stored " + + std::to_string(w.size()) + " and " + + std::to_string(sc.size()) + " bytes an expert, for " + + std::to_string(wbytes) + " and " + std::to_string(sbytes)); + return; + } + wq[q].insert(wq[q].end(), w.begin(), w.end()); + ws[q].insert(ws[q].end(), sc.begin(), sc.end()); + } + } + + /* moe_w4_gemm's activation and routing: E4M3 bytes with no subnormal and no NaN, an f32 scale + * a (row, group), an uneven run on each expert and a dropped tail. */ + std::vector aq((size_t)(M * K)); + std::vector as((size_t)(M * kb)); + for (int64_t m = 0; m < M; ++m) { + for (int64_t g = 0; g < kb; ++g) as[(size_t)(m * kb + g)] = 0.011f + 0.003f * (float)g; + for (int64_t k = 0; k < K; ++k) { + const uint32_t c = (uint32_t)((m * 13 + k * 5) % 119) + 8; + aq[(size_t)(m * K + k)] = (uint8_t)(((m + k) & 1) ? (c | 0x80u) : c); + } + } + std::vector off((size_t)(ne + 1), 0), sorted((size_t)Tr, -1); + const int64_t live = Tr - 3; + for (int64_t e = 0; e <= ne; ++e) off[(size_t)e] = (int32_t)((live * e) / ne); + off[(size_t)ne] = (int32_t)live; + for (int64_t i = 0; i < live; ++i) sorted[(size_t)i] = (int32_t)((i * 7 + 3) % Tr); + + void* d_a = dalloc(aq.size()); + void* d_as = dalloc(as.size() * 4); + void* d_w[4]; + void* d_ws[4]; + for (int q = 0; q < 4; ++q) { + d_w[q] = dalloc(wq[q].size()); + d_ws[q] = dalloc(ws[q].size()); + st_memcpy(d_w[q], wq[q].data(), wq[q].size(), hipMemcpyHostToDevice); + st_memcpy(d_ws[q], ws[q].data(), ws[q].size(), hipMemcpyHostToDevice); + } + void* d_s = dalloc(sorted.size() * 4); + void* d_o = dalloc(off.size() * 4); + void* d_y = dalloc((size_t)(Tr * N * 2)); + st_memcpy(d_a, aq.data(), aq.size(), hipMemcpyHostToDevice); + st_memcpy(d_as, as.data(), as.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_s, sorted.data(), sorted.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_o, off.data(), off.size() * 4, hipMemcpyHostToDevice); + + /* The stacked table form, as moe_w4_gemm hands it, each class at its own extents. */ + auto codes_t = [&](int q) { + return T(d_w[q], fp8 ? (uint32_t)RAD_F8E4M3 : w5 ? (uint32_t)R4D_DT_MOEW5 + : (uint32_t)R4D_DT_MOEW4, + { nec[q], sh.N[q], sh.K[q] }); + }; + auto scale_t = [&](int q) { + const int64_t kbq = sh.K[q] / group; + return fp8 ? T(d_ws[q], RAD_BF16, { nec[q], (sh.N[q] + group - 1) / group, kbq }) + : g64 ? T(d_ws[q], RAD_F8E4M3, { nec[q], sh.N[q], sub * kbq }) + : T(d_ws[q], RAD_BF16, { nec[q], sh.N[q], kbq }); + }; + std::vector ts = { + T(d_a, RAD_F8E4M3, { M, K }), T(d_as, RAD_F32, { M, kb }), codes_t(0), scale_t(0), + T(d_s, RAD_I32, { Tr }), T(d_o, RAD_I32, { ne + 1 }), codes_t(1), scale_t(1), + codes_t(2), scale_t(2), codes_t(3), scale_t(3), T(d_y, RAD_BF16, { Tr, N }), + }; + std::vector ps = { + PI("M", M), PI("N", sh.N[0]), PI("K", sh.K[0]), PI("N_1", sh.N[1]), PI("K_1", sh.K[1]), + PI("N_2", sh.N[2]), PI("K_2", sh.K[2]), PI("N_3", sh.N[3]), PI("K_3", sh.K[3]), + PI("parts", sh.parts), PI("n_expert", ne), PI("top_k", top_k), PI("group", group), + PS("a_order", "token"), PS("dtype", dt), + }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + const int64_t map_bytes = (1 + 2 * (ne + Tr / 16 + 2)) * 4; + void* d_map = dalloc((size_t)map_bytes); + + /* The reference, from the planes: row i's expert e is class e % 4, entry e / 4, at that + * class's width and K; a part's columns past the class's width are zero. */ + std::vector ref((size_t)(Tr * N), 0.0); + for (int64_t i = 0; i < Tr; ++i) { + const int32_t f = sorted[(size_t)i]; + int64_t e = 0; + while (e + 1 < ne && off[(size_t)(e + 1)] <= i) ++e; + const int q = (int)(e % 4); + const Planes& p = cp[q][(size_t)(e / 4)]; + const int64_t fc = sh.N[q] / sh.parts, Kq = sh.K[q], kbq = Kq / group; + for (int64_t n = 0; n < N; ++n) { + double want = 0.0; + const int64_t pp = n / fy, j = n - pp * fy; + if (f >= 0 && i < live && j < fc) { + const int64_t tok = f / top_k, wr = pp * fc + j; + for (int64_t g = 0; g < kbq; ++g) { + const double a_s = (double)as[(size_t)(tok * kb + g)]; + if (fp8) { + /* E4M3 codes, and the bf16 scale of the 128x128 tile the element is in. */ + double part = 0.0; + for (int64_t k = g * group; k < (g + 1) * group; ++k) + part += (double)h_e4m3(p.data[0][(size_t)(wr * Kq + k)]) * + (double)st_e4m3(aq[(size_t)(tok * K + k)]); + want += part * (double)rad_load_f32(p.data[1].data(), RAD_BF16, + (wr / group) * kbq + g) * a_s; + } else if (g64) { + /* `sub` scale groups a 128, each an E4M3 byte under the fixed constant. */ + const int64_t gw = group / sub; + for (int64_t h = 0; h < sub; ++h) { + double part = 0.0; + for (int64_t k = g * group + h * gw; k < g * group + (h + 1) * gw; ++k) + part += (double)tab[code_at(p, wr, k)] * + (double)st_e4m3(aq[(size_t)(tok * K + k)]); + const uint8_t sb = + p.data[1][(size_t)(wr * p.row_bytes(1) + sub * g + h)]; + want += part * (double)h_e4m3(sb) * (double)kW4G64Scale * a_s; + } + } else { + double part = 0.0; + for (int64_t k = g * group; k < (g + 1) * group; ++k) + part += (double)code_at(p, wr, k) * + (double)st_e4m3(aq[(size_t)(tok * K + k)]); + want += part * (double)rad_load_f32(p.data[1].data(), RAD_BF16, + wr * kbq + g) * a_s; + } + } + } + ref[(size_t)(i * N + n)] = want; + } + } + + const int f_lo = pl.pin_moe ? 1 : 0, f_hi = pl.pin_moe ? 3 : 0; + for (int form = f_lo; form <= f_hi; ++form) { + const std::string label = what + " " + kForm[form]; + if (pl.pin_moe) pl.pin_moe(form); + /* Stale bytes where a narrow class writes zeros, so a pad tile left unwritten shows. */ + { + std::vector junk((size_t)(Tr * N), 0x7f7fu); + st_memcpy(d_y, junk.data(), junk.size() * 2, hipMemcpyHostToDevice); + } + a.scratch = form == 3 ? nullptr : d_map; + a.scratch_bytes = form == 3 ? 0 : map_bytes; + const int rc = r->launch(&a, nullptr); + st_stream_sync(nullptr); + if (pl.pin_moe) pl.pin_moe(0); + if (rc != RAD_OK) { ok(label.c_str(), false, "launch rc=" + std::to_string(rc)); continue; } + + std::vector got((size_t)(Tr * N)); + st_memcpy(got.data(), d_y, got.size() * 2, hipMemcpyDeviceToHost); + double worst = 0.0; + int64_t bad = 0; + std::string first; + for (int64_t i = 0; i < Tr; ++i) + for (int64_t n = 0; n < N; ++n) { + const double want = ref[(size_t)(i * N + n)]; + const double err = std::fabs((double)h_bf16(got[(size_t)(i * N + n)]) - want); + /* moe_w4_gemm's tolerance, written so that a NaN on either side is a miss. */ + if (!(err <= 0.004 * std::fabs(want) + 1e-4)) { + if (!bad++) + first = ", first at row " + std::to_string(i) + " col " + + std::to_string(n) + ": " + + std::to_string(h_bf16(got[(size_t)(i * N + n)])) + " for " + + std::to_string(want); + if (!(err <= worst)) worst = err; + } + } + ok(label.c_str(), bad == 0, std::to_string(bad) + " of " + std::to_string(Tr * N) + + " elements off, worst " + std::to_string(worst) + first); + } +} + /* THE ARRANGED PLANE, AGAINST THE FORMAT IT STATES, AND BACK. * * `moe_gemm_w4a8` is the one large weight of a routed model, and what a checker reads it through is @@ -9728,7 +9989,7 @@ static void device_phase(const Plugin& pl) { if (sel("moe_gemm_w4a8_mod4")) { if (!g_case) std::printf("\nthe 4-bit grouped MoE GEMM over four classes, against its " - "two-class form\n"); + "two-class form and a host decode\n"); /* The same shapes, read as four classes: the even table's halves are classes 0 and 2 and * the odd one's 1 and 3, so the two-class launch is the reference, byte for byte. */ static const MoeW4Shape kShapes4[] = { @@ -9741,8 +10002,22 @@ static void device_phase(const Plugin& pl) { for (const int64_t t : { (int64_t)24, (int64_t)200, (int64_t)600 }) { moe_w4_gemm(pl, t, sh, 0, false, true); moe_w4_gemm(pl, t, sh, 2, false, true); + moe_w4_gemm(pl, t, sh, 4, false, true); moe_w4_gemm(pl, t, sh, 2, true, true); } + /* And every class at its own geometry, one of classes 1 to 3 the only wide one. */ + for (const MoeQ4Shape& sh : kMoeQ4Shapes) + for (const int64_t t : { (int64_t)24, (int64_t)200, (int64_t)600 }) + for (const char* dt : { "w4a8", "w4nl64a8h", "w4nl32a8h", "w5nl64a8h" }) + moe_q4_gemm(pl, t, sh, dt); + } + + if (sel("moe_gemm_fp8a8_mod4")) { + if (!g_case) std::printf("\nthe block-fp8 grouped MoE GEMM over four classes, against a " + "host decode\n"); + for (const MoeQ4Shape& sh : kMoeQ4Shapes) + for (const int64_t t : { (int64_t)24, (int64_t)200, (int64_t)600 }) + moe_q4_gemm(pl, t, sh, "fp8a8"); } if (sel("hc_read_e4m3")) { diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 4cf08f69..77ee84e9 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -489,13 +489,7 @@ static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_voc P_F64O("wscale") }; static const RadOperandSpec oEmbed[] = { OPD("tokens"), WGT("wte"), OUT("x") }; /* The quantised table: one scale for all of it. A SEPARATE OP and not a dtype on the above -- - * the operand list differs and operands are positional, the same argument gemm_nt_q makes. - * `resident` asks a kernel that reads a file-backed table from disk to keep a copy of it in RAM - * instead (--ngram-table ram). It changes where the rows come from and not what they are, and a - * kernel that reads the table as memory, as this one does, has nothing to do for it. */ -static const RadParamSpec pEmbedQ[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), - P_STR("dtype"), P_INTO("vocab_offset"), P_F64O("wscale"), - P_INTO("resident") }; + * the operand list differs and operands are positional, the same argument gemm_nt_q makes. */ static const RadOperandSpec oEmbedQ[] = { OPD("tokens"), WGT("wte"), WGT_O("scale"), OUT("x"), OPD_O("ahead") }; @@ -875,7 +869,7 @@ static const RadOpSchema kSchemas[] = { { "embed_lookup", ARR(pEmbed), ARR(oEmbed), "A gather from wte[n_vocab, n_embd]. A negative token id writes a zero row (padding); an id at " "or above n_vocab fails the launch." }, -{ "embed_lookup_q", ARR(pEmbedQ), ARR(oEmbedQ), +{ "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ), "The same gather from a table quantised with ONE scale for all of it: x[m] = wte[id] * scale[0]. " "Qwen3.8-Flash-Next-FP8's 320-million-row n-gram embedding is stored that way -- E4M3 codes and a " "single bf16 `weight_scale` -- and it can be, because E4M3 carries its own exponent and a row's " diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index c5cfcd22..41de9380 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1111,11 +1111,13 @@ int ref_moe_gemm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) } /* THE WEIGHT SCALE GRID IS THE ONE `dtype` NAMES, and the grouped GEMM serves more than one. The - * block-fp8 experts carry the checkpoint's: a scale a 128x128 tile, `group` holding the 128. The - * four-bit ones (docs/MOE-W4.md) carry one a ROW per group of K -- all of `group` at w4a8, w4a8h - * and w4nla8h, half of it at w4nl64a8h and w5nl64a8h, a quarter at w4nl32a8h. Those strings are - * the served formats' own names (arch/common/rad_block_moe_fp8.h, kServed), so this states a - * format and guesses at no kernel's stream; anything else is the block grid. + * block-fp8 experts (fp8a8) carry the checkpoint's: a scale a 128x128 tile, `group` holding the + * 128. The four-bit ones (docs/MOE-W4.md) carry one a ROW per group of K -- all of `group` at + * w4a8, w4a8h and w4nla8h, half of it at w4nl64a8h and w5nl64a8h, a quarter at w4nl32a8h. Those + * strings are the served formats' own names (arch/common/rad_block_moe_fp8.h, kServed), so this + * states a format and guesses at no kernel's stream. Any other dtype, or none, names no grid this + * file knows: the answer is { 0, 0 } and the description declines (RAD_E_UNSUPPORTED), because a + * scale plane sized on a guessed grid is a tensor of the wrong extent handed to the oracle. * * It matters past the extents. A weight its kernel stores re-laid goes back through that * kernel's inverse into the tensor THIS describes before the oracle hands it over @@ -1123,15 +1125,16 @@ int ref_moe_gemm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) * operand -- so tiles here leave every such expert's scales with nothing to be inverted into. * The arithmetic reads whichever grid it is handed (ref_gemm.h derives the group from the * extents) and is unchanged. Weight rows and K elements a scale covers, or 0 when `group` is too - * small to divide. */ + * small to divide or the dtype names no grid. */ struct MoeScaleGrid { int64_t rows, k; }; static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) { const char* d = gs(p, n_p, "dtype"); auto is = [&](const char* s) { return d && std::strcmp(d, s) == 0; }; + if (is("fp8a8")) return { g, g }; if (is("w4a8") || is("w4a8h") || is("w4nla8h")) return { 1, g }; if (is("w4nl64a8h") || is("w5nl64a8h")) return { 1, g / 2 }; if (is("w4nl32a8h")) return { 1, g / 4 }; - return { g, g }; + return { 0, 0 }; } /* The quantised arm. Same planes, plus the two scale streams: the activation's is per row per diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9ac88116..4b438547 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -158,8 +158,7 @@ endif() # runs embed_lookup_q over a file-backed table with two ranks and the read-ahead racing: the path a # model's host gather takes and that no geometry reaches. It writes its table beside itself, where # the filesystem reports its direct-I/O alignment, and again in TMPDIR, where a tmpfs reports none -# and the gather aligns its reads by the block size, as it does on btrfs. And once with `resident`, -# from the table's copy in RAM where the process may lock it. +# and the gather aligns its reads by the block size, as it does on btrfs. if(TARGET libavx AND TARGET rad-avx-check) add_test(NAME avx_check COMMAND rad-avx-check --ref ${RAD_PLUGIN_OUT}/kernels/libref.so diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 266b52ca..fc459ac2 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -1849,18 +1849,18 @@ TEST(a_sizing_declare_leaves_the_step_state_alone_and_shrinks_only_rows) { * cannot cut evenly, so the split is UNEVEN BY CLASS and it is the width that divides, not the * expert set: every rank routes every one of the 512 experts and computes [lo, hi) of each, the * rank taking the odd block going round with the expert's number mod 4 -- five blocks of every - * four experts on every rank -- and with its parity in a layer whose quantised experts do not - * come in fours. Sharding the experts instead - * was tried and is wrong here -- protection is per-rank, so a rank can end up owning one plain - * bf16 expert, leaving an odd count of quantised ones, and the grouped GEMM takes its experts as - * two EQUAL tables by parity. The recipe protects experts in pairs for exactly that reason. + * four experts on every rank, whatever count of quantised experts (four or more) a layer + * keeps. Sharding the experts instead was tried and is wrong here -- protection is per-rank, + * so a rank can end up owning one plain bf16 expert, leaving an odd count of quantised ones, + * and the grouped GEMM takes its experts as two EQUAL tables by parity. The recipe protects + * experts in pairs for exactly that reason. * - the FUSED all-reduces are world-2 kernels (`ar_wire_is_exact` and `ar_fused_ok` both return * false off two), with one exception: the gated residual's write. `ar_hc_write` and - * `ar_gather_hc_write` also exist at four, on the exact wire only (no `wire` key, never the - * rotated form). Every block still declares its standalone `all_reduce`, and every MoE block - * its `moe_gather`, which serve the steps the fused write declines. 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. + * `ar_gather_hc_write` also exist at four, on the exact wire only (`wire` 0, never the rotated + * form) and over the rows of a decode or verify step, max_seqs * (1 + max_spec). Every block + * still declares its standalone `all_reduce`, and every MoE block its `moe_gather`, which + * serve the steps the fused write declines. 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 @@ -2002,7 +2002,9 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { /* (4) A standalone collective per reduction, the exact four-rank ar_hc_write and * ar_gather_hc_write beside it -- the gather form on every MoE connection, so one a layer - * plus the MTP head's if there is one -- and not the fused norm. */ + * plus the MTP head's if there is one -- and not the fused norm. Both fused forms state + * the exact wire and are declared over a decode or verify step's rows, 8 * (1 + 3): the + * architecture's own bound, not a message size a kernel library chose. */ CHECK(count_op(b[r], "all_reduce") > 0); CHECK_EQ(pint(find_op(b[r], "all_reduce"), "world_size"), world); CHECK(count_op(b[r], "ar_hc_write") > 0); @@ -2012,7 +2014,11 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { for (const RecOp& o : b[r].ops) { if (o.op != "ar_hc_write" && o.op != "ar_gather_hc_write") continue; CHECK_EQ(pint(&o, "world_size"), world); - CHECK(param(&o, "wire") == nullptr); /* exact only */ + CHECK_EQ(pint(&o, "wire"), 0); /* exact only, and stated */ + const RecParam* m = param(&o, "M"); + REQUIRE(m != nullptr); + CHECK_EQ(m->kind, (int)RAD_P_RANGE); + CHECK_EQ(m->ihi, c[r].max_seqs * (1 + c[r].max_spec)); } CHECK_EQ(count_op(b[r], "ar_rmsnorm_quant_fp8"), 0); } @@ -2048,9 +2054,9 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { } /* THE SHARED ARM IS SPLIT BY WHOLE BLOCKS AND IS UNEVEN AT FOUR: 640 is five blocks of 128, and - * the rank taking the extra block is rank 2, the first rank the routed split gives no extra - * block (qwen4exp_fp8.cpp's narrow_place) -- ranks 2, 3, 0, 1 cut [0,256) [256,384) [384,512) - * [512,640) in the model's column numbering. At two ranks rank 0 still takes three of five. + * the rank taking the extra block is rank 2, the first rank after the plain experts' extra + * tiles on ranks 0 and 1 (qwen4exp_fp8.cpp's shared_place) -- ranks 2, 3, 0, 1 cut [0,256) + * [256,384) [384,512) [512,640) in the model's column numbering. At two ranks rank 0 still takes three of five. * This is the one world-4 span that is NOT a KV head. */ const int64_t sh_lo[] = { 384, 512, 0, 256 }; const int64_t sh_hi[] = { 512, 640, 256, 384 }; @@ -2095,6 +2101,14 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { 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); + /* Two ranks keep the exact write over every step, prefill chunks included. */ + for (const RecOp& o : h[r].ops) { + if (o.op != "ar_hc_write") continue; + CHECK_EQ(pint(&o, "wire"), 0); + const RecParam* m = param(&o, "M"); + REQUIRE(m != nullptr); + CHECK_EQ(m->ihi, c2.max_tok); + } /* 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 @@ -2103,24 +2117,54 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { } } - /* THE FOUR-RANK FUSED WRITE'S STEPS: exactly those the standalone collective would have served - * as the exact one-shot -- under 1 MiB, and on the lossy wire also under its floor (or off its - * 128-element tile). The block in front and the write ask the same predicate. At two ranks it - * is ar_wire_is_exact unchanged, and ar_wire_is_exact itself stays false at four. */ + /* THE FOUR-RANK FUSED WRITE'S STEPS: the decode and verify steps -- max_seqs * (1 + max_spec) + * rows, never more than max_tok -- whose message goes out exact, which on the lossy wire means + * under its floor or off its 128-element tile. The bound is the architecture's own and not a + * message size: 64 sequences at depth 3 are 256 rows, 1.25 MiB, and still take it, while a + * prefill chunk keeps the pair at any size. The block in front and the write ask the same + * predicate. At two ranks it is ar_wire_is_exact unchanged, and ar_wire_is_exact itself stays + * false at four. */ { rad::arch::Geom g4{}; g4.world = 4; g4.n_embd = 2560; g4.wire_exact = 1; g4.wire_min_bytes = 128 * 1024; - CHECK(rad::arch::ar_exact_write_takes(g4, 8)); /* a decode step, 40 KiB */ - CHECK(rad::arch::ar_exact_write_takes(g4, 204)); /* 1020 KiB */ - CHECK(!rad::arch::ar_exact_write_takes(g4, 205)); /* 1025 KiB: the two-shot's */ + g4.max_tok = 2048; g4.max_seqs = 8; g4.max_spec = 3; + CHECK_EQ(rad::arch::ar_wide_write_rows(g4), (int64_t)32); + CHECK_EQ(rad::arch::ar_exact_write_rows(g4), (int64_t)32); + CHECK(!rad::arch::ar_exact_write_takes(g4, 0)); + CHECK(rad::arch::ar_exact_write_takes(g4, 1)); + CHECK(rad::arch::ar_exact_write_takes(g4, 8)); /* a decode step */ + CHECK(rad::arch::ar_exact_write_takes(g4, 32)); /* every sequence verifying 1 + 3 */ + CHECK(!rad::arch::ar_exact_write_takes(g4, 33)); /* more: a prefill chunk's */ + CHECK(!rad::arch::ar_exact_write_takes(g4, 2048)); CHECK(!rad::arch::ar_wire_is_exact(g4, 8)); g4.wire_exact = 0; CHECK(rad::arch::ar_exact_write_takes(g4, 25)); /* 125 KiB, under the floor */ CHECK(!rad::arch::ar_exact_write_takes(g4, 26)); /* 130 KiB, the ti8 wire's */ + CHECK(!rad::arch::ar_exact_write_takes(g4, 32)); + g4.wire_exact = 1; + g4.max_spec = 0; /* one row a sequence */ + CHECK_EQ(rad::arch::ar_wide_write_rows(g4), (int64_t)8); + CHECK(rad::arch::ar_exact_write_takes(g4, 8)); + CHECK(!rad::arch::ar_exact_write_takes(g4, 9)); + g4.max_seqs = 64; g4.max_spec = 3; + CHECK(rad::arch::ar_exact_write_takes(g4, 256)); /* 1.25 MiB */ + CHECK(!rad::arch::ar_exact_write_takes(g4, 257)); + g4.max_tok = 128; /* a step holds no more than this */ + CHECK_EQ(rad::arch::ar_wide_write_rows(g4), (int64_t)128); + CHECK(rad::arch::ar_exact_write_takes(g4, 128)); + CHECK(!rad::arch::ar_exact_write_takes(g4, 129)); + rad::arch::Geom g8 = g4; + g8.world = 8; + CHECK_EQ(rad::arch::ar_exact_write_rows(g8), (int64_t)0); + CHECK(!rad::arch::ar_exact_write_takes(g8, 8)); rad::arch::Geom g2 = g4; - g2.world = 2; - for (int64_t T : { 1, 8, 25, 26, 205, 4096 }) - CHECK(rad::arch::ar_exact_write_takes(g2, T) == rad::arch::ar_wire_is_exact(g2, T)); + g2.world = 2; g2.max_tok = 4096; g2.max_seqs = 8; + CHECK_EQ(rad::arch::ar_exact_write_rows(g2), g2.max_tok); + for (int exact : { 0, 1 }) { + g2.wire_exact = exact; + for (int64_t T : { 1, 8, 25, 26, 33, 205, 4096 }) + CHECK(rad::arch::ar_exact_write_takes(g2, T) == rad::arch::ar_wire_is_exact(g2, T)); + } } /* THE FOUR-RANK GATHER'S STEPS: the fused write's, and within one MoE pass. The exact bound * is the only one at four (the rotated form is never declared there, so `rows6` is 0), and a @@ -2129,14 +2173,15 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { { rad::arch::Geom g4{}; g4.world = 4; g4.n_embd = 2560; g4.wire_exact = 1; g4.wire_min_bytes = 128 * 1024; - CHECK(rad::arch::gather_taken(g4, 8, 2048, 0)); /* a decode step */ - CHECK(rad::arch::gather_taken(g4, 204, 2048, 0)); /* 1020 KiB, one pass */ - CHECK(!rad::arch::gather_taken(g4, 205, 2048, 0)); /* the two-shot's */ + g4.max_tok = 2048; g4.max_seqs = 8; g4.max_spec = 3; + CHECK(rad::arch::gather_taken(g4, 8, 32, 0)); /* a decode step */ + CHECK(rad::arch::gather_taken(g4, 32, 32, 0)); /* a verify step, one pass */ + CHECK(!rad::arch::gather_taken(g4, 33, 2048, 0)); /* the write declines it */ CHECK(!rad::arch::gather_taken(g4, 8, 0, 0)); /* not declared */ - CHECK(!rad::arch::gather_taken(g4, 100, 64, 0)); /* two passes */ + CHECK(!rad::arch::gather_taken(g4, 20, 16, 0)); /* two passes */ g4.wire_exact = 0; - CHECK(rad::arch::gather_taken(g4, 25, 2048, 0)); /* under the floor */ - CHECK(!rad::arch::gather_taken(g4, 26, 2048, 0)); /* the ti8 wire's */ + CHECK(rad::arch::gather_taken(g4, 25, 32, 0)); /* under the floor */ + CHECK(!rad::arch::gather_taken(g4, 26, 32, 0)); /* the ti8 wire's */ rad::arch::Geom g2 = g4; g2.world = 2; for (int64_t T : { 1, 8, 25, 26, 205, 4096 }) @@ -2146,7 +2191,7 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { } } /* ...and the lossy wire at four declares no rotated write and no rotated gather form: the - * exact ones only, for the steps under the floor. */ + * exact ones only, stating `wire` 0, for the decode and verify steps under the floor. */ { RadBuilder b4; RadBuildCtx c4 = build_ctx(0, world); @@ -2158,7 +2203,10 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { CHECK(count_op(b4, "ar_gather_hc_write") > 0); for (const RecOp& o : b4.ops) { if (o.op != "ar_hc_write" && o.op != "ar_gather_hc_write") continue; - CHECK(param(&o, "wire") == nullptr); + CHECK_EQ(pint(&o, "wire"), 0); + const RecParam* m = param(&o, "M"); + REQUIRE(m != nullptr); + CHECK_EQ(m->ihi, c4.max_seqs * (1 + c4.max_spec)); } } @@ -2181,9 +2229,7 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { const RadEncoding w4p = [] { RadEncoding e = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128); rad_enc_copy_str(e.transform, "fwht128"); return e; }(); const RadEncoding plain = rad_enc_plain(RAD_BF16); - /* The parity slices, [lo, hi) by place parity, and the four-class ones by place mod 4. */ - const int64_t par_lo[4][2] = { { 0, 512 }, { 256, 0 }, { 384, 256 }, { 512, 384 } }; - const int64_t par_hi[4][2] = { { 256, 640 }, { 384, 256 }, { 512, 384 }, { 640, 512 } }; + /* The four-class slices, [lo, hi) by rank and place mod 4. */ const int64_t c4_lo[4][4] = { { 0, 512, 384, 256 }, { 256, 0, 512, 384 }, { 384, 256, 0, 512 }, { 512, 384, 256, 0 } }; const int64_t c4_hi[4][4] = { { 256, 640, 512, 384 }, { 384, 256, 640, 512 }, @@ -2204,7 +2250,6 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { RadBuildCtx cp = build_ctx(r, world); cp.max_tok = 2048; cp.max_seqs = 8; cp.max_spec = 3; cp.max_ctx = 200000; REQUIRE_EQ(qwen4exp_fp8::declare(&bp, &meta, &cp), RAD_OK); - const int ncls = 4; const int64_t n_reg = ne_all - nprot; /* layer 1's quantised GEMMs, and nobody else's */ int l1_ops = 0, other_ops = 0; @@ -2215,7 +2260,7 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { l1 = l1 || bp.weights[wh - 1].name.rfind("blk.1.", 0) == 0; if (!l1) { CHECK_EQ(o.op, std::string("moe_gemm_q_mod4")); ++other_ops; continue; } ++l1_ops; - CHECK_EQ(o.op, std::string(ncls == 4 ? "moe_gemm_q_mod4" : "moe_gemm_q")); + CHECK_EQ(o.op, std::string("moe_gemm_q_mod4")); CHECK_EQ(pint(&o, "n_expert"), n_reg); CHECK_EQ(o.w.size(), (size_t)(2 * n_reg)); /* the four runs, read off the declaration: codes then scales, class by class, @@ -2247,18 +2292,12 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { int place = e; for (int x : pe) place -= x < e ? 1 : 0; CHECK(w.span_set); - if (ncls == 4) { - CHECK_EQ(w.span_lo, c4_lo[r][place % 4]); - CHECK_EQ(w.span_hi, c4_hi[r][place % 4]); - } else { - CHECK_EQ(w.span_lo, par_lo[r][place % 2]); - CHECK_EQ(w.span_hi, par_hi[r][place % 2]); - } + CHECK_EQ(w.span_lo, c4_lo[r][place % 4]); + CHECK_EQ(w.span_hi, c4_hi[r][place % 4]); ++seen; } CHECK_EQ(seen, (int)n_reg); - /* the plain experts' tiles: by narrow_place at two classes, by rank at four */ - const int64_t p2_lo[4] = { 384, 512, 0, 192 }, p2_hi[4] = { 512, 640, 192, 384 }; + /* the plain experts' tiles, by rank: 3, 3, 2, 2 */ const int64_t p4_lo[4] = { 0, 192, 384, 512 }, p4_hi[4] = { 192, 384, 512, 640 }; int pseen = 0; for (const RecWeight& w : bp.weights) { @@ -2266,8 +2305,8 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { if (w.name.find("_exps.") == std::string::npos) continue; if (w.name.compare(w.name.size() - 7, 7, ".weight") != 0) continue; CHECK(w.span_set); - CHECK_EQ(w.span_lo, ncls == 4 ? p4_lo[r] : p2_lo[r]); - CHECK_EQ(w.span_hi, ncls == 4 ? p4_hi[r] : p2_hi[r]); + CHECK_EQ(w.span_lo, p4_lo[r]); + CHECK_EQ(w.span_hi, p4_hi[r]); ++pseen; } CHECK_EQ(pseen, 2 * nprot); @@ -2289,7 +2328,7 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { * Ten tiles over four ranks is 3, 3, 2, 2: an UNEVEN share, still whole tiles, every tile owned * once. Ranks 0 and 1 compute 192 columns of every protected expert and ranks 2 and 3 compute * 128: the routed experts are split in four classes, so every rank holds the same routed - * width, and rank 2 holds the shared expert's extra block (narrow_place). Two protected + * width, and rank 2 holds the shared expert's extra block (shared_place). Two protected * experts, as the production recipe's pairs have it. */ { const RadEncoding w4p = [] { RadEncoding e = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128); diff --git a/tests/build_test.cpp b/tests/build_test.cpp index 9dfa1778..7e4b0320 100644 --- a/tests/build_test.cpp +++ b/tests/build_test.cpp @@ -486,6 +486,87 @@ TEST(no_schema_names_the_near_miss) { CHECK(has(b.errors().back(), "did you mean")); } +/* ================================================================== a weight list over its tables + * A table operand consumes a RUN of the declared weights, and the declaration decides which run: + * the fixed weight positions take one each, and the rest is divided over the table positions in + * declaration order, the first positions taking one more where it does not divide. That map + * (OpInfo::weight_opd) is what the layout pass, the converter and the issue path all read, so it + * is asserted whole. t_moe is one fixed weight (operand 1) and eight tables -- class pairs at + * operands 2/3, 5/6, 7/8 and 9/10 -- the way a four-class grouped GEMM lays its classes out. */ +namespace { + +/* `n` weights declared in a row under `tag`, and t_moe over them. */ +rad_op decl_moe(Builder& b, const char* tag, int n, std::vector* w) { + w->clear(); + for (int i = 0; i < n; ++i) + w->push_back(decl_w(b, (std::string(tag) + ".e" + std::to_string(i)).c_str(), 64, 64)); + const RadParam p[] = { RAD_INT("M", 8), RAD_INT("n", 64) }; + return b.decl_op("t_moe", p, 2, w->data(), (int)w->size()); +} + +/* The operand each declared weight went to, as runs: "1x1 2x3" is one weight at operand 1, then + * three at operand 2. */ +std::string runs(const OpInfo* o) { + std::string s; + for (size_t i = 0; i < o->weight_opd.size();) { + size_t j = i; + while (j < o->weight_opd.size() && o->weight_opd[j] == o->weight_opd[i]) ++j; + s += (s.empty() ? "" : " ") + std::to_string(o->weight_opd[i]) + "x" + + std::to_string(j - i); + i = j; + } + return s; +} + +} /* namespace */ + +TEST(a_weight_list_divides_over_its_tables_the_first_taking_the_remainder) { + NEED_PLUGIN(reg) + Builder b(reg, make_meta(), make_ctx()); + std::vector w; + + /* Ten experts' codes and scales behind the fixed weight: twenty entries over eight tables is + * two each and four left, so the first four positions -- classes 0 and 1, codes and scales -- + * hold three and the last four two. A four-class grouped GEMM over ten experts, whose first + * two classes are one expert longer. */ + rad_op h = decl_moe(b, "ten", 21, &w); + REQUIRE(h != RAD_NULL_HANDLE); + const OpInfo* o = b.program().op(h); + REQUIRE(o != nullptr); + CHECK_EQ(runs(o), std::string("1x1 2x3 3x3 5x3 6x3 7x2 8x2 9x2 10x2")); + /* The list is cut into runs in the order it was declared, not dealt out. */ + CHECK(o->weights == w); + + /* A list that divides is the plain equal division: sixteen entries, two a table. */ + h = decl_moe(b, "eight", 17, &w); + REQUIRE(h != RAD_NULL_HANDLE); + CHECK_EQ(runs(b.program().op(h)), std::string("1x1 2x2 3x2 5x2 6x2 7x2 8x2 9x2 10x2")); + + /* One entry a table is the least a declaration can give. */ + h = decl_moe(b, "four", 9, &w); + REQUIRE(h != RAD_NULL_HANDLE); + CHECK_EQ(runs(b.program().op(h)), std::string("1x1 2x1 3x1 5x1 6x1 7x1 8x1 9x1 10x1")); + CHECK_EQ((int)b.errors().size(), 0); +} + +TEST(a_weight_list_shorter_than_its_tables_is_refused_by_name) { + NEED_PLUGIN(reg) + Builder b(reg, make_meta(), make_ctx()); + std::vector w; + const size_t ops = b.program().ops.size(); + + /* Seven entries for eight tables leaves one empty, which no division can fill: refused at + * declare, with the counts that say so. */ + CHECK_EQ(decl_moe(b, "short", 8, &w), RAD_NULL_HANDLE); + CHECK_EQ(b.status(), RAD_E_SCHEMA); + REQUIRE(!b.errors().empty()); + CHECK(has(b.errors().back(), "op 't_moe': 8 weight operands declared")); + CHECK(has(b.errors().back(), "1 fixed weight operands and 8 weight TABLE operands")); + CHECK(has(b.errors().back(), "so 7 leaves a table empty")); + /* Nothing is recorded for the run phase to reach. */ + CHECK_EQ(b.program().ops.size(), ops); +} + /* ================================================================== misses, reported whole */ TEST(a_hole_in_the_range_is_reported_as_that_band) { NEED_PLUGIN(reg) diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 20ba2659..eded9b45 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -324,21 +324,27 @@ TEST(the_kv_cache_dtype_is_one_of_two_names) { CHECK_EQ(d.kv_cache_dtype, std::string("bf16")); } -TEST(the_ngram_table_is_on_disk_or_in_ram) { +/* THE TWO TABLE PLACEMENTS take the same four names and nothing else, default to auto, and leave + * the resolved values to Engine::plan: a parse never decides a tier. Where each table may go is + * the engine's to refuse, with the model in hand -- not the parser's. */ +TEST(the_table_placements_are_auto_vram_ram_or_disk) { Config d; CHECK_EQ(parse({}, &d), RAD_OK); - CHECK(!d.ngram_table_ram); + CHECK(d.embedding_placement == TablePlacement::Auto); + CHECK(d.ngram_placement == TablePlacement::Auto); Config c; - CHECK_EQ(parse({ "--ngram-table", "ram" }, &c), RAD_OK); - CHECK(c.ngram_table_ram); - CHECK_EQ(parse({ "--ngram-table", "disk" }, &c), RAD_OK); - CHECK(!c.ngram_table_ram); - /* 47.7 GiB of locked memory is the operator's to give, so a name this build does not know - * stops the server rather than picking either side. */ - CHECK_EQ(parse({ "--ngram-table", "memory" }, &c), RAD_E_INVAL); - CHECK_EQ(parse({ "--ngram-table", "RAM" }, &c), RAD_E_INVAL); - CHECK_EQ(parse({ "--ngram-table", "" }, &c), RAD_E_INVAL); - CHECK_EQ(parse({ "--ngram-table" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--embedding-placement", "ram", "--ngram-placement", "disk" }, &c), RAD_OK); + CHECK(c.embedding_placement == TablePlacement::Ram); + CHECK(c.ngram_placement == TablePlacement::Disk); + CHECK_EQ(parse({ "--embedding-placement", "vram", "--ngram-placement", "auto" }, &c), RAD_OK); + CHECK(c.embedding_placement == TablePlacement::Vram); + CHECK(c.ngram_placement == TablePlacement::Auto); + CHECK(c.embedding_resolved == TablePlacement::Vram); /* untouched until plan */ + for (const char* bad : { "RAM", "memory", "host", "" }) { + CHECK_EQ(parse({ "--embedding-placement", bad }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--ngram-placement", bad }, &c), RAD_E_INVAL); + } + CHECK_EQ(parse({ "--ngram-placement" }, &c), RAD_E_INVAL); } /* THE FLAG THAT DECIDES WHETHER MULTI-TURN WORKS. It is the WEIGHTS share, strictly inside @@ -814,7 +820,8 @@ TEST(usage_names_every_flag_it_documents) { CHECK(text.find("--checkpoint-policy") != std::string::npos); CHECK(text.find("--prefix-cache-host-mib") != std::string::npos); CHECK(text.find("--tp-wire") != std::string::npos); - CHECK(text.find("--ngram-table") != std::string::npos); + CHECK(text.find("--embedding-placement") != std::string::npos); + CHECK(text.find("--ngram-placement") != std::string::npos); CHECK(text.find("--kld-record") != std::string::npos); CHECK(text.find("--kld-ref") != std::string::npos); for (const char* f : { "--default-max-tokens", "--max-tokens-cap", "--presence-penalty", diff --git a/tests/format_test.cpp b/tests/format_test.cpp index 6c517688..d0c37fa2 100644 --- a/tests/format_test.cpp +++ b/tests/format_test.cpp @@ -8,6 +8,7 @@ */ #include "rad_test.h" #include "format/radfile.h" +#include "format/table_copy.h" #include "format/tunecache.h" #include "format/imatrix.h" #include "format/safetensors.h" @@ -426,6 +427,59 @@ TEST(fixed_stride_expert_addressing) { ::unlink(b.path.c_str()); } +/* --ngram-placement ram: A TABLE COPIED OUT OF THE CONTAINER INTO LOCKED MEMORY is the mapping's + * bytes, every one of them, at an address no file backs; and a copy read from the wrong file offset + * is refused by the check against the mapping rather than handed out. Small enough to lock under a + * default RLIMIT_MEMLOCK, and an odd size so the copy's 2 MiB rounding is exercised. */ +TEST(a_table_copied_into_locked_memory_is_the_mapping_byte_for_byte) { + const std::string p = tmp_path("tcopy"); + RadWriter w; + REQUIRE(w.begin(p.c_str()) >= 0); + w.set_arch("radtest"); + const RadWriter::Weight x = mkw("ngram.weight", plain_bf16(), 1500, 999, -1, -1, 0); + const Planes want = planes_of(x, 5); + REQUIRE(w.add_weight(x, want.ptr.data()) >= 0); + /* A weight after it, so a read shifted past the table's end is still inside the file. */ + const RadWriter::Weight y = mkw("tail.weight", plain_bf16(), 64, 64, -1, -1, 0); + const Planes ywant = planes_of(y, 6); + REQUIRE(w.add_weight(y, ywant.ptr.data()) >= 0); + REQUIRE(w.finish() >= 0); + + RadFile f; + REQUIRE(f.open(p.c_str()) >= 0); + const RadFileEntry* e = f.find("ngram.weight"); + REQUIRE(e != nullptr); + const RadFilePlane& pl = f.plane(*e, 0); + const uint8_t* src = f.data(pl); + const int64_t n = (int64_t)pl.bytes; + CHECK_EQ(n, (int64_t)1500 * 999 * 2); + + TableCopy c; + std::string why; + const int rc = table_copy_make(f, src, n, (int64_t)pl.offset, &c, &why); + if (rc == RAD_E_NOMEM && why.find("mlock2") != std::string::npos) { + std::fprintf(stderr, " SKIP %s: %s\n", ::radtest::current(), why.c_str()); + } else { + CHECK_OK(rc); + CHECK(c.base != nullptr && c.base != (const void*)src); + CHECK_EQ(c.bytes % ((size_t)2 << 20), (size_t)0); + CHECK(c.bytes >= (size_t)n); + if (c.base) CHECK(std::memcmp(c.base, src, (size_t)n) == 0); + table_copy_free(&c); + CHECK(c.base == nullptr); + + /* A sixteen-byte shift in the file offset reads real bytes from the wrong place. */ + TableCopy bad; + std::string bwhy; + CHECK_EQ(table_copy_make(f, src, n, (int64_t)pl.offset + 16, &bad, &bwhy), (int)RAD_E_IO); + CHECK(bad.base == nullptr); + CHECK(bwhy.find("does not match") != std::string::npos); + } + table_copy_free(&c); /* a copy never made, or freed already: a no-op */ + f.close(); + ::unlink(p.c_str()); +} + /* ------------------------------------------------------------------ reserving and writing */ TEST(a_weight_is_written_in_pieces_in_any_order) { const std::string p = tmp_path("pieces"); diff --git a/tests/place_test.cpp b/tests/place_test.cpp index 9e1c6fb8..1b88b4b9 100644 --- a/tests/place_test.cpp +++ b/tests/place_test.cpp @@ -2237,7 +2237,7 @@ TEST(the_weight_footprint_splits_statics_from_the_elastic_expert_plane) { build_moe(f, /*n=*/4, /*each=*/2 * MiB, &experts); WeightFootprint fp; - weight_footprint(f.prog, &fp); + weight_footprint(f.prog, &fp, TablePlacement::Vram); /* One model-level weight and four experts: five units. */ CHECK_EQ(fp.n_units, 5ll); @@ -2267,7 +2267,7 @@ TEST(weights_in_one_layer_are_one_unit_and_are_aligned_once_each) { } WeightFootprint fp; - weight_footprint(f.prog, &fp); + weight_footprint(f.prog, &fp, TablePlacement::Vram); CHECK_EQ(fp.n_units, 2ll); /* the declared group is the unit, not the weight */ /* ONE align_up A UNIT AND ONE INSIDE IT, which is how Mover::init spends the slab. A budget @@ -2300,16 +2300,16 @@ TEST(a_weight_with_no_device_band_takes_its_whole_unit_to_the_mapped_tier) { f.prog.ops.push_back(host_only); WeightFootprint fp; - weight_footprint(f.prog, &fp); + weight_footprint(f.prog, &fp, TablePlacement::Vram); CHECK_EQ(fp.n_units, 1ll); CHECK_EQ(fp.statics, 0ll); CHECK_EQ(fp.mapped, 6 * MiB); /* both weights: the unit is what moves */ } -/* --host-weights. The fixture's embedding is read by an `embed_lookup`, as every arch declares it: - * that is the only reader the flag accepts. */ -void build_dense_lookup(Fixture& f, int layers, int64_t per_layer) { - const rad_weight m = f.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1); +/* --embedding-placement. The fixture's embedding is read by an `embed_lookup`, as every arch + * declares it, and its head by a GEMM: the first is the table the flag moves, the second never. */ +void build_dense_lookup(Fixture& f, int layers, int64_t per_layer, int64_t emb = 1 * MiB) { + const rad_weight m = f.weight("token_embd.weight", emb, RAD_ACCESS_VOCAB, -1, -1); f.op("embed_lookup", {m}, false); for (int l = 0; l < layers; ++l) { const rad_weight w = f.weight("blk." + std::to_string(l) + ".ffn_down.weight", per_layer, @@ -2320,39 +2320,72 @@ void build_dense_lookup(Fixture& f, int layers, int64_t per_layer) { f.op("logits_gemm", {o}, false); } -/* A HOSTED WEIGHT IS IN THE HOST POOL, NOT ON THE CARD, and the footprint has to say so: the - * resolver sizes a derived weight budget from `statics`, so a hosted weight counted there would - * reserve VRAM the planner never spends. */ -TEST(host_weights_leave_the_statics_for_the_hosted_bucket) { +/* An n-gram table: model-level, read only by `embed_lookup_q`, which only a host kernel serves. */ +rad_weight add_ngram_table(Fixture& f, int64_t bytes) { + const rad_weight t = f.weight("ngram.weight", bytes, RAD_ACCESS_VOCAB, -1, -1); + OpInfo o; + o.op = "embed_lookup_q"; + o.index = (int32_t)f.prog.ops.size(); + o.weights = { t }; + Band hb; + hb.hi = 1 << 20; + hb.dom[RAD_DOMAIN_HOST].row = &g_host_row; + hb.miss[RAD_DOMAIN_DEVICE] = "no device kernel"; + o.bands.push_back(hb); + f.prog.ops.push_back(o); + return t; +} + +/* THE TABLES ARE FOUND BY WHAT READS THEM. A model-level weight only embed_lookup reads is the + * embedding; one only embed_lookup_q reads is an n-gram table; a head a GEMM reads is neither, and + * neither is a table a GEMM reads beside the lookup -- a tied head would stream whole over the + * link every step. Placed in RAM the embedding leaves the statics for the hosted bucket, because + * the resolver sizes a derived weight budget from the statics. */ +TEST(the_placement_flags_find_their_tables_by_what_reads_them) { Fixture f; build_dense_lookup(f, /*layers=*/2, /*per_layer=*/4 * MiB); + add_ngram_table(f, 8 * MiB); WeightFootprint fp; - weight_footprint(f.prog, &fp, {"token_embd.weight"}); + weight_footprint(f.prog, &fp, TablePlacement::Vram); + CHECK_EQ(fp.embedding, 1 * MiB); + CHECK_EQ(fp.ngram, 8 * MiB); + CHECK(!fp.ngram_device); + CHECK_EQ(fp.hosted, 0ll); + CHECK_EQ(fp.statics, 2 * 4 * MiB + 2 * MiB); + CHECK_EQ(fp.mapped, 8 * MiB); + + weight_footprint(f.prog, &fp, TablePlacement::Ram); + CHECK_EQ(fp.embedding, 1 * MiB); CHECK_EQ(fp.hosted, 1 * MiB); CHECK_EQ(fp.statics, 2 * 4 * MiB + 1 * MiB); - weight_footprint(f.prog, &fp, {"token_*"}); /* a trailing '*' is a prefix */ - CHECK_EQ(fp.hosted, 1 * MiB); + CHECK(is_embedding_table(f.prog, 1)); + CHECK(!is_embedding_table(f.prog, 2)); /* a layer's GEMM operand */ + CHECK(!is_embedding_table(f.prog, 4)); /* the head */ + CHECK(is_ngram_table(f.prog, 5)); + CHECK(!is_ngram_table(f.prog, 1)); - /* NEITHER A LAYER WEIGHT NOR A GEMM'S: layers belong to the offload strategies, and a GEMM - operand would stream every step. */ - weight_footprint(f.prog, &fp, {"blk.*", "output.weight"}); + /* A head tied to the table: the same weight read by the lookup and the logits GEMM. */ + Fixture t; + const rad_weight m = t.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1); + t.op("embed_lookup", {m}, false); + t.op("logits_gemm", {m}, false); + CHECK(!is_embedding_table(t.prog, m)); + weight_footprint(t.prog, &fp, TablePlacement::Ram); + CHECK_EQ(fp.embedding, 0ll); CHECK_EQ(fp.hosted, 0ll); - - weight_footprint(f.prog, &fp); /* and none named is none hosted */ - CHECK_EQ(fp.hosted, 0ll); - CHECK_EQ(fp.statics, 2 * 4 * MiB + 2 * MiB); } -TEST(host_weights_go_to_the_pinned_pool_read_in_place_and_cost_no_vram) { +TEST(embedding_ram_goes_to_the_pinned_pool_read_in_place_and_costs_no_vram) { Fixture f; build_dense_lookup(f, /*layers=*/2, /*per_layer=*/4 * MiB); Config cfg = base_config(); cfg.placement = "all_vram"; cfg.vram_weights_mib = 9; /* layers and the head exactly: not the embedding */ cfg.host_pool_mib = 2; - cfg.host_weights = {"token_embd.weight"}; + cfg.embedding_placement = TablePlacement::Ram; + cfg.embedding_resolved = TablePlacement::Ram; Plan plan; PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0}; CHECK_OK(Planner(in).plan(&plan)); @@ -2361,31 +2394,69 @@ TEST(host_weights_go_to_the_pinned_pool_read_in_place_and_cost_no_vram) { CHECK(plan.weight[emb].tier == Tier::HostPinned); CHECK(plan.weight[emb].site == Site::DeviceZeroCopy); CHECK(!plan.units[(size_t)plan.weight[emb].unit].movable); - CHECK_EQ(plan.host_weights_bytes, 1 * MiB); + CHECK_EQ(plan.embedding_host_bytes, 1 * MiB); for (rad_weight w = 2; (size_t)w < f.prog.weights.size(); ++w) CHECK(plan.weight[w].tier == Tier::VRAM); + + /* Vram, the default, leaves it with the other weights. */ + cfg.embedding_resolved = TablePlacement::Vram; + cfg.vram_weights_mib = 10; + Plan plan2; + CHECK_OK(Planner(in).plan(&plan2)); + CHECK(plan2.weight[emb].tier == Tier::VRAM); + CHECK_EQ(plan2.embedding_host_bytes, 0ll); } -TEST(host_weights_that_a_gemm_reads_are_refused) { +/* A TABLE THAT IS NOT A WHOLE NUMBER OF PAGES still leaves the report's pinned total at what the + * pooled units use: the pool slot is charged rounded up and the tier total counts weight bytes, so + * the report subtracts the same weight bytes it added. */ +TEST(the_report_counts_a_hosted_embedding_once_in_one_unit) { Fixture f; - build_dense_lookup(f, /*layers=*/1, /*per_layer=*/4 * MiB); + build_dense_lookup(f, /*layers=*/1, /*per_layer=*/4 * MiB, /*emb=*/3 * MiB + 100); + Config cfg = base_config(); + cfg.placement = "all_vram"; + cfg.host_pool_mib = 8; + cfg.embedding_resolved = TablePlacement::Ram; + Plan plan; + PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0}; + CHECK_OK(Planner(in).plan(&plan)); + CHECK_EQ(plan.embedding_host_used, 3 * MiB + 100); + CHECK(plan.embedding_host_bytes >= plan.embedding_host_used); + const std::string r = plan.report(f.prog); + const size_t at = r.find("host pinned"); + CHECK(at != std::string::npos); + if (at != std::string::npos) { + const std::string line = r.substr(at, r.find('\n', at) - at); + CHECK(line.find('-') == std::string::npos); /* no negative total */ + } + CHECK(r.find("--embedding-placement ram") != std::string::npos); +} + +/* A plan resolved to Ram for a program with no table only embed_lookup reads is a budget split + * for a different program; it refuses rather than leave the table on a card split without it. */ +TEST(embedding_ram_with_no_table_to_place_is_refused) { + Fixture t; + const rad_weight m = t.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1); + t.op("embed_lookup", {m}, false); + t.op("logits_gemm", {m}, false); Config cfg = base_config(); cfg.placement = "all_vram"; cfg.host_pool_mib = 4; - cfg.host_weights = {"output.weight"}; + cfg.embedding_resolved = TablePlacement::Ram; Plan plan; - PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0}; - CHECK_EQ(Planner(in).plan(&plan), RAD_E_INVAL); + PlannerInput in{&t.prog, &cfg, 0, 1, nullptr, 0}; + CHECK_EQ(Planner(in).plan(&plan), RAD_E_STATE); CHECK(!plan.notes.empty()); + CHECK(plan.weight[m].tier == Tier::VRAM); } -TEST(host_weights_that_do_not_fit_the_host_pool_are_refused_with_the_plan_filled_in) { +TEST(embedding_ram_that_does_not_fit_the_host_pool_is_refused_with_the_plan_filled_in) { Fixture f; build_dense_lookup(f, /*layers=*/1, /*per_layer=*/4 * MiB); Config cfg = base_config(); cfg.placement = "all_vram"; cfg.host_pool_mib = 0; /* nowhere to put it */ - cfg.host_weights = {"token_embd.weight"}; + cfg.embedding_resolved = TablePlacement::Ram; Plan plan; PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0}; CHECK_EQ(Planner(in).plan(&plan), RAD_E_NOMEM); @@ -2393,16 +2464,42 @@ TEST(host_weights_that_do_not_fit_the_host_pool_are_refused_with_the_plan_filled CHECK(!plan.notes.empty()); } +/* --ngram-placement ram leaves the table on the mapped tier, which no pool counts, and names the + * copy the load phase makes: its reason says where the rows will come from, and the report what + * the copy costs in RAM. */ +TEST(ngram_ram_stays_mapped_and_reports_the_copy) { + Fixture f; + build_dense_lookup(f, /*layers=*/1, /*per_layer=*/4 * MiB); + const rad_weight t = add_ngram_table(f, 8 * MiB); + Config cfg = base_config(); + cfg.placement = "all_vram"; + cfg.ngram_resolved = TablePlacement::Ram; + Plan plan; + PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0}; + CHECK_OK(Planner(in).plan(&plan)); + CHECK(plan.weight[t].tier == Tier::Mapped); + CHECK(plan.weight[t].site == Site::Host); + CHECK_EQ(plan.ngram_copy_bytes, 8 * MiB); + CHECK(std::string(plan.weight[t].reason).find("--ngram-placement ram") != std::string::npos); + CHECK(plan.report(f.prog).find("n-gram copy") != std::string::npos); + + cfg.ngram_resolved = TablePlacement::Disk; + Plan plan2; + CHECK_OK(Planner(in).plan(&plan2)); + CHECK_EQ(plan2.ngram_copy_bytes, 0ll); + CHECK(plan2.report(f.prog).find("n-gram copy") == std::string::npos); +} + TEST(an_empty_program_has_an_empty_footprint) { Fixture f; WeightFootprint fp; fp.statics = 1; /* and the out parameter is reset, not accumulated */ - weight_footprint(f.prog, &fp); + weight_footprint(f.prog, &fp, TablePlacement::Vram); CHECK_EQ(fp.statics, 0ll); CHECK_EQ(fp.experts, 0ll); CHECK_EQ(fp.mapped, 0ll); CHECK_EQ(fp.n_units, 0ll); - weight_footprint(f.prog, nullptr); /* and a null one is not a crash */ + weight_footprint(f.prog, nullptr, TablePlacement::Vram); /* and a null one is not a crash */ } RAD_TEST_MAIN() diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 19ac7f86..02cfee3b 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -119,8 +119,8 @@ TEST(loading_reads_identity_and_calls_open) { if (!base) return; CHECK_EQ((int)base->kind, RAD_PLUGIN_KERNEL); CHECK_EQ(base->version, "0.1"); - CHECK_EQ(base->n_kernels, 16); - CHECK_EQ(base->n_schemas, 9); + CHECK_EQ(base->n_kernels, 17); + CHECK_EQ(base->n_schemas, 10); /* The optional open hook runs once, after load and before any selection. */ auto open_calls = reinterpret_cast(dlsym(base->handle, "radtest_open_calls")); @@ -286,7 +286,7 @@ TEST(every_row_s_op_has_a_schema) { CHECK_OK(load(r)); CHECK_OK(r.check_complete()); const auto ops = r.op_names(); - CHECK_EQ(ops.size(), (size_t)9); + CHECK_EQ(ops.size(), (size_t)10); CHECK_EQ(ops[0], "t_attn"); } @@ -881,4 +881,59 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) { } } +/* THE FOUR-RANK FUSED WRITES SERVE THE EXACT WIRE ONLY, AND SAY SO IN SELECTION. A caller states + * `wire` 0 for the exact form and gets the four-rank rows; a request for the rotated wire at four + * ranks is a miss that names `wire`, so the caller keeps its unfused pair -- not a row that + * matches and then refuses its instance, which would stop declare. At two ranks both wires keep + * their row. Geometry is Qwen3.8-Flash-Next's: 2560 wide, four streams, top-k 10, declared over a + * decode or verify step of 8 sequences at depth 3. */ +TEST(libr4d_resolves_the_four_rank_fused_writes_on_the_exact_wire_only) { + const std::string so = home() + "/kernels/libr4d.so"; + if (access(so.c_str(), R_OK) != 0) { + fprintf(stderr, " SKIP %s: no %s (a build without HIP)\n", ::radtest::current(), + so.c_str()); + return; + } + Registry r; + CHECK(r.load_plugin(so, 0) >= 0); + r.set_device_fact(RAD_FACT_P2P, 1); + + const int64_t rows = 8 * (1 + 3); + auto bands = [&](const std::string& op, int world, int wire) { + Geometry g; + g.set_i("n", 2560); + g.set_i("hc", 4); + g.set_i("world_size", world); + g.set_s("dtype", "bf16"); + g.set_i("wire", wire); + if (op == "ar_gather_hc_write") { + g.set_i("top_k", 10); + g.set_s("act", "sigmoid"); + } + return r.build_bands(op, "M", 1, rows, g); + }; + auto names = [](const std::vector& b) { + std::string s; + for (const Band& x : b) + s += fmt("%lld:%s ", (long long)x.hi, picked(x.dom[RAD_DOMAIN_DEVICE].row).c_str()); + return s; + }; + + CHECK_EQ(names(bands("ar_hc_write", 4, 0)), "32:ar_hc_write_4rank "); + CHECK_EQ(names(bands("ar_gather_hc_write", 4, 0)), "32:ar_gather_hc_write_4rank "); + for (int wire : { 0, 6 }) { + CHECK_EQ(names(bands("ar_hc_write", 2, wire)), "32:ar_hc_write "); + CHECK_EQ(names(bands("ar_gather_hc_write", 2, wire)), "32:ar_gather_hc_write "); + } + + for (const char* op : { "ar_hc_write", "ar_gather_hc_write" }) { + const std::vector none = bands(op, 4, 6); + CHECK(!none.empty()); + for (const Band& b : none) { + CHECK(!b.dom[RAD_DOMAIN_DEVICE]); + CHECK(has(b.miss[RAD_DOMAIN_DEVICE], "wire")); + } + } +} + RAD_TEST_MAIN() diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index cd558d79..e2674310 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -2072,6 +2072,28 @@ TEST(op_moe_gemm_q_scale_grid_by_dtype) { CHECK_EQ(y.at(0), 160.0f); /* 0.5 * (64*1*2 + 64*1*3) */ CHECK_EQ(y.at(1), 320.0f); /* 0.5 * (64*2*2 + 64*2*3) */ } + + /* A dtype that names none of those grids -- a format of another op, or no dtype at all -- is + * declined for every operand, the scale planes and the rest: a plane sized on a guessed grid + * is a tensor of the wrong extent. */ + for (const char* op : { "moe_gemm_q", "moe_gemm_q_mod4" }) { + const RadKernelInfo* k = kern(op); + REQUIRE(k != nullptr && k->opd_shape != nullptr); + for (const char* dt : { "w8a8", "mxfp4a8", "" }) { + A a; + a.i("M", 2).i("N", 256).i("K", 512).i("n_expert", 8).i("top_k", 2).i("group", 128) + .s("a_order", "token"); + if (*dt) a.s("dtype", dt); + const RadArgs* r = a.get(); + for (int opd : { 0, 2, 3 }) { + RadOpdDesc d{}; + if (k->opd_shape(r->p, r->n_p, opd, &d) != RAD_E_UNSUPPORTED) + std::fprintf(stderr, " %s at dtype '%s': operand %d described\n", op, dt, + opd); + CHECK_EQ(k->opd_shape(r->p, r->n_p, opd, &d), RAD_E_UNSUPPORTED); + } + } + } } TEST(op_moe_chain) { diff --git a/tests/runtime_test.cpp b/tests/runtime_test.cpp index dd206959..e1818715 100644 --- a/tests/runtime_test.cpp +++ b/tests/runtime_test.cpp @@ -667,6 +667,72 @@ TEST(a_weight_table_resolves_only_the_entries_that_moved) { CHECK_EQ(res.lookups, before + 4); } +/* A TABLE'S RUN IS THE DECLARATION'S. The weights declared at a table position (OpInfo:: + * weight_opd) are bound as one table before the first step. A declared run with a gap in it is + * refused there -- the kernel is handed one base and strides through it, so a gap is a wrong + * expert read -- and an issue naming any other run than the bound one is refused at issue, by + * name, rather than handed a table of other experts. */ +TEST(a_weight_table_issued_against_its_declaration_is_refused) { + static const RadOperandSpec opds[] = { + { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_WTAB, 0 }, { "y", RAD_OPD_OUT, 0 }, + }; + static const RadOpSchema schema = { + "moe_gemm", g_gemm_params, 4, opds, 3, "A[M,K] x B[e][N,K]^T -> Y[M,N]" + }; + static uint16_t expert_bytes[4][32]; + auto experts = [](Fixture& f) { + std::vector w; + for (int e = 0; e < 4; ++e) + w.push_back(f.add_weight(("blk.0.e" + std::to_string(e)).c_str(), RAD_BF16, 8, 4, + expert_bytes[e])); + return w; + }; + + { + /* Experts 0, 1 and 3 at the table, 2 missing from the run: refused when the tables are + * bound, so the Ctx never runs a step. */ + Fixture f; + const std::vector w = experts(f); + f.add_buffer("x", RAD_BF16, 64, 4, 0); + f.add_buffer("y", RAD_BF16, 64, 8, 1024); + rad_op op = f.add_op("moe_gemm", "M", { 8192 }, { k_pre }, { "prefill" }, &schema, + { w[0], w[1], w[3] }); + f.P.ops[op].weight_opd = { 1, 1, 1 }; + CHECK_EQ(f.start(), RAD_E_INVAL); + } + + Fixture f; + const std::vector w = experts(f); + rad_buf x = f.add_buffer("x", RAD_BF16, 64, 4, 0); + rad_buf y = f.add_buffer("y", RAD_BF16, 64, 8, 1024); + rad_op op = f.add_op("moe_gemm", "M", { 8192 }, { k_pre }, { "prefill" }, &schema, w); + f.P.ops[op].weight_opd = { 1, 1, 1, 1 }; + CHECK_OK(f.start()); + + /* The declared run is served. */ + g_rec.clear(); + CHECK_OK(f.step(4, 0, [&](Ctx& c) { + RadOperand opd[3] = { RAD_B(x), RAD_WTAB(w[0], 4), RAD_B(y) }; + CHECK_OK(c.issue(op, opd, 3, RAD_N_BATCH)); + })); + CHECK_EQ(g_rec.size(), (size_t)1); + + /* One entry short, and the same length one expert along: both name experts the declaration + * did not put at this table, and neither reaches the kernel. */ + int step_no = 1; + for (const RadOperand tab : { RAD_WTAB(w[0], 3), RAD_WTAB(w[1], 3) }) { + g_rec.clear(); + const int s = f.step(4, step_no++, [&](Ctx& c) { + RadOperand opd[3] = { RAD_B(x), tab, RAD_B(y) }; + c.issue(op, opd, 3, RAD_N_BATCH); + }); + CHECK_EQ(s, RAD_E_INVAL); + CHECK_EQ(g_rec.size(), (size_t)0); + CHECK(std::strstr(f.ctx.step_error(), "A table's run is fixed by the declaration") != + nullptr); + } +} + /* Routing never blocks the compute stream: the histogram is copied back asynchronously and the * heat engine DRAINS it on a later step (spec §5.5). */ TEST(route_report_is_asynchronous_and_drains_oldest_first) {