diff --git a/CMakeLists.txt b/CMakeLists.txt index 5906cc04..48da6d79 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.4.0 LANGUAGES C CXX) +project(radiance VERSION 1.5.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/NOTICE b/NOTICE index 7f3b0765..a0429270 100644 --- a/NOTICE +++ b/NOTICE @@ -19,10 +19,14 @@ the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of the th crash, cardclock.py, --busy-prefill-chunk, and curl, jq and a CA bundle in the image with hfget.sh under its busybox), hazyumps (static YaRN for the Qwen rotary paths), malic (ParoQuant: its MXFP4, int5 and int4 checkpoints imported and served, the Givens rotation as stages and as dense per-group -matrices on the matrix cores, and the 5- and 4-bit asymmetric GEMMs), redxherring (--model taking a -Hugging Face repo id), sfjes (Gemma 4 31B dense: its plugin, its two attention classes and their -kernels, and prefix reuse that leaves a windowed group alone) and zivius (LiquidAI's LFM2 and -LFM2-VL and d1's /v1/systemone, after the design of their Codeberg PR 50). +matrices on the matrix cores, and the 5- and 4-bit asymmetric GEMMs), Perire (Gemma 4 26B-A4B with +z-lab's DFlash drafter: its plugin, its kernels in libr4d -- the windowed paged attention, +pair_argmax, the fused sandwich joins and expert_scale -- and the host emulator that tests them, the +prefill split into two slices with their all-reduces beside the compute, and the vocabulary-sharded +draft head), redxherring (--model taking a Hugging Face repo id), sfjes (Gemma 4 31B dense: its +plugin, its two attention classes and their kernels, and prefix reuse that leaves a windowed group +alone) and zivius (LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their +Codeberg PR 50). 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 c6898613..1a939c3b 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ If you wish to support the developement of the radiance engine you can do so [he | MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` | | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` | | Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | +| Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` | | Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` | | Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` | | EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` | @@ -43,6 +44,13 @@ with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkp that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's, and its drafts are accepted a little less often (0.46 against 0.50 of them on prose). +The ParoQuant containers keep the trunk exactly as the ParoQuant releases ship it, with the learned +Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, int5 from +`Launch80/Qwen3.8-27B-PARO-int5` and MXFP4 from `MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2`, each with +`data/recipes/q38-27b-paro-mxfp4-df2.recipe` and the DFlash2 drafter. A ParoQuant container made +before 1.5.0 is refused at startup. Convert it again and pass the old one as `--reuse` to copy every +tensor that did not change. + ## Run with Docker The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The @@ -55,7 +63,7 @@ model from one of them: docker pull stilldeadcode/radiance git clone https://codeberg.org/StillDeadcode/radiance.git cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose -cp .env.example .env # set RADIANCE_MODELS, RADIANCE_STATE, RADIANCE_API_KEY, the GIDs +cp .env.example .env # set RADIANCE_MODELS, RADIANCE_API_KEY, the GIDs docker compose -f minicpm5-2b.yaml up -d # or any file from the table docker compose -f minicpm5-2b.yaml logs -f docker compose -f minicpm5-2b.yaml down @@ -133,9 +141,10 @@ odd block alternates with the parity, so every rank's share is whole blocks and exactly one owner — and the resident expert bytes per rank are smaller, so the elastic window is a different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before trusting it. **`--host-pool-mib` is pinned on every card**, so the row -above pins 4 × 12 GiB = 48 GiB, and the amdgpu driver caps pinned memory at `ttm.pages_limit`, half -of RAM by default: that row needs 96 GiB of RAM or a raised limit -([`docs/GUIDE.md`](docs/GUIDE.md) §7). +above pins 4 × 12 GiB = 48 GiB of RAM that nothing else can use and the kernel cannot swap out. The +amdgpu driver caps what every process together pins at the machine's RAM less 1/64 and 1.5 GiB; the +pool is locked user memory, which `ttm.pages_limit` does not count. A 64 GiB machine serves +`flashnext-tp1.yaml` with 49 GiB pinned ([`docs/GUIDE.md`](docs/GUIDE.md) §7). Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). Add `--debug-graph` to print every op and the kernel it resolved to, then exit without serving. Then: @@ -161,6 +170,9 @@ build/bin/rad-convert ~/models/google/gemma-4-31B-it -o gemma4-31b-w4a8.rad \ --recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \ --set quantization_config.quant_method=compressed-tensors \ --draft-model ~/models/google/gemma-4-31B-it-assistant +build/bin/rad-convert ~/models/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \ + --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \ + --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 ``` With Docker, use `docker run --rm -v ~/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`. In diff --git a/abi/rad_builder.h b/abi/rad_builder.h index a2efb946..d07e5d34 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -404,6 +404,13 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g); * becomes one only if the plugin issues it. */ int rad_op_resolved(RadBuilder* b, rad_op h); +/* Does a loaded kernel library declare op `op` -- is it in the vocabulary at all? Declaring an op + * nobody declares is an error, because that is what a misspelt name looks like; an op that is + * declared and only resolved to no kernel is not (rad_op_resolved). A plugin asks this first for a + * fused op that only an optional library defines, and emits the chain when the answer is 0. + * Additive export. */ +int rad_op_declared(RadBuilder* b, const char* op); + /* ================================================================== checkpoint name map */ /* The plugin owns the map from checkpoint tensor names to declared weight names, including * convert-time fusions -- q/k/v into a single qkv, gate and up into gate_up. It is the only diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index d7e21973..811feee4 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -1108,24 +1108,25 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL; } - /* ---- A ROTATED 5-BIT (or plain asymmetric 4-bit) WEIGHT (ParoQuant int5; z-lab's int4): its input's bf16 plane rotated into this linear's - * own f16 planes, then the w5a16 GEMM. Two views of one stored weight: the codes, and the - * (scale, zero) pair as `b_scale`. */ + /* ---- A ROTATED 5-BIT OR ASYMMETRIC 4-BIT WEIGHT (ParoQuant int5; z-lab's int4): its input's + * bf16 plane rotated into this linear's own f16 planes, then the w5a16 GEMM. Two views of one + * stored weight: the codes, and the (scale, zero) pair as `b_scale`. */ paro5 = known && linear_is_paro_w5(enc); if (paro5) { + const int bits = enc.plane[0].dtype == RAD_U4 ? 4 : 5; if (!a.x) { - fprintf(stderr, "radiance: '%s' is a rotated 5-bit weight, rotated from its input's bf16 " - "plane, and its input has none\n", wn); + fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight, rotated from its input's " + "bf16 plane, and its input has none\n", wn, bits); return RAD_E_DTYPE; } if (g.world > 1 || span_hi > 0) { - fprintf(stderr, "radiance: '%s' is a rotated 5-bit weight; its rotation is not cut by a " - "tensor-parallel shard (world %d)\n", wn, g.world); + fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight; its rotation is not cut by " + "a tensor-parallel shard (world %d)\n", wn, bits, g.world); return RAD_E_UNSUPPORTED; } if (N % 16 || K % RAD_FP8_BLOCK) { - fprintf(stderr, "radiance: '%s' is %lldx%lld; a 5-bit weight takes rows in 16s and K in " - "whole 128s\n", base, (long long)N, (long long)K); + fprintf(stderr, "radiance: '%s' is %lldx%lld; a %d-bit weight takes rows in 16s and K " + "in whole 128s\n", base, (long long)N, (long long)K, bits); return RAD_E_INVAL; } std::vector cut; diff --git a/arch/gemma4_bf16/gemma4_chat_format.h b/arch/common/rad_gemma4_chat.h similarity index 81% rename from arch/gemma4_bf16/gemma4_chat_format.h rename to arch/common/rad_gemma4_chat.h index 7520d298..74dc4ae7 100644 --- a/arch/gemma4_bf16/gemma4_chat_format.h +++ b/arch/common/rad_gemma4_chat.h @@ -1,4 +1,4 @@ -/* gemma4_chat_format.h -- how Gemma 4 spells a turn: its reasoning and its tool calls, as data. +/* rad_gemma4_chat.h -- how Gemma 4 spells a turn: its reasoning and its tool calls, as data. * * The chat template is one llama.cpp reads with a hand-written handler, so the template analysis * finds nothing in it, and the engine would serve the model with no reasoning split and refuse @@ -16,14 +16,17 @@ * the answer, and a lone . `reasoning_anywhere` reads the first as reasoning and drops * the second, so neither reaches the content. * - * Kept in a header of its own so the reply-format tests read the declaration the plugin exports - * rather than a copy of it. */ + * Here rather than in one plugin because two plugins serve Gemma 4 -- arch/gemma4 (bf16 and fp8 + * experts) and arch/gemma4_bf16 (the CT-INT4 dense release) -- and the format is the model's, not + * the weights'. One declaration, so the two cannot drift apart, and so the reply-format tests read + * the declaration the plugins export rather than a copy of it. */ #pragma once #include "rad_builder.h" -namespace gemma4_bf16 { +namespace rad { +namespace arch { -inline const RadChatFormat* chat_format_decl() { +inline const RadChatFormat* gemma4_chat_format() { static const char* const kBreaks[] = { "<|tool_call>" }; static const char* const kTriggers[] = { "<|tool_call>" }; static const RadChatFormat f = [] { @@ -57,4 +60,5 @@ inline const RadChatFormat* chat_format_decl() { return &f; } -} /* namespace gemma4_bf16 */ +} /* namespace arch */ +} /* namespace rad */ diff --git a/arch/gemma4/CMakeLists.txt b/arch/gemma4/CMakeLists.txt new file mode 100644 index 00000000..54e911f6 --- /dev/null +++ b/arch/gemma4/CMakeLists.txt @@ -0,0 +1,14 @@ +# gemma4 -- the architecture plugin for Gemma 4's text model (Gemma4ForConditionalGeneration / +# Gemma4ForCausalLM; the 26B-A4B MoE and the dense sizes without per-layer embeddings), with a +# z-lab DFlash drafter merged at convert time. +# +# Built inside radiance's tree (arch/ discovers it) or on its own against an installed radiance: +# cmake -S arch/gemma4 -B build-gemma4 -DCMAKE_PREFIX_PATH=/opt/radiance && cmake --build build-gemma4 +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(gemma4 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(gemma4 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma4.cpp) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp new file mode 100644 index 00000000..dfd173da --- /dev/null +++ b/arch/gemma4/gemma4.cpp @@ -0,0 +1,2021 @@ +/* gemma4 -- Gemma 4 text decoders (26B-A4B MoE, and the dense members of the family): a bf16 + * trunk, routed experts bf16 or block fp8 (see FP8 EXPERTS), and the DFlash block-diffusion + * drafter. + * + * ============================== THE SHAPE (gemma-4-26B-A4B-it) ============================== + * + * 30 layers, hidden 2816, vocab 262144 (tied to the embedding), rms_norm_eps 1e-6 + * layer_types: five `sliding_attention` then one `full_attention`, five times over + * sliding: 16 heads / 8 KV heads x 256, rope theta 1e4 over the whole head, window 1024 + * full: 16 heads / 2 KV heads x 512, PROPORTIONAL rope theta 1e6 over a quarter of it, + * and K IS V (`attention_k_eq_v`): there is no v_proj, V is the k projection before + * its norm and its rotary + * attention scale 1.0 -- the q/k norms carry the temperature; q and k RMS-normed per head with a + * gain, v with none + * Gemma's sandwich norms, plain gains (x_hat * w, not 1 + w) + * the feed-forward is TWO ARMS BESIDE EACH OTHER, both reading the same residual: + * dense pre_feedforward_layernorm -> gate|up 2112 (gelu-tanh) -> down + * -> post_feedforward_layernorm_1 + * routed router over rmsnorm(x) * scale * hidden^-0.5 -> softmax -> top 8 of 128 -> + * renormalised -> times per_expert_scale[expert]; + * pre_feedforward_layernorm_2 -> 128 experts of 704 (gelu-tanh) -> + * post_feedforward_layernorm_2 + * sum -> post_feedforward_layernorm -> residual add + * layer_scalar multiplies the residual stream at the end of every layer + * embedding scaled by sqrt(hidden) AS A bf16 (53.0, not 53.066); final norm; tied lm_head; + * final_logit_softcapping 30 + * + * The reference is transformers' modeling_gemma4 (Gemma4TextDecoderLayer, Gemma4TextAttention, + * Gemma4TextRouter, _compute_proportional_rope_parameters), read at 5.19. + * + * ============================== THE READINGS THAT STAY PLAUSIBLE WHEN WRONG ============================== + * + * PROPORTIONAL ROPE IS NOT A PARTIAL ROTARY. It rotates the first 64 frequency PAIRS of a + * 512-wide head at theta^(-2j/512) -- the exponent divides by the HEAD, and pair j is channels + * (j, j + 256) -- and leaves the other 192 pairs at frequency zero. `rope` with rotary_dim 128 + * would pair (j, j + 64) at theta^(-2j/128), which is a different function that still produces + * fluent text. It is declared here as a full-width NeoX rotary whose frequencies past pair 63 + * are divided by 1e30 -- the YaRN blend `rope` already carries, with the ramp a step at 63.5..64 + * -- which evaluates to exactly the reference's angles below the step and to cos 1, sin ~1e-31 + * above it. See decl_full_rope(). + * + * V ON A FULL LAYER IS THE UN-NORMED, UN-ROTATED K PROJECTION, RMS-normed with a unit gain. So + * the value norm reads `k` BEFORE the key norm writes it, which is the issue order below. + * + * THE ROUTER DOES NOT READ THE FEED-FORWARD'S INPUT. It reads the residual stream through a + * GAINLESS norm, times its own `scale` vector, times hidden^-0.5 -- one `rmsnorm` with `scale` + * as the gain and `mult` the constant -- while the experts read pre_feedforward_layernorm_2's + * output and the dense arm pre_feedforward_layernorm's. + * + * per_expert_scale MULTIPLIES THE RENORMALISED WEIGHT, after the top-k. It is gathered by expert + * id with `embed_lookup` (a 128 x 1 table) and multiplied in with `mul`. + * + * THE TWO POST-NORMS OF THE ARMS ARE PER ARM, so under tensor parallel each arm's partial sum is + * reduced BEFORE its norm. The two partials sit in one [2T, n_embd] buffer -- dense rows first, + * routed rows after -- so one all-reduce carries both. + * + * ============================== TENSOR PARALLEL ============================== + * + * Heads split by rank, o and down by column with an all-reduce, the vocabulary by row. The full + * layers' two KV heads are REPLICATED past two ranks -- at four, ranks {0,1} hold KV head 0 and + * {2,3} KV head 1, each reading its head's row span of k_proj -- the scheme rad_arch.h's geom_from + * describes. Routed experts are EXPERT-PARALLEL (whole experts, 128/world a rank): a 704-wide + * expert is 5.5 fp8 blocks and has no block-aligned width split. The router is replicated, so + * every rank agrees on the routing without a collective and the arm's all-reduce sums the ranks' + * experts. + * + * ============================== FP8 EXPERTS ============================== + * + * The experts are ~90% of the weight bytes and the decode step reads whichever were routed, so + * their width is the step's bandwidth. Each projection is served as the container holds it -- + * bf16 by `moe_gemm`, block fp8 (the recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`) by + * `moe_gemm_q` at fp8a8 over an E4M3 input -- per layer and per projection (expert_format): + * + * gate_up [2 * 704, 2816]: 1408 rows are whole 64-row tiles and eleven 128-row scale blocks + * (one straddles gate and up, which only shares a scale); K is 22 blocks. fp8 at the + * checkpoint's own width. + * down [2816, 704]: K is the expert width and moe_gemm_q reads K in whole 128-column + * blocks, which 704 is not. It stays bf16 -- unless the checkpoint is padded to 768 + * first, outside the engine: zero rows of gate and up give gelu(0) * 0 = 0 in the + * padded columns, which meet zero columns of down, so the function is unchanged, and + * then both projections are fp8 (data/recipes/gemma4-26b-a4b-df-pad768.recipe). + * + * ============================== WHAT THIS PLUGIN DOES NOT YET DECLARE ============================== + * + * the vision tower (Gemma 4's, which arch/embgemma2 already declares for an encoder) -- this + * serves text; a container that carries a tower is served with --mm-max-patches 0 and the + * server refuses a media part by name; + * an fp8 attention or dense arm -- under a tenth of the weight bytes, and the dense arm's 2112 + * is not whole 128-blocks either. + */ +#include +#include +#include + +#include "gemma4_dflash.h" + +#include +#include +#include +#include +#include +#include + +namespace gemma4 { + +using namespace rad::arch; + +/* The fused router's two bounds, as rad_block_moe_fp8.h states them: the most routing slots + * libr4d's sort serves in one workgroup (its kScatterSmall), and the skinny bf16 GEMM's decode + * band, where the fused op's GEMM is that GEMM's own arithmetic. */ +static const int64_t kMoeSortRows = 1024; +static const int64_t kMoeRouterFusedRows = 64; + +/* ============================================================== metadata */ +/* Gemma4ForConditionalGeneration nests the text model's config under `text_config`; a + * Gemma4ForCausalLM checkpoint does not. rad-convert flattens nested keys with dots, so every key + * is asked for in both spellings, text_config's first. */ +static long long tc_geti(const RadModelMeta* m, const char* k, long long dflt) { + const long long sentinel = -0x7FFFFFFFll; + char key[160]; + std::snprintf(key, sizeof key, "text_config.%s", k); + long long v = rad_meta_geti(m, key, sentinel); + if (v == sentinel) v = rad_meta_geti(m, k, sentinel); + return v == sentinel ? dflt : v; +} +static double tc_getf(const RadModelMeta* m, const char* k, double dflt) { + char key[160]; + std::snprintf(key, sizeof key, "text_config.%s", k); + if (rad_meta_gets(m, key, nullptr)) return rad_meta_getf(m, key, dflt); + return rad_meta_getf(m, k, dflt); +} +static const char* tc_gets(const RadModelMeta* m, const char* k, const char* dflt) { + char key[160]; + std::snprintf(key, sizeof key, "text_config.%s", k); + const char* v = rad_meta_gets(m, key, nullptr); + return v ? v : rad_meta_gets(m, k, dflt); +} +/* A JSON boolean reaches the meta as 1/0 or as true/false, depending on the converter's path. */ +static bool tc_getb(const RadModelMeta* m, const char* k, bool dflt) { + const char* s = tc_gets(m, k, nullptr); + if (!s) return dflt; + if (!std::strcmp(s, "true") || !std::strcmp(s, "True")) return true; + if (!std::strcmp(s, "false") || !std::strcmp(s, "False") || !std::strcmp(s, "null")) return false; + return std::atoll(s) != 0; +} + +/* A value as a bf16 tensor holds it: round to nearest even on the top 16 bits of the f32. The + * reference's embedding scale is a bf16 buffer, so sqrt(2816) = 53.066 multiplies as 53.0. */ +static double bf16_round(double v) { + float f = (float)v; + uint32_t u; + std::memcpy(&u, &f, 4); + u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u; + std::memcpy(&f, &u, 4); + return (double)f; +} + +/* "1 6 11 17 22 27" -> the trunk layers whose output the drafter reads. Out-of-range entries are + * dropped (llama_fp8.cpp says why). */ +static int parse_ids(const char* s, int64_t n, int* out, int max) { + if (!s) return 0; + int k = 0; + for (const char* p = s; *p && k < max;) { + while (*p == ' ' || *p == ',' || *p == '[' || *p == ']') ++p; + if (!*p) break; + char* e = nullptr; + const long v = std::strtol(p, &e, 10); + if (e == p) break; + p = e; + if (v >= 0 && v < n) out[k++] = (int)v; + } + return k; +} + +/* "sliding_attention full_attention ..." -> 1 for each full layer. */ +static int parse_types(const char* s, std::vector* full) { + full->clear(); + if (!s) return RAD_E_INVAL; + for (const char* p = s; *p;) { + while (*p == ' ' || *p == ',' || *p == '[' || *p == ']' || *p == '"') ++p; + if (!*p) break; + const char* t = p; + while (*p && *p != ' ' && *p != ',' && *p != ']' && *p != '"') ++p; + const size_t len = (size_t)(p - t); + if (len == 14 && !std::strncmp(t, "full_attention", 14)) full->push_back(1); + else if (len == 17 && !std::strncmp(t, "sliding_attention", 17)) full->push_back(0); + else { + fprintf(stderr, "radiance: gemma4: layer_types names '%.*s'; this plugin knows " + "full_attention and sliding_attention\n", (int)len, t); + return RAD_E_UNSUPPORTED; + } + } + return RAD_OK; +} + +/* ============================================================== the model */ + +/* One attention kind: the sliding and the full layers differ in head width, KV heads, rotary + * and window, and in whether V has a projection of its own. */ +struct Kind { + int64_t hd = 0; /* head_dim */ + int64_t nh = 0; /* query heads, THIS rank */ + int64_t nkv = 0; /* KV heads, THIS rank */ + int64_t nkv_all = 0; + bool kv_repl = false; /* KV heads replicated across ranks (world > nkv_all) */ + int64_t kv_off = 0; /* this rank's first KV row in the unsharded k/v projection */ + double theta = 0.0; + int64_t window = 0; /* attn_paged's: key j visible to query i when i - j < window */ + int64_t rot_pairs = 0; /* frequency pairs that rotate; < hd/2 is proportional rope */ + bool k_eq_v = false; + rad_kvgroup kv = 0; + int64_t q() const { return nh * hd; } + int64_t kv_dim() const { return nkv * hd; } +}; + +struct Layer { + int full = 0; + /* attention */ + rad_weight w_anorm = 0, w_qkv = 0, w_q = 0, w_k = 0, w_qn = 0, w_kn = 0, w_o = 0, w_apost = 0; + rad_op op_anorm = 0, op_qkv = 0, op_qknr = 0, op_lift = 0; + rad_op op_q = 0, op_k = 0, op_vnorm = 0, op_qn = 0, op_kn = 0, op_qrope = 0, op_krope = 0; + rad_op op_store = 0, op_attn = 0, op_o = 0, op_ar_o = 0, op_apost = 0, op_add_a = 0; + /* dense arm */ + rad_weight w_fnorm = 0, w_gu = 0, w_dn = 0, w_fpost1 = 0; + rad_op op_fnorm = 0, op_gu = 0, op_act = 0, op_dn = 0; + /* routed arm. Each projection's experts are plain bf16 or block fp8, whichever the container + * holds (expert_format). A bf16 projection's handles are its experts in order, one table; an + * fp8 one's are the EVEN local experts then the ODD ones, codes in w_egu/w_edn and the scale + * views in w_egus/w_edns, so each parity is one run (see declare). */ + rad_weight w_rscale = 0, w_router = 0, w_escale = 0, w_enorm = 0, w_fpost2 = 0; + std::vector w_egu, w_edn, w_egus, w_edns; + bool gu_fp8 = false, dn_fp8 = false; + rad_op op_rnorm = 0, op_router = 0, op_topk = 0, op_escale = 0, op_emul = 0, op_enorm = 0; + rad_op op_scatter = 0, op_egu = 0, op_eact = 0, op_eq = 0, op_edn = 0, op_gather = 0; + /* libr4d's fused forms of the router, its top-k and the sort, where they resolve: the pair + * (`router_topk_scatter`) up to `topk_scatter_rows`, and the router GEMM in front of it + * (`router_gemm_topk_scatter`) up to `router_fused_rows`. A pass past their rows issues the + * separate ops, which are declared either way. */ + rad_op op_topk_scatter = 0, op_router_fused = 0; + /* expert_scale: op_escale and op_emul in one launch, where it resolves */ + rad_op op_expert_scale = 0; + int64_t topk_scatter_rows = 0, router_fused_rows = 0; + /* the join */ + rad_weight w_fpost = 0, w_scalar = 0; + rad_op op_ar_f = 0, op_fpost1 = 0, op_fpost2 = 0, op_fsum = 0, op_fpost = 0, op_add_f = 0; + rad_op op_scale = 0; + /* THE SANDWICH JOINS, FUSED: op_join_a is apost + add_a + fnorm, op_join_f the + * routed layer's fpost1 + fpost2 + fsum + fpost + add_f + scale. Zero where not served, and + * then the chain above is declared and issued instead. */ + rad_op op_join_a = 0, op_join_f = 0; + /* op_join_r: op_join_a writing the routed arm's two inputs as well -- the router's norm into + * b_rn and the experts' fp8 codes into b_hq / b_hqs (norm_add_norm_route) -- where the + * layer's gate_up is block fp8. op_rnorm and op_enorm are then declared and not issued. */ + rad_op op_join_r = 0; + /* op_join_f also writes the NEXT norm -- the following layer's input norm, or the final norm + * after the last layer -- into `h`, with that norm's gain `w_next`; the norm it replaces is + * then neither declared nor issued. */ + bool next_norm = false; + rad_weight w_next = 0; + /* the drafter's tap, on a layer the drafter reads (see declare) */ + rad_op op_tap = 0; +}; + +struct Model { + Names nm{""}; + Geom g{}; /* the sliding kind's geometry, and everything model-wide */ + Kind ks{}, kf{}; /* sliding, full */ + int64_t n_layer = 0, E = 0; + int64_t n_ff = 0; /* dense arm, THIS rank */ + bool moe = false; + int64_t n_expert = 0, n_local = 0, expert_base = 0, top_k = 0, n_ffe = 0; + int64_t moe_rows = 0; /* tokens a routed pass */ + /* A prefill chunk of 2 * moe_rows tokens or more runs as two slices, the trunk's all-reduces + * on the second lane beside the other slice's compute (trunk_overlap). Set at declare. */ + bool overlap = false; + /* In a step that runs whole -- every decode and verify step -- the dense arm rides the second + * lane beside the routed arm (trunk). Set at declare. */ + bool arms = false; + double escale = 1.0, softcap = 0.0; + + rad_buf b_x = 0, b_h = 0, b_o = 0; + rad_buf b_qkv = 0, b_qs = 0, b_atts = 0; /* sliding; q_s where q is lifted */ + int qrow = -1; /* attn_paged_qrow resolved: -1 not asked yet, then 0 or 1 */ + rad_buf b_qf = 0, b_kf = 0, b_vf = 0, b_attf = 0; /* full */ + rad_buf b_ff2 = 0, b_gu = 0, b_act = 0; /* the arms' join; the dense arm */ + rad_buf b_rn = 0, b_logit = 0, b_ids = 0, b_ew = 0, b_es = 0, b_hx = 0; + rad_buf b_sorted = 0, b_eoff = 0, b_ecnt = 0, b_egu = 0, b_eact = 0, b_edn = 0; + /* the experts' E4M3 inputs, declared only where some layer's projection is fp8: gate_up's + * (the normed block input, a row a token) and down's (the gated product, a row a slot) */ + rad_buf b_hq = 0, b_hqs = 0, b_eq = 0, b_eqs = 0; + int n_gu_fp8 = 0, n_dn_fp8 = 0; /* layers whose projection is fp8 */ + rad_buf b_hout = 0, b_logits = 0; + + rad_weight w_tok = 0, w_onorm = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_onorm = 0, op_gather = 0, op_logits = 0, op_cap = 0; + + enum { MAX_TAPS = 8 }; + int n_taps = 0; + int tap_layer[MAX_TAPS] = {}; + rad_buf b_dfsrc = 0; + + Dflash1 df{}; + Dflash1::Wire dfw{}; + rad_kvgroup kv_draft = 0; + bool have_df = false; + const char* tok_src = nullptr; /* the checkpoint's table, which the fp8 draft head copies */ + + std::vector layers; +}; + +static Model g_model[MAX_RANKS]; + +/* ============================================================== geometry */ + +static int split_heads(Kind& k, int64_t nh_all, int world, int rank, const char* what) { + if (nh_all % world) { + fprintf(stderr, "radiance: gemma4: %lld %s query heads do not divide over %d ranks\n", + (long long)nh_all, what, world); + return RAD_E_INVAL; + } + k.nh = nh_all / world; + if (world <= k.nkv_all) { + if (k.nkv_all % world) { + fprintf(stderr, "radiance: gemma4: %lld %s KV heads do not divide over %d ranks\n", + (long long)k.nkv_all, what, world); + return RAD_E_INVAL; + } + k.nkv = k.nkv_all / world; + k.kv_repl = false; + k.kv_off = rank * k.nkv * k.hd; + } else { + /* REPLICATED: ranks [i*r, (i+1)*r) share KV head i, r = world / nkv_all. A rank's query + * heads [rank*nh, (rank+1)*nh) all belong to that head because gqa = nh_all / nkv_all is a + * multiple of nh exactly when world is a multiple of nkv_all -- which is checked. */ + if (world % k.nkv_all) { + fprintf(stderr, "radiance: gemma4: %d ranks cannot replicate %lld %s KV heads; the " + "world must be a multiple of the KV head count\n", world, + (long long)k.nkv_all, what); + return RAD_E_INVAL; + } + k.nkv = 1; + k.kv_repl = true; + k.kv_off = (rank / (world / k.nkv_all)) * k.hd; + } + return RAD_OK; +} + +/* THE FULL LAYERS' ROTARY (see the header). `rope` rotates n_head + n_head_kv heads of its operand, + * so a q-only tensor is n_head = nh, n_head_kv = 0 and a k-only one n_head = nkv. */ +static rad_op decl_full_rope(RadBuilder* b, const Kind& k, int64_t rows, int64_t heads) { + const int64_t half = k.hd / 2; + if (k.rot_pairs >= half) + return RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", k.hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0), + RAD_F64("theta", k.theta), RAD_F64("scale", 1.0), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", k.hd)), + RAD_NOWEIGHTS); + /* frequency(inv, i) = inv / factor for i >= high, inv for i <= low (rad_yarn.h); the + * magnitude multiplies cos and sin and stays 1. */ + return RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", k.hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0), + RAD_F64("theta", k.theta), RAD_F64("scale", 1.0), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", k.hd), + RAD_F64("yarn_factor", 1e30), + RAD_F64("yarn_low", (double)k.rot_pairs - 0.5), + RAD_F64("yarn_high", (double)k.rot_pairs), + RAD_F64("yarn_magnitude", 1.0)), + RAD_NOWEIGHTS); +} + +/* ============================================================== the drafter */ + +static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Model& m, int base_layer) { + Names& nm = m.nm; + Geom dg = m.g; + dg.n_layer = rad_meta_geti(meta, "draft.num_hidden_layers", 0); + dg.head_dim = rad_meta_geti(meta, "draft.head_dim", 0); + dg.n_head_all = rad_meta_geti(meta, "draft.num_attention_heads", 0); + dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0); + dg.n_ff_all = rad_meta_geti(meta, "draft.intermediate_size", 0); + dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0); + dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta", + rad_meta_getf(meta, "draft.rope_theta", 0.0)); + dg.wadd = dg.wadd_qk = 0.0f; + if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 || + dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) { + fprintf(stderr, "radiance: gemma4: the container's `draft.` config does not describe a " + "DFlash drafter: layers %lld, heads %lld / kv %lld, head_dim %lld, ffn " + "%lld, rms_eps %g, rope_theta %g\n", + (long long)dg.n_layer, (long long)dg.n_head_all, (long long)dg.n_head_kv_all, + (long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta); + return RAD_E_INVAL; + } + if (rad_meta_geti(meta, "draft.hidden_size", dg.n_embd) != dg.n_embd) { + fprintf(stderr, "radiance: gemma4: the drafter is %lld wide and the target %lld; it reads " + "the target's embedding and head, so it is not this target's drafter\n", + (long long)rad_meta_geti(meta, "draft.hidden_size", 0), (long long)dg.n_embd); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim)); + int s; + if ((s = divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)) < 0) return s; + if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s; + if ((s = divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff)) < 0) return s; + const long long dvocab = rad_meta_geti(meta, "draft.vocab_size", dg.n_vocab_all); + if (dvocab != dg.n_vocab_all) { + fprintf(stderr, "radiance: gemma4: the drafter claims a %lld-token vocabulary and the " + "target has %lld\n", dvocab, (long long)dg.n_vocab_all); + return RAD_E_UNSUPPORTED; + } + + Dflash1::Config dc{}; + dc.n_taps = m.n_taps; + dc.escale = m.escale; + /* v1 states its block at the top level; a SpecForge config nests it under dflash_config. */ + long long trained = rad_meta_geti(meta, "draft.block_size", 0); + if (trained <= 0) trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); + if (trained < 2) { + fprintf(stderr, "radiance: gemma4: the DFlash checkpoint states no block_size\n"); + return RAD_E_FORMAT; + } + if ((long long)ctx->max_spec + 1 != trained) { + fprintf(stderr, "radiance: gemma4: the DFlash drafter was trained at block_size %lld, " + "which is %lld draft tokens, and this serve asks for %d. A block-diffusion " + "drafter denoises a fixed number of mask positions; run it at " + "--num-speculative-tokens %lld (or `auto`).\n", + trained, trained - 1, ctx->max_spec, trained - 1); + return RAD_E_UNSUPPORTED; + } + dc.block = trained; + if (dg.n_layer > Dflash1::MAX_LAYERS) return RAD_E_UNSUPPORTED; + { + std::vector full; + const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr); + if (lt) { + RAD_ARCH_TRY(parse_types(lt, &full)); + if ((int64_t)full.size() != dg.n_layer) { + fprintf(stderr, "radiance: gemma4: the drafter's layer_types names %zu layers and " + "it has %lld\n", full.size(), (long long)dg.n_layer); + return RAD_E_INVAL; + } + } else { + full.assign((size_t)dg.n_layer, 1); + } + bool any_swa = false; + for (int64_t l = 0; l < dg.n_layer; ++l) { + dc.full[l] = full[(size_t)l]; + any_swa = any_swa || !full[(size_t)l]; + } + if (any_swa) { + dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size", + rad_meta_geti(meta, "draft.sliding_window", 0)); + if (!rad_meta_geti(meta, "draft.use_sliding_window", 1) || dc.window <= 0) { + fprintf(stderr, "radiance: gemma4: the drafter names sliding layers and no " + "window\n"); + return RAD_E_INVAL; + } + } + } + + /* ONE CACHE FOR ALL FIVE LAYERS, unbounded, because the full layer reads every position. The + * sliding layers bound themselves with their attention op's `window`, so the declared drafter + * window is 0 and the core stages the whole context. A window group for the four sliding + * layers would cap their share at the window; it is the obvious saving once this runs. */ + RadKVGroupDecl dd{}; + dd.kind = RAD_KV_FULL; + dd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + dd.n_head_kv = dg.n_head_kv; + dd.head_dim = dg.head_dim; + m.kv_draft = rad_decl_kv_group(b, nm.f("kv_draft"), &dd); + for (int64_t l = 0; l < dg.n_layer; ++l) + RAD_ARCH_TRY(rad_bind_layer_kv(b, base_layer + (int)l, m.kv_draft)); + dg.kv_dtype = rad_dtype_name(dd.dtype); + + const int64_t qd = dg.n_head * dg.head_dim; + const int64_t kvd = dg.n_head_kv * dg.head_dim; + int64_t qr = dg.max_seqs * dc.block; + if (qr > dg.max_tok) qr = dg.max_tok; + const int64_t sr = dg.max_seqs * dc.steps(); + const int64_t tw = dc.n_taps * dg.n_embd; + + Dflash1::Wire& dw = m.dfw; + dw.src = m.b_dfsrc; + dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, tw}); + dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(tw)}); + dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd}); + dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd}); + dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)}); + dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd}); + dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd}); + dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd}); + dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd}); + dw.hq = decl_b(b, nm.f("df_hq"), RAD_F8E4M3, {qr, dg.n_embd}); + dw.hs = decl_b(b, nm.f("df_hs"), RAD_F32, {qr, fp8_blocks(dg.n_embd)}); + dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd}); + dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd}); + dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd}); + dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd}); + dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd}); + dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)}); + dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff}); + dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff}); + dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff}); + dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)}); + dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd}); + dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, dg.n_vocab}); + if (Dflash1::head_sharded(dg)) { + const int64_t R = Dflash1::kTopR; + dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, R}); + dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, R}); + dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, R, 2}); + dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * R, 2}); + } else { + dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, 1}); + } + if (!Dflash1::head_sharded(dg) && dg.world > 1) { + fprintf(stderr, "radiance: gemma4: the vocabulary (%lld) does not split evenly into whole " + "16-row blocks over %d ranks, which the drafter's sharded head needs\n", + (long long)dg.n_vocab_all, dg.world); + return RAD_E_UNSUPPORTED; + } + /* THE DRAFT, one row a draft position -- [n_seq * steps, 1], which is [n_seq, steps] with a + * pitch of `steps` -- and the engine reads it by the declaration below. */ + dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {sr, 1}); + + RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", dw, + m.tok_src)); + m.have_df = true; + + RadDrafterDecl drf{}; + drf.name = "dflash"; + drf.kind = RAD_DRAFT_BLOCK; + drf.depth = ctx->max_spec; + drf.block = dc.block; /* the anchor predicts nothing: block = depth + 1 */ + drf.proposal = dw.tokens; + drf.proposal_pitch = dc.steps(); + drf.window = 0; /* the full layer reads everything; see the group */ + drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", + rad_meta_geti(meta, "draft.mask_token_id", -1)); + if (drf.mask_token < 0) { + fprintf(stderr, "radiance: gemma4: the DFlash checkpoint declares no mask_token_id\n"); + return RAD_E_FORMAT; + } + RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + + int nfull = 0; + for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l]; + rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld " + "sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the " + "trunk at %d tap(s). ONE forward over %lld rows proposes %lld tokens; the head is " + "%s, argmax %s", + (long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1, nfull, + (long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head, + (long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, m.n_taps, + (long long)dc.block, (long long)dc.steps(), + m.df.fp8_head + ? "the container's block-fp8 copy of the target's table (dflash.draft_head)" + : "the target's tied bf16 table", + Dflash1::head_sharded(dg) ? "per vocab shard, merged" : "over the whole vocabulary"); + return RAD_OK; +} + +/* ============================================================== the experts' encoding */ + +/* WHAT ONE EXPERT PROJECTION IS STORED AS -- the container's entry, or in rad-convert the recipe's + * plan for it (rad_weight_encoding) -- which picks the GEMM: plain bf16 is `moe_gemm`, block fp8 + * (fp8_e4m3 codes, a bf16 scale a 128x128 block) is `moe_gemm_q` at fp8a8. Anything else is + * refused by name. A builder with no model behind it answers nothing, and the declared dtype is + * then what is read: bf16. */ +enum { EXP_BF16 = 0, EXP_FP8 = 1 }; +static int expert_format(RadBuilder* b, const char* wn, int* fmt) { + RadEncoding e{}; + *fmt = EXP_BF16; + if (!weight_enc(b, wn, &e)) return RAD_OK; + if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return RAD_OK; + if (block_fp8_128(e)) { + *fmt = EXP_FP8; + return RAD_OK; + } + char en[256]; + rad_enc_format(&e, en, sizeof en); + fprintf(stderr, "radiance: gemma4: '%s' is %s; the routed experts are served plain bf16 or " + "block fp8 (fp8_e4m3*bf16[128x128]). Convert with no rule for them, or with " + "`rtn codes=fp8_e4m3 block=128x128 scale=bf16`.\n", wn, en); + return RAD_E_DTYPE; +} + +/* ONE ENCODING A PROJECTION A LAYER, because one table of experts takes one: the first local + * expert's decides, and every other has to match it. `what` is "gate_up" or "down". */ +static int layer_expert_format(RadBuilder* b, Names& nm, int64_t l, int64_t base, int64_t n, + const char* what, int* fmt) { + for (int64_t e = 0; e < n; ++e) { + const char* wn = nm.f("blk.%lld.ffn_%s_exps.%lld.weight", (long long)l, what, + (long long)(base + e)); + int f = EXP_BF16; + RAD_ARCH_TRY(expert_format(b, wn, &f)); + if (e == 0) { *fmt = f; continue; } + if (f != *fmt) { + fprintf(stderr, "radiance: gemma4: '%s' is %s and expert %lld of the same layer is %s; " + "one layer's %s experts take one encoding (a recipe rule for them " + "matches all of a layer's or none)\n", wn, + f == EXP_FP8 ? "block fp8" : "bf16", (long long)base, + *fmt == EXP_FP8 ? "block fp8" : "bf16", what); + return RAD_E_DTYPE; + } + } + return RAD_OK; +} + +/* ============================================================== declare */ + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + if (ctx->is_draft) { + fprintf(stderr, "radiance: gemma4: this plugin has no draft scope\n"); + return RAD_E_UNSUPPORTED; + } + const char* q = meta->quant ? meta->quant : ""; + if (*q) { + fprintf(stderr, "radiance: gemma4 serves a container converted from the bf16 checkpoint " + "(google/gemma-4-*-it), with the recipe choosing what is fp8, and this one " + "declares '%s'.\n", q); + return RAD_E_UNSUPPORTED; + } + + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + Names& nm = m.nm; + Geom& g = m.g; + + /* ---- what this plugin is NOT, refused by name. */ + if (tc_geti(meta, "hidden_size_per_layer_input", 0) > 0 || + tc_geti(meta, "num_kv_shared_layers", 0) > 0 || tc_getb(meta, "use_double_wide_mlp", false) || + tc_getb(meta, "attention_bias", false)) { + fprintf(stderr, "radiance: gemma4: this checkpoint uses per-layer embeddings, shared KV " + "layers, a double-wide MLP or attention biases (the E2B/E4B shape); this " + "plugin serves the 26B-A4B and 31B shape\n"); + return RAD_E_UNSUPPORTED; + } + { + const char* act = tc_gets(meta, "hidden_activation", ""); + if (!act || std::strcmp(act, "gelu_pytorch_tanh")) { + fprintf(stderr, "radiance: gemma4: hidden_activation '%s'; this plugin serves " + "gelu_pytorch_tanh\n", act ? act : ""); + return RAD_E_UNSUPPORTED; + } + } + + /* ---- the geometry. Read, never derived: head_dim is not hidden / heads on this family. */ + m.n_layer = meta->n_layers > 0 ? meta->n_layers : tc_geti(meta, "num_hidden_layers", 0); + m.E = tc_geti(meta, "hidden_size", meta->n_embd); + const int64_t nh_all = tc_geti(meta, "num_attention_heads", meta->n_head); + const int64_t vocab = tc_geti(meta, "vocab_size", meta->n_vocab); + const int64_t ff_all = tc_geti(meta, "intermediate_size", meta->n_ff); + const double eps = tc_getf(meta, "rms_norm_eps", meta->rms_eps); + m.ks.hd = tc_geti(meta, "head_dim", meta->head_dim); + m.ks.nkv_all = tc_geti(meta, "num_key_value_heads", meta->n_head_kv); + m.kf.hd = tc_geti(meta, "global_head_dim", m.ks.hd); + m.kf.nkv_all = tc_geti(meta, "num_global_key_value_heads", m.ks.nkv_all); + m.kf.k_eq_v = tc_getb(meta, "attention_k_eq_v", false); + m.ks.theta = tc_getf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0); + m.kf.theta = tc_getf(meta, "rope_parameters.full_attention.rope_theta", 0.0); + m.ks.window = tc_geti(meta, "sliding_window", 0); /* HF: q - k < window, attn_paged's rule */ + m.softcap = tc_getf(meta, "final_logit_softcapping", 0.0); + if (m.n_layer <= 0 || m.E <= 0 || nh_all <= 0 || vocab <= 0 || ff_all <= 0 || !(eps > 0) || + m.ks.hd <= 0 || m.ks.nkv_all <= 0 || m.kf.hd <= 0 || m.kf.nkv_all <= 0 || + !(m.ks.theta > 0) || !(m.kf.theta > 0) || m.ks.window <= 0) { + fprintf(stderr, "radiance: gemma4: the container does not describe the model: layers " + "%lld, hidden %lld, heads %lld, vocab %lld, ffn %lld, eps %g, sliding %lld " + "x %lld kv theta %g window %lld, full %lld x %lld kv theta %g\n", + (long long)m.n_layer, (long long)m.E, (long long)nh_all, (long long)vocab, + (long long)ff_all, eps, (long long)m.ks.hd, (long long)m.ks.nkv_all, m.ks.theta, + (long long)m.ks.window, (long long)m.kf.hd, (long long)m.kf.nkv_all, m.kf.theta); + return RAD_E_INVAL; + } + /* The two rotaries. The sliding one is the ordinary full-head NeoX; the full one is read for + * its type and its proportion and refused if it is anything this plugin does not compute. */ + { + const char* st = tc_gets(meta, "rope_parameters.sliding_attention.rope_type", "default"); + const char* ft = tc_gets(meta, "rope_parameters.full_attention.rope_type", "default"); + const double prf = tc_getf(meta, "rope_parameters.full_attention.partial_rotary_factor", 1.0); + const double ff = tc_getf(meta, "rope_parameters.full_attention.factor", 1.0); + if (std::strcmp(st, "default") || (std::strcmp(ft, "default") && std::strcmp(ft, "proportional")) || + ff != 1.0 || !(prf > 0.0) || prf > 1.0) { + fprintf(stderr, "radiance: gemma4: rotary '%s' (sliding) and '%s' factor %g " + "proportion %g (full); this plugin computes default and " + "proportional at factor 1\n", st, ft, ff, prf); + return RAD_E_UNSUPPORTED; + } + m.ks.rot_pairs = m.ks.hd / 2; + /* int(rope_proportion * head_dim // 2), exactly as transformers computes it. */ + m.kf.rot_pairs = !std::strcmp(ft, "proportional") + ? (int64_t)std::floor(prf * (double)m.kf.hd / 2.0) + : m.kf.hd / 2; + if (m.kf.rot_pairs <= 0) return RAD_E_INVAL; + } + + std::vector full; + RAD_ARCH_TRY(parse_types(tc_gets(meta, "layer_types", nullptr), &full)); + if ((int64_t)full.size() != m.n_layer) { + fprintf(stderr, "radiance: gemma4: layer_types names %zu layers and the model has %lld\n", + full.size(), (long long)m.n_layer); + return RAD_E_INVAL; + } + + /* The model-wide Geom, which the shared helpers (and the drafter's copy) read. */ + g.n_layer = m.n_layer; + g.n_embd = m.E; + g.head_dim = m.ks.hd; + g.n_head_all = nh_all; + g.n_head_kv_all = m.ks.nkv_all; + g.n_ff_all = ff_all; + g.n_vocab_all = vocab; + g.max_tok = ctx->max_tok; + g.max_seqs = ctx->max_seqs; + g.max_ctx = ctx->max_ctx; + g.max_spec = ctx->max_spec; + g.max_logit_rows = ctx->max_seqs * (ctx->max_spec > 0 ? ctx->max_spec + 1 : 1); + if (g.max_logit_rows > ctx->max_tok) g.max_logit_rows = ctx->max_tok; + if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows; + g.rank = ctx->rank; + g.world = ctx->world_size > 0 ? ctx->world_size : 1; + g.wire_exact = ctx->tp_wire_lossy ? 0 : 1; + g.wire_min_bytes = ctx->tp_wire_min_bytes; + g.eps = (float)eps; + g.theta = (float)m.ks.theta; + g.rope_scale = 1.0f; + g.dtype = "bf16"; + g.act_dtype = RAD_BF16; + if (g.max_tok <= 0 || g.max_seqs <= 0) return RAD_E_INVAL; + const int W = g.world, R = g.rank; + RAD_ARCH_TRY(split_heads(m.ks, nh_all, W, R, "sliding")); + RAD_ARCH_TRY(split_heads(m.kf, nh_all, W, R, "full")); + g.n_head = m.ks.nh; + g.n_head_kv = m.ks.nkv; + RAD_ARCH_TRY(divide_or_fail(ff_all, W, "intermediate_size", &m.n_ff)); + g.n_ff = m.n_ff; + g.n_vocab = shard_extent(vocab, W, R); + g.vocab_off = shard_begin(vocab, W, R); + if (g.n_vocab <= 0) return RAD_E_INVAL; + const int64_t E = m.E, T = g.max_tok; + + /* ---- the routed arm's geometry. */ + m.moe = tc_getb(meta, "enable_moe_block", false); + if (m.moe) { + m.n_expert = tc_geti(meta, "num_experts", meta->n_expert); + m.top_k = tc_geti(meta, "top_k_experts", meta->n_expert_used); + m.n_ffe = tc_geti(meta, "moe_intermediate_size", 0); + if (m.n_expert <= 0 || m.top_k <= 0 || m.top_k > m.n_expert || m.n_ffe <= 0) { + fprintf(stderr, "radiance: gemma4: enable_moe_block with %lld experts, top %lld, of " + "%lld\n", (long long)m.n_expert, (long long)m.top_k, + (long long)m.n_ffe); + return RAD_E_INVAL; + } + RAD_ARCH_TRY(divide_or_fail(m.n_expert, W, "num_experts", &m.n_local)); + m.expert_base = (int64_t)R * m.n_local; + /* A pass bounds the [rows * top_k, ...] expert planes; 2048 tokens is one pass at the + * default chunk. */ + m.moe_rows = T < 2048 ? T : 2048; + } + + /* ---- the embedding scale and the rotary scaling the converter may have written. */ + m.escale = bf16_round(std::sqrt((double)E)); + RAD_ARCH_TRY(yarn_from(g, meta, "", m.ks.hd)); + if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f) { + fprintf(stderr, "radiance: gemma4: --rope-scaling is not implemented for this family's " + "two rotaries\n"); + return RAD_E_UNSUPPORTED; + } + + /* ---- the KV groups, one a geometry: the sliding layers' (256-wide heads) and the full + * layers' (512). + * + * THE SLIDING LAYERS' GROUP IS RAD_KV_FULL, NOT RAD_KV_WINDOW, and the window lives on the + * attention op (`window` 1024), which reads only the keys inside it. A WINDOW group is not + * prefix-cached (core/mem/prefix.cpp: a hit's blocks do not describe a cache whose floor + * moves). Before the scheduler knew that, a hit gave the sliding layers a table whose reused + * prefix was never written for this request -- recycled blocks of other conversations, and a + * reply that answers someone else's question; now a hit on a model with a windowed trunk group + * reuses nothing and re-prefills (core/sched). As FULL the group is cached with the others and + * a hit is kept, exactly; the drafter's KV gets no hole either. What it costs is the recycling + * below the window, which buys nothing here: the planner gives every paged group the same + * block count, so the full group bounds the tokens a card holds either way. */ + { + RadKVGroupDecl d{}; + d.kind = RAD_KV_FULL; + d.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + d.window = 0; + d.n_head_kv = m.ks.nkv; + d.head_dim = m.ks.hd; + m.ks.kv = rad_decl_kv_group(b, nm.f("kv_swa"), &d); + d.kind = RAD_KV_FULL; + d.window = 0; + d.n_head_kv = m.kf.nkv; + d.head_dim = m.kf.hd; + m.kf.kv = rad_decl_kv_group(b, nm.f("kv_full"), &d); + g.kv_dtype = rad_dtype_name(d.dtype); + } + + /* Gemma4ForConditionalGeneration keeps the text model under model.language_model; + * Gemma4ForCausalLM (a text-only export) under model. */ + const char* archs = rad_meta_gets(meta, "architectures", ""); + const char* L = (archs && std::strstr(archs, "Gemma4ForCausalLM")) ? "model" + : "model.language_model"; + + /* ---- THE EXPERTS' NAME MAPS, AND FROM THEM WHAT EACH LAYER'S EXPERTS ARE, before any buffer: + * an fp8 projection reads an E4M3 input that a bf16 one does not, and a plane nothing reads + * is still charged by the planner. One stacked tensor a projection a layer, sliced by the + * GLOBAL expert index -- this rank declares its window into the checkpoint's experts. */ + m.layers.resize((size_t)m.n_layer); + if (m.moe) { + const int64_t NL = m.n_local; + for (int64_t l = 0; l < m.n_layer; ++l) { + Layer& y = m.layers[(size_t)l]; + const long long ll = (long long)l; + const char* sgu = nm.ckpt("%s.layers.%lld.experts.gate_up_proj", L, ll); + const char* sdn = nm.ckpt("%s.layers.%lld.experts.down_proj", L, ll); + for (int64_t e = 0; e < NL; ++e) { + const long long ge = (long long)(m.expert_base + e); + RAD_ARCH_TRY(map_slice(b, nm.f("blk.%lld.ffn_gate_up_exps.%lld.weight", ll, ge), sgu, (int)ge)); + RAD_ARCH_TRY(map_slice(b, nm.f("blk.%lld.ffn_down_exps.%lld.weight", ll, ge), sdn, (int)ge)); + } + int fgu = EXP_BF16, fdn = EXP_BF16; + RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "gate_up", &fgu)); + RAD_ARCH_TRY(layer_expert_format(b, nm, l, m.expert_base, NL, "down", &fdn)); + y.gu_fp8 = fgu == EXP_FP8; + y.dn_fp8 = fdn == EXP_FP8; + /* moe_gemm_q's geometry, refused here by name rather than as a kernel miss. Its + * experts are two tables by parity, so a rank holds an even count of them. */ + if ((y.gu_fp8 || y.dn_fp8) && NL % 2) { + fprintf(stderr, "radiance: gemma4: block fp8 experts come in pairs on a rank (the " + "fp8 grouped GEMM takes them as two tables by parity); this rank " + "holds %lld\n", (long long)NL); + return RAD_E_INVAL; + } + if (y.gu_fp8 && ((2 * m.n_ffe) % 64 || E % RAD_FP8_BLOCK)) { + fprintf(stderr, "radiance: gemma4: layer %lld's gate_up experts are block fp8 at " + "%lld x %lld; the fp8 grouped GEMM takes N in 64s and K in whole " + "%d-column blocks\n", ll, (long long)(2 * m.n_ffe), (long long)E, + RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + if (y.dn_fp8 && (E % 64 || m.n_ffe % RAD_FP8_BLOCK)) { + fprintf(stderr, "radiance: gemma4: layer %lld's down experts are block fp8, and " + "the experts are %lld wide: the fp8 grouped GEMM reads K in whole " + "%d-column scale blocks. Keep `ffn_down_exps` bf16 (no recipe " + "rule for it), or pad the experts to a multiple of %d (zero rows " + "of gate and up, zero columns of down) and convert the padded " + "checkpoint.\n", ll, + (long long)m.n_ffe, RAD_FP8_BLOCK, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + m.n_gu_fp8 += y.gu_fp8; + m.n_dn_fp8 += y.dn_fp8; + } + } + + /* ---- activations. */ + const int64_t qs = m.ks.q(), kvs = m.ks.kv_dim(), qf = m.kf.q(), kvf = m.kf.kv_dim(); + m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {T, E}); + m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {T, E}); + m.b_o = decl_b(b, nm.f("o"), RAD_BF16, {T, E}); + m.b_qkv = decl_b(b, nm.f("qkv_s"), RAD_BF16, {T, qs + 2 * kvs}); + m.b_atts = decl_b(b, nm.f("att_s"), RAD_BF16, {T, qs}); + m.b_qf = decl_b(b, nm.f("q_f"), RAD_BF16, {T, qf}); + m.b_kf = decl_b(b, nm.f("k_f"), RAD_BF16, {T, kvf}); + m.b_vf = decl_b(b, nm.f("v_f"), RAD_BF16, {T, kvf}); + m.b_attf = decl_b(b, nm.f("att_f"), RAD_BF16, {T, qf}); + m.b_ff2 = decl_b(b, nm.f("ff2"), RAD_BF16, {2 * T, E}); + m.b_gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * m.n_ff}); + m.b_act = decl_b(b, nm.f("ffn"), RAD_BF16, {T, m.n_ff}); + if (m.moe) { + const int64_t P = m.moe_rows, K = m.top_k; + m.b_rn = decl_b(b, nm.f("moe_rn"), RAD_BF16, {T, E}); + m.b_logit = decl_b(b, nm.f("moe_logits"), RAD_BF16, {T, m.n_expert}); + m.b_ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {T, K}); + m.b_ew = decl_b(b, nm.f("moe_w"), RAD_BF16, {T, K}); + m.b_es = decl_b(b, nm.f("moe_es"), RAD_BF16, {T, K}); + if (m.n_gu_fp8 < m.n_layer) + m.b_hx = decl_b(b, nm.f("moe_h"), RAD_BF16, {T, E}); + if (m.n_gu_fp8 > 0) { + m.b_hq = decl_b(b, nm.f("moe_hq"), RAD_F8E4M3, {T, E}); + m.b_hqs = decl_b(b, nm.f("moe_hqs"), RAD_F32, {T, fp8_blocks(E)}); + } + m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {P * K}); + m.b_eoff = decl_b(b, nm.f("moe_eoff"), RAD_I32, {m.n_local + 1}); + m.b_ecnt = decl_b(b, nm.f("moe_ecnt"), RAD_I32, {m.n_local}); + m.b_egu = decl_b(b, nm.f("moe_egu"), RAD_BF16, {P * K, 2 * m.n_ffe}); + m.b_eact = decl_b(b, nm.f("moe_eact"), RAD_BF16, {P * K, m.n_ffe}); + if (m.n_dn_fp8 > 0) { + m.b_eq = decl_b(b, nm.f("moe_eq"), RAD_F8E4M3, {P * K, m.n_ffe}); + m.b_eqs = decl_b(b, nm.f("moe_eqs"), RAD_F32, {P * K, fp8_blocks(m.n_ffe)}); + } + m.b_edn = decl_b(b, nm.f("moe_edn"), RAD_BF16, {P * K, E}); + } + m.b_hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, E}); + + /* ---- the drafter's taps: declared when the container carries a DFlash drafter AND this serve + * speculates. DFlash2 is refused by name -- its convolutions and selector are another block. */ + if (ctx->max_spec > 0) { + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (da && std::strstr(da, "DFlash2")) { + fprintf(stderr, "radiance: gemma4: the container carries a DFlash2 drafter; this plugin " + "serves the DFlash (v1) block z-lab publishes for Gemma 4\n"); + return RAD_E_UNSUPPORTED; + } + if (da && std::strstr(da, "DFlash")) { + const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr); + if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr); + m.n_taps = parse_ids(ids, m.n_layer, m.tap_layer, Model::MAX_TAPS); + if (m.n_taps <= 0) { + fprintf(stderr, "radiance: gemma4: the drafter names no trunk layer this model " + "has; it is paired with a different target\n"); + return RAD_E_UNSUPPORTED; + } + m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)m.n_taps * E}); + } + } + + m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); + RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits)); + + /* ---- the vocabulary edges: ONE table, row-sharded with the vocabulary, read as the embedding + * by `embed_lookup` and as the head by `logits_gemm` -- Gemma ties them, so storing the head + * a second time would be 1.4 GiB for nothing. */ + m.tok_src = nm.ckpt("%s.embed_tokens.weight", L); + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), m.tok_src)); + RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.norm.weight", L))); + m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, E}, RAD_ACCESS_VOCAB, + RAD_SHARD_ROW, grp_model()); + m.w_onorm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {E}, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_model()); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", m.escale)), + RAD_WEIGHTS(m.w_tok)), + {}, {m.b_x}); + if (W > 1) + m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", W), RAD_RANGE("numel", E, T * E), + RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + + /* ---- small declaration helpers, every one rows-banded at the step's height unless told. */ + auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, double mult, rad_buf in, rad_buf out) { + rad_op h = w ? RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16"), + RAD_F64("wadd", 0.0), RAD_F64("mult", mult)), + RAD_WEIGHTS(w)) + : RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16"), + RAD_F64("wadd", 0.0), RAD_F64("mult", mult)), + RAD_NOWEIGHTS); + return rw(b, h, {in}, {out}); + }; + auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + {in}, {out}); + }; + auto binop = [&](const char* op, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {a, c}, {out}); + }; + auto act_mul = [&](int64_t rows, int64_t n, rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {in}, {out}); + }; + auto allreduce = [&](int64_t max_numel, rad_buf buf) { + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", W), RAD_RANGE("numel", E, max_numel), + RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {buf}, {buf}); + }; + auto attn = [&](const Kind& k, rad_buf q, rad_buf out, const char* op = "attn_paged") { + return rw(b, RAD_OP(b, op, + RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", k.hd), + RAD_INT("gqa", k.nh / k.nkv), RAD_INT("causal", 1), + RAD_INT("window", k.window), RAD_INT("n_head", k.nh), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype), + RAD_F64("scale", 1.0)), + RAD_NOWEIGHTS), + {q}, {out}); + }; + auto kv_store = [&](const Kind& k, rad_buf kb, rad_buf vb) { + return rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", k.hd), + RAD_INT("n_head_kv", k.nkv), + RAD_INT("block_size", rad_kv_block_size(b, k.kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {kb, vb}, {}); + }; + + /* THE SANDWICH JOINS, expert_scale AND attn_paged_qrow: asked of the kernel libraries as one + * op each and declared as the chain where they do not resolve. Not every library declares them + * -- libr4d does, with device rows; libref and libavx do not -- and declaring an op no loaded + * library declares is an error, so each is asked about first (rad_op_declared). A deployment + * where none is declared -- a CPU-only build, a --kernels list without libr4d -- or where none + * resolves -- the host backend -- runs the chain. The fused kernels round where the host chain + * rounds (libr4d/r4d_norm_join_bf16.hip); on a card they differ from libr4d's chain by the + * order of its reductions. libref has no row for them on purpose, so "nothing serves them" + * stays reachable. */ + const bool has_join_a = rad_op_declared(b, "norm_add_norm") != 0; + const bool has_join_r = rad_op_declared(b, "norm_add_norm_route") != 0; + const bool has_join_f = rad_op_declared(b, "join_add_scale") != 0; + const bool has_escale = rad_op_declared(b, "expert_scale") != 0; + const bool has_qrow = rad_op_declared(b, "attn_paged_qrow") != 0; + int n_joins = 0, n_route = 0; + + const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE; + /* EVERY LAYER'S INPUT NORM GAIN, AHEAD OF THE LAYERS: a feed-forward join writes the next + * layer's input norm (join_add_scale's `y`) and so names that layer's gain before the layer + * itself is declared. */ + for (int64_t l = 0; l < m.n_layer; ++l) { + const long long ll = (long long)l; + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll), + nm.ckpt("%s.layers.%lld.input_layernorm.weight", L, ll))); + m.layers[(size_t)l].w_anorm = decl_w(b, nm.f("blk.%lld.attn_norm.weight", ll), RAD_F32, + {E}, A, N, grp_layer((int)l)); + } + + for (int64_t l = 0; l < m.n_layer; ++l) { + Layer& y = m.layers[(size_t)l]; + y.full = full[(size_t)l]; + const Kind& k = y.full ? m.kf : m.ks; + const long long ll = (long long)l; + const int li = (int)l; + const RadWeightGroup gl = grp_layer(li); + auto src = [&](const char* s) { return nm.ckpt("%s.layers.%lld.%s", L, ll, s); }; + RAD_ARCH_TRY(rad_bind_layer_kv(b, li, k.kv)); + + /* ------------------------------------------------ attention: weights */ + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_q_norm.weight", ll), src("self_attn.q_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_k_norm.weight", ll), src("self_attn.k_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_output.weight", ll), src("self_attn.o_proj.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_post_norm.weight", ll), + src("post_attention_layernorm.weight"))); + /* bf16 gains: `qk_norm_rope` reads its gains at the activation's width. */ + y.w_qn = decl_w(b, nm.f("blk.%lld.attn_q_norm.weight", ll), RAD_BF16, {k.hd}, A, N, gl); + y.w_kn = decl_w(b, nm.f("blk.%lld.attn_k_norm.weight", ll), RAD_BF16, {k.hd}, A, N, gl); + y.w_o = decl_w(b, nm.f("blk.%lld.attn_output.weight", ll), RAD_BF16, {E, k.q()}, A, + RAD_SHARD_COL, gl); + y.w_apost = decl_w(b, nm.f("blk.%lld.attn_post_norm.weight", ll), RAD_F32, {E}, A, N, gl); + if (!y.full) { + /* ONE PROJECTION, q|k|v, three row parts: every rank takes its slice of each. */ + RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.attn_qkv.weight", ll), + { src("self_attn.q_proj.weight"), src("self_attn.k_proj.weight"), + src("self_attn.v_proj.weight") })); + if (!k.kv_repl) { + y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16, + {k.q() + 2 * k.kv_dim(), E}, A, RAD_SHARD_ROW, gl, 0, + {k.q(), k.kv_dim(), k.kv_dim()}); + } else { + y.w_qkv = decl_w(b, nm.f("blk.%lld.attn_qkv.weight", ll), RAD_BF16, + {k.q() + 2 * k.kv_dim(), E}, A, RAD_SHARD_ROW, gl, 0, + {k.q(), k.kv_dim(), k.kv_dim()}); + const int64_t lo[3] = { R * k.q(), k.kv_off, k.kv_off }; + const int64_t hi[3] = { lo[0] + k.q(), lo[1] + k.kv_dim(), lo[2] + k.kv_dim() }; + const int64_t tot[3] = { nh_all * k.hd, k.nkv_all * k.hd, k.nkv_all * k.hd }; + RAD_ARCH_TRY(rad_weight_shard_span_parts(b, y.w_qkv, lo, hi, tot, 3)); + } + } else { + if (!k.k_eq_v) { + fprintf(stderr, "radiance: gemma4: full-attention layer %lld has a v_proj " + "(attention_k_eq_v false); this plugin serves K = V\n", ll); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_q.weight", ll), src("self_attn.q_proj.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_k.weight", ll), src("self_attn.k_proj.weight"))); + y.w_q = decl_w(b, nm.f("blk.%lld.attn_q.weight", ll), RAD_BF16, {k.q(), E}, A, + RAD_SHARD_ROW, gl); + y.w_k = decl_w(b, nm.f("blk.%lld.attn_k.weight", ll), RAD_BF16, {k.kv_dim(), E}, A, + RAD_SHARD_ROW, gl); + if (k.kv_repl) + RAD_ARCH_TRY(rad_weight_shard_span(b, y.w_k, k.kv_off, k.kv_off + k.kv_dim())); + } + + /* ------------------------------------------------ attention: ops, in issue order (the + * attention op is declared ahead of its kv_store, which reads the block size off it). */ + if (!(l > 0 && m.layers[(size_t)l - 1].next_norm)) + y.op_anorm = rmsnorm(T, E, y.w_anorm, 1.0, m.b_x, m.b_h); + if (!y.full) { + y.op_qkv = gemm(T, k.q() + 2 * k.kv_dim(), E, y.w_qkv, m.b_h, m.b_qkv); + y.op_qknr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", k.hd), + RAD_INT("n_head", k.nh), RAD_INT("n_head_kv", k.nkv), + RAD_F64("theta", k.theta), RAD_F64("eps", eps), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", k.hd), + RAD_F64("wadd", 0.0), RAD_INT("v_norm", 1)), + RAD_WEIGHTS(y.w_qn, y.w_kn)), + {m.b_qkv}, {m.b_qkv}); + /* Q IS READ WHERE THE PROJECTION LEFT IT, a column slice of the fused [q|k|v] row, by + * `attn_paged_qrow` -- attn_paged with q at its own row pitch, an op of its own so + * that no `--kernels` order can hand the slice to a kernel that reads q only dense + * (one refuses it with RAD_E_STRIDE, which stops the engine). That saves the + * lift: a launch and a [T, q] round trip a sliding layer. Where the op is not declared + * or does not resolve, q is lifted into a dense block for attn_paged, which every + * attention library takes. Asked once, because every + * sliding layer asks the same question; a miss is still the group's first op carrying + * a block_size, and answers rad_kv_block_size with the RAD_KV_BLOCK it declares. */ + if (has_qrow && m.qrow != 0) { + y.op_attn = attn(k, m.b_qkv, m.b_atts, "attn_paged_qrow"); + m.qrow = y.op_attn ? 1 : 0; + } + if (!y.op_attn) { + /* declared here, not with the others: a buffer no op names is live for the whole + * program, and where q is read in place nothing names this one */ + if (!m.b_qs) m.b_qs = decl_b(b, nm.f("q_s"), RAD_BF16, {T, k.q()}); + y.op_lift = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", k.q()), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {m.b_qkv}, {m.b_qs}); + y.op_attn = attn(k, m.b_qs, m.b_atts); + } + y.op_store = kv_store(k, m.b_qkv, m.b_qkv); + y.op_o = gemm(T, E, k.q(), y.w_o, m.b_atts, m.b_o); + } else { + y.op_q = gemm(T, k.q(), E, y.w_q, m.b_h, m.b_qf); + y.op_k = gemm(T, k.kv_dim(), E, y.w_k, m.b_h, m.b_kf); + /* V FIRST: the unit-gain norm of the RAW k projection, before the key norm writes k. */ + y.op_vnorm = rmsnorm(T * k.nkv, k.hd, 0, 1.0, m.b_kf, m.b_vf); + y.op_qn = rmsnorm(T * k.nh, k.hd, y.w_qn, 1.0, m.b_qf, m.b_qf); + y.op_kn = rmsnorm(T * k.nkv, k.hd, y.w_kn, 1.0, m.b_kf, m.b_kf); + y.op_qrope = rw(b, decl_full_rope(b, k, T, k.nh), {m.b_qf}, {m.b_qf}); + y.op_krope = rw(b, decl_full_rope(b, k, T, k.nkv), {m.b_kf}, {m.b_kf}); + y.op_attn = attn(k, m.b_qf, m.b_attf); + y.op_store = kv_store(k, m.b_kf, m.b_vf); + y.op_o = gemm(T, E, k.q(), y.w_o, m.b_attf, m.b_o); + } + if (W > 1) y.op_ar_o = allreduce(T * E, m.b_o); + /* The post-norm AFTER the reduction: it is a norm of the whole sum. Declared below, with the + * dense arm's pre-norm, as one `norm_add_norm` where a kernel library serves it. */ + + /* ------------------------------------------------ the dense arm */ + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm.weight", ll), src("pre_feedforward_layernorm.weight"))); + RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.ffn_gate_up.weight", ll), + { src("mlp.gate_proj.weight"), src("mlp.up_proj.weight") })); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_down.weight", ll), src("mlp.down_proj.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_post_norm.weight", ll), + src("post_feedforward_layernorm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.layer_scalar", ll), src("layer_scalar"))); + y.w_fnorm = decl_w(b, nm.f("blk.%lld.ffn_norm.weight", ll), RAD_F32, {E}, A, N, gl); + y.w_gu = decl_w(b, nm.f("blk.%lld.ffn_gate_up.weight", ll), RAD_BF16, {2 * m.n_ff, E}, + A, RAD_SHARD_ROW, gl, 0, {m.n_ff, m.n_ff}); + y.w_dn = decl_w(b, nm.f("blk.%lld.ffn_down.weight", ll), RAD_BF16, {E, m.n_ff}, A, + RAD_SHARD_COL, gl); + y.w_fpost = decl_w(b, nm.f("blk.%lld.ffn_post_norm.weight", ll), RAD_F32, {E}, A, N, gl); + /* bf16 and one element: the reference multiplies the bf16 stream by it. */ + y.w_scalar = decl_w(b, nm.f("blk.%lld.layer_scalar", ll), RAD_BF16, {1}, A, N, gl); + + /* The routed arm's two input norms -- the router's gain and the experts' pre-norm -- are + * declared here, ahead of the attention join, which writes both inputs where + * `norm_add_norm_route` is served and an op names its weights after they are declared. */ + if (m.moe) { + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), + src("pre_feedforward_layernorm_2.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), src("router.scale"))); + y.w_enorm = decl_w(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), RAD_F32, {E}, A, N, + gl); + y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl); + } + + /* THE ATTENTION JOIN, and on a layer whose gate_up is block fp8 the routed arm's two + * inputs with it: the router's norm (rmsnorm's expression, its mult hidden^-0.5) and the + * experts' E4M3 codes (rmsnorm_quant_fp8's) from the norm of x the join already takes -- + * two launches a layer fewer, and two reads of x. Then norm_add_norm, then the chain. */ + if (has_join_r && m.moe && y.gu_fp8) + y.op_join_r = rw(b, RAD_OP(b, "norm_add_norm_route", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16"), + RAD_F64("mult", 1.0 / std::sqrt((double)E)), + RAD_INT("group", RAD_FP8_BLOCK)), + RAD_WEIGHTS(y.w_apost, y.w_fnorm, y.w_rscale, y.w_enorm)), + {m.b_o, m.b_x}, {m.b_x, m.b_h, m.b_rn, m.b_hq, m.b_hqs}); + if (has_join_a && !y.op_join_r) + y.op_join_a = rw(b, RAD_OP(b, "norm_add_norm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(y.w_apost, y.w_fnorm)), + {m.b_o, m.b_x}, {m.b_x, m.b_h}); + if (!y.op_join_a && !y.op_join_r) { + y.op_apost = rmsnorm(T, E, y.w_apost, 1.0, m.b_o, m.b_o); + y.op_add_a = binop("add", T, E, m.b_x, m.b_o, m.b_x); + y.op_fnorm = rmsnorm(T, E, y.w_fnorm, 1.0, m.b_x, m.b_h); + } + y.op_gu = gemm(T, 2 * m.n_ff, E, y.w_gu, m.b_h, m.b_gu); + y.op_act = act_mul(T, m.n_ff, m.b_gu, m.b_act); + /* The dense partial into rows [0, T) of the join. */ + y.op_dn = gemm(T, E, m.n_ff, y.w_dn, m.b_act, m.b_ff2); + + /* ------------------------------------------------ the routed arm */ + if (m.moe) { + const int64_t P = m.moe_rows, K = m.top_k, NL = m.n_local; + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_post_norm1.weight", ll), + src("post_feedforward_layernorm_1.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_post_norm2.weight", ll), + src("post_feedforward_layernorm_2.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_gate_inp.weight", ll), src("router.proj.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_exp_scale", ll), src("router.per_expert_scale"))); + y.w_fpost1 = decl_w(b, nm.f("blk.%lld.ffn_post_norm1.weight", ll), RAD_F32, {E}, A, N, gl); + y.w_fpost2 = decl_w(b, nm.f("blk.%lld.ffn_post_norm2.weight", ll), RAD_F32, {E}, A, N, gl); + /* THE ROUTER IS REPLICATED (rad_block_moe_fp8.h argues it): every rank routes every + * token the same way from the same residual stream. */ + y.w_router = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.weight", ll), RAD_BF16, + {m.n_expert, E}, A, N, gl); + y.w_escale = decl_w(b, nm.f("blk.%lld.ffn_exp_scale", ll), RAD_BF16, {m.n_expert}, A, + N, gl); + /* THE EXPERTS: whole experts, this rank's run of them (their name maps and encodings + * were settled before the buffers). Each projection's handles are declared as the + * runs its GEMM's tables are: bf16, one run in expert order; block fp8, the codes of + * the even local experts, then the odd ones', then the scale views in the same two + * runs -- `moe_gemm_q` takes a projection's experts as two tables by parity, and a + * table is a run of consecutively declared handles. The codes and the scale plane are + * two views of one stored weight and one movement unit (slot 0 gate_up, 1 down). */ + auto experts = [&](bool fp8, const char* what, int slot, int64_t rows, int64_t cols, + std::vector& wc, std::vector& ws) { + wc.assign((size_t)NL, 0); + ws.clear(); + if (!fp8) { + for (int64_t e = 0; e < NL; ++e) { + const long long ge = (long long)(m.expert_base + e); + wc[(size_t)e] = decl_w(b, nm.f("blk.%lld.ffn_%s_exps.%lld.weight", ll, what, ge), + RAD_BF16, {rows, cols}, RAD_ACCESS_CONDITIONAL, N, + grp_expert_slot(li, (int)e, slot)); + if (!wc[(size_t)e]) return RAD_E_INVAL; + } + return RAD_OK; + } + ws.assign((size_t)NL, 0); + const int64_t half = NL / 2; + for (int pass = 0; pass < 2; ++pass) /* codes, then scales */ + for (int par = 0; par < 2; ++par) /* even, then odd */ + for (int64_t i = 0; i < half; ++i) { + const int64_t e = 2 * i + par; + const long long ge = (long long)(m.expert_base + e); + const char* wn = nm.f("blk.%lld.ffn_%s_exps.%lld.weight", ll, what, ge); + rad_weight& h = (pass ? ws : wc)[(size_t)(par * half + i)]; + h = pass ? decl_view(b, nm.f("blk.%lld.ffn_%s_exps.%lld.scale", ll, what, ge), + wn, "scale", RAD_BF16, + {fp8_blocks(rows), fp8_blocks(cols)}, + RAD_ACCESS_CONDITIONAL, N, + grp_expert_slot(li, (int)e, slot)) + : decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, {rows, cols}, + RAD_ACCESS_CONDITIONAL, N, + grp_expert_slot(li, (int)e, slot)); + if (!h) return RAD_E_INVAL; + } + return RAD_OK; + }; + RAD_ARCH_TRY(experts(y.gu_fp8, "gate_up", 0, 2 * m.n_ffe, E, y.w_egu, y.w_egus)); + RAD_ARCH_TRY(experts(y.dn_fp8, "down", 1, E, m.n_ffe, y.w_edn, y.w_edns)); + /* An fp8 projection's op takes its weights in its table operands' order: even codes, + * even scales, odd codes, odd scales. */ + auto tables = [&](const std::vector& wc, const std::vector& ws) { + const size_t h = wc.size() / 2; + std::vector t; + t.insert(t.end(), wc.begin(), wc.begin() + (long)h); + t.insert(t.end(), ws.begin(), ws.begin() + (long)h); + t.insert(t.end(), wc.begin() + (long)h, wc.end()); + t.insert(t.end(), ws.begin() + (long)h, ws.end()); + return t; + }; + + y.op_rnorm = rmsnorm(P, E, y.w_rscale, 1.0 / std::sqrt((double)E), m.b_x, m.b_rn); + y.op_router = gemm(P, m.n_expert, E, y.w_router, m.b_rn, m.b_logit); + y.op_topk = rw(b, RAD_OP(b, "router_topk", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_expert", m.n_expert), + RAD_INT("top_k", K), RAD_INT("norm", 1), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_logit}, {m.b_ids, m.b_ew}); + /* per_expert_scale[expert] times the routing weight: one launch where `expert_scale` is + * served, and otherwise the table gathered as [n_expert, 1] by the ids and a + * `mul` -- the same bf16 product either way (docs/OPS.md). */ + if (has_escale) + y.op_expert_scale = rw(b, RAD_OP(b, "expert_scale", + RAD_PARAMS(RAD_RANGE("M", 1, P), + RAD_INT("n_expert", m.n_expert), + RAD_INT("top_k", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(y.w_escale)), + {m.b_ids, m.b_ew}, {m.b_ew}); + if (!y.op_expert_scale) { + y.op_escale = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, P * K), RAD_INT("n_embd", 1), + RAD_INT("n_vocab", m.n_expert), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(y.w_escale)), + {m.b_ids}, {m.b_es}); + y.op_emul = binop("mul", P, K, m.b_ew, m.b_es, m.b_ew); + } + /* THE EXPERTS' INPUT: pre_feedforward_layernorm_2 of the stream -- for an fp8 gate_up, + * normed and quantised in one pass (`rmsnorm_quant_fp8`), with no bf16 copy, since the + * fp8 GEMM reads only the codes and their scales. */ + if (y.gu_fp8) { + y.op_enorm = RAD_OP(b, "rmsnorm_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", E), + RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "bf16"), RAD_F64("wadd", 0.0)), + RAD_WEIGHTS(y.w_enorm)); + y.op_enorm = rw(b, y.op_enorm, {m.b_x}, {m.b_hq, m.b_hqs}); + } else { + y.op_enorm = rmsnorm(P, E, y.w_enorm, 1.0, m.b_x, m.b_hx); + } + y.op_scatter = rw(b, RAD_OP(b, "moe_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_expert", NL), + RAD_INT("top_k", K), + RAD_INT("expert_base", m.expert_base)), + RAD_NOWEIGHTS), + {m.b_ids}, {m.b_sorted, m.b_eoff, m.b_ecnt}); + /* THE ROUTER, ITS TOP-K AND THE SORT IN ONE LAUNCH at decode heights. At a decode step + * each of the three is one small workgroup's work behind a full dispatch, and libr4d + * fuses them: `router_topk_scatter` for the pair, bounded by the sort's single-workgroup + * form (kMoeSortRows routing slots), and `router_gemm_topk_scatter` with the router's + * GEMM in front, up to the skinny GEMM's decode band -- byte-identical to the launches + * they stand in for (docs/OPS.md), so the routing does not move. The per-expert scale + * and the experts' input norm sit between them in the issue order and read only the ids + * and weights the fused op writes. Declared here, after every buffer they name: a late + * declaration only lengthens a buffer's planned life (rad_block_moe_fp8.h). */ + { + const int64_t sort_rows = P * K <= kMoeSortRows ? P : kMoeSortRows / K; + if (sort_rows > 0) + y.op_topk_scatter = rw(b, RAD_OP(b, "router_topk_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, sort_rows), + RAD_INT("n_expert", m.n_expert), + RAD_INT("n_local", NL), RAD_INT("top_k", K), + RAD_INT("norm", 1), RAD_STR("dtype", "bf16"), + RAD_INT("expert_base", m.expert_base)), + RAD_NOWEIGHTS), + {m.b_logit}, {m.b_ids, m.b_ew, m.b_sorted, m.b_eoff, m.b_ecnt}); + if (y.op_topk_scatter) { + y.topk_scatter_rows = sort_rows; + const int64_t fr = sort_rows < kMoeRouterFusedRows ? sort_rows : kMoeRouterFusedRows; + y.op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", E), + RAD_INT("n_expert", m.n_expert), + RAD_INT("n_local", NL), RAD_INT("top_k", K), + RAD_INT("norm", 1), RAD_STR("dtype", "bf16"), + RAD_INT("expert_base", m.expert_base)), + RAD_WEIGHTS(y.w_router)), + {m.b_rn}, + {m.b_logit, m.b_ids, m.b_ew, m.b_sorted, m.b_eoff, m.b_ecnt}); + if (y.op_router_fused) y.router_fused_rows = fr; + } + } + /* THE TWO GROUPED GEMMs DISAGREE ABOUT a_order, and must: gate_up reads the block + * input, a row a TOKEN, gathered through sorted_tok; down reads gate_up's product, + * already a row a (token, slot) in the scatter's order (rad_block_moe_fp8.h). */ + if (y.gu_fp8) { + const std::vector tab = tables(y.w_egu, y.w_egus); + y.op_egu = rw(b, rad_decl_op(b, "moe_gemm_q", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe), + RAD_INT("K", E), RAD_INT("n_expert", NL), + RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("a_order", "token"), RAD_STR("dtype", "fp8a8")), + tab.data(), (int)tab.size()), + {m.b_hq, m.b_hqs, m.b_sorted, m.b_eoff}, {m.b_egu}); + } else { + y.op_egu = rw(b, rad_decl_op(b, "moe_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", 2 * m.n_ffe), + RAD_INT("K", E), RAD_INT("n_expert", NL), + RAD_INT("top_k", K), RAD_STR("a_order", "token"), + RAD_STR("dtype", "bf16")), + y.w_egu.data(), (int)NL), + {m.b_hx, m.b_sorted, m.b_eoff}, {m.b_egu}); + } + /* gelu_tanh(gate) * up over the two column halves. An fp8 down then quantises the + * product on its own launch: libr4d's fused gated quantiser is compiled for silu. */ + y.op_eact = act_mul(P * K, m.n_ffe, m.b_egu, m.b_eact); + if (y.dn_fp8) { + y.op_eq = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, P * K), RAD_INT("n", m.n_ffe), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_eact}, {m.b_eq, m.b_eqs}); + const std::vector tab = tables(y.w_edn, y.w_edns); + y.op_edn = rw(b, rad_decl_op(b, "moe_gemm_q", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", E), + RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL), + RAD_INT("top_k", K), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("a_order", "sorted"), RAD_STR("dtype", "fp8a8")), + tab.data(), (int)tab.size()), + {m.b_eq, m.b_eqs, m.b_sorted, m.b_eoff}, {m.b_edn}); + } else { + y.op_edn = rw(b, rad_decl_op(b, "moe_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", E), + RAD_INT("K", m.n_ffe), RAD_INT("n_expert", NL), + RAD_INT("top_k", K), RAD_STR("a_order", "sorted"), + RAD_STR("dtype", "bf16")), + y.w_edn.data(), (int)NL), + {m.b_eact, m.b_sorted, m.b_eoff}, {m.b_edn}); + } + { + rad_buf rd[3] = { m.b_edn, m.b_ew, m.b_sorted }; + rad_buf wr[1] = { m.b_ff2 }; + y.op_gather = RAD_OP(b, "moe_gather", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", E), + RAD_INT("top_k", K), RAD_STR("dtype", "bf16"), + RAD_STR("act", "none")), + RAD_NOWEIGHTS); + if (!y.op_gather) return RAD_E_INVAL; + rad_op_reads(b, y.op_gather, rd, 3); + rad_op_writes(b, y.op_gather, wr, 1); + } + if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_fp8 && !y.op_eq)) return RAD_E_INVAL; + if (W > 1) y.op_ar_f = allreduce(2 * T * E, m.b_ff2); + if (has_join_f) + { + /* ...and the norm that reads the x it writes: the next layer's input norm, or the + * final norm after the last layer -- one launch and one read of x the less. */ + const rad_weight w_next = l + 1 < m.n_layer ? m.layers[(size_t)l + 1].w_anorm + : m.w_onorm; + y.op_join_f = rw(b, RAD_OP(b, "join_add_scale", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(y.w_fpost1, y.w_fpost2, y.w_fpost, y.w_scalar, + w_next)), + {m.b_ff2, m.b_x}, {m.b_x, m.b_h}); + if (y.op_join_f) { y.next_norm = true; y.w_next = w_next; } + } + if (!y.op_join_f) { + y.op_fpost1 = rmsnorm(T, E, y.w_fpost1, 1.0, m.b_ff2, m.b_ff2); + y.op_fpost2 = rmsnorm(T, E, y.w_fpost2, 1.0, m.b_ff2, m.b_ff2); + y.op_fsum = binop("add", T, E, m.b_ff2, m.b_ff2, m.b_h); + y.op_fpost = rmsnorm(T, E, y.w_fpost, 1.0, m.b_h, m.b_h); + } + } else { + if (W > 1) y.op_ar_f = allreduce(T * E, m.b_ff2); + y.op_fpost = rmsnorm(T, E, y.w_fpost, 1.0, m.b_ff2, m.b_h); + } + if (!y.op_join_f) { + y.op_add_f = binop("add", T, E, m.b_x, m.b_h, m.b_x); + y.op_scale = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_STR("dtype", "bf16"), RAD_INT("scalar", 1)), + RAD_WEIGHTS(y.w_scalar)), + {m.b_x}, {m.b_x}); + } + n_joins += (y.op_join_a || y.op_join_r ? 1 : 0) + (y.op_join_f ? 1 : 0); + n_route += y.op_join_r ? 1 : 0; + + /* THE TAP: a row copy of the layer's output into the column slice a tap owns, DECLARED + * HERE, after the layer's last op, because that is where step() issues it. The buffer + * planner's liveness is declaration order. One tap op declared after the whole trunk made + * `dflash_src` look born at the end of it, so the plan was free to put it on top of + * buffers every layer writes -- and at --max-num-seqs 16 it did, under `moe_edn`, the + * routed experts' output: every MoE layer after a tap overwrote what the drafter reads, + * and on gemma-4-26B-A4B-it it accepted 2% of its drafts with the reply still fluent. */ + for (int t = 0; t < m.n_taps; ++t) + if (m.tap_layer[t] == (int)l && !y.op_tap) + y.op_tap = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_dfsrc}); + } + + /* ---- THE PREFILL OVERLAP (trunk_overlap): where there is a reduction to hide, a routed arm + * whose passes a slice can be a whole number of, and every join fused -- the slices issue the + * fused forms only. On the exact wire alone: nothing here shows the lossy one gives a slice + * the bits it gives the whole. On two R9700s the two slices give the whole chunk's text and + * logprobs exactly, at 2048- and 8192-token chunks. The two buffers the second lane reduces in place are taken out of the arena's + * sharing, which the runtime asks of every buffer a second lane touches (rad_buf_concurrent); + * both live across the whole trunk already, so what that costs is only the sharing with the + * drafter's and the head's buffers. */ + m.overlap = W > 1 && m.moe && g.wire_exact && T >= 2 * m.moe_rows; + for (const Layer& y : m.layers) + m.overlap = m.overlap && (y.op_join_a || y.op_join_r) && y.op_join_f && y.next_norm && + y.op_ar_o && y.op_ar_f; + /* ---- THE TWO ARMS SIDE BY SIDE (trunk), in a step that runs whole: the dense arm on the + * second lane beside the routed arm, which needs nothing of it until the feed-forward join. At a + * decode step on 4x R9700 the dense arm is three launches, ~36 us under --profile-ops, behind + * the routed arm's ~120 in a layer, and its GEMMs at a few rows are latency-bound -- far from + * the bandwidth the experts take. No collective rides it, so the reductions keep lane 0. The + * buffers the dense arm touches leave the arena's sharing. */ + m.arms = m.moe; + if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_o)); + if (m.overlap || m.arms) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ff2)); + if (m.arms) + for (rad_buf bb : { m.b_h, m.b_gu, m.b_act }) RAD_ARCH_TRY(rad_buf_concurrent(b, bb)); + + if (m.layers.empty() || !m.layers.back().next_norm) + m.op_onorm = rmsnorm(T, E, m.w_onorm, 1.0, m.b_x, m.b_h); + m.op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", E), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_h}, {m.b_hout}); + m.op_logits = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), + RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", E), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_tok)), + {m.b_hout}, {m.b_logits}); + /* FINAL LOGIT SOFTCAPPING, cap * tanh(x / cap) over the f32 logits: `logit_softcap`, which + * libref, libavx and libr4d serve. Where nothing does the model still runs and greedy decoding + * is unchanged -- the cap is strictly increasing -- but a sampled distribution is SHARPER than + * the model's, so the startup log says so. */ + if (m.softcap > 0.0) { + m.op_cap = rw(b, RAD_OP(b, "logit_softcap", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), + RAD_INT("n", g.n_vocab), RAD_F64("cap", m.softcap), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {m.b_logits}, {m.b_logits}); + if (!m.op_cap) + rad_note(b, "WARNING: nothing serves `logit_softcap` (load libr4d or libavx). " + "The model's logits are %g * tanh(x / %g); without it greedy output is " + "unchanged and SAMPLED output draws from a sharper distribution than the " + "model's", m.softcap, m.softcap); + } + + /* THE DRAFTER LAST: declaration order is the buffer planner's liveness (llama_fp8.cpp). */ + if (m.n_taps > 0) + RAD_ARCH_TRY(declare_dflash(b, meta, ctx, m, (int)m.n_layer)); + + int nfull = 0; + for (int f : full) nfull += f; + rad_note(b, "rank %d/%d: %lld layers (%d full attention %lld x %lld over %lld kv%s, %lld " + "sliding %lld x %lld over %lld kv, window %lld); dense ffn %lld; %s; vocab " + "[%lld,%lld) tied", + R, W, (long long)m.n_layer, nfull, (long long)m.kf.nh, (long long)m.kf.hd, + (long long)m.kf.nkv, m.kf.kv_repl ? " replicated" : "", + (long long)(m.n_layer - nfull), (long long)m.ks.nh, (long long)m.ks.hd, + (long long)m.ks.nkv, (long long)m.ks.window, (long long)m.n_ff, + m.moe ? "routed: experts [base, base + local) of the model's, top-k" : "no routed arm", + (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab)); + rad_note(b, "sandwich joins: %d of %lld fused (norm_add_norm / join_add_scale)%s", + n_joins, (long long)(m.moe ? 2 * m.n_layer : m.n_layer), + n_joins == 0 ? " -- not served, the rmsnorm / add / mul_weight chain" : ""); + if (m.moe && m.n_gu_fp8 > 0) + rad_note(b, "routed inputs: %d of %d fp8 layers take the router's norm and the experts' " + "codes from the attention join (norm_add_norm_route)%s", + n_route, m.n_gu_fp8, + n_route ? "" : " -- the rmsnorm and rmsnorm_quant_fp8 launches instead"); + if (m.ks.nh > 0) + rad_note(b, "sliding attention: q %s", m.qrow == 1 + ? "read in the fused qkv row (attn_paged_qrow)" + : "lifted into a dense block for attn_paged (attn_paged_qrow not served)"); + if (m.moe) { + auto how = [&](int n_fp8) { + return n_fp8 == m.n_layer ? "block fp8" : n_fp8 == 0 ? "bf16" : "mixed"; + }; + rad_note(b, "routed arm: %lld local experts from %lld of %lld, top %lld, %lld wide; " + "gate_up %s (%d of %lld layers fp8), down %s (%d fp8); passes of %lld tokens", + (long long)m.n_local, (long long)m.expert_base, (long long)m.n_expert, + (long long)m.top_k, (long long)m.n_ffe, how(m.n_gu_fp8), m.n_gu_fp8, + (long long)m.n_layer, how(m.n_dn_fp8), m.n_dn_fp8, (long long)m.moe_rows); + if (W > 1) + rad_note(b, "prefill overlap: %s", m.overlap + ? "a chunk of two routed passes or more runs as two slices, each slice's " + "all-reduces on a second stream beside the other's compute" + : !g.wire_exact ? "off (the lossy all-reduce wire)" + : T < 2 * m.moe_rows ? "off (a step holds fewer than two routed passes)" + : "off (the sandwich joins are not fused)"); + rad_note(b, "the two arms: in a step that runs whole, the dense arm on a second stream " + "beside the routed"); + } + if (m.kf.rot_pairs < m.kf.hd / 2) + rad_note(b, "full layers: PROPORTIONAL rope -- %lld of %lld frequency pairs rotate at " + "theta %g over the whole %lld-wide head, the rest stay at frequency zero", + (long long)m.kf.rot_pairs, (long long)(m.kf.hd / 2), m.kf.theta, + (long long)m.kf.hd); + return RAD_OK; +} + +/* ============================================================== step */ + +/* The routed arm over rows [first, first + rows) of a T-token step, in passes of m.moe_rows, its + * partial into rows [dst, dst + rows) of the join: [T, 2T) for a whole step, and right after the + * slice's dense rows for a slice of one (trunk_overlap). */ +static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t first, + int64_t rows, int64_t dst) { + const int64_t E = m.E, K = m.top_k, NL = m.n_local, NE = m.n_expert; + const int64_t end = first + rows; + for (int64_t r0 = first; r0 < end; r0 += m.moe_rows) { + const int64_t n = (end - r0 < m.moe_rows) ? (end - r0) : m.moe_rows; + int32_t* const counts = rad_route_counts(c, (int)(&y - m.layers.data()), NL); + const RadOperand ecnt = counts ? praw(counts, RAD_I32, NL) : brows(m.b_ecnt, NL); + if (!y.op_join_r) /* the attention join wrote the router's input otherwise */ + RAD_ISSUE_N(c, y.op_rnorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_rscale), + brow_slice(m.b_rn, r0, n, E)); + /* One launch, two or three: the router, its top-k and the sort (see declare). */ + const bool rfused = y.op_router_fused && n <= y.router_fused_rows; + const bool pair = !rfused && y.op_topk_scatter && n <= y.topk_scatter_rows; + if (rfused) { + RAD_ISSUE_N(c, y.op_router_fused, n, brow_slice(m.b_rn, r0, n, E), RAD_W(y.w_router), + RAD_NONE, brow_slice(m.b_logit, r0, n, NE), + brow_slice(m.b_ids, r0, n, K), brow_slice(m.b_ew, r0, n, K), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), ecnt, RAD_NONE); + } else { + RAD_ISSUE_N(c, y.op_router, n, brow_slice(m.b_rn, r0, n, E), RAD_W(y.w_router), + brow_slice(m.b_logit, r0, n, NE)); + if (pair) + RAD_ISSUE_N(c, y.op_topk_scatter, n, brow_slice(m.b_logit, r0, n, NE), + brow_slice(m.b_ids, r0, n, K), brow_slice(m.b_ew, r0, n, K), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), ecnt); + else + RAD_ISSUE_N(c, y.op_topk, n, brow_slice(m.b_logit, r0, n, NE), + brow_slice(m.b_ids, r0, n, K), brow_slice(m.b_ew, r0, n, K)); + } + /* The ids and the gathered scales read as flat [n * K] vectors: the same bytes. */ + int32_t* ids = (int32_t*)rad_buf_ptr(c, m.b_ids); + uint16_t* es = (uint16_t*)rad_buf_ptr(c, m.b_es); + if (y.op_expert_scale) { + RAD_ISSUE_N(c, y.op_expert_scale, n, brow_slice(m.b_ids, r0, n, K), RAD_W(y.w_escale), + brow_slice(m.b_ew, r0, n, K)); + } else { + RAD_ISSUE_N(c, y.op_escale, n * K, praw(ids ? ids + r0 * K : nullptr, RAD_I32, n * K), + RAD_W(y.w_escale), praw2(es ? es + r0 * K : nullptr, RAD_BF16, n * K, 1)); + RAD_ISSUE_N(c, y.op_emul, n, brow_slice(m.b_ew, r0, n, K), brow_slice(m.b_es, r0, n, K), + brow_slice(m.b_ew, r0, n, K)); + } + /* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent) -- + * where the attention join did not write the codes already. */ + if (y.gu_fp8 && !y.op_join_r) + RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_NONE, RAD_W(y.w_enorm), + brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK), + RAD_NONE); + else if (!y.gu_fp8) + RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_enorm), + brow_slice(m.b_hx, r0, n, E)); + if (!rfused && !pair) + RAD_ISSUE_N(c, y.op_scatter, n, brow_slice(m.b_ids, r0, n, K), brows(m.b_sorted, n * K), + brows(m.b_eoff, NL + 1), ecnt); + /* An fp8 projection's tables: the first handle of each parity's run and its length -- + * even codes, even scales, odd codes, odd scales (declare). */ + const int64_t H = NL / 2; + if (y.gu_fp8) + RAD_ISSUE_N(c, y.op_egu, n, brow_slice(m.b_hq, r0, n, E), + brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK), + RAD_WTAB(y.w_egu[0], H), RAD_WTAB(y.w_egus[0], H), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), + RAD_WTAB(y.w_egu[(size_t)H], H), RAD_WTAB(y.w_egus[(size_t)H], H), + brows(m.b_egu, n * K)); + else + RAD_ISSUE_N(c, y.op_egu, n, brow_slice(m.b_hx, r0, n, E), RAD_WTAB(y.w_egu[0], NL), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), brows(m.b_egu, n * K)); + RAD_ISSUE_N(c, y.op_eact, n * K, bcol(m.b_egu, 0, m.n_ffe, n * K), + bcol(m.b_egu, m.n_ffe, m.n_ffe, n * K), brows(m.b_eact, n * K)); + if (y.dn_fp8) { + RAD_ISSUE_N(c, y.op_eq, n * K, brows(m.b_eact, n * K), brows(m.b_eq, n * K), + brows(m.b_eqs, n * K)); + RAD_ISSUE_N(c, y.op_edn, n, brows(m.b_eq, n * K), brows(m.b_eqs, n * K), + RAD_WTAB(y.w_edn[0], H), RAD_WTAB(y.w_edns[0], H), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), + RAD_WTAB(y.w_edn[(size_t)H], H), RAD_WTAB(y.w_edns[(size_t)H], H), + brows(m.b_edn, n * K)); + } else { + RAD_ISSUE_N(c, y.op_edn, n, brows(m.b_eact, n * K), RAD_WTAB(y.w_edn[0], NL), + brows(m.b_sorted, n * K), brows(m.b_eoff, NL + 1), brows(m.b_edn, n * K)); + } + /* The routed partial into its rows of the join. */ + RAD_ISSUE_N(c, y.op_gather, n, brows(m.b_edn, n * K), brow_slice(m.b_ew, r0, n, K), + brows(m.b_sorted, n * K), RAD_NONE, RAD_NONE, + brow_slice(m.b_ff2, dst + (r0 - first), n, E)); + if (r0 + n >= T) { + RadRouting rt{}; + rt.expert_ids = ids; + rt.expert_w = nullptr; /* bf16 weights; the field is const float* (moe_fp8.h) */ + rt.expert_count = counts ? counts : (const int32_t*)rad_buf_ptr(c, m.b_ecnt); + rt.sorted_tok = (const int32_t*)rad_buf_ptr(c, m.b_sorted); + rt.expert_offset = (const int32_t*)rad_buf_ptr(c, m.b_eoff); + rt.top_k = K; + rt.n_expert = NL; + rad_route_report(c, (int)(&y - m.layers.data()), &rt); + } + } +} + +/* A layer's attention between its projections and its output projection, over the whole step: + * the norms and the rotaries, the cache write, the attention. */ +static void attend(RadCtx* c, const Model& m, const Layer& y, size_t li, const RadBatch* batch) { + const int64_t T = batch->n_tok; + const RadOperand pos = praw(batch->positions, RAD_I32, T); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + const Kind& k = y.full ? m.kf : m.ks; + const RadKVGroupBatch* kvb = kv_batch(batch, k.kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + const RadOperand bt = praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0); + const RadOperand su = praw(used, RAD_I32, batch->n_seq); + + if (!y.full) { + const int64_t qd = k.q(), kvd = k.kv_dim(); + RAD_ISSUE(c, y.op_qknr, brows(m.b_qkv, T), pos, RAD_W(y.w_qn), RAD_W(y.w_kn)); + RAD_ISSUE(c, y.op_store, bcol(m.b_qkv, qd, kvd, T), bcol(m.b_qkv, qd + kvd, kvd, T), + praw(slot, RAD_I32, T), kv_cache(k.kv, (int)li)); + if (y.op_lift) RAD_ISSUE(c, y.op_lift, bcol(m.b_qkv, 0, qd, T), brows(m.b_qs, T)); + RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, + y.op_lift ? brows(m.b_qs, T) : bcol(m.b_qkv, 0, qd, T), + kv_cache(k.kv, (int)li), bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_atts, T)); + } else { + RAD_ISSUE_N(c, y.op_vnorm, T * k.nkv, brows(m.b_kf, T), RAD_NONE, brows(m.b_vf, T)); + RAD_ISSUE_N(c, y.op_qn, T * k.nh, brows(m.b_qf, T), RAD_W(y.w_qn), brows(m.b_qf, T)); + RAD_ISSUE_N(c, y.op_kn, T * k.nkv, brows(m.b_kf, T), RAD_W(y.w_kn), brows(m.b_kf, T)); + RAD_ISSUE(c, y.op_qrope, brows(m.b_qf, T), pos); + RAD_ISSUE(c, y.op_krope, brows(m.b_kf, T), pos); + RAD_ISSUE(c, y.op_store, brows(m.b_kf, T), brows(m.b_vf, T), praw(slot, RAD_I32, T), + kv_cache(k.kv, (int)li)); + RAD_ISSUE_N(c, y.op_attn, batch->max_q_len, brows(m.b_qf, T), kv_cache(k.kv, (int)li), + bt, su, RAD_NONE, RAD_NONE, cu, brows(m.b_attf, T)); + } +} + +/* The trunk over the whole step, the dense arm beside the routed one where the model says so. */ +static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) { + const int64_t T = batch->n_tok, E = m.E; + bool lanes_ok = true; + for (size_t li = 0; li < m.layers.size(); ++li) { + const Layer& y = m.layers[li]; + if (y.op_anorm) RAD_ISSUE(c, y.op_anorm, brows(m.b_x, T), RAD_W(y.w_anorm), brows(m.b_h, T)); + if (!y.full) { + RAD_ISSUE(c, y.op_qkv, brows(m.b_h, T), RAD_W(y.w_qkv), brows(m.b_qkv, T)); + } else { + RAD_ISSUE(c, y.op_q, brows(m.b_h, T), RAD_W(y.w_q), brows(m.b_qf, T)); + RAD_ISSUE(c, y.op_k, brows(m.b_h, T), RAD_W(y.w_k), brows(m.b_kf, T)); + } + attend(c, m, y, li, batch); + RAD_ISSUE(c, y.op_o, brows(y.full ? m.b_attf : m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T)); + if (y.op_ar_o) RAD_ISSUE_N(c, y.op_ar_o, T * E, brows(m.b_o, T), RAD_NONE); + if (y.op_join_r) { + RAD_ISSUE(c, y.op_join_r, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T), + RAD_W(y.w_fnorm), brows(m.b_h, T), RAD_W(y.w_rscale), brows(m.b_rn, T), + RAD_W(y.w_enorm), brows(m.b_hq, T), brows(m.b_hqs, T)); + } else if (y.op_join_a) { + RAD_ISSUE(c, y.op_join_a, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T), + RAD_W(y.w_fnorm), brows(m.b_h, T)); + } else { + RAD_ISSUE(c, y.op_apost, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_o, T)); + RAD_ISSUE(c, y.op_add_a, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T)); + RAD_ISSUE(c, y.op_fnorm, brows(m.b_x, T), RAD_W(y.w_fnorm), brows(m.b_h, T)); + } + + /* dense arm -> rows [0, T) of the join: on lane 1 behind the attention join, where the arms + * run side by side, and lane 0 joins it back before the reduction reads them */ + if (m.arms) + lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK; + RAD_ISSUE(c, y.op_gu, brows(m.b_h, T), RAD_W(y.w_gu), brows(m.b_gu, T)); + RAD_ISSUE(c, y.op_act, bcol(m.b_gu, 0, m.n_ff, T), bcol(m.b_gu, m.n_ff, m.n_ff, T), + brows(m.b_act, T)); + RAD_ISSUE(c, y.op_dn, brows(m.b_act, T), RAD_W(y.w_dn), brows(m.b_ff2, T)); + if (m.arms) lanes_ok = rad_lane(c, 0) == RAD_OK && lanes_ok; + if (m.moe) { + routed(c, m, y, T, 0, T, T); + if (m.arms) lanes_ok = rad_lane_join(c, 1, 0) == RAD_OK && lanes_ok; + if (y.op_ar_f) RAD_ISSUE_N(c, y.op_ar_f, 2 * T * E, brows(m.b_ff2, 2 * T), RAD_NONE); + if (y.op_join_f) { + RAD_ISSUE(c, y.op_join_f, brows(m.b_ff2, T), RAD_W(y.w_fpost1), + brow_slice(m.b_ff2, T, T, E), RAD_W(y.w_fpost2), RAD_W(y.w_fpost), + brows(m.b_x, T), RAD_W(y.w_scalar), RAD_W(y.w_next), brows(m.b_h, T)); + } else { + RAD_ISSUE(c, y.op_fpost1, brows(m.b_ff2, T), RAD_W(y.w_fpost1), brows(m.b_ff2, T)); + RAD_ISSUE(c, y.op_fpost2, brow_slice(m.b_ff2, T, T, E), RAD_W(y.w_fpost2), + brow_slice(m.b_ff2, T, T, E)); + RAD_ISSUE(c, y.op_fsum, brows(m.b_ff2, T), brow_slice(m.b_ff2, T, T, E), brows(m.b_h, T)); + RAD_ISSUE(c, y.op_fpost, brows(m.b_h, T), RAD_W(y.w_fpost), brows(m.b_h, T)); + } + } else { + if (y.op_ar_f) RAD_ISSUE_N(c, y.op_ar_f, T * E, brows(m.b_ff2, T), RAD_NONE); + RAD_ISSUE(c, y.op_fpost, brows(m.b_ff2, T), RAD_W(y.w_fpost), brows(m.b_h, T)); + } + if (!y.op_join_f) { + RAD_ISSUE(c, y.op_add_f, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T)); + RAD_ISSUE(c, y.op_scale, brows(m.b_x, T), RAD_W(y.w_scalar), brows(m.b_x, T)); + } + + /* The tap AFTER the scalar: HF's hidden_states[i + 1] is the decoder layer's return value, + * which has been multiplied by it. */ + for (int t = 0; t < m.n_taps && y.op_tap; ++t) { + if (m.tap_layer[t] != (int)li) continue; + RAD_ISSUE(c, y.op_tap, brows(m.b_x, T), + bcol(m.b_dfsrc, (int64_t)t * E, E, T)); + } + } + if (!lanes_ok) + rad_step_fail(c, "gemma4: the dense arm's second lane could not be ordered against the " + "first"); +} + +/* ============================================================== the prefill overlap */ +/* A PREFILL CHUNK IN TWO SLICES, each slice's all-reduces on the second lane (rad_lane) beside the + * other slice's compute. On gemma-4-26B-A4B at tp 4 on 4x R9700 the reductions were 47% of a + * 20K-token prefill under --profile-ops: a layer reduces T x E after attention and both arms' 2T x + * E after the feed-forward, at ~16.5 GB/s a rank on the link, against ~8 ms of compute a layer at + * the average chunk. Run whole, the two take turns. Cut in two, a slice's reduction runs while the + * other slice computes: + * + * lane 0 o(A) o(B) . nan(A) ff(A) . nan(B) ff(B) . jas(A) qkv(A) . jas(B) qkv(B) attn o(A) .. + * lane 1 ar_o(A) ar_o(B) ar_f(A) ar_f(B) + * + * ATTENTION RUNS WHOLE: it reads every row's keys, and its batch bounds describe the whole step. + * The rest is a row at a time -- the projections, the joins, both arms -- and so is the reduction, + * which folds a word in fp32 in ascending rank order whichever message carries it. + * + * THE SAME KERNELS, SO THE SAME BITS (core/runtime/ctx.h, the second lane's rule FOUR). A cut is + * a whole number of routed passes from the step's first row, so the routed arm makes exactly the + * passes the whole step makes, and both slices are at least one pass (2048 rows): above every row + * band the projections, the joins, the activation and the reduction have -- the GEMM's at 16 and + * 64, the reduction's one-shot edge at 524288 elements. None of those kernels' row results + * depends on the row count, so the step's output is the whole step's. + * + * THE ORDER. Every reduction rides lane 1 behind a join from lane 0, which holds its producer; + * lane 0 waits for lane 1 before the reduction's consumer. A join orders behind EVERYTHING its + * lane has issued, so each wait goes in after the lane-0 work that does not need it and before + * the next reduction is issued -- which is what fixes the issue order below. The embedding's + * reduction stays on lane 0, ahead of everything lane 1 is first joined behind, so the + * collectives keep one order on every rank; the runtime joins lane 1 back at the end of a step. */ + +/* The first row of slice B, or 0 for a step that runs whole: the whole number of routed passes + * nearest half the step. Both slices are then at least one pass. */ +static int64_t split_at(const Model& m, int64_t T) { + if (!m.overlap || T < 2 * m.moe_rows) return 0; + const int64_t P = m.moe_rows; + return P * ((T + P) / (2 * P)); +} + +/* Rows [r0, r0 + n) of a layer's projections: q|k|v on a sliding layer, q and k on a full one. */ +static void project(RadCtx* c, const Model& m, const Layer& y, int64_t r0, int64_t n) { + const RadOperand h = brow_slice(m.b_h, r0, n, m.E); + if (!y.full) { + RAD_ISSUE_N(c, y.op_qkv, n, h, RAD_W(y.w_qkv), + brow_slice(m.b_qkv, r0, n, m.ks.q() + 2 * m.ks.kv_dim())); + } else { + RAD_ISSUE_N(c, y.op_q, n, h, RAD_W(y.w_q), brow_slice(m.b_qf, r0, n, m.kf.q())); + RAD_ISSUE_N(c, y.op_k, n, h, RAD_W(y.w_k), brow_slice(m.b_kf, r0, n, m.kf.kv_dim())); + } +} + +/* Rows [r0, r0 + n) of the output projection. */ +static void out_proj(RadCtx* c, const Model& m, const Layer& y, int64_t r0, int64_t n) { + const int64_t q = y.full ? m.kf.q() : m.ks.q(); + RAD_ISSUE_N(c, y.op_o, n, brow_slice(y.full ? m.b_attf : m.b_atts, r0, n, q), RAD_W(y.w_o), + brow_slice(m.b_o, r0, n, m.E)); +} + +/* Rows [r0, r0 + n) from the attention join to the arms' partials, once those rows' attention + * reduction is in. The slice's partials land in rows [2 r0, 2 r0 + 2n) of the join, dense then + * routed, so its feed-forward reduction is one run. */ +static void arms(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t r0, int64_t n) { + const int64_t E = m.E, F = m.n_ff; + if (y.op_join_r) + RAD_ISSUE_N(c, y.op_join_r, n, brow_slice(m.b_o, r0, n, E), RAD_W(y.w_apost), + brow_slice(m.b_x, r0, n, E), RAD_W(y.w_fnorm), brow_slice(m.b_h, r0, n, E), + RAD_W(y.w_rscale), brow_slice(m.b_rn, r0, n, E), RAD_W(y.w_enorm), + brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK)); + else + RAD_ISSUE_N(c, y.op_join_a, n, brow_slice(m.b_o, r0, n, E), RAD_W(y.w_apost), + brow_slice(m.b_x, r0, n, E), RAD_W(y.w_fnorm), brow_slice(m.b_h, r0, n, E)); + RAD_ISSUE_N(c, y.op_gu, n, brow_slice(m.b_h, r0, n, E), RAD_W(y.w_gu), + brow_slice(m.b_gu, r0, n, 2 * F)); + RAD_ISSUE_N(c, y.op_act, n, bcol_at(m.b_gu, r0, 2 * F, 0, F, n), + bcol_at(m.b_gu, r0, 2 * F, F, F, n), brow_slice(m.b_act, r0, n, F)); + RAD_ISSUE_N(c, y.op_dn, n, brow_slice(m.b_act, r0, n, F), RAD_W(y.w_dn), + brow_slice(m.b_ff2, 2 * r0, n, E)); + routed(c, m, y, T, r0, n, 2 * r0 + n); +} + +/* Rows [r0, r0 + n) of layer li's feed-forward join, once their reduction is in -- with the next + * norm it writes -- and the drafter's taps of those rows. */ +static void join_ff(RadCtx* c, const Model& m, size_t li, int64_t r0, int64_t n) { + const Layer& y = m.layers[li]; + const int64_t E = m.E; + RAD_ISSUE_N(c, y.op_join_f, n, brow_slice(m.b_ff2, 2 * r0, n, E), RAD_W(y.w_fpost1), + brow_slice(m.b_ff2, 2 * r0 + n, n, E), RAD_W(y.w_fpost2), RAD_W(y.w_fpost), + brow_slice(m.b_x, r0, n, E), RAD_W(y.w_scalar), RAD_W(y.w_next), + brow_slice(m.b_h, r0, n, E)); + for (int t = 0; t < m.n_taps && y.op_tap; ++t) { + if (m.tap_layer[t] != (int)li) continue; + RAD_ISSUE_N(c, y.op_tap, n, brow_slice(m.b_x, r0, n, E), + bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * E, (int64_t)t * E, E, n)); + } +} + +static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int64_t cut) { + const int64_t T = batch->n_tok, E = m.E; + const int64_t a0 = 0, an = cut, b0 = cut, bn = T - cut; + bool lanes_ok = true; + /* An all-reduce in place over `rows` rows of `buf` from `row`, on lane 1 behind everything + * lane 0 has issued -- its producer among it. */ + auto reduce = [&](rad_op op, rad_buf buf, int64_t row, int64_t rows) { + lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK; + RAD_ISSUE_N(c, op, rows * E, brow_slice(buf, row, rows, E), RAD_NONE); + lanes_ok = rad_lane(c, 0) == RAD_OK && lanes_ok; + }; + /* Lane 0 behind every reduction issued so far. */ + auto join_back = [&] { lanes_ok = rad_lane_join(c, 1, 0) == RAD_OK && lanes_ok; }; + + const size_t L = m.layers.size(); + for (size_t li = 0; li < L; ++li) { + const Layer& y = m.layers[li]; + if (li == 0) { + RAD_ISSUE(c, y.op_anorm, brows(m.b_x, T), RAD_W(y.w_anorm), brows(m.b_h, T)); + project(c, m, y, a0, an); + project(c, m, y, b0, bn); + } else { + join_ff(c, m, li - 1, a0, an); /* its reduction was waited for last layer */ + project(c, m, y, a0, an); + join_back(); /* the last layer's feed-forward, slice B */ + join_ff(c, m, li - 1, b0, bn); + project(c, m, y, b0, bn); + } + attend(c, m, y, li, batch); + out_proj(c, m, y, a0, an); + reduce(y.op_ar_o, m.b_o, a0, an); + out_proj(c, m, y, b0, bn); + join_back(); /* attention, slice A */ + reduce(y.op_ar_o, m.b_o, b0, bn); + arms(c, m, y, T, a0, an); + join_back(); /* attention, slice B */ + reduce(y.op_ar_f, m.b_ff2, 2 * a0, 2 * an); + arms(c, m, y, T, b0, bn); + join_back(); /* the feed-forward, slice A */ + reduce(y.op_ar_f, m.b_ff2, 2 * b0, 2 * bn); + } + join_ff(c, m, L - 1, a0, an); + join_back(); /* the last feed-forward, slice B */ + join_ff(c, m, L - 1, b0, bn); + if (!lanes_ok) + rad_step_fail(c, "gemma4: the prefill overlap could not order its second lane against " + "the first"); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (batch->draft_pass != 0) { + if (!m.have_df) { + rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the " + "container carries no DFlash `draft.` block, or declare ran at " + "max_spec 0"); + return; + } + if (batch->draft_pass > 0) m.df.step(c, batch); + else m.df.context(c, batch); + return; + } + if (batch->enc) { + rad_step_fail(c, "gemma4 declares no encoder; serve this container with --mm-max-patches 0"); + return; + } + const int64_t T = batch->n_tok, E = m.E; + if (T <= 0) return; + + RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T)); + if (m.op_embed_ar) + RAD_ISSUE_N(c, m.op_embed_ar, T * E, brows(m.b_x, T), RAD_NONE); + + const int64_t cut = split_at(m, T); + if (cut > 0) trunk_overlap(c, m, batch, cut); + else trunk(c, m, batch); + + if (m.op_onorm) RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T)); + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T), + praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out)); + RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out), RAD_W(m.w_tok), + brows(m.b_logits, batch->n_out)); + if (m.op_cap) + RAD_ISSUE_N(c, m.op_cap, batch->n_out, brows(m.b_logits, batch->n_out), + brows(m.b_logits, batch->n_out)); + } +} + +/* ============================================================== probe */ +/* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less + * the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->draft_depth = 0; + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (da && std::strstr(da, "DFlash") && !std::strstr(da, "DFlash2")) { + long long bs = rad_meta_geti(meta, "draft.block_size", 0); + if (bs <= 0) bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); + if (bs > 1) { + out->draft_depth = (int)(bs - 1); + out->draft_depth_fixed = 1; + } + } + return RAD_OK; +} + +/* ============================================================== the reply format + * The model's, not this plugin's -- the thought channel, and calls written as a name and one + * object in Gemma's dialect of JSON -- and shared with gemma4_bf16 (arch/rad_gemma4_chat.h). The + * container's template is not visible from here (it lives in the vocab section, not the metadata), + * so this answers for every Gemma 4 container. */ +static const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_chat_format(); } + +} /* namespace gemma4 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PLUGIN(gemma4, "gemma4", "", "0.1.0", + "Gemma 4 text decoders (26B-A4B MoE, dense 31B), bf16: sliding and full attention " + "with proportional rope and K = V, a dense and a routed feed-forward side by side, " + "and z-lab's DFlash block-diffusion drafter") +RAD_ARCH_PROBE(gemma4) +RAD_ARCH_CHAT_FORMAT(gemma4) +#endif diff --git a/arch/gemma4/gemma4_dflash.h b/arch/gemma4/gemma4_dflash.h new file mode 100644 index 00000000..3fc58bc5 --- /dev/null +++ b/arch/gemma4/gemma4_dflash.h @@ -0,0 +1,686 @@ +/* gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4. + * + * ============================== WHAT IT IS ============================== + * + * rad_block_dflash2.h WITHOUT THE TWO THINGS DFLASH2 ADDED: the per-layer dynamic convolutions + * around attention and the feed-forward, and the candidate selector that walks a path through the + * block. What is left is the original DFlash: a small Qwen3-shaped transformer that denoises one + * anchor token plus `block - 1` mask tokens in ONE forward and reads every position's argmax off + * the TARGET's lm_head. + * + * context pass, one row a committed token: + * c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids))) + * for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v) + * + * query pass, `block` rows a sequence: + * x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below + * for each layer: + * h = input_layernorm(x) + * q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store + * x += o_proj(attention(q, cache)) sliding layers CAUSAL over a 2048 window, + * the full layer NON-causal over everything + * x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x) + * x = norm(x) + * over the mask rows: logits = lm_head(x) [the TARGET's]; draft = argmax + * + * ============================== THE THREE GEMMA-SPECIFIC FACTS ============================== + * + * They are vLLM PR #41703's, and each one costs acceptance and nothing else when it is wrong -- + * every draft is verified against the trunk, so the model's output never depends on any of them. + * + * THE EMBEDDING IS SCALED. Gemma multiplies its token embedding by sqrt(hidden_size), stored as a + * bf16 (53.0 at 2816), and the drafter was trained reading the target's embedding module, which + * applies it. `embed_lookup`'s `mult` carries it. + * + * THE SLIDING LAYERS ARE CAUSAL AND THE FULL LAYER IS NOT. The checkpoint's `layer_types` names + * four sliding layers and one full one; the PR's own test pins `causal True` on the sliding + * layers and `False` on the full one. So this block declares TWO attention ops and issues the + * one each layer's type names. + * + * THE LOGITS ARE SOFT-CAPPED, and that is ignored on purpose: the draft is an argmax, and + * cap * tanh(x / cap) is strictly increasing, so it cannot move one. + * + * ============================== THE HEAD ============================== + * + * The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma + * ties it to the embedding, so it is the same weight the trunk's `embed_lookup` and `logits_gemm` + * read: no extra bytes are stored. It is vocab-sharded with the trunk, so the top-1 runs over this + * rank's slice and the ranks' candidates are merged exactly (`row_topk` at R = 2 -> `all_gather` -> + * `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR). + * + * Reading the bf16 head every draft pass is the expensive way to do it -- 262144 x 2816 x 2 bytes + * over the ranks, 566 us of a 26B-A4B decode step at tp 4 (--profile-ops, 4x R9700), the widest + * read on the draft path. So where the CONTAINER holds a block-fp8 copy of the table under a name + * of its own -- `dflash.draft_head.weight`, one checkpoint tensor and two logical weights, as + * rad_block_dflash2.h does it, made by a recipe line + * + * dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + * + * -- the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, and the argmax is taken over + * its coarser logits. Every draft is still verified, so the copy can change what is proposed and + * never what is accepted; draft_n_accepted is what says whether it proposes worse. A container + * without it, or with it in any other encoding, reads the bf16 table as before. The copy costs + * half the table's bytes again, 176 MiB a rank at tp 4. No rerank against the bf16 table yet: + * DFlash2's needs the target's head in fp8 or int8, which a tied Gemma head is not. + * + * ============================== THE LINEARS ARE FP8 ============================== + * + * The same as DFlash2 and for the same reason -- the drafter is read whole on every decode step -- + * so the container must be converted with a recipe that makes the six linears block fp8 (or + * MXFP4). declare() refuses a bf16 one by name rather than letting the loader fail on a view. + */ +#ifndef GEMMA4_DFLASH_H +#define GEMMA4_DFLASH_H + +#include +#include + +#include +#include + +namespace gemma4 { + +using namespace rad::arch; + +/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale a 128x128 block, no + * transform -- a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`. */ +inline bool block_fp8_128(const RadEncoding& e) { + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] && + e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 && + sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK; +} + +struct Dflash1 { + enum { MAX_LAYERS = 8 }; + + struct Config { + int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */ + int64_t block = 0; /* query rows a sequence: the anchor plus block - 1 masks */ + int64_t window = 0; /* the sliding layers' window; 0 for none */ + int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */ + double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */ + int64_t steps() const { return block - 1; } + }; + + struct Wire { + /* the context pass */ + rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | e4m3 | f32 */ + rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */ + rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */ + /* the query pass */ + rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */ + rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */ + rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */ + rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */ + rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */ + /* the head, one row a draft position */ + rad_buf sel_h = 0; /* [srows, n_embd] */ + rad_buf selq = 0, sels = 0; /* [srows, n_embd] e4m3 | f32, the fp8 head's */ + rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */ + rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */ + rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */ + rad_buf tokens = 0; /* [srows, 1] i32: THE DRAFT, pitch `steps` */ + }; + + Geom g{}; /* the drafter's geometry */ + Config cfg{}; + Wire w{}; + int first_layer = 0; + int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0; + rad_kvgroup kv = 0; + bool sharded = false; + + DenseFP8 w_fc{}; + rad_weight w_hnorm = 0, w_norm = 0; + rad_weight w_tok = 0; /* the TARGET's table: embedding AND head */ + DenseFP8 w_dh{}; /* its block-fp8 copy, the head where it is stored */ + bool fp8_head = false; + rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {}; + DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{}; + rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}; + DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{}; + + rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0; + rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {}; + + rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0; + rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}; + /* THE RESIDUAL ADD, THE NORM AND THE QUANTISER IN ONE LAUNCH where `rmsnorm_quant_fp8` is + * served (libr4d): op_anq[i] the attention input's -- layer 0's with no add, x as the + * embedding left it -- and op_fnq[i] the feed-forward input's. Zero where it is not, and the + * `add` / `rmsnorm` / `quant_act_fp8` chain is issued instead. */ + rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {}; + rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {}; + rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}; + rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; + rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0; + rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; + rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0; + + /* CANDIDATES A RANK CONTRIBUTES under a sharded head. The draft needs one, but the gather moves + * whole 16-byte words a row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is refused at + * launch ("shape this kernel does not serve") -- the bound rad_block_mtp_hc.h states. Two pairs + * are one word; `pair_argmax` reduces the world * 2 of them to the global top-1. */ + static constexpr int64_t kTopR = 2; + + static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); } + + int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer, + rad_kvgroup group, rad_weight tok_embd, const char* ck, const Wire& wire, + const char* tok_src); + void context(RadCtx* c, const RadBatch* batch) const; + void step(RadCtx* c, const RadBatch* batch) const; + +private: + int64_t q_dim() const { return g.n_head * g.head_dim; } + int64_t kv_dim() const { return g.n_head_kv * g.head_dim; } + /* The six linears must be what the recipe made them. DenseFP8 declares E4M3 (or MXFP4) views + * whatever the container holds, and the loader's complaint about a bf16 weight read through an + * fp8 view names the view, not the missing recipe. */ + static int need_quantised(RadBuilder* b, const char* wn) { + RadEncoding e{}; + if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */ + const uint32_t dt = e.plane[0].dtype; + if (dt == RAD_F8E4M3 || dt == RAD_FP4E2M1) return RAD_OK; + fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its six linears " + "are served block fp8 (or MXFP4): convert with a recipe that names them, " + "e.g. `dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 " + "scale=bf16` and the same for fc, attn_k/v/output, ffn_gate_up and " + "ffn_down.\n", wn, rad_dtype_name(dt)); + return RAD_E_DTYPE; + } +}; + +/* ------------------------------------------------------------------------------ declare */ + +inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, + int base_layer, rad_kvgroup group, rad_weight tok_embd, + const char* ck, const Wire& wire, const char* tok_src) { + g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd; + if (!ck || !w_tok || !tok_src) return RAD_E_INVAL; + if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) { + fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most " + "%d\n", (long long)g.n_layer, MAX_LAYERS); + return RAD_E_UNSUPPORTED; + } + if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL; + + const int64_t qd = q_dim(), kvd = kv_dim(); + crows = g.max_tok; + qrows = g.max_seqs * cfg.block; + if (qrows > g.max_tok) qrows = g.max_tok; + srows = g.max_seqs * cfg.steps(); + if (qrows <= 0 || srows <= 0) return RAD_E_INVAL; + sharded = head_sharded(g); + + /* ---------------------------------------------------------------- model-scope weights */ + RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(), + { nm.ckpt("%s.fc.weight", ck) })); + RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck))); + w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + + /* ---------------------------------------------------------------- per-layer weights */ + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + const RadWeightGroup gl = grp_layer(first_layer + i); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i), + nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), + nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), + nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), + nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i))); + w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + /* The declared names are rad_block_dflash2.h's, deliberately: the recipe that quantises a + * DFlash2 drafter's linears names exactly these, so one recipe serves both drafters. */ + RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, + { nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff, + g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i), + nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) }, + { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, + { nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) })); + for (const char* s : { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up", + "ffn_down" }) + RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, s))); + } + + /* ---------------------------------------------------------------- attention: two kinds + * Declared before either kv_store: `block_size` is read back off the resolved kernel. Both + * read the one KV group, so whichever resolves first answers for it. */ + auto attn = [&](int causal, int64_t window) { + return rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", causal), + RAD_INT("window", window), RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.q}, {w.attn}); + }; + bool any_full = false, any_swa = false; + for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true; + if (any_swa) op_attn_swa = attn(1, cfg.window); + if (any_full) op_attn_full = attn(0, 0); + + /* ---------------------------------------------------------------- the context pass */ + op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.src}, {w.srcq, w.srcs}); + op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c}); + op_cnorm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_hnorm)), + {w.c}, {w.c}); + op_qc = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.c}, {w.cq, w.cs}); + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck}); + op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv}); + op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_kn[i])), + {w.ck}, {w.ck}); + } + op_crope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.ck}, {w.ck}); + op_cstore = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.ck, w.cv}, {}); + + /* ---------------------------------------------------------------- the query pass */ + op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)), + RAD_WEIGHTS(w_tok)), + {}, {w.x}); + if (g.world > 1) + op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {w.x}, {w.x}); + op_qh = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.h}, {w.hq, w.hs}); + op_qat = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.attn}, {w.atq, w.ats}); + op_qff = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.ffn}, {w.ffq, w.ffs}); + + /* x's norm under `gain`, quantised into hq|hs, in one launch; with `add` the fused_add_rms_norm + * form, x += h first. The row is the chain's function exactly -- the norm of the bf16-rounded + * sum, the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp) -- and a draft is verified + * whatever it is. */ + auto norm_quant = [&](rad_weight gain, bool add) -> rad_op { + const rad_op h = RAD_OP(b, "rmsnorm_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)), + RAD_WEIGHTS(gain)); + return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs}); + }; + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_anorm[i])), + {w.x}, {w.h}); + op_anq[i] = norm_quant(w_anorm[i], l > 0); + op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q}); + op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k}); + op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v}); + op_qn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_qn[i])), + {w.q}, {w.q}); + op_kn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_kn[i])), + {w.k}, {w.k}); + op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h}); + op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_fnorm[i])), + {w.x}, {w.h}); + op_fnq[i] = norm_quant(w_fnorm[i], true); + op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up}); + /* The gate_up|silu|quant fold where it resolves, the pair where it does not -- + * rad_block_dflash2.h's rule, band included. */ + { + const int64_t hi = qrows < 64 ? qrows : 64; + if (hi > 0 && !w_gu[i].mx) { + op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff), + RAD_INT("K", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")), + RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)), + {w.hq, w.hs}, {w.ffq, w.ffs}); + if (op_gug[i]) gated_rows = hi; + } + } + op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h}); + } + op_qrope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.q}, {w.q}); + op_krope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.k}, {w.k}); + op_store = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.k, w.v}, {}); + op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.gate_up}, {w.ffn}); + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + op_final = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + + /* ---------------------------------------------------------------- the head + * The MASK rows -- offsets 1..block-1 of each block; the core names them through out_ids -- + * gathered contiguous, projected onto THIS RANK's slice of the target's vocabulary, and the + * argmax taken. Sharded, each rank's best kTopR are reported as global ids with their logits, + * all-gathered, and reduced to the global top-1 by `pair_argmax`, ties to the lower id -- exact, + * since the global winner is its own shard's first. */ + op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.h}, {w.sel_h}); + /* THE FP8 COPY, where the container holds one (see the top of this file). The name map comes + * first -- it is how the encoding is looked up -- and a map whose weight is never declared is + * written by nothing: rad-convert walks the declared weights. The copy is row-sharded exactly + * as the table is, so this rank's rows are the same vocabulary slice and `vocab_off` holds. */ + const char* dhn = nm.f("dflash.draft_head.weight"); + RAD_ARCH_TRY(map_copy(b, dhn, tok_src)); + RadEncoding he{}; + fp8_head = weight_enc(b, dhn, &he) && block_fp8_128(he); + if (fp8_head) { + if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: gemma4: the fp8 draft head is %lldx%lld a rank, which " + "is not whole %d-row scale blocks\n", + (long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE; + w_dh.w = decl_view(b, dhn, nullptr, "codes", RAD_F8E4M3, { g.n_vocab, g.n_embd }, + RAD_ACCESS_PER_TOKEN, shard, grp_model()); + w_dh.s = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16, + { fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN, + shard, grp_model()); + if (!w_dh.w || !w_dh.s) return RAD_E_INVAL; + w.selq = decl_b(b, nm.f("df_selq"), RAD_F8E4M3, {srows, g.n_embd}); + w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, {srows, fp8_blocks(g.n_embd)}); + op_qsel = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.sel_h}, {w.selq, w.sels}); + op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog}); + } else { + op_head = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_tok)), + {w.sel_h}, {w.dlog}); + } + if (sharded) { + op_topk = rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.dlog}, {w.cand, w.unary, w.dpair}); + /* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side. */ + op_dgather = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"), + RAD_INT("row", kTopR * 2)), + RAD_NOWEIGHTS), + {w.dpair}, {w.dgath}); + op_pick = rw(b, RAD_OP(b, "pair_argmax", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {w.dgath}, {w.tokens}); + if (!op_pick) { + fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the " + "device, and no loaded kernel library serves it there\n"); + return RAD_E_UNSUPPORTED; + } + } else { + op_topk = rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("R", 1), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.dlog}, {w.tokens, w.unary}); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------------------ the context pass */ + +inline void Dflash1::context(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (T <= 0) return; + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + + RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T)); + RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s), + brows(w.c, T), RAD_NONE, w_fc.bref()); + RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T)); + RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T)); + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T), + RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref()); + RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T), + RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref()); + RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]), + brows(w.ck, T)); + RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T)); + RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T), praw(slot, RAD_I32, T), + kv_cache(kv, first_layer + i)); + } +} + +/* ------------------------------------------------------------------------------ the query pass */ + +inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (T <= 0) return; + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + + RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T)); + if (op_embed_ar) + RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE); + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa; + + /* The attention input, with the last layer's residual add where one launch takes both. */ + if (op_anq[i]) { + RAD_ISSUE_N(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T), + l > 0 ? brows(w.x, T) : RAD_NONE, RAD_W(w_anorm[i]), brows(w.hq, T), + brows(w.hs, T), RAD_NONE); + } else { + RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); + RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); + } + RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref()); + RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref()); + RAD_ISSUE_N(c, op_vp[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref()); + RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T)); + RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T)); + RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T)); + RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T)); + RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), + kv_cache(kv, first_layer + i)); + RAD_ISSUE_N(c, op_attn, batch->max_q_len, + brows(w.q, T), kv_cache(kv, first_layer + i), + praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), + praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE, + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T)); + RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T)); + RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T), + RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref()); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + if (op_fnq[i]) { + RAD_ISSUE_N(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), RAD_W(w_fnorm[i]), + brows(w.hq, T), brows(w.hs, T), RAD_NONE); + } else { + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); + RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); + RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); + } + if (op_gug[i] && T <= gated_rows) { + RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T), + RAD_NONE); + } else { + RAD_ISSUE_N(c, op_gu[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE, + w_gu[i].bref()); + RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T)); + RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T)); + } + RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T), + RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref()); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + /* the residual add, unless the next layer's input norm takes it */ + if (l + 1 == g.n_layer || !op_anq[i + 1]) + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); + } + RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + + const int64_t S = batch->n_out; + if (S <= 0) return; + RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S)); + if (fp8_head) { + RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S)); + RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w), + RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref()); + } else { + RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S)); + } + if (sharded) { + RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S), + brows(w.dpair, S)); + RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S)); + RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE); + } else { + RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S), + RAD_NONE); + } +} + +} /* namespace gemma4 */ + +#endif /* GEMMA4_DFLASH_H */ diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 2549d404..7ffed45d 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -9,8 +9,7 @@ * cap * tanh(x / cap). */ #include - -#include "gemma4_chat_format.h" +#include #include #include @@ -1543,8 +1542,8 @@ static void step(RadCtx* c, const RadBatch* batch) { } } -/* The reply format: gemma4_chat_format.h. */ -const RadChatFormat* chat_format(const RadModelMeta*) { return chat_format_decl(); } +/* The reply format: the model's, shared with arch/gemma4 (arch/rad_gemma4_chat.h). */ +const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_chat_format(); } /* WHAT THIS CONTAINER'S HEAD IS WORTH SPECULATING TO, for `--num-speculative-tokens auto`. A serial * head names an operating point, not a trained depth: one more round is one more pass of the head, diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 2dd5e6e0..2fc8d50f 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -130,6 +130,7 @@ public: rad_op decl_op (const char* op, const RadParam* p, int n_p, const rad_weight* w, int n_w); int op_resolved (rad_op h) const; + int op_declared (const char* op) const; int decl_name_map(const RadNameMap* m); int declare_logits(rad_buf b); int declare_pooled(rad_buf b); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 6e04d262..6f48a91c 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -835,6 +835,10 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, return resolved ? h : RAD_NULL_HANDLE; } +int Builder::op_declared(const char* op) const { + return op && reg_.schema(op) ? 1 : 0; +} + int Builder::op_resolved(rad_op h) const { if (h == 0 || h >= prog_.ops.size()) return 0; const OpInfo& o = prog_.ops[h]; @@ -1749,6 +1753,11 @@ int rad_op_resolved(RadBuilder* b, rad_op h) { return B(b)->op_resolved(h); } +int rad_op_declared(RadBuilder* b, const char* op) { + if (!b) return 0; + return B(b)->op_declared(op); +} + /* Proposed additions to rad_builder.h -- defined here so the mechanism exists and core-side * callers (rad-convert, the tests) can use it. A C plugin cannot until the declarations * move into the frozen header. */ diff --git a/core/config.cpp b/core/config.cpp index 71347377..689febe6 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -72,6 +72,10 @@ static const Flag g_flags[] = { " pins it in host memory beside --host-pool-mib, read over the\n" " link in place; by default a model whose output head reads the\n" " table, or a host without the memory, keeps it on the card" }, + { "--vision-tower-placement", "WHERE", "vram (default) | ram: where the encoder towers live (the\n" + " vision tower; the audio encoder too). ram pins them in host\n" + " memory beside --host-pool-mib, read over the link once an\n" + " image, and gives their VRAM to the KV cache" }, { "--ngram-placement", "WHERE", "auto (default) | vram | ram | disk: where an n-gram\n" " embedding table lives (Qwen3.8-Flash-Next: 47.7 GiB).\n" " vram puts all of it on every card; ram copies it into\n" @@ -82,16 +86,13 @@ static const Flag g_flags[] = { { "--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" }, - { "--prefix-cache-host-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n" + { "--prefix-cache-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" - " snapshots on a hybrid or sliding-window model;\n" - " startup says how many" }, - { "--prefix-cache-dir", "DIR", "where the disk tier keeps them. Not --weights-disk-tier, which is\n" - " about WEIGHTS" }, - { "--prefix-cache-disk-mib", "N", "and copy them on to disk under --prefix-cache-dir, up to N MiB,\n" - " so a full host tier gives slots up for nothing. Holds\n" - " conversation content unencrypted. 0 is off" }, + " instead of re-prefilling. A full tier drops its least\n" + " recently used entries. 0 is off" }, + { "--prefix-cache-ttl", "S", "seconds a cached conversation no request uses is kept, in VRAM\n" + " or host memory (default 3600). 0 keeps it until the memory\n" + " is wanted" }, { "--placement", "MODE", "all_vram | layer_offload | expert_tiered | auto" }, { "--deterministic", nullptr, "pin placement to the plan the loader made, so the resident\n" @@ -469,7 +470,12 @@ int config_parse(int argc, char** argv, Config* c) { * ram the default wherever it can be honoured, nothing left for auto to choose. */ if (emb && (!parse_table_placement(v, &p) || (p != TablePlacement::Ram && p != TablePlacement::Vram))) { - RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v); + if (parse_table_placement(v, &p) && p == TablePlacement::Auto) + RAD_ERR("--embedding-placement auto was removed in 1.3.0: ram, the default, " + "holds the table in pinned host memory, and vram keeps it on the card. " + "Drop the flag or name one of the two"); + else + RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v); return RAD_E_INVAL; } if (!emb && !parse_table_placement(v, &p)) { @@ -479,10 +485,35 @@ int config_parse(int argc, char** argv, Config* c) { (emb ? c->embedding_placement : c->ngram_placement) = p; if (emb) c->embedding_placement_given = true; } + else if (S("--vision-tower-placement")) { + if (!(v = need(i))) return RAD_E_INVAL; + TablePlacement p; + /* Two tiers, for the embedding's reason: an encoder writes activations the card reads. */ + if (!parse_table_placement(v, &p) || (p != TablePlacement::Ram && p != TablePlacement::Vram)) { + RAD_ERR("--vision-tower-placement takes vram or ram, not '%s'", v); + return RAD_E_INVAL; + } + c->tower_placement = p; + } else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; } - 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); } + else if (S("--prefix-cache-mib")) { if (!(v = need(i)) || + !parse_int(a.c_str(), v, 0, INT32_MAX, &c->prefix_cache_mib)) + return RAD_E_INVAL; } + else if (S("--prefix-cache-ttl")) { if (!(v = need(i)) || + !parse_int(a.c_str(), v, 0, INT32_MAX, &c->prefix_cache_ttl)) + return RAD_E_INVAL; } + /* THE PREFIX CACHE KEEPS NOTHING ON A DRIVE: a tier there wore it at the rate the server + * prefills, and its copies never outlived the process. The old size flags are told what + * replaced them rather than "unknown option". */ + else if (S("--prefix-cache-host-mib")) { + RAD_ERR("--prefix-cache-host-mib was renamed: use --prefix-cache-mib"); + return RAD_E_INVAL; + } + else if (S("--prefix-cache-dir") || S("--prefix-cache-disk-mib")) { + RAD_ERR("%s was removed: the prefix cache is kept in VRAM and host memory only " + "(--prefix-cache-mib), and --prefix-cache-ttl says how long", a.c_str()); + return RAD_E_INVAL; + } else if (S("--placement")) { if (!(v = need(i))) return RAD_E_INVAL; c->placement = v; } else if (S("--deterministic")) c->deterministic = true; else if (S("--checkpoint-interval")) { if (!(v = need(i))) return RAD_E_INVAL; c->checkpoint_interval = atoll(v); } @@ -918,12 +949,12 @@ const ShowRow kShow[] = { { "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } }, { "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } }, { "--ngram-placement", [](const Config& c) { return std::string(table_placement_name(c.ngram_placement)); } }, + { "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } }, { "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } }, - { "--prefix-cache-host-mib", [](const Config& c) { - return c.prefix_cache_host_mib ? num(c.prefix_cache_host_mib) : std::string("0 (off)"); } }, - { "--prefix-cache-dir", [](const Config& c) { return or_none(c.prefix_cache_dir, "none"); } }, - { "--prefix-cache-disk-mib", [](const Config& c) { - return c.prefix_cache_disk_mib ? num(c.prefix_cache_disk_mib) : std::string("0 (off)"); } }, + { "--prefix-cache-mib", [](const Config& c) { + return c.prefix_cache_mib ? num(c.prefix_cache_mib) : std::string("0 (off)"); } }, + { "--prefix-cache-ttl", [](const Config& c) { + return c.prefix_cache_ttl ? num(c.prefix_cache_ttl) + " s" : std::string("0 (never)"); } }, { "--placement", [](const Config& c) { return c.placement; } }, { "--deterministic", [](const Config& c) { return onoff(c.deterministic); } }, { "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } }, diff --git a/core/device/directio.cpp b/core/device/directio.cpp index 0d159968..7841dbde 100644 --- a/core/device/directio.cpp +++ b/core/device/directio.cpp @@ -181,9 +181,7 @@ int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) { /* ------------------------------------------------------------------ write */ -/* The store is written to as well as read: the SSD prefix-cache tier (core/mem/sstier.cpp) - * publishes blocks, and the SSD weight tier is populated once at load. Both write whole aligned - * slots, so this has the same shape as read_at -- one fast path, and a read-modify-write for +/* The same shape as read_at -- one fast path for whole aligned blocks, and a read-modify-write for * anything that does not cover a whole block. */ int DirectFile::write_at(const void* src, int64_t off, int64_t bytes) { if (fd_ < 0) return RAD_E_STATE; diff --git a/core/device/directio.h b/core/device/directio.h index 3f51ca6a..52aa5488 100644 --- a/core/device/directio.h +++ b/core/device/directio.h @@ -30,11 +30,11 @@ enum { /* Open buffered when the filesystem refuses O_DIRECT, instead of failing the open. * - * Off by default, and that default is the point. The weight tier and the prefix cache are - * sized in gigabytes and read in megabyte runs; a silent buffered fallback turns both into a - * page-cache pump that is three times slower and looks like nothing at all in a profile. An - * operator who pointed --prefix-cache-dir at tmpfs wants to be told, not accommodated. The flag is - * for tests, which have to run on whatever /tmp happens to be. */ + * Off by default, and that default is the point. The weight tier is sized in gigabytes and + * read in megabyte runs; a silent buffered fallback turns it into a page-cache pump that is + * three times slower and looks like nothing at all in a profile. An operator whose container + * sits on tmpfs wants to be told, not accommodated. The flag is for tests, which have to run + * on whatever /tmp happens to be. */ RAD_DIO_ALLOW_BUFFERED = 16, }; diff --git a/core/diag/checks.cpp b/core/diag/checks.cpp index 0d7c25cb..2c407d58 100644 --- a/core/diag/checks.cpp +++ b/core/diag/checks.cpp @@ -302,7 +302,7 @@ void check_memory(const Facts& f, const RunFacts& r, std::vector* out) "the page cache is what a container read in place and the n-gram rows read from disk " "come through; with it starved every step waits on the drive, and the kernel starts " "reclaiming and swapping", - "lower --host-pool-mib or --prefix-cache-host-mib, or stop what else holds memory"); + "lower --host-pool-mib or --prefix-cache-mib, or stop what else holds memory"); if (h.swap_total > 0 && h.swap_free >= 0 && h.swap_total - h.swap_free > 256 * kMiB) add(out, Finding::Note, "swap-in-use", fmt("%s of swap is in use", humanb(h.swap_total - h.swap_free).c_str()), diff --git a/core/diag/diag.h b/core/diag/diag.h index 3cd3c780..92a582e7 100644 --- a/core/diag/diag.h +++ b/core/diag/diag.h @@ -167,7 +167,6 @@ struct RunFacts { /* Why the engine turned prefix caching off itself (the KL mode, an embedding model); "" when * it is on or the operator turned it off. */ std::string prefix_cache_off_why; - int64_t prefix_host_mib = 0, prefix_disk_mib = 0; int64_t host_pool_mib = 0; /* a rank, as configured */ int64_t pinned_bytes = -1; /* every pinned host allocation the process made */ int64_t host_weight_bytes = 0; /* weights a rank reads from the pinned host pool */ diff --git a/core/engine.cpp b/core/engine.cpp index 1dd5a67a..160636c2 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -66,9 +66,6 @@ Engine::~Engine() { for (float* p : kld_host_) if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED); if (pooled_host_) rad_dev_free(pooled_host_, RAD_MEM_HOST_PINNED); for (auto& r : ranks_) if (r->score_host) rad_dev_free(r->score_host, RAD_MEM_HOST_PINNED); - /* The disk thread first: it reads the host arena and writes the store, both of which go with - * the ranks and kv_disk_ below. */ - if (pump_) pump_->io.stop(); /* WHAT THE TIERING ACTUALLY DID, and it is printed here for the same reason: this is the last * moment the plan the rows name is still alive. Only when the plan was dynamic -- a static * one has nothing to say and a banner saying nothing is a banner people learn to skip. The @@ -503,6 +500,7 @@ int Engine::step_loop() { sched_.release_deferred(); } tier_tick(); + expire_tick(rad_mono_ns()); loan_tick(/*idle=*/true); /* RADIANCE_DEBUG_IDLE_SCRUB -- a DIAGNOSTIC, not a fix, and the one question it * answers is whether request N+1 differs from request N because of bytes request N @@ -948,7 +946,9 @@ int Engine::step_loop() { sched_.step_finished(); tier_tick(); loan_tick(/*idle=*/false); - arena_tick(rad_mono_ns()); + const uint64_t now = rad_mono_ns(); + arena_tick(now); + expire_tick(now); drain_completed(); sched_.publish(/*idle=*/false); @@ -1305,9 +1305,8 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) { /* EVERY ITERATION, ON BOTH PATHS. A copy to host memory is asynchronous and reported when its * event has signalled, so the tick that collects it is simply the first one after it landed; the * next copy is handed out on the same tick. Tying either to a slower clock would only delay the - * moment a finished conversation's VRAM can be given up. The disk half runs once a second -- its - * thresholds are measured in minutes -- and at once when the host tier has refused a copy for - * want of room, since that copy is waiting on it. + * moment a finished conversation's VRAM can be given up. Room in a full arena is made at once + * when the host tier has refused a copy for want of it, since that copy is waiting on it. * * THE SCHEDULER'S LOCK IS HELD FOR THE BOOKKEEPING ONLY. Planning a batch and reporting one touch * rank 0's manager, the prefix cache and -- through the tiers' drop sinks -- the index an HTTP @@ -1486,42 +1485,6 @@ void Engine::tier_tick() { } } - /* ---- reads off disk that have landed --------------------------------------------------- */ - /* THEIR REQUESTS GO NEXT STEP: the records are host records now, held for them, and the - * admission that asks again restores them out of host memory. */ - { - TierIO::Fetch f; - while (P.io.take_fetch(&f)) { - destroy_fences(f.fences); - const auto lk = sched_.hold(); - lead.tierx.report_pass(f.jobs, f.ok, now); - /* A SNAPSHOT READ BACK INTO ITS SLOT goes to the cache's index entry, which the lookup - * then serves. One whose entry went while the read was out has nothing to land in, and - * the record must not go on naming a slot the store will hand to somebody else. */ - for (const TierJob& j : f.jobs) { - if (!j.ck_want || j.ck_slot < 0 || !lead.tiers.snapshot_in_slot(j.key, j.ck_slot)) - continue; - if (lead.prefix.reattach_snapshot(j.key, j.ck_slot) != RAD_OK) { - lead.tiers.snapshot_detached(j.key); - lead.kv.free_checkpoint(j.ck_slot); - } - } - P.waiting.erase(std::remove(P.waiting.begin(), P.waiting.end(), f.tag), P.waiting.end()); - } - } - - /* ---- the disk batch the thread finished ------------------------------------------------ */ - { - std::vector jobs; - std::vector ok; - std::vector fences; - if (P.io.take(&jobs, &ok, &fences)) { - destroy_fences(fences); - const auto lk = sched_.hold(); - lead.tierx.report_pass(jobs, ok, now); - } - } - /* ---- the next copy ---------------------------------------------------------------------- */ if (P.copy.empty() && lead.tiers.writeback_waiting()) { { @@ -1554,68 +1517,27 @@ void Engine::tier_tick() { if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean(); } - /* ---- the slow half ---------------------------------------------------------------------- */ - /* AS SOON AS A DISK COPY IS WAITING, not on the clock: until it lands, the entry's host slot - * cannot be given up for nothing, and a full arena is then a restore that cannot read through - * it. The thread takes one batch at a time, so this is also as fast as the disk takes them. */ - if (!P.io.busy() && (lead.tiers.disk_waiting() || lead.tiers.starved() || - now - tier_last_ns_ >= 1000000000ull)) { - tier_last_ns_ = now; + /* ---- capacity ---------------------------------------------------------------------------- */ + /* WHEN THE ARENA HAS REFUSED A COPY: the oldest host-only entries make room for it. The drops + * move no bytes, so the plan is reported as soon as it is made. */ + if (lead.tiers.starved()) { std::vector jobs; lead.tiers.plan(P.slow_budget, &jobs); - /* A SNAPSHOT'S SLOT IS FILLED BY A COPY ON THE COMPUTE STREAM, issued after the step that - * produced the state and before the cache was told of it; the write waits for that copy to - * land, and every one of its kind is behind this mark. */ - bool snaps = false; - for (const TierJob& j : jobs) snaps = snaps || j.ck_slot >= 0; - int fst = RAD_OK; - std::vector fences = snaps ? rank_fences(false, true, &fst) - : std::vector{}; - /* A mark that could not be made leaves nothing to order the write by: the batch is - * reported failed, and every record keeps what it had. */ - if (fst != RAD_OK) { - destroy_fences(fences); - const std::vector ok(jobs.size(), 0); - const auto lk = sched_.hold(); - lead.tierx.report_pass(jobs, ok, now); - return; - } - if (!jobs.empty() && !P.io.submit(std::move(jobs), std::move(fences))) { - destroy_fences(fences); - /* The thread is not running -- no disk tier -- and a plan without one holds only drops, - * which move nothing. They are reported here. */ - std::vector ok(jobs.size(), 1); + if (!jobs.empty()) { + const std::vector ok(jobs.size(), 1); const auto lk = sched_.hold(); lead.tierx.report_pass(jobs, ok, now); } } } -std::vector Engine::rank_fences(bool transfer, bool compute, int* st) { - std::vector out; - int rc = RAD_OK; - for (int pass = 0; pass < 2; ++pass) { - if ((pass == 0 && !transfer) || (pass == 1 && !compute)) continue; - for (auto& r : ranks_) { - RadEvent e = nullptr; - const int s = r->tierx.fence(&e, pass == 1 ? r->ctx.stream() : nullptr); - if (s != RAD_OK && rc == RAD_OK) rc = s; - out.push_back(e); - } - } - if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); - if (st) *st = rc; - return out; -} - -void Engine::destroy_fences(std::vector& f) { - for (size_t i = 0; i < f.size(); ++i) { - if (!f[i]) continue; - (void)rad_dev_set(ranks_[i % ranks_.size()]->device); - rad_event_destroy(f[i]); - } - f.clear(); - if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); +void Engine::expire_tick(uint64_t now_ns) { + if (cfg_.prefix_cache_ttl <= 0 || now_ns - expire_last_ns_ < 1000000000ull) return; + expire_last_ns_ = now_ns; + PrefixCache& pc = ranks_[0]->prefix; + if (!pc.enabled()) return; + const auto lk = sched_.hold(); + (void)pc.expire(now_ns, (uint64_t)cfg_.prefix_cache_ttl * 1000000000ull); } bool Engine::flush_copies() { @@ -1659,34 +1581,6 @@ bool Engine::flush_copies() { return landed; } -/* HAND A READ OFF DISK TO THE IO THREAD, fenced on every rank's transfer stream: the slots it - * writes may have been given up by entries a restore is still copying out of. False when it could - * not be handed over, and then the reads are reported unstarted -- the records stay on disk and the - * request is admitted with what the host tier holds. */ -bool Engine::submit_fetch(uint64_t tag, std::vector&& jobs) { - TierPump& P = *pump_; - TierIO::Fetch f; - f.tag = tag; - f.jobs = std::move(jobs); - /* THE TRANSFER STREAMS, for the restores that read block slots, and THE COMPUTE STREAMS when a - * snapshot comes in: its store slot may have been given up by a snapshot a restore on that - * stream is still copying out of. */ - bool snap = false; - for (const TierJob& j : f.jobs) snap = snap || (j.ck_want && j.ck_slot >= 0); - int st = RAD_OK; - f.fences = rank_fences(true, snap, &st); - if (st == RAD_OK && P.io.submit_fetch(std::move(f))) { - P.waiting.push_back(tag); - return true; - } - RAD_ERR("kv tiers: a read off disk could not be handed to the IO thread (%s); the request is " - "admitted with what host memory holds", st < 0 ? rad_strerror(st) : "not running"); - destroy_fences(f.fences); - const std::vector ok(f.jobs.size(), 0); - ranks_[0]->tierx.report_pass(f.jobs, ok, rad_mono_ns()); - return false; -} - void Engine::drain_completed() { /* TAKEN, NOT READ. The list is appended to by HTTP threads' cancels, so walking it by * reference would race them; and nothing else consumes it -- the server learns of a terminal @@ -1788,42 +1682,13 @@ int Engine::serve() { /* CALLED FROM INSIDE Scheduler::step(), UNDER ITS LOCK -- which is what makes it safe to * touch the cache and rank 0's manager here, and why nothing below may call back into the * scheduler. */ - b->restore_fn = [this](const Request& req) -> IPrefixCache::Restore { - using R = IPrefixCache::Restore; + b->restore_fn = [this](const Request& req) { const uint64_t t0 = rad_mono_ns(); PrefixCache& pc = ranks_[0]->prefix; - TierPump& P = *pump_; - if (std::find(P.waiting.begin(), P.waiting.end(), req.id) != P.waiting.end()) - return R::Wait; - std::vector chain; std::vector mk; media_keys(req, &mk); - const std::vector want = pc.restorable_from(req.prompt, mk, &chain); - /* THE DISK PART IS READ FIRST, ON THE IO THREAD, while this request waits and every - * other one runs; the restore below then copies host memory and nothing else. Asked - * on every attempt, because a chain wholly in VRAM can still want a read: its deepest - * snapshot may have given its store slot up and be on disk alone. - * - * THAT SNAPSHOT NEEDS A STORE SLOT TO LAND IN, and the store's free list is rank 0's - * manager's: one is taken here -- making room by detaching a snapshot the disk also - * holds, which is the cache's choice -- and handed to the plan, which gives it back - * when it does not read the snapshot after all. */ - { - std::vector reads; - int32_t ck = -1; - if (ranks_[0]->tiers.snapshot_fetch_wanted(chain) && - ranks_[0]->kv.alloc_checkpoint(&ck) != RAD_OK) { - ck = -1; - if (pc.free_checkpoint_for_restore() && - ranks_[0]->kv.alloc_checkpoint(&ck) != RAD_OK) - ck = -1; - } - const bool wait = ranks_[0]->tiers.plan_fetch(chain, &reads, rad_mono_ns(), &ck); - if (ck >= 0) ranks_[0]->kv.free_checkpoint(ck); - if (wait && (reads.empty() || submit_fetch(req.id, std::move(reads)))) - return R::Wait; - } - if (want.empty()) return R::Done; + const std::vector want = pc.restorable_from(req.prompt, mk); + if (want.empty()) return; /* THE WHOLE CHAIN IN ONE RESTORE. A 4-token block makes a long conversation tens of * thousands of entries, and one transfer an entry is tens of thousands of host round * trips before the turn can start; as one restore it is a launch per (group, layer) @@ -1835,7 +1700,7 @@ int Engine::serve() { if (!ranks_[0]->tierx.plan_promote(h, &j)) break; jobs.push_back(std::move(j)); } - if (jobs.empty()) return R::Done; + if (jobs.empty()) return; std::vector ok(jobs.size(), 1); for (auto& r : ranks_) { std::vector mine; @@ -1867,7 +1732,6 @@ int Engine::serve() { } } ranks_[0]->tiers.note_restore((int64_t)(rad_mono_ns() - t0)); - return R::Done; }; /* AN EVICTION THAT WOULD LOSE AN ENTRY WAITS FOR ITS COPY INSTEAD. Called by the * prefix cache binding under the scheduler's lock, on this thread, when dropping the @@ -1992,6 +1856,8 @@ std::string Engine::engine_info() const { { "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["vision_tower_placement"] = { { "asked", table_placement_name(cfg_.tower_placement) }, + { "resolved", table_placement_name(cfg_.tower_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 c200ca5e..7ce1fb4e 100644 --- a/core/engine.h +++ b/core/engine.h @@ -41,7 +41,6 @@ namespace rad { -class SSDTier; class Kld; struct TierPump; struct TierJob; @@ -92,18 +91,7 @@ private: * shared BY POINTER rather than broadcast (spec §1). */ struct Rank; std::vector> ranks_; - /* THE DISK HALF OF THE IDLE TIERS. One store for the engine, not one per rank: it is - * keyed by a chained hash of TOKENS, which every rank computes identically, and a - * per-rank store would write the same key several times over. Off unless - * --prefix-cache-disk-mib and a directory are both given; it holds conversation content - * unencrypted and says so at startup. - * - * unique_ptr because engine.h is included by main.cpp and the tools, and SSDTier - * drags in the O_DIRECT device layer that none of them want to compile against. */ - std::unique_ptr kv_disk_; - /* THE TIERS' WORK IN FLIGHT: the copy to host memory the transfer streams are running and the - * disk batch the IO thread is writing. Declared after kv_disk_ so it goes first -- the thread - * writes into that store. */ + /* THE TIERS' WORK IN FLIGHT: the copy to host memory the transfer streams are running. */ std::unique_ptr pump_; std::vector rank_threads_; @@ -146,10 +134,11 @@ private: int apply_rope_scaling(); int declare(); int plan(); - /* --embedding-placement and --ngram-placement, resolved into Config before the card is split - * (engine_bringup.cpp says how auto chooses). */ + /* --embedding-placement, --vision-tower-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, + const std::vector& emb_bytes, + const std::vector& tower_bytes, int64_t kv_floor, int64_t ngram_bytes, bool ngram_device, bool ngram_host); /* --ngram-placement ram: the copy of the container's [src, src + n), file offset `foff`, made * once and shared by every rank -- locked for the host gather, or pinned for a device kernel @@ -352,20 +341,15 @@ private: /* The terminal ids drain_completed() took, reused so a steady state allocates nothing. */ std::vector done_; /* THE TIERS' SIDE OF THE LOOP, every iteration: collect a copy that has landed, hand the next - * one out, collect and hand out the disk work. Nothing in it waits on the device or on a file, - * and the scheduler's lock is held only around the bookkeeping. */ + * one out, and make room in a full arena. Nothing in it waits on the device, and the + * scheduler's lock is held only around the bookkeeping. */ void tier_tick(); - bool submit_fetch(uint64_t tag, std::vector&& jobs); - /* A MARK ON EVERY RANK'S STREAMS, for the disk thread to wait on before it touches a slot: - * the transfer streams' when `transfer`, the compute streams' when `compute`, in that order, - * one a rank each; `st` is the first failure to make one. destroy_fences gives them back on - * their own cards. */ - std::vector rank_fences(bool transfer, bool compute, int* st = nullptr); - void destroy_fences(std::vector& f); + /* --prefix-cache-ttl, once a second, with or without the tiers (PrefixCache::expire). */ + void expire_tick(uint64_t now_ns); + uint64_t expire_last_ns_ = 0; /* Every host copy that is waiting, issued and landed now. Under the scheduler's lock, from an * eviction that would otherwise erase what the copies cover. True when any landed. */ bool flush_copies(); - uint64_t tier_last_ns_ = 0; /* THE LOAN: what the KV cache is not using, lent to every rank's expert slab at the addresses * the cache already owns (KVManager, the loan block). Here rather than inside the scheduler * because it spans both sides -- rank 0's cache decides how much, and every rank's mover diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 59e725c0..e1543557 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -220,9 +220,11 @@ static int usable_devices(std::vector* out, std::string* inventory, std::st * * A card refusing its weights pool after its budget was measured had that memory taken in * between, and another process on the card is the usual taker -- the budget is measured once, - * before any rank allocates. A host pool is PINNED memory, and the amdgpu driver caps what the - * whole system may pin (ttm.pages_limit, half of RAM unless raised); every rank pins its own - * --host-pool-mib, so a second rank asks for the same amount again. */ + * before any rank allocates. A host pool is PINNED memory, and every rank pins its own + * --host-pool-mib, so a second rank asks for the same amount again. The pool is locked user memory, + * which the amdgpu driver counts against one system-wide cap: RAM less 1/64 and 1.5 GiB (half of + * RAM less 1/64 below 3 GiB), unless amdgpu.no_system_mem_limit lifts it. ttm.pages_limit bounds + * the driver's own allocations and not these. */ static void report_pool_refusal(int rank, int device, const Pools& pools, const Config& cfg) { bool card = false, host = false; for (const Shortfall& f : pools.shortfalls()) (f.pool == "host_pool" ? host : card) = true; @@ -238,46 +240,54 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const int64_t pinned = 0, mapped = 0; rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr); rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr); - int64_t cap = -1, avail = -1; - { - std::ifstream f("/sys/module/ttm/parameters/pages_limit"); - long long pages = 0; - if (f >> pages && pages > 0) cap = (int64_t)pages * (int64_t)sysconf(_SC_PAGESIZE); - } + int64_t total = -1, avail = -1; { std::ifstream f("/proc/meminfo"); std::string line; while (std::getline(f, line)) { long long kb = 0; - if (std::sscanf(line.c_str(), "MemAvailable: %lld kB", &kb) == 1) { - avail = (int64_t)kb * 1024; - break; - } + if (std::sscanf(line.c_str(), "MemTotal: %lld kB", &kb) == 1) total = (int64_t)kb * 1024; + if (std::sscanf(line.c_str(), "MemAvailable: %lld kB", &kb) == 1) avail = (int64_t)kb * 1024; } } + bool lifted = false; + { + std::ifstream f("/sys/module/amdgpu/parameters/no_system_mem_limit"); + std::string v; + lifted = (f >> v) && (v == "Y" || v == "1"); + } + const int64_t reserve = (int64_t)3 << 29; + int64_t cap = -1; + if (total > 0 && !lifted) { + cap = total - (total >> 6); + cap = cap < 2 * reserve ? cap >> 1 : cap - reserve; + } /* A refusal with room under both is not a capacity one, and advice to shrink the pool * would send the reader after the wrong cause: the device's reason above is the answer. */ - const int64_t pool = (cfg.host_pool_mib + cfg.embedding_host_mib) * 1024 * 1024; + const int64_t pool = cfg.host_pool_total_mib() * 1024 * 1024; + std::string tables, advice = "Lower --host-pool-mib"; + if (cfg.embedding_host_mib) { + tables += fmt(" and the token embedding's %lld MiB", (long long)cfg.embedding_host_mib); + advice += ", keep the embedding on the card with --embedding-placement vram"; + } + if (cfg.tower_host_mib) { + tables += fmt(" and the encoder towers' %lld MiB", (long long)cfg.tower_host_mib); + advice += ", keep the encoder towers on the card with --vision-tower-placement vram"; + } const int64_t want = (int64_t)cfg.tp * pool + pinned + mapped; - const bool fits = cap > 0 && avail >= 0 && want <= cap && want <= avail; + const bool fits = avail >= 0 && want <= avail && (lifted || (cap > 0 && want <= cap)); RAD_ERR("host: --host-pool-mib %lld%s is pinned once per rank, so %d rank(s) pin %s; this " "process had taken %s of pinned host memory before rank %d's pool. The amdgpu " - "driver caps pinned memory system-wide at %s (ttm.pages_limit, half of RAM unless " - "raised), and %s of RAM is available. %s", - (long long)cfg.host_pool_mib, - cfg.embedding_host_mib - ? fmt(" and the token embedding's %lld MiB", (long long)cfg.embedding_host_mib).c_str() - : "", - cfg.tp, humanb((int64_t)cfg.tp * pool).c_str(), + "driver caps what every process together pins at %s, and %s of RAM is available. %s", + (long long)cfg.host_pool_mib, tables.c_str(), cfg.tp, humanb((int64_t)cfg.tp * pool).c_str(), humanb(pinned + mapped).c_str(), rank, - cap > 0 ? humanb(cap).c_str() : "an unreadable limit", + lifted ? "no limit (amdgpu.no_system_mem_limit)" + : cap > 0 ? fmt("%s (RAM less 1/64 and 1.5 GiB)", humanb(cap).c_str()).c_str() + : "an unknown limit (MemTotal unreadable)", avail >= 0 ? humanb(avail).c_str() : "an unknown amount", fits ? "The pools fit under both, so the refusal is not one of size; the reason " "the device gave is above" - : cfg.embedding_host_mib - ? "Lower --host-pool-mib, keep the embedding on the card with " - "--embedding-placement vram, or raise the cap" - : "Lower --host-pool-mib, or raise the cap"); + : advice.c_str()); } } @@ -472,6 +482,9 @@ bool Engine::ngram_gather_to_host() { * 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 ENCODER TOWERS: Vram by default; Ram, when named, pins them beside the pool as the embedding + * is (Config::tower_host_mib), read over the link once an image. + * * THE N-GRAM TABLE: Vram where a device kernel gathers it and the card holds it; Ram as a copy, * pinned for that kernel to read over the link or locked for the host gather; Disk in the * container, read by the host gather. Each tier is refused where no kernel reads it there. Auto @@ -480,7 +493,8 @@ bool Engine::ngram_gather_to_host() { * the memory and every cgroup after the pools still to be allocated, and the memlock limit for a * locked copy. */ int Engine::resolve_table_placement(const std::vector& facts, - const std::vector& emb_bytes, int64_t kv_floor, + const std::vector& emb_bytes, + const std::vector& tower_bytes, int64_t kv_floor, int64_t ngram_bytes, bool ngram_device, bool ngram_host) { const int64_t MiB = (int64_t)1 << 20; int64_t emb_max = 0; @@ -494,7 +508,7 @@ int Engine::resolve_table_placement(const std::vector& facts, * which a pin the cards read is not charged to. */ const int64_t emb_pin = (int64_t)cfg_.tp * align_up(emb_max, (int64_t)MiB); const int64_t pools_still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB + - cfg_.prefix_cache_host_mib * MiB; + cfg_.prefix_cache_mib * MiB; std::string emb_room_why; auto emb_room = [&]() { return lockable_room(emb_pin, pools_still, false, &emb_room_why); }; if (emb_max == 0) { @@ -528,6 +542,36 @@ int Engine::resolve_table_placement(const std::vector& facts, cfg_.embedding_resolved = emb; cfg_.embedding_host_mib = emb == TablePlacement::Ram ? align_up(emb_max, MiB) / MiB : 0; + /* THE ENCODER TOWERS: on the card unless ram was named, and then pinned beside the pool or the + * server stops -- the flag has no default to give way to. Every rank pins a whole tower: an + * encoder is not sharded. Decided before the n-gram table, whose card test needs the statics + * as they will be and whose RAM test the pools still to be allocated. */ + int64_t tower_max = 0; + for (int64_t b : tower_bytes) tower_max = std::max(tower_max, b); + const TablePlacement tw = cfg_.tower_placement; + if (tw == TablePlacement::Ram) { + if (tower_max == 0) { + if (cfg_.mm_max_patches == 0) + RAD_ERR("--vision-tower-placement ram: --mm-max-patches 0 asked for no media, so " + "this server declares no encoder tower to place"); + else + RAD_ERR("--vision-tower-placement ram: this model has no encoder tower (no weight " + "its architecture reads once per request)"); + return RAD_E_INVAL; + } + std::string why; + const int64_t pin = (int64_t)cfg_.tp * align_up(tower_max, (int64_t)MiB); + if (!lockable_room(pin, pools_still + (int64_t)cfg_.tp * cfg_.embedding_host_mib * MiB, + false, &why)) { + RAD_ERR("--vision-tower-placement ram: the encoder towers (%s a rank, pinned on every " + "rank) cannot be held in host memory: %s. Use vram.", humanb(tower_max).c_str(), + why.c_str()); + return RAD_E_NOMEM; + } + } + cfg_.tower_resolved = tw; + cfg_.tower_host_mib = tw == TablePlacement::Ram ? align_up(tower_max, MiB) / MiB : 0; + TablePlacement ng = cfg_.ngram_placement; std::string ng_why; /* THE FASTEST TIER WITH THE ROOM, the card first: the table on the card, every rank holding @@ -535,8 +579,8 @@ int Engine::resolve_table_placement(const std::vector& facts, * --max-model-len sequence beside it; then a copy in RAM -- pinned * for a device kernel to read over the link, or locked for the host gather; then the * container, which only the host gather reads. Each is open only where a kernel reads it. */ - const int64_t still = (int64_t)cfg_.tp * (cfg_.host_pool_mib + cfg_.embedding_host_mib) * MiB + - cfg_.prefix_cache_host_mib * MiB; + const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_total_mib() * MiB + + cfg_.prefix_cache_mib * MiB; const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20); const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy"; auto card_holds = [&](std::string* why) { @@ -546,6 +590,7 @@ int Engine::resolve_table_placement(const std::vector& facts, VramFacts& f = with[i]; f.statics += ngram_bytes; if (emb == TablePlacement::Ram) f.statics -= emb_bytes[i]; + if (tw == TablePlacement::Ram) f.statics -= tower_bytes[i]; fixed = std::max(fixed, f.statics); } /* `fixed` and not the trial's own statics: the split clamps those to what the card can give @@ -645,6 +690,15 @@ int Engine::resolve_table_placement(const std::vector& facts, decide("--embedding-placement", table_placement_name(emb), emb_max > 0 ? fmt("the table is %s a rank: %s", humanb(emb_max).c_str(), emb_why.c_str()) : emb_why); + if (tower_max > 0) + RAD_INFO("placement: encoder towers (%s a rank) %s%s", humanb(tower_max).c_str(), + table_placement_name(tw), + tw == TablePlacement::Ram ? ": pinned in host memory, read over the link once an " + "image, their VRAM the KV cache's" + : " (default)"); + decide("--vision-tower-placement", tower_max > 0 ? table_placement_name(tw) : "n/a", + tower_max > 0 ? fmt("the towers are %s a rank", humanb(tower_max).c_str()) + : std::string("this server declares no encoder tower")); has_ngram_ = ngram_bytes > 0; decide("--ngram-placement", ngram_bytes > 0 ? table_placement_name(ng) : "n/a", ngram_bytes > 0 ? fmt("the table is %s: %s", humanb(ngram_bytes).c_str(), ng_why.c_str()) @@ -1223,7 +1277,7 @@ int Engine::plan() { 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; + std::vector emb_bytes, tower_bytes; std::vector wfs; int64_t ngram_bytes = 0, kv_floor = 0; bool ngram_device = false, ngram_host = false; @@ -1288,6 +1342,7 @@ int Engine::plan() { f.lends = VMem::supported() && !cfg_.deterministic && (cfg_.placement == "auto" || cfg_.placement == "expert_tiered"); emb_bytes.push_back(wf.embedding); + tower_bytes.push_back(wf.tower); ngram_bytes = std::max(ngram_bytes, wf.ngram); ngram_device = ngram_device || wf.ngram_device; ngram_host = ngram_host || wf.ngram_host; @@ -1333,7 +1388,7 @@ int Engine::plan() { /* AND THE KV TIERS' COPY STAGING, which TierExec::device_init builds on the first * copy out. Which groups the prefix cache indexes is settled after this split, so * every paged group is counted: the entry it sizes can only be smaller. */ - if (cfg_.prefix_cache_host_mib > 0 || cfg_.prefix_cache_disk_mib > 0) { + if (cfg_.prefix_cache_mib > 0) { int64_t entry = 0, bs = 0; int ng = 0; for (size_t g = 0; g < r->program.kv_groups.size(); ++g) { @@ -1359,13 +1414,15 @@ int Engine::plan() { room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed); facts[i].expert_floor = expert_vram_floor(wfs[i], std::max(room, 0)); } - RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device, - ngram_host)); + RAD_TRY(resolve_table_placement(facts, emb_bytes, tower_bytes, kv_floor, ngram_bytes, + ngram_device, ngram_host)); /* The n-gram table was counted off the card; on it, it is every rank's whole table. */ if (cfg_.ngram_resolved == TablePlacement::Vram) for (VramFacts& f : facts) f.statics += ngram_bytes; if (cfg_.embedding_resolved == TablePlacement::Ram) for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i]; + if (cfg_.tower_resolved == TablePlacement::Ram) + for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= tower_bytes[i]; VramBudget vb; RAD_TRY(vram_budget_resolve(cfg_, facts, &vb)); if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str()); @@ -1535,9 +1592,10 @@ int Engine::plan() { humanb(r->plan.totals.bytes[(int)Tier::VRAM]).c_str(), humanb(host).c_str(), humanb(r->plan.totals.bytes[(int)Tier::SSD]).c_str(), humanb(r->plan.totals.bytes[(int)Tier::Mapped]).c_str()), - r->plan.embedding_host_used > 0 - ? fmt("the host pool holds the token embedding's %s beside the weights " - "placed there", humanb(r->plan.embedding_host_used).c_str()) + r->plan.forced_host_used > 0 + ? fmt("the host pool holds the %s the placement flags put there (the token " + "embedding, the encoder towers) beside the weights placed in it", + humanb(r->plan.forced_host_used).c_str()) : std::string()); } /* --host-pool-mib IS ONE NUMBER FOR EVERY RANK, allocated whole by Pools::configure, so a @@ -2933,17 +2991,16 @@ int Engine::configure_kv() { /* ---------------- the idle session tiers (spec §7.3) ---------------- */ /* AFTER the prefix cache, because the tiers are sized in units of ONE CACHE ENTRY and only the - * configured cache knows which groups an entry covers. No memory is committed unless an - * operator gave a tier a size: a tier of zero bytes holds nothing, so the two inactivity - * thresholds are ordinary defaults rather than a commitment of memory nobody asked to spend. + * configured cache knows which groups an entry covers. No memory is committed unless the + * operator gave the host tier a size. * * CONFIGURED EVEN SO, because this object is also where a stored conversation is RECORDED, - * and that is not a tiering fact. A server with no --prefix-cache-host-mib holds its whole prefix + * and that is not a tiering fact. A server with no --prefix-cache-mib holds its whole prefix * cache in VRAM and holds it for exactly as long; skipping the configure would leave the * sessions view reading an unconfigured object and reporting an empty server, on every * deployment that has not opted into demotion. What the flags gate is the MOVER, below. */ { - const bool tier_asked = cfg_.prefix_cache_host_mib > 0 || cfg_.prefix_cache_disk_mib > 0; + const bool tier_asked = cfg_.prefix_cache_mib > 0; const std::vector& cg = ranks_[0]->prefix.cached_groups(); /* ONE SLOT HOLDS EVERY RANK'S SHARD. An entry under tensor parallelism is n_ranks * pieces of KV that are not interchangeable, so the unit the tiers store and budget @@ -2967,138 +3024,36 @@ int Engine::configure_kv() { entry_bytes = std::max(entry_bytes, rank_entry[i]); } - /* ---- how the disk tier is split between the two halves of a session ---- - * - * ON THIS BUILD A RESTORED HYBRID SESSION WITH NO SNAPSHOT REUSES NOTHING AT ALL. The - * scheduler clamps its reuse to the last reachable checkpoint and says why: RadBatch - * carries one query length for every KV group, so the linear layers cannot be replayed - * over a longer range than the attention layers, and the correct answer is to recompute - * from the checkpoint (core/sched/scheduler.cpp, admit_one). A session whose blocks came - * back and whose state did not therefore gets a hit of ZERO -- the blocks are not a - * partial win, they are unusable -- and the snapshot store is not a nice-to-have beside - * the block store, it is the thing that decides whether any of this works. - * - * So the split is DERIVED, from the session the operator sized the server for. At - * --max-model-len M a session costs - * - * blocks (M / block_size) * slot_bytes - * snapshots (log2(M / interval) + 1) * ck_slot_bytes [geometric backoff] - * - * and splitting the cap in that ratio makes both halves hold the same NUMBER OF SESSIONS, - * which is the only sense in which they can be balanced. The ratio is strongly length - * dependent -- snapshots want 22% of the tier at 200K and more than half at 32K, because - * the retained set grows logarithmically while the blocks grow linearly -- which is - * exactly why a single fixed fraction is the wrong shape. - * - * Two thirds is the ceiling. Not because the arithmetic asks for one, but because the - * clamp above is a property of THIS build rather than of the design, and a tier with - * almost no room for blocks would be badly sized the day it is lifted. - * - * THE HOST TIER IS NOT SPLIT: snapshots live in the checkpoint store, which - * --checkpoint-slots sizes, and --prefix-cache-host-mib is the blocks' alone. */ + /* THE SNAPSHOTS ARE NOT IN THE HOST TIER: they live in the checkpoint store, which + * --checkpoint-slots sizes, and --prefix-cache-mib is the blocks' alone. */ const int64_t ck_slot_bytes = ck_store_.enabled() ? ck_store_.slot_bytes() : 0; - int64_t ck_disk_slots = 0; - if (ck_slot_bytes > 0) { - const int64_t bs = ranks_[0]->prefix.block_size(); - const int64_t iv = ranks_[0]->prefix.checkpoint_interval(); - /* The session the server was sized for: --max-model-len, or the training context - * when it is unset -- the same reading the declare and the KV pool take. */ - const int64_t mlen = std::max( - 1, cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train); - int64_t retained = 1; - for (int64_t n = (iv > 0 ? mlen / iv : 0); n > 1; n >>= 1) ++retained; - const int64_t sess_blocks = bs > 0 ? (mlen / bs) * slot_bytes : slot_bytes; - const int64_t sess_snaps = retained * ck_slot_bytes; - const int64_t denom = sess_blocks + sess_snaps; - const int64_t disk_cap = cfg_.prefix_cache_disk_mib << 20; - const int64_t disk_ck = std::min(disk_cap * 2 / 3, denom > 0 ? disk_cap / denom * sess_snaps - + disk_cap % denom * sess_snaps / denom - : 0); - ck_disk_slots = disk_ck / ck_slot_bytes; - /* One where there is room for one at all: a tier that holds a session's blocks and not - * one snapshot holds nothing usable. */ - if (ck_disk_slots == 0 && disk_cap >= ck_slot_bytes * 2) ck_disk_slots = 1; - } if (cg.empty() || entry_bytes <= 0) { /* Said only to an operator who asked for a tier. With no flag there is nothing to * report: a cache that indexes no paged group stores no blocks to begin with. */ if (tier_asked) RAD_WARN("kv tiers: the prefix cache indexes no paged group, so there is nothing " - "to move. --prefix-cache-host-mib and --prefix-cache-disk-mib do nothing here."); + "to move. --prefix-cache-mib does nothing here."); } else { - if (cfg_.prefix_cache_disk_mib > 0) { - if (cfg_.prefix_cache_dir.empty()) { - RAD_WARN("kv tiers: --prefix-cache-disk-mib needs --prefix-cache-dir to say WHERE. " - "The disk tier is off."); - } else { - SSDTierConfig sc; - sc.dir = cfg_.prefix_cache_dir; - sc.block_payload = slot_bytes; - sc.block_tokens = ranks_[0]->prefix.block_size(); - sc.ckpt_payload = ck_slot_bytes; - sc.n_ckpt_slots = ck_disk_slots; - sc.n_block_slots = ((cfg_.prefix_cache_disk_mib << 20) - - ck_disk_slots * ck_slot_bytes) / slot_bytes; - /* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE, and it is built from - * everything a cached block's bytes actually depend on. Read back under a - * different container, layout, KV width or rotary, a block is a lossless - * function of somebody else's weights -- fluent, confident and wrong. There is - * no cheaper check than refusing the whole store, because a block carries no - * evidence of what produced it beyond the tokens it was keyed by. - * - * The rotary is the RESOLVED one, target and drafter, after --rope-scaling - * (rope_identity): a YaRN container converted from the same checkpoint has the - * same name and shapes as the stock one, and every cached key and QSA block key - * is rotated differently under it. */ - { - char theta[32]; - std::snprintf(theta, sizeof theta, "%.9g", (double)meta_.rope_theta); - const std::string id = - std::string(meta_.name ? meta_.name : "") + "|" + - std::string(meta_.arch_id ? meta_.arch_id : "") + "|" + - std::to_string(meta_.n_layers) + "|" + - std::to_string(ranks_[0]->prefix.block_size()) + "|" + - std::to_string(slot_bytes) + "|" + std::to_string(ck_slot_bytes) + "|" + - cfg_.kv_cache_dtype + "|" + - std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION + - "|theta=" + theta + "|" + rope_identity(meta_kv_k_, meta_kv_v_); - uint64_t h = 1469598103934665603ull; - for (char c : id) { h ^= (unsigned char)c; h *= 1099511628211ull; } - sc.fingerprint = h; - } - sc.persistent = true; - kv_disk_ = std::make_unique(); - RAD_INFO("%s", SSDTier::disclosure(sc.dir).c_str()); - if (kv_disk_->open(sc) != RAD_OK) { - RAD_WARN("kv tiers: the disk tier at %s would not open; it is off.", - sc.dir.c_str()); - kv_disk_.reset(); - } - } - } IdleTiers::Config tc; - tc.host_cap_bytes = cfg_.prefix_cache_host_mib << 20; - tc.disk_cap_bytes = kv_disk_ ? (cfg_.prefix_cache_disk_mib << 20) : 0; + tc.host_cap_bytes = cfg_.prefix_cache_mib << 20; tc.entry_bytes = slot_bytes; tc.ckpt_bytes = ck_slot_bytes; tc.ckpt_slots = ck_store_.capacity(); - tc.ckpt_disk_slots = kv_disk_ ? ck_disk_slots : 0; /* THE POLICY IS RANK 0'S AND THE TRANSFER IS EVERY RANK'S. A session is not sharded -- * it is a conversation -- so one decision is taken about it; but each rank holds its * own shard of every block and gathers out of its own pool, so each rank moves its own * bytes when that decision is taken. */ IdleTiers& T = ranks_[0]->tiers; - RAD_TRY(T.configure(tc, kv_disk_.get())); + RAD_TRY(T.configure(tc)); T.set_model(meta_.name && meta_.name[0] ? meta_.name : "(unnamed)"); if (T.any_on()) { /* HOW MUCH A PASS MOVES, SIZED IN BYTES AND NOT IN ENTRIES. A cache entry is one * block per cached group, and that is 29 KiB on a 4-token-block hybrid and four * times more on a 16-token one -- so a fixed entry count means a fixed batch on * one model and a quarter of one on another. At a fixed 64 entries a 200K session - * on a 4-token-block hybrid takes about thirteen minutes to leave VRAM, which is - * most of the way to the disk threshold: a tier that works and is too slow to be - * worth having. + * on a 4-token-block hybrid takes about thirteen minutes to leave VRAM: a tier that + * works and is too slow to be worth having. * * 16 MiB of device staging a rank, which is about a millisecond of PCIe a pass * and 0.02 ms a step of the VRAM it costs. The batch is one gather per (group, @@ -3129,12 +3084,11 @@ int Engine::configure_kv() { * AND THE STREAM IS THE MOVER'S. See Mover::transfer_stream -- a fourth * hardware queue costs an RDNA4 card 65% of its decode step. */ RAD_TRY(rad_dev_set(r->device)); - if (r->tierx.configure(&rad_tools_registry(), &r->kv, &T, kv_disk_.get(), cg, + if (r->tierx.configure(&rad_tools_registry(), &r->kv, &T, cg, max_batch, max_copy, max_chain, /*leader=*/&r == &ranks_[0], r->device, entry_off[(size_t)(&r - &ranks_[0])], - &ck_store_, /*shared=*/r->mover.transfer_stream()) != RAD_OK) { all = false; @@ -3148,10 +3102,8 @@ int Engine::configure_kv() { * reported size is computed from, so the object is re-configured for the * caps it can still honour -- none. */ T.close(); - kv_disk_.reset(); - tc.host_cap_bytes = tc.disk_cap_bytes = 0; - tc.ckpt_disk_slots = 0; - RAD_TRY(T.configure(tc, nullptr)); + tc.host_cap_bytes = 0; + RAD_TRY(T.configure(tc)); } else { /* The tiers can lose an entry without the cache asking: a capacity drop, or a * promotion that failed. The cache has to hear about it or it will go on @@ -3159,21 +3111,11 @@ int Engine::configure_kv() { T.set_drop_sink([this](const BlockHash& h) { ranks_[0]->prefix.drop_offdevice(h); }); - /* And the linear half on its own: a snapshot whose only copy was on disk and - * that the disk store let go of. An index entry left behind would be a - * checkpoint the cache goes on offering whose bytes nobody holds, which is the - * recurrent-state form of the same corruption. */ - T.set_snapshot_drop_sink([this](const BlockHash& h) { - ranks_[0]->prefix.drop_snapshot(h); - }); - /* THE DISK HALF GETS A THREAD, and a plan holds about 512 MiB of it -- a - * fraction of a second of the store's write rate, so the disk copies keep up - * with the host copies in a handful of plans rather than one entry a second. */ + /* A capacity plan drops up to 512 MiB of the oldest host-only entries. */ pump_ = std::make_unique(); pump_->max_copy = max_copy; pump_->slow_budget = (int)std::min( 1 << 20, std::max(64, (512ll << 20) / std::max(1, slot_bytes))); - if (kv_disk_) pump_->io.start(&ranks_[0]->tierx); RAD_INFO("%s", ranks_[0]->tierx.report().c_str()); } } diff --git a/core/engine_diag.cpp b/core/engine_diag.cpp index 0493489d..6941acae 100644 --- a/core/engine_diag.cpp +++ b/core/engine_diag.cpp @@ -74,8 +74,6 @@ diag::RunFacts Engine::run_facts(bool failed) const { r.tp_wire_min_kb = cfg_.tp_wire_min_kb; r.prefix_cache = cfg_.prefix_cache; r.prefix_cache_off_why = prefix_off_why_; - r.prefix_host_mib = cfg_.prefix_cache_host_mib; - r.prefix_disk_mib = cfg_.prefix_cache_disk_mib; r.host_pool_mib = cfg_.host_pool_mib; { int64_t pinned = 0, mapped = 0, n = 0; @@ -85,11 +83,11 @@ diag::RunFacts Engine::run_facts(bool failed) const { } /* THE MOST ANY RANK READS FROM THE HOST: the ranks step together, so the one that streams most * is the one each step waits for. The embedding the placement flag put in host memory is read - * a few rows a step and is not what this counts. */ + * a few rows a step, the encoder towers once an image, and neither is what this counts. */ for (const auto& rk : ranks_) { const Plan& p = rk->plan; const int64_t host = p.totals.bytes[(int)Tier::HostPinned] + - p.totals.bytes[(int)Tier::HostPageable] - p.embedding_host_used; + p.totals.bytes[(int)Tier::HostPageable] - p.forced_host_used; r.host_weight_bytes = std::max(r.host_weight_bytes, std::max(host, 0)); r.file_weight_bytes = std::max(r.file_weight_bytes, p.totals.bytes[(int)Tier::SSD]); } diff --git a/core/engine_priv.h b/core/engine_priv.h index eaaf85ad..902c5d6a 100644 --- a/core/engine_priv.h +++ b/core/engine_priv.h @@ -17,7 +17,6 @@ #include "mem/kv.h" #include "mem/prefix.h" #include "mem/kvtier.h" -#include "mem/sstier.h" #include "runtime/tierexec.h" #include "build/rad_build.h" #include "place/heat.h" @@ -66,9 +65,8 @@ struct Engine::Rank { /* THE IDLE SESSION TIERS (spec 7.3). Rank 0 owns the policy and the session index, * because they describe CONVERSATIONS and a conversation is not sharded -- but the * transfer is per rank, since each rank holds its own shard of every KV block and - * has its own pool to gather out of. The disk store is rank 0's alone for the same - * reason the policy is: one store, keyed by a hash of tokens every rank agrees on. - * Both are inert unless the operator gave a tier a size. */ + * has its own pool to gather out of. Both are inert unless --prefix-cache-mib gave the + * host tier a size. */ IdleTiers tiers; TierExec tierx; /* The activation arena's smaller levels, smallest step first (Engine::probe_arena_levels). */ @@ -101,16 +99,12 @@ struct Engine::Rank { /* THE TIERS' WORK IN FLIGHT (Engine::tier_tick). One copy batch out on every rank's transfer * stream at a time, with each rank's answer kept until all of them have one -- a rank that has - * landed must not be asked again and forget it failed -- and one disk batch out on the IO thread. */ + * landed must not be asked again and forget it failed. */ struct TierPump { std::vector copy; std::vector copy_st; /* per rank: 0 in flight, 1 landed, negative failed */ - TierIO io; int64_t max_copy = 0; - int slow_budget = 0; - /* The requests a read off disk is out for (IdleTiers::plan_fetch). Asked again while their - * read is out, they wait without walking their prompt; the read's collection lets them go. */ - std::vector waiting; + int slow_budget = 0; /* capacity drops one plan may make */ }; /* THE BUFFER PROBE (engine_probe.cpp). Declared here because three files call it: the step diff --git a/core/main.cpp b/core/main.cpp index 8e27f065..9d5943ce 100644 --- a/core/main.cpp +++ b/core/main.cpp @@ -3,6 +3,7 @@ */ #include "engine.h" #include "hf_model.h" +#include "util/stallwatch.h" int main(int argc, char** argv) { rad::Config cfg; @@ -14,7 +15,12 @@ int main(int argc, char** argv) { rad::Engine engine(std::move(cfg)); - s = engine.start(); + { + /* A startup that stops printing says where it waits (util/stallwatch.h). Two minutes: + * the slowest normal step, a container read from a slow disk, logs well inside that. */ + rad::StallWatch watch("startup", 120000); + s = engine.start(); + } if (s < 0) { /* start() already said what and why; the report adds what it was running on and what it * had decided by then, which is what a log of a server that never came up is read for. */ diff --git a/core/mem/hostarena.h b/core/mem/hostarena.h index fb4b1a37..d562ce81 100644 --- a/core/mem/hostarena.h +++ b/core/mem/hostarena.h @@ -3,7 +3,8 @@ * Two stores are built from it: the KV tiers' block arena (core/mem/kvtier.h), where one slot is * one cache entry, and the linear-state snapshot store (KVManager::set_checkpoint_store), where * one slot is one snapshot. Under tensor parallelism a slot holds EVERY rank's shard of its - * object, each rank at its own offset, so the disk store can read and write it as one payload. + * object, each rank at its own offset, so one slot id -- rank 0's to hand out -- names the object + * on every rank. * * Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the * driver stages an async copy to pageable memory through its own buffer and, on some paths, diff --git a/core/mem/kv.h b/core/mem/kv.h index a37f1169..51637d84 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -350,7 +350,7 @@ public: * A BLOCK IS NOT LENT WHILE ANYTHING HOLDS IT, and a held block is a block a sequence owns OR * one the prefix cache still indexes. So a loan cannot evict anything: it is a claim on what * is free. Everything that makes a block free -- a sequence ending, an eviction, an idle-tier - * demotion to host memory or disk -- makes it lendable, and the min-heap free list is what + * demotion to host memory -- makes it lendable, and the min-heap free list is what * keeps the free blocks at the top, where a loan can reach them. * * THE BUFFER IS DERIVED AND NOT STATED. It is the free blocks the cache keeps in hand so that @@ -456,8 +456,7 @@ public: * that resumes from it, each a few milliseconds on a 50-100 MiB snapshot. * * THE STORE IS SHARED BY EVERY RANK and owned by the engine: a slot holds every rank's shard - * of one snapshot, each at its own offset (`rank_off`), so the disk tier reads and writes a - * slot as one payload. The slot ids are rank 0's -- its manager hands them out and the others + * of one snapshot, each at its own offset (`rank_off`). The slot ids are rank 0's -- its manager hands them out and the others * address the id they are given. Without a store no slot is ever handed out and a hybrid * model's prefix hits replay their linear layers from zero. `checkpoint_bytes()` is THIS * rank's shard. */ diff --git a/core/mem/kvtier.cpp b/core/mem/kvtier.cpp index 4a77ae79..72ed6b61 100644 --- a/core/mem/kvtier.cpp +++ b/core/mem/kvtier.cpp @@ -1,6 +1,5 @@ #include "mem/kvtier.h" -#include "mem/sstier.h" #include "rad_internal.h" #include @@ -13,18 +12,16 @@ const char* kv_tier_name(KVTier t) { switch (t) { case KVTier::Device: return "device"; case KVTier::Host: return "host"; - case KVTier::Disk: return "disk"; } return "?"; } /* ------------------------------------------------------------------ IdleTiers */ -int IdleTiers::configure(const Config& c, SSDTier* disk) { +int IdleTiers::configure(const Config& c) { std::lock_guard lk(mu_); reset(); cfg_ = c; - disk_ = disk; if (cfg_.host_cap_bytes > 0 && cfg_.entry_bytes > 0) { const int st = arena_.open(cfg_.entry_bytes, cfg_.host_cap_bytes); @@ -36,46 +33,27 @@ int IdleTiers::configure(const Config& c, SSDTier* disk) { } else { cfg_.host_cap_bytes = 0; } - if (!disk_ || !disk_->enabled()) cfg_.disk_cap_bytes = 0; - - /* A disk tier under no host tier is legal and it is not a mistake: the blocks' path to disk - * runs through host memory, so with no host tier no block ever reaches disk, and saying so at - * startup is cheaper than an operator reading a disk tier's zero counters for an afternoon. */ - if (!host_on() && disk_on()) - RAD_WARN("kv tiers: --prefix-cache-disk-mib is set but --prefix-cache-host-mib is not, and the " - "blocks' path to disk runs through host memory -- only snapshots will be written"); char buf[512]; if (!any_on()) { - report_ = "kv tiers: off (no --prefix-cache-host-mib), so a finished conversation's KV stays " + report_ = "kv tiers: off (no --prefix-cache-mib), so a finished conversation's KV stays " "in VRAM until the cache evicts it under pressure -- it is never copied to host " "memory, and what the pool is holding is mostly cache rather than live requests"; } else { std::snprintf(buf, sizeof buf, "kv tiers: a finished conversation's KV is copied to host memory at once " "(%s, %lld entries) and its VRAM is given up when the expert loan or a " - "request wants it; %s. One entry is %s", + "request wants it; a full host tier drops its least recently used entries. " + "One entry is %s", humanb(arena_.cap_bytes()).c_str(), (long long)arena_.capacity(), - disk_on() ? ("every host copy is written on to disk (" + - humanb(cfg_.disk_cap_bytes) + ") and its slot is given up " - "when another entry needs it").c_str() - : "no disk tier, so a full host tier drops its oldest entries", humanb(cfg_.entry_bytes).c_str()); report_ = buf; - /* SAID EVEN WHEN IT IS ZERO, on a model that has recurrent state. A hybrid server whose - * snapshots do not reach disk looks identical from every block counter there is, and the - * difference it makes is a full linear replay of the transcript on what the hit rate will - * happily report as a hit. */ if (cfg_.ckpt_bytes > 0) { std::snprintf(buf, sizeof buf, "\nkv tiers: a session's linear state is saved to host memory -- %lld " - "snapshot slot(s) of %s -- and %s", - (long long)cfg_.ckpt_slots, humanb(cfg_.ckpt_bytes).c_str(), - ckpt_disk_on() - ? fmt("written on to disk (%lld slots), so a full store detaches " - "the least recently used instead of losing it", - (long long)cfg_.ckpt_disk_slots).c_str() - : "with no disk copy a full store retires the least recently used"); + "snapshot slot(s) of %s -- and a full store retires the least recently " + "used", + (long long)cfg_.ckpt_slots, humanb(cfg_.ckpt_bytes).c_str()); report_ += buf; } } @@ -93,18 +71,11 @@ void IdleTiers::reset() { sessions_.clear(); roots_.clear(); host_lru_.clear(); - disk_lru_.clear(); wb_q_.clear(); - resume_q_.clear(); - dk_q_.clear(); clean_q_.clear(); - ck_reading_.clear(); - ck_free_after_.clear(); - ck_frees_.clear(); starved_ = 0; wb_stuck_ = false; arena_.close(); - disk_ = nullptr; cfg_ = Config{}; report_.clear(); } @@ -113,7 +84,7 @@ std::string IdleTiers::report() const { return report_; } void IdleTiers::unlist(Rec& r) { if (!r.listed) return; - list_for(r.tier).erase(r.it); + host_lru_.erase(r.it); r.listed = false; } @@ -122,25 +93,13 @@ void IdleTiers::unlist(Rec& r) { * header's one-record rule exists to rule out. */ void IdleTiers::relist(const BlockHash& key, Rec& r) { if (r.pending || r.tier == KVTier::Device || r.listed) return; - std::list& l = list_for(r.tier); - l.push_back(key); - r.it = std::prev(l.end()); + r.it = host_lru_.emplace_hint(host_lru_.end(), r.used_ns, key); r.listed = true; } bool IdleTiers::wants_copy(const Rec& r) const { if (r.pending || r.doomed) return false; - return host_on() && r.tier == KVTier::Device && r.host_slot < 0 && !r.on_disk && - !r.blocks.empty(); -} - -bool IdleTiers::wants_ck_disk(const Rec& r) const { - return ckpt_disk_on() && !r.doomed && r.ck_slot >= 0 && !r.ck_on_disk && r.ck_disk_src < 0; -} - -bool IdleTiers::wants_disk(const Rec& r) const { - if (!disk_on() || r.doomed) return false; - return (r.host_slot >= 0 && !r.on_disk && r.disk_src < 0) || wants_ck_disk(r); + return host_on() && r.tier == KVTier::Device && r.host_slot < 0 && !r.blocks.empty(); } void IdleTiers::queue_copy(const BlockHash& key, Rec& r) { @@ -149,12 +108,6 @@ void IdleTiers::queue_copy(const BlockHash& key, Rec& r) { r.queued = true; } -void IdleTiers::queue_disk(const BlockHash& key, Rec& r) { - if (r.disk_q || !wants_disk(r)) return; - dk_q_.push_back(key); - r.disk_q = true; -} - void IdleTiers::give_slot(int32_t slot) { if (slot < 0) return; arena_.free(slot); @@ -162,106 +115,41 @@ void IdleTiers::give_slot(int32_t slot) { } void IdleTiers::free_host(Rec& r) { - if (r.host_slot < 0) return; - if (r.host_slot != r.disk_src) give_slot(r.host_slot); + give_slot(r.host_slot); r.host_slot = -1; } -/* THE ONE PLACE `on_disk` CHANGES, because the disk figure in the occupancy view is kept beside it - * rather than counted, and an entry landing on disk is also what unblocks a stuck write-back. */ -void IdleTiers::set_on_disk(Rec& r, bool v) { - if (r.on_disk == v) return; - r.on_disk = v; - stats_.disk_bytes += v ? cfg_.entry_bytes : -cfg_.entry_bytes; - if (v) wb_stuck_ = false; -} - void IdleTiers::queue_clean(const BlockHash& key, Rec& r) { if (r.clean_q) return; clean_q_.push_back(key); r.clean_q = true; } -/* EVERYTHING THIS RECORD HOLDS OFF THE CARD. The blocks' arena slot is the tiers'; SSDTier owns - * its own slots and reclaims them by LRU, so there is nothing to give back for a disk-resident - * copy of either half. - * - * A snapshot in its store slot is the CACHE'S, not this object's: the cache retires snapshots by - * its own retention policy and the slot is still correct and indexed. Only a snapshot that exists - * nowhere but on disk is lost with the record, and only that loss is announced -- the cache - * learns about a lost ENTRY from set_drop_sink at the sites that erase one, and this is also - * called from forget(), where the cache is the caller and already knows. */ -void IdleTiers::release_storage(const BlockHash& key, Rec& r) { - free_host(r); - set_on_disk(r, false); - const bool lost_ck = r.ck_slot < 0 && r.ck_on_disk; - r.ck_on_disk = false; - if (lost_ck) { ++stats_.ck_drops; if (on_ck_drop_) on_ck_drop_(key); } -} - /* ------------------------------------------------------------------ the linear half */ -void IdleTiers::note_snapshot(const BlockHash& key, int32_t slot, int64_t pos, bool resume) { +/* RECORDED, NOT MOVED. A snapshot is in host memory from the moment it is saved and stays in its + * store slot until the cache retires it; the tiers keep its slot and position for the session + * view. */ +void IdleTiers::note_snapshot(const BlockHash& key, int32_t slot, int64_t pos) { if (slot < 0) return; std::lock_guard lk(mu_); Rec& r = recs_[key]; - /* A FRESH SNAPSHOT REPLACES WHATEVER DISK COPY THERE WAS, never joins it. The disk copy - * described the state as it was last written; the slot now holds it as it was just written, - * and a record that called the two the same bytes would read the older one back. */ - r.ck_on_disk = false; r.ck_slot = slot; r.ck_pos = pos; - /* WRITTEN TO DISK ONCE ITS RECORD IS PUBLISHED, like the blocks: note_used queues it then. A - * request commits its checkpoints as its prefill passes them and the store's retention policy - * thins them as it goes, so writing each at commit would send most of them to disk to be - * retired a moment later. A record the request had already published takes a new commit at - * once. A RESUME POINT does not wait: it is the snapshot the next turn needs, and until it is - * on disk a full store can only retire it. */ - if (r.tier != KVTier::Device || !r.blocks.empty()) queue_disk(key, r); - if (resume && !r.resume_q && wants_ck_disk(r)) { - resume_q_.push_back(key); - r.resume_q = true; - } } -bool IdleTiers::release_snapshot(const BlockHash& key, int32_t slot) { +void IdleTiers::release_snapshot(const BlockHash& key) { std::lock_guard lk(mu_); - bool held = false; - if (slot >= 0 && - std::find(ck_reading_.begin(), ck_reading_.end(), slot) != ck_reading_.end()) { - ck_free_after_.push_back(slot); - held = true; - } auto it = recs_.find(key); - if (it == recs_.end()) return held; + if (it == recs_.end()) return; Rec& r = it->second; r.ck_slot = -1; - r.ck_on_disk = false; /* A RECORD THAT ONLY EVER EXISTED FOR THE SNAPSHOT GOES WITH IT. note_snapshot creates one at * commit time, which is mid-request and long before the chain is published; a request that * never publishes -- a rebased block table, a cancel before the first whole block -- would * otherwise leave a record with no blocks, no storage and no way to be reached again. */ - if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0 && - r.ck_disk_src < 0 && !r.disk_q) + if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0) recs_.erase(it); - return held; -} - -void IdleTiers::take_checkpoint_frees(std::vector* out) { - std::lock_guard lk(mu_); - out->insert(out->end(), ck_frees_.begin(), ck_frees_.end()); - ck_frees_.clear(); -} - -bool IdleTiers::slot_reading(int32_t slot) const { - std::lock_guard lk(mu_); - return slot >= 0 && std::find(ck_reading_.begin(), ck_reading_.end(), slot) != ck_reading_.end(); -} - -bool IdleTiers::snapshot_in_slot(const BlockHash& key, int32_t slot) const { - std::lock_guard lk(mu_); - auto it = recs_.find(key); - return it != recs_.end() && slot >= 0 && it->second.ck_slot == slot; } /* ------------------------------------------------------------------ the cache's notices */ @@ -272,17 +160,14 @@ void IdleTiers::note_used(const BlockHash& key, const std::vector& bloc Rec& r = recs_[key]; r.used_ns = now_ns; if (r.tier == KVTier::Device && !r.pending) r.blocks = blocks; - /* A record only moves to the back of its list when it is IN one. A device record is a - * timestamp and nothing else, which is what keeps this cheap enough to sit on the publish - * path -- the hash insert is the whole cost. */ + /* A record only moves on the host list when it is IN it. A device record is a timestamp and + * nothing else, which is what keeps this cheap enough to sit on the publish path -- the hash + * insert is the whole cost. */ if (r.listed) { - list_for(r.tier).erase(r.it); - r.listed = false; + unlist(r); relist(key, r); } queue_copy(key, r); - /* A snapshot the request committed under this key goes to disk now that its chain is out. */ - if (wants_ck_disk(r)) queue_disk(key, r); } void IdleTiers::note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns) { @@ -294,8 +179,7 @@ void IdleTiers::note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns) { Rec& r = it->second; r.used_ns = now_ns; if (r.listed) { - list_for(r.tier).erase(r.it); - r.listed = false; + unlist(r); relist(keys[i], r); } } @@ -307,7 +191,7 @@ void IdleTiers::rebound(const BlockHash& key, const std::vector& blocks Rec& r = recs_[key]; if (r.pending) return; unlist(r); - release_storage(key, r); + free_host(r); r.tier = KVTier::Device; r.blocks = blocks; r.used_ns = now_ns; @@ -330,18 +214,21 @@ IdleTiers::Stats IdleTiers::stats() const { return s; } +/* AND EVERY CONVERSATION THAT STARTED HERE. A chain whose first block has gone cannot be hit at any + * length -- a prefix hit starts at position zero. Leaving the row behind would report blocks the + * pool has already handed to somebody else as this session's, and would hold its whole chain in + * memory for a conversation that can never come back. Called wherever an entry goes for good: the + * cache's forget(), and the sites here that drop an off-device entry and tell the cache. */ +void IdleTiers::drop_rooted(const BlockHash& key) { + auto ro = roots_.find(key); + if (ro == roots_.end()) return; + const std::vector ids = ro->second; /* drop_session rewrites the list */ + for (uint64_t id : ids) drop_session(id); +} + void IdleTiers::forget(const BlockHash& key) { std::lock_guard lk(mu_); - /* AND EVERY CONVERSATION THAT STARTED HERE. This is the only notice the cache gives that an - * entry is gone for good, and a chain whose first block has gone cannot be hit at any length - * -- a prefix hit starts at position zero. Leaving the row behind would report blocks the - * pool has already handed to somebody else as this session's, and would hold its whole chain - * in memory for a conversation that can never come back. */ - auto ro = roots_.find(key); - if (ro != roots_.end()) { - const std::vector ids = ro->second; /* drop_session rewrites the list */ - for (uint64_t id : ids) drop_session(id); - } + drop_rooted(key); auto it = recs_.find(key); if (it == recs_.end()) return; Rec& r = it->second; @@ -353,7 +240,7 @@ void IdleTiers::forget(const BlockHash& key) { return; } unlist(r); - release_storage(key, r); + free_host(r); recs_.erase(it); } @@ -374,74 +261,13 @@ bool IdleTiers::resident_off_device(const BlockHash& key) const { bool IdleTiers::writeback_waiting() const { std::lock_guard lk(mu_); - /* NOT WHILE NOTHING CAN MOVE. An arena full of copies the disk does not hold yet has nothing - * to give up, so a plan would pop the queue, find no slot and put it back, every tick, until - * a slot is freed or a disk copy lands -- which is what ends the wait. */ + /* NOT WHILE NOTHING CAN MOVE. An arena full of the copies of entries still in VRAM has nothing + * a capacity drop may take, so a plan would pop the queue, find no slot and put it back, every + * tick, until a slot is freed or a VRAM copy is given up -- which is what ends the wait. */ if (wb_stuck_ && arena_.full()) return false; return !wb_q_.empty() && host_on(); } -bool IdleTiers::disk_waiting() const { - std::lock_guard lk(mu_); - return !dk_q_.empty() || !resume_q_.empty(); -} - -int64_t IdleTiers::make_room(int64_t n) { - std::lock_guard lk(mu_); - return make_room_locked(n); -} - -/* A READ NO REQUEST CLAIMS IS HELD THIS LONG. A request is admitted on the step after its read lands, - * which is milliseconds; this only bounds what one that went away -- cancelled while it waited -- - * keeps out of reach of everybody else. */ -static constexpr uint64_t kFetchHoldNs = 10ull * 1000000000ull; - -bool IdleTiers::held_by_fetch(const Rec& r, uint64_t now_ns) const { - return r.keep || (r.fetched_ns != 0 && now_ns - r.fetched_ns < kFetchHoldNs); -} - -int64_t IdleTiers::make_room_locked(int64_t n) { - if (!disk_on() || n <= 0) return 0; - const uint64_t now = rad_mono_ns(); - int64_t freed = 0; - /* HOST RECORDS FIRST, oldest first: nothing is in VRAM to use them, and they become disk - * records. The walk skips the ones whose disk copy has not landed, which are the newest -- - * the writes go out in the order the copies landed -- so it stops close to the front. */ - for (auto it = host_lru_.begin(); it != host_lru_.end() && freed < n;) { - const BlockHash key = *it; - ++it; - auto ri = recs_.find(key); - if (ri == recs_.end()) continue; - Rec& r = ri->second; - if (r.pending || !r.on_disk || r.host_slot < 0 || r.host_slot == r.disk_src || - held_by_fetch(r, now)) - continue; - unlist(r); - free_host(r); - r.tier = KVTier::Disk; - relist(key, r); - ++freed; - } - /* THEN THE HOST COPIES OF CLEAN VRAM ENTRIES, oldest first. The VRAM copy stays and stays - * clean -- its disk copy is what lets it go now. These are on no list (a device record is - * ordered by the cache), so they are found by a walk, which only a full arena of them pays. */ - if (freed < n) { - std::vector> c; - for (auto& kv : recs_) { - Rec& r = kv.second; - if (r.tier == KVTier::Device && !r.pending && r.on_disk && r.host_slot >= 0 && - r.host_slot != r.disk_src && !held_by_fetch(r, now)) - c.emplace_back(r.used_ns, &r); - } - const size_t k = std::min(c.size(), (size_t)(n - freed)); - std::partial_sort(c.begin(), c.begin() + (long)k, c.end(), - [](const auto& a, const auto& b) { return a.first < b.first; }); - for (size_t i = 0; i < k; ++i) { free_host(*c[i].second); ++freed; } - } - stats_.host_freed += freed; - return freed; -} - bool IdleTiers::starved() const { std::lock_guard lk(mu_); return starved_ > 0; @@ -473,7 +299,6 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector* out) { * front of the queue, and the maintenance plan is told how many copies were refused so it can * make that much room. */ const int64_t want = (int64_t)(out->size() - first); - if (want > arena_.free_slots()) make_room_locked(want - arena_.free_slots()); std::vector slots; slots.reserve((size_t)want); while ((int64_t)slots.size() < want) { @@ -527,7 +352,7 @@ bool IdleTiers::droppable(const BlockHash& key) const { auto it = recs_.find(key); if (it == recs_.end()) return false; const Rec& r = it->second; - return !r.pending && !r.doomed && r.tier == KVTier::Device && (r.host_slot >= 0 || r.on_disk); + return !r.pending && !r.doomed && r.tier == KVTier::Device && r.host_slot >= 0; } void IdleTiers::drop_commit(const BlockHash& key) { @@ -536,113 +361,26 @@ void IdleTiers::drop_commit(const BlockHash& key) { if (it == recs_.end()) return; Rec& r = it->second; if (r.tier != KVTier::Device) return; - r.tier = r.host_slot >= 0 ? KVTier::Host : KVTier::Disk; + r.tier = KVTier::Host; ++stats_.dropped; - wb_stuck_ = false; /* with no disk tier, a host record is what a capacity drop takes */ + wb_stuck_ = false; /* a host record is what a capacity drop takes */ relist(key, r); } -bool IdleTiers::snapshot_backed(const BlockHash& key) const { - std::lock_guard lk(mu_); - auto it = recs_.find(key); - if (it == recs_.end()) return false; - const Rec& r = it->second; - return !r.doomed && r.ck_slot >= 0 && r.ck_on_disk && r.ck_disk_src < 0; -} - -void IdleTiers::snapshot_detached(const BlockHash& key) { - std::lock_guard lk(mu_); - auto it = recs_.find(key); - if (it == recs_.end()) return; - it->second.ck_slot = -1; -} - -/* ------------------------------------------------------------------ the slow half */ +/* ------------------------------------------------------------------ capacity and expiry */ void IdleTiers::plan(int budget, std::vector* out) { - if (!any_on() || budget <= 0) return; + if (!host_on() || budget <= 0) return; std::lock_guard lk(mu_); - /* ---- disk copies: the resume points first, then in the order the host copies landed --- */ - /* ONE SNAPSHOT BUDGET FOR THE WAY TO DISK, apart from the blocks'. A snapshot is a hundred - * megabytes or more and the disk store copies it twice on the way out (an aligned bounce, then - * the write), so a plan that sent a session's whole retained set at once would hold the IO - * thread for most of a second. A record whose snapshot the budget left behind still sends its - * blocks, and goes to the back of the queue for the rest. */ - int ck_disk_budget = 2; - int n = 0; - auto take_ck = [&](const BlockHash& key, Rec& r, TierJob& j) { - j.ck_slot = r.ck_slot; - j.ck_pos = r.ck_pos; - j.ck_bytes = cfg_.ckpt_bytes; - r.ck_disk_src = r.ck_slot; - ck_reading_.push_back(r.ck_slot); - --ck_disk_budget; - (void)key; - }; - /* A RESUME POINT IS THE SNAPSHOT THE NEXT TURN NEEDS, and the store can only retire it until - * the disk holds it. Its record's blocks are not waited for: they go through the host tier on - * their own clock. */ - while (ckpt_disk_on() && ck_disk_budget > 0 && !resume_q_.empty() && n < budget) { - const BlockHash key = resume_q_.front(); - resume_q_.pop_front(); - auto ri = recs_.find(key); - if (ri == recs_.end()) continue; - Rec& r = ri->second; - r.resume_q = false; - if (!wants_ck_disk(r)) continue; - TierJob j; - j.kind = TierJob::Kind::ToDisk; - j.key = key; - j.bytes = cfg_.entry_bytes; - take_ck(key, r, j); - out->push_back(std::move(j)); - ++n; - } - std::vector later; - while (disk_on() && !dk_q_.empty() && n < budget) { - const BlockHash key = dk_q_.front(); - dk_q_.pop_front(); - auto ri = recs_.find(key); - if (ri == recs_.end()) continue; - Rec& r = ri->second; - if (!r.disk_q) continue; - r.disk_q = false; - if (!wants_disk(r)) continue; - TierJob j; - j.kind = TierJob::Kind::ToDisk; - j.key = key; - j.bytes = cfg_.entry_bytes; - if (r.host_slot >= 0 && !r.on_disk && r.disk_src < 0) { - j.host_slot = r.host_slot; - r.disk_src = r.host_slot; - } - if (wants_ck_disk(r)) { - if (ck_disk_budget > 0) take_ck(key, r, j); - else later.push_back(key); - } - if (j.host_slot < 0 && j.ck_slot < 0) continue; - out->push_back(std::move(j)); - ++n; - } - for (const BlockHash& k : later) { - auto ri = recs_.find(k); - if (ri != recs_.end()) queue_disk(k, ri->second); - } - - /* ---- capacity, with no disk tier: oldest first ----------------------------------------- */ /* HOW MANY, AND NOT "UNTIL THERE IS ROOM". A queued drop does not free its slot until the * engine reports it, so a loop that tested the arena would queue a drop for every entry on the * list and empty the whole tier to make room for one. The copies refused since the last plan - * say how much room was wanted; this frees exactly that much. With a disk tier the room comes - * from make_room instead, for nothing, once the disk copies above have landed. */ - const int64_t want = starved_; + * say how much room was wanted; this frees exactly that much, least recently used first. */ + const int64_t want = std::min(starved_, budget); starved_ = 0; - if (disk_on()) return; - int n_cap = 0; - for (int64_t k = 0; k < want && n_cap < budget; ) { - if (host_lru_.empty()) break; - auto ri = recs_.find(host_lru_.front()); - if (ri == recs_.end()) { host_lru_.pop_front(); continue; } + for (int64_t k = 0; k < want && !host_lru_.empty();) { + auto ri = recs_.find(host_lru_.begin()->second); + if (ri == recs_.end()) { host_lru_.erase(host_lru_.begin()); continue; } Rec& r = ri->second; TierJob j; j.kind = TierJob::Kind::DropHost; @@ -653,10 +391,17 @@ void IdleTiers::plan(int budget, std::vector* out) { r.pending = true; out->push_back(std::move(j)); ++k; - ++n_cap; } } +void IdleTiers::expired(uint64_t cutoff_ns, size_t max, std::vector* out) const { + std::lock_guard lk(mu_); + /* The list holds no record with a job out (relist), so every key it yields can go now. */ + for (auto it = host_lru_.begin(); + it != host_lru_.end() && it->first < cutoff_ns && out->size() < max; ++it) + out->push_back(it->second); +} + bool IdleTiers::plan_promote(const BlockHash& key, TierJob* out) { std::lock_guard lk(mu_); auto it = recs_.find(key); @@ -669,189 +414,33 @@ bool IdleTiers::plan_promote(const BlockHash& key, TierJob* out) { out->key = key; out->host_slot = r.host_slot; out->bytes = cfg_.entry_bytes; - if (r.fetched_ns) ++stats_.disk_hits; else ++stats_.host_hits; + ++stats_.host_hits; unlist(r); r.pending = true; return true; } -/* THE DEEPEST SNAPSHOT ON THE CHAIN, wherever it is and whatever tier its blocks are on: that is - * the one the hit resumes from, and it is read off disk only when the disk is the one place it - * is. Its record may be in VRAM -- a snapshot can leave its slot while its blocks stay -- and then - * the read is of the snapshot alone. A record with a job out is passed over. */ -size_t IdleTiers::deepest_snapshot(const std::vector& chain) const { - size_t deep = chain.size(); - for (size_t i = 0; i < chain.size(); ++i) { - auto it = recs_.find(chain[i]); - if (it == recs_.end()) continue; - const Rec& r = it->second; - if (r.pending || r.doomed) continue; - if (r.ck_slot >= 0 || r.ck_on_disk) deep = i; - } - return deep; -} - -bool IdleTiers::snapshot_fetch_wanted(const std::vector& chain) const { - if (!ckpt_disk_on() || chain.empty()) return false; - std::lock_guard lk(mu_); - const size_t deep = deepest_snapshot(chain); - if (deep >= chain.size()) return false; - const Rec& r = recs_.find(chain[deep])->second; - return r.ck_slot < 0 && r.ck_on_disk; -} - -bool IdleTiers::plan_fetch(const std::vector& chain, std::vector* out, - uint64_t now_ns, int32_t* ck_slot) { - if (!disk_on() || chain.empty()) return false; - std::lock_guard lk(mu_); - bool wait = false; - std::vector recs(chain.size(), nullptr); - std::vector need; /* chain positions whose blocks are only on disk */ - for (size_t i = 0; i < chain.size(); ++i) { - auto it = recs_.find(chain[i]); - if (it == recs_.end()) continue; - Rec& r = it->second; - if (r.fetching) { wait = true; continue; } - if (r.pending || r.doomed || r.tier == KVTier::Device) continue; - recs[i] = &r; - if (r.tier == KVTier::Disk) need.push_back(i); - } - const size_t deep = deepest_snapshot(chain); - Rec* deep_rec = deep < chain.size() ? &recs_.find(chain[deep])->second : nullptr; - const bool ck_read = deep_rec && deep_rec->ck_slot < 0 && deep_rec->ck_on_disk && - ckpt_disk_on() && ck_slot && *ck_slot >= 0; - if (need.empty() && !ck_read) return wait; - - /* THE ROOM, OUT OF EVERYTHING BUT THIS CHAIN. What the disk also holds goes for nothing - * (make_room); the chain's own host copies are what the restore is about to read, and giving - * one up to read another would only move the gap. */ - for (Rec* r : recs) if (r) r->keep = true; - if (deep_rec) deep_rec->keep = true; - std::vector slots; - if (!need.empty()) { - const int64_t want = (int64_t)need.size(); - if (want > arena_.free_slots()) make_room_locked(want - arena_.free_slots()); - slots.reserve((size_t)want); - while ((int64_t)slots.size() < want) { - int32_t got = 0; - const int32_t s = arena_.alloc_run((int32_t)(want - (int64_t)slots.size()), &got); - if (s < 0) break; - for (int32_t k = 0; k < got; ++k) slots.push_back(s + k); - } - } - for (Rec* r : recs) if (r) r->keep = false; - if (deep_rec) deep_rec->keep = false; - - /* IN CHAIN ORDER, AND CUT WHERE THE SLOTS RAN OUT: a hit needs a contiguous prefix, so an entry - * read past a gap would be read for nothing. */ - const size_t first = out->size(); - for (size_t k = 0; k < slots.size(); ++k) { - TierJob j; - j.kind = TierJob::Kind::ToHost; - j.key = chain[need[k]]; - j.host_slot = slots[k]; - j.bytes = cfg_.entry_bytes; - out->push_back(std::move(j)); - } - /* ONLY A SNAPSHOT THE RESTORE WILL REACH: every disk entry at or before it has a slot. - * Otherwise the store slot stays the caller's. */ - if (ck_read && (slots.size() == need.size() || need[slots.size()] > deep)) { - TierJob* j = nullptr; - for (size_t k = first; k < out->size(); ++k) - if ((*out)[k].key == chain[deep]) { j = &(*out)[k]; break; } - if (!j) { - out->push_back(TierJob{}); - j = &out->back(); - j->kind = TierJob::Kind::ToHost; - j->key = chain[deep]; - j->bytes = cfg_.entry_bytes; - } - j->ck_want = true; - j->ck_slot = *ck_slot; - j->ck_pos = deep_rec->ck_pos; - j->ck_bytes = cfg_.ckpt_bytes; - *ck_slot = -1; - } - for (size_t k = first; k < out->size(); ++k) { - Rec& r = recs_[(*out)[k].key]; - unlist(r); - r.pending = true; - r.fetching = true; - r.used_ns = now_ns; - } - return wait || out->size() > first; -} - void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { std::lock_guard lk(mu_); auto it = recs_.find(job.key); - - /* A DISK WRITE IS NOT A PENDING JOB, so it is settled before anything below touches the - * record's pending state -- which may belong to a restore running beside it. The slots it - * read are the record's, unless the record gave them up (or went) while the write was out: - * then the write's report is what frees them. */ - if (job.kind == TierJob::Kind::ToDisk) { - if (!ok) ++stats_.failures; - Rec* r = it == recs_.end() ? nullptr : &it->second; - if (job.host_slot >= 0) { - if (r && r->disk_src == job.host_slot) r->disk_src = -1; - if (!r || r->host_slot != job.host_slot) give_slot(job.host_slot); - else if (ok) { set_on_disk(*r, true); ++stats_.to_disk; } - } - if (job.ck_slot >= 0) { - /* THE STORE SLOT IS FREE TO WRITE AGAIN, and one the cache let go of meanwhile goes - * back now. */ - auto rd = std::find(ck_reading_.begin(), ck_reading_.end(), job.ck_slot); - if (rd != ck_reading_.end()) ck_reading_.erase(rd); - auto fa = std::find(ck_free_after_.begin(), ck_free_after_.end(), job.ck_slot); - if (fa != ck_free_after_.end()) { - ck_free_after_.erase(fa); - ck_frees_.push_back(job.ck_slot); - } - /* ON DISK ONLY IF THE RECORD STILL NAMES THE SLOT THE WRITE READ. A new commit at this - * key, or a release by the cache, moved it while the write ran, and the bytes that - * landed describe a state nobody holds any more; a new commit is written on its own. */ - if (r && r->ck_disk_src == job.ck_slot) { - r->ck_disk_src = -1; - if (ok && job.ck_ok && r->ck_slot == job.ck_slot) { - r->ck_on_disk = true; - ++stats_.ck_to_disk; - } - } - if (r) queue_disk(job.key, *r); - } - /* A write that failed is not tried again: a store that refused it once will refuse the - * next, and the entry stays host-only, which is what it was before. */ - return; - } - - /* A store slot a read was given and nothing took goes back to the store. */ - auto ck_back = [&] { if (job.ck_want && job.ck_slot >= 0) ck_frees_.push_back(job.ck_slot); }; - if (it == recs_.end()) { - /* Nothing names the slots a job was handed but the job itself. */ + /* Nothing names the slots a copy was handed but the job itself. */ if (job.kind == TierJob::Kind::WriteBack) give_slot(job.host_slot); - ck_back(); return; } Rec& r = it->second; r.pending = false; - r.fetching = false; - /* A promotion the chain was cut before, or a read that never ran, is not a failure: nothing - * was tried. */ - const bool may_skip = job.kind == TierJob::Kind::ToDevice || job.kind == TierJob::Kind::ToHost; - if (!ok && (!may_skip || job.started)) ++stats_.failures; + /* A promotion the chain was cut before is not a failure: nothing was tried. */ + if (!ok && (job.kind != TierJob::Kind::ToDevice || job.started)) ++stats_.failures; /* A record that was forgotten mid-transfer is finished off here and nowhere else. Doing it at * the top, before the per-kind handling, means no branch below has to remember to check. */ if (r.doomed) { - /* THE JOB'S SLOTS AND THE RECORD'S ARE NOT THE SAME SLOTS on every path. A copy's host - * slots were the job's until it reported, and a promotion out of disk ran through a join - * slot the record never owned; freeing only the record's would leak those, and freeing - * the job's as well where they ARE the record's would return one slot twice. */ + /* THE JOB'S SLOT AND THE RECORD'S ARE NOT THE SAME SLOT on every path. A copy's host slot + * is the job's until it reports; freeing only the record's would leak it, and freeing the + * job's as well where it IS the record's would return one slot twice. */ if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot); - ck_back(); - release_storage(job.key, r); + free_host(r); recs_.erase(it); return; } @@ -871,8 +460,6 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { if (r.tier == KVTier::Device && r.host_slot >= 0) queue_clean(job.key, r); /* A copy that failed is tried again. */ queue_copy(job.key, r); - /* And what landed goes on to disk. */ - queue_disk(job.key, r); return; } @@ -882,16 +469,12 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { r.blocks = job.blocks; /* THE HOST COPY IS KEPT, which is what makes the entry clean the moment it lands: * its VRAM copy can go again at no cost, and the next copy this conversation needs - * is only of the tokens its next turn adds. A disk entry keeps the slot it was - * read into for the same reason -- it holds exactly the entry's bytes -- and keeps - * its disk copy, which is what lets that slot go again for nothing. */ + * is only of the tokens its next turn adds. */ r.host_slot = job.host_slot; /* THE CLOCK RESTARTS: the entry came back because a request is about to hit it. */ if (now_ns) r.used_ns = now_ns; - r.fetched_ns = 0; ++stats_.promoted; queue_clean(job.key, r); - queue_disk(job.key, r); return; } if (!job.started) { @@ -908,68 +491,19 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { * still holds an entry naming blocks that are not ours any more, and left alone it * would serve them. */ if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot); - release_storage(job.key, r); + free_host(r); recs_.erase(it); + drop_rooted(job.key); if (on_drop_) on_drop_(job.key); return; case TierJob::Kind::DropHost: - give_slot(job.host_slot); + free_host(r); ++stats_.host_drops; - r.host_slot = -1; - release_storage(job.key, r); recs_.erase(it); + drop_rooted(job.key); if (on_drop_) on_drop_(job.key); return; - - case TierJob::Kind::ToHost: { - if (!job.started) { - /* NEVER READ: the slots go back and the record is where it was, on disk. */ - give_slot(job.host_slot); - ck_back(); - relist(job.key, r); - return; - } - if (!ok) { - /* THE STORE NO LONGER HOLDS WHAT THE RECORD SAYS IT DOES -- its own eviction does - * not tell the tiers, and a slot that fails its verify is dropped by the read. The - * record claims bytes nobody has, so it goes, and the cache has to hear so. */ - give_slot(job.host_slot); - ck_back(); - release_storage(job.key, r); - recs_.erase(it); - if (on_drop_) on_drop_(job.key); - return; - } - if (job.host_slot >= 0) { - r.host_slot = job.host_slot; - r.tier = KVTier::Host; - ++stats_.fetched; - } - if (job.ck_want && job.ck_slot >= 0) { - /* THE SNAPSHOT IS IN ITS STORE SLOT AGAIN, and keeps its disk copy -- which is what - * lets the slot go again for nothing. The engine hands the slot to the cache's - * index entry (PrefixCache::reattach_snapshot). */ - if (job.ck_ok && r.ck_slot < 0) { - r.ck_slot = job.ck_slot; - ++stats_.ck_fetched; - } else { - ck_back(); - if (!job.ck_ok && r.ck_slot < 0 && r.ck_on_disk) { - /* The disk store lost it; the blocks are still good. */ - r.ck_on_disk = false; - ++stats_.ck_drops; - if (on_ck_drop_) on_ck_drop_(job.key); - } - } - } - r.fetched_ns = now_ns ? now_ns : rad_mono_ns(); - relist(job.key, r); - return; - } - - case TierJob::Kind::ToDisk: - return; /* settled above */ } } @@ -1094,11 +628,11 @@ std::vector IdleTiers::sessions(Occupancy* occ) const { out.push_back(std::move(si)); } } - /* SNAPSHOTS IN THE STORE AND ON DISK, each once. The store is the engine's and is not read - * from this thread, and a disk snapshot has only a flag on its record -- but this walk visits - * every record a stored conversation reaches, so it counts them here. They are sparse, one - * per checkpoint interval, so the sets stay small beside the walk that fills them. */ - std::unordered_set disk_snaps, host_snaps; + /* SNAPSHOTS IN THE STORE, each once. The store is the engine's and is not read from this + * thread -- but this walk visits every record a stored conversation reaches, so it counts them + * here. They are sparse, one per checkpoint interval, so the set stays small beside the walk + * that fills it. */ + std::unordered_set host_snaps; size_t kept = 0; for (size_t k = 0; k < out.size(); ++k) { SessionInfo& si = out[k]; @@ -1124,17 +658,14 @@ std::vector IdleTiers::sessions(Occupancy* occ) const { switch (rr.tier) { case KVTier::Device: ++si.on_device; break; case KVTier::Host: ++si.on_host; break; - case KVTier::Disk: ++si.on_disk; break; } - /* THE LINEAR HALF, COUNTED WHERE ITS BYTES ACTUALLY ARE and not where the blocks - * are: a snapshot is in host memory from the moment it is saved, whatever tier - * its blocks are on, and on disk alone once the store has given its slot up. */ - const bool ck = rr.ck_slot >= 0 || rr.ck_on_disk; - if (rr.ck_slot >= 0) { ++si.snapshots; ++si.snap_host; } - else if (rr.ck_on_disk) { ++si.snapshots; ++si.snap_disk; } - if (rr.ck_on_disk && occ) disk_snaps.insert(h); - if (rr.ck_slot >= 0 && occ) host_snaps.insert(h); - if (ck && rr.ck_pos > si.resume_tokens) si.resume_tokens = rr.ck_pos; + /* THE LINEAR HALF, which is in host memory from the moment it is saved, whatever + * tier its blocks are on. */ + if (rr.ck_slot >= 0) { + ++si.snapshots; + if (occ) host_snaps.insert(h); + if (rr.ck_pos > si.resume_tokens) si.resume_tokens = rr.ck_pos; + } } if (at >= chain.size()) break; } @@ -1152,12 +683,10 @@ std::vector IdleTiers::sessions(Occupancy* occ) const { Slice lk(mu_); occ->host_bytes = arena_.used_slots() * cfg_.entry_bytes + (int64_t)host_snaps.size() * cfg_.ckpt_bytes; - occ->disk_bytes = stats_.disk_bytes + (int64_t)disk_snaps.size() * cfg_.ckpt_bytes; /* What the operator gave the block arena and the snapshot store -- the same scope as * `host_bytes` above, which counts both. */ occ->host_cap_bytes = (host_on() ? cfg_.host_cap_bytes : 0) + cfg_.ckpt_slots * cfg_.ckpt_bytes; - occ->disk_cap_bytes = disk_on() ? cfg_.disk_cap_bytes : 0; } return out; } diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h index 24add901..3c15e6bd 100644 --- a/core/mem/kvtier.h +++ b/core/mem/kvtier.h @@ -1,5 +1,5 @@ /* kvtier.h -- where a finished conversation's KV is kept once VRAM has a better use for it - * (spec §7.3). + * (spec §7.3): VRAM, then host memory, and nowhere else. * * The prefix cache holds a KV reference on every block it indexes, so a finished turn's context * survives into the next one. That is the whole value of it, and it is also the whole cost: those @@ -20,15 +20,14 @@ * published --(copy, at once)--> clean on device --(memory wanted)--> host * ^ | * +------------(a hit restores)------+ - * host copy --(copy to disk, at once)--> clean on host --(a slot wanted)--> disk * - * THE DISK TIER IS A COPY TOO, by the same argument one level down. Every host copy is written to - * the disk store in the background as soon as it lands, and keeps its host slot. Once the write - * has landed the host slot is as free to give up as a clean entry's VRAM: when a copy or a - * restore needs a slot and the arena is full, the oldest entries the disk also holds give theirs - * up, which is bookkeeping and nothing else. Moving an entry to disk only when its slot is wanted - * would put a write on the path of whatever wanted it -- a restore out of disk needs a host slot to - * read through, and an arena full of host-only entries has no slot to give it at all. + * HOST MEMORY IS THE LAST TIER. When a copy needs a slot and the arena is full, the oldest + * entries only the host holds are dropped, as many as the copies refused. Nothing is written to a + * drive: a tier there wears it at the rate the server prefills -- every block and every snapshot a + * prompt produces -- to spare a re-prefill only for what outgrows VRAM and host memory together. + * + * AND EVERY ENTRY EXPIRES. One no request has used for --prefix-cache-ttl seconds leaves the cache + * from whichever tier holds it (PrefixCache::expire); it is not moved anywhere first. * * THERE IS NO IDLE THRESHOLD ON THE WAY OUT OF VRAM, and that is the point of the design rather * than an omission. A threshold is a guess at when an entry stops being worth its VRAM, made in @@ -74,8 +73,7 @@ * is on no list: the copy it keeps off the card is what lets the VRAM copy go, and the tiers' * lists are for entries no longer in VRAM. A Rec with a transfer through the pool outstanding is * `pending` and is in no list either: it cannot be chosen as a victim, cannot be planned again, - * and cannot be erased until the engine reports the job finished or failed. A disk write is not - * such a transfer -- it reads host memory and nothing else -- and holds only the slots it reads. + * and cannot be erased until the engine reports the job finished or failed. */ #pragma once #include "mem/hostarena.h" @@ -86,7 +84,7 @@ #include #include #include -#include +#include #include #include #include @@ -96,9 +94,7 @@ namespace rad { -class SSDTier; - -enum class KVTier : uint8_t { Device = 0, Host = 1, Disk = 2 }; +enum class KVTier : uint8_t { Device = 0, Host = 1 }; const char* kv_tier_name(KVTier t); /* What the engine is being asked to do. One job is one entry moving one step. The block ids are @@ -107,47 +103,23 @@ const char* kv_tier_name(KVTier t); struct TierJob { enum class Kind : uint8_t { WriteBack, /* gather_rows out of the pool into a host slot; the entry stays in VRAM */ - ToDisk, /* a host slot written to the disk store; the host copy is kept */ ToDevice, /* allocate blocks, scatter_rows in; the host copy is kept */ - DropHost, /* no disk tier and the arena is full: this record's bytes go */ - ToHost, /* the disk store read into a host slot, ahead of the restore that wants it */ + DropHost, /* the arena is full: this record's bytes go */ }; Kind kind = Kind::WriteBack; BlockHash key; /* Per cached group, in PrefixCache::cached_groups() order. For a write-back these are the - * blocks to read -- EMPTY when only the snapshot is being copied, because the blocks already - * have their host copy; for a promotion they are filled in by the engine with the blocks it + * blocks to read; for a promotion they are filled in by the engine with the blocks it * allocated. */ std::vector blocks; int32_t host_slot = -1; int64_t bytes = 0; - /* ---- the linear half, on a hybrid model ---- - * - * A session's recurrent state lives in a SNAPSHOT SLOT of the checkpoint store -- pinned host - * memory, one contiguous KVManager::checkpoint_bytes() shard a rank -- rather than in blocks, - * so it never crosses the link with them: a lookup restores it straight out of its slot. The - * tiers only move it between that slot and the disk store, on the disk thread: a ToDisk job - * reads `ck_slot`, a ToHost job writes it. - * - * `ck_slot` is an INPUT to both. A read off disk is planned with `ck_want` and the engine - * allocates the slot before the job leaves its hands (it holds the store's free list); a - * write names the slot the snapshot is in. */ - int32_t ck_slot = -1; - int64_t ck_pos = 0; /* the token position, which the disk store verifies on the way back */ - bool ck_want = false; /* a read off disk should bring the snapshot in too */ - int64_t ck_bytes = 0; - /* DID THE SNAPSHOT HALF SUCCEED. Separate from the job's own result because the two halves - * fail for different reasons and are repaired differently: a snapshot whose disk write failed - * is still correct in its slot, and one whose read failed costs the session a replay of its - * linear layers, not its blocks. */ - bool ck_ok = true; /* A PROMOTION THAT WAS NEVER STARTED, as opposed to one that failed part of the way through. * A restore reserves every block before it moves a byte, and a chain that did not fit is cut * where the reservation ran out: the entries past that point were not touched, their host * copies are exactly what they were, and they stay on the host tier. Only an entry whose - * scatter may have run is dropped on failure. A read off disk that never ran -- its batch - * could not be handed to the thread -- is the same: the record stays on disk. */ + * scatter may have run is dropped on failure. */ bool started = false; }; @@ -156,23 +128,19 @@ class IdleTiers { public: struct Config { int64_t host_cap_bytes = 0; /* 0 is off */ - int64_t disk_cap_bytes = 0; int64_t entry_bytes = 0; /* one entry: sum over cached groups of bytes_per_block */ /* ---- the linear half ---- * `ckpt_bytes` is ONE SNAPSHOT, every rank's shard of it, laid out exactly like * `entry_bytes`. The snapshots live in the engine's checkpoint store, `ckpt_slots` deep, - * which is reported here and not allocated: --prefix-cache-host-mib is the blocks' alone. - * `ckpt_disk_slots` zero means snapshots never reach disk, and the blocks still do. */ + * which is reported here and not allocated: --prefix-cache-mib is the blocks' alone. */ int64_t ckpt_bytes = 0; int64_t ckpt_slots = 0; /* the checkpoint store's capacity, for the report and view */ - int64_t ckpt_disk_slots = 0; /* how many the disk store was opened for */ }; - int configure(const Config& c, SSDTier* disk); + int configure(const Config& c); void close(); bool host_on() const { return cfg_.host_cap_bytes > 0 && arena_.enabled(); } - bool disk_on() const { return cfg_.disk_cap_bytes > 0 && disk_ != nullptr; } - bool any_on() const { return host_on() || disk_on(); } + bool any_on() const { return host_on(); } std::string report() const; /* Called by PrefixCache whenever an entry is inserted. The blocks come with it because a copy @@ -189,7 +157,7 @@ public: * storage it held is returned. A record with work outstanding is marked instead of erased and * is cleaned up when the job reports. */ void forget(const BlockHash& key); - /* AN OFF-DEVICE ENTRY WAS RECOMPUTED. A request that could not reach the tier copy -- a + /* AN OFF-DEVICE ENTRY WAS RECOMPUTED. A request that could not reach the host copy -- a * restore that did not fit, a chain past the point a promotion was cut -- computes the same * tokens again and publishes them, and the cache takes those blocks as the entry's device * copy. The tier copy goes: two copies of one entry computed by two different batches agree @@ -209,10 +177,9 @@ public: * slots already allocated. Oldest first, so a conversation that went idle before another is * copied before it. Blocks only: a snapshot is in host memory from the moment it is saved. * - * Every record named by a returned job is `pending` until report() is called for it. An arena - * too full to take the batch first gives up the host slots of the oldest entries the disk also - * holds (make_room); what is still short stays queued, and with no disk tier the next - * maintenance plan drops that many of the oldest host-only entries. */ + * Every record named by a returned job is `pending` until report() is called for it. What an + * arena too full to take the batch cannot hold stays queued, and the next maintenance plan + * drops that many of the oldest host-only entries. */ void plan_writeback(int64_t max_entries, std::vector* out); bool writeback_waiting() const; /* Has the arena refused a copy since the last maintenance plan? That plan is then due now. */ @@ -223,87 +190,36 @@ public: * free nothing -- and reports what it did through drop_commit. A key handed out here and not * dropped is the cache's to ask about again. */ void take_clean(std::vector* out); - /* Can this entry's blocks leave VRAM for nothing, right now: a copy off the card has landed -- - * in host memory or on disk -- and no job is out on the record. */ + /* Can this entry's blocks leave VRAM for nothing, right now: its host copy has landed and no + * job is out on the record. */ bool droppable(const BlockHash& key) const; /* The cache released the blocks. The record is now a host record with its copy, on the host - * tier's list like any other -- or a disk record, when its host slot was already given up. - * Its snapshot stays in its slot: the store is not the pool, and the blocks leaving frees - * nothing there. */ + * tier's list like any other. Its snapshot stays in its slot: the store is not the pool, and + * the blocks leaving frees nothing there. */ void drop_commit(const BlockHash& key); - /* ---------------- the snapshots' own pressure ---------------- + /* ---------------- capacity ---------------- * - * The checkpoint store is --checkpoint-slots deep for the whole server, and when it is full - * the cache retires the least recently used snapshot to make room. One the disk also holds - * need not be lost: the cache DETACHES it instead -- the slot goes back, the index entry - * stays, and the next restore of the session reads the state back off disk (plan_fetch). - * True when this key's snapshot is in a slot and has a finished disk copy that no write is - * still producing. */ - bool snapshot_backed(const BlockHash& key) const; - /* Is this key's snapshot in store slot `slot` by this object's record? */ - bool snapshot_in_slot(const BlockHash& key, int32_t slot) const; - /* The cache gave the slot back; the disk copy is now the snapshot. */ - void snapshot_detached(const BlockHash& key); - - /* ---------------- the slow half ---------------- - * - * The host copies waiting for their disk copy, in the order they landed, as ToDisk jobs -- - * blocks and snapshot halves together where both are waiting, and a resume point's snapshot - * ahead of everything (note_snapshot). A ToDisk job does NOT make its record pending: it only - * reads the host slots it names, which a restore may read at the same time, and a slot given - * up while the write is out is freed when the write reports rather than under it. With no disk tier, the copies the arena refused since the last plan - * are made room for by dropping that many of the oldest host-only entries. `budget` bounds - * one plan so the IO a pass asks for is bounded too. */ + * The copies the arena refused since the last plan are made room for by dropping that many of + * the oldest host-only entries, as DropHost jobs; `budget` bounds one plan. */ void plan(int budget, std::vector* out); - /* Is a host copy waiting for its disk copy? The slow half is then due now rather than on its - * once-a-second clock: an entry the disk does not hold yet is one whose host slot cannot be - * given up for nothing. */ - bool disk_waiting() const; - /* ROOM IN THE ARENA, FOR NOTHING. Up to `n` host slots of entries the disk also holds, given - * up oldest first: host records first -- they become disk records -- and then the host copies - * of clean VRAM entries, which stay clean through their disk copy. Nothing is written; an - * entry whose disk copy has not landed is not a candidate. Returns how many were freed. */ - int64_t make_room(int64_t n); - - /* ---------------- reading a chain back off disk, before its request runs ---------------- + /* ---------------- expiry ---------------- * - * A RESTORE COPIES HOST MEMORY TO THE DEVICE AND NOTHING ELSE. It runs inside the scheduler's - * step, and a disk read there -- thousands of entries for a long conversation -- would hold - * every other request's next token for as long as the reads take. So the disk half of a chain - * is read into host slots on the IO thread first, as ToHost jobs, while the request that wants - * it waits outside admission and everything else keeps running; the restore then finds the - * chain in host memory. - * - * `chain` is every key a prompt's prefix matched, in order. True when the request must wait: - * a read for one of its entries was planned now, into `out`, or is already out. False when - * none of the chain is on disk, or none of what is can be given a slot -- a chain larger than - * the arena comes back as far as the arena holds, and the rest is prefilled. - * - * The chain's deepest snapshot, when it is only on disk, is read with it -- that is the state - * the hit resumes from -- into the store slot `*ck_slot` the caller allocated after asking - * snapshot_fetch_wanted. The slot is taken (and `*ck_slot` set to -1) only when the read is - * planned; otherwise it is still the caller's to free. Every record named is `pending` until - * the read reports, and what a read brought in is not given up to make room for anybody else - * until the request has had the step it needs to claim it. */ - bool plan_fetch(const std::vector& chain, std::vector* out, - uint64_t now_ns, int32_t* ck_slot = nullptr); - /* Would plan_fetch read this chain's deepest snapshot off disk -- is it there and nowhere - * else? Asked first, because the slot it reads into is the store's, which the caller owns. */ - bool snapshot_fetch_wanted(const std::vector& chain) const; + * THE HOST RECORDS NO REQUEST HAS USED SINCE `cutoff_ns`, oldest first, up to `max`: what + * --prefix-cache-ttl takes out of host memory. The cache drops each one (drop_offdevice) and + * the record goes with it; a record with a job out is passed over and asked about again. */ + void expired(uint64_t cutoff_ns, size_t max, std::vector* out) const; /* A promotion, asked for by a lookup that hit off-device. Returns false when the entry is not - * in host memory -- a disk entry is read in by plan_fetch first -- or already has work - * outstanding. */ + * in host memory or already has work outstanding. */ bool plan_promote(const BlockHash& key, TierJob* out); /* The engine finished (or failed) a job. On failure the record returns to the state it was in * with its storage intact, EXCEPT for a failed ToDevice that had started, which cannot leave a - * half-scattered pool behind and so drops the entry -- and a disk read that failed is marked - * started for that reason too: the store no longer holds what the record says it does. A - * successful ToDevice restarts the record's clock at `now_ns` when one is given: the promotion - * happened because something is about to use it. */ + * half-scattered pool behind and so drops the entry. A successful ToDevice restarts the + * record's clock at `now_ns` when one is given: the promotion happened because something is + * about to use it. */ void report(const TierJob& job, bool ok, uint64_t now_ns = 0); /* WAS THIS KEY FORGOTTEN WHILE ITS JOB WAS OUT -- or is it not known at all. The engine asks @@ -314,8 +230,8 @@ public: /* ============================ WHEN THE BYTES ARE GONE, SO IS THE ENTRY ==================== * - * A record erased while its bytes are OFF-DEVICE -- a capacity drop, or a promotion that - * failed -- leaves the prefix cache holding an entry whose block ids the pool has already + * A record erased while its bytes are OFF-DEVICE -- a capacity drop, a promotion that failed, + * an expiry -- leaves the prefix cache holding an entry whose block ids the pool has already * given to somebody else. `resident_off_device` then answers false, because there is no * record any more, and the cache would serve those ids as an ordinary hit: one conversation * gets another's context, as fluent and plausible text. @@ -326,43 +242,18 @@ public: /* ---------------- the linear half of an idle session ---------------- * - * Told by PrefixCache::commit_checkpoint, for the same reason note_used carries the block ids: - * a copy has to know what to move and the cache's index is the only place it is written down. - * `slot` is a checkpoint store slot and `pos` the token position the disk store verifies a - * read against. - * - * A record may hear this BEFORE it hears note_used -- a checkpoint is committed mid-request - * and the chain is published when the request closes -- so this creates the record if it has - * to. The snapshot is queued for its disk copy when the record is published, or at once when - * it already was -- or AT ONCE AND AHEAD OF EVERYTHING when it is a resume point (`resume`): - * the deepest checkpoint its prompt gets, which the next turn resumes from. Until it is on disk - * the store can only retire it, and a burst of prefills churns the store through the whole - * decode in between. */ - void note_snapshot(const BlockHash& key, int32_t slot, int64_t pos, bool resume = false); - /* The cache is done with the snapshot at `key`, which is in store slot `slot`: return whatever - * the tiers hold for it. The record's BLOCKS are untouched -- the two halves are retired by - * different policies on different clocks, and a snapshot the retention policy drops says - * nothing about the prefix. - * - * TRUE WHEN A DISK WRITE IS STILL READING THE SLOT, and then the slot is NOT the caller's to - * free: a save into it would put half of another snapshot on disk under this key. The tiers - * keep the slot and hand it back through `take_checkpoint_frees` once the write has reported. - * Decided by the slot and not by the record, which may have gone while the write was out. */ - bool release_snapshot(const BlockHash& key, int32_t slot); - /* Store slots whose release waited on a disk write, now safe to free. */ - void take_checkpoint_frees(std::vector* out); - /* Is a disk write reading store slot `slot` right now? A save into it would tear the write. */ - bool slot_reading(int32_t slot) const; - /* THE TIERS LOST A SNAPSHOT BUT KEPT THE BLOCKS: its only copy was on disk and the disk store - * no longer has it. The cache has to stop offering an index entry whose bytes nobody holds. - * Wired to PrefixCache::drop_snapshot; separate from set_drop_sink because losing half an - * entry and losing all of it are different events with different repairs. Never said of a - * snapshot still in its slot: that one is the cache's. */ - void set_snapshot_drop_sink(std::function f) { on_ck_drop_ = std::move(f); } - /* Do snapshots reach disk at all? */ - bool ckpt_disk_on() const { return disk_on() && cfg_.ckpt_bytes > 0 && cfg_.ckpt_disk_slots > 0; } + * Told by PrefixCache::commit_checkpoint and PrefixCache::retire_ckpt, so the session view can + * say which conversations hold a snapshot and where a return resumes from. A snapshot lives in + * its checkpoint store slot, in host memory, and never moves: the tiers only record it. A + * record may hear of a snapshot BEFORE it hears note_used -- a checkpoint is committed + * mid-request and the chain is published when the request closes -- so this creates the + * record if it has to. */ + void note_snapshot(const BlockHash& key, int32_t slot, int64_t pos); + /* The cache is done with the snapshot at `key`. The record's BLOCKS are untouched -- the two + * halves are retired by different policies on different clocks, and a snapshot the retention + * policy drops says nothing about the prefix. */ + void release_snapshot(const BlockHash& key); int64_t ckpt_bytes() const { return cfg_.ckpt_bytes; } - int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; } int64_t ckpt_slots() const { return cfg_.ckpt_slots; } /* ---------------- the session view ---------------- @@ -375,11 +266,7 @@ public: * * THE SIZES THEREFORE OVERLAP AND THE TOTAL IS NOT A SUM. Sharing is the point of the cache; * a view that hid it would make a server look like it was storing several times what it is. - * Anything reporting these numbers says so. - * - * The model name is carried rather than looked up because the disk tier outlives the process: - * a store written by one container and read back under another is refused by fingerprint, and - * the name is what turns that refusal into something an operator can act on. */ + * Anything reporting these numbers says so. */ struct SessionInfo { uint64_t id = 0; std::string model; @@ -388,36 +275,34 @@ public: int64_t bytes = 0; uint64_t first_seen_ns = 0; uint64_t last_used_ns = 0; - int64_t on_device = 0, on_host = 0, on_disk = 0; /* blocks, by tier */ + int64_t on_device = 0, on_host = 0; /* blocks, by tier */ /* LINEAR STATE, on a hybrid model. Counted separately from blocks because it is a * different resource with a different scarcity: a snapshot is thousands of blocks' worth * of bytes and there are only --checkpoint-slots of them in host memory. A session showing - * blocks on disk and no snapshot anywhere is one that will come back and re-run every + * blocks in host memory and no snapshot is one that will come back and re-run every * recurrent layer over its whole transcript, which is not what "restored" should mean. */ - int64_t snapshots = 0; /* this session holds, any tier */ - int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */ + int64_t snapshots = 0; /* this session holds */ int64_t snap_bytes = 0; - /* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain, in any - * tier. On a hybrid model the scheduler clamps a hit to the last linear checkpoint it can + /* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain. On a + * hybrid model the scheduler clamps a hit to the last linear checkpoint it can * reach, so this -- not n_tokens and not the blocks -- is the prefix the next turn skips, * and n_tokens minus it is what that turn prefills. Zero with no snapshot anywhere. */ int64_t resume_tokens = 0; bool moving = false; /* a job is outstanding */ }; - /* WHAT THE TIERS OFF THE CARD ARE HOLDING, blocks and snapshots together, each counted once. - * The per-session figures cannot be summed into this: sessions sharing a prefix share its - * blocks and its snapshots. Caps are what the operator configured, snapshots included. A - * clean entry's host copy is counted: it occupies the arena whether or not the VRAM copy has - * gone yet. */ + /* WHAT HOST MEMORY IS HOLDING FOR THE CACHE, each block counted once. The per-session figures + * cannot be summed into this: sessions sharing a prefix share its blocks. The cap is what the + * operator configured. A clean entry's host copy is counted: it occupies the arena whether or + * not the VRAM copy has gone yet. */ struct Occupancy { - int64_t host_bytes = 0, disk_bytes = 0; - int64_t host_cap_bytes = 0, disk_cap_bytes = 0; + int64_t host_bytes = 0; + int64_t host_cap_bytes = 0; }; /* Publish one request's chain. Called from PrefixCache::insert, which is the only place that * knows a chain was completed rather than merely touched. * * KEPT WHETHER OR NOT ANY TIER IS ON, because what it records is not a tiering fact. A server - * with no --prefix-cache-host-mib still stores conversations -- it stores them all in VRAM, which + * with no --prefix-cache-mib still stores conversations -- it stores them all in VRAM, which * is the case the table most wants to show -- and gating the record on the mover would make * the view report an empty server to every operator who has not opted into tiering. * @@ -441,19 +326,11 @@ public: * then given up. They are different events: a copy is link traffic and a drop is VRAM * handed to something else, and a conversation that returns before anything wants its * VRAM is copied and never dropped. */ - int64_t to_host = 0, dropped = 0, to_disk = 0, promoted = 0; - /* `host_freed` is host slots given up because the disk holds the entry -- the host tier's - * counterpart of `dropped`; `host_drops` is entries lost with no disk tier to hold them. */ - int64_t host_freed = 0, host_drops = 0, failures = 0; - int64_t host_bytes = 0, disk_bytes = 0; - int64_t host_hits = 0, disk_hits = 0; - /* Entries and snapshots read off disk into host memory ahead of a restore. */ - int64_t fetched = 0, ck_fetched = 0; - /* SNAPSHOTS MOVED, counted apart from blocks. A hybrid session can move its whole chain - * off the device and still replay every linear layer from zero on the way back, and no - * block counter can tell the two apart -- these are the numbers that can. `ck_drops` is - * snapshots whose only copy was lost. */ - int64_t ck_to_disk = 0, ck_drops = 0; + int64_t to_host = 0, dropped = 0, promoted = 0; + /* `host_drops` is entries the full arena gave up. */ + int64_t host_drops = 0, failures = 0; + int64_t host_bytes = 0; + int64_t host_hits = 0; /* WHAT THE STEP THREAD SPENT ON THEM, under the scheduler's lock: restores issued at * admission, and copies landed synchronously because pressure could not wait for them. * Host time, not link time -- what every other request waits through. */ @@ -474,72 +351,34 @@ private: KVTier tier = KVTier::Device; uint64_t used_ns = 0; /* THE HOST COPY. On a device record it is a copy that makes the record clean; on a host - * record it is where the bytes are read from. -1 on a disk record always. */ + * record it is where the bytes are read from. */ int32_t host_slot = -1; - /* THE DISK STORE HOLDS THESE BYTES, written from the host copy. What makes the host slot - * free to give up, and a device record with no host copy clean. The store evicts on its own - * and does not say so; a read that finds the entry gone drops it (report). */ - bool on_disk = false; - /* The host slot a disk write is reading right now, -1 when none. A slot given up while - * this names it is freed when the write reports, not under it. */ - int32_t disk_src = -1; - bool disk_q = false; /* in dk_q_: waiting for a disk copy */ bool pending = false; - bool fetching = false; /* the pending job is a read off disk (plan_fetch) */ bool doomed = false; /* forget() arrived while pending */ bool queued = false; /* in wb_q_: waiting for a copy */ - bool resume_q = false; /* in resume_q_: a resume point waiting for its disk copy */ bool clean_q = false; /* in clean_q_: a drop the cache has not been asked about */ - bool listed = false; /* on host_lru_ or disk_lru_; `it` is valid */ + bool listed = false; /* on host_lru_; `it` is valid */ std::vector blocks; /* ---- the linear half ---- - * `ck_slot` is the snapshot's checkpoint store slot and `ck_on_disk` the disk store's - * copy. A snapshot the store gave up has only the second. All clear when the record - * carries no snapshot, which is the common case -- one block in every - * (interval / block_size) is a checkpoint position. */ + * `ck_slot` is the snapshot's checkpoint store slot and `ck_pos` its token position, for the + * session view. -1 when the record carries no snapshot, which is the common case -- one + * block in every (interval / block_size) is a checkpoint position. */ int32_t ck_slot = -1; - bool ck_on_disk = false; int64_t ck_pos = 0; - /* The store slot a disk write is reading, as `disk_src` is for the blocks. */ - int32_t ck_disk_src = -1; - /* WHEN A READ OFF DISK BROUGHT THIS RECORD IN, 0 when none did or its restore has run. - * Until the request that asked for it has been admitted the slots are its and not the - * arena's to give up: two conversations waiting on reads into a full arena would - * otherwise each evict what the other had read, and neither would ever be restored. Held - * for kFetchHoldNs at most, which bounds what a request that went away can pin. */ - uint64_t fetched_ns = 0; - /* Set only while plan_fetch makes room: this record is part of the chain being read, and - * giving its slot up to read another part of the same chain would be no progress. */ - bool keep = false; - std::list::iterator it; + std::multimap::iterator it; }; /* Does this record want a host copy it does not have yet? Its blocks are in VRAM with none. */ bool wants_copy(const Rec& r) const; - /* And a disk copy: a host copy of either half that the disk does not hold yet. */ - bool wants_disk(const Rec& r) const; - bool wants_ck_disk(const Rec& r) const; void queue_copy(const BlockHash& key, Rec& r); void queue_clean(const BlockHash& key, Rec& r); - void queue_disk(const BlockHash& key, Rec& r); /* GIVE UP A HOST SLOT, the record's or a finished job's. Every block-arena free goes through * `give_slot`, because a freed slot is what unblocks a write-back that found the arena full. - * `free_host` is the record's own: a slot a disk write is reading is left - * for that write's report to free. */ + * `free_host` is the record's own. */ void give_slot(int32_t slot); void free_host(Rec& r); - void set_on_disk(Rec& r, bool v); - int64_t make_room_locked(int64_t n); - /* May this record's host copies be given up to make room right now? Not while a read put - * them there for a request that has not claimed them yet, nor while the chain being read - * includes it. */ - bool held_by_fetch(const Rec& r, uint64_t now_ns) const; void unlist(Rec& r); void relist(const BlockHash& key, Rec& r); - std::list& list_for(KVTier t) { return t == KVTier::Host ? host_lru_ : disk_lru_; } - void release_storage(const BlockHash& key, Rec& r); - /* The chain position of the deepest snapshot no job is out on, or chain.size(). */ - size_t deepest_snapshot(const std::vector& chain) const; struct Session { int64_t n_tokens = 0; @@ -551,6 +390,8 @@ private: /* Erase one row and its root index entry together. */ void drop_session(uint64_t id); + /* Every row whose chain starts at `key`, which has gone for good. */ + void drop_rooted(const BlockHash& key); /* The body of close(), for a caller that already holds the lock. */ void reset(); @@ -594,42 +435,37 @@ private: mutable YieldingMutex mu_; Config cfg_; - SSDTier* disk_ = nullptr; HostArena arena_; std::unordered_map recs_; - std::list host_lru_, disk_lru_; /* front = oldest */ + /* THE HOST-ONLY RECORDS BY LAST USE, begin() the least recently used. Keyed by the clock rather + * than kept in the order records arrive, because a record arrives here when its VRAM copy is + * given up, which says nothing about when a request last read it -- and both the capacity drop + * and the expiry take the oldest by use. */ + std::multimap host_lru_; /* THE WORK QUEUES, in the order the work arrived. Each holds a key at most once -- the Rec's * flag says whether it is in -- and a key whose record changed under it is skipped when it is * reached rather than searched for, so both stay a push and a pop. */ std::deque wb_q_; /* records wanting a host copy */ - std::deque resume_q_; /* resume points wanting a disk copy, served first */ - std::deque dk_q_; /* records wanting a disk copy, in the order they landed */ std::vector clean_q_; /* records whose VRAM copy may now go */ - /* STORE SLOTS A DISK WRITE IS READING, and those the cache let go of meanwhile. Kept by slot - * and not on the record, because the record can be forgotten while the write is out and the - * slot is the cache's either way. A few entries at most: one write batch is out at a time. */ - std::vector ck_reading_; - std::vector ck_free_after_; - std::vector ck_frees_; /* store slots a finished write released */ /* COPIES THE ARENA REFUSED since the last maintenance plan, which is what that plan frees * room for. A count and not a list: any host-only entry makes room for any copy. */ int64_t starved_ = 0; /* A WRITE-BACK FOUND THE ARENA FULL AND NOTHING TO GIVE UP. Waiting again changes nothing until - * a slot is freed or an entry's disk copy lands, so the copy is not planned until one does -- - * otherwise every tick pops the queue, finds no slot and puts it back. */ + * a slot is freed, so the copy is not planned until one is -- otherwise every tick pops the + * queue, finds no slot and puts it back. */ bool wb_stuck_ = false; std::unordered_map sessions_; /* THE DEATH SIGNAL FOR A ROW, and the reason the table is bounded. A published chain is only * ever reachable from position zero, so the moment the cache evicts its FIRST block the * conversation cannot be hit at any length and the row describes blocks that are not there. - * The cache announces every eviction through forget(), which is the only notice this object - * gets, so the root is indexed and the row goes with it. Several sessions share a root when + * The cache announces its evictions and expiries through forget(), and the entries this object + * drops itself -- a full arena's, a failed restore's -- go through drop_rooted as well, so the + * root is indexed and the row goes with it. Several sessions share a root when * they share a system prompt and all of them are unreachable together, which is why the value * is a list. */ std::unordered_map, BlockHashHash> roots_; std::string model_; std::function on_drop_; - std::function on_ck_drop_; Stats stats_; std::string report_; }; diff --git a/core/mem/pools.cpp b/core/mem/pools.cpp index 9be5cb2a..5ad56832 100644 --- a/core/mem/pools.cpp +++ b/core/mem/pools.cpp @@ -199,7 +199,7 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity, const int64_t MiB = 1024 * 1024; const int64_t w = cfg.vram_weights_mib * MiB; const int64_t kv = cfg.vram_kv_mib * MiB; - const int64_t hp = (cfg.host_pool_mib + cfg.embedding_host_mib) * MiB; + const int64_t hp = cfg.host_pool_total_mib() * MiB; /* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM. * core/mem/vram_budget.cpp derived them from the card, the measured driver residency and the diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index 142bee1a..2b894d48 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -13,9 +13,7 @@ namespace rad { * shared and long-lived is usually keyed by SHA-256, because a cheap hash's collision would serve * one caller another caller's context. We get the same guarantee more cheaply: every entry keeps * its BLOCK'S TOKEN IDS and compares them on a hit, so a collision is a miss rather than a wrong - * answer, and the hash only has to be good enough to keep the bucket chains short. The SSD tier, - * which is such a store, carries the token ids into the slot header for the same reason - * (sstier.h). + * answer, and the hash only has to be good enough to keep the bucket chains short. * * splitmix64's finaliser, which is a full 64-bit bijection -- so folding one token cannot lose the * bits of the previous one, which is the failure mode of a plain multiply-xor chain. */ @@ -219,10 +217,11 @@ std::vector PrefixCache::chain_all(const std::vector& tokens return hs; } -void PrefixCache::touch(const BlockHash& h) const { +void PrefixCache::touch(const BlockHash& h, uint64_t now_ns) const { auto it = map_.find(h); if (it == map_.end() || !it->second.in_lru) return; lru_.splice(lru_.end(), lru_, it->second.lru); + it->second.used_ns = now_ns; } CacheHit PrefixCache::lookup(const std::vector& tokens, @@ -274,7 +273,7 @@ CacheHit PrefixCache::lookup(const std::vector& tokens, auto best = ck_by_prefix_.end(); for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) { const Ckpt& c = it->second; - if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > limit || + if (!c.valid || c.slot < 0 || c.pos <= 0 || c.pos > limit || c.pos % block_size_ != 0) continue; if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue; @@ -302,8 +301,9 @@ CacheHit PrefixCache::lookup(const std::vector& tokens, } } + const uint64_t now = rad_mono_ns(); for (int64_t b = 0; b < matched; ++b) { - touch(hs[(size_t)b]); + touch(hs[(size_t)b], now); if (!blocks_out) continue; const Entry& e = map_.find(hs[(size_t)b])->second; for (size_t g = 0; g < groups_.size(); ++g) @@ -313,7 +313,7 @@ CacheHit PrefixCache::lookup(const std::vector& tokens, * entry leaves the device, and without this it runs from when the chain was published, so a * prefix hit on every turn -- or one just promoted back for this very lookup -- would read as * idle and be demoted from under the request using it. */ - if (tiers_ && matched > 0) tiers_->note_hits(hs.data(), matched, rad_mono_ns()); + if (tiers_ && matched > 0) tiers_->note_hits(hs.data(), matched, now); hit.n_attn_tokens = (int32_t)(matched * block_size_); stats_.block_hits += matched; stats_.block_misses += n_full - matched; @@ -336,6 +336,7 @@ CacheHit PrefixCache::lookup(const std::vector& tokens, hit.n_linear_tokens = (int32_t)best->second.pos; hit.checkpoint_slot = best->second.slot; best->second.used = ++clock_; + best->second.used_ns = now; handed_.push_back(best->first); ++stats_.ckpt_hits; return hit; @@ -359,7 +360,7 @@ int PrefixCache::insert(uint64_t session, for (int64_t b = 0; b < n_full; ++b) { const BlockHash& h = hs[(size_t)b]; auto it = map_.find(h); - if (it != map_.end() && it->second.in_lru) { touch(h); continue; } + if (it != map_.end() && it->second.in_lru) { touch(h, now); continue; } if (it != map_.end()) { /* AN ENTRY WHOSE ONLY COPY IS OFF THE CARD, AND THIS REQUEST JUST COMPUTED IT AGAIN -- * a restore that did not fit, or a chain cut short. The request's blocks become the @@ -379,6 +380,7 @@ int PrefixCache::insert(uint64_t session, } Entry& e = it->second; e.blocks = std::move(mine); + e.used_ns = now; lru_.push_back(h); e.lru = std::prev(lru_.end()); e.in_lru = true; @@ -403,6 +405,7 @@ int PrefixCache::insert(uint64_t session, } e.tokens.assign(tokens.begin() + b * block_size_, tokens.begin() + (b + 1) * block_size_); + e.used_ns = now; lru_.push_back(h); e.lru = std::prev(lru_.end()); e.in_lru = true; @@ -460,15 +463,13 @@ int PrefixCache::insert(uint64_t session, /* ------------------------------------------------------------------ idle session tiers */ std::vector PrefixCache::restorable_from(const std::vector& tokens, - const std::vector& mm, - std::vector* chain) const { + const std::vector& mm) const { std::vector out; - if (chain) chain->clear(); if (!enabled_ || !tiers_ || tokens.empty()) return out; /* THE BLOCKS A HIT CAN USE: one token must remain to compute a logit from, so a prompt that * ends on a block boundary never reuses its last block (lookup backs off by one) and neither - * restoring it nor bringing back a snapshot keyed there would be read. */ + * restoring it would be read. */ const int64_t n_full = ((int64_t)tokens.size() - 1) / block_size_; std::vector hs = chain_all(tokens, mm, n_full); @@ -495,7 +496,6 @@ std::vector PrefixCache::restorable_from(const std::vector& if ((int64_t)it->second.tokens.size() != block_size_ || std::memcmp(it->second.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) != 0) break; - if (chain) chain->push_back(hs[(size_t)b]); if (tiers_->resident_off_device(hs[(size_t)b])) out.push_back(hs[(size_t)b]); } return out; @@ -510,13 +510,9 @@ void PrefixCache::drop_offdevice(const BlockHash& key) { if (it->second.in_lru) lru_.erase(it->second.lru); map_.erase(it); ++stats_.evictions; - /* AND THE SNAPSHOT KEYED BY THE SAME HASH, when the disk was all it had: its record is gone, - * and an index entry left behind would be a detached snapshot nobody can read back. One still - * in its store slot stays -- no lookup reaches it past the missing block, the slot may be - * under a disk write this sink cannot ask about, and the retention policy retires it through - * the path that does ask (retire_ckpt). */ - auto ck = ck_by_prefix_.find(key); - if (ck != ck_by_prefix_.end() && ck->second.detached) drop_snapshot(key); + /* A SNAPSHOT KEYED BY THE SAME HASH STAYS. No lookup reaches it past the missing block, and + * the retention policy or the expiry retires it through the path that tells the tiers + * (retire_ckpt) -- this one is called by the tiers, holding their lock. */ } int PrefixCache::rebind(const BlockHash& key, const std::vector& blocks) { @@ -533,6 +529,8 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector& blocks e.blocks = blocks; for (size_t g = 0; g < groups_.size(); ++g) kv_->cache_reserved_block(groups_[g], blocks[g]); if (!e.in_lru) { + /* A restore is a use: a request is about to hit it. */ + e.used_ns = rad_mono_ns(); lru_.push_back(key); e.lru = std::prev(lru_.end()); e.in_lru = true; @@ -552,7 +550,9 @@ int64_t PrefixCache::evict_lru(int64_t n) { * goes to the back rather than being evicted: releasing the cache's reference on it frees no * block, and an entry that had no host copy would be erased for nothing. It is in use, which is * what the back of the list means, and moving it is what keeps a caller that asks again from - * walking the same shared run every time. */ + * walking the same shared run every time. It is stamped as used, which keeps the list in the + * clock's order. */ + const uint64_t now = rad_mono_ns(); for (int64_t seen = (int64_t)lru_.size(); done < n && seen > 0 && !lru_.empty(); --seen) { const BlockHash h = lru_.front(); auto it = map_.find(h); @@ -560,6 +560,7 @@ int64_t PrefixCache::evict_lru(int64_t n) { Entry& e = it->second; if (shared_with_live(e)) { lru_.splice(lru_.end(), lru_, lru_.begin()); + e.used_ns = now; continue; } lru_.pop_front(); @@ -587,6 +588,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) { /* TIERS ATTACHED AND OFF are no tiers: nothing becomes droppable, and waiting for a copy that * nobody will make would leave the reserve unkept for good. */ const bool keep = tiers_ && tiers_->any_on(); + const uint64_t now = rad_mono_ns(); int64_t done = 0; auto it = lru_.begin(); for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_blocks && seen > 0; @@ -599,6 +601,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) { /* In use: to the back, as evict_lru does, and the walk carries on from the next. */ auto next = std::next(it); lru_.splice(lru_.end(), lru_, it); + e.used_ns = now; it = next; continue; } @@ -670,7 +673,7 @@ int64_t PrefixCache::drop_clean() { * the answer by the group count. * * OFF-DEVICE ENTRIES COUNT FOR NOTHING. A demoted entry released its blocks, and the mark went - * with the release; its bytes are on the host or on disk and it is holding none of the card. */ + * with the release; its bytes are in host memory and it is holding none of the card. */ int64_t PrefixCache::unshared_tokens() const { if (!kv_ || groups_.empty() || block_size_ <= 0) return 0; return kv_->cache_only_blocks(groups_[0]) * block_size_; @@ -717,19 +720,11 @@ int64_t PrefixCache::retain(uint64_t session) { auto it = ck_by_session_.find(session); if (it == ck_by_session_.end()) return 0; - /* SNAPSHOTS IN THE STORE ONLY. This policy exists to spend a fixed number of --checkpoint- - * slots well, and it runs when the store is exhausted. A detached snapshot occupies none of - * it, so retiring one would free nothing here and would cost a session the state it was - * written to disk precisely in order to keep. The disk store bounds its own, oldest first, - * which is the right policy for the resource it actually spends. - * - * It stays in `kept` rather than being skipped, or the session index would forget it. */ std::vector> all; std::vector kept; for (const BlockHash& h : it->second) { auto e = ck_by_prefix_.find(h); if (e == ck_by_prefix_.end()) continue; - if (e->second.detached) { kept.push_back(h); continue; } all.push_back({e->second.pos, h}); } std::sort(all.begin(), all.end(), @@ -748,15 +743,6 @@ int64_t PrefixCache::retain(uint64_t session) { if (handed(a.second)) { kept.push_back(a.second); continue; } auto e = ck_by_prefix_.find(a.second); if (e == ck_by_prefix_.end()) continue; - /* A SNAPSHOT THE DISK HOLDS LEAVES THE SLOT AND STAYS IN THE INDEX: the policy is about - * the slots, and that copy costs none of them. */ - if (tiers_ && tiers_->snapshot_backed(a.second)) { - (void)detach_snapshot(a.second); - tiers_->snapshot_detached(a.second); - kept.push_back(a.second); - ++freed; - continue; - } retire_ckpt(e); ++freed; ++stats_.ckpt_evictions; @@ -786,30 +772,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa } auto existing = ck_by_prefix_.find(prefix); if (existing != ck_by_prefix_.end()) { - /* A DETACHED SNAPSHOT IS NOT ONE THIS CALL CAN HAND BACK. Returning its -1 slot would - * look to the scheduler exactly like a refusal (it tests `cs >= 0`) and the chunk would - * silently stop checkpointing; handing back a slot that is not in the store would be - * worse. The state is about to be recomputed anyway -- that is what a reservation at this - * prefix means -- so the disk copy is retired and a fresh slot allocated below. */ - /* NOR ONE A DISK WRITE IS READING. The save that follows this reservation writes the slot - * while the write reads it, and the disk would keep a snapshot that is half of each. A - * fresh slot costs one allocation. */ - if (!existing->second.detached && - !(tiers_ && tiers_->slot_reading(existing->second.slot))) { - *slot_out = existing->second.slot; - return RAD_OK; - } - /* ONE HANDED OUT THIS STEP IS NOT RETIRED either: an admission restores from it ahead of - * the step. This chunk goes without a checkpoint, which costs a later hit some replay. */ - if (handed(prefix)) return RAD_E_FULL; - const uint64_t vs = existing->second.session; - retire_ckpt(existing); - auto sit = ck_by_session_.find(vs); - if (sit != ck_by_session_.end()) { - sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), prefix), - sit->second.end()); - if (sit->second.empty()) ck_by_session_.erase(sit); - } + existing->second.used_ns = rad_mono_ns(); + *slot_out = existing->second.slot; + return RAD_OK; } int32_t slot = -1; @@ -843,14 +808,7 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa const Ckpt* victim = nullptr; const Ckpt* tip_victim = nullptr; for (const auto& kvp : ck_by_prefix_) { - /* A DETACHED SNAPSHOT IS NOT A CANDIDATE, because evicting it frees nothing HERE. - * Its slot went back to the store when it was detached, so picking it as the - * victim would retire a usable snapshot and then fail the retry anyway. */ - if (kvp.second.detached) continue; - /* NOR ONE A DISK WRITE IS READING: its slot comes back only when the write - * reports, so retiring it now loses the snapshot and frees nothing yet. */ - if (tiers_ && tiers_->slot_reading(kvp.second.slot)) continue; - /* NOR ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot + /* NOT ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot * ahead of the step, and a slot freed under it restores nothing. */ if (handed(kvp.first)) continue; auto sit = ck_by_session_.find(kvp.second.session); @@ -868,54 +826,34 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa } if (!victim) victim = tip_victim; if (!victim) return RAD_E_FULL; - BlockHash vh = victim->prefix; - uint64_t vs = victim->session; - /* A VICTIM THE DISK HOLDS IS DETACHED, NOT LOST. The slot goes back all the same; the - * index entry stays, and the session's next restore reads the state back instead of - * replaying every recurrent layer from an older point. */ - if (tiers_ && tiers_->snapshot_backed(vh)) { - (void)detach_snapshot(vh); - tiers_->snapshot_detached(vh); - if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL; - Ckpt c; - c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot; - c.used = ++clock_; - ck_by_prefix_.emplace(prefix, c); - ck_by_session_[session].push_back(prefix); - *slot_out = slot; - return RAD_OK; - } + const BlockHash vh = victim->prefix; + const uint64_t vs = victim->session; retire_ckpt(ck_by_prefix_.find(vh)); ++stats_.ckpt_evictions; - auto sit = ck_by_session_.find(vs); - if (sit != ck_by_session_.end()) { - sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), vh), - sit->second.end()); - if (sit->second.empty()) ck_by_session_.erase(sit); - } + unindex_ckpt(vs, vh); if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL; } } Ckpt c; c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot; c.used = ++clock_; + c.used_ns = rad_mono_ns(); ck_by_prefix_.emplace(prefix, c); ck_by_session_[session].push_back(prefix); *slot_out = slot; return RAD_OK; } -void PrefixCache::commit_checkpoint(const BlockHash& prefix, bool resume) { +void PrefixCache::commit_checkpoint(const BlockHash& prefix) { auto it = ck_by_prefix_.find(prefix); if (it == ck_by_prefix_.end()) return; /* One that lost its slot between the reservation and now holds nothing to serve. */ - if (it->second.detached || it->second.slot < 0) return; + if (it->second.slot < 0) return; it->second.valid = true; - /* THE TIERS LEARN THE SNAPSHOT HERE, for the same reason note_used tells them the block ids: - * a demotion has to know what to move and this index is the only place it is written down. - * Before the commit there is nothing to move -- the slot still holds the previous tenant's - * state -- so this is also the earliest moment at which telling them would be true. */ - if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos, resume); + /* THE TIERS LEARN THE SNAPSHOT HERE, for the session view: before the commit the slot still + * holds the previous tenant's state, so this is the earliest moment at which telling them + * would be true. */ + if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos); } @@ -923,73 +861,19 @@ void PrefixCache::commit_checkpoint(const BlockHash& prefix, bool resume) { void PrefixCache::retire_ckpt(std::unordered_map::iterator it) { if (it == ck_by_prefix_.end()) return; - /* THE TIERS ARE ASKED FIRST, because a disk write may be reading the slot: a save into it - * before the write is done would put half of another snapshot on disk under this key. When - * one is, the tiers keep the slot and hand it back once the write has reported. */ - const bool held = tiers_ && tiers_->release_snapshot(it->first, it->second.slot); - if (it->second.slot >= 0 && !held) kv_->free_checkpoint(it->second.slot); - /* TOLD EITHER WAY, AND NOT ONLY WHEN THE DISK HOLDS THE BYTES. The tiers also remember a - * snapshot's slot -- note_snapshot records it at commit, because a disk write has to know - * what to read and this index is the only place it is written down. Freeing that slot here - * without saying so leaves the tiers naming a slot the store has since given to another - * session, and the next write puts THAT session's recurrent state on disk as this one's. The - * text that comes back is fluent, deterministic and about the wrong conversation, which is - * the exact failure the whole tier design is arranged to make impossible. - * - * Not reachable from the tiers' own drop sink, which erases the index entry through - * drop_snapshot instead -- so this never calls back into a record being erased. */ + /* THE TIERS ARE TOLD, because they name the slot too: note_snapshot records it for the session + * view, and a view that kept it would count a slot the store has since given to another + * session as this one's resume point. */ + if (tiers_) tiers_->release_snapshot(it->first); + if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot); ck_by_prefix_.erase(it); } -int PrefixCache::detach_snapshot(const BlockHash& key) { - auto it = ck_by_prefix_.find(key); - if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND; - if (it->second.detached) return RAD_OK; /* already only on disk */ - /* Only ever asked of a snapshot the tiers call backed, which no write is reading. */ - if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot); - it->second.slot = -1; - it->second.detached = true; - /* NOT SERVABLE FROM HERE ON, which is the same state a reserved-but-unwritten snapshot is in - * and is handled by the same branch in lookup(). A hit that reaches this position simply walks - * back to an older checkpoint, or to none -- shorter, never wrong. */ - it->second.valid = false; - return RAD_OK; -} - -int PrefixCache::reattach_snapshot(const BlockHash& key, int32_t slot) { - auto it = ck_by_prefix_.find(key); - if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND; - if (slot < 0) return RAD_E_INVAL; - /* AN ENTRY ALREADY IN A SLOT keeps it: taking the new one would leak the old. The caller gives - * the new slot back. */ - if (!it->second.detached && it->second.slot >= 0) return it->second.slot == slot ? RAD_OK - : RAD_E_STATE; - /* A SLOT THIS ENTRY DID NOT ASK FOR IS STILL ITS OWN. The read allocated it and filled it - * from the disk copy of THIS key's state, so the identity that matters -- which prefix the - * bytes describe -- is carried by the key and not by the slot number it happened to get. */ - it->second.slot = slot; - it->second.detached = false; - it->second.valid = true; - it->second.used = ++clock_; - return RAD_OK; -} - -bool PrefixCache::free_checkpoint_for_restore() { - if (!tiers_) return false; - const Ckpt* victim = nullptr; - for (const auto& kvp : ck_by_prefix_) { - const Ckpt& c = kvp.second; - if (c.detached || c.slot < 0 || !c.valid) continue; - if (victim && c.used >= victim->used) continue; - if (handed(kvp.first)) continue; - if (!tiers_->snapshot_backed(kvp.first)) continue; - victim = &c; - } - if (!victim) return false; - const BlockHash vh = victim->prefix; - (void)detach_snapshot(vh); - tiers_->snapshot_detached(vh); - return true; +void PrefixCache::unindex_ckpt(uint64_t session, const BlockHash& key) { + auto sit = ck_by_session_.find(session); + if (sit == ck_by_session_.end()) return; + sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), key), sit->second.end()); + if (sit->second.empty()) ck_by_session_.erase(sit); } void PrefixCache::hold(uint64_t req, const std::vector& tokens, @@ -1030,25 +914,65 @@ void PrefixCache::release(uint64_t req) { released_ = true; } -void PrefixCache::drop_snapshot(const BlockHash& key) { - auto it = ck_by_prefix_.find(key); - if (it == ck_by_prefix_.end()) return; - const uint64_t session = it->second.session; - /* No release_snapshot on this path: the tiers are the caller, holding their lock, and the - * bytes are already gone. They say this only of a detached snapshot, so there is normally no - * slot to give back. */ - if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot); - ck_by_prefix_.erase(it); - ++stats_.ckpt_evictions; - auto sit = ck_by_session_.find(session); - if (sit == ck_by_session_.end()) return; - sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), key), sit->second.end()); - if (sit->second.empty()) ck_by_session_.erase(sit); -} +/* ------------------------------------------------------------------ expiry */ -int64_t PrefixCache::snapshots_detached() const { +int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) { + if (!enabled_ || ttl_ns == 0 || now_ns <= ttl_ns) return 0; + const uint64_t cutoff = now_ns - ttl_ns; int64_t n = 0; - for (const auto& kvp : ck_by_prefix_) if (kvp.second.detached) ++n; + + /* ---- in VRAM: the LRU list is in the clock's order, so the walk stops at the first entry it + * keeps. A block a running sequence also holds stays allocated -- releasing the cache's + * reference is not freeing the block -- and that sequence publishes it again when it ends. */ + while (!lru_.empty()) { + const BlockHash h = lru_.front(); + auto it = map_.find(h); + if (it == map_.end()) { lru_.pop_front(); continue; } + Entry& e = it->second; + if (e.used_ns >= cutoff) break; + lru_.pop_front(); + e.in_lru = false; + for (size_t g = 0; g < groups_.size(); ++g) + kv_->release_block(groups_[g], e.blocks[g]); + /* The host copy goes with it: an expired entry is not demoted. */ + if (tiers_) tiers_->forget(h); + map_.erase(it); + ++n; + } + + /* ---- only in host memory: the tiers keep these in the clock's order too. */ + if (tiers_) { + std::vector keys; + tiers_->expired(cutoff, (size_t)-1, &keys); + for (const BlockHash& h : keys) { + tiers_->forget(h); + auto it = map_.find(h); + if (it == map_.end() || it->second.in_lru) continue; + map_.erase(it); + ++n; + } + } + + /* ---- snapshots, used when their prefix entry is or when a lookup hands them out. Not one + * that is still being written (a reservation not yet committed) and not one handed out this + * step: its admission restores from the slot ahead of the step. There are --checkpoint-slots + * of them at most, so the whole index is walked. */ + std::vector gone; + for (const auto& kvp : ck_by_prefix_) { + const Ckpt& c = kvp.second; + if (!c.valid || handed(kvp.first)) continue; + auto e = map_.find(kvp.first); + const uint64_t used = std::max(c.used_ns, e == map_.end() ? 0 : e->second.used_ns); + if (used < cutoff) gone.push_back(kvp.first); + } + for (const BlockHash& h : gone) { + auto it = ck_by_prefix_.find(h); + const uint64_t session = it->second.session; + retire_ckpt(it); + unindex_ckpt(session, h); + } + stats_.expired += n; + stats_.ckpt_expired += (int64_t)gone.size(); return n; } } /* namespace rad */ diff --git a/core/mem/prefix.h b/core/mem/prefix.h index b1b28275..3856e337 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -266,11 +266,8 @@ public: * It is a separate call rather than something lookup does because lookup is const and has no * device: a promotion allocates blocks and runs a scatter, which is the engine's to do * between steps and not something a cache query may trigger under the caller. */ - /* `chain`, when given, receives every key the walk matched, wherever it is -- what the tiers - * need to see whether any of it is still being read off disk (IdleTiers::plan_fetch). */ std::vector restorable_from(const std::vector& tokens, - const std::vector& mm, - std::vector* chain = nullptr) const; + const std::vector& mm) const; /* THE TIERS LOST THE BYTES. Erase the entry WITHOUT releasing blocks: an off-device entry * owns none -- demotion released them -- and its recorded ids belong to whoever the pool gave @@ -297,25 +294,10 @@ public: * and re-prefills its whole transcript. * * A snapshot never needs to follow its blocks: it is restored straight out of its slot into - * the new sequence's state, wherever the blocks are. The only tier below the store is disk, - * and a snapshot the disk holds can give its slot up and stay in the index (DETACHED) until a - * read brings it back. */ + * the new sequence's state, wherever the blocks are. There is no tier below the store: a + * snapshot the store retires is gone, and a session that needed it replays its recurrent + * layers from an older one. */ - /* Its bytes are only on disk now: give the slot back and stop offering it. The index entry - * STAYS, because that is what a read off disk puts the snapshot back into, and an entry whose - * state is not in the store is exactly the `valid` flag's existing meaning -- lookup already - * walks past one and falls back to an older position. */ - int detach_snapshot(const BlockHash& key); - /* And back again, into a slot the caller has already filled. */ - int reattach_snapshot(const BlockHash& key, int32_t slot); - /* A STORE SLOT FOR A READ OFF DISK. The store is --checkpoint-slots deep for the whole server, - * and it is full whenever as many sessions have run since; a session whose snapshot is only on - * disk would then replay every recurrent layer from an older point, because its state has - * nowhere to land. One slot is freed by detaching the least recently used snapshot the disk - * also holds -- which the next restore of THAT session reads back -- and never one whose only - * copy is the slot, and never one a lookup has handed out since the step began: that request's - * restore reads the slot ahead of its step. True when a slot was freed. */ - bool free_checkpoint_for_restore(); /* KEEP A WAITING REQUEST'S CHAIN ON THE CARD. An admission that restored a chain and was then * refused -- no free sequence, no room in the pool -- gives its hit back, and its entries are * clean: drop_clean would let them go at the next pass and the next attempt would restore the @@ -329,13 +311,22 @@ public: /* A step's admissions begin. The snapshots the last step's lookups handed out have been read * by its forward, which committed before this step was planned. Until then a handed snapshot * keeps its slot through every path that would give one up: retention, the eviction in - * reserve_checkpoint, and free_checkpoint_for_restore. */ + * reserve_checkpoint, and the expiry. */ void begin_step() { handed_.clear(); } - /* The tiers lost it -- the disk store let it go, a failed read, or an entry they were told to - * forget. Erase the index entry and give back the slot, if it still has one. */ - void drop_snapshot(const BlockHash& key); - /* How many snapshots the index holds whose bytes are only on disk. */ - int64_t snapshots_detached() const; + + /* ---------------- expiry ---------------- + * + * TAKE OUT EVERYTHING NO REQUEST HAS USED FOR `ttl_ns`: entries in VRAM (their blocks go back + * to the pool), entries only the host holds (their slots go back to the arena), and snapshots + * (their store slots go back). An entry is used when a lookup hits it or a request publishes + * it, and a snapshot when its prefix entry is or when a lookup hands it out. Nothing is moved + * anywhere first: an expired conversation is one the operator has said is not coming back. + * + * A PREFIX IS NEVER OLDER THAN WHAT FOLLOWS IT. A hit or a publish stamps every block of the + * chain up to where it ends with one clock, so a conversation expires from its tip inwards and + * a shared system prompt outlives every conversation that still reads it. Returns how many + * entries went. */ + int64_t expire(uint64_t now_ns, uint64_t ttl_ns); /* ---------------- linear checkpoints ---------------- */ /* The next position strictly after `pos` at which the scheduler must split a chunk so that a * checkpoint lands on a boundary (spec §7.1, §7.3). */ @@ -350,9 +341,8 @@ public: int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix, int32_t* slot_out); /* The state named by `prefix` is now IN its slot. Until this is called the reservation is only - * a promise and lookup() will not offer it -- see Ckpt::valid. A `resume` point is copied off - * the card at once (IdleTiers::note_snapshot). */ - void commit_checkpoint(const BlockHash& prefix, bool resume = false); + * a promise and lookup() will not offer it -- see Ckpt::valid. */ + void commit_checkpoint(const BlockHash& prefix); /* Every checkpoint of a session, ascending. */ std::vector checkpoints(uint64_t session) const; /* Apply the retention policy to one session now. Returns how many snapshots were released. @@ -373,6 +363,9 @@ public: * was lost, and a counter that mixed the two would read a working tier as a thrashing * cache. */ int64_t drops = 0; + /* Entries and snapshots --prefix-cache-ttl took, from whichever tier held them. Not + * evictions either: nothing wanted the memory. */ + int64_t expired = 0, ckpt_expired = 0; }; const Stats& stats() const { return stats_; } @@ -386,6 +379,10 @@ private: * valid only while this is set. */ bool in_lru = false; bool drop_wait = false; /* in drop_wait_: clean, but a sequence still reads it */ + /* LAST USE, on the monotonic clock: a hit or a publish. The LRU list is in this order -- + * every path that puts an entry at its back stamps it -- which is what lets the expiry + * stop at the first entry it keeps. */ + uint64_t used_ns = 0; std::list::iterator lru; }; struct Ckpt { @@ -394,30 +391,26 @@ private: BlockHash prefix; int32_t slot = -1; uint64_t used = 0; + uint64_t used_ns = 0; /* reserved, or handed out by a lookup */ /* HAS THE STATE ACTUALLY BEEN WRITTEN INTO THE SLOT YET. reserve_checkpoint runs when the * scheduler PLANS the chunk; the copy happens after the step that computes the state. A * lookup between those two points would hand out a slot holding the previous tenant's * history, which is the exact failure this whole mechanism exists to prevent. */ bool valid = false; - /* ARE THE BYTES ONLY ON DISK. A detached snapshot gave its store slot up because the disk - * holds it, and `slot` is -1 until a read brings it back. Kept as its own flag rather than - * inferred from the slot so that the two reasons a snapshot cannot be served -- not written - * yet, and not here -- stay distinguishable in a debugger and in a report. */ - bool detached = false; }; std::vector chain_all(const std::vector& tokens, const std::vector& mm, int64_t n_blocks) const; - void touch(const BlockHash& h) const; + void touch(const BlockHash& h, uint64_t now_ns) const; /* Does a live sequence hold any of this entry's blocks as well? Then releasing the cache's * reference frees nothing. */ bool shared_with_live(const Entry& e) const; - /* Retire one snapshot whatever tier holds its bytes: a slot goes back to the store, and a disk - * copy goes back to the tiers. One place, because three call sites that each remembered to - * check `detached` would be three places to forget. The session index is the caller's, since - * every caller is already rebuilding or erasing it. */ + /* Retire one snapshot: its slot goes back to the store and the tiers stop naming it. The + * session index is the caller's, since every caller is already rebuilding or erasing it. */ void retire_ckpt(std::unordered_map::iterator it); + /* Take one key out of a session's index entry, and the entry when it empties. */ + void unindex_ckpt(uint64_t session, const BlockHash& key); KVManager* kv_ = nullptr; IdleTiers* tiers_ = nullptr; diff --git a/core/mem/sstier.cpp b/core/mem/sstier.cpp deleted file mode 100644 index e3e01dad..00000000 --- a/core/mem/sstier.cpp +++ /dev/null @@ -1,536 +0,0 @@ -/* sstier.cpp -- see sstier.h. IT HOLDS CONVERSATION CONTENT ON DISK, UNENCRYPTED. */ -#include "mem/sstier.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace rad { - -/* The device layer's alignment, not a second opinion about it: every slot, every header region and - * every staging buffer here is a multiple of it, which is what keeps every transfer on - * DirectFile's aligned fast path and its bounce buffer unallocated. */ -static constexpr int64_t kAlign = DirectFile::alignment(); - -static void* alloc_aligned(int64_t bytes) { - void* p = nullptr; - if (posix_memalign(&p, (size_t)kAlign, (size_t)align_up(bytes, kAlign)) != 0) return nullptr; - return p; -} -static constexpr uint32_t kMagicBlock = 0x4b4c4252u; /* "RBLK" */ -static constexpr uint32_t kMagicCkpt = 0x504b4352u; /* "RCKP" */ - -struct SSSlotHeader { - uint32_t magic; - uint32_t n_tokens; - uint64_t fingerprint; - uint64_t payload_bytes; - uint64_t key_hi, key_lo; - int64_t pos; /* checkpoint: the token position it restores to; 0 for a block */ - uint64_t reserved[3]; -}; - -/* ------------------------------------------------------------------ TokenBucket */ - -const char* ssd_consumer_name(SSDConsumer c) { - switch (c) { - case SSDConsumer::PrefixCache: return "prefix-cache"; - case SSDConsumer::WeightTier: return "weight-tier"; - default: return "?"; - } -} - -static int64_t now_ns() { - return std::chrono::duration_cast( - std::chrono::steady_clock::now().time_since_epoch()).count(); -} - -void TokenBucket::configure(int64_t bytes_per_sec, int64_t burst_bytes) { - std::lock_guard lk(mu_); - rate_ = bytes_per_sec > 0 ? bytes_per_sec : 0; - burst_ = burst_bytes > 0 ? burst_bytes : rate_; - tokens_ = (double)burst_; - last_ns_ = now_ns(); -} - -void TokenBucket::refill_locked() { - int64_t t = now_ns(); - double dt = (double)(t - last_ns_) * 1e-9; - last_ns_ = t; - tokens_ = std::min((double)burst_, tokens_ + dt * (double)rate_); -} - -bool TokenBucket::try_take(int64_t bytes, SSDConsumer who) { - std::lock_guard lk(mu_); - Use& u = use_[(int)who]; - if (rate_ <= 0) { u.bytes += bytes; ++u.grants; return true; } - refill_locked(); - if (tokens_ < (double)bytes) return false; - tokens_ -= (double)bytes; - u.bytes += bytes; - ++u.grants; - return true; -} - -void TokenBucket::take(int64_t bytes, SSDConsumer who) { - int64_t t0 = now_ns(); - bool waited = false; - for (;;) { - if (try_take(bytes, who)) break; - waited = true; - /* Sleep for the deficit rather than spinning. Coarse on purpose: this is a placeholder - * and a precise scheduler for a policy nobody has measured would be effort spent on the - * wrong thing (spec §19.5). */ - std::this_thread::sleep_for(std::chrono::microseconds(200)); - } - if (waited) { - std::lock_guard lk(mu_); - ++use_[(int)who].waits; - use_[(int)who].wait_us += (now_ns() - t0) / 1000; - } -} - -TokenBucket::Use TokenBucket::use(SSDConsumer c) const { - std::lock_guard lk(mu_); - return use_[(int)c]; -} - -std::string TokenBucket::report() const { - std::lock_guard lk(mu_); - std::string s = rate_ > 0 - ? fmt("SSD token bucket: %s/s, burst %s (PLACEHOLDER, spec §19.5)\n", - humanb(rate_).c_str(), humanb(burst_).c_str()) - : std::string("SSD token bucket: off (no measured rate to enforce, spec §19.5)\n"); - for (int i = 0; i < (int)SSDConsumer::N; ++i) - s += fmt(" %-14s %10s in %lld ops, %lld waits totalling %lld ms\n", - ssd_consumer_name((SSDConsumer)i), humanb(use_[i].bytes).c_str(), - (long long)use_[i].grants, (long long)use_[i].waits, - (long long)(use_[i].wait_us / 1000)); - return s; -} - -TokenBucket& rad_ssd_bucket() { static TokenBucket b; return b; } - -/* ------------------------------------------------------------------ SSDTier */ - -std::string SSDTier::disclosure(const std::string& dir) { - return fmt("SSD prefix tier active at %s.\n" - " It stores CONVERSATION CONTENT ON DISK, UNENCRYPTED: the cached KV blocks are a\n" - " lossless function of the prompt, and the prompt's token ids are written beside\n" - " them so a hit can be verified. Anything that persists across restarts says so\n" - " (spec §7.3). Put this directory on storage you are willing to treat as holding\n" - " the text itself.\n", dir.c_str()); -} - -SSDTier::~SSDTier() { close(); } - -static int64_t hdr_region_bytes(int64_t tok_bytes) { - return align_up((int64_t)sizeof(SSSlotHeader) + tok_bytes, kAlign); -} - -int SSDTier::open_store(Store& s, const std::string& path, int64_t payload, int64_t n_slots, - int64_t tok_bytes, bool allow_buffered) { - s.payload = payload; - s.hdr_bytes = hdr_region_bytes(tok_bytes); - s.slot_bytes = s.hdr_bytes + align_up(payload, kAlign); - if (n_slots <= 0) return RAD_OK; - - int flags = RAD_DIO_READ | RAD_DIO_WRITE | RAD_DIO_CREATE; - if (allow_buffered) flags |= RAD_DIO_ALLOW_BUFFERED; - RAD_TRY(s.file.open(path.c_str(), flags)); - - /* Size the store up front. DirectFile does not take a size hint and does not need one -- a - * write past the end extends the file -- but a store laid out in one ftruncate is one extent - * rather than N, which is the difference between a slot read being one seek and being several - * once the filesystem has interleaved somebody else's writes between ours. */ - if (::ftruncate(s.file.fd(), (off_t)(s.slot_bytes * n_slots)) != 0) - RAD_WARN("ftruncate %s to %s: %s -- the store will be extended by its writes instead", - path.c_str(), humanb(s.slot_bytes * n_slots).c_str(), strerror(errno)); - - s.slots.assign((size_t)n_slots, Slot{}); - s.freelist.resize((size_t)n_slots); - for (int64_t i = 0; i < n_slots; ++i) s.freelist[(size_t)i] = (int32_t)(n_slots - 1 - i); - s.stage = alloc_aligned(s.slot_bytes); - if (!s.stage) return RAD_E_NOMEM; - return RAD_OK; -} - -int SSDTier::open(const SSDTierConfig& cfg) { - close(); - cfg_ = cfg; - if (cfg.dir.empty()) { enabled_ = false; return RAD_OK; } - if (cfg.block_payload <= 0 && cfg.ckpt_payload <= 0) { - RAD_ERR("--prefix-cache-dir is set but neither a block payload nor a checkpoint payload was " - "given; there is nothing for the tier to store"); - return RAD_E_INVAL; - } - - /* The engine says so at startup. Not behind a verbosity flag. */ - RAD_WARN("%s", disclosure(cfg.dir).c_str()); - - if (::mkdir(cfg.dir.c_str(), 0700) != 0 && errno != EEXIST) { - RAD_ERR("cannot create %s: %s", cfg.dir.c_str(), strerror(errno)); - return RAD_E_IO; - } - - RAD_TRY(open_store(blocks_, cfg.dir + "/blocks.bin", cfg.block_payload, cfg.n_block_slots, - cfg.block_tokens * (int64_t)sizeof(uint32_t), cfg.allow_buffered)); - RAD_TRY(open_store(ckpts_, cfg.dir + "/ckpts.bin", cfg.ckpt_payload, cfg.n_ckpt_slots, - 0, cfg.allow_buffered)); - - enabled_ = true; - - if (cfg.persistent) { - /* Rebuild the index by scanning the slot headers rather than persisting a separate index - * file. One sequential pass at startup, and no way for an index to disagree with the data - * it names -- which is the failure a separate index file has and which produces exactly - * the "serves one caller another caller's context" outcome this tier verifies against. */ - const int64_t nb = scan_store(blocks_, kMagicBlock); - if (nb < 0) return (int)nb; - const int64_t nc = scan_store(ckpts_, kMagicCkpt); - if (nc < 0) return (int)nc; - RAD_INFO("SSD tier: recovered %lld block and %lld checkpoint slots from %s", - (long long)nb, (long long)nc, cfg.dir.c_str()); - } else { - /* Not persistent means the store must not outlive the process, and unlinking now rather - * than at exit means it also does not outlive a crash. The descriptors stay valid. */ - ::unlink((cfg.dir + "/blocks.bin").c_str()); - ::unlink((cfg.dir + "/ckpts.bin").c_str()); - } - - report_ = fmt("SSD tier %s: %lld block slots x %s, %lld checkpoint slots x %s, %s%s\n", - cfg.dir.c_str(), - (long long)cfg.n_block_slots, humanb(blocks_.slot_bytes).c_str(), - (long long)cfg.n_ckpt_slots, humanb(ckpts_.slot_bytes).c_str(), - blocks_.file.direct() ? "O_DIRECT" : "BUFFERED", - cfg.persistent ? ", persistent" : ", volatile"); - return RAD_OK; -} - -void SSDTier::close() { - for (Store* s : { &blocks_, &ckpts_ }) { - s->file.close(); - if (s->stage) { ::free(s->stage); s->stage = nullptr; } - s->slots.clear(); s->index.clear(); s->freelist.clear(); - } - enabled_ = false; -} - -std::string SSDTier::report() const { - std::string s = report_; - s += fmt(" %lld hits, %lld misses, %lld verify misses, %lld evictions; " - "%s read, %s written\n", - (long long)stats_.hits, (long long)stats_.misses, (long long)stats_.verify_misses, - (long long)stats_.evictions, humanb(stats_.bytes_read).c_str(), - humanb(stats_.bytes_written).c_str()); - s += rad_ssd_bucket().report(); - return s; -} - -void SSDTier::lru_unlink(Store& s, int32_t i) { - Slot& x = s.slots[(size_t)i]; - if (x.prev >= 0) s.slots[(size_t)x.prev].next = x.next; else s.lru_head = x.next; - if (x.next >= 0) s.slots[(size_t)x.next].prev = x.prev; else s.lru_tail = x.prev; - x.prev = x.next = -1; -} - -void SSDTier::lru_push(Store& s, int32_t i) { - Slot& x = s.slots[(size_t)i]; - x.prev = s.lru_tail; - x.next = -1; - if (s.lru_tail >= 0) s.slots[(size_t)s.lru_tail].next = i; else s.lru_head = i; - s.lru_tail = i; -} - -/* THE HEADERS ARE READ MANY AT A TIME. Each is one 4 KiB direct read at its own slot, so a single - * reader waits one device round trip a slot -- some tens of microseconds, over the millions of - * slots a store sized in hundreds of GiB holds, which is over a minute of every start. The device - * serves dozens of such reads at once at little more latency than one, so the scan keeps - * kScanDepth in flight: one thread each, over its own contiguous run of slots with its own staging - * page. The threads only record each slot's verdict in the slot itself; the index, the order and - * the free list are built afterwards in one descending pass, which is the order a single - * sequential reader would produce. */ -static constexpr int64_t kScanDepth = 64; - -int64_t SSDTier::scan_store(Store& s, uint32_t magic) { - if (s.slots.empty()) return 0; - s.index.clear(); - s.freelist.clear(); - s.lru_head = s.lru_tail = -1; - for (Slot& x : s.slots) { x.used = 0; x.prev = x.next = -1; } - - const int64_t n = (int64_t)s.slots.size(); - const int64_t nt = std::min(kScanDepth, n); - std::atomic nomem{false}; - std::vector th; - th.reserve((size_t)nt); - for (int64_t t = 0; t < nt; ++t) - th.emplace_back([&, t] { - void* stage = alloc_aligned(s.hdr_bytes); - if (!stage) { nomem.store(true); return; } - for (int64_t i = n * t / nt; i < n * (t + 1) / nt; ++i) { - if (s.file.read_at(stage, i * s.slot_bytes, s.hdr_bytes) < 0) continue; - const SSSlotHeader* h = (const SSSlotHeader*)stage; - if (h->magic != magic || h->fingerprint != cfg_.fingerprint - || h->payload_bytes != (uint64_t)s.payload) continue; - Slot& x = s.slots[(size_t)i]; - x.key.hi = h->key_hi; - x.key.lo = h->key_lo; - x.pos = h->pos; - x.used = 1; - } - std::free(stage); - }); - for (std::thread& x : th) x.join(); - if (nomem.load()) { - for (Slot& x : s.slots) x.used = 0; - RAD_ERR("SSD tier: no staging page for the header scan"); - return RAD_E_NOMEM; - } - - int64_t live = 0; - for (const Slot& x : s.slots) live += x.used; - s.index.reserve((size_t)live); - s.freelist.reserve((size_t)(n - live)); - for (int64_t i = n - 1; i >= 0; --i) { - if (!s.slots[(size_t)i].used) { s.freelist.push_back((int32_t)i); continue; } - lru_push(s, (int32_t)i); - s.index[s.slots[(size_t)i].key] = (int32_t)i; - } - return live; -} - -int SSDTier::claim(Store& s, const BlockHash& key, int32_t* out) { - auto it = s.index.find(key); - if (it != s.index.end()) { *out = it->second; return RAD_OK; } - if (!s.freelist.empty()) { *out = s.freelist.back(); s.freelist.pop_back(); return RAD_OK; } - - /* LRU. Evicting the DEEPEST entry first would be better -- a deeper block chains more tokens, - * is less shareable, and losing it only shortens the usable prefix, whereas losing a shallow - * one strands everything above it -- but depth is not a property this tier is told. Straight - * LRU until the caller carries depth in. */ - const int32_t victim = s.lru_head; - if (victim < 0) return RAD_E_FULL; - lru_unlink(s, victim); - s.index.erase(s.slots[(size_t)victim].key); - s.slots[(size_t)victim].used = 0; - ++stats_.evictions; - *out = victim; - return RAD_OK; -} - -int SSDTier::put(Store& s, uint32_t magic, const BlockHash& key, int64_t pos, - const int32_t* toks, int32_t n_toks, const void* payload, int64_t bytes) { - if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED; - if (bytes != s.payload) return RAD_E_SHAPE; - if ((int64_t)sizeof(SSSlotHeader) + (int64_t)n_toks * 4 > s.hdr_bytes) return RAD_E_SHAPE; - - int32_t slot = -1; - RAD_TRY(claim(s, key, &slot)); - const int64_t base = (int64_t)slot * s.slot_bytes; - - std::memset(s.stage, 0, (size_t)s.slot_bytes); - SSSlotHeader* h = (SSSlotHeader*)s.stage; - h->magic = magic; - h->n_tokens = (uint32_t)n_toks; - h->fingerprint = cfg_.fingerprint; - h->payload_bytes = (uint64_t)bytes; - h->key_hi = key.hi; h->key_lo = key.lo; - h->pos = pos; - if (n_toks > 0) std::memcpy((char*)s.stage + sizeof(SSSlotHeader), toks, (size_t)n_toks * 4); - std::memcpy((char*)s.stage + s.hdr_bytes, payload, (size_t)bytes); - - rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache); - - /* Payload first, header last. Written front to back, a short write would leave the header - * COMPLETE and the payload truncated, so the slot verifies and the engine loads whatever was - * in the file underneath it -- which is the worst failure this tier can have. - * - * A WRITE THAT FAILS GIVES THE SLOT BACK. claim() took it off the free list or out of the - * index, so returning here without that leaves a slot no list names and the store one slot - * smaller for good. Whatever the slot held before is no longer trustworthy either -- the - * payload may be half overwritten under a header that still verifies -- so the key comes out - * of the index and the header is cleared on a best-effort basis, which keeps a persistent - * store from indexing it again at the next start. */ - int wst = s.file.write_at((char*)s.stage + s.hdr_bytes, base + s.hdr_bytes, - s.slot_bytes - s.hdr_bytes); - if (wst >= 0) wst = s.file.write_at(s.stage, base, s.hdr_bytes); - if (wst < 0) { - auto it = s.index.find(key); - if (it != s.index.end() && it->second == slot) s.index.erase(it); - if (s.slots[(size_t)slot].used) lru_unlink(s, slot); - s.slots[(size_t)slot].used = 0; - s.freelist.push_back(slot); - std::memset(s.stage, 0, (size_t)s.hdr_bytes); - (void)s.file.write_at(s.stage, base, s.hdr_bytes); - return wst; - } - - if (s.slots[(size_t)slot].used) lru_unlink(s, slot); - s.slots[(size_t)slot].key = key; - s.slots[(size_t)slot].used = 1; - s.slots[(size_t)slot].pos = pos; - lru_push(s, slot); - s.index[key] = slot; - ++stats_.writes; - stats_.bytes_written += s.slot_bytes; - return RAD_OK; -} - -int SSDTier::get(Store& s, uint32_t magic, const BlockHash& key, int64_t pos, - const int32_t* toks, int32_t n_toks, void* payload, int64_t bytes) { - if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED; - if (bytes != s.payload) return RAD_E_SHAPE; - auto it = s.index.find(key); - if (it == s.index.end()) { ++stats_.misses; return RAD_E_NOTFOUND; } - const int32_t slot = it->second; - const int64_t base = (int64_t)slot * s.slot_bytes; - - rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache); - RAD_TRY(s.file.read_at(s.stage, base, s.slot_bytes)); - ++stats_.reads; - stats_.bytes_read += s.slot_bytes; - - if (!header_ok(s, s.stage, magic, key, pos, toks, n_toks, bytes)) { - /* Drop it rather than leaving it to fail every future probe: without this a single bad - * slot poisons its prefix permanently. */ - forget_slot(s, slot); - ++stats_.verify_misses; - return RAD_E_NOTFOUND; - } - std::memcpy(payload, (const char*)s.stage + s.hdr_bytes, (size_t)bytes); - lru_unlink(s, slot); - lru_push(s, slot); - ++stats_.hits; - return RAD_OK; -} - -/* Belt and braces on top of the index: verify the header AND the token ids. A store that survives - * a restart, a model change or a layout change would otherwise serve one caller another caller's - * context, and that is not a failure anybody would ever diagnose. */ -bool SSDTier::header_ok(const Store& s, const void* stage, uint32_t magic, const BlockHash& key, - int64_t pos, const int32_t* toks, int32_t n_toks, int64_t bytes) const { - (void)s; - const SSSlotHeader* h = (const SSSlotHeader*)stage; - bool ok = h->magic == magic && h->fingerprint == cfg_.fingerprint - && h->key_hi == key.hi && h->key_lo == key.lo - && h->payload_bytes == (uint64_t)bytes && h->pos == pos - && h->n_tokens == (uint32_t)n_toks; - if (ok && n_toks > 0) - ok = std::memcmp((const char*)stage + sizeof(SSSlotHeader), toks, (size_t)n_toks * 4) == 0; - return ok; -} - -void SSDTier::forget_slot(Store& s, int32_t slot) { - auto it = s.index.find(s.slots[(size_t)slot].key); - if (it != s.index.end() && it->second == slot) s.index.erase(it); - if (s.slots[(size_t)slot].used) lru_unlink(s, slot); - s.slots[(size_t)slot].used = 0; - s.freelist.push_back(slot); -} - -/* READS OUTSTANDING AT ONCE. An NVMe drive reading tens-of-kilobyte extents at random reaches its - * bandwidth only with many requests in flight; a thread each is the simplest way to have them, and - * every thread has an aligned staging buffer of its own. */ -static constexpr int kReaders = 16; - -int SSDTier::get_blocks(const BlockHash* keys, int64_t n, void* const* payloads, int64_t bytes, - char* ok) { - std::lock_guard lk(io_mu_); - Store& s = blocks_; - for (int64_t i = 0; i < n; ++i) ok[i] = 0; - if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED; - if (bytes != s.payload) return RAD_E_SHAPE; - - std::vector slot((size_t)n, -1); - int64_t found = 0; - for (int64_t i = 0; i < n; ++i) { - auto it = s.index.find(keys[i]); - if (it == s.index.end()) { ++stats_.misses; continue; } - slot[(size_t)i] = it->second; - ++found; - } - if (found == 0) return RAD_OK; - - /* The reads, and nothing that touches the index or the order: those are settled after, on this - * thread. 1 read and verified, 2 read and not the key asked for, negative a failed read. */ - std::vector st((size_t)n, 0); - std::atomic next{0}; - auto reader = [&](void* stage) { - for (int64_t i; (i = next.fetch_add(1, std::memory_order_relaxed)) < n;) { - if (slot[(size_t)i] < 0) continue; - rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache); - const int r = s.file.read_at(stage, (int64_t)slot[(size_t)i] * s.slot_bytes, - s.slot_bytes); - if (r < 0) { st[(size_t)i] = r; continue; } - if (!header_ok(s, stage, kMagicBlock, keys[i], 0, nullptr, 0, bytes)) { - st[(size_t)i] = 2; - continue; - } - std::memcpy(payloads[i], (const char*)stage + s.hdr_bytes, (size_t)bytes); - st[(size_t)i] = 1; - } - }; - const int nt = (int)std::min(kReaders, found); - std::vector stages; - for (int t = 1; t < nt; ++t) { - void* p = alloc_aligned(s.slot_bytes); - if (!p) break; - stages.push_back(p); - } - std::vector th; - th.reserve(stages.size()); - for (void* p : stages) th.emplace_back(reader, p); - reader(s.stage); - for (std::thread& t : th) t.join(); - for (void* p : stages) ::free(p); - - for (int64_t i = 0; i < n; ++i) { - const int32_t sl = slot[(size_t)i]; - if (sl < 0 || st[(size_t)i] < 0) continue; - ++stats_.reads; - stats_.bytes_read += s.slot_bytes; - if (st[(size_t)i] == 2) { - forget_slot(s, sl); - ++stats_.verify_misses; - continue; - } - lru_unlink(s, sl); - lru_push(s, sl); - ++stats_.hits; - ok[i] = 1; - } - return RAD_OK; -} - -/* ONE CALLER AT A TIME. Every call is the KV tiers' IO thread today, but a store is one staging - * buffer, one slot table and one index, and nothing about the interface says who may call it. */ -int SSDTier::put_block(const BlockHash& key, const int32_t* toks, int32_t n_toks, - const void* payload, int64_t bytes) { - std::lock_guard lk(io_mu_); - return put(blocks_, kMagicBlock, key, 0, toks, n_toks, payload, bytes); -} -int SSDTier::get_block(const BlockHash& key, const int32_t* toks, int32_t n_toks, - void* payload, int64_t bytes) { - std::lock_guard lk(io_mu_); - return get(blocks_, kMagicBlock, key, 0, toks, n_toks, payload, bytes); -} -int SSDTier::put_checkpoint(const BlockHash& key, int64_t pos, const void* payload, int64_t bytes) { - std::lock_guard lk(io_mu_); - return put(ckpts_, kMagicCkpt, key, pos, nullptr, 0, payload, bytes); -} -int SSDTier::get_checkpoint(const BlockHash& key, int64_t pos, void* payload, int64_t bytes) { - std::lock_guard lk(io_mu_); - return get(ckpts_, kMagicCkpt, key, pos, nullptr, 0, payload, bytes); -} - -} /* namespace rad */ diff --git a/core/mem/sstier.h b/core/mem/sstier.h deleted file mode 100644 index ce55820c..00000000 --- a/core/mem/sstier.h +++ /dev/null @@ -1,181 +0,0 @@ -/* sstier.h -- the optional SSD tier for served attention state and linear checkpoints alike, so - * an agent session does not re-prefill its whole transcript every turn (spec §7.3). - * - * ============================== IT HOLDS CONVERSATION CONTENT ON DISK, UNENCRYPTED ============== - * A KV block IS the prompt: the token ids are stored beside it so a hit can be verified, and the - * cached tensors are a lossless function of the text. Anything that persists it across restarts - * says so, and this engine says so at startup whenever --prefix-cache-dir is set. There is no - * encryption option, no obfuscation, and no claim of one; if the content is sensitive the - * directory must be on storage the operator is willing to treat as sensitive. - * ================================================================================================ - * - * O_DIRECT, same as the weight tier. Going through the page cache would evict the weight tier's own - * file mappings, which is paid for in decode and would never show up as a *cache* problem. O_DIRECT - * wants offsets, lengths and buffers all on the logical block size, so every slot and every - * sub-region here is a multiple of it and there is no unaligned tail to handle. - * - * Spec §19.5 records that prefix-cache and weight-tier contention on one SSD has NO PLAN. The - * TokenBucket below is a placeholder for a measured policy, and it is labelled as one: it is a - * shared byte budget between the two consumers, which at least makes the contention visible and - * boundable instead of invisible. What the right split is, or whether a rate limit is even the - * right shape of answer rather than a priority queue, is a measurement nobody has taken. - */ -#pragma once -#include "device/directio.h" -#include "mem/prefix.h" -#include "rad_core.h" - -#include -#include -#include -#include - -namespace rad { - -/* The O_DIRECT file is the device layer's rad::DirectFile (core/device/directio.h). Every extent - * this tier reads or writes is a whole slot or a whole aligned header region, so every transfer - * lands on its fast path and its bounce buffer is never allocated -- which is the property worth - * stating, since the bounce exists for callers reading a header or a file tail and one on this - * path would mean a slot geometry bug rather than a performance problem. */ - -/* ------------------------------------------------------------------ the shared rate limiter */ -enum class SSDConsumer { PrefixCache = 0, WeightTier = 1, N = 2 }; -const char* ssd_consumer_name(SSDConsumer c); - -/* PLACEHOLDER FOR A MEASURED POLICY (spec §19.5). - * - * Both the prefix cache and the weight tier want O_DIRECT bandwidth and under load they fight. A - * token bucket is the simplest thing that bounds the fight: one shared byte budget, refilled at a - * stated rate, drawn on by both. What it does NOT do is decide who should win, and that is the - * actual open question -- a weight-tier read blocks a layer that is about to execute, while a - * prefix-cache read only makes a prefill shorter, so a priority scheme is probably the right shape - * and a flat rate limit certainly is not. Replace this once there is a workload to measure - * against; the per-consumer counters exist so that measurement has something to read. */ -class TokenBucket { -public: - /* 0 bytes_per_sec disables the limiter entirely, which is the default: an unmeasured rate - * limit that throttles a machine nobody profiled is worse than none. */ - void configure(int64_t bytes_per_sec, int64_t burst_bytes); - bool enabled() const { return rate_ > 0; } - - bool try_take(int64_t bytes, SSDConsumer who); /* non-blocking */ - void take(int64_t bytes, SSDConsumer who); /* sleeps until the budget allows */ - - struct Use { int64_t bytes = 0; int64_t grants = 0; int64_t waits = 0; int64_t wait_us = 0; }; - Use use(SSDConsumer c) const; - std::string report() const; - -private: - void refill_locked(); - - mutable std::mutex mu_; - int64_t rate_ = 0; /* bytes per second */ - int64_t burst_ = 0; - double tokens_ = 0; - int64_t last_ns_ = 0; - Use use_[(int)SSDConsumer::N]; -}; - -/* The one bucket both consumers share. The weight tier (core/place/) draws on the same object; - * that is the entire point of it living here rather than inside either one. */ -TokenBucket& rad_ssd_bucket(); - -/* ------------------------------------------------------------------ the tier */ -struct SSDTierConfig { - std::string dir; /* Config::prefix_cache_dir */ - int64_t block_payload = 0; /* bytes one cached attention block occupies, all groups */ - int64_t block_tokens = 0; /* the attention block size, for the verify */ - int64_t ckpt_payload = 0; /* KVManager::checkpoint_bytes() */ - /* Slot counts are STATED, not derived from statvfs. A tier that sizes itself from the free - * space it happens to see at startup is a tier whose capacity changes when somebody untars - * something, and §6's rule is that budgets do not move on their own. */ - int64_t n_block_slots = 0; - int64_t n_ckpt_slots = 0; - uint64_t fingerprint = 0; /* model + layout identity; a mismatch invalidates the store */ - bool persistent = false; /* keep the files across restarts */ - /* Passes RAD_DIO_ALLOW_BUFFERED. Off by default: the device layer REFUSES a filesystem - * without O_DIRECT rather than downgrading it, because a silent buffered fallback costs the - * weight tier its own page cache and shows up only as a decode regression nobody can - * attribute. The flag is for tests, which run on whatever /tmp happens to be. */ - bool allow_buffered = false; -}; - -class SSDTier { -public: - ~SSDTier(); - int open(const SSDTierConfig& cfg); - void close(); - bool enabled() const { return enabled_; } - - /* The line the engine prints at startup when the flag is on. Not optional. */ - static std::string disclosure(const std::string& dir); - std::string report() const; - - /* Attention blocks. `toks` is the block's token ids: they are stored in the slot header and - * memcmp'd on the way back in, so a hash collision is a miss and never a wrong answer. */ - int put_block(const BlockHash& key, const int32_t* toks, int32_t n_toks, - const void* payload, int64_t bytes); - int get_block(const BlockHash& key, const int32_t* toks, int32_t n_toks, - void* payload, int64_t bytes); - /* MANY BLOCKS AT ONCE, READ IN PARALLEL. A conversation coming back off disk is thousands of - * entries of tens of kilobytes each, and read one at a time they keep the drive at a queue - * depth of one -- a fraction of what it delivers with dozens of reads outstanding. `ok[i]` is - * whether block i was found, read and verified into `payloads[i]`; one that was not is a miss - * exactly as get_block's would be. Blocks stored with no token ids only. */ - int get_blocks(const BlockHash* keys, int64_t n, void* const* payloads, int64_t bytes, - char* ok); - - /* Linear-state checkpoints. Keyed by the chained block hash at the checkpoint position, which - * is exactly what PrefixCache::reserve_checkpoint keys them by in VRAM. */ - int put_checkpoint(const BlockHash& key, int64_t pos, const void* payload, int64_t bytes); - int get_checkpoint(const BlockHash& key, int64_t pos, void* payload, int64_t bytes); - - struct Stats { - int64_t reads = 0, writes = 0, hits = 0, misses = 0, verify_misses = 0, evictions = 0; - int64_t bytes_read = 0, bytes_written = 0; - }; - const Stats& stats() const { return stats_; } - -private: - /* `prev`/`next` link the used slots from least to most recently used, so a full store finds - * the one to give up without a walk. A walk would be over every slot of a store sized in the - * millions, once per write, on the thread that has to keep up with the host tier's copies. */ - struct Slot { BlockHash key; int32_t used = 0; int64_t pos = 0; int32_t prev = -1, next = -1; }; - struct Store { - DirectFile file; - int64_t slot_bytes = 0; - int64_t hdr_bytes = 0; /* header + token ids, padded */ - int64_t payload = 0; - std::vector slots; - std::unordered_map index; - std::vector freelist; - int32_t lru_head = -1, lru_tail = -1; /* least and most recently used */ - void* stage = nullptr; - }; - /* A used slot leaves the order; a slot becomes the most recently used. */ - static void lru_unlink(Store& s, int32_t i); - static void lru_push(Store& s, int32_t i); - - int open_store(Store& s, const std::string& path, int64_t payload, int64_t n_slots, - int64_t tok_bytes, bool allow_buffered); - int64_t scan_store(Store& s, uint32_t magic); - int claim(Store& s, const BlockHash& key, int32_t* out); - int put(Store& s, uint32_t magic, const BlockHash& key, int64_t pos, - const int32_t* toks, int32_t n_toks, const void* payload, int64_t bytes); - int get(Store& s, uint32_t magic, const BlockHash& key, int64_t pos, - const int32_t* toks, int32_t n_toks, void* payload, int64_t bytes); - /* Is the slot read into `stage` the one asked for: this store, this model, this key. */ - bool header_ok(const Store& s, const void* stage, uint32_t magic, const BlockHash& key, - int64_t pos, const int32_t* toks, int32_t n_toks, int64_t bytes) const; - /* A slot whose bytes are not what the index says: out of the index and the order, and free. */ - static void forget_slot(Store& s, int32_t slot); - - SSDTierConfig cfg_; - std::mutex io_mu_; - Store blocks_, ckpts_; - bool enabled_ = false; - Stats stats_; - std::string report_; -}; - -} /* namespace rad */ diff --git a/core/place/mover.cpp b/core/place/mover.cpp index fffe8773..6cf892b5 100644 --- a/core/place/mover.cpp +++ b/core/place/mover.cpp @@ -1115,9 +1115,10 @@ int Mover::drop(int32_t unit, HeatEngine* heat) { * slot or back across the link (reclaim), and a loan that shrinks under it moves it the same way * (balance). There is always somewhere for it to go -- each donor's copy went to a unit * whose budgeted slot it left free, so the free budgeted slots and the free pool slots together - * number at least the donors. The donors are bounded by the turnover slots, and they come out of - * the KV cache's loan only: the arena takes its loan back at every prompt's first chunk, and that - * recall stays a change of address. + * number at least the donors once the quarantine has emptied (a recall drains it first). The + * donors are bounded by the turnover slots, and they come out of the KV cache's loan only: the + * arena takes its loan back at every prompt's first chunk, and that recall stays a change of + * address. * * THE HOTTEST UNIT GIVES ITS COPY -- of the victim's layer, when pool_slot_for asks for one -- * because a donor the engine later demotes needs a pool slot of its own where it would have been a @@ -1458,13 +1459,28 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) { RAD_TRY(flush_moves()); RAD_TRY(rad_stream_sync(mover_)); RAD_TRY(retire(heat)); + /* AND NO SLOT IS STILL IN QUARANTINE. The slots the donors below are owed come back through + * it: a donation's victim leaves its budgeted slot that way, and a promotion that refilled the + * slot leaves its pool slot that way (donor_slot). Looked for before the compute stream has + * passed their barriers, the slots of the last few dispatches' swaps are not free yet, and a + * donor finds nowhere to go. Nothing goes on the compute stream from this drain to the end of + * the recall, which issues only the mover's own copies. */ + RAD_TRY(rad_stream_sync(compute_)); + RAD_TRY(retire(heat)); /* EVERY UNIT PAST THE LOAN GOES BACK TO ITS HOST COPY, which is a change of address -- or, * for a donor (donor_slot), which has none, it moves: into a free budgeted slot, a copy inside * the card, or else back across the link into a free pool slot. One of the two is free for - * every donor (donor_slot says why). Nothing is published until the copies have landed. */ + * every donor once the quarantine is empty (donor_slot says why). Nothing is published until + * the copies have landed. + * + * A DONOR WITH NOWHERE TO GO STAYS WHERE IT IS, and the recall still finishes: every other + * slot is given back and every moved donor published, so the loan stops short only by that + * unit's slot, and a later recall or balance() moves it. Stopping at it instead would leave + * the slots already taken off their units held by nothing, for the life of the process. */ std::vector> freed; std::vector moved; + int stuck = 0; for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) { UnitState& us = unit_[(size_t)u]; if (us.klass < 0 || us.slab_slot < 0) continue; @@ -1477,16 +1493,11 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) { cp.slab.add_free(to); to = -1; } + const int64_t g = to < 0 ? cp.pool.take() : -1; if (to >= 0) { RAD_TRY(rad_memcpy_async(cp.slot_ptr(to), cp.slot_ptr(from), us.bytes, mover_)); us.slab_slot = to; - } else { - const int64_t g = cp.pool.take(); - if (g < 0) { - RAD_ERR("mover: unit %d gave its host copy away and neither a budgeted slot nor " - "a pool slot is free to move it to", (int)u); - return RAD_E_STATE; - } + } else if (g >= 0) { RAD_TRY(rad_memcpy_async((char*)cp.pool_base + g * cp.stride, cp.slot_ptr(from), us.bytes, mover_)); us.pool_slot = g; @@ -1499,6 +1510,9 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) { heat->set_tier(u, Tier::HostPinned); heat->set_busy(u, false); } + } else { + ++stuck; + continue; } --cp.n_donated; ++stats_.relocated; @@ -1525,9 +1539,9 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) { } /* AND NO KERNEL STILL NAMES ONE. The compute stream is the only reader of the slab -- the - * quarantine barrier rests on the same fact -- so once it has drained, nothing already issued - * can reach a slot past the loan, and everything issued from here reads the host copies. */ - RAD_TRY(rad_stream_sync(compute_)); + * quarantine barrier rests on the same fact -- and it drained above with nothing issued since, + * so nothing can reach a slot past the loan, and everything issued from here reads the host + * copies. */ for (const auto& f : freed) pools_[f.first].slab.add_free(f.second); /* EVERY RECORD WAITING ON ONE OF THOSE SLOTS IS DONE WAITING: its barrier is behind the @@ -1550,6 +1564,14 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) { m.slab_slot = m.pool_slot = m.to_slot = -1; } count_flex(); + if (stuck > 0) { + stats_.stranded += (uint64_t)stuck; + RAD_ERR("mover: %d unit(s) that gave their host copy away found no free slot to move to; " + "the %s loan stops at %lld instead of %lld until they move", stuck, + lender == kLendKV ? "KV" : "arena", (long long)loan_held(lender), + (long long)loan_[lender]); + return RAD_E_FULL; + } if (loan_held(lender) > loan_[lender]) { RAD_ERR("mover: recalled the %s loan to %lld and a slot at %lld is still held", lender == kLendKV ? "KV" : "arena", (long long)loan_[lender], @@ -1719,8 +1741,9 @@ std::string Mover::report() const { (unsigned long long)stats_.starved_pool, (unsigned long long)stats_.quarantined); if (stats_.donated) s += fmt(" %llu host copies given by lent units to budgeted victims, %llu such units moved " - "by a recall\n", - (unsigned long long)stats_.donated, (unsigned long long)stats_.relocated); + "by a recall, %llu left past one with no free slot\n", + (unsigned long long)stats_.donated, (unsigned long long)stats_.relocated, + (unsigned long long)stats_.stranded); if (stats_.ssd_reads) s += fmt(" file tier: %llu demand reads (%.2f GiB), each a blocking pread in the middle " "of a dispatch. Raise --host-pool-mib.\n", diff --git a/core/place/mover.h b/core/place/mover.h index 37d889a3..83eb2b50 100644 --- a/core/place/mover.h +++ b/core/place/mover.h @@ -422,8 +422,9 @@ struct MoverStats { uint64_t dropped = 0; /* Host copies a unit in a lent slot gave to a budgeted victim that had no pool slot to go to * (Mover::donor_slot), and such units moved rather than dropped when their loan was recalled - * or shrank. */ - uint64_t donated = 0, relocated = 0; + * or shrank. `stranded` counts the recalls that found no free slot for one of them: it stayed + * past the loan until a later recall or balance() moved it. */ + uint64_t donated = 0, relocated = 0, stranded = 0; uint64_t ssd_reads = 0, ssd_bytes = 0; /* The prefill stager's copies (stage_units): layers staged, units and bytes copied, and * pooled units a buffer had no room left for -- those were read across the link in place. diff --git a/core/place/planner.cpp b/core/place/planner.cpp index b37ec0c3..cba67daa 100644 --- a/core/place/planner.cpp +++ b/core/place/planner.cpp @@ -80,7 +80,7 @@ int strategy_parse(const char* s, Strategy* out) { Budgets Budgets::from(const Config& c) { Budgets b; b.vram_weights = c.vram_weights_mib * 1024 * 1024; - b.host_pool = (c.host_pool_mib + c.embedding_host_mib) * 1024 * 1024; + b.host_pool = c.host_pool_total_mib() * 1024 * 1024; b.ssd = c.weights_disk_tier; return b; } @@ -146,7 +146,8 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement /* 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 emb = false, ngram = false, host = true, direct = true; }; + bool emb = false, ngram = false, host = true, direct = true; + int access = -1; }; std::map, size_t> by_group; std::vector units; @@ -177,6 +178,9 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement if (w < device_ok.size() && !device_ok[w]) mu.mapped = true; if (!weight_file_direct(wi, prog.ctx.world_size)) mu.direct = false; if (w < host_ok.size() && !host_ok[w]) mu.host = false; + /* build_units: the group's strongest access class, which says whether it is a tower's. */ + if (mu.access < 0 || access_strength(wi.decl.access) > access_strength(mu.access)) + mu.access = wi.decl.access; /* The placement flags' tables: model-level, so the unit is this one weight. */ if (layer < 0) { mu.emb = is_embedding_table(prog, w); @@ -198,6 +202,8 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement if (mu.emb && !mu.mapped) out->embedding += b; if (mu.ngram) out->ngram += b; if (mu.ngram && !mu.mapped) out->ngram_device = true; + /* pin_towers moves an encoder tower's unit out of the statics on the same test. */ + if (mu.access == RAD_ACCESS_PER_REQUEST && !mu.mapped && mu.expert < 0) out->tower += b; /* pin_mapped: an n-gram table a device kernel reads stays off the card unless it was * placed in VRAM. */ if (mu.mapped || (mu.ngram && ngram != TablePlacement::Vram)) out->mapped += b; @@ -1073,7 +1079,7 @@ 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; + if (mu.host_forced) p->forced_host_used += pl.bytes; } } } @@ -1142,6 +1148,53 @@ int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) cons return rc; } +/* --vision-tower-placement ram: EVERY UNIT OF AN ENCODER TOWER goes to the pinned host pool before + * any strategy runs, as the embedding does, at the DeviceZeroCopy site: the encoder's kernels read + * the weights over the link in place, once an image or a clip, and a text-only request never + * touches them. A tower's unit is one whose every weight the architecture declared read once per + * request (RAD_ACCESS_PER_REQUEST) -- the test weight_footprint counted out of the statics with, + * so the budget the card was split by is the one spent here. The test is the access class and not + * the unit's level: a tower is model-level weights (a stem, a merger) and a layer unit a block. */ +int Planner::pin_towers(const Config& cfg, Plan* p) const { + if (cfg.tower_resolved != TablePlacement::Ram) return RAD_OK; + auto tower = [](const MoveUnit& mu) { + return mu.access == RAD_ACCESS_PER_REQUEST && mu.expert < 0 && mu.tier != Tier::Mapped && + !mu.host_forced; + }; + int64_t need = 0, n = 0; + for (const MoveUnit& mu : p->units) + if (tower(mu)) { need += mu.slot_bytes; ++n; } + /* Engine::plan resolves Ram only where weight_footprint found a tower with this same test. */ + if (!n) { + RAD_ERR("placement: --vision-tower-placement ram, and this rank's program has no weight it " + "reads once per request"); + p->notes.push_back("--vision-tower-placement ram: no encoder tower to place"); + return RAD_E_STATE; + } + if (need > p->host_budget) { + RAD_ERR("placement: --vision-tower-placement ram: the encoder towers need %s of the pinned " + "host pool and %s of it is left%s", humanb(need).c_str(), + humanb(p->host_budget).c_str(), + p->file_stage_reserve ? " after the file tier's staging" : ""); + p->notes.push_back(fmt("--vision-tower-placement ram: the encoder towers (%s) do not fit " + "the host pool", humanb(need).c_str())); + return RAD_E_NOMEM; + } + for (MoveUnit& mu : p->units) { + if (!tower(mu)) continue; + p->host_budget -= mu.slot_bytes; + p->tower_host_bytes += mu.slot_bytes; + mu.tier = Tier::HostPinned; + mu.site = Site::DeviceZeroCopy; + mu.movable = false; + mu.host_forced = true; + mu.reason = "--vision-tower-placement ram; read over the link in place"; + } + RAD_INFO("placement: the encoder towers, %lld units (%s), in the pinned host pool, read in place " + "(--vision-tower-placement ram)", (long long)n, humanb(need).c_str()); + return RAD_OK; +} + /* ------------------------------------------------------------------ plan */ int Planner::plan(Plan* out) { if (!out || !in_.program || !in_.config) return RAD_E_INVAL; @@ -1216,7 +1269,9 @@ int Planner::plan(Plan* out) { } /* NOT a RAD_TRY: a refusal still leaves `out` filled in far enough to print. */ - const int hrc = pin_embedding(prog, cfg, out); + int hrc = pin_embedding(prog, cfg, out); + const int trc = pin_towers(cfg, out); + if (hrc >= 0) hrc = trc; int rc = assign(out); enforce_op_site_agreement(prog, out); @@ -1329,7 +1384,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] - embedding_host_used).c_str()); + humanb(totals.bytes[(int)Tier::HostPinned] - forced_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()); @@ -1354,6 +1409,9 @@ std::string Plan::report(const Program& prog) const { if (embedding_host_bytes) s += fmt(" embedding %12s %12s (--embedding-placement ram, pinned, read in place)\n", "-", humanb(embedding_host_bytes).c_str()); + if (tower_host_bytes) + s += fmt(" encoder tower %12s %12s (--vision-tower-placement ram, pinned, read in place)\n", + "-", humanb(tower_host_bytes).c_str()); if (ngram_copy_bytes) s += fmt(" n-gram copy %12s %12s (--ngram-placement ram, %s, filled at load)\n", "-", humanb(ngram_copy_bytes).c_str(), diff --git a/core/place/planner.h b/core/place/planner.h index 3e21bb30..9ac243e8 100644 --- a/core/place/planner.h +++ b/core/place/planner.h @@ -95,10 +95,12 @@ 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; /* --embedding-placement ram put it in the pinned pool */ + bool host_forced = false; /* a placement flag put it in the pinned pool: the embedding's + * or the encoder tower's */ /* 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 --embedding-placement ram. */ + * it: the mapped tier (no device kernel can read it), --embedding-placement ram and + * --vision-tower-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 */ @@ -274,11 +276,13 @@ 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 */ - /* --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. */ + /* --embedding-placement ram and --vision-tower-placement ram: the pool slots each flag's + * units took before any strategy ran, like the file staging above, and reported beside it + * rather than among the pooled units. `forced_host_used` is both flags' weight bytes, the unit + * the tier totals count in, which the pooled weights' figures leave out. */ int64_t embedding_host_bytes = 0; - int64_t embedding_host_used = 0; + int64_t tower_host_bytes = 0; + int64_t forced_host_used = 0; /* --ngram-placement ram: the n-gram tables the load phase copies into host memory. They stay * on the mapped tier as far as every pool is concerned; this is what the copy costs in RAM. * `ngram_copy_card` says which copy: pinned memory a device kernel reads in place over the @@ -379,6 +383,7 @@ private: void build_units(const Program& prog, Plan* p); void pin_mapped(const Program& prog, Plan* p); int pin_embedding(const Program& prog, const Config& cfg, Plan* p) const; + int pin_towers(const Config& cfg, Plan* p) const; void build_classes(Plan* p); void rank_units(Plan* p, std::vector* order) const; int assign(Plan* p); @@ -430,11 +435,13 @@ struct WeightFootprint { bool routed = false; /* a layer has experts: the file tier's read windows */ int64_t mapped = 0; /* no device kernel can read them; they never enter a pool at all */ 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` + /* The tables the placement flags move, wherever the buckets above count them: `embedding` * is inside statics or hosted, `ngram` inside statics when a device kernel reads it and it is - * placed in VRAM, inside mapped otherwise. */ + * placed in VRAM, inside mapped otherwise. `tower` is the encoder towers' units, every weight + * of which the architecture declared read once per request, inside statics. */ int64_t embedding = 0; int64_t ngram = 0; + int64_t tower = 0; /* A device kernel reads the n-gram table, so it can be on the card or read over the link from * pinned host memory; without one only the host gather reads it, from RAM or the container. */ bool ngram_device = false; diff --git a/core/rad_core.h b/core/rad_core.h index df44afb9..8ce4da1f 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -800,6 +800,17 @@ struct Config { * a rank, ON TOP OF host_pool_mib -- so the table never takes the experts' share of the pool, * and a dense model that has no pool still has a place for it. */ int64_t embedding_host_mib = 0; + /* --vision-tower-placement: where a model's encoder towers live. A tower is every weight its + * architecture declared read once per request (RAD_ACCESS_PER_REQUEST) -- the vision tower, + * and the audio encoder where a model has one -- and Vram, the default, keeps it on the card + * with the rest. Ram pins it in host memory of its own, `tower_host_mib` a rank on top of + * host_pool_mib as the embedding's is, and the encoder's kernels read it over the link in + * place, once an image: what it held on the card goes to the KV cache. */ + TablePlacement tower_placement = TablePlacement::Vram; + TablePlacement tower_resolved = TablePlacement::Vram; + int64_t tower_host_mib = 0; + /* The pinned host pool one rank allocates: --host-pool-mib and the tables placed beside it. */ + int64_t host_pool_total_mib() const { return host_pool_mib + embedding_host_mib + tower_host_mib; } 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. @@ -822,23 +833,19 @@ struct Config { * live and the least valuable thing in it once the session stops. With a host tier, a * finished conversation is COPIED to host memory at once and its VRAM given up the moment * something wants it -- the expert slab's loan, or a request -- so no threshold decides when - * it leaves the card: the copy makes leaving free. With a disk tier every host copy is copied - * on to disk too, so a full host tier gives the oldest slots up for nothing in the same way. + * it leaves the card: the copy makes leaving free. A full host tier drops its least recently + * used entries. Nothing is written to a drive. * * Moving is worth it because the alternative is a re-prefill. Recovering a 200K-token turn * costs a copy over PCIe; recomputing it costs minutes. The two are not the same order. * * CAPACITY IS WHAT TURNS THEM ON. Nothing is copied until the host tier has a size: a tier of - * zero bytes holds nothing, so the feature is off until an operator says how much memory and - * how much disk it may have. */ - int64_t prefix_cache_host_mib = 0; /* the host tier's size. 0 is off */ - int64_t prefix_cache_disk_mib = 0; /* the disk tier's size. 0 is off */ - /* WHERE THE DISK TIER LIVES, and a flag of its own rather than a second meaning for - * --weights-disk-tier. That one is the WEIGHT planner's permission to place weights on the file - * tier -- it reads the container, needs pinned staging, and refuses startup without it. The - * two have nothing in common but the word "disk", and a shared flag would make asking for a KV - * cache also ask for weight offload, which fails for want of a host pool nobody wanted. */ - std::string prefix_cache_dir; + * zero bytes holds nothing, so the feature is off until an operator says how much memory it + * may have. */ + int64_t prefix_cache_mib = 0; /* the host tier's size. 0 is off */ + /* HOW LONG AN UNUSED CONVERSATION IS KEPT, in seconds, whichever tier holds it: VRAM, host + * memory, and its snapshots. 0 keeps everything until the memory is wanted. */ + int64_t prefix_cache_ttl = 3600; /* THE CACHE ALWAYS LENDS AND THERE IS NO FLAG FOR IT. It keeps the blocks it is using plus a * buffer it derives, and lends the rest to the expert plane at the addresses it already owns; diff --git a/core/rad_internal.h b/core/rad_internal.h index 8151ce0b..7ff54077 100644 --- a/core/rad_internal.h +++ b/core/rad_internal.h @@ -25,6 +25,9 @@ void log_set_level(Log l); Log log_level(); void log_emit(Log l, const char* file, int line, const char* fmt, ...) __attribute__((format(printf, 4, 5))); +/* When the last line was written (rad_mono_ns), whatever its level: what StallWatch reads as + * progress. 0 before the first. */ +uint64_t log_last_line_ns(); /* WHICH RANK IS SPEAKING. * diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp index 11444e8e..3c563b3f 100644 --- a/core/runtime/tierexec.cpp +++ b/core/runtime/tierexec.cpp @@ -1,6 +1,5 @@ #include "runtime/tierexec.h" -#include "mem/sstier.h" #include "rad_internal.h" #include @@ -16,19 +15,18 @@ TierExec::~TierExec() { close(); } * maintenance path -- a selector call between steps would be affordable and is still the wrong * shape: the kernel that serves a transfer must not be able to change underneath a half-finished * batch. */ -int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk, +int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, const std::vector& groups, int max_batch, int64_t max_copy, int64_t max_chain, bool leader, int device, int64_t slot_off, - const HostArena* ck_store, RadStream shared) { + RadStream shared) { close(); if (!reg || !kv || !tiers || groups.empty() || max_batch <= 0 || max_copy <= 0 || max_chain <= 0) return RAD_E_INVAL; - reg_ = reg; kv_ = kv; tiers_ = tiers; disk_ = disk; leader_ = leader; device_ = device; + reg_ = reg; kv_ = kv; tiers_ = tiers; leader_ = leader; device_ = device; max_batch_ = max_batch; max_copy_ = max_copy; max_chain_ = max_chain; slot_off_ = slot_off; slot_bytes_ = tiers->entry_bytes(); - ck_store_ = ck_store && ck_store->enabled() ? ck_store : nullptr; shared_ = shared; RAD_TRY(rad_dev_set(device_)); @@ -139,10 +137,9 @@ void TierExec::close() { order_.clear(); verify_pending_.clear(); entry_bytes_ = 0; - ck_store_ = nullptr; enabled_ = false; leader_ = false; - reg_ = nullptr; kv_ = nullptr; tiers_ = nullptr; disk_ = nullptr; + reg_ = nullptr; kv_ = nullptr; tiers_ = nullptr; report_.clear(); } @@ -155,7 +152,7 @@ void TierExec::close() { * device side built at bringup, on a two-card R9700 Flash-Next server at 200K context: * * no tiers 20.54 ms/step collect 14.66 - * tiers on, 512 MiB host arena, no disk 33.94 ms/step collect 26.78 + * tiers on, 512 MiB host arena 33.94 ms/step collect 26.78 * tiers on, idle threshold a day -- NOTHING EVER MOVED 33.88 ms/step collect 26.66 * * In the third line not one byte crosses the link, and the step is still 65% longer. The cost is @@ -536,74 +533,6 @@ int TierExec::issue_restore(std::vector& jobs, RadStream compute, return st; } -int TierExec::fence(RadEvent* out, RadStream on) { - *out = nullptr; - if (!enabled_ || (!on && !stream_)) return RAD_OK; - RAD_TRY(rad_dev_set(device_)); - RadEvent e = nullptr; - RAD_TRY(rad_event_create(&e)); - const int st = rad_event_record(e, on ? on : stream_); - if (st != RAD_OK) { rad_event_destroy(e); return st; } - *out = e; - return RAD_OK; -} - -/* ------------------------------------------------------------------ the disk store */ - -void TierExec::run_disk(std::vector& jobs, std::vector* ok) { - ok->assign(jobs.size(), 1); - for (size_t i = 0; i < jobs.size(); ++i) (*ok)[i] = run_write(jobs[i]) ? 1 : 0; -} - -bool TierExec::run_write(TierJob& j) { - if (j.kind != TierJob::Kind::ToDisk) return true; /* the drops move nothing */ - bool ok = true; - /* THE WHOLE SLOT, every rank's shard of it, because a disk entry read back must be able to - * serve all of them. A job may carry only the snapshot half, when the blocks are already on - * disk or their write went out earlier. */ - if (j.host_slot >= 0) { - const void* src = tiers_->arena().at(j.host_slot); - ok = disk_ && src && disk_->put_block(j.key, nullptr, 0, src, slot_bytes_) == RAD_OK; - } - if (j.ck_slot >= 0) { - const void* cs = ck_store_ ? ck_store_->at(j.ck_slot) : nullptr; - /* A snapshot store that was never opened -- no room for one inside the disk cap -- refuses - * this, which is the right answer and not an error: the slot stays the only copy, as it - * was. */ - j.ck_ok = disk_ && cs && - disk_->put_checkpoint(j.key, j.ck_pos, cs, ck_store_->slot_bytes()) == RAD_OK; - } - return ok; -} - -void TierExec::run_fetch(std::vector& jobs, std::vector* ok) { - ok->assign(jobs.size(), 1); - std::vector keys; - std::vector dst; - std::vector at; - for (size_t i = 0; i < jobs.size(); ++i) { - TierJob& j = jobs[i]; - j.started = true; - if (j.host_slot < 0) continue; /* only the snapshot half */ - keys.push_back(j.key); - dst.push_back(tiers_->arena().at(j.host_slot)); - at.push_back(i); - } - if (!keys.empty()) { - std::vector got(keys.size(), 0); - if (disk_) (void)disk_->get_blocks(keys.data(), (int64_t)keys.size(), dst.data(), - slot_bytes_, got.data()); - for (size_t k = 0; k < keys.size(); ++k) (*ok)[at[k]] = got[k]; - st_.bytes_in += (int64_t)keys.size() * slot_bytes_; - } - for (TierJob& j : jobs) { - if (!j.ck_want || j.ck_slot < 0) continue; - void* cs = ck_store_ ? ck_store_->at(j.ck_slot) : nullptr; - j.ck_ok = disk_ && cs && - disk_->get_checkpoint(j.key, j.ck_pos, cs, ck_store_->slot_bytes()) == RAD_OK; - } -} - /* ------------------------------------------------------------------ the report */ void TierExec::report_pass(std::vector& jobs, const std::vector& ok, @@ -624,11 +553,6 @@ void TierExec::report_pass(std::vector& jobs, const std::vector& } tiers_->report(j, good, now_ns); } - /* STORE SLOTS THE TIERS HAD BEEN KEEPING: a write that read one the cache let go of, or a - * read nothing took. The disk thread is done with them -- these come only from reports. */ - std::vector frees; - tiers_->take_checkpoint_frees(&frees); - for (int32_t s : frees) kv_->free_checkpoint(s); } bool TierExec::plan_promote(const BlockHash& key, TierJob* out) { @@ -636,135 +560,4 @@ bool TierExec::plan_promote(const BlockHash& key, TierJob* out) { return tiers_->plan_promote(key, out); } -/* ------------------------------------------------------------------ TierIO */ - -TierIO::~TierIO() { stop(); } - -void TierIO::start(TierExec* leader) { - stop(); - x_ = leader; - stop_ = false; - th_ = std::thread([this] { loop(); }); -} - -void TierIO::stop() { - { - std::lock_guard lk(mu_); - stop_ = true; - } - cv_.notify_all(); - if (th_.joinable()) th_.join(); - has_work_ = has_done_ = false; - work_.clear(); - done_.clear(); - ok_.clear(); - work_at_ = 0; - fetch_q_.clear(); - fetch_done_.clear(); -} - -bool TierIO::submit(std::vector&& jobs, std::vector&& fences) { - { - std::lock_guard lk(mu_); - if (has_work_ || has_done_ || !th_.joinable()) return false; - work_ = std::move(jobs); - work_fences_ = std::move(fences); - ok_.assign(work_.size(), 1); - work_at_ = 0; - has_work_ = true; - } - cv_.notify_all(); - return true; -} - -bool TierIO::submit_fetch(Fetch&& f) { - { - std::lock_guard lk(mu_); - if (!th_.joinable()) return false; - fetch_q_.push_back(std::move(f)); - } - cv_.notify_all(); - return true; -} - -bool TierIO::take_fetch(Fetch* out) { - std::lock_guard lk(mu_); - if (fetch_done_.empty()) return false; - *out = std::move(fetch_done_.front()); - fetch_done_.pop_front(); - return true; -} - -bool TierIO::take(std::vector* jobs, std::vector* ok, - std::vector* fences) { - std::lock_guard lk(mu_); - if (!has_done_) return false; - *jobs = std::move(done_); - *ok = std::move(ok_); - if (fences) *fences = std::move(done_fences_); - done_.clear(); - done_fences_.clear(); - ok_.clear(); - has_done_ = false; - return true; -} - -bool TierIO::busy() const { - std::lock_guard lk(mu_); - return has_work_ || has_done_; -} - -void TierIO::loop() { - for (;;) { - Fetch f; - bool read = false; - size_t i = 0; - { - std::unique_lock lk(mu_); - cv_.wait(lk, [this] { return stop_ || !fetch_q_.empty() || (has_work_ && !has_done_); }); - if (stop_) return; - if (!fetch_q_.empty()) { - f = std::move(fetch_q_.front()); - fetch_q_.pop_front(); - read = true; - } else { - i = work_at_; - } - } - if (read) { - /* NOT A BYTE UNTIL EVERY RANK'S RESTORES THAT COULD READ THESE SLOTS HAVE RUN. A fence - * that cannot be waited on leaves the read unstarted, and the records stay on disk. */ - bool fenced = true; - for (RadEvent e : f.fences) if (e && rad_event_sync(e) != RAD_OK) fenced = false; - if (fenced) x_->run_fetch(f.jobs, &f.ok); - else f.ok.assign(f.jobs.size(), 0); - std::lock_guard lk(mu_); - fetch_done_.push_back(std::move(f)); - continue; - } - /* NOT A BYTE UNTIL THE COPIES THAT FILLED THE SLOTS HAVE LANDED, once a batch. A fence - * that cannot be waited on fails the batch, and every record keeps what it had. */ - bool fenced = true; - if (i == 0) - for (RadEvent e : work_fences_) if (e && rad_event_sync(e) != RAD_OK) fenced = false; - bool ok = false; - if (fenced) ok = i < work_.size() ? x_->run_write(work_[i]) : true; - std::lock_guard lk(mu_); - if (!fenced) { - ok_.assign(work_.size(), 0); - work_at_ = work_.size(); - } else { - if (i < ok_.size()) ok_[i] = ok ? 1 : 0; - work_at_ = i + 1; - } - if (work_at_ >= work_.size()) { - done_ = std::move(work_); - done_fences_ = std::move(work_fences_); - work_.clear(); - work_fences_.clear(); - has_work_ = false; - has_done_ = true; - } - } -} } /* namespace rad */ diff --git a/core/runtime/tierexec.h b/core/runtime/tierexec.h index 68112927..c25c1712 100644 --- a/core/runtime/tierexec.h +++ b/core/runtime/tierexec.h @@ -16,9 +16,6 @@ * - a restore in makes the COMPUTE stream wait for it, so the step that reads the restored * blocks runs after they land without the host having waited for anything. * - * The disk store is the one part that is synchronous by nature, and it runs on a thread of its own - * (TierIO below), so the engine thread never waits on a file either. - * * ============================== THE TRANSFER, AND WHY IT IS SHAPED THIS WAY ==================== * * A paged pool is LAYER-MAJOR: layer l of group g owns `[base + l*layer_stride, + layer_stride)` @@ -44,20 +41,13 @@ #include "plugin/registry.h" #include "rad_core.h" -#include -#include #include -#include -#include #include -#include #include #include namespace rad { -class SSDTier; - class TierExec { public: ~TierExec(); @@ -68,10 +58,10 @@ public: * `max_batch` is the staging buffer in entries, `max_copy` the most entries one copy out may * carry, and `max_chain` the longest chain one restore brings back -- the index buffers are * sized from the last two. */ - int configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk, + int configure(Registry* reg, KVManager* kv, IdleTiers* tiers, const std::vector& groups, int max_batch, int64_t max_copy, int64_t max_chain, bool leader, int device, int64_t slot_off, - const HostArena* ck_store, RadStream shared); + RadStream shared); void close(); bool enabled() const { return enabled_; } std::string report() const { return report_; } @@ -115,34 +105,14 @@ public: /* ---------------- restore ---------------- * - * Enqueue a chain of ToDevice jobs, in chain order, and make `compute` wait for them. Every - * job's bytes are in host memory -- a disk entry was read in first (run_fetch) -- so nothing - * here waits on a file. The leader chooses every block first, recalling the loan for the + * Enqueue a chain of ToDevice jobs, in chain order, and make `compute` wait for them. The + * leader chooses every block first, recalling the loan for the * whole chain at once; a chain the pool cannot hold is cut where the reservation ran out, and * the jobs past the cut are left unstarted. `ok[i]` is whether job i was fully enqueued on * this rank. */ int issue_restore(std::vector& jobs, RadStream compute, std::vector* ok); - /* A MARK ON THIS RANK'S TRANSFER STREAM, after everything enqueued on it so far -- or on - * `on`, the rank's compute stream, when it is given. A restore reads host slots - * asynchronously, and a slot it is still reading may be given up and handed to a read off - * disk the moment the restore has reported; the IO thread waits for this mark before it - * writes into any slot it was handed. A snapshot's store slot is read and written by copies - * on the compute stream (KVManager::checkpoint_save), so a disk write or read of one waits - * for that stream's mark. Null when nothing was ever enqueued on the transfer stream. The - * caller owns the event. */ - int fence(RadEvent* out, RadStream on = nullptr); - - /* ---------------- the disk store (leader only; TierIO's thread) ---------------- */ - void run_disk(std::vector& jobs, std::vector* ok); - /* One ToDisk job; true when it was written. */ - bool run_write(TierJob& j); - /* ToHost jobs: the blocks read in parallel into the host slots they were given, then the - * snapshots into their store slots. `ok[i]` is the blocks' result, `ck_ok` the snapshot's. */ - void run_fetch(std::vector& jobs, std::vector* ok); - - /* Leader only. Gives back what a failed job held -- a restore's blocks -- reports every job to - * the policy, and frees the store slots a finished write or an unclaimed read was holding on - * the cache's behalf. `now_ns` is when the pass ran: a promotion is a use. */ + /* Leader only. Gives back what a failed job held -- a restore's blocks -- and reports every + * job to the policy. `now_ns` is when the pass ran: a promotion is a use. */ void report_pass(std::vector& jobs, const std::vector& ok, uint64_t now_ns); /* A lookup hit off-device: the job that would bring it back, or false when the entry is not @@ -209,14 +179,8 @@ private: Registry* reg_ = nullptr; KVManager* kv_ = nullptr; IdleTiers* tiers_ = nullptr; - SSDTier* disk_ = nullptr; std::vector gi_; int64_t entry_bytes_ = 0; - /* ---- the linear half ---- - * The engine's snapshot store, whose slots the disk thread writes out and reads back whole -- - * every rank's shard of a snapshot together. Null on a model with no recurrent state, which - * is the whole of the "off" path here. */ - const HostArena* ck_store_ = nullptr; int max_batch_ = 0; int64_t max_copy_ = 0; int64_t max_chain_ = 0; @@ -275,58 +239,4 @@ private: Stats st_; }; -/* ------------------------------------------------------------------ the disk thread */ -/* THE DISK STORE ON A THREAD OF ITS OWN. A host-to-disk move is a file write of the whole slot, - * and a pass that makes room for a conversation's worth of copies is hundreds of megabytes of it - * -- the engine thread would build no step for as long as the writes took. So a batch is handed - * over and collected later. The thread touches the host arena and the disk store and nothing - * else: every decision about the records is made before the hand-over and after the collection, - * on the engine thread, under the scheduler's lock. - * - * TWO KINDS OF WORK, AND THE READS GO FIRST. A write batch is the background copy to disk: one at - * a time, and the engine does not hand over the next until it has collected the last. A read - * batch is a conversation a request is waiting on (IdleTiers::plan_fetch), so reads queue in the - * order they were asked for and each one is taken ahead of whatever write is out -- between two - * of its jobs, not after the whole batch. */ -class TierIO { -public: - ~TierIO(); - void start(TierExec* leader); - void stop(); - /* False when a batch is already out. `fences` are waited on before the first job is written -- - * a snapshot's store slot is filled by a copy on the compute stream (TierExec::fence) -- and - * come back with the batch from take(), still the caller's to destroy. */ - bool submit(std::vector&& jobs, std::vector&& fences = {}); - /* The finished batch, when there is one. */ - bool take(std::vector* jobs, std::vector* ok, - std::vector* fences = nullptr); - bool busy() const; - - /* A read off disk. `tag` is the caller's (the request waiting on it); `fences` are waited on - * before the first byte is written (TierExec::fence) and stay the caller's to destroy. */ - struct Fetch { - uint64_t tag = 0; - std::vector jobs; - std::vector fences; - std::vector ok; - }; - /* False when the thread is not running. */ - bool submit_fetch(Fetch&& f); - /* A finished read, oldest first. */ - bool take_fetch(Fetch* out); - -private: - void loop(); - TierExec* x_ = nullptr; - std::thread th_; - mutable std::mutex mu_; - std::condition_variable cv_; - std::vector work_, done_; - std::vector work_fences_, done_fences_; - std::vector ok_; - size_t work_at_ = 0; /* the next write job; the thread's alone while has_work_ */ - bool has_work_ = false, has_done_ = false, stop_ = false; - std::deque fetch_q_, fetch_done_; -}; - } /* namespace rad */ diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index f6bf781b..3296f4cf 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -146,18 +146,13 @@ struct IPrefixCache { * `blocks_out` receives the block ids per cached group, in cached_groups() order, ready for * IKVManager::adopt. */ /* GIVE BACK WHATEVER THE TIERS HOLD FOR THIS PROMPT, before the lookup that would otherwise - * stop at it. `Wait` when part of it is still being read off disk: the request is not - * admitted this step -- the ones behind it may be -- and is asked again on the next. Admitting - * it anyway would stop its hit at the first entry not yet read, and the hit length is what - * its prefill is chunked against, so the same prompt would run different shapes depending on - * how far a read had got. + * stop at it. * * The scheduler calls it and must not know what a tier is: a restore allocates blocks and * runs a device scatter, so it is the engine's to perform and is installed as a callable * rather than reached through this header. A failure is not an error here -- it leaves a * shorter prefix, and a shorter prefix is always safe. */ - enum class Restore { Done, Wait }; - virtual Restore restore(const Request&) { return Restore::Done; } + virtual void restore(const Request&) {} /* A step's admissions begin: what the last step's lookups handed out has been read. */ virtual void begin_step() {} /* KEEP THIS WAITING REQUEST'S CHAIN WHERE IT IS until release(). Called when an admission is @@ -212,6 +207,9 @@ struct IPrefixCache { * that has happened; this count rises first. */ virtual int64_t evictions() const = 0; virtual int64_t ckpt_evictions() const = 0; + /* And what --prefix-cache-ttl took: not memory pressure, so not evictions. */ + virtual int64_t expired() const { return 0; } + virtual int64_t ckpt_expired() const { return 0; } /* WHAT IT IS HOLDING ON ITS OWN RIGHT NOW, in tokens of context, as against the counters * above which are cumulative. A finished turn's blocks stay held so the next turn can reuse @@ -237,9 +235,8 @@ struct IPrefixCache { /* The state that reservation named is now IN its slot. A reservation is made when the chunk is * PLANNED and the state exists only after the step that computes it, so a lookup in between * would adopt a slot holding the previous tenant's history. Until this is called, the - * reservation is a promise and lookup will not offer it. `resume`: the deepest checkpoint this - * prompt gets, the one its next turn resumes from (Scheduler::last_checkpoint). */ - virtual void commit_checkpoint(const Request& r, int64_t pos, bool resume) = 0; + * reservation is a promise and lookup will not offer it. */ + virtual void commit_checkpoint(const Request& r, int64_t pos) = 0; }; /* ------------------------------------------------------------------ block geometry */ @@ -367,9 +364,9 @@ struct PCBinding final : IPrefixCache { } /* Installed by the engine when the idle tiers are on; empty otherwise. */ - std::function restore_fn; - Restore restore(const Request& r) override { - return restore_fn ? restore_fn(r) : Restore::Done; + std::function restore_fn; + void restore(const Request& r) override { + if (restore_fn) restore_fn(r); } void begin_step() override { m->begin_step(); } void hold(const Request& r) override { @@ -400,9 +397,9 @@ struct PCBinding final : IPrefixCache { uint64_t lost_warned_ns_ = 0; /* PRESSURE TAKES WHAT CAN LEAVE VRAM AND STAY, FIRST. An entry whose host copy has landed is * dropped and kept (trim); a copy still on its way is landed and that entry dropped too; only - * what the tiers then still cannot take -- an arena with no room and a disk that has not caught - * up, or no tiers at all -- is erased, and an erase with the tiers on is said, because it is - * a conversation a later turn will prefill again. */ + * what the tiers then still cannot take -- an arena with no room, or no tiers at all -- is + * erased, and an erase with the tiers on is said, because it is a conversation a later turn + * will prefill again. */ int64_t evict(int64_t n) override { int64_t k = m->trim(n); if (k < n && flush_fn && flush_fn()) k += m->trim(n - k); @@ -415,8 +412,8 @@ struct PCBinding final : IPrefixCache { if (now - lost_warned_ns_ >= 60ull * 1000000000ull) { lost_warned_ns_ = now; RAD_WARN("prefix cache: %lld entries erased with no copy off the card -- the host " - "tier had no room for them in time (--prefix-cache-host-mib, and the disk " - "behind it); radiance:prefix_cache_evictions_total counts every one", + "tier had no room for them in time (--prefix-cache-mib); " + "radiance:prefix_cache_evictions_total counts every one", (long long)lost); } } @@ -430,6 +427,8 @@ struct PCBinding final : IPrefixCache { } int64_t evictions() const override { return m->stats().evictions; } int64_t ckpt_evictions() const override { return m->stats().ckpt_evictions; } + int64_t expired() const override { return m->stats().expired; } + int64_t ckpt_expired() const override { return m->stats().ckpt_expired; } int64_t held_tokens() const override { return m->unshared_tokens(); } int64_t next_checkpoint_after(int64_t p) const override { return m->next_checkpoint_after(p); } @@ -448,8 +447,8 @@ struct PCBinding final : IPrefixCache { return m->reserve_checkpoint(r.id, pos, prefix_hash(r, pos), slot_out); } - void commit_checkpoint(const Request& r, int64_t pos, bool resume) override { - m->commit_checkpoint(prefix_hash(r, pos), resume); + void commit_checkpoint(const Request& r, int64_t pos) override { + m->commit_checkpoint(prefix_hash(r, pos)); } private: diff --git a/core/sched/metrics.h b/core/sched/metrics.h index 4e1de4f8..9bb78ba8 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -107,6 +107,7 @@ struct SchedMetrics { * mean the pool cannot hold the working set and turn-2 latency is about to collapse. */ int64_t prefix_evictions = 0; int64_t prefix_ckpt_evictions = 0; + int64_t prefix_expired = 0, prefix_ckpt_expired = 0; /* --prefix-cache-ttl */ /* WHAT THE CACHE IS HOLDING ON ITS OWN NOW, in tokens of context: the part of the pool that * an eviction would actually free, because no live sequence is reading it. The pool figure * above counts a held block whoever holds it, and on a server serving conversations most of diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index baa4fafb..9bca6b15 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -120,25 +120,34 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac DraftController::Params dp; dp.max_depth = cfg.n_spec; - /* THE ADAPTIVE WINDOW IS THE SERIAL DRAFTER'S POLICY (draft.h): it prices a draft as one more - * round of the head. A block drafter proposes its block in one pass and prompt lookup runs no - * pass at all, so for either the window stays fixed -- decided here, once, before any step - * has counted an acceptance, and said, because a flag that changes nothing reads exactly - * like a flag that made no difference. */ + /* THE ADAPTIVE WINDOW (draft.h) prices a draft by what the step it adds to costs, measured. + * For a serial head that is a round of the head and a verify row. For a BLOCK drafter the + * block is proposed in one pass whatever is verified, but each verified draft is still a + * verify row -- and on a model whose verify streams weights per row, a MoE that reads the + * experts every row routes to, a row is not free: sixteen rows read ten times the experts one + * does. So a block drafter takes the same policy with its rounds fixed: each sequence verifies + * the first min(D, its stop) of the block, its stop from its own measured acceptance, and D + * from the measured step times. Deep where the text is predictable (code, JSON, greedy), a few + * drafts where it is not (prose at temperature 1, where a point-mass draft survives a position + * with probability p(x) and a fifteen-token chain dies after one or two). Prompt lookup runs + * no pass and keeps the fixed window, decided here, once, and said, because a flag that + * changes nothing reads exactly like a flag that made no difference. */ if (cfg.draft_window == DraftWindow::Adaptive) { const RadDrafterDecl& dd = prog.drafter; if (cfg.n_spec <= 0) RAD_WARN("--draft-window adaptive: this deployment does not speculate " "(--num-speculative-tokens %d), so there is no window to adapt", cfg.n_spec); - else if (dd.kind != RAD_DRAFT_SERIAL || dd.depth <= 0) - RAD_WARN("--draft-window adaptive: the window is fixed at %d with %s -- the adaptive " - "window prices the rounds of a serial draft head, which this deployment does " - "not run", cfg.n_spec, - dd.kind == RAD_DRAFT_BLOCK ? "a block drafter, which proposes its block in one " - "pass" - : "prompt lookup only"); - else + else if ((dd.kind != RAD_DRAFT_SERIAL && dd.kind != RAD_DRAFT_BLOCK) || dd.depth <= 0) + RAD_WARN("--draft-window adaptive: the window is fixed at %d with prompt lookup only " + "-- the adaptive window prices draft passes and verify rows, and prompt " + "lookup runs no pass", cfg.n_spec); + else { dp.adapt = true; + if (dd.kind == RAD_DRAFT_BLOCK) + RAD_INFO("--draft-window adaptive with a block drafter: the block of %d is " + "proposed whole, and each sequence verifies the first min(D, its stop) " + "of it", dd.depth); + } } RAD_TRY(draft_.configure(dp)); draft_est_.clear(); @@ -796,17 +805,6 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg return want; } -/* THE DEEPEST CHECKPOINT A PROMPT OF `target` TOKENS GETS, asked of one at `pos`: no interval - * boundary is left before the target and no tail checkpoint will follow (plan_chunk's rules). It - * is the state the prompt's next turn resumes from. */ -bool Scheduler::last_checkpoint(int64_t pos, int64_t target) const { - if (!geo_.checkpoints()) return false; - const int64_t I = geo_.checkpoint_interval; - if (geo_.window_ckpt) { const int64_t t = tail_checkpoint(target); return t > 0 && t <= pos; } - if ((pos / I + 1) * I <= target) return false; - return tail_checkpoint(target) <= pos; -} - /* THE TAIL CHECKPOINT OF A PROMPT OF `target` TOKENS, or -1: its last quantum boundary, past the * first interval -- a shorter prompt is cheap to prefill again -- and only where it buys a quarter * of an interval or more over the interval checkpoint below it, which is worth the extra step. */ @@ -975,7 +973,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { * honest shorter hit, but a shorter one. This is where a cold session gets its * context back instead of re-prefilling it: it costs a copy, and the alternative * costs a prefill. */ - if (pc_->restore(r) == IPrefixCache::Restore::Wait) return kAdmitWait; + pc_->restore(r); HitCap cap; if (draft_refill_ > 0) { cap.tokens = std::max(0, (int64_t)r.prompt.size() - draft_refill_); @@ -1384,9 +1382,9 @@ const RadBatch* Scheduler::step() { * blocks, so it will refuse a new one, and the front of the queue is now the request we just * took them from. Probing would cost a lookup per step and admit nothing. */ if (!preempted_here) { - /* `at` walks the queue and `took_` is what it admitted: a request waiting on a read off - * disk stays where it is and the one behind it is asked, so the queue is compacted after - * the walk rather than cut at its front. */ + /* `at` walks the queue and `took_` is what it admitted: a request whose media is not + * encoded yet stays where it is and the one behind it is asked, so the queue is compacted + * after the walk rather than cut at its front. */ took_.clear(); size_t at = 0; while (at < waiting_.size() && @@ -1410,8 +1408,8 @@ const RadBatch* Scheduler::step() { continue; } /* ITS MEDIA FIRST. A request whose items are not encoded keeps its place and the one - * behind it is asked, exactly as for a context still being read off disk; the engine - * runs the encoder before the next step (encodes_pending). */ + * behind it is asked; the engine runs the encoder before the next step + * (encodes_pending). */ if (s.req->media && !media_ready(s)) { ++at; continue; } /* One share left for the next request in the queue, when there is one and a slot * for it (busy_cap). The embed path takes a whole input or nothing, so it is not @@ -1422,7 +1420,6 @@ const RadBatch* Scheduler::step() { ? share_tok : 0; admit_full_ = 0; const int as = admit_one(s, budget, areserve); - if (as == kAdmitWait) { ++at; continue; } if (as < 0) break; /* head of line: do not admit behind it */ if (admit_full_ > s.sched_tokens && capped_at < 0) { capped_at = (int32_t)plan_.e.size(); @@ -1886,10 +1883,8 @@ int Scheduler::commit(const StepResult& res) { * still holding the previous tenant's state. Stream ordering does the rest -- a later * restore is enqueued on the same stream behind this save, so validity does not have to * wait on the copy landing, only on it being issued. */ - if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && pc_) { - const int64_t pos = (int64_t)e.ctx_len + e.ckpt_tok + 1; - pc_->commit_checkpoint(r, pos, last_checkpoint(pos, s.seq_len())); - } + if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && pc_) + pc_->commit_checkpoint(r, (int64_t)e.ctx_len + e.ckpt_tok + 1); if (e.is_prefill) { r.n_computed += e.n_tokens; @@ -2749,6 +2744,8 @@ SchedMetrics Scheduler::metrics_locked() const { if (pc_) { m.prefix_evictions = pc_->evictions(); m.prefix_ckpt_evictions = pc_->ckpt_evictions(); + m.prefix_expired = pc_->expired(); + m.prefix_ckpt_expired = pc_->ckpt_expired(); m.prefix_held_tokens = pc_->held_tokens(); } m.attn_hit_rate = m.prompt_tokens ? (float)((double)m.attn_cached_tokens / (double)m.prompt_tokens) : 0.0f; diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 000cb4c6..733064f1 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -463,8 +463,7 @@ public: SchedMetrics observed_metrics() const; int observed_requests(ReqStat* out, int max) const; - /* plan_chunk's checkpoint rules, asked after the fact (see the definitions). */ - bool last_checkpoint(int64_t pos, int64_t target) const; + /* plan_chunk's tail-checkpoint rule (see the definition). */ int64_t tail_checkpoint(int64_t target) const; /* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a * token budget, and the checkpoint position it will land on (-1 for none). `keep_at` is the @@ -759,13 +758,11 @@ private: void preempt_back(); /* Give blocks back from the prefix cache until the pool has headroom again. */ void trim_prefix_cache(); - /* RAD_OK, a negative status when the request cannot be admitted now -- nothing behind it is - * either -- or kAdmitWait when its context is still being read off disk and the next request - * may go ahead of it. */ + /* RAD_OK, or a negative status when the request cannot be admitted now -- nothing behind it is + * either. */ /* `reserve`: tokens of the step to leave for the requests queued behind this one * (--busy-prefill-chunk; busy_cap). 0 plans the chunk on the whole budget, as before. */ int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0); - static constexpr int kAdmitWait = 1; /* The queue positions one step's admission took, kept to reuse the allocation. */ std::vector took_; diff --git a/core/server/adapters.h b/core/server/adapters.h index a84a4d07..f882f934 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -50,7 +50,7 @@ public: * behind it still compiles. Every rank declares the same chain against the same hierarchy, so * whether a stage resolved is not a per-rank fact and asking one of them is asking all. */ /* `tiers` is rank 0's IdleTiers, and it is given whether or not a tier can move anything: - * the object holds the session table either way, and a server with no --prefix-cache-host-mib is + * the object holds the session table either way, and a server with no --prefix-cache-mib is * one whose every stored session is in VRAM rather than one with no sessions. Null only when * there is no engine behind this at all. */ explicit SchedulerBridge(Scheduler* s, const Sampler* sampler = nullptr, @@ -111,19 +111,14 @@ public: TierCounters c; if (!tiers_) return c; const IdleTiers::Stats& s = tiers_->stats(); - c.to_host = s.to_host; c.dropped = s.dropped; c.to_disk = s.to_disk; - c.promoted = s.promoted; - c.host_freed = s.host_freed; c.host_drops = s.host_drops; c.failures = s.failures; - c.fetched = s.fetched; c.ck_fetched = s.ck_fetched; - c.host_bytes = s.host_bytes; c.disk_bytes = s.disk_bytes; - c.ck_to_disk = s.ck_to_disk; c.ck_drops = s.ck_drops; + c.to_host = s.to_host; c.dropped = s.dropped; c.promoted = s.promoted; + c.host_drops = s.host_drops; c.failures = s.failures; + c.host_bytes = s.host_bytes; c.restores = s.restores; c.restore_ns = s.restore_ns; c.flushes = s.flushes; c.flush_ns = s.flush_ns; c.ck_bytes = tiers_->ckpt_bytes(); - c.ck_host_slots = tiers_->ckpt_slots(); - c.ck_disk_slots = tiers_->ckpt_disk_slots(); + c.ck_slots = tiers_->ckpt_slots(); c.host_on = tiers_->host_on(); - c.disk_on = tiers_->disk_on(); return c; } @@ -133,8 +128,8 @@ public: IdleTiers::Occupancy held; const std::vector v = tiers_->sessions(occ ? &held : nullptr); if (occ) { - occ->host_bytes = held.host_bytes; occ->disk_bytes = held.disk_bytes; - occ->host_cap_bytes = held.host_cap_bytes; occ->disk_cap_bytes = held.disk_cap_bytes; + occ->host_bytes = held.host_bytes; + occ->host_cap_bytes = held.host_cap_bytes; } const uint64_t now = rad_mono_ns(); out->reserve(v.size()); @@ -149,11 +144,8 @@ public: o.age_s = now > s.first_seen_ns ? (double)(now - s.first_seen_ns) / 1e9 : 0.0; o.on_device = s.on_device; o.on_host = s.on_host; - o.on_disk = s.on_disk; o.moving = s.moving; o.snapshots = s.snapshots; - o.snap_host = s.snap_host; - o.snap_disk = s.snap_disk; o.snap_bytes = s.snap_bytes; o.resume_tokens = s.resume_tokens; out->push_back(std::move(o)); @@ -263,6 +255,8 @@ public: * figure above the used one would draw a negative live share. */ o.kv_tokens_cached = std::min(m.prefix_held_tokens, o.kv_tokens_used); o.prefix_ckpt_evictions = m.prefix_ckpt_evictions; + o.prefix_expired = m.prefix_expired; + o.prefix_ckpt_expired = m.prefix_ckpt_expired; o.prefill_tps = m.prefill_tps; o.decode_tps = m.decode_tps; diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 1e6fa8c7..3c7ab84b 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -52,8 +52,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { SessionOccupancy occ; if (deps_.sched) deps_.sched->sessions(&v, &occ); - int64_t dev = 0, host = 0, disk = 0, bytes = 0; - int64_t shost = 0, sdisk = 0; + int64_t dev = 0, host = 0, bytes = 0; + int64_t snaps = 0; json a = json::array(); for (const SessionStat& s : v) { json e; @@ -66,20 +66,16 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { e["age_s"] = s.age_s; e["on_device"] = s.on_device; e["on_host"] = s.on_host; - e["on_disk"] = s.on_disk; e["moving"] = s.moving; /* THE RECURRENT HALF. On a hybrid model a session's attention blocks are only part of * what it needs back; the rest is its linear-state snapshots, which are a different size - * of object in a different store. Counted where the BYTES are: in the store in host - * memory, or on disk alone. */ + * of object in a different store, in host memory. */ e["snapshots"] = s.snapshots; - e["snap_host"] = s.snap_host; - e["snap_disk"] = s.snap_disk; e["snap_bytes"] = s.snap_bytes; e["resume_tokens"] = s.resume_tokens; a.push_back(std::move(e)); - dev += s.on_device; host += s.on_host; disk += s.on_disk; - shost += s.snap_host; sdisk += s.snap_disk; + dev += s.on_device; host += s.on_host; + snaps += s.snapshots; bytes += s.bytes; } o["sessions"] = std::move(a); @@ -87,8 +83,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { * the blocks for it, so these per-session sizes overlap and adding them up over-counts -- on * a server carrying long agent transcripts by more than an order of magnitude. The field * names say so rather than pretending the sums are totals. */ - o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host }, { "disk", disk } }; - o["snapshots"] = { { "host", shost }, { "disk", sdisk } }; + o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host } }; + o["snapshots_sum_overlapping"] = snaps; o["bytes_sum_overlapping"] = bytes; const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{}; /* AND THE ONE FIGURE THAT IS NOT A SUM, because a view about what the conversations cost has @@ -103,17 +99,14 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { { "bytes_total", sm.kv_bytes_total } }; const IScheduler::TierCounters c = deps_.sched ? deps_.sched->tier_counters() : IScheduler::TierCounters{}; - o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped }, { "to_disk", c.to_disk }, - { "promoted", c.promoted }, { "host_freed", c.host_freed }, - { "host_drops", c.host_drops }, { "failures", c.failures }, - { "fetched", c.fetched } }; - /* THE SNAPSHOT COUNTERS ARE NOT OPTIONAL ON A HYBRID MODEL, because a server that moves every - * block it has and no snapshots at all looks identical in the block counters to one where - * tiering works -- and the difference is a full linear replay on every restored session. */ - o["snapshots_moved"] = { { "to_disk", c.ck_to_disk }, { "fetched", c.ck_fetched }, - { "drops", c.ck_drops }, { "bytes_each", c.ck_bytes }, - { "host_slots", c.ck_host_slots }, - { "disk_slots", c.ck_disk_slots } }; + o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped }, + { "promoted", c.promoted }, { "host_drops", c.host_drops }, + { "failures", c.failures } }; + /* THE SNAPSHOT STORE, on a hybrid model: what one snapshot costs and how many the store + * holds. `bytes_each` is 0 on a model with no recurrent state. */ + o["snapshot_store"] = { { "bytes_each", c.ck_bytes }, { "slots", c.ck_slots } }; + /* WHAT --prefix-cache-ttl TOOK, entries and snapshots, from whichever tier held them. */ + o["expired"] = { { "entries", sm.prefix_expired }, { "snapshots", sm.prefix_ckpt_expired } }; /* THE STEP THREAD'S TIME ON THE TIERS: every request waits through it. */ o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 }, { "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } }; @@ -127,15 +120,14 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { /* WHETHER ANYTHING MOVES, which is not whether anything is STORED. A session is recorded * whether or not it can be demoted, so a non-empty table says only that something is held; * these say whether a tier exists that can move it. */ - o["tiers"] = { { "host", c.host_on }, { "disk", c.disk_on } }; + o["tiers"] = { { "host", c.host_on } }; /* WHAT IS OFF THE CARD, counted once -- see SessionOccupancy. */ - o["occupancy"] = { { "host_bytes", occ.host_bytes }, { "disk_bytes", occ.disk_bytes }, - { "host_cap_bytes", occ.host_cap_bytes }, - { "disk_cap_bytes", occ.disk_cap_bytes } }; + o["occupancy"] = { { "host_bytes", occ.host_bytes }, + { "host_cap_bytes", occ.host_cap_bytes } }; /* THE ATTENTION HIT RATE, for a model with no recurrent state, where it is the whole answer * to how much of the prompt the cache served. On a hybrid model `linear.hit_rate` is. */ o["prefix_hit_rate"] = sm.prefix_hit_rate; - o["enabled"] = c.host_on || c.disk_on; + o["enabled"] = c.host_on; return HttpResponse::json_body(200, json_dump(o)); } @@ -695,7 +687,6 @@ th + th, td + td { padding-left:14px; } .tbar > i { display:block; height:100%; } .t-dev { background:#4ade80; } .tn-dev { color:#7fe0a3; } .t-host { background:#60a5fa; } .tn-host { color:#8dbcfb; } -.t-disk { background:#a78bfa; } .tn-disk { color:#c4b5fd; } /* The group that starts over is folded by default: it is a count first and rows second. */ details.sgrp > summary { list-style:none; cursor:pointer; } details.sgrp > summary::-webkit-details-marker { display:none; } @@ -1185,9 +1176,6 @@ nav button.on { color:var(--fg); background:var(--track); }
–
moved to host ram
-
–
- moved to disk -
@@ -2838,7 +2826,7 @@ $("tab-model").addEventListener("click", () => show("model")); * snapshot reuses nothing however many of its blocks are kept. On a model with no recurrent state * the blocks are the whole answer and every stored token is reused. */ const reuseOf = (r, hybrid) => hybrid ? Math.min(r.resume_tokens || 0, r.tokens) : r.tokens; -const TIERS = [["dev", "on_device", "vram"], ["host", "on_host", "host"], ["disk", "on_disk", "disk"]]; +const TIERS = [["dev", "on_device", "vram"], ["host", "on_host", "host"]]; function sessCols(tr, manyModels) { tr.textContent = ""; @@ -2874,7 +2862,7 @@ function sessRow(r, hybrid, manyModels) { read as three equal parts. The per-tier counts are blocks, and a block is the same number of tokens in every tier, so the proportion is the proportion of its tokens. */ const wh = tr.appendChild(el("td", "l")), bar = wh.appendChild(el("span", "tbar")); - const held = r.on_device + r.on_host + r.on_disk, parts = []; + const held = r.on_device + r.on_host, parts = []; for (const [k, f, name] of TIERS) { if (!(r[f] > 0)) continue; bar.appendChild(el("i", "t-" + k)).style.width = (100 * r[f] / held).toFixed(1) + "%"; @@ -2897,7 +2885,7 @@ async function loadSessions() { return; } const rows = (s.sessions || []).slice().sort((x, y) => x.idle_s - y.idle_s); - const mv = s.snapshots_moved || {}, ln = s.linear || {}; + const mv = s.snapshot_store || {}, ln = s.linear || {}; const pool = s.pool || {}, occ = s.occupancy || {}; /* The model has recurrent state if its snapshots have a size. */ const hybrid = mv.bytes_each > 0; @@ -2913,13 +2901,12 @@ async function loadSessions() { $("s-live").firstChild.nodeValue = cnt(live.length); $("s-liveof").textContent = "of " + cnt(rows.length); $("s-livedet").textContent = cold.length ? cnt(cold.length) + " start over" : ""; - /* VRAM IN TOKENS, THE OTHER TIERS IN BYTES. The pool's token count is the context the card can - serve without a copy; the tiers off the card are sized by --prefix-cache-host-mib and - --prefix-cache-disk-mib and are read against them. A tier that is off has no cell. */ + /* VRAM IN TOKENS, HOST MEMORY IN BYTES. The pool's token count is the context the card can + serve without a copy; the host tier is sized by --prefix-cache-mib and read against it. A + tier that is off has no cell. */ $("s-vram").firstChild.nodeValue = cnt3(pool.tokens_used || 0); $("s-vramdet").textContent = pool.tokens_total ? "of " + cnt3(pool.tokens_total) + " tok" : ""; - for (const [id, used, cap] of [["s-host", occ.host_bytes, occ.host_cap_bytes], - ["s-disk", occ.disk_bytes, occ.disk_cap_bytes]]) { + for (const [id, used, cap] of [["s-host", occ.host_bytes, occ.host_cap_bytes]]) { $(id + "cell").hidden = !(cap > 0); const x = hbs(used || 0); $(id).firstChild.nodeValue = x.n; diff --git a/core/server/http.cpp b/core/server/http.cpp index e1d739a1..164ab3a5 100644 --- a/core/server/http.cpp +++ b/core/server/http.cpp @@ -412,6 +412,8 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) { req.path = hreq.path; req.body = std::move(body); req.peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port); + req.t_received_ns = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); for (auto& h : hreq.headers) req.headers[h.first] = h.second; for (auto& p : hreq.params) req.query[p.first] = p.second; req.closed = [&hreq] { return hreq.is_connection_closed(); }; diff --git a/core/server/http.h b/core/server/http.h index f1992a41..cc694f72 100644 --- a/core/server/http.h +++ b/core/server/http.h @@ -32,6 +32,10 @@ struct HttpRequest { std::map query; std::map params; /* from a ":name" route segment */ std::string peer; /* "addr:port"; empty in-process */ + /* WHEN THE WHOLE BODY HAD ARRIVED, in steady-clock nanoseconds: where the server's own time + * for the request starts, before it is parsed, rendered or tokenised, so the time the body + * spent on the network is not in it. -1 for a request made in-process. */ + int64_t t_received_ns = -1; /* True once the peer is gone. The transport supplies it; in-process it is absent and the * waiting paths simply never see a drop. A dropped connection is a cancellation (spec §14), diff --git a/core/server/iface.h b/core/server/iface.h index 6e28fa2d..e1bba8ac 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -79,6 +79,8 @@ struct SchedMetrics { * between an alert and a post-mortem. */ int64_t prefix_evictions = 0; int64_t prefix_ckpt_evictions = 0; + /* What --prefix-cache-ttl took, cumulative. Not evictions: nothing wanted the memory. */ + int64_t prefix_expired = 0, prefix_ckpt_expired = 0; /* PREFIX CACHING, DECOUPLED (spec §7.3). `prefix_hit_rate` above is the ATTENTION one, because * that is what vLLM's single number has always meant. The linear side hits at a different * granularity -- whole checkpoints, not blocks -- and averaging the two would hide exactly the @@ -166,13 +168,12 @@ struct SessionStat { int64_t bytes = 0; double idle_s = 0; /* since its last turn */ double age_s = 0; /* since it was first seen */ - int64_t on_device = 0, on_host = 0, on_disk = 0; /* blocks */ + int64_t on_device = 0, on_host = 0; /* blocks */ /* LINEAR STATE, on a hybrid model, and counted apart from blocks because the two are not - * interchangeable. A session showing every block on disk and no snapshot anywhere will come + * interchangeable. A session showing every block in host memory and no snapshot will come * back and re-run every recurrent layer over its whole transcript -- which the hit rate will * report as a hit. Zero everywhere on a model that has no recurrent state. */ int64_t snapshots = 0; - int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */ int64_t snap_bytes = 0; /* The prefix a return skips: the deepest snapshot's position (IdleTiers::SessionInfo). */ int64_t resume_tokens = 0; @@ -182,8 +183,8 @@ struct SessionStat { /* WHAT THE STORED CONVERSATIONS OCCUPY OFF THE CARD, blocks and snapshots each counted once -- * the one total the per-session rows cannot be summed into. Caps are 0 for a tier that is off. */ struct SessionOccupancy { - int64_t host_bytes = 0, disk_bytes = 0; - int64_t host_cap_bytes = 0, disk_cap_bytes = 0; + int64_t host_bytes = 0; + int64_t host_cap_bytes = 0; }; struct RequestStat { @@ -268,27 +269,20 @@ public: * tiers are working, switched off, or trying and failing every pass -- three very different * situations that all render as "everything is in VRAM". */ struct TierCounters { - /* `to_host` and `to_disk` count COPIES; `dropped` is VRAM given up after one and - * `host_freed` host slots given up after the disk copy. A conversation that returns before - * anything wants its VRAM is copied and never dropped. `host_drops` is entries lost with - * no disk tier to hold them. */ - int64_t to_host = 0, dropped = 0, to_disk = 0, promoted = 0; - int64_t host_freed = 0, host_drops = 0, failures = 0; - /* Entries and snapshots read off disk into host memory ahead of the restore that wanted - * them; `promoted` counts the restore itself. */ - int64_t fetched = 0, ck_fetched = 0; - int64_t host_bytes = 0, disk_bytes = 0; - /* THE LINEAR HALF, MOVED. Separate counters because a hybrid server can move every block - * it has and no snapshots at all, and no block counter can tell that apart from tiering - * working. `ck_drops` is snapshots whose only copy was lost. */ - int64_t ck_to_disk = 0, ck_drops = 0; + /* `to_host` counts COPIES; `dropped` is VRAM given up after one. A conversation that + * returns before anything wants its VRAM is copied and never dropped. `host_drops` is + * entries a full host tier gave up; `promoted` counts restores. */ + int64_t to_host = 0, dropped = 0, promoted = 0; + int64_t host_drops = 0, failures = 0; + int64_t host_bytes = 0; + /* THE SNAPSHOT STORE, which lives in host memory and moves nothing. */ int64_t ck_bytes = 0; /* one snapshot; 0 on a model with no recurrent state */ - int64_t ck_host_slots = 0, ck_disk_slots = 0; /* the store's; the disk store's */ + int64_t ck_slots = 0; int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0; /* IdleTiers::Stats */ /* WHETHER ANYTHING CAN MOVE AT ALL, which no counter above can answer: a tier that is on * and has had nothing to do reads the same as one that was never given a size, and the * two call for opposite responses from whoever is looking. */ - bool host_on = false, disk_on = false; + bool host_on = false; }; virtual TierCounters tier_counters() const { return TierCounters{}; } }; diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp index 51b05de5..98408ff0 100644 --- a/core/server/metrics.cpp +++ b/core/server/metrics.cpp @@ -185,6 +185,9 @@ void Metrics::sample(const SchedMetrics& m) { c_prefix_evict_.inc(std::max(0.0, (double)m.prefix_evictions - c_prefix_evict_.get())); c_prefix_ckpt_evict_.inc(std::max(0.0, (double)m.prefix_ckpt_evictions - c_prefix_ckpt_evict_.get())); + c_prefix_expired_.inc(std::max(0.0, (double)m.prefix_expired - c_prefix_expired_.get())); + c_prefix_ckpt_expired_.inc(std::max(0.0, + (double)m.prefix_ckpt_expired - c_prefix_ckpt_expired_.get())); g_linear_hit_.set(m.linear_hit_rate); } @@ -394,6 +397,12 @@ std::string Metrics::render() const { "Prefix-cache entries evicted (attention blocks).", L, c_prefix_evict_.get()); w.counter("radiance:prefix_cache_ckpt_evictions_total", "Prefix-cache linear-state checkpoints evicted.", L, c_prefix_ckpt_evict_.get()); + w.counter("radiance:prefix_cache_expired_total", + "Prefix-cache entries no request used for --prefix-cache-ttl, taken out.", L, + c_prefix_expired_.get()); + w.counter("radiance:prefix_cache_ckpt_expired_total", + "Prefix-cache linear-state checkpoints taken out by --prefix-cache-ttl.", L, + c_prefix_ckpt_expired_.get()); w.gauge("radiance:draft_acceptance_ratio", "Fraction of speculative draft tokens accepted (spec 10).", L, g_draft_accept_.get()); /* CONDITIONAL, per draft position: of the verifies that reached position j -- every earlier diff --git a/core/server/metrics.h b/core/server/metrics.h index 832f6fce..5d276bbc 100644 --- a/core/server/metrics.h +++ b/core/server/metrics.h @@ -156,6 +156,7 @@ private: Counter c_draft_refills_, c_draft_refill_tokens_; Counter c_attn_cached_, c_linear_cached_, c_checkpoints_; Counter c_prefix_evict_, c_prefix_ckpt_evict_; + Counter c_prefix_expired_, c_prefix_ckpt_expired_; Gauge g_linear_hit_; Counter c_success_[(size_t)SuccessReason::N_]; Counter c_rejected_, c_disconnect_, c_overflow_; diff --git a/core/server/oai.cpp b/core/server/oai.cpp index d5a8f022..b71d3a26 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -245,7 +245,11 @@ const char* kAcceptedChat[] = { "functions", "function_call", }; -const char* kAcceptedCompletion[] = { "prompt", "echo" }; +/* `preserved_tokens` is llama-server's: control tokens a raw completion's text keeps. On chat the + * reply format decides them (the guarded entry below); a raw completion has no format, and a + * client that renders its own template and parses its own reply -- a tool-call sidecar -- has no + * other way to see a format built of control tokens. */ +const char* kAcceptedCompletion[] = { "prompt", "echo", "preserved_tokens" }; const char* kAcceptedEmbedding[] = { "model", "input", "messages", "encoding_format", "dimensions", "image_tokens", "prompt_name" }; @@ -1233,6 +1237,15 @@ static int json_text_depth(const std::string& s) { return most; } +/* A STRING THAT PARSES INTO A TREE DEEPER THAN THE BOUND. Only valid JSON becomes a tree: text + * that is not JSON never becomes one (a tool result that does not parse is rendered as the + * string it is), so its brackets are not nesting, however they count. The count + * runs first and the validation (json::accept, which builds nothing and does not recurse) only + * when it is over. */ +static bool json_text_too_deep(const std::string& s) { + return json_text_depth(s) > kJsonMaxDepth && json::accept(s); +} + /* STRINGS THE CHAT TEMPLATE PARSES AS JSON are bounded like the body is (parse_json_bounded). An * assistant message's tool-call arguments and a tool message's content arrive as strings, one * level deep in the request, and the template layer parses them into trees and serialises those @@ -1248,7 +1261,7 @@ static int check_template_json(const json& msg, const std::string& role, ApiErro if (fn == tc.end() || !fn->is_object()) continue; auto args = fn->find("arguments"); if (args != fn->end() && args->is_string() && - json_text_depth(args->get_ref()) > kJsonMaxDepth) { + json_text_too_deep(args->get_ref())) { *err = err_bad("messages[].tool_calls[].function.arguments", "nests more than " + std::to_string(kJsonMaxDepth) + " levels deep"); @@ -1260,7 +1273,7 @@ static int check_template_json(const json& msg, const std::string& role, ApiErro if (role == "tool") { auto c = msg.find("content"); if (c != msg.end() && c->is_string() && - json_text_depth(c->get_ref()) > kJsonMaxDepth) { + json_text_too_deep(c->get_ref())) { *err = err_bad("messages[].content", "a tool result nests more than " + std::to_string(kJsonMaxDepth) + " levels deep"); @@ -1613,9 +1626,18 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit if (!render.think_open.empty()) o = d.tok->encode(render.think_open, false, true); n_close = c.size(); n_open = o.size(); - if (c.size() == 1 && (render.think_starts_open || o.size() == 1)) { + /* AN OPENER THAT IS ONE CONTROL TOKEN AND THEN TEXT -- Gemma 4's `<|channel>thought` -- + * is found by that first token: it is what a reply opening its own block writes first, + * and no text can be. The text after it counts as reasoning, as the markers do. An opener + * with a second control token in it (a channel and a message marker) is not read this + * way, since its first token may open something other than the reasoning. */ + bool open_first = o.size() > 1 && d.tok->reply_bytes(o[0]).empty() && + !d.tok->token_bytes(o[0]).empty(); + for (size_t i = 1; open_first && i < o.size(); ++i) + if (d.tok->reply_bytes(o[i]).empty()) open_first = false; + if (c.size() == 1 && (render.think_starts_open || o.size() == 1 || open_first)) { span.close = c[0]; - span.open = o.size() == 1 ? o[0] : -1; + span.open = (o.size() == 1 || open_first) ? o[0] : -1; span.starts_open = render.think_starts_open; } } @@ -1654,8 +1676,8 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit "as one token"; else why = "this reply has to open its own reasoning block, and the opener `" + - render.think_open + "` is " + std::to_string(n_open) + " tokens, so the block " - "cannot be found by token"; + render.think_open + "` is " + std::to_string(n_open) + " tokens and does not " + "start with a lone control token, so the block cannot be found by token"; *err = err_unsupported(named, why); return RAD_E_UNSUPPORTED; } @@ -2135,6 +2157,29 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa if (!get_bool(b, "echo", &out->echo, err)) return RAD_E_INVAL; + /* The control tokens this completion's text keeps (llama-server's field): each string is + * tokenised by the decoder and every control token in it is rendered rather than dropped. + * Bounded as the stop strings are, since the decoder looks each one up per token. */ + { + auto pt = b.find("preserved_tokens"); + if (pt != b.end() && !pt->is_null()) { + if (!pt->is_array() || pt->size() > (size_t)lim.max_stops) { + *err = err_bad("preserved_tokens", "expected an array of at most " + + std::to_string(lim.max_stops) + " strings"); + return RAD_E_INVAL; + } + for (const auto& s : *pt) { + if (!s.is_string() || s.get().size() > (size_t)lim.max_stop_bytes) { + *err = err_bad("preserved_tokens", "expected strings of at most " + + std::to_string(lim.max_stop_bytes) + + " bytes"); + return RAD_E_INVAL; + } + out->preserved_tokens.push_back(s.get()); + } + } + } + RAD_TRY(parse_logprobs(b, lim, Endpoint::Completion, out, err)); /* `echo` with logprobs asks for the PROMPT's logprobs too, which are not computed: a prompt * position's distribution never leaves the card. */ @@ -2569,6 +2614,8 @@ json timings_json(const TimingsOut& t) { o["predicted_ms"] = t.predicted_ms; o["predicted_per_token_ms"] = per(t.decode_n, t.predicted_ms); o["predicted_per_second"] = rate(t.decode_n, t.predicted_ms); + o["ttft_ms"] = t.ttft_ms >= 0.0 ? json(t.ttft_ms) : json(nullptr); + o["total_ms"] = t.total_ms >= 0.0 ? json(t.total_ms) : json(nullptr); if (t.draft_n > 0) { o["draft_n"] = t.draft_n; o["draft_n_accepted"] = t.draft_n_accepted; diff --git a/core/server/oai.h b/core/server/oai.h index 87a77a22..b92be847 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -138,6 +138,7 @@ struct OaiRequest { int n_tools = 0; std::string last_user; std::string peer; /* the handler sets it from the transport; "" in-process */ + int64_t t_received_ns = -1; /* HttpRequest::t_received_ns, for timings' ttft and total */ bool parse_tools = false; /* The reply parser this request's render produced. Per request and not per server: it is the * model's format bound to the tools THIS call sent, so two concurrent requests against the @@ -362,6 +363,11 @@ struct UsageOut { * draft_n, draft_n_accepted * speculative tokens proposed for this request and accepted; present when any * were proposed, as llama.cpp does + * ttft_ms from the moment the server had the whole request body to the first token: the + * parse, the chat template, tokenisation, the wait for admission and the prefill. + * The time the body took to arrive is not in it, so a client far from the server + * reads the server's own share of what it measured + * total_ms from the same moment to the last token * * The rates divide the tokens by the time that produced them: prompt_n by prompt_ms, and the * predicted_n - 1 tokens after the first by predicted_ms, since the first token is the prompt @@ -376,6 +382,7 @@ struct TimingsOut { int64_t decode_n = 0; /* of predicted_n, the tokens after each choice's first */ double predicted_ms = 0.0; int64_t draft_n = 0, draft_n_accepted = 0; + double ttft_ms = -1.0, total_ms = -1.0; /* < 0: the body's arrival is not known */ }; /* `timings` is added at the top level when it is valid. */ diff --git a/core/server/server.cpp b/core/server/server.cpp index ffbb83ec..35d78564 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -635,8 +635,9 @@ UsageOut Server::usage_of(const OaiRequest& r, const std::vector& ge /* WHERE THE REQUEST'S TIME WENT, from its sinks: one for a choice's final chunk, all of them for * the request. Every time is moved onto one clock first -- each sink counts from its own - * construction. See TimingsOut for what each field means. */ -TimingsOut Server::timings_of(const Sink* const* sinks, size_t n) { + * construction, and `received_ns` (the body's arrival, -1 when unknown) is on that clock already. + * See TimingsOut for what each field means. */ +TimingsOut Server::timings_of(const Sink* const* sinks, size_t n, int64_t received_ns) { TimingsOut t; int64_t admit = INT64_MAX, first_lo = INT64_MAX, first_hi = INT64_MIN, last = INT64_MIN; bool admitted = true; @@ -662,14 +663,18 @@ TimingsOut Server::timings_of(const Sink* const* sinks, size_t n) { if (!t.valid) return t; if (admitted) t.prompt_ms = (double)(first_hi - admit) * 1e-6; t.predicted_ms = (double)(last - first_lo) * 1e-6; + if (received_ns >= 0) { + t.ttft_ms = (double)(first_lo - received_ns) * 1e-6; + t.total_ms = (double)(last - received_ns) * 1e-6; + } return t; } -TimingsOut Server::timings_of(const std::vector& gens) { +TimingsOut Server::timings_of(const std::vector& gens, int64_t received_ns) { std::vector v; v.reserve(gens.size()); for (const auto& g : gens) v.push_back(g.sink.get()); - return timings_of(v.data(), v.size()); + return timings_of(v.data(), v.size(), received_ns); } /* ------------------------------------------------------------------ metrics bookkeeping */ @@ -722,7 +727,7 @@ void Server::record(const OaiRequest& r, const std::vector& gens, Fi /* THE OTHER HALF OF THE REQUEST LOG. The same figures /metrics aggregates, for this one * request: how it ended, what the prefix cache spared, the reasoning share when the parser * knows it, time to first token, the decode rate after it, and the whole. */ - const TimingsOut t = timings_of(gens); + const TimingsOut t = timings_of(gens, r.t_received_ns); const UsageOut u = usage_of(r, gens); const double rate = (decode > 0.0 && n_gen > 1) ? (double)(n_gen - 1) / decode : -1.0; char reason[32] = ""; @@ -740,6 +745,7 @@ void Server::record(const OaiRequest& r, const std::vector& gens, Fi /* ------------------------------------------------------------------ non-streaming */ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) { + r.t_received_ns = req.t_received_ns; std::vector gens; ApiError err; if (submit_all(r, &gens, &err) < 0) { @@ -846,7 +852,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) retire(gens); release(r.n_choices()); - const TimingsOut timings = timings_of(gens); + const TimingsOut timings = timings_of(gens, r.t_received_ns); if (r.shape == ApiShape::LlamaNative) { /* llama-server answers one result, and an array of them for several prompts. */ json res = json::array(); @@ -918,7 +924,7 @@ static const char* native_stop_type(Finish f) { * in the chunks before it. */ json Server::native_result(const OaiRequest& r, const Generation& g, const std::string& content) { const Sink* one = g.sink.get(); - const TimingsOut t = timings_of(&one, 1); + const TimingsOut t = timings_of(&one, 1, r.t_received_ns); const int64_t n_prompt = (int64_t)r.prompts[(size_t)g.prompt_index].tokens.size(); nlohmann::ordered_json o; o["index"] = g.index; @@ -1014,6 +1020,7 @@ static std::string progress_chunk(const OaiRequest& r, int index, const Sink& s) } HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) { + r.t_received_ns = req.t_received_ns; auto st = std::make_shared(); st->r = r; st->peer_closed = req.closed; @@ -1121,7 +1128,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) TimingsOut now; if (st->r.timings_per_token) { const Sink* one = g.sink.get(); - now = timings_of(&one, 1); + now = timings_of(&one, 1, st->r.t_received_ns); if (g.delta) g.delta->set_timings(now); } if (st->r.endpoint == Endpoint::Chat) { @@ -1172,7 +1179,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) /* EACH CHOICE'S OWN TIMINGS ON ITS FINAL CHUNK, so a client that asked for no * usage chunk still has them, as llama.cpp sends them. */ const Sink* one = g.sink.get(); - const TimingsOut gt = timings_of(&one, 1); + const TimingsOut gt = timings_of(&one, 1, st->r.t_received_ns); /* A failed generation cannot become a non-200 -- the headers left long ago -- so * it travels as an error event in the stream. Silence would look like a normal * end of stream and the client would use a truncated answer. */ @@ -1212,7 +1219,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) * prompt and one total, so emitting it per generation would count the prompt n times * and interleave usage between the choices' final chunks. */ if (st->r.include_usage) { - const TimingsOut t = timings_of(st->gens); + const TimingsOut t = timings_of(st->gens, st->r.t_received_ns); out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u, t) : text_usage_chunk(st->r, u, t); } diff --git a/core/server/server.h b/core/server/server.h index e33672d3..9ff2a2a2 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -189,8 +189,8 @@ private: struct StreamState; static UsageOut usage_of(const OaiRequest& r, const std::vector& gens); - static TimingsOut timings_of(const Sink* const* sinks, size_t n); - static TimingsOut timings_of(const std::vector& gens); + static TimingsOut timings_of(const Sink* const* sinks, size_t n, int64_t received_ns); + static TimingsOut timings_of(const std::vector& gens, int64_t received_ns); void register_routes(); diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp index 8ff945a4..b5acc4c4 100644 --- a/core/text/tokenizer.cpp +++ b/core/text/tokenizer.cpp @@ -605,16 +605,34 @@ int Vocab::load(VocabBuild b) { if (b_.eos >= 0) eog_.push_back(b_.eos); if (b_.eot >= 0 && b_.eot != b_.eos) eog_.push_back(b_.eot); { + /* Gemma 4 ends a turn on `` and a tool-calling turn on `<|tool_response>` -- the + * opener of the result the CALLER supplies, which the model writes after its last + * `` -- and declares neither: its eos is ``. llama.cpp's loader lists + * both for it, and both are control tokens nothing else spells. */ static const char* const kEogNames[] = { "<|endoftext|>", "<|im_end|>", "<|eot_id|>", "<|end_of_text|>", "", "<|end|>", "<|EOT|>", "<|eom_id|>", "<|return|>", "", "", + "", "<|tool_response>", }; + /* `` IS A DOCUMENT'S END, NOT A TURN'S. A vocabulary with a turn marker of its own + * ends a reply on that marker, and there `` -- where it is a control token at all + * and not the declared eos -- is text a reply may write: Gemma 4 spells the HTML tag with + * it. So it joins the set only in a vocabulary that has no turn marker. */ + static const char* const kTurnEnds[] = { + "<|im_end|>", "<|eot_id|>", "", "<|end|>", "<|EOT|>", "", + }; + bool has_turn_end = false; + for (int32_t id : special_) { + if (b_.types[id] != RAD_TT_CONTROL) continue; + for (const char* n : kTurnEnds) if (b_.tokens[id] == n) has_turn_end = true; + } std::string added; for (int32_t id : special_) { if (b_.types[id] != RAD_TT_CONTROL) continue; if (std::find(eog_.begin(), eog_.end(), id) != eog_.end()) continue; bool known = false; for (const char* n : kEogNames) if (b_.tokens[id] == n) { known = true; break; } + if (has_turn_end && b_.tokens[id] == "") known = false; if (!known) continue; eog_.push_back(id); added += (added.empty() ? "" : " ") + b_.tokens[id] + "=" + std::to_string(id); diff --git a/core/util/rad_util.cpp b/core/util/rad_util.cpp index 48ce2984..81b8667b 100644 --- a/core/util/rad_util.cpp +++ b/core/util/rad_util.cpp @@ -1,6 +1,7 @@ /* rad_util.cpp -- logging, error strings, dtype arithmetic and tensor helpers. The bedrock every * other translation unit links against. */ +#include #include #include "../rad_internal.h" @@ -73,6 +74,9 @@ void log_rank_tags(bool on) { g_rank_tags = on; } LogRank::LogRank(int rank) : prev_(g_log_rank) { g_log_rank = rank; } LogRank::~LogRank() { g_log_rank = prev_; } +static std::atomic g_last_line_ns{0}; +uint64_t log_last_line_ns() { return g_last_line_ns.load(std::memory_order_relaxed); } + void log_emit(Log l, const char* file, int line, const char* fmt, ...) { const char* base = std::strrchr(file, '/'); base = base ? base + 1 : file; @@ -95,6 +99,7 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...) { fprintf(stderr, "%s%s%s%s %s:%d %s\n", col, level_tag(l), rank, rst, base, line, msg); else fprintf(stderr, "%s%s%s%s %s\n", col, level_tag(l), rank, rst, msg); + g_last_line_ns.store(rad_mono_ns(), std::memory_order_relaxed); } void fatal(const char* fmt, ...) { diff --git a/core/util/stallwatch.cpp b/core/util/stallwatch.cpp new file mode 100644 index 00000000..018007b3 --- /dev/null +++ b/core/util/stallwatch.cpp @@ -0,0 +1,290 @@ +/* stallwatch.cpp -- see stallwatch.h. */ +#include "util/stallwatch.h" + +#include "rad_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +namespace { + +std::string read_first_line(const std::string& path) { + std::ifstream f(path); + std::string s; + if (f) std::getline(f, s); + return s; +} + +/* The ioctl numbers of the KFD (type 'K'), as assigns them. By number rather + * than by macro, because the header a build sees can be older than the driver it runs on. */ +const char* kfd_ioctl_name(unsigned nr) { + static const char* const k[] = { + nullptr, "GET_VERSION", "CREATE_QUEUE", "DESTROY_QUEUE", "SET_MEMORY_POLICY", + "GET_CLOCK_COUNTERS", "GET_PROCESS_APERTURES", "UPDATE_QUEUE", "CREATE_EVENT", + "DESTROY_EVENT", "SET_EVENT", "RESET_EVENT", "WAIT_EVENTS", "DBG_REGISTER", + "DBG_UNREGISTER", "DBG_ADDRESS_WATCH", "DBG_WAVE_CONTROL", "SET_SCRATCH_BACKING_VA", + "GET_TILE_CONFIG", "SET_TRAP_HANDLER", "GET_PROCESS_APERTURES_NEW", "ACQUIRE_VM", + "ALLOC_MEMORY_OF_GPU", "FREE_MEMORY_OF_GPU", "MAP_MEMORY_TO_GPU", "UNMAP_MEMORY_FROM_GPU", + "SET_CU_MASK", "GET_QUEUE_WAVE_STATE", "GET_DMABUF_INFO", "IMPORT_DMABUF", + "ALLOC_QUEUE_GWS", "SMI_EVENTS", "SVM", "SET_XNACK_MODE", "CRIU_OP", "AVAILABLE_MEMORY", + "EXPORT_DMABUF", "RUNTIME_ENABLE", "DBG_TRAP", "CREATE_PROCESS", "PROFILER", + }; + return nr < sizeof k / sizeof k[0] ? k[nr] : nullptr; +} + +/* The system calls a waiting thread is found in, by their x86-64 numbers. */ +const char* syscall_name(long nr) { +#if defined(__x86_64__) + switch (nr) { + case 0: return "read"; case 1: return "write"; case 2: return "open"; + case 3: return "close"; case 4: return "stat"; case 7: return "poll"; + case 9: return "mmap"; case 10: return "mprotect"; case 11: return "munmap"; + case 16: return "ioctl"; case 17: return "pread64"; case 18: return "pwrite64"; + case 23: return "select"; case 28: return "madvise"; case 35: return "nanosleep"; + case 61: return "wait4"; case 149: return "mlock"; case 202: return "futex"; + case 230: return "clock_nanosleep"; case 232: return "epoll_wait"; + case 237: return "mbind"; case 257: return "openat"; case 262: return "newfstatat"; + case 270: return "pselect6"; case 271: return "ppoll"; case 281: return "epoll_pwait"; + case 332: return "statx"; case 426: return "io_uring_enter"; case 437: return "openat2"; + default: return nullptr; + } +#else + (void)nr; + return nullptr; +#endif +} + +bool is_ioctl(long nr) { +#if defined(__x86_64__) + return nr == 16; +#else + (void)nr; + return false; +#endif +} + +/* ---- the stack of a thread that waits in user space, taken by a signal it handles itself ---- */ + +constexpr int kMaxFrames = 48; +std::atomic g_want_tid{0}; +std::atomic g_have{0}; +void* g_frames[kMaxFrames]; +int g_n_frames = 0; + +void on_stack_signal(int) { + if ((pid_t)syscall(SYS_gettid) != g_want_tid.load(std::memory_order_acquire)) return; + g_n_frames = backtrace(g_frames, kMaxFrames); + g_have.store(1, std::memory_order_release); +} + +/* A real-time signal nothing else in the process uses (glibc keeps the first few for itself). */ +int stack_signal() { return SIGRTMIN + 7; } + +std::once_flag g_install_once; +void install_stack_handler() { + std::call_once(g_install_once, [] { + /* backtrace() loads its unwinder on first use; done here, outside any handler. */ + void* prime[2]; + (void)backtrace(prime, 2); + struct sigaction sa {}; + sa.sa_handler = on_stack_signal; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESTART; + sigaction(stack_signal(), &sa, nullptr); + }); +} + +std::string stack_of(pid_t tid) { + install_stack_handler(); + g_have.store(0, std::memory_order_relaxed); + g_want_tid.store(tid, std::memory_order_release); + if (syscall(SYS_tgkill, getpid(), tid, stack_signal()) != 0) { + g_want_tid.store(0); + return "the thread could not be signalled"; + } + for (int i = 0; i < 200 && !g_have.load(std::memory_order_acquire); ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + g_want_tid.store(0, std::memory_order_release); + if (!g_have.load(std::memory_order_acquire)) + return "no stack: the thread did not take the signal within 2 s"; + std::string s; + /* Frame 0 and 1 are the handler and the signal trampoline. */ + for (int i = 2; i < g_n_frames; ++i) + s += (s.empty() ? "" : " ") + stall_module_offset((uintptr_t)g_frames[i]); + return s; +} + +} /* namespace */ + +std::string stall_module_offset(uintptr_t addr) { + /* RELATIVE TO WHERE THE MODULE IS LOADED, which is what addr2line takes for a position- + * independent binary or library: the start of its first mapping, less that mapping's file + * offset. The offset into the file is not the same number wherever the linker puts a segment + * at a different address than its file position, as lld does. */ + struct Map { unsigned long lo, hi, off; std::string path; }; + std::vector maps; + { + std::ifstream f("/proc/self/maps"); + std::string line; + while (std::getline(f, line)) { + Map m{}; + char path[512] = ""; + if (std::sscanf(line.c_str(), "%lx-%lx %*s %lx %*s %*s %511s", &m.lo, &m.hi, &m.off, + path) < 3) + continue; + m.path = path; + maps.push_back(std::move(m)); + } + } + for (const Map& m : maps) { + if (addr < m.lo || addr >= m.hi) continue; + if (m.path.empty() || m.path[0] != '/') return fmt("0x%lx", (unsigned long)addr); + unsigned long base = m.lo - m.off; + for (const Map& o : maps) + if (o.path == m.path && o.lo - o.off < base) base = o.lo - o.off; + const size_t slash = m.path.rfind('/'); + return fmt("%s+0x%lx", m.path.c_str() + slash + 1, (unsigned long)(addr - base)); + } + return fmt("0x%lx", (unsigned long)addr); +} + +std::string stall_decode_syscall(const std::string& line) { + if (line.empty()) return "unknown"; + if (line == "running") return "running"; + std::istringstream in(line); + long nr = 0; + if (!(in >> nr)) return "unknown"; + if (nr < 0) return "not in a system call"; + std::vector a; + std::string w; + while (in >> w) a.push_back(std::strtoul(w.c_str(), nullptr, 16)); + /* Six arguments, then the stack pointer and the program counter. */ + const unsigned long pc = a.size() >= 8 ? a[7] : 0; + std::string s; + if (is_ioctl(nr) && a.size() >= 2) { + const long fd = (long)a[0]; + const unsigned long req = a[1]; + char target[256] = ""; + const ssize_t n = readlink(fmt("/proc/self/fd/%ld", fd).c_str(), target, sizeof target - 1); + if (n > 0) target[n] = 0; else std::snprintf(target, sizeof target, "fd %ld", fd); + const unsigned type = (unsigned)((req >> 8) & 0xff), num = (unsigned)(req & 0xff); + const char* kfd = type == 'K' ? kfd_ioctl_name(num) : nullptr; + s = kfd ? fmt("ioctl(%s, AMDKFD_IOC_%s)", target, kfd) + : fmt("ioctl(%s, request 0x%lx: type '%c' number 0x%x)", target, req, + type >= 0x20 && type < 0x7f ? (char)type : '?', num); + } else if (const char* name = syscall_name(nr)) { + s = name; + } else { + s = fmt("system call %ld", nr); + } + if (pc) s += ", called from " + stall_module_offset(pc); + return s; +} + +std::string stall_describe_thread(pid_t tid, bool stack) { + const std::string dir = fmt("/proc/self/task/%d/", (int)tid); + const std::string stat = read_first_line(dir + "stat"); + /* The state is the field after the parenthesised name, which may itself hold spaces. */ + char state = '?'; + const size_t rp = stat.rfind(')'); + if (rp != std::string::npos && rp + 2 < stat.size()) state = stat[rp + 2]; + const std::string wchan = read_first_line(dir + "wchan"); + const std::string sc = read_first_line(dir + "syscall"); + std::string s = fmt("tid %d (%s), state %c", (int)tid, read_first_line(dir + "comm").c_str(), + state); + if (!wchan.empty() && wchan != "0") s += ", waiting in the kernel at " + wchan; + s += ", " + stall_decode_syscall(sc); + long nr = -1; + std::sscanf(sc.c_str(), "%ld", &nr); + /* A thread in a driver call is not signalled: the call already says where it is, and a wait + * the signal interrupts may end the call early instead of restarting it. */ + if (stack && !is_ioctl(nr) && state != 'D') s += "\n stack: " + stack_of(tid); + return s; +} + +struct StallWatch::Impl { + std::string phase; + uint64_t quiet_ns = 0; + pid_t holder = 0; + std::mutex mu; + std::condition_variable cv; + bool stop = false; + std::thread th; + + void report(uint64_t silent_ns) { + const pid_t me = (pid_t)syscall(SYS_gettid); + std::string others; + int n_others = 0; + if (DIR* d = opendir("/proc/self/task")) { + while (dirent* e = readdir(d)) { + const pid_t t = (pid_t)std::atoi(e->d_name); + if (t <= 0 || t == holder || t == me) continue; + long nr = -1; + std::sscanf(read_first_line(fmt("/proc/self/task/%d/syscall", (int)t)).c_str(), + "%ld", &nr); + if (!is_ioctl(nr)) continue; + if (n_others++ < 8) others += "\n also in a driver call: " + + stall_describe_thread(t, false); + } + closedir(d); + } + if (n_others > 8) others += fmt("\n and %d more threads in a driver call", n_others - 8); + RAD_WARN("%s: nothing has been logged for %.0f s since the line above. The thread doing " + "the %s is %s%s\n A report of a %s that stops here should include these lines.", + phase.c_str(), (double)silent_ns / 1e9, phase.c_str(), + stall_describe_thread(holder, true).c_str(), others.c_str(), phase.c_str()); + } + + void run() { + uint64_t since = rad_mono_ns(); /* the start of the current silence */ + uint64_t own = 0; /* the time of this watch's own last report */ + uint64_t next = quiet_ns; /* the silence that is reported next */ + std::unique_lock lk(mu); + while (!cv.wait_for(lk, std::chrono::seconds(1), [&] { return stop; })) { + const uint64_t last = log_last_line_ns(); + if (last > since && last != own) { since = last; next = quiet_ns; } + const uint64_t now = rad_mono_ns(); + if (now - since < next) continue; + lk.unlock(); + report(now - since); + lk.lock(); + own = log_last_line_ns(); + next *= 2; + } + } +}; + +StallWatch::StallWatch(const char* phase, uint64_t quiet_ms) : p_(std::make_unique()) { + p_->phase = phase ? phase : "phase"; + p_->quiet_ns = quiet_ms * 1000000ull; + p_->holder = (pid_t)syscall(SYS_gettid); + install_stack_handler(); + p_->th = std::thread([this] { p_->run(); }); +} + +StallWatch::~StallWatch() { + { + std::lock_guard lk(p_->mu); + p_->stop = true; + } + p_->cv.notify_all(); + if (p_->th.joinable()) p_->th.join(); +} + +} /* namespace rad */ diff --git a/core/util/stallwatch.h b/core/util/stallwatch.h new file mode 100644 index 00000000..b0240e8e --- /dev/null +++ b/core/util/stallwatch.h @@ -0,0 +1,58 @@ +/* stallwatch.h -- naming where a phase that has gone quiet is waiting. + * + * A startup that stops printing leaves the hardest report to act on: the log ends on the last line + * that was printed, and whatever came after it -- a driver call that never returned, a lock inside a + * runtime library -- leaves no trace. The machine it happens on is often one this project cannot + * run (a guest kernel, a card passed through to a VM), so where it waits has to come from the + * process itself. + * + * A StallWatch is held across a phase by the thread doing it. When nothing has been logged for the + * quiet interval it says what that thread is doing: + * - its scheduler state and kernel wait channel; + * - the system call it is in, an ioctl with its device and request, and the library that made + * the call; + * - when the thread waits in user space (a lock, a sleep), its stack as module+offset frames, + * which addr2line symbolises against the released binary. A thread inside an ioctl is not + * signalled: the call already names where it waits, and a signal could end a driver wait + * early; + * - the process's other threads that are inside an ioctl, since a lock in a runtime library is + * usually held by one of them. + * It says it again each time the silence doubles, so a later log shows whether the thread moved. + * The watch reads only its own process's /proc entries and costs one wake-up a second while held. + */ +#pragma once + +#include +#include +#include +#include + +namespace rad { + +class StallWatch { +public: + /* `phase` names what is being watched in the report ("startup"). */ + explicit StallWatch(const char* phase, uint64_t quiet_ms = 60000); + ~StallWatch(); + StallWatch(const StallWatch&) = delete; + StallWatch& operator=(const StallWatch&) = delete; + + struct Impl; + +private: + std::unique_ptr p_; +}; + +/* What thread `tid` of this process is doing, as the report words it: state, wait channel, system + * call. With `stack`, a thread waiting in user space is also asked for its frames. */ +std::string stall_describe_thread(pid_t tid, bool stack); + +/* One line of /proc//task//syscall in words: "running", "not in a system call", or the + * call with its arguments decoded where they name something (an ioctl's device and request). */ +std::string stall_decode_syscall(const std::string& line); + +/* `addr` as the module that maps it and its offset from the module's load base, "libfoo.so+0x1a2b": + * the number addr2line takes for that module. */ +std::string stall_module_offset(uintptr_t addr); + +} /* namespace rad */ diff --git a/data/recipes/gemma4-26b-a4b-df-bf16x.recipe b/data/recipes/gemma4-26b-a4b-df-bf16x.recipe new file mode 100644 index 00000000..90cd1f37 --- /dev/null +++ b/data/recipes/gemma4-26b-a4b-df-bf16x.recipe @@ -0,0 +1,23 @@ +# gemma4-26b-a4b-df-bf16x.recipe -- gemma-4-26B-A4B-it with z-lab's DFlash drafter and the routed +# experts left bf16, as arch/gemma4 serves it. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-26b-a4b-df-bf16x.recipe -o gemma4-26b-a4b-df-bf16x.rad +# +# The trunk exactly as the checkpoint holds it -- the bf16 reference the fp8-expert containers are +# measured against (radiance --kld-record) -- with only the drafter quantised. + +# The DFlash drafter's six linears: block fp8 (the drafter only proposes; the trunk verifies). +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The drafter's head: the target's tied table again under a name of its own, block fp8, which the +# draft head reads instead of the bf16 table -- half the widest read on the draft path, for half +# the table's bytes again (176 MiB a rank at tp 4). Drafts are verified, so this changes what is +# proposed, never what is accepted. +dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/data/recipes/gemma4-26b-a4b-df-pad768.recipe b/data/recipes/gemma4-26b-a4b-df-pad768.recipe new file mode 100644 index 00000000..46749c3b --- /dev/null +++ b/data/recipes/gemma4-26b-a4b-df-pad768.recipe @@ -0,0 +1,31 @@ +# gemma4-26b-a4b-df-pad768.recipe -- gemma-4-26B-A4B-it with its experts PADDED TO 768 wide, and +# z-lab's DFlash drafter, as arch/gemma4 serves it. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-26b-a4b-df-pad768.recipe -o gemma4-26b-a4b-df-pad768.rad +# +# The padding happens BEFORE conversion, outside the engine: each expert's gate and up gain 64 +# zero rows (704 -> 768) and its down 64 zero columns, and moe_intermediate_size becomes 768. It is +# exact -- gelu(0) * 0 = 0 in the added intermediate columns, which meet zero columns of down -- so +# the padded model computes the original's function. 768 is six whole 128-blocks, which the fp8 +# grouped GEMM needs for down's K, and gate and up each start on a block boundary. +# +# Both expert projections block fp8. Everything else as gemma4-26b-a4b-df.recipe says. + +blk.*.ffn_gate_up_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_down_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The DFlash drafter's six linears: block fp8 (the drafter only proposes; the trunk verifies). +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The drafter's head: the target's tied table again under a name of its own, block fp8, which the +# draft head reads instead of the bf16 table -- half the widest read on the draft path, for half +# the table's bytes again (176 MiB a rank at tp 4). Drafts are verified, so this changes what is +# proposed, never what is accepted. +dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/data/recipes/gemma4-26b-a4b-df.recipe b/data/recipes/gemma4-26b-a4b-df.recipe new file mode 100644 index 00000000..b296b701 --- /dev/null +++ b/data/recipes/gemma4-26b-a4b-df.recipe @@ -0,0 +1,33 @@ +# gemma4-26b-a4b-df.recipe -- gemma-4-26B-A4B-it with z-lab's DFlash drafter, from the bf16 +# checkpoint as Google ships it, as arch/gemma4 serves it. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-26b-a4b-df.recipe -o gemma4-26b-a4b-df.rad +# +# The routed experts are ~90% of the weight bytes and a decode step reads whichever were routed. +# Their gate_up is block fp8: 2 x 704 = 1408 rows are whole 64-row GEMM tiles and eleven 128-row +# scale blocks, and K = 2816 is 22. A third of the expert bytes a decode step reads. +# +# Their down projection stays bf16: K is the expert width, 704, and the fp8 grouped GEMM reads K +# in whole 128-column blocks. gemma4-26b-a4b-df-pad768.recipe makes it fp8 as well, from a +# checkpoint whose experts were padded to 768 first. +# +# The attention, the dense arm, the router, the norms and the tied embedding stay bf16: together +# under a tenth of the bytes, and the dense arm's 2112 is not whole 128-blocks either. + +blk.*.ffn_gate_up_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The DFlash drafter's six linears: block fp8 (the drafter only proposes; the trunk verifies). +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The drafter's head: the target's tied table again under a name of its own, block fp8, which the +# draft head reads instead of the bf16 table -- half the widest read on the draft path, for half +# the table's bytes again (176 MiB a rank at tp 4). Drafts are verified, so this changes what is +# proposed, never what is accepted. +dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/deploy/compose/.env.example b/deploy/compose/.env.example index 5e2b5eb0..d6941845 100644 --- a/deploy/compose/.env.example +++ b/deploy/compose/.env.example @@ -7,9 +7,6 @@ RADIANCE_IMAGE=stilldeadcode/radiance:latest # Directory holding the .rad containers, mounted read-only at /models. RADIANCE_MODELS=/srv/models/rad -# Writable directory mounted at /data: the prefix cache's disk tier lives under it. -RADIANCE_STATE=/srv/radiance - # Every request but /health, /ping and the dashboard page must carry `Authorization: Bearer ` # (or `X-Api-Key: `). RADIANCE_API_KEY= diff --git a/deploy/compose/common.yaml b/deploy/compose/common.yaml index afc29967..4c9d1cf8 100644 --- a/deploy/compose/common.yaml +++ b/deploy/compose/common.yaml @@ -32,7 +32,6 @@ services: memlock: -1 volumes: - ${RADIANCE_MODELS:?set RADIANCE_MODELS in .env}:/models:ro - - ${RADIANCE_STATE:?set RADIANCE_STATE in .env}:/data # A server finishes the step in flight and releases the cards on SIGTERM. stop_grace_period: 60s healthcheck: diff --git a/deploy/compose/flashnext-tp1.yaml b/deploy/compose/flashnext-tp1.yaml index 0c4350c3..51e46278 100644 --- a/deploy/compose/flashnext-tp1.yaml +++ b/deploy/compose/flashnext-tp1.yaml @@ -19,6 +19,5 @@ services: --tp 1 --max-num-seqs 4 --max-model-len 200000 --placement expert_tiered --host-pool-mib 43000 --gpu-headroom-mib 96 --kv-cache-dtype fp8 - --prefix-cache-host-mib 4096 --prefix-cache-dir /data/kvcache/flashnext-tp1 - --prefix-cache-disk-mib 131072 + --prefix-cache-mib 4096 --num-speculative-tokens 3 --max-num-batched-tokens 4096 --checkpoint-interval 4096 diff --git a/deploy/compose/flashnext.yaml b/deploy/compose/flashnext.yaml index 8e6f7a53..62e43f9e 100644 --- a/deploy/compose/flashnext.yaml +++ b/deploy/compose/flashnext.yaml @@ -1,7 +1,6 @@ # Qwen3.8-Flash-Next, the production container (data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe): # int8 trunk and lm_head, routed experts as 4-bit codebook codes at E4M3 scales. The experts that -# do not fit VRAM are streamed from a pinned host pool; idle sessions move to host memory and then -# to disk under /data/kvcache/flashnext. +# do not fit VRAM are streamed from a pinned host pool; idle sessions move to host memory. name: radiance-flashnext services: radiance: @@ -13,6 +12,5 @@ services: --tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 - --prefix-cache-host-mib 4096 --prefix-cache-dir /data/kvcache/flashnext - --prefix-cache-disk-mib 131072 + --prefix-cache-mib 4096 --num-speculative-tokens 3 --max-num-batched-tokens 2048 diff --git a/deploy/compose/qwen3.8-27b-paro.yaml b/deploy/compose/qwen3.8-27b-paro.yaml new file mode 100644 index 00000000..ccc0f2c7 --- /dev/null +++ b/deploy/compose/qwen3.8-27b-paro.yaml @@ -0,0 +1,13 @@ +# Qwen3.8-27B ParoQuant int4 (z-lab's release: AWQ int4, group 128, with the learned Givens +# rotations it was trained in) and its DFlash2 block-diffusion drafter, on one card. The int5 and +# MXFP4 containers serve from this file too: point --model at them. +name: radiance-qwen3.8-27b-paro +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-qwen3.8-27b-paro + command: > + --model /models/qwen3.8-27b-paro-int4.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8 + --max-num-batched-tokens 2048 --embedding-placement ram --host-pool-mib 3072 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 24961413..a79b58e0 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -14,7 +14,8 @@ into the id an architecture plugin claims. | `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed | | `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | -| `arch/gemma4_bf16` | `gemma4_bf16` | `i4` (group-128 codes, f16 scale) | Gemma 4 31B dense (text): two attention classes — sliding-window and proportional-RoPE global (`attention_k_eq_v`) — over one GemmaRMSNorm stream, GELU ffn, two KV groups, softcapped logits, tied scaled embedding; served from a CT-INT4 (QAT w4a16) checkpoint. Optional draft head: Google's assistant (`rad-convert --draft-model`), a serial head with no cache of its own (`rad_drafter_shared_kv`) | +| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense (text): two attention classes — sliding-window and proportional-RoPE global (`attention_k_eq_v`) — over one GemmaRMSNorm stream, GELU ffn, two KV groups, softcapped logits, tied scaled embedding; served from a CT-INT4 (QAT w4a16) checkpoint as group-128 int4 codes with an f16 scale. Optional draft head: Google's assistant (`rad-convert --draft-model`), a serial head with no cache of its own (`rad_drafter_shared_kv`) | +| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint — the 26B-A4B MoE (a dense and a routed arm side by side) and the dense sizes without per-layer embeddings — with z-lab's DFlash drafter; routed experts bf16 or block fp8, as the recipe chose | This document is the geometry of each, and the handful of readings that are **arithmetically silent** — wrong in a way that produces fluent output and no error anywhere. @@ -447,3 +448,131 @@ The traps: is a real one; the processor stages exactly those plus zero frames to whole rows, which reproduces every row the reference keeps. +--- + +# `gemma4` — Gemma 4 text, and its DFlash drafter + +`arch/gemma4` serves a container converted from Google's bf16 checkpoint (`Gemma4ForConditionalGeneration` +or `Gemma4ForCausalLM`), the recipe choosing what is fp8: gemma-4-26B-A4B-it, and the dense sizes +without per-layer embeddings. The CT-INT4 31B release is `arch/gemma4_bf16`'s. A z-lab DFlash +drafter is merged at convert time (`--draft-model`); the recipes are +`data/recipes/gemma4-26b-a4b-df*.recipe`. The reference is transformers' `modeling_gemma4`. + +``` +gemma-4-26B-A4B-it + 30 layers, hidden 2816, vocab 262144 tied to the embedding, rms_norm_eps 1e-6 + layer_types: five sliding_attention then one full_attention, five times + sliding 16 heads / 8 kv x 256, rope theta 1e4 over the whole head, window 1024 + full 16 heads / 2 kv x 512, PROPORTIONAL rope theta 1e6 over a quarter of it, K = V + attention scale 1: q and k RMS-normed per head with a gain, v with none + sandwich norms, plain gains (x_hat * w) + the feed-forward is two arms reading the same residual, summed: + dense pre_feedforward_layernorm -> gate|up 2112 (gelu-tanh) -> down -> post_feedforward_layernorm_1 + routed router -> softmax -> top 8 of 128 -> renormalised -> * per_expert_scale[expert]; + pre_feedforward_layernorm_2 -> 128 experts of 704 (gelu-tanh) -> post_feedforward_layernorm_2 + sum -> post_feedforward_layernorm -> residual add + layer_scalar multiplies the residual stream at the end of every layer + embedding * sqrt(2816) as a bf16; final norm; tied head; final_logit_softcapping 30 +DFlash a small Qwen3-shaped block drafter: an anchor and block - 1 mask tokens denoised in one + pass over the trunk's hidden states at target_layer_ids; drafts read off the TARGET's head +``` + +The readings that stay plausible when wrong: + +- **Proportional rope is not a partial rotary.** The full layers rotate the first 64 frequency + pairs of the 512-wide head at theta^(-2j/512) — the exponent divides by the HEAD — with pair j + channels (j, j + 256), and leave the other 192 pairs at frequency zero. `rope` with + `rotary_dim` 128 pairs (j, j + 64) at theta^(-2j/128): a different function that still produces + fluent text. The plugin declares a full-width NeoX `rope` whose frequencies past pair 63 are + divided by 1e30 through the YaRN ramp `rope` already carries, a step at 63.5..64. +- **V on a full layer is the un-normed, un-rotated k projection**, RMS-normed with a unit gain, so + the value norm reads `k` before the key norm writes it. +- **The router does not read the feed-forward's input.** It reads the residual stream through a + gainless norm times its own `scale` vector times hidden^-0.5, while the experts read + pre_feedforward_layernorm_2's output. `per_expert_scale` multiplies the weight AFTER the + renormalised top-k. +- **The arms' two post-norms are per arm**, so under tensor parallel each arm's partial sum is + reduced before its norm. The partials share one [2T, hidden] buffer, dense rows first -- each + slice's own run of it when a prefill chunk is cut in two -- so one all-reduce carries both. +- **The embedding scale is sqrt(hidden) rounded to bf16**: 53.0, not 53.066. The drafter reads the + same scaled embedding. +- **The sliding layers' KV group is `RAD_KV_FULL`**, with the window on the attention op. A + `RAD_KV_WINDOW` group is not prefix-cached, so a hit on it reuses nothing and re-prefills; as + FULL the hit is kept. The planner gives every paged group the same block count, so the recycling + a window group would buy is worth nothing here. +- **The drafter's sliding layers are causal and its full layer is not**, and its logits' softcap + is ignored on purpose: a draft is an argmax and the cap is strictly increasing. + +**Tensor parallel.** Heads split by rank, o and down by column with an all-reduce, the vocabulary +by row. The full layers' two KV heads are replicated past two ranks. Routed experts are +expert-parallel, 128 / world whole experts a rank, because a 704-wide expert has no block-aligned +width split; the router is replicated, so every rank agrees on the routing without a collective. +The drafter's head is vocab-sharded with the trunk's: each rank's top-2 are all-gathered and +`pair_argmax` picks the winner (two a rank, because a row-interleaved `all_gather` moves 16-byte +words and one pair is 8 bytes). + +**The prefill overlap.** At more than one rank, a prefill chunk of two routed passes or more (4096 +tokens, at the 2048-token pass) runs as two slices, and the trunk's all-reduces ride the runtime's +second lane beside the other slice's compute: slice A's attention reduction runs under slice B's +output projection, slice B's under slice A's two arms, and so on through the layer. Attention runs +whole, since it reads every row's keys. The cut is a whole number of routed passes and both slices +are above every row band the sliced kernels have, so the step issues the same kernels over the +same rows and its output is the whole step's, bit for bit. On 4x R9700 the reductions were 47% of +a 20K-token prefill under `--profile-ops`; a model of the measured times puts the overlap at up to +a quarter off an unprofiled prefill. The per-op profile syncs every op, so it cannot show it -- +time a prefill without `--profile-ops`. A step that runs whole -- every decode and verify step -- +takes the second lane for the dense arm instead, beside the routed arm, which needs nothing of it +until the feed-forward join: at decode the dense arm's GEMMs are a few rows, latency-bound and far +from the bandwidth the experts take, and its reductions stay on lane 0. On two R9700s the sliced +prefill gives the whole chunk's text and logprobs exactly, at 2048- and 8192-token chunks; the +startup notes say which form each step takes. + +**The draft head in fp8.** The drafter's head is the widest read on the draft path: the target's +bf16 table, 352 MiB a rank at tp 4, every draft pass. A container converted with the line +`dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16` (the three `-df` recipes +carry it) stores a block-fp8 copy of the table under that name, and the head reads the copy at +fp8a8 instead -- half the bytes, for 176 MiB a rank more. Drafts are verified, so the coarser +logits can change what is proposed and never what is accepted; `draft_n_accepted` says whether +they propose worse. A container without the copy reads the bf16 table as before, and the startup +note names which head is in use. + +**FP8 experts.** The experts are ~90% of the weight bytes, so each projection is served as the +container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up `[1408, 2816]` +is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not — the fp8 grouped GEMM reads K in +whole 128-column blocks — so it stays bf16 unless the checkpoint's experts were padded to 768 before +conversion (zero rows of gate and up, zero columns of down: exact). The fp8 tables are split by +expert parity, so a rank holds an even number of experts. + +**Kernels.** libr4d serves all of the trunk's attention on its windowed kernels -- the sliding +layers (h256, gqa 2) and the full layers at gqa 8, 4 and 2 (one or two, four, eight ranks) -- +plus `pair_argmax` and the fusions: the two sandwich-norm joins (`norm_add_norm`, +`join_add_scale`), `norm_add_norm_route` -- on a layer whose gate_up is block fp8, the attention +join writing the router's input and the experts' fp8 codes from the norm it already takes, in place +of an `rmsnorm` and an `rmsnorm_quant_fp8` -- `expert_scale`, and `attn_paged_qrow`, the sliding +layers' attention reading q where the fused qkv projection left it. The plugin declares each one's +unfused form where nothing serves it -- the rmsnorm / add chain, `embed_lookup` + `mul`, a `cast` +lifting q for `attn_paged` -- and the startup notes say which were taken. libref and libavx do not +declare these ops, so the plugin asks whether one is declared before it asks for it +(`rad_op_declared`), and a deployment without libr4d's device rows -- a CPU-only build, the host +backend -- runs the chains. On a card the fused joins and libr4d's chain differ by the order of +the chain's reductions, not bit for bit: the joins round as the host chain does (tests/r4d_emu). +The drafter's residual add, norm and fp8 quantiser of x are one libr4d `rmsnorm_quant_fp8` launch +an input (ten a draft pass), and the `add` / `rmsnorm` / `quant_act_fp8` chain where nothing serves +it. The sliding layers' attention stays on the windowed kernel because only it reads q in place: +plain `attn_paged` at h256/gqa2 -- the dense 31B's sliding layers -- takes libr4d's h256/gqa2 +leg, which rad-kbench times at 0.26-0.71 of the windowed kernel at decode and 0.43-0.67 at +prefill. A drafter head sharded over more than one rank needs `pair_argmax` on the card. + +**A drafter that is not working still writes fluent text.** Every draft is verified, so a broken +drafter costs speed and nothing else: judge it by `draft_n_accepted` (about a third of `draft_n` on +prose, at about two tokens a step), not by the reply. The trap that showed it: the buffer planner +takes liveness from DECLARATION order, so the tap copy into `dflash_src` is declared at the end of +the layer it taps, where it is issued. Declared once after the trunk, it let the planner share +`dflash_src` with `moe_edn`, which every MoE layer writes, whenever the sizes allowed it +(`--max-num-seqs 16` did): 2% acceptance, slower than no speculation, and nothing in the text to +say so. arch_test holds the two live ranges to overlap. + +**Not declared.** The vision tower (`arch/embgemma2` declares Gemma 4's, for an encoder): a container +that carries one is served with `--mm-max-patches 0`. An fp8 attention or dense arm — under a tenth +of the weight bytes, and the dense arm's 2112 is not whole 128-blocks either. + diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 70ab80c5..b0cc3c43 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -128,16 +128,18 @@ the cards the engine runs on. | `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 | | `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower | | `qwen3.8-27b-mxfp4.yaml` | `qwen3.8-27b-mxfp4.rad` | Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk, its DFlash2 drafter and vision tower | +| `qwen3.8-27b-paro.yaml` | `qwen3.8-27b-paro-int4.rad` | Qwen3.8-27B ParoQuant int4 (learned rotations) with its DFlash2 drafter and vision tower; the int5 and MXFP4 containers serve from it too | | `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 | +| `gemma4-31b-w4a8.yaml` | `gemma4-31b-w4a8.rad` | Gemma 4 31B, int4 trunk with int8 activations, its assistant head as the MTP drafter, vision tower | | `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter | | `minicpm5-2b-bf16.yaml` | `minicpm5-2b-bf16.rad` | MiniCPM5-2B in bf16 with its DSpark drafter | +| `embeddinggemma2.yaml` | `embeddinggemma2-bf16.rad` | EmbeddingGemma 2 in bf16: text, image, video and audio embeddings on one card | The container names are the files the README's model table downloads or converts. Copy the directory to the serving host and fill in `.env` from `.env.example`. It sets the image, -the models directory (mounted read-only at `/models`), a writable state directory (`/data`, where -the prefix cache's disk tier lives), the API key, the port, and the user and GPU groups the server -runs as. The models directory has to be on a local filesystem that does direct I/O, such as ext4, +the models directory (mounted read-only at `/models`), the API key, the port, and the user and GPU +groups the server runs as. The models directory has to be on a local filesystem that does direct I/O, such as ext4, XFS or btrfs: Qwen3.8-Flash-Next reads its n-gram table from the container that way. On btrfs with compression on, the extents it stored compressed are read through the page cache instead, which works but loses what the direct reads are for; a container copied into a directory set `chattr +C` @@ -150,6 +152,5 @@ docker compose -f flashnext.yaml down # stop ``` Each model takes both cards and the same port, so run one at a time: `down` one before `up` on -another. The server runs as the host user given in `.env`, so the files it writes under `/data` -belong to that user. `/health`, `/ping` and the dashboard page answer without the API key, and the +another. The server runs as the host user given in `.env`. `/health`, `/ping` and the dashboard page answer without the API key, and the health check fetches `/health` with busybox's `wget`. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index faf6cccc..75cae766 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -335,6 +335,11 @@ rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-27b -o swift-27b-fp8.rad \ --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 --recipe data/recipes/q38-27b-fp8block-df2.recipe \ --set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \ --set "quantization_config.weight_block_size=128 128" --set quantization_config.activation_scheme=dynamic + +# gemma-4-26B-A4B-it with z-lab's DFlash drafter, the routed experts' gate_up as block fp8 (served by +# arch/gemma4; docs/ARCHITECTURES.md says why down stays bf16 unless the experts were padded to 768) +rad-convert ~/models/google/gemma-4-26B-A4B-it -o gemma4-26b-a4b-df.rad \ + --draft-model ~/models/z-lab/gemma-4-26B-A4B-it-DFlash --recipe data/recipes/gemma4-26b-a4b-df.recipe ``` A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read @@ -574,6 +579,7 @@ Related flags: --host-pool-mib 8192 # pinned host tier for weights --embedding-placement vram # keep the token embedding on the card (below) --ngram-placement ram # an n-gram table in RAM instead of read from disk (below) +--vision-tower-placement ram # the encoder towers in host memory, their VRAM to the KV cache (below) --weights-disk-tier # stream what fits neither from the container; needs O_DIRECT ``` @@ -605,6 +611,21 @@ container cannot write them. radiance --model m.rad --tp 2 --embedding-placement vram # the table on the cards ``` +**The encoder towers** -- a vision tower, and an audio encoder where a model has one -- are read +once an image, a clip or a recording, never on a text step. On the card (`vram`, the default) they +are weights like any other and the KV pool is carved from what is left: Qwen3.8-27B's vision tower +is 0.86 GiB a card, about 24,000 tokens of fp8 context. `--vision-tower-placement ram` pins them in +host memory of their own, every rank a whole tower, on top of `--host-pool-mib`, and their kernels +read the weights over the link in place: that VRAM goes to the KV cache, and every image costs one +read of the tower over the link (about 55 ms for 0.86 GiB on PCIe 4.0 x16). Text-only requests do +not touch it. A tower is every weight the model's architecture declares read once per request. +`ram` is refused, naming the reason, where the model has no tower, where `--mm-max-patches 0` +declared none, or where the host cannot pin it. + +```sh +radiance --model qwen3.8-27b-fp8.rad --tp 1 --vision-tower-placement ram +``` + **An n-gram table** (Qwen3.8-Flash-Next's is 47.7 GiB) is read a few rows a token, which is why it can live off the card at all. `disk` reads its rows from the container through a row cache and direct reads on the host; about half of a step's rows are first-seen, so steps wait on the drive. @@ -925,26 +946,25 @@ serve. A conversation that comes back before that resumes from VRAM; one that co restored from host memory and keeps its host copy, so its next turn copies only what that turn added. There is no idle threshold on the way out of VRAM. -With a disk tier the same happens one level down: every host copy is written on to disk in the -background and keeps its host slot, and once the write has landed the slot can be given up for -nothing. A full host tier gives up its oldest slots when a new copy or a restore needs one, so a -conversation that no longer fits in host memory is on disk already rather than lost. +A full host tier drops its least recently used conversations to make room. Nothing is written to a +drive: the prefix cache lives in VRAM and host memory only. + +**Every stored conversation expires.** One that no request has used for `--prefix-cache-ttl` +seconds (an hour by default) is taken out of whichever tier holds it — its VRAM blocks go back to +the pool, its host slot back to the arena, its snapshots back to the store. It is not moved +anywhere first. A conversation in use stays: a hit or a new turn counts as a use, and a system +prompt that several conversations share stays for as long as any of them is used. ```sh -radiance --model m.rad \ - --prefix-cache-host-mib 8192 \ - --prefix-cache-disk-mib 65536 --prefix-cache-dir /var/cache/radiance +radiance --model m.rad --prefix-cache-mib 8192 --prefix-cache-ttl 3600 ``` -- `--prefix-cache-host-mib N` — **this is the switch.** Without a size, nothing is copied. It holds +- `--prefix-cache-mib N` — **this is the switch.** Without a size, nothing is copied. It holds attention blocks only; a hybrid model's linear-state snapshots are in host memory already, in the `--checkpoint-slots` store. Size it for the conversations you expect to come back: one that does - not fit comes back from disk instead. -- `--prefix-cache-disk-mib N` — the disk tier's size. Everything that reaches host memory is - written here too, snapshots included, so a full snapshot store detaches its least recently used - snapshot instead of losing it. -- `--prefix-cache-dir DIR` — where the disk tier lives. **Not `--weights-disk-tier`**, which is about - *weights*. The disk tier holds conversation content unencrypted. + not fit is prefilled again. +- `--prefix-cache-ttl S` — seconds an unused conversation is kept (default 3600). `0` keeps + everything until the memory is wanted. - Recovering a 200K-token turn costs a copy over PCIe; recomputing it costs minutes. On a hybrid model the recurrent state matters as much as the attention blocks — restoring the @@ -1092,15 +1112,15 @@ one line naming each one the command line moved. | `--host-pool-mib N` | 0 | pinned host tier (weights) | | `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card. See §4.3 | | `--ngram-placement WHERE` | auto | `auto`, `vram`, `ram` or `disk`: an n-gram table on the card, as a copy in RAM made at load and read by the card, or read from the container. See §4.3 | +| `--vision-tower-placement WHERE` | vram | `vram` or `ram`: the encoder towers (vision, and audio where a model has one) on the card, or pinned in host memory beside `--host-pool-mib` and read in place once an image. 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 | **Idle session tiers** | flag | default | | |---|---|---| -| `--prefix-cache-host-mib N` | 0 (off) | copy finished conversations' KV to host memory | -| `--prefix-cache-disk-mib N` | 0 (off) | and copy them on to disk | -| `--prefix-cache-dir DIR` | — | where the disk tier keeps them | +| `--prefix-cache-mib N` | 0 (off) | copy finished conversations' KV to host memory | +| `--prefix-cache-ttl S` | 3600 | seconds an unused conversation is kept, in VRAM or host memory; `0` never expires | **Placement and state** @@ -1109,7 +1129,7 @@ one line naming each one the command line moved. | `--placement MODE` | auto | `all_vram`, `layer_offload`, `expert_tiered`, `auto` | | `--deterministic` | off | pin placement to the loader's plan, so the resident set cannot change under the heat engine | | `--checkpoint-interval N` | 2048 | linear-attention state checkpoint interval, in tokens | -| `--checkpoint-slots N` | 8 | linear-state (hybrid) or sliding-window snapshots the server may hold at once, **in total**, not per sequence. They live in pinned host memory, not VRAM: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`), allocated at startup. A snapshot is copied off the card after the step that produced it and back before the step that resumes from it. With a disk tier a full store detaches its least recently used snapshot to disk instead of losing it | +| `--checkpoint-slots N` | 8 | linear-state (hybrid) or sliding-window snapshots the server may hold at once, **in total**, not per sequence. They live in pinned host memory, not VRAM: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`), allocated at startup. A snapshot is copied off the card after the step that produced it and back before the step that resumes from it. A full store retires its least recently used snapshot | | `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` | | `--no-prefix-cache` | — | disable prefix caching | @@ -1617,7 +1637,8 @@ view, for one) reads it unchanged: "prompt_per_token_ms": 4.0, "prompt_per_second": 250.0, "predicted_n": 64, "predicted_ms": 711.0, "predicted_per_token_ms": 11.29, "predicted_per_second": 88.6, - "draft_n": 78, "draft_n_accepted": 37 + "draft_n": 78, "draft_n_accepted": 37, + "ttft_ms": 297.5, "total_ms": 1008.5 } ``` @@ -1631,6 +1652,8 @@ view, for one) reads it unchanged: | `predicted_ms` | from the first generated token to the last | | `predicted_per_second`, `predicted_per_token_ms` | the `predicted_n − 1` tokens after the first, over `predicted_ms`. The first token is the prefill's product. It is the same figure as `/metrics`' time per output token, and with speculative decoding it counts every token a step accepts | | `draft_n`, `draft_n_accepted` | speculative tokens proposed for this request and how many were accepted. Present when any were proposed, as llama.cpp does | +| `ttft_ms` | the server's time to first token: from the moment it had the whole request body to the first generated token. It holds parsing the request, rendering the chat template, tokenising, the wait for admission and the prefill. The time the body took to reach the server is not in it, so a client on a slow link can tell the server's share of the time it measured from the network's. Not a llama.cpp field | +| `total_ms` | from the same moment to the last generated token: `ttft_ms + predicted_ms`. Not a llama.cpp field | Milliseconds are wall-clock milliseconds, and the rates are tokens per second. A rate whose count or time is zero is `null`. A request with several choices (`n`, or a batch of prompts) sums the @@ -1825,6 +1848,7 @@ lists the efforts the chat template takes, or is `null` when it takes any. `serv | `attn_cached_tokens_total`, `linear_cached_tokens_total` | prefix reuse, both halves | | `linear_checkpoints_written_total`, `linear_prefix_cache_hit_rate` | | | `prefix_cache_evictions_total`, `prefix_cache_ckpt_evictions_total` | | +| `prefix_cache_expired_total`, `prefix_cache_ckpt_expired_total` | what `--prefix-cache-ttl` took (§4.8) | | `num_requests_preempted` | | | `http_queue_depth`, `http_responses_total`, `http_admission_rejected_total` | | | `client_disconnect_total`, `stream_overflow_total` | | @@ -1892,8 +1916,6 @@ TLS-terminating reverse proxy in front: radiance --model m.rad --host 127.0.0.1 --port 8000 --api-key "$KEY" ``` -Also note `--prefix-cache-disk-mib` writes **conversation content unencrypted** under `--prefix-cache-dir`. - ### 6.7 Restarting and stopping Nothing here is a daemon; run it under systemd, a supervisor or `nohup`. `scripts/fnstop.sh` stops @@ -1935,7 +1957,7 @@ of a log to paste into an issue. fix. Every warning is also printed as a `W` line of its own. ``` -I STARTUP REPORT -- radiance 1.4.0 +I STARTUP REPORT -- radiance 1.5.0 I CONFIGURATION -- every option, the value in force, and where it came from I --model /models/flashnext.rad [command line] I --tp 2 [command line] @@ -1976,9 +1998,9 @@ curl -s -H "Authorization: Bearer $KEY" localhost:8000/diagnostics | jq '.findin | `does not read '' encoded ` at startup | No loaded kernel takes that weight's encoding for the op that reads it | Convert with a recipe that writes an encoding a loaded kernel reads, or load the library that reads it | | Prefix hit rate 0% and every turn re-prefills | The KV pool cannot hold the live sessions, so the cache evicts what the next turn wanted | The cache already has everything the experts can do without: a larger `--host-pool-mib` (RAM permitting), `--kv-cache-dtype fp8`, or fewer/shorter sessions. See §4.3 | | The server dies with no log line, on a request it had been serving fine | A kernel whose code object had never been loaded could not be: the card has no room left. HIP faults inside the launch rather than returning an error, so there is nothing to print | A card left with too little room for a first launch — see §4.3. Set `--gpu-headroom-mib` to the value the startup warning names. `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault | -| KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-host-mib N` | +| KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-mib N` | | `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for | -| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps pinned memory system-wide at `ttm.pages_limit`, half of RAM by default | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under the cap the refusal names, or raise it with the kernel parameter `ttm.pages_limit` | +| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps what every process together pins at RAM less 1/64 and 1.5 GiB. The pool is locked user memory, which `ttm.pages_limit` does not count | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under both the cap and the available RAM the refusal names. `amdgpu.no_system_mem_limit=1` lifts the driver's cap, but not the RAM | | `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, which moves every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line | | `a synchronisation has waited 5 s` naming a kernel, then `no queue has advanced`, then `HW Exception … GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue. The kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps is moved under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits for a queue a serve never lets drain. A voltage offset or other clock instability is the other cause seen on R9700s. If the stall line says the queues **advanced**, the wait was long rather than stuck, and nothing is wrong | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the startup report warns when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset puts the power cap, fan curve and voltage offset back to firmware defaults, so re-apply them before every start rather than once at boot. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`; a reboot loses it. `docker inspect` shows exit code 0 for a container Docker has already restarted, which says nothing about how the old process ended | | `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time | diff --git a/docs/OPS.md b/docs/OPS.md index ba0589db..b04690f1 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -298,6 +298,60 @@ rounding. -log(max_timescale) / max(n/2 - 1, 1))`, each step in f32 as the reference's torch expressions are, then rounded. +### Gemma 4's fusions: the sandwich-norm joins, `expert_scale`, `attn_paged_qrow` — no reference row + +| op | params | operands | +|---|---|---| +| `norm_add_norm` | `M`(range) `n` `eps`:f64 `dtype` | `a`, `w_a`w, `x`:inout, `w_y`w → `y` | +| `norm_add_norm_route` | `M`(range) `n` `eps`:f64 `dtype` `mult`:f64 `group` | `a`, `w_a`w, `x`:inout, `w_y`w → `y`; `w_r`w → `r`; `w_e`w → `q`, `qs` | +| `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w, `w_n`w? → `y`? | +| `expert_scale` | `M`(range) `n_expert` `top_k` `dtype` | `ids`, `w_e`w, `ew`:inout | +| `attn_paged_qrow` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` | + +Gemma's sandwich norms, each one kernel in place of a chain of `rmsnorm`, `add` and `mul_weight`. +`norm_add_norm` is `t = rmsnorm(a) * w_a; x += t; y = rmsnorm(x) * w_y` -- a post-norm, the +residual add, the next pre-norm. `join_add_scale` is `x = (x + rmsnorm(rmsnorm(d) * w_d + +rmsnorm(r) * w_r) * w_j) * s` -- two arms' post-norms, their sum, its norm, the residual add and a +one-element layer scalar (Gemma 4's MoE feed-forward) -- and, given `w_n` and `y` (both or +neither), `y = rmsnorm(x) * w_n` over the `x` it writes: the next layer's input norm, or the final +norm after the last layer, which would otherwise be a launch of its own reading that `x` back. +Every value the chain stores is rounded to the activation dtype at the same point, so the two +differ from the chain only in the order a sum of squares is added in: with the same order they are +bit-identical to it, and against a chain summed in another block width a norm factor can differ in +its last bit. + +`norm_add_norm_route` is `norm_add_norm` and, from the same norm of the `x` it writes, a MoE +layer's two routed inputs: `r = rmsnorm(x) * w_r * mult` -- `rmsnorm`'s expression with `mult` -- +and `q`, `qs` = `rmsnorm_quant_fp8` of `x` under `w_e`: E4M3 codes of the bf16-rounded norm, an +f32 scale per (row, `group` columns) of `amax / 448` (1 for an all-zero group), the value over it +clamped to +-448. `n` is whole groups and `group` 128. In Gemma 4 it replaces the router's +`rmsnorm` and the experts' `rmsnorm_quant_fp8`, two launches a layer that read back the `x` the +join had just written. + +`expert_scale` is `ew[t, k] = ew[t, k] * w_e[ids[t, k]]` over `[M, top_k]`, `w_e` an `[n_expert]` +table and an id outside it reading 0: Gemma 4's per_expert_scale on the renormalised routing +weights, in place of an `embed_lookup` of the table by the ids and a `mul` into the weights. One +product rounded once, so the pair's value bit for bit. + +`attn_paged_qrow` is `attn_paged` -- the same parameters, operands and values -- with `q` read at +its own row pitch: a column slice of a wider row, the q part of a fused `[q|k|v]` projection, read +where it lies instead of lifted into a dense block by a `cast` first. It is a name of its own +because an `attn_paged` kernel may refuse a pitched `q` (libr4d's other attention kernels do, with +`RAD_E_STRIDE`, at the first step), and under `attn_paged` whichever library is first in `--kernels` wins the op: an +architecture handing it the slice would depend on an order it cannot see. Asked for by name, the op +resolves to a library that reads the pitch or to nothing, and the architecture lifts `q` for +`attn_paged` where it is nothing. + +**libref has no row for any of them, on purpose.** An architecture asks for a join and declares the +chain where it does not resolve (`rad_op_resolved`), and a reference row would resolve it +everywhere -- so a model loaded without the library that serves the join would resolve it to the +reference and be refused at serve, instead of running the chain on libr4d or libavx. libr4d +declares them, with device rows only, so the host backend runs the chains too. With no oracle, its +kernels are held to a chain summed in their own block order, bit for bit, by `tests/r4d_emu`. No row +declares `replaces`: rad-kbench's fusion oracle runs the replaced chain out of the fusing library's +own rows and compares bytes, and libr4d's `rmsnorm` adds its sums of squares in another block +order, which can move a norm factor's last bit. + ## Quantisation and rotation | op | params | operands | @@ -652,6 +706,7 @@ and adding 0.0f is exact, so a block sum over 8 wave partials and over 32 are th | `moe_gather` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`? → `y` | | `row_topk` | `M`(range) `N` `R` `vocab_off`/opt `dtype` | `x` → `idx`, `val`, `pairs`? | | `row_topk_merge` | `M` `R` `world_size` `dtype` | `gathered` → `idx`, `val` | +| `pair_argmax` | `M`(range) `n` `dtype` | `pairs` → `idx`, `val`? | | `logit_rerank` | `M`(range) `R` `n_vocab` `n_embd` `vocab_off`/opt `dtype` | `x`, `head`w, `idx_in` → `idx`, `val`, `pairs`? | `row_topk` and `row_topk_merge` are a pair, and the second only means anything with the first's @@ -667,6 +722,14 @@ over the unsharded plane element for element. A slot a shard could not fill carr `pairs` and is dropped -- a sentinel rather than a -inf value, because a masked logit takes that value legitimately. +`pair_argmax` is the merge at R = 1, for a vocab-sharded draft head that wants each position's +winner as a proposal: `idx` gets the id of the largest value among a row's `n` gathered pairs, +ties to the lower id, a negative id skipped, -1 (and -inf in `val`) when nothing is valid -- +written one element a row at the output's own pitch, which is what a block drafter's contiguous +proposal needs. It is not `row_topk_merge` with R = 1 because a rank still sends R >= 2 pairs: a +row-interleaved `all_gather` moves whole 16-byte words and one pair is 8 bytes, so `n` is +`world_size * R` and the op takes the top-1 of all of them. + `logit_rerank` is the second half of a COARSE top-R. A speculative step can afford a cheap draft head -- the target verifies every proposal, so a worse draft costs acceptance and never a token -- but a head quantised hard enough to be cheap also picks a different top-1 often enough to matter. diff --git a/docs/TOOLS.md b/docs/TOOLS.md index 67394691..7f1478e9 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -547,7 +547,7 @@ need nothing but `curl` and `jq`. Scripts resolve each other by `$(dirname "$0") it is on. `oracle.sh` starts its own server and stops whatever listens on its port (`P`, default 8302). Everything else — `cstep2.sh`, `ident.sh`, `tierident.sh`, `tiercross.sh`, `mctools.sh`, `mcstream.sh`, `hfget.sh`, `convfn.sh`, `convdspark.sh`, `fnpf.sh`, `fnconc.sh`, `fndrop.sh`, -`apikeys.sh`, `diskstall.py`, `cardclock.py` — leaves a live serve alone. +`apikeys.sh`, `cardclock.py` — leaves a live serve alone. `fndrop.sh` is the one to read the description of first: it leaves the PROCESS alone and deliberately disconnects clients from it, which is not the same promise. @@ -583,7 +583,6 @@ deployment. `P` selects the port. | `apikeys.sh` | whether the server does what oai.cpp says about request keys: every rejected one refused by name, every inert one accepted, every accepted one honoured | `P` | | `cstep2.sh` | steady-state decode ms/step at concurrency | `P` `LEVELS` `MT` `WIN` | | `ident.sh` | run-to-run reproducibility at a fixed configuration: one hash per (temperature, question) | `P` | -| `diskstall.py` | what restoring a conversation from the disk tier costs: the returning request's time to first token, and the longest stall it puts on a stream decoding beside it | `--port` `--session` `--fill` | | `cardclock.py` | what holds each card's clock under a sustained load (power limit, temperature or current limit, or the top of the voltage/frequency curve) and which card the tensor-parallel step waits for, with the engine's step counters per window beside it. Drives its own greedy load; `--watch` only samples while real traffic drives the server. Never writes to a card | `--port` `--conc` `--gen` `--seconds` `--window` `--seed` `--watch` `--json` `--compare` | `fndrop.sh` exists because a disconnect reaps a request at an arbitrary point in the step loop, and @@ -639,7 +638,7 @@ model's output. | | | |---|---| -| `tierident.sh` | does a session that left VRAM come back byte for byte, both halves? `P` `H` `N` `TO_HOST` `TO_DISK` `FILL` | +| `tierident.sh` | does a session that left VRAM come back byte for byte, both halves, after a full host tier, and (with `TTL`) after it expired? `P` `H` `N` `TO_HOST` `FILL` `TTL` | | `tiercross.sh` | the same with **two** sessions in flight — the only way to see one being served the other's context | | `mctools.sh` | the tool-call shapes hardest to parse — an array argument, two calls in one reply, prose before a call, plain chat with tools available. Asserts `finish_reason` and that no ` build_cases() { add("row_topk", { HI("M", 5), HI("N", 97), HI("R", 4), HI("vocab_off", 0), HS("dtype", dt) }); add("row_topk_merge", { HI("M", 5), HI("R", 4), HI("world_size", 2), HS("dtype", dt) }); + add("pair_argmax", { HI("M", 5), HI("n", 8), HS("dtype", dt) }); /* "sorted" and not "slot": libref refuses any other spelling with RAD_E_UNSUPPORTED, and a case at a spelling both plugins decline is a case that proves nothing. */ for (const char* order : { "token", "sorted" }) { diff --git a/libavx/avx_elementwise.cpp b/libavx/avx_elementwise.cpp index a5ef8b97..2d2540c5 100644 --- a/libavx/avx_elementwise.cpp +++ b/libavx/avx_elementwise.cpp @@ -692,7 +692,7 @@ AVX_KERNEL(logit_softcap) { AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN) for (int64_t i = 0; i < nel; ++i) { const float v = ldt(x, offlin(x, i)); - stt(y, offlin(y, i), cap * std::tanhf(v / cap)); + stt(y, offlin(y, i), cap * std::tanh(v / cap)); } return RAD_OK; } @@ -713,7 +713,7 @@ AVX_KERNEL(logit_softcap) { for (; i + VF_N <= m; i += VF_N) vf_storeu(so + i, vf_fma(c2, vf_sigmoid(vf_mul(vf_loadu(v + i), z)), c1)); for (; i < m; ++i) - so[i] = cap * std::tanhf(v[i] / cap); + so[i] = cap * std::tanh(v[i] / cap); out_row(y, off, m, so); } return RAD_OK; diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index b653936c..8fceca98 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -107,7 +107,7 @@ int avx_isa_force(int level); /* ---- mixture of experts */ \ X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \ X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \ - X(moe_gemm_q_mod4) \ + X(moe_gemm_q_mod4) X(pair_argmax) \ /* ---- gated delta net */ \ X(gdn_conv_prep) X(gdn_conv_update) X(gdn_kkt_solve) X(gdn_chunk_scan) \ X(gdn_recurrent_update) X(gdn_conv_recurrent_update) X(gdn_gated_rmsnorm) \ diff --git a/libavx/avx_moe.cpp b/libavx/avx_moe.cpp index aad45cbc..bbbe0c38 100644 --- a/libavx/avx_moe.cpp +++ b/libavx/avx_moe.cpp @@ -740,3 +740,37 @@ AVX_KERNEL(row_topk_merge) { } return RAD_OK; } + +/* ------------------------------------------------------------------ pair_argmax */ +/* row_topk_merge at R = 1, one id a row at the output's own pitch: the vocab-sharded draft head's + * proposal. Same pads, same tie rule, -1 and -inf for a row with nothing valid; `val` optional. + * + * LEFT SCALAR for the merge's reason, more so: `n` is world_size * R -- sixteen pairs at TP8 and + * R 2 -- and the whole op is one pass over them a row. */ +AVX_KERNEL(pair_argmax) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *p = &a->t[0], *idx = &a->t[1]; + const RadTensor* val = rad_arg_in(a, 2); + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + if (p->dtype != RAD_F32) return RAD_E_DTYPE; /* the id is carried by bit pattern */ + const int64_t M = numel(p) / (n * 2); + if (M <= 0 || numel(idx) < M || (val && numel(val) < M)) return RAD_E_SHAPE; + const float* const pf = (const float*)p->data; + + AVX_PARALLEL_FOR_IF(M * n >= 4096) + for (int64_t m = 0; m < M; ++m) { + int32_t bid = -1; + float bv = -INFINITY; + for (int64_t j = 0; j < n; ++j) { + int32_t id; + std::memcpy(&id, pf + offlin(p, (m * n + j) * 2), sizeof id); + if (id < 0) continue; /* a pad, not a candidate */ + const float v = pf[offlin(p, (m * n + j) * 2 + 1)]; + if (bid < 0 || v > bv || (v == bv && id < bid)) { bid = id; bv = v; } + } + st_int_dt(idx->dtype, idx->data, offlin(idx, m), bid); + if (val) stt(val, offlin(val, m), bv); + } + return RAD_OK; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 49fcff0c..ded0eba6 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -365,6 +365,8 @@ static const RadOperandSpec oRowTopk[] = { OPD("x"), OUT("idx"), OUT("val"), OUT static const RadParamSpec pRowTopkMerge[] = { P_INT("M"), P_INT("R"), P_INT("world_size"), P_STR("dtype") }; static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT("val") }; +static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oPairArgmax[] = { OPD("pairs"), OUT("idx"), OUT_O("val") }; /* Mirrors libref's row exactly: R candidates rescored against the full-precision head, ties to the * lower id, pads sort last. libref's shape hook declines to describe this op, so the checker skips @@ -638,6 +640,8 @@ static const RadOpSchema kSchemas[] = { { "row_topk", ARR(pRowTopk), ARR(oRowTopk), "exact per-row top-R." }, { "row_topk_merge", ARR(pRowTopkMerge), ARR(oRowTopkMerge), "the global top-R of the gathered per-rank candidate sets." }, +{ "pair_argmax", ARR(pPairArgmax), ARR(oPairArgmax), + "the global top-1 of a row of gathered (id, value) pairs, one id a row." }, { "logit_rerank", ARR(pLogitRerank), ARR(oLogitRerank), "R candidates a row rescored exactly against the full-precision head." }, { "gdn_conv_prep", ARR(pConvPrep), ARR(oConvPrep), @@ -872,6 +876,9 @@ SIMPLE("avx_moe_gather", "moe_gather", "moe", "weighted scatter back to token or SIMPLE("avx_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, L(row_topk)), SIMPLE("avx_row_topk_merge", "row_topk_merge", "moe", "the global top-R of the gathered per-rank candidate sets", DT_FLOAT, L(row_topk_merge)), +SIMPLE("avx_pair_argmax", "pair_argmax", "moe", + "the global top-1 of a row of gathered (id, value) pairs, one id a row", DT_FLOAT, + L(pair_argmax)), SIMPLE("avx_logit_rerank", "logit_rerank", "moe", "R candidates a row rescored exactly against the full-precision head", DT_FLOAT, L(logit_rerank)), diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 2fb9865c..a36599d7 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -57,13 +57,9 @@ set(RAD_W4_GROUP 128 CACHE STRING "libr4d quantised-weight group size (must matc set(R4D_UNITS "r4d_attn_paged_h256_gqa6|" "r4d_attn_paged_h128_gqa4|" - # Gemma 4 dense sliding window: head_dim 256, 2 queries per KV head, windowed decode only - # (prefill falls to the caller's libref path). The windowed twin of the drafter leg above. + # Gemma 4 dense sliding window: head_dim 256, 2 queries per KV head, windowed decode and + # prefill. The windowed twin of the drafter leg above. "r4d_attn_paged_h256_gqa2|" - # Gemma 4 dense global layers: head_dim 512, 8 queries per KV head, full attention (window 0). - # The head_dim the library had not compiled before -- the prefill KV tile drops to 16 to fit 64 - # KiB of LDS, and the decode combine takes the head-generic merge (DPL 16 breaks the vector form). - "r4d_attn_paged_h512_gqa8|" # Eight queries per KV head, at both head widths: the routed 35B-A3B is 16 over 2 at 256 # and MiniCPM5-2B is 16 over 2 at 128. Same device code, different instantiations. "r4d_attn_paged_gqa8|" @@ -76,6 +72,10 @@ set(R4D_UNITS # Six, head_dim 256 and the same 4-token page: the same QSA layers at four ranks, where each KV # head is replicated across a rank pair. Again four lines that set the ratio and include the body. "r4d_attn_paged_h256_gqa6_bs4|" + # head_dim 256 and 512 at 1, 2, 4 or 8 queries per KV head with ANY window: Gemma 4's sliding + # (h256/gqa2, window 1024) and full (h512, gqa 8 at TP1/TP2) layers. One kernel a geometry for + # every q_len, reading q at any row pitch, which is what attn_paged_qrow is. + "r4d_attn_paged_window|" "r4d_attn_vit_h72_bf16|" # An encoder's dense attention (bidirectional, GQA in the workgroup, a two-sided window) and # the small ops around it: act_mul, seg_mean, qk_norm_rope with a v norm, the f32 widening. @@ -156,6 +156,12 @@ set(R4D_UNITS "r4d_gdn_gated_norm_had_quant_i8|" "r4d_dequant_w4_bf16|" "r4d_rowtopk_bf16|" + # The vocab-sharded draft head's cross-rank top-1, one id a row. + "r4d_pair_argmax_f32|" + # Gemma 4's two sandwich-norm joins (norm_add_norm, norm_add_norm_route, join_add_scale) and + # expert_scale: each one kernel for a chain of small ones. + "r4d_norm_join_bf16|" + "r4d_expert_scale_bf16|" "r4d_dflash_conv_t2_g16_bf16|" "r4d_dflash_select_bf16|" # The routed mixture of experts: router, scatter, the grouped block-scaled fp8 GEMM and diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 1ec00bf4..292c4984 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -111,21 +111,12 @@ long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a); // The Gemma 4 dense sliding-window geometry: head_dim 256, 2 queries per KV head, sliding window. // Both bands: the decode band (q_len*gqa <= 64, i.e. q_len <= 32) and the windowed prefill band // (a prefill-length query, WIN on). The prefill leg is the same r4d_attn_prefill_kernel the - // h256/gqa6 and h512/gqa8 dispatches instantiate, with the window bit turned on. + // h256/gqa6 dispatch instantiates, with the window bit turned on. int r4d_attn_prefill_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream); long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a); -// The Gemma 4 dense global geometry: head_dim 512, 8 queries per KV head, full attention (window 0). -// The one head_dim the library had not compiled -- a stand-alone instantiation, not the gqa8 -// parameterised body (whose prefill tile of 48 does not fit 512-channel tiles in LDS). Both legs -// spill ~384 VGPRs at this head; a 3b tuning question, not a 3a one. -int r4d_attn_prefill_h512_gqa8_fp8kv (const R4DArgs* a, hipStream_t stream); -int r4d_attn_prefill_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t stream); -int r4d_attn_decode_h512_gqa8_fp8kv (const R4DArgs* a, hipStream_t stream); -int r4d_attn_decode_h512_gqa8_bf16kv (const R4DArgs* a, hipStream_t stream); -long r4d_attn_decode_h512_gqa8_scratch_bytes(const R4DArgs* a); // The geometry the attention kernels above are compiled for, so a caller can test a model against // it instead of discovering the mismatch at the first launch. void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows); @@ -422,8 +413,12 @@ void r4d_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers); // Shards are as even as the word count allows (the first n16 % ws take one more word), so a // message need not divide by the rank count -- at three it almost never does. Regions A and B sit // at 0 and the longest shard, so the slot stride must hold twice that. Above this bound the caller -// falls back: -enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 20971520 }; // a 4096-token hidden-5120 prefill chunk +// falls back to the one-shot. The bound guards the kernel's int word offsets (the message, the +// slot stride) and nothing else: 2^28 elements is 2^26 words at fp32. It was 20971520 -- a +// 4096-token chunk of a 5120-wide residual -- which handed every larger prefill chunk back to the +// one-shot and its (ws-1)*N send: an 8192-token chunk at Gemma 4's 2816 is 23M elements at the +// attention's reduce and 46M at the feed-forward's, which carries both branches. +enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 268435456 }; void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 755c8336..b4a825cd 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -38,7 +38,7 @@ #include #include -static_assert(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS == 20971520, +static_assert(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS == 268435456, "r4d_rows.cpp restates this bound; libr4d changed it"); static_assert(R4D_MAX_RANKS == 8, "the 8-rank entry point names exactly seven peers"); diff --git a/libr4d/r4d_attn_paged_h256_gqa2.hip b/libr4d/r4d_attn_paged_h256_gqa2.hip index d06574a7..fdb80a90 100644 --- a/libr4d/r4d_attn_paged_h256_gqa2.hip +++ b/libr4d/r4d_attn_paged_h256_gqa2.hip @@ -8,8 +8,8 @@ // Both bands, now. The decode band (q_len * gqa <= 64, i.e. q_len <= 32 at gqa 2) is the // windowed decode kernel above. The prefill band (a query long enough to want the query-tiled // prefill kernel) is the windowed prefill kernel below -- the same r4d_attn_prefill_kernel the -// h256/gqa6 and h512/gqa8 dispatches instantiate, with the window bit (template arg WIN) turned on, -// the way the decode leg does. A trunk layer prefills, so it needs the prefill band on the device: +// h256/gqa6 dispatch instantiates, with the window bit (template arg WIN) turned on, the way the +// decode leg does. A trunk layer prefills, so it needs the prefill band on the device: // libref is an opt-in fallback the engine refuses by default (spec §17). The drafter leg is // decode-only because a drafter never prefills. #include "r4d.h" @@ -128,8 +128,8 @@ extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) // ---- prefill --------------------------------------------------------------------------------- // The h256/gqa6 prefill option set (P_OPT 3955211) is reused unchanged: at head_dim 256 the wide K -// fetch (O_KWIDE) is valid -- it is written for 16 channels = head_dim 256 exactly -- so unlike the -// h512 leg (which turns it off because 512 reads past the tile) this one keeps it. gqa 2 makes +// fetch (O_KWIDE) is valid -- it is written for 16 channels = head_dim 256 exactly, and a wider head +// would read past the tile -- so this leg keeps it. gqa 2 makes // BLOCK_Q (NWARPS*16/2 = 192) larger than gqa 6's 64, so a workgroup covers more query positions: // fewer grid.x blocks, the same KV tile. WIN is on (the last template arg); window <= 0 folds it // away to the full-attention form, so a windowless launch is safe. @@ -157,8 +157,8 @@ extern "C" int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s return prefill_launch_h256_gqa2<1>(a, s); } -/* The prefill RadArgs wrappers, defined here (not in the h256 dispatch) for the same reason the - * h512 leg's live in theirs: an entry point appended to a textual inclusion compiles into nothing. +/* The prefill RadArgs wrappers, defined here (not in the h256 dispatch): an entry point appended to + * a textual inclusion compiles into nothing. * Absent descales mean 1.0 (fill_paged leaves them null and the kernel reads 1.0). */ extern "C" int r4d_rad_attn_prefill_h256_gqa2_fp8(const RadArgs* a, RadStream s) { R4DArgs r; diff --git a/libr4d/r4d_attn_paged_h512_gqa8.hip b/libr4d/r4d_attn_paged_h512_gqa8.hip deleted file mode 100644 index a92e0f61..00000000 --- a/libr4d/r4d_attn_paged_h512_gqa8.hip +++ /dev/null @@ -1,212 +0,0 @@ -// R4D attention dispatch for the Gemma 4 dense model's GLOBAL layers: head_dim 512, 8 queries per -// KV head, full attention (window 0), paged block 16. This is the one head_dim the library has not -// compiled before -- no h512 kernel existed -- so this file is a real new instantiation, not a -// rename. It is the same device code as the h256/gqa6 and gqa8 dispatches (the kernels are -// templates on head_dim and gqa), with the two changes head_dim 512 forces: -// -// PREFILL -- TILE 16, not 48. The 16-bit K+V tiles are sK[TILE*(512+8)] + sV16[512*(TILE+8)]; -// at TILE 48 that is 107264 B, past the 64 KiB of LDS the part has, and only TILE 16 clears it -// (41216 B). The prefill warps tile the QUERY dimension (BLOCK_Q = NWARPS*16/gqa) and loop the -// KV in TILE chunks, so shrinking the KV tile costs loop iterations, not a different tiling. -// `O_KWIDE` is off -- its thread-to-(key,channel) map is written for 16 channels, head_dim 256 -// exactly, and at 512 it would read past the tile; the h128 prefill runs the same set minus it, -// so the non-wide path is already a shipped, correct one. -// -// DECODE -- the split-KV combine is the HEAD-GENERIC plain form (one thread per channel, a block -// of head_dim threads), not the vectorised form: that one pins a lane's width to eight or four -// dwords, and head_dim 512 would give it sixteen and refuse to compile. The plain form is slower -// but merges off the decode critical path; the trade is a 3b question. -// -// Register pressure at head_dim 512 is the one thing this file does not fix -- a thread carries -// head_dim/16 query fragments plus head_dim/8 accumulator floats, ~384 VGPRs, which the part tops -// out at, so both legs spill. That is correct and a tuning (3b) question, not a 3a one. -#include "r4d.h" -#include "r4d_attn_args.h" -#include "r4d_common.h" -#include -#include -using std::max; -#include "r4d_attn_prefill_h256_gqa6.hip" -#include "r4d_attn_decode_h256_gqa6.hip" - -#define CHK5() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0) - -#define H5_HEAD_DIM 512 -#define H5_GQA 8 -#define H5_BLOCK_SIZE 16 -#define H5_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold: q_len <= 8 -// The h256 prefill option set (3955211) minus O_KWIDE -- the only head-512 option change; the h128 -// prefill ships this exact number. -#define H5_P_NWARPS 24 -#define H5_P_TILE 16 // the KV tile that fits 64 KiB LDS at head_dim 512 (see above) -#define H5_P_OPT 3430923 -#define H5_D_TILE 16 -#define H5_D_OPT 3429947 // the shared decode opt set; bit 32 (f16 partials) is set -#define H5_D_JPB 2 -#define H5_D_VECMIN 256 - -// ---- prefill ----------------------------------------------------------------------------------- -template -static int h5_prefill_launch(const R4DArgs* a, hipStream_t s) { - if (a->head_dim != H5_HEAD_DIM || a->block_size != H5_BLOCK_SIZE) return -1; - if (a->q_heads / a->kv_heads != H5_GQA) return -2; - constexpr int BQ = (H5_P_NWARPS * 16) / H5_GQA; - dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs); - hipLaunchKernelGGL((r4d_attn_prefill_kernel), - grid, dim3(H5_P_NWARPS * 32), 0, s, *a); - CHK5(); - return 0; -} - -extern "C" int r4d_attn_prefill_h512_gqa8_fp8kv(const R4DArgs* a, hipStream_t s) { - return h5_prefill_launch<0>(a, s); -} -extern "C" int r4d_attn_prefill_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t s) { - return h5_prefill_launch<1>(a, s); -} - -// ---- decode ------------------------------------------------------------------------------------ -// The h256 full-attention split law: as many workgroups as fit under 128, at least two tiles a -// segment. It reads kv_heads, num_seqs and max_ctx and nothing about gqa or head_dim, so there is -// nothing to re-derive for this geometry; a window does not exist at full attention. -static int h5_decode_splits(const R4DArgs* a) { - if (a->splits > 0) return a->splits; - const int tiles = (a->max_ctx + H5_D_TILE - 1) / H5_D_TILE; - const int units = max(1, a->kv_heads * a->num_seqs); - int s = 128 / units; - const int cap = tiles / 2; - if (s > cap) s = cap; - if (s > tiles) s = tiles; - if (s < 1) s = 1; - return s; -} - -extern "C" long r4d_attn_decode_h512_gqa8_scratch_bytes(const R4DArgs* a) { - const int splits = h5_decode_splits(a); - const long rows = (long)r4d_q_total(*a) * a->q_heads; - return (H5_D_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8) - : rows * splits * (long)(a->head_dim + 2) * 4L; -} - -template -static int h5_decode_launch(const R4DArgs* a, hipStream_t s) { - if (a->head_dim != H5_HEAD_DIM || a->block_size != H5_BLOCK_SIZE) return -1; - if (a->q_heads / a->kv_heads != H5_GQA) return -2; - const int rows = a->q_len * H5_GQA; - if (rows > H5_MAX_DECODE_ROWS) return -4; - const int nw = (rows + 15) / 16; - const int splits = h5_decode_splits(a); - -#define H5_LAUNCH(NW) \ - hipLaunchKernelGGL((r4d_attn_decode_kernel), \ - dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits) - if (nw == 1) H5_LAUNCH(1); - else if (nw == 2) H5_LAUNCH(2); - else if (nw == 3) H5_LAUNCH(3); - else H5_LAUNCH(4); -#undef H5_LAUNCH - CHK5(); - - // The head-generic plain combine, always: a single thread per channel, one block of head_dim - // threads, no DPL to trip on at 512. H5_D_OPT carries bit 32 (f16 partials), so it reads them - // as such; the f32 half is spelled for the same guard the other dispatches use, not expected. - const int jobs3 = r4d_q_total(*a) * a->q_heads; - if (H5_D_OPT & 32) - hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), - dim3(H5_HEAD_DIM), splits * sizeof(float), s, *a, splits, H5_D_TILE); - else - hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), - dim3(H5_HEAD_DIM), splits * sizeof(float), s, *a, splits, H5_D_TILE); - CHK5(); - return 0; -} - -extern "C" int r4d_attn_decode_h512_gqa8_fp8kv(const R4DArgs* a, hipStream_t s) { - return h5_decode_launch<0>(a, s); -} -extern "C" int r4d_attn_decode_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t s) { - return h5_decode_launch<1>(a, s); -} - -// ============================================================== the plugin ABI entry points -// Defined here, in this translation unit, for the same reason the h128 drafter's live in theirs: -// the prefill and decode headers are textual inclusions, and an entry point appended to either -// compiles into nothing, leaving the .so with an undefined symbol only r4d_selftest would catch. - -extern "C" int r4d_rad_attn_prefill_h512_gqa8_fp8(const RadArgs* a, RadStream s) { - R4DArgs r; - int rc = fill_paged(a, &r, 512); - if (rc != RAD_OK) return rc; - /* Absent descales mean 1.0; see the prefill twins in the h256 dispatch. */ - return r4d_attn_prefill_h512_gqa8_fp8kv(&r, (hipStream_t)s); -} -extern "C" int r4d_rad_attn_prefill_h512_gqa8_bf16(const RadArgs* a, RadStream s) { - R4DArgs r; - int rc = fill_paged(a, &r, 512); - if (rc != RAD_OK) return rc; - return r4d_attn_prefill_h512_gqa8_bf16kv(&r, (hipStream_t)s); -} - -/* The split-KV partial buffer, sized at declare from the batch's worst step, the way the other - * decode geometries do it. The h256 split law makes splits * num_seqs flat, but its clamp to - * `>= 2 tiles a segment` breaks that at large batches, so the sweep over every count to the bound - * is still the right size even at full attention. */ -extern "C" int64_t r4d_rad_attn_decode_h512_gqa8_scratch(const RadArgs* a) { - const int sp = split_of(a); - if (sp < 0) return R4D_NO(RAD_E_INVAL); - - R4DArgs r; - const long long n_head = r4d_geti_or(a, "n_head", 0); - const long long max_seqs = r4d_geti_or(a, "max_seqs", 0); - if (n_head > 0 && max_seqs > 0) { - std::memset(&r, 0, sizeof(r)); - r.head_dim = H5_HEAD_DIM; - r.q_heads = (int)n_head; - r.kv_heads = (int)(n_head / H5_GQA); - r.num_seqs = (int)max_seqs; - r.q_len = (int)r4d_geti_or(a, "q_len", 1); - r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0); - r.block_size = (int)r4d_geti_or(a, "block_size", 16); - r.splits = sp; - if (r.max_ctx <= 0) return R4D_NO(RAD_E_INVAL); - int64_t worst = 0; - for (long long n = 1; n <= max_seqs; ++n) { - r.num_seqs = (int)n; - const int64_t need = r4d_attn_decode_h512_gqa8_scratch_bytes(&r); - if (need > worst) worst = need; - } - return worst; - } - - int rc = fill_paged(a, &r, H5_HEAD_DIM); - if (rc != RAD_OK) return rc; - r.splits = sp; - return r4d_attn_decode_h512_gqa8_scratch_bytes(&r); -} - -static int h5_decode_common(const RadArgs* a, R4DArgs* r, int which) { - const int sp = split_of(a); - if (sp < 0) return R4D_NO(RAD_E_INVAL); - int rc = fill_paged(a, r, H5_HEAD_DIM); - if (rc != RAD_OK) return rc; - r->splits = sp; - const int64_t need = r4d_attn_decode_h512_gqa8_scratch_bytes(r); - if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH); - return RAD_OK; -} - -extern "C" int r4d_rad_attn_decode_h512_gqa8_fp8(const RadArgs* a, RadStream s) { - R4DArgs r; - int rc = h5_decode_common(a, &r, 0); - if (rc != RAD_OK) return rc; - /* Absent descales mean 1.0; see the prefill twin above. */ - return r4d_attn_decode_h512_gqa8_fp8kv(&r, (hipStream_t)s); -} -extern "C" int r4d_rad_attn_decode_h512_gqa8_bf16(const RadArgs* a, RadStream s) { - R4DArgs r; - int rc = h5_decode_common(a, &r, 1); - if (rc != RAD_OK) return rc; - return r4d_attn_decode_h512_gqa8_bf16kv(&r, (hipStream_t)s); -} diff --git a/libr4d/r4d_attn_paged_window.hip b/libr4d/r4d_attn_paged_window.hip new file mode 100644 index 00000000..c28d25d5 --- /dev/null +++ b/libr4d/r4d_attn_paged_window.hip @@ -0,0 +1,1138 @@ +/* r4d_attn_paged_window.hip -- paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV + * head, ANY sliding window, causal or not, bf16 or fp8-e4m3 cache, q at any row pitch. + * + * Gemma 4's text layers are two of these geometries: its sliding layers are 16 query heads over 8 + * KV heads at head_dim 256 with a 1024-token window (gqa 2 at every TP), and its full layers 16 + * over 2 at head_dim 512 (gqa 8 at TP1/TP2, 4 at TP4, 2 at TP8). The library's other h256 legs are + * gqa 2 (windowed, q dense) and gqa 4/6/8/12 (`window == 0`); the row table says which serves + * where two meet (r4d_rows.cpp). + * + * WHAT THIS IS. Two kernels behind one entry point. The scalar one, for decode and verify steps: one + * workgroup owns one (sequence, KV head, slice of BQ query positions, split of the key range); each + * wave owns RW of the tile's R = BQ*gqa query rows; K and V come through LDS one paged block (or + * two) at a time, prefetched into registers while the previous tile is being consumed; the dot + * products are scalar FMAs with a butterfly reduce-scatter that leaves key j's score in lane j; the + * softmax is online, in the log2 domain. It is memory-bound at decode, where that is the only thing + * that matters. A prefill-shaped launch takes the WMMA kernel further down instead (its own header + * says how), which feeds RDNA4's matrix cores. + * + * WHAT IT COMPUTES is libref's ref_attn_paged, predicate for predicate: + * pos = seqused[s] - q_len(s) + i (seqused INCLUDES this step's queries) + * causal key j visible when j <= pos; non-causal when j < seqused[s] + * window causal: pos - j < window; non-causal: |pos - j| < window; 0 = none + * a block-table entry < 0 is a missing block: its keys are not visible + * no visible key at all -> a zero row + * k_descale / v_descale per (sequence, kv head), absent = 1 + * + * THE PAGED LAYOUT is kv_cache[n_blocks, kv_heads, 16, 2*head_dim], K then V inside a slot, which + * makes one block of one KV head ONE contiguous run of 16 * 2 * head_dim elements: a key tile is + * one or two such runs, fetched as 16-byte loads. + * + * SPLIT-KV. A launch with few (tile, kv head) pairs -- a decode step, a short verify -- would leave + * most of the card idle, so the key range of each tile is cut into `n_split` pieces, each written + * as an unnormalised partial (acc, max, sum) into the op's scratch, and a second kernel merges + * them. The split count is chosen at launch from host-side numbers only (rows, sequences, the + * window or max_ctx); each workgroup divides ITS OWN key range by it, so a split that receives no + * keys writes (0, -inf, 0) and the merge needs no host knowledge of the device-side context. + * + * Nothing here allocates, synchronises, or uses anything but hipLaunchKernel (docs/PLUGIN.md §5). + * Wave32 (RDNA): the shuffles and the reduce-scatter are written for 32 lanes. + */ +#include + +#include +#include + +#include "r4d_plugin.h" +#include "r4d_launch.h" +#include "rad_plugin.h" + +#if defined(__HIP_DEVICE_COMPILE__) && defined(__AMDGCN_WAVEFRONT_SIZE) && __AMDGCN_WAVEFRONT_SIZE != 32 +#error "this attention is written for wave32 (RDNA): build without -mwavefrontsize64" +#endif + +namespace r4d_win { + +constexpr int kThreads = 256; +constexpr int kWaves = kThreads / 32; + +/* split-KV bookkeeping: at most this many (tile, kv head, split) triples carry partials, and the + * tile table behind them holds at most kTinfoMax tiles. The launch keeps under both by + * construction; the scratch hook sizes for exactly these. */ +constexpr int kPartBudget = 192; +constexpr int kTinfoMax = 128; +constexpr int kMaxSplit = 64; + +template struct Geo; +/* R query rows a workgroup (R / 8 a wave), BK keys a tile. BK * 2 * HD bf16 = 32 KiB of LDS either + * way: two paged blocks at 256, one at 512. */ +template <> struct Geo<256> { static constexpr int R = 32, BK = 32; }; +template <> struct Geo<512> { static constexpr int R = 16, BK = 16; }; + +/* ------------------------------------------------------------------ device helpers */ +__device__ __forceinline__ int lane_id() { return (int)(threadIdx.x & 31u); } + +__device__ __forceinline__ float shfl_xor(float v, int m) { + return __int_as_float(__builtin_amdgcn_ds_bpermute((lane_id() ^ m) << 2, __float_as_int(v))); +} +__device__ __forceinline__ int shfl_up(int v, int d) { + const int l = lane_id(); + return __builtin_amdgcn_ds_bpermute((l >= d ? l - d : l) << 2, v); +} +__device__ __forceinline__ float readlane(float v, int l) { + return __int_as_float(__builtin_amdgcn_readlane(__float_as_int(v), l)); +} +__device__ __forceinline__ float wave_max(float v) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) v = __builtin_fmaxf(v, shfl_xor(v, d)); + return v; +} +__device__ __forceinline__ float wave_sum(float v) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) v += shfl_xor(v, d); + return v; +} +__device__ __forceinline__ float ex2(float x) { +#if __has_builtin(__builtin_amdgcn_exp2f) + return __builtin_amdgcn_exp2f(x); /* v_exp_f32: exp2(-inf) = 0 */ +#else + return exp2f(x); +#endif +} +__device__ __forceinline__ int imin(int a, int b) { return a < b ? a : b; } +__device__ __forceinline__ int imax(int a, int b) { return a > b ? a : b; } + +/* f(Ic<0>{}), ..., f(Ic{}): a loop whose index is a CONSTANT in every body, unconditionally. + * `#pragma unroll` is a request the unroller drops past a size threshold -- the fp8 legs of the + * row loop crossed it -- and a register array indexed by a loop variable that survives is demoted + * to scratch memory. This cannot be dropped. */ +template struct Ic { static constexpr int value = I; }; +template struct StaticFor { + template __device__ __forceinline__ static void run(F& f) { + if constexpr (I < N) { + f(Ic{}); + StaticFor::run(f); + } + } +}; + +__device__ __forceinline__ void bf16x4(uint2 w, float (&f)[4]) { + f[0] = __uint_as_float(w.x << 16); + f[1] = __uint_as_float(w.x & 0xffff0000u); + f[2] = __uint_as_float(w.y << 16); + f[3] = __uint_as_float(w.y & 0xffff0000u); +} +/* OCP E4M3 (e4m3fn, bias 7, 0x7f/0xff NaN, no infinity) -- the KV cache's bytes at + * --kv-cache-dtype fp8 (docs/PLUGIN.md §10). Exact; subnormals kept. */ +__device__ __forceinline__ float fp8e4m3(unsigned b) { + const unsigned e = (b >> 3) & 15u, m = b & 7u; + float v = e ? __uint_as_float(((e + 120u) << 23) | (m << 20)) : (float)m * 0.001953125f; + if (e == 15u && m == 7u) v = __uint_as_float(0x7fc00000u); + return __uint_as_float(__float_as_uint(v) | ((b & 0x80u) << 24)); +} +__device__ __forceinline__ void fp8x4(unsigned w, float (&f)[4]) { +#if defined(__GFX12__) + /* v_cvt_pk_f32_fp8: RDNA4 converts OCP E4M3 in hardware, two bytes an instruction -- the same + * instruction the library's other attention kernels read their fp8 cache with. */ + const auto a = __builtin_amdgcn_cvt_pk_f32_fp8((int)w, false); + const auto b = __builtin_amdgcn_cvt_pk_f32_fp8((int)w, true); + f[0] = a[0]; f[1] = a[1]; f[2] = b[0]; f[3] = b[1]; +#else + f[0] = fp8e4m3(w & 0xffu); + f[1] = fp8e4m3((w >> 8) & 0xffu); + f[2] = fp8e4m3((w >> 16) & 0xffu); + f[3] = fp8e4m3(w >> 24); +#endif +} +/* f32 -> bf16, round to nearest even, NaN kept quiet (rad_plugin.h's rad_f32_to_bf16). */ +__device__ __forceinline__ unsigned bf16_rtne(float f) { + unsigned u = __float_as_uint(f); + if ((u & 0x7fffffffu) > 0x7f800000u) return (u >> 16) | 0x40u; + u += 0x7fffu + ((u >> 16) & 1u); + return u >> 16; +} +__device__ __forceinline__ unsigned pack2(float a, float b) { return bf16_rtne(a) | (bf16_rtne(b) << 16); } + +/* Four elements of one slot row, at element offset `e`, out of the LDS tile. */ +template +__device__ __forceinline__ void lds4(const unsigned char* row, int e, float (&f)[4]) { + if constexpr (KV8) fp8x4(*(const unsigned*)(row + e), f); + else bf16x4(*(const uint2*)(row + 2 * e), f); +} + +/* THE REDUCE-SCATTER. Each lane holds a partial dot for every key of the tile; after it, lane l + * holds key l's full sum. Each step keeps the half of the vector its lane bit selects and adds the + * partner's copy of that half: 16 + 8 + 4 + 2 + 1 = 31 shuffles for 32 keys, against 32 * 5 for 32 + * separate reductions. */ +template +__device__ __forceinline__ void reduce_scatter(float (&v)[N], int lane) { + if constexpr (H >= 1) { + const bool up = (lane & H) != 0; +#pragma unroll + for (int i = 0; i < H; ++i) { + /* VALUES, not lvalues: `up ? v[i + H] : v[i]` selects between two ADDRESSES, and an + * array addressed by a lane-dependent pointer is demoted to scratch memory. */ + const float lo = v[i], hi = v[i + H]; + const float keep = up ? hi : lo; + const float send = up ? lo : hi; + v[i] = keep + shfl_xor(send, H); + } + reduce_scatter(v, lane); + } +} + +/* ------------------------------------------------------------------ the launch's arguments */ +struct AttnArgs { + const uint16_t* q; long long q_rs, q_hs; /* elements */ + const unsigned char* kv; long long kv_sb, kv_sh; /* elements of the cache's dtype */ + const int* bt; long long bt_rs; + const int* seqused; + const int* cu; /* null: uniform q_len */ + const float* kdes; + const float* vdes; + uint16_t* out; long long o_rs, o_hs; + float* part; /* split-KV partials, or null */ + int* tinfo; /* [tile] = (first row, positions) */ + float qscale; /* softmax scale * log2(e) */ + int max_blocks, n_seq, q_len, tps, kv_heads, causal, window, n_split; +}; + +/* Tile `tile` of a ragged batch: the sequence it belongs to and which BQ-position slice of that + * sequence's query it is. Tiles are numbered sequence by sequence, ceil(q_len(s) / BQ) each, so the + * answer is a prefix sum over cu_seqlens -- done by the whole block, 256 sequences a pass. Every + * thread returns the same answer: it is read back out of LDS after a barrier. */ +template +__device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int* s_res, int& s_out, + int& lt_out) { + constexpr int NW = NT / 32; + const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5; + if (tid == 0) { s_res[0] = -1; s_res[1] = 0; } + __syncthreads(); + int base = 0; + for (int c0 = 0; c0 < n_seq; c0 += NT) { + const int s = c0 + tid; + int nt = 0; + if (s < n_seq) { + const int ql = cu[s + 1] - cu[s]; + nt = ql > 0 ? (ql + BQ - 1) / BQ : 0; + } + int x = nt; + for (int d = 1; d < 32; d <<= 1) { + const int y = shfl_up(x, d); + if (lane >= d) x += y; + } + if (lane == 31) s_scan[wave] = x; + __syncthreads(); + int before = 0, total = 0; + for (int w = 0; w < NW; ++w) { + const int v = s_scan[w]; + before += (w < wave) ? v : 0; + total += v; + } + const int incl = base + before + x; + if (nt > 0 && tile >= incl - nt && tile < incl) { s_res[0] = s; s_res[1] = tile - (incl - nt); } + base += total; + __syncthreads(); + if (s_res[0] >= 0 || base > tile) break; + } + s_out = s_res[0]; + lt_out = s_res[1]; +} + +/* ------------------------------------------------------------------ the attention kernel */ +template +__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { + constexpr int R = Geo::R, BK = Geo::BK, RW = R / kWaves, BQ = R / GQA; + constexpr int NC = HD / 128; /* 4-element chunks a lane holds of a row */ + constexpr int ESZ = KV8 ? 1 : 2; + constexpr int KEY_BYTES = 2 * HD * ESZ; /* one slot: K then V */ + constexpr int TILE_U4 = BK * KEY_BYTES / 16; + constexpr int NPT = TILE_U4 / kThreads; /* 16-byte loads a thread, per tile */ + constexpr int BLK_U4 = 16 * KEY_BYTES / 16; /* one paged block of one kv head */ + constexpr int NB = BK / 16; /* paged blocks a key tile spans */ + static_assert(R % kWaves == 0 && R % GQA == 0, "rows must split over waves and heads"); + static_assert(TILE_U4 % kThreads == 0 && BLK_U4 % kThreads == 0, "tile must split over threads"); + static_assert(BK == 32 || BK == 16, "the reduce-scatter is written for 16 or 32 keys"); + + __shared__ uint4 s_kv[TILE_U4]; + __shared__ int s_scan[kWaves]; + __shared__ int s_res[2]; + + const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int tile = (int)blockIdx.x, kh = (int)blockIdx.y, z = (int)blockIdx.z; + + /* ---- which sequence, and which slice of its query */ + int s = -1, lt = 0; + if (A.cu) { + find_tile(A.cu, A.n_seq, tile, s_scan, s_res, s, lt); + } else { + s = tile / A.tps; + lt = tile - s * A.tps; + if (s >= A.n_seq) s = -1; + } + int qlen = 0, tokb = 0, ctx = 0; + if (s >= 0) { + if (A.cu) { tokb = A.cu[s]; qlen = A.cu[s + 1] - tokb; } + else { tokb = s * A.q_len; qlen = A.q_len; } + ctx = A.seqused[s]; + } + const int pfirst = lt * BQ; + const int npos = s >= 0 ? imax(0, imin(BQ, qlen - pfirst)) : 0; + if (A.n_split > 1 && kh == 0 && z == 0 && tid == 0) { + A.tinfo[2 * tile] = tokb + pfirst; + A.tinfo[2 * tile + 1] = npos; + } + if (npos <= 0) return; /* uniform across the block */ + + const int tok0 = tokb + pfirst; + const int qbase = ctx - qlen + pfirst; /* absolute position of the tile's first query */ + const int plast = qbase + npos - 1; + const int causal = A.causal, window = A.window; + + /* ---- the tile's key range, and this split's share of it */ + int hi = causal ? plast + 1 : ctx; + if (!causal && window > 0) hi = imin(hi, plast + window); + hi = imin(imin(hi, ctx), A.max_blocks * 16); + const int lo = window > 0 ? imax(0, qbase - window + 1) : 0; + const int lo_a = lo & ~(BK - 1); + const int nkt = hi > lo_a ? (hi - lo_a + BK - 1) / BK : 0; + const int per = (nkt + A.n_split - 1) / A.n_split; + const int kt_lo = imin(nkt, z * per), kt_hi = imin(nkt, kt_lo + per); + + const float kds = A.kdes ? A.kdes[(long long)s * A.kv_heads + kh] : 1.0f; + const float vds = A.vdes ? A.vdes[(long long)s * A.kv_heads + kh] : 1.0f; + + /* ---- this wave's query rows: row r is position r / GQA, head kh * GQA + r % GQA */ + float qf[RW][NC][4], o[RW][NC][4], m[RW], l[RW]; + int pos[RW]; + bool val[RW]; +#pragma unroll + for (int i = 0; i < RW; ++i) { + const int r = wave * RW + i, p = r / GQA, g = r - p * GQA; + val[i] = p < npos; + pos[i] = qbase + p; + m[i] = -__builtin_inff(); + l[i] = 0.0f; + const uint16_t* qp = A.q + (long long)(tok0 + p) * A.q_rs + (long long)(kh * GQA + g) * A.q_hs; + const float qs = A.qscale * kds; /* k_descale folds into the query */ +#pragma unroll + for (int c = 0; c < NC; ++c) { + float f[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + if (val[i]) bf16x4(*(const uint2*)(qp + c * 128 + lane * 4), f); +#pragma unroll + for (int e = 0; e < 4; ++e) { qf[i][c][e] = f[e] * qs; o[i][c][e] = 0.0f; } + } + } + + /* ---- the key tiles, prefetched one ahead through registers */ + uint4 pre[NPT]; + bool pre_ok[NB]; + auto fetch = [&](int kt) __attribute__((always_inline)) { + const int k0 = lo_a + kt * BK; + const unsigned char* src[NB]; +#pragma unroll + for (int b = 0; b < NB; ++b) { + const int lb = (k0 >> 4) + b; + int blk = -1; + if (lb < A.max_blocks && (lb << 4) < hi) blk = A.bt[(long long)s * A.bt_rs + lb]; + pre_ok[b] = blk >= 0; + /* never a null: a select against null makes the pointer FLAT rather than global, and + * every tile load a flat_load. A missing block points at the cache's base and its + * value is replaced by zeros below. */ + src[b] = A.kv + ((long long)(blk >= 0 ? blk : 0) * A.kv_sb + (long long)kh * A.kv_sh) * ESZ; + } +#pragma unroll + for (int i = 0; i < NPT; ++i) { + const int b = (i * kThreads) / BLK_U4; /* constant: BLK_U4 is a multiple of 256 */ + const int off = tid + i * kThreads - b * BLK_U4; + if (pre_ok[b]) pre[i] = ((const uint4*)src[b])[off]; + else pre[i] = make_uint4(0u, 0u, 0u, 0u); + } + }; + + const unsigned char* sb = (const unsigned char*)s_kv; + if (kt_lo < kt_hi) fetch(kt_lo); + for (int kt = kt_lo; kt < kt_hi; ++kt) { + __syncthreads(); /* the previous tile is consumed */ +#pragma unroll + for (int i = 0; i < NPT; ++i) s_kv[tid + i * kThreads] = pre[i]; + const bool ok0 = pre_ok[0], ok1 = pre_ok[NB - 1]; /* values: see reduce_scatter */ + __syncthreads(); + const int k0 = lo_a + kt * BK; + if (kt + 1 < kt_hi) fetch(kt + 1); + + const int jl = lane & (BK - 1); /* the key this lane scores */ + const int kk = k0 + jl; + const bool kok = (jl < 16 ? ok0 : ok1) && kk >= lo && kk < hi; + + auto row_step = [&](auto ic) __attribute__((always_inline)) { + constexpr int i = decltype(ic)::value; + if (!val[i]) return; /* uniform: one row, all lanes */ + float sc[BK]; +#pragma unroll + for (int j = 0; j < BK; ++j) { + const unsigned char* row = sb + j * KEY_BYTES; + float acc = 0.0f; +#pragma unroll + for (int c = 0; c < NC; ++c) { + float k[4]; + lds4(row, c * 128 + lane * 4, k); +#pragma unroll + for (int e = 0; e < 4; ++e) acc = __builtin_fmaf(qf[i][c][e], k[e], acc); + } + sc[j] = acc; + } + if constexpr (BK == 32) { + reduce_scatter<16, BK>(sc, lane); + } else { +#pragma unroll + for (int j = 0; j < BK; ++j) sc[j] += shfl_xor(sc[j], 16); + reduce_scatter<8, BK>(sc, lane); + } + const int pq = pos[i]; + bool vis = kok && (causal ? kk <= pq : true); + if (window > 0) vis = vis && (pq - kk < window) && (causal || kk - pq < window); + const float sv = vis ? sc[0] : -__builtin_inff(); + const float mn = __builtin_fmaxf(m[i], wave_max(sv)); + if (mn == -__builtin_inff()) return; /* nothing visible yet: uniform */ + const float corr = ex2(m[i] - mn); + const float p = vis ? ex2(sv - mn) : 0.0f; + l[i] = l[i] * corr + wave_sum((BK == 16 && lane >= 16) ? 0.0f : p); +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int e = 0; e < 4; ++e) o[i][c][e] *= corr; +#pragma unroll + for (int j = 0; j < BK; ++j) { + const float pj = readlane(p, j); /* uniform; a masked key's V is never read */ + if (pj != 0.0f) { + const unsigned char* row = sb + j * KEY_BYTES; +#pragma unroll + for (int c = 0; c < NC; ++c) { + float v[4]; + lds4(row, HD + c * 128 + lane * 4, v); +#pragma unroll + for (int e = 0; e < 4; ++e) o[i][c][e] = __builtin_fmaf(pj, v[e], o[i][c][e]); + } + } + } + m[i] = mn; + }; + StaticFor<0, RW>::run(row_step); + } + + /* ---- out: normalised bf16 rows, or this split's partials */ +#pragma unroll + for (int i = 0; i < RW; ++i) { + if (!val[i]) continue; + const int r = wave * RW + i, p = r / GQA, g = r - p * GQA; + if (A.n_split == 1) { + const float inv = l[i] > 0.0f ? vds / l[i] : 0.0f; + uint16_t* op = A.out + (long long)(tok0 + p) * A.o_rs + (long long)(kh * GQA + g) * A.o_hs; +#pragma unroll + for (int c = 0; c < NC; ++c) + *(uint2*)(op + c * 128 + lane * 4) = + make_uint2(pack2(o[i][c][0] * inv, o[i][c][1] * inv), + pack2(o[i][c][2] * inv, o[i][c][3] * inv)); + } else { + const long long slot = (((long long)tile * A.kv_heads + kh) * A.n_split + z) * R + r; + float* pp = A.part + slot * (HD + 4); + if (lane == 0) { pp[HD] = m[i]; pp[HD + 1] = l[i]; } + /* no key visible to this row in this split: the merge weighs it 0 and never reads its + * accumulator, so it is not written (uniform: m is the wave's) */ + if (m[i] == -__builtin_inff()) continue; +#pragma unroll + for (int c = 0; c < NC; ++c) + *(float4*)(pp + c * 128 + lane * 4) = + make_float4(o[i][c][0] * vds, o[i][c][1] * vds, o[i][c][2] * vds, o[i][c][3] * vds); + } + } +} + +/* ================================================================== the WMMA prefill kernel + * + * WHY A SECOND KERNEL. The kernel above is scalar FMAs: right for decode, where a step is a few + * rows and the cache read is the whole cost, and about 8 TFLOP/s a card on a long prefill, where + * the global layers' attention is quadratic in the prompt and 46% of a 48k-token prefill. RDNA4's + * matrix cores do a 16x16x16 bf16 product a WMMA instruction; this kernel feeds them. It is chosen + * at launch for prefill-shaped steps only (a sequence with >= kWmmaMinQ query rows) and computes + * the same function, predicate for predicate. + * + * THE LAYOUTS (RDNA4, wave32, v_wmma_f32_16x16x16_bf16 -- confirmed against llama.cpp's mma.cuh, + * which runs on the card): A[M][K] gives lane L row M = L % 16 and K = 8 * (L / 16) .. + 7; B[K][N] + * gives lane L column N = L % 16 and the same K; the f32 result gives lane L column N = L % 16 and + * rows M = 8 * (L / 16) .. + 7. So the kernel computes S TRANSPOSED: S^T = K * Q^T puts each + * lane's eight values in ONE query row (row L % 16, keys 8h .. 8h + 7), the row's other eight keys + * in lane L ^ 16 -- the softmax statistics are one shuffle -- and those eight values, as bf16, are + * exactly the B operand of O^T = V^T * P^T. O^T's lane L likewise holds only row L % 16, so the + * online-softmax rescale is a per-lane scalar. + * + * THE SPLIT. O^T for 16 rows of a 512-dim head is 256 f32 a lane -- the whole register file. So a + * wave owns 16 rows by a 128-dim slice of the head (kDQ): its Q^T (32 VGPRs) and O^T (64). The + * slices of one row group each compute S^T over their own dims; the partials meet in LDS and every + * slice sums them in the same order, so all of them see bit-identical scores and take identical + * softmax steps. 16 waves: h512 is 4 row groups of 4 slices (64 rows), h256 8 of 2 (128 rows). + * + * THE TILE is one paged block, 16 keys. K goes to LDS as it is ([key][dim] bf16, a 16-byte pad a row + * so the A-fragment reads hit 32 different banks); V goes TRANSPOSED ([dim][key], rows of 48 + * bytes), since the PV product reduces over keys and an operand's eight K-values must be + * contiguous. The transposed write is two keys' dims packed a dword, the dword index rotated per + * lane group so a wave's 32 writes land in 32 banks. An fp8 cache is widened on the way in -- exact, + * e4m3 has 3 mantissa bits. Keys outside the tile's range or in a missing block are written as + * zeros: a probability of 0 times a NaN in a recycled slot is still NaN. + * + * P AND V IN f16, Q AND K IN bf16. The probabilities are rounded for the matrix product, and bf16's + * 8 bits leave 2^-9 of |v| in every output -- measured in the emulator against f64 at up to 0.25% + * of the V range, four times the scalar kernel's error. f16 runs at the same rate with 11 bits. V's + * bf16 values are exact in f16 between 2^-14 and 65504 (clamped beyond, NaN kept); an fp8 cache's + * are exact outright. The denominator sums the probabilities as rounded, so a row is a true + * weighted mean of V: a dominant key keeps weight 1 exactly. + */ +typedef short win_v8s __attribute__((ext_vector_type(8))); /* 8 bf16, as the builtin takes them */ +typedef float win_v8f __attribute__((ext_vector_type(8))); +typedef _Float16 win_v8h __attribute__((ext_vector_type(8))); + +constexpr int kWThreads = 512; +constexpr int kWWaves = kWThreads / 32; +constexpr int kDQ = 128; /* dims of a wave's slice of the head */ +constexpr int kWmmaMinQ = 64; /* a launch whose longest query is shorter stays scalar */ + +template struct WGeo { + static constexpr int NS = HD / kDQ; /* slices: waves sharing one 16-row group */ + static constexpr int RG = kWWaves / NS; /* row groups a workgroup */ + static constexpr int R = RG * 16; /* rows a workgroup */ + static constexpr int KS = HD * 2 + 16; /* bytes a key row of the K tile */ + static constexpr int VS = 48; /* bytes a dim row of the V^T tile: 16 keys + pad */ +}; + +__device__ __forceinline__ win_v8f wmma_bf16(win_v8s a, win_v8s b, win_v8f c) { + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); +} +__device__ __forceinline__ win_v8f wmma_f16(win_v8h a, win_v8h b, win_v8f c) { + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +} +/* f32 -> f16 bits, round to nearest even; a finite value past f16's range saturates, NaN stays */ +__device__ __forceinline__ unsigned f16_bits(float f) { + if (f == f) f = __builtin_fminf(__builtin_fmaxf(f, -65504.0f), 65504.0f); + return (unsigned)__builtin_bit_cast(unsigned short, (_Float16)f); +} +__device__ __forceinline__ void fp8x16_f16(const uint4 w, unsigned (&h)[16]) { + const unsigned in[4] = {w.x, w.y, w.z, w.w}; +#pragma unroll + for (int q = 0; q < 4; ++q) { + float f[4]; + fp8x4(in[q], f); +#pragma unroll + for (int e = 0; e < 4; ++e) h[q * 4 + e] = f16_bits(f[e]); + } +} +__device__ __forceinline__ void bf16x8_f16(const uint4 w, unsigned (&h)[8]) { + const unsigned in[4] = {w.x, w.y, w.z, w.w}; +#pragma unroll + for (int q = 0; q < 4; ++q) { + h[2 * q] = f16_bits(__uint_as_float(in[q] << 16)); + h[2 * q + 1] = f16_bits(__uint_as_float(in[q] & 0xffff0000u)); + } +} +/* fp8 e4m3 -> bf16 bits (the K tile), exact: the f32 a byte widens to has nothing below bit 16 */ +__device__ __forceinline__ void fp8x16_bf16(const uint4 w, unsigned (&h)[16]) { + const unsigned in[4] = {w.x, w.y, w.z, w.w}; +#pragma unroll + for (int q = 0; q < 4; ++q) { + float f[4]; + fp8x4(in[q], f); +#pragma unroll + for (int e = 0; e < 4; ++e) h[q * 4 + e] = __float_as_uint(f[e]) >> 16; + } +} + +template +__global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) { + using G = WGeo; + constexpr int NS = G::NS, R = G::R, BQ = R / GQA, KS = G::KS, VS = G::VS; + constexpr int ESZ = KV8 ? 1 : 2; + constexpr int SLOT = 2 * HD * ESZ; /* bytes of one key's slot: K then V */ + constexpr int CW = 16 / ESZ; /* cache elements one 16-byte load carries */ + constexpr int NCH = HD / CW; /* such chunks a head */ + constexpr int NKI = 16 * NCH; /* K items a tile: (key, chunk) */ + constexpr int NVI = 8 * NCH; /* V items a tile: (key pair, chunk) */ + constexpr int KPT = (NKI + kWThreads - 1) / kWThreads; + constexpr int VPT = (NVI + kWThreads - 1) / kWThreads; + static_assert(R % GQA == 0 && NS * G::RG == kWWaves, "rows must split over heads and waves"); + static_assert(KS % 16 == 0 && VS % 16 == 0, "16-byte LDS rows"); + + __shared__ uint4 s_k[16 * KS / 16]; + __shared__ uint4 s_vt[HD * VS / 16]; + __shared__ float4 s_x[kWWaves * 32 * 2]; + __shared__ int s_scan[kWWaves]; + __shared__ int s_res[2]; + + const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int rg = wave / NS, sl = wave - rg * NS; + const int tile = (int)blockIdx.x, kh = (int)blockIdx.y; + + /* ---- which sequence, and which slice of its query: as the scalar kernel, at this BQ */ + int s = -1, lt = 0; + if (A.cu) { + find_tile(A.cu, A.n_seq, tile, s_scan, s_res, s, lt); + } else { + s = tile / A.tps; + lt = tile - s * A.tps; + if (s >= A.n_seq) s = -1; + } + int qlen = 0, tokb = 0, ctx = 0; + if (s >= 0) { + if (A.cu) { tokb = A.cu[s]; qlen = A.cu[s + 1] - tokb; } + else { tokb = s * A.q_len; qlen = A.q_len; } + ctx = A.seqused[s]; + } + const int pfirst = lt * BQ; + const int npos = s >= 0 ? imax(0, imin(BQ, qlen - pfirst)) : 0; + if (npos <= 0) return; /* uniform across the block */ + + const int tok0 = tokb + pfirst; + const int qbase = ctx - qlen + pfirst; + const int plast = qbase + npos - 1; + const int causal = A.causal, window = A.window; + int hi = causal ? plast + 1 : ctx; + if (!causal && window > 0) hi = imin(hi, plast + window); + hi = imin(imin(hi, ctx), A.max_blocks * 16); + const int lo = window > 0 ? imax(0, qbase - window + 1) : 0; + const int lo_a = lo & ~15; + const int nkt = hi > lo_a ? (hi - lo_a + 15) / 16 : 0; + + const float kds = A.kdes ? A.kdes[(long long)s * A.kv_heads + kh] : 1.0f; + const float vds = A.vdes ? A.vdes[(long long)s * A.kv_heads + kh] : 1.0f; + const float sscale = A.qscale * kds; /* log2-domain softmax scale, k_descale in */ + + /* ---- this lane's query row: column n of every S^T and O^T tile */ + const int n = lane & 15, h = lane >> 4; + const int r = rg * 16 + n, p = r / GQA, g = r - p * GQA; + const bool rval = p < npos; + const int pos = qbase + p; + + win_v8s qf[kDQ / 16]; + { + const uint16_t* qp = A.q + (long long)(tok0 + (rval ? p : 0)) * A.q_rs + + (long long)(kh * GQA + g) * A.q_hs + sl * kDQ + 8 * h; +#pragma unroll + for (int kc = 0; kc < kDQ / 16; ++kc) { + const uint4 w = rval ? *(const uint4*)(qp + kc * 16) : make_uint4(0u, 0u, 0u, 0u); + qf[kc] = __builtin_bit_cast(win_v8s, w); + } + } + win_v8f oacc[kDQ / 16]; +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) +#pragma unroll + for (int e = 0; e < 8; ++e) oacc[mc][e] = 0.0f; + float m = -__builtin_inff(), l = 0.0f; + + /* ---- the key tiles, one paged block each, prefetched one ahead through registers */ + uint4 pk[KPT], pv[VPT][2]; + bool pre_ok = false; + auto fetch = [&](int kt) __attribute__((always_inline)) { + const int k0 = lo_a + kt * 16, lb = k0 >> 4; + int blk = -1; + if (lb < A.max_blocks && k0 < hi) blk = A.bt[(long long)s * A.bt_rs + lb]; + pre_ok = blk >= 0; + /* never a null: see the scalar kernel's fetch */ + const unsigned char* base = + A.kv + ((long long)(blk >= 0 ? blk : 0) * A.kv_sb + (long long)kh * A.kv_sh) * ESZ; +#pragma unroll + for (int j = 0; j < KPT; ++j) { + const int idx = tid + j * kWThreads; + pk[j] = make_uint4(0u, 0u, 0u, 0u); + if (pre_ok && idx < NKI) { + const int key = idx / NCH, ch = idx - key * NCH; + pk[j] = *(const uint4*)(base + key * SLOT + ch * 16); + } + } +#pragma unroll + for (int j = 0; j < VPT; ++j) { + const int idx = tid + j * kWThreads; + pv[j][0] = pv[j][1] = make_uint4(0u, 0u, 0u, 0u); + if (pre_ok && idx < NVI) { + const int kp = idx & 7, ch = idx >> 3; + const unsigned char* v0 = base + (2 * kp) * SLOT + HD * ESZ + ch * 16; + pv[j][0] = *(const uint4*)v0; + pv[j][1] = *(const uint4*)(v0 + SLOT); + } + } + }; + + unsigned char* kb = (unsigned char*)s_k; + unsigned char* vb = (unsigned char*)s_vt; + if (nkt > 0) fetch(0); + for (int kt = 0; kt < nkt; ++kt) { + const int k0 = lo_a + kt * 16; + const bool tok = pre_ok; /* this tile's block is present */ + __syncthreads(); /* the previous tile's LDS is consumed */ + + /* ---- K: [key][dim] as bf16 */ +#pragma unroll + for (int j = 0; j < KPT; ++j) { + const int idx = tid + j * kWThreads; + if (idx < NKI) { + const int key = idx / NCH, ch = idx - key * NCH; + const int kk = k0 + key; + const bool keep = tok && kk >= lo && kk < hi; + const uint4 w = keep ? pk[j] : make_uint4(0u, 0u, 0u, 0u); + if constexpr (KV8) { + unsigned hb[16]; + fp8x16_bf16(w, hb); + uint4* dst = (uint4*)(kb + key * KS + ch * 32); + dst[0] = make_uint4(hb[0] | hb[1] << 16, hb[2] | hb[3] << 16, hb[4] | hb[5] << 16, hb[6] | hb[7] << 16); + dst[1] = make_uint4(hb[8] | hb[9] << 16, hb[10] | hb[11] << 16, hb[12] | hb[13] << 16, hb[14] | hb[15] << 16); + } else { + *(uint4*)(kb + key * KS + ch * 16) = w; + } + } + } + /* ---- V: [dim][key] as f16, two keys a dword; the row order rotated by 2 per 8-lane + * group, so the four groups of a wave write four different rows mod 8 -- 32 banks */ +#pragma unroll + for (int j = 0; j < VPT; ++j) { + const int idx = tid + j * kWThreads; + if (idx < NVI) { + const int kp = idx & 7, ch = idx >> 3; + const int ka = k0 + 2 * kp, kb1 = ka + 1; + const uint4 wa = (tok && ka >= lo && ka < hi) ? pv[j][0] : make_uint4(0u, 0u, 0u, 0u); + const uint4 wb = (tok && kb1 >= lo && kb1 < hi) ? pv[j][1] : make_uint4(0u, 0u, 0u, 0u); + unsigned d[CW]; /* f16 pairs: key 2kp low, 2kp + 1 high */ + if constexpr (KV8) { + unsigned ha[16], hb2[16]; + fp8x16_f16(wa, ha); + fp8x16_f16(wb, hb2); +#pragma unroll + for (int e = 0; e < CW; ++e) d[e] = ha[e] | hb2[e] << 16; + } else { + unsigned ha[8], hb2[8]; + bf16x8_f16(wa, ha); + bf16x8_f16(wb, hb2); +#pragma unroll + for (int e = 0; e < CW; ++e) d[e] = ha[e] | hb2[e] << 16; + } + const int rot = 2 * ((lane >> 3) & 3); + unsigned* col = (unsigned*)(vb + (ch * CW) * VS) + kp; +#pragma unroll + for (int t = 0; t < CW; ++t) { + /* element (t + rot) % CW, chosen by value: rot is per lane */ + const unsigned v0 = d[t], v2 = d[(t + 2) % CW], v4 = d[(t + 4) % CW], v6 = d[(t + 6) % CW]; + const unsigned v = rot == 0 ? v0 : rot == 2 ? v2 : rot == 4 ? v4 : v6; + const int e = (t + rot) % CW; + col[e * (VS / 4)] = v; + } + } + } + __syncthreads(); + if (kt + 1 < nkt) fetch(kt + 1); + + /* ---- S^T partial over this wave's slice: A = K rows (key n), B = Q^T (row n) */ + win_v8f sacc; +#pragma unroll + for (int e = 0; e < 8; ++e) sacc[e] = 0.0f; + { + /* one accumulator: a second one hides the chain's latency but costs 12 VGPRs, and at + * 187 two 16-wave workgroups share a WGP (8 waves a SIMD, 1536 VGPRs) where at 200 + * one does -- the other waves hide the latency better */ + const unsigned char* ka = kb + n * KS + (sl * kDQ + 8 * h) * 2; +#pragma unroll + for (int kc = 0; kc < kDQ / 16; ++kc) + sacc = wmma_bf16(__builtin_bit_cast(win_v8s, *(const uint4*)(ka + kc * 32)), qf[kc], sacc); + } + /* ---- the slices' partials meet: every slice sums them in slice order */ + s_x[(wave * 2 + 0) * 32 + lane] = make_float4(sacc[0], sacc[1], sacc[2], sacc[3]); + s_x[(wave * 2 + 1) * 32 + lane] = make_float4(sacc[4], sacc[5], sacc[6], sacc[7]); + __syncthreads(); + float tot[8]; +#pragma unroll + for (int j = 0; j < NS; ++j) { + float v[8]; + if (j == sl) { /* uniform: the wave's own, as written */ +#pragma unroll + for (int e = 0; e < 8; ++e) v[e] = sacc[e]; + } else { + const float4 a = s_x[((rg * NS + j) * 2 + 0) * 32 + lane]; + const float4 b = s_x[((rg * NS + j) * 2 + 1) * 32 + lane]; + v[0] = a.x; v[1] = a.y; v[2] = a.z; v[3] = a.w; + v[4] = b.x; v[5] = b.y; v[6] = b.z; v[7] = b.w; + } +#pragma unroll + for (int e = 0; e < 8; ++e) tot[e] = j == 0 ? v[e] : tot[e] + v[e]; + } + + /* ---- online softmax, row n: eight keys here, eight in lane ^ 16 */ + float sv[8], mx = -__builtin_inff(); +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int kk = k0 + 8 * h + e; + bool vis = rval && tok && kk >= lo && kk < hi; + if (causal) vis = vis && kk <= pos; + if (window > 0) vis = vis && (pos - kk < window) && (causal || kk - pos < window); + sv[e] = vis ? tot[e] * sscale : -__builtin_inff(); + mx = __builtin_fmaxf(mx, sv[e]); + } + mx = __builtin_fmaxf(mx, shfl_xor(mx, 16)); + const float mn = __builtin_fmaxf(m, mx); + const float corr = mn == -__builtin_inff() ? 1.0f : ex2(m - mn); + /* P in f16, and the denominator summed from P as rounded (see the head of this kernel) */ + float ps = 0.0f; + win_v8h pf; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const float pe = sv[e] == -__builtin_inff() ? 0.0f : ex2(sv[e] - mn); + pf[e] = (_Float16)pe; /* in [0, 1]: no saturation to worry about */ + ps += (float)pf[e]; + } + l = l * corr + ps; + m = mn; + + /* ---- O^T += V^T * P^T in f16: A = V^T rows (dim n of the chunk), keys 8h .. 8h + 7 */ + const unsigned char* va = vb + (sl * kDQ + n) * VS + h * 16; +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) { + oacc[mc] *= corr; + oacc[mc] = wmma_f16(__builtin_bit_cast(win_v8h, *(const uint4*)(va + mc * 16 * VS)), pf, oacc[mc]); + } + } + + /* ---- out: the row's denominator is its two lanes' partial sums */ + const float lt2 = l + shfl_xor(l, 16); + if (rval) { + const float inv = lt2 > 0.0f ? vds / lt2 : 0.0f; + uint16_t* op = A.out + (long long)(tok0 + p) * A.o_rs + (long long)(kh * GQA + g) * A.o_hs + + sl * kDQ + 8 * h; +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) + *(uint4*)(op + mc * 16) = + make_uint4(pack2(oacc[mc][0] * inv, oacc[mc][1] * inv), pack2(oacc[mc][2] * inv, oacc[mc][3] * inv), + pack2(oacc[mc][4] * inv, oacc[mc][5] * inv), pack2(oacc[mc][6] * inv, oacc[mc][7] * inv)); + } +} + +/* ------------------------------------------------------------------ the split-KV merge + * + * ONE WAVE A ROW, THE SPLITS ACROSS ITS LANES. Lane z reads split z's (max, sum) and lane z + 32 + * split z + 32's -- kMaxSplit is 64 -- so the row's max and denominator are one wave reduction + * each; then one sweep over the splits that saw a key, four at a time, every lane accumulating + * its 4 * NC dims. The first version walked the splits three times over, + * serially, in one thread block per tile: at the 64 splits a decode step of a full-attention layer + * gets, that was 750 us a call, a quarter of the step's device time. */ +template +__global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { + constexpr int R = Geo::R, NC = HD / 128; + static_assert(kMaxSplit <= 64, "two splits a lane"); + const int tile = (int)blockIdx.x, kh = (int)blockIdx.y; + const int lane = lane_id(), wave = (int)(threadIdx.x >> 5); + const int tok0 = A.tinfo[2 * tile], npos = A.tinfo[2 * tile + 1]; + const int ns = A.n_split; + const float ninf = -__builtin_inff(); + for (int r = wave; r < npos * GQA; r += kWaves) { + const int p = r / GQA, g = r - p * GQA; + const long long base = ((long long)tile * A.kv_heads + kh) * ns * R + r; + uint16_t* op = A.out + (long long)(tok0 + p) * A.o_rs + (long long)(kh * GQA + g) * A.o_hs; + float m0 = ninf, m1 = ninf, l0 = 0.0f, l1 = 0.0f; + if (lane < ns) { + const float* pp = A.part + (base + (long long)lane * R) * (HD + 4); + m0 = pp[HD]; l0 = pp[HD + 1]; + } + if (lane + 32 < ns) { + const float* pp = A.part + (base + (long long)(lane + 32) * R) * (HD + 4); + m1 = pp[HD]; l1 = pp[HD + 1]; + } + const float mt = wave_max(__builtin_fmaxf(m0, m1)); + if (mt == ninf) { /* no key visible to the row: a zero row */ +#pragma unroll + for (int c = 0; c < NC; ++c) *(uint2*)(op + c * 128 + lane * 4) = make_uint2(0u, 0u); + continue; + } + const float w0 = ex2(m0 - mt), w1 = ex2(m1 - mt); /* an empty split: ex2(-inf) = 0 */ + const float lt = wave_sum(__builtin_fmaf(l0, w0, l1 * w1)); + const float inv = lt > 0.0f ? 1.0f / lt : 0.0f; + float acc[NC][4]; +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int e = 0; e < 4; ++e) acc[c][e] = 0.0f; + /* The splits that carry weight, as a 64-bit set every lane holds the same copy of, taken + * four at a time so 4 * NC loads are in flight before the first FMA waits on one. A short + * group repeats its first split at weight 0: the index is a written one, so the product is + * 0 * finite. An empty split's accumulator was never written and is never read. */ + uint64_t live = (uint64_t)__builtin_amdgcn_ballot_w32(w0 != 0.0f) | + ((uint64_t)__builtin_amdgcn_ballot_w32(w1 != 0.0f) << 32); + while (live) { + int zi[4]; + float wj[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const bool have = live != 0; + zi[j] = have ? __builtin_ctzll(live) : zi[0]; + live &= have ? live - 1 : live; + wj[j] = readlane(zi[j] < 32 ? w0 : w1, zi[j] & 31); + if (!have) wj[j] = 0.0f; + } + float4 v[4][NC]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float* pp = A.part + (base + (long long)zi[j] * R) * (HD + 4); +#pragma unroll + for (int c = 0; c < NC; ++c) v[j][c] = *(const float4*)(pp + c * 128 + lane * 4); + } +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int c = 0; c < NC; ++c) { + acc[c][0] = __builtin_fmaf(wj[j], v[j][c].x, acc[c][0]); + acc[c][1] = __builtin_fmaf(wj[j], v[j][c].y, acc[c][1]); + acc[c][2] = __builtin_fmaf(wj[j], v[j][c].z, acc[c][2]); + acc[c][3] = __builtin_fmaf(wj[j], v[j][c].w, acc[c][3]); + } + } +#pragma unroll + for (int c = 0; c < NC; ++c) + *(uint2*)(op + c * 128 + lane * 4) = + make_uint2(pack2(acc[c][0] * inv, acc[c][1] * inv), pack2(acc[c][2] * inv, acc[c][3] * inv)); + } +} + +/* ------------------------------------------------------------------ host: the launch adapter */ + +/* q and out as [rows, heads, head_dim] at whatever rank they arrived in: rank 3 (or more, leading + * axes dense), or rank 2 [rows, heads * head_dim] with its own row pitch -- a column slice of a + * fused projection. The last axis must be dense. */ +static bool head_view(const RadTensor* t, int64_t heads, int64_t hd, int64_t* rows, int64_t* rs, + int64_t* hs) { + if (t->rank >= 3) { + const uint32_t k = t->rank; + if (t->shape[k - 1] != hd || t->shape[k - 2] != heads || t->stride[k - 1] != 1) return false; + int64_t n = 1; + for (uint32_t i = 0; i + 2 < k; ++i) n *= t->shape[i]; + for (uint32_t i = 0; i + 3 < k; ++i) + if (t->shape[i] > 1 && t->stride[i] != t->stride[i + 1] * t->shape[i + 1]) return false; + *rows = n; *rs = t->stride[k - 3]; *hs = t->stride[k - 2]; + return true; + } + if (t->rank == 2) { + if (t->shape[1] != heads * hd || t->stride[1] != 1) return false; + *rows = t->shape[0]; *rs = t->stride[0]; *hs = hd; + return true; + } + if (t->rank == 1) { + if (t->shape[0] % (heads * hd)) return false; + *rows = t->shape[0] / (heads * hd); *rs = heads * hd; *hs = hd; + return true; + } + return false; +} + +template +static constexpr int64_t part_bytes() { + return (int64_t)kPartBudget * Geo::R * (HD + 4) * (int64_t)sizeof(float); +} +template +static constexpr int64_t scratch_need() { + return part_bytes() + (int64_t)kTinfoMax * 2 * (int64_t)sizeof(int); +} + +template +static int launch_attn(const RadArgs* a, RadStream stream) { + constexpr int R = Geo::R, BK = Geo::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2; + if (!a || a->n_t < 8) return RAD_E_INVAL; + const RadTensor* q = rad_arg_in(a, 0); + const RadTensor* kv = rad_arg_in(a, 1); + const RadTensor* bt = rad_arg_in(a, 2); + const RadTensor* su = rad_arg_in(a, 3); + const RadTensor* kd = rad_arg_in(a, 4); + const RadTensor* vd = rad_arg_in(a, 5); + const RadTensor* cu = rad_arg_in(a, 6); + const RadTensor* o = rad_arg_in(a, 7); + if (!q || !kv || !bt || !su || !o) return RAD_E_INVAL; + + if (rad_args_geti_or(a, "head_dim", HD) != HD || rad_args_geti_or(a, "gqa", GQA) != GQA || + rad_args_geti_or(a, "block_size", 16) != 16) + return RAD_E_SHAPE; + const long long causal = rad_args_geti_or(a, "causal", 1); + const long long window = rad_args_geti_or(a, "window", 0); + if ((causal != 0 && causal != 1) || window < 0 || window > (1ll << 30)) return RAD_E_SHAPE; + + if (q->dtype != RAD_BF16 || o->dtype != RAD_BF16) return RAD_E_DTYPE; + if (kv->dtype != (uint32_t)(KV8 ? RAD_F8E4M3 : RAD_BF16)) return RAD_E_DTYPE; + if (bt->dtype != RAD_I32 || su->dtype != RAD_I32 || (cu && cu->dtype != RAD_I32)) return RAD_E_DTYPE; + if ((kd && kd->dtype != RAD_F32) || (vd && vd->dtype != RAD_F32)) return RAD_E_DTYPE; + + /* the cache: [n_blocks, kv_heads, 16, 2 * head_dim], slots dense */ + if (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * HD) return RAD_E_SHAPE; + if (kv->stride[3] != 1 || kv->stride[2] != 2 * HD) return RAD_E_STRIDE; + const int64_t kvh = kv->shape[1]; + if (kvh <= 0 || kvh > 65535) return RAD_E_SHAPE; + const int64_t qh = kvh * GQA; + + int64_t rows = 0, q_rs = 0, q_hs = 0, orows = 0, o_rs = 0, o_hs = 0; + if (!head_view(q, qh, HD, &rows, &q_rs, &q_hs) || !head_view(o, qh, HD, &orows, &o_rs, &o_hs)) + return RAD_E_SHAPE; + if (orows < rows) return RAD_E_SHAPE; + const int64_t n_seq = rad_tensor_numel(su); + if (rows == 0) return RAD_OK; + if (n_seq <= 0 || n_seq > (1 << 24)) return RAD_E_SHAPE; + + /* the block table: [n_seq, max_blocks] with a row pitch, or flat */ + int64_t max_blocks = 0, bt_rs = 0; + if (bt->rank >= 2) { + if (bt->stride[bt->rank - 1] != 1) return RAD_E_STRIDE; + max_blocks = bt->shape[bt->rank - 1]; + bt_rs = bt->stride[bt->rank - 2]; + if (rad_tensor_numel(bt) / max_blocks < n_seq) return RAD_E_SHAPE; + } else { + max_blocks = rad_tensor_numel(bt) / n_seq; + bt_rs = max_blocks; + } + if (max_blocks <= 0 || max_blocks > (1 << 26)) return RAD_E_SHAPE; + if ((kd && rad_tensor_numel(kd) < n_seq * kvh) || (vd && rad_tensor_numel(vd) < n_seq * kvh)) + return RAD_E_SHAPE; + + /* 8-byte query/output chunks, 16-byte cache loads */ + if (!rad_ptr_aligned(q->data, 8) || !rad_ptr_aligned(o->data, 8) || (q_rs | q_hs | o_rs | o_hs) % 4) + return RAD_E_ALIGN; + if (!rad_ptr_aligned(kv->data, 16) || (kv->stride[0] * ESZ) % 16 || (kv->stride[1] * ESZ) % 16) + return RAD_E_ALIGN; + + /* the tiles: uniform, or an upper bound over a ragged batch (empty tiles exit at once) */ + int64_t nt = 0, tps = 0, qlen_u = 0; + if (!cu) { + if (rows % n_seq) return RAD_E_SHAPE; + qlen_u = rows / n_seq; + tps = (qlen_u + BQ - 1) / BQ; + nt = n_seq * tps; + } else { + if (rad_tensor_numel(cu) != n_seq + 1) return RAD_E_SHAPE; + int64_t qmax = rad_args_geti_or(a, "q_len", rows); + if (qmax <= 0 || qmax > rows) qmax = rows; + const int64_t b1 = (rows + n_seq * (BQ - 1)) / BQ; + const int64_t b2 = n_seq * ((qmax + BQ - 1) / BQ); + nt = b1 < b2 ? b1 : b2; + } + if (nt <= 0) return RAD_OK; + if (nt > 0x7fffffff) return RAD_E_SHAPE; + + /* THE WMMA PATH, for a prefill-shaped step: the longest query at least kWmmaMinQ rows and the + * mean at least half that -- a decode or verify batch, a few rows a sequence however many + * sequences, keeps the scalar kernel and its split-KV below. 16-byte query and output rows. + * Both forms agree with libref's attention within 0.02 on the engine's own operands (the op + * oracle, Gemma 4 26B-A4B at two ranks); they differ from each other by summation order. */ + { + int64_t qmax_w = qlen_u; + if (cu) { + qmax_w = rad_args_geti_or(a, "q_len", rows); + if (qmax_w <= 0 || qmax_w > rows) qmax_w = rows; + } + const bool shaped = qmax_w >= kWmmaMinQ && rows >= n_seq * (kWmmaMinQ / 2); + const bool aligned = rad_ptr_aligned(q->data, 16) && rad_ptr_aligned(o->data, 16) && + (q_rs | q_hs | o_rs | o_hs) % 8 == 0; + if (shaped && aligned) { + constexpr int BQW = WGeo::R / GQA; + int64_t ntw = 0, tpsw = 0; + if (!cu) { + tpsw = (qlen_u + BQW - 1) / BQW; + ntw = n_seq * tpsw; + } else { + const int64_t b1 = (rows + n_seq * (BQW - 1)) / BQW; + const int64_t b2 = n_seq * ((qmax_w + BQW - 1) / BQW); + ntw = b1 < b2 ? b1 : b2; + } + if (ntw <= 0) return RAD_OK; + if (ntw > 0x7fffffff) return RAD_E_SHAPE; + AttnArgs W{}; + W.q = (const uint16_t*)q->data; W.q_rs = q_rs; W.q_hs = q_hs; + W.kv = (const unsigned char*)kv->data; W.kv_sb = kv->stride[0]; W.kv_sh = kv->stride[1]; + W.bt = (const int*)bt->data; W.bt_rs = bt_rs; + W.seqused = (const int*)su->data; + W.cu = cu ? (const int*)cu->data : nullptr; + W.kdes = kd ? (const float*)kd->data : nullptr; + W.vdes = vd ? (const float*)vd->data : nullptr; + W.out = (uint16_t*)o->data; W.o_rs = o_rs; W.o_hs = o_hs; + const double wscale = rad_args_getf_or(a, "scale", 1.0 / __builtin_sqrt((double)HD)); + W.qscale = (float)(wscale * 1.4426950408889634); + W.max_blocks = (int)max_blocks; + W.n_seq = (int)n_seq; + W.q_len = (int)qlen_u; + W.tps = (int)tpsw; + W.kv_heads = (int)kvh; + W.causal = (int)causal; + W.window = (int)window; + W.n_split = 1; + R4D_KLAUNCH(R4D_KNAME(attn_wmma_kernel), dim3((unsigned)ntw, (unsigned)kvh, 1u), + dim3(kWThreads), (hipStream_t)stream, W); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; + } + } + + /* SPLIT-KV: only where (tile, kv head) pairs are too few to fill the card */ + int64_t ns = 1; + const int64_t pairs = nt * kvh; + if (pairs < kTinfoMax) { + ns = kPartBudget / pairs; + if (ns > kMaxSplit) ns = kMaxSplit; + const int64_t span = window > 0 ? window + BQ + : rad_args_geti_or(a, "max_ctx", max_blocks * 16); + const int64_t nkt = (span + BK - 1) / BK + 1; + if (ns > nkt / 2) ns = nkt / 2; + if (ns < 1) ns = 1; + if (ns > 1 && (!a->scratch || a->scratch_bytes < scratch_need() || + !rad_ptr_aligned(a->scratch, 16))) + ns = 1; /* never wrong, only slower: the unsplit kernel writes the rows itself */ + } + + AttnArgs A{}; + A.q = (const uint16_t*)q->data; A.q_rs = q_rs; A.q_hs = q_hs; + A.kv = (const unsigned char*)kv->data; A.kv_sb = kv->stride[0]; A.kv_sh = kv->stride[1]; + A.bt = (const int*)bt->data; A.bt_rs = bt_rs; + A.seqused = (const int*)su->data; + A.cu = cu ? (const int*)cu->data : nullptr; + A.kdes = kd ? (const float*)kd->data : nullptr; + A.vdes = vd ? (const float*)vd->data : nullptr; + A.out = (uint16_t*)o->data; A.o_rs = o_rs; A.o_hs = o_hs; + A.part = ns > 1 ? (float*)a->scratch : nullptr; + A.tinfo = ns > 1 ? (int*)((char*)a->scratch + part_bytes()) : nullptr; + const double scale = rad_args_getf_or(a, "scale", 1.0 / __builtin_sqrt((double)HD)); + A.qscale = (float)(scale * 1.4426950408889634); + A.max_blocks = (int)max_blocks; + A.n_seq = (int)n_seq; + A.q_len = (int)qlen_u; + A.tps = (int)tps; + A.kv_heads = (int)kvh; + A.causal = (int)causal; + A.window = (int)window; + A.n_split = (int)ns; + + hipStream_t s = (hipStream_t)stream; + R4D_KLAUNCH(R4D_KNAME(attn_kernel), dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), + dim3(kThreads), s, A); + if (ns > 1) + R4D_KLAUNCH(R4D_KNAME(merge_kernel), dim3((unsigned)nt, (unsigned)kvh), dim3(kThreads), + s, A); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +} /* namespace r4d_win */ + +/* ------------------------------------------------------------------ the exported entry points */ +extern "C" { + +#define R4D_WIN_DEF(HD, G) \ + int r4d_rad_attn_window_h##HD##_gqa##G##_bf16(const RadArgs* a, RadStream s) { \ + return r4d_win::launch_attn(a, s); \ + } \ + int r4d_rad_attn_window_h##HD##_gqa##G##_fp8(const RadArgs* a, RadStream s) { \ + return r4d_win::launch_attn(a, s); \ + } +R4D_WIN_DEF(256, 1) R4D_WIN_DEF(256, 2) R4D_WIN_DEF(256, 4) R4D_WIN_DEF(256, 8) +R4D_WIN_DEF(512, 1) R4D_WIN_DEF(512, 2) R4D_WIN_DEF(512, 4) R4D_WIN_DEF(512, 8) +#undef R4D_WIN_DEF + +/* Called at declare with the band's bound and no tensors: the split-KV partials are capped at + * kPartBudget (tile, head, split) triples whatever the batch, so the answer is a constant. */ +int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*) { return r4d_win::scratch_need<256>(); } +int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*) { return r4d_win::scratch_need<512>(); } + +} /* extern "C" */ diff --git a/libr4d/r4d_expert_scale_bf16.hip b/libr4d/r4d_expert_scale_bf16.hip new file mode 100644 index 00000000..650f4561 --- /dev/null +++ b/libr4d/r4d_expert_scale_bf16.hip @@ -0,0 +1,87 @@ +/* r4d_expert_scale_bf16.hip -- expert_scale: each routing weight times its expert's own scale, in place. + * + * Gemma 4's router renormalises its top-k and then multiplies each weight by per_expert_scale of + * the expert it chose. Said in the conventional vocabulary that is two launches a MoE layer -- an + * `embed_lookup` of the [n_expert, 1] scale table by the expert ids, then a `mul` into the weights + * -- each a few dozen elements behind a full dispatch at decode. This is the pair as one: + * + * ew[t, k] = bf16( ew[t, k] * scale[ids[t, k]] ) + * + * THE CHAIN'S VALUE, BIT FOR BIT: the lookup copies a bf16 scale and the multiply is one f32 + * product rounded once to nearest even, which is all this does. An id outside the table reads a + * zero scale, as embed_lookup writes a zero row for an id it does not hold, and the product's sign + * survives it the same way. One thread an element; a decode step is a handful of rows. + */ +#include + +#include + +#include "r4d_plugin.h" +#include "r4d_launch.h" +#include "rad_plugin.h" + +namespace r4d_escale { + +struct EscaleArgs { + const int32_t* ids; long long ids_ld; + const uint16_t* sc; /* [n_expert], bf16 */ + uint16_t* ew; long long ew_ld; + long long rows; + int k, n_expert; +}; + +__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((unsigned)h << 16); } +__device__ __forceinline__ uint16_t f2bf(float f) { + const unsigned u = __float_as_uint(f); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +__global__ __launch_bounds__(256) void expert_scale_kernel(EscaleArgs A) { + const long long e = (long long)blockIdx.x * 256 + threadIdx.x; + if (e >= A.rows * A.k) return; + const long long r = e / A.k; + const int c = (int)(e - r * A.k); + const int id = A.ids[r * A.ids_ld + c]; + const float s = (id >= 0 && id < A.n_expert) ? bf2f(A.sc[id]) : 0.0f; + uint16_t* w = A.ew + r * A.ew_ld + c; + *w = f2bf(bf2f(*w) * s); +} + +/* [rows, k] with a dense last axis: its rows and row pitch, or false */ +static bool rows_k(const RadTensor* t, uint32_t dt, int64_t k, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != dt || t->rank < 1) return false; + if (rad_tensor_lastdim(t) != k || t->stride[t->rank - 1] != 1) return false; + *rows = rad_tensor_rows(t); + *ld = rad_tensor_row_pitch(t); + return *ld >= k || *rows <= 1; +} + +} /* namespace r4d_escale */ + +extern "C" { + +/* operands: ids, w_e (the [n_expert] scale table), ew (inout) */ +int r4d_rad_expert_scale_bf16(const RadArgs* a, RadStream stream) { + using namespace r4d_escale; + if (!a || a->n_t < 3) return RAD_E_INVAL; + const int64_t k = rad_args_geti_or(a, "top_k", 0), ne = rad_args_geti_or(a, "n_expert", 0); + if (k <= 0 || k > 64 || ne <= 0 || ne > (1 << 20)) return RAD_E_SHAPE; + const RadTensor *I = rad_arg_in(a, 0), *S = rad_arg_in(a, 1), *W = rad_arg_in(a, 2); + if (!I || !S || !W) return RAD_E_INVAL; + if (S->dtype != RAD_BF16 || rad_tensor_numel(S) < ne) return RAD_E_DTYPE; + int64_t ri = 0, li = 0, rw = 0, lw = 0; + if (!rows_k(I, RAD_I32, k, &ri, &li) || !rows_k(W, RAD_BF16, k, &rw, &lw)) return RAD_E_SHAPE; + const int64_t M = rw; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (ri < M || M * k > 0x7fffffff) return RAD_E_SHAPE; + EscaleArgs P{}; + P.ids = (const int32_t*)I->data; P.ids_ld = li; + P.sc = (const uint16_t*)S->data; + P.ew = (uint16_t*)W->data; P.ew_ld = lw; + P.rows = M; P.k = (int)k; P.n_expert = (int)ne; + const unsigned blocks = (unsigned)((M * k + 255) / 256); + R4D_KLAUNCH(R4D_KNAME(expert_scale_kernel), dim3(blocks), dim3(256), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +} /* extern "C" */ diff --git a/libr4d/r4d_launch.h b/libr4d/r4d_launch.h new file mode 100644 index 00000000..3d3cd321 --- /dev/null +++ b/libr4d/r4d_launch.h @@ -0,0 +1,15 @@ +/* r4d_launch.h -- the one spelling of a kernel launch in the libr4d units tests/r4d_emu runs on the + * host: the windowed paged attention, pair_argmax, the sandwich-norm joins and expert_scale. + * + * A template kernel's name carries commas, so it goes through R4D_KNAME the way HIP_KERNEL_NAME + * exists for hipLaunchKernelGGL. R4D_KLAUNCH is overridable so the same sources can be driven by a + * host-side SIMT emulator in a test -- the kernels are ordinary C++ once the HIP names are + * supplied. A build never defines it, and gets the triple-chevron launch, which the engine answers + * through hipLaunchKernel on its own queues (docs/PLUGIN.md §5). */ +#ifndef R4D_LAUNCH_H +#define R4D_LAUNCH_H +#define R4D_KNAME(...) __VA_ARGS__ +#ifndef R4D_KLAUNCH +#define R4D_KLAUNCH(kernel, grid, block, stream, ...) kernel<<>>(__VA_ARGS__) +#endif +#endif diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index e56c8bef..8cfff398 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -338,13 +338,18 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel( // ref_logit_softcap: y = cap * tanh(x / cap), the final-logit softcap. THE ROW-WISE-WITH-A-PITCH // SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the logits_gemm's output, // and the pitch form costs nothing on a contiguous buffer -- it is x_ld == n. +// +// A ROW IS SPREAD OVER gridDim.y BLOCKS, because a row is a vocabulary shard: 65536 wide at Gemma +// 4's tp 4, and the step's rows are a decode's few. One block a row walked 256 elements a thread of +// tanhf on a handful of CUs -- ~85 us at one row, --profile-ops on an R9700, for 256 KiB of f32. +// Elementwise, so the spread moves no bits. __global__ __launch_bounds__(kThreads) void logit_softcap_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) { const uint32_t m = blockIdx.x; const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; - for (uint32_t i = threadIdx.x; i < n; i += kThreads) + for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads) yr[i] = f32_to_bf16(cap * tanhf(bf2f(xr[i]) / cap)); } @@ -357,10 +362,16 @@ __global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32( const uint32_t m = blockIdx.x; const float* __restrict__ xr = x + (size_t)m * x_ld; float* __restrict__ yr = y + (size_t)m * y_ld; - for (uint32_t i = threadIdx.x; i < n; i += kThreads) + for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads) yr[i] = cap * tanhf(xr[i] / cap); } +/* The blocks a softcap row is spread over: eight elements a thread, at most 64 blocks a row. */ +static uint32_t softcap_blocks_per_row(int n) { + uint32_t b = (uint32_t)((n + kThreads * 8 - 1) / (kThreads * 8)); + return b < 1 ? 1 : (b > 64 ? 64 : b); +} + // ---------------------------------------------------------------------------- scale // ref_scale: y = x * s, s a [1] weight broadcast over every element. THE ROW-WISE-WITH-A-PITCH // SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the residual stream at @@ -915,7 +926,8 @@ extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap, if (!(cap > 0.0f)) return -3; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; - hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M, softcap_blocks_per_row(n)), + dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (uint16_t*)y, (uint32_t)n, cap, (uint32_t)x_ld, (uint32_t)y_ld); @@ -929,7 +941,8 @@ extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap, if (!(cap > 0.0f)) return -3; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; - hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M), dim3(kThreads), 0, + hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M, softcap_blocks_per_row(n)), + dim3(kThreads), 0, (hipStream_t)stream, (const float*)x, (float*)y, (uint32_t)n, cap, (uint32_t)x_ld, (uint32_t)y_ld); diff --git a/libr4d/r4d_norm_join_bf16.hip b/libr4d/r4d_norm_join_bf16.hip new file mode 100644 index 00000000..c74f80fc --- /dev/null +++ b/libr4d/r4d_norm_join_bf16.hip @@ -0,0 +1,434 @@ +/* r4d_norm_join_bf16.hip -- Gemma 4's sandwich-norm joins, each one kernel instead of a chain of small ones. + * + * A decode step of the 26B-A4B launches ~250 rmsnorms and ~90 adds a step, each a few hundred + * bytes of work behind a full launch: --profile-ops measured 2.0 ms and 0.85 ms of a 16.6 ms step. + * Two places in every layer are pure chains of them: + * + * norm_add_norm the attention's join: t = norm(a) * w_a; x += t; y = norm(x) * w_y + * (post_attention_layernorm, the residual add, pre_feedforward_layernorm) + * join_add_scale the feed-forward's: d' = norm(d) * w_d; r' = norm(r) * w_r; + * j = norm(d' + r') * w_j; x = (x + j) * s; and optionally y = norm(x) * w_n + * (post_feedforward_layernorm_1 and _2, the arms' sum, post_feedforward_layernorm, + * the residual add, layer_scalar -- and the NEXT layer's input_layernorm, or the + * final norm after the last layer, which read the x this writes) + * + * THE SAME FUNCTION AS THE CHAIN, ROUNDING FOR ROUNDING. Every value the chain stores as bf16 is + * rounded to bf16 here at the same point, and every element is computed with libr4d's own + * expression: a norm is bf16((v * rsqrtf(mean(v^2) + eps)) * g), an add bf16(u + v), a scale + * bf16(x * s). The one thing that can differ is the ORDER the sum of squares is added in -- libr4d + * picks its block width from a measured table -- which moves the f32 norm factor by an ulp at most + * and, rarely, a bf16 output by one ulp. The arch plugin asks for these first and falls back to + * the chain where nothing serves them (gemma4.cpp). + * + * AND THE ROUTED ARM'S TWO INPUTS (norm_add_norm_route). The 26B-A4B's router reads norm(x) * w_r * + * hidden^-0.5 and its experts norm(x) * w_e, quantised to E4M3 -- two more launches a layer + * (`rmsnorm`, `rmsnorm_quant_fp8`), each reading back the x norm_add_norm has just written and + * taking the sum of squares norm_add_norm has just taken. The route form writes both from the norm + * factor it holds: the router's row by libr4d's rmsnorm expression, ((x * s) * w) * mult, and the + * experts' codes as libr4d's rmsnorm_quant_fp8 writes them -- the bf16-rounded norm, a scale of + * amax * (1 / 448) a 128 columns (1 where the group is all zero), the value times its reciprocal + * clamped to +-448, one v_cvt_pk_fp8_f32. Element i is thread i % 256 at slot i / 256, so a group + * is four waves at one slot: a wave's max, then the four. + * + * One 256-thread block a row: a decode step is a handful of rows, so the row is latency-bound and + * a block's three reductions beat seven launches. Values a later stage reuses stay in registers + * (PER a thread, 12 to n = 3072 and kMaxPer = 24 to 6144; the row table says so). + * + * EVERY LOAD IS ISSUED FIRST. A barrier is a fence, so a load written after a reduction waits for + * it: the first version fetched the gains, the residual and the layer scalar phase by phase and + * paid a global round trip for each on top of the reductions -- 17.8 us for join_add_scale and 13.2 + * for norm_add_norm at decode under --profile-ops, against ~7 for a launch that does nothing. Now + * the row's every operand is in flight at once, the two arm norms share one barrier pair, and a + * thread holds the elements it touches and no more. Nothing about the arithmetic moved: the same + * expressions in the same order, a sum's extra terms past n were +0. + */ +#include + +#include + +#include "r4d_plugin.h" +#include "r4d_launch.h" +#include "rad_plugin.h" + +namespace r4d_join { + +constexpr int kThreads = 256; +constexpr int kWaves = kThreads / 32; +constexpr int kMaxPer = 24; /* elements a thread holds: n <= 6144 */ + +__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((unsigned)h << 16); } +/* round to nearest even, as libr4d's f32_to_bf16 */ +__device__ __forceinline__ uint16_t f2bf(float f) { + const unsigned u = __float_as_uint(f); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} +__device__ __forceinline__ float rbf(float f) { return bf2f(f2bf(f)); } +__device__ __forceinline__ int lane_id() { return (int)(threadIdx.x & 31u); } +__device__ __forceinline__ float shfl_xor(float v, int m) { + return __int_as_float(__builtin_amdgcn_ds_bpermute((lane_id() ^ m) << 2, __float_as_int(v))); +} +/* the block's sum, every thread the same value: a wave butterfly, then the waves in order */ +__device__ __forceinline__ float block_sum(float v, float* lds) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) v += shfl_xor(v, d); + const int lane = lane_id(), wave = (int)(threadIdx.x >> 5); + __syncthreads(); /* lds is free: the last read of it is done */ + if (lane == 0) lds[wave] = v; + __syncthreads(); + float s = 0.0f; +#pragma unroll + for (int w = 0; w < kWaves; ++w) s += lds[w]; + return s; +} +/* two block sums for one barrier pair: each value takes block_sum's butterfly and wave order */ +__device__ __forceinline__ void block_sum2(float& a, float& b, float* lds) { +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) { a += shfl_xor(a, d); b += shfl_xor(b, d); } + const int lane = lane_id(), wave = (int)(threadIdx.x >> 5); + __syncthreads(); + if (lane == 0) { lds[wave] = a; lds[kWaves + wave] = b; } + __syncthreads(); + float sa = 0.0f, sb = 0.0f; +#pragma unroll + for (int w = 0; w < kWaves; ++w) { sa += lds[w]; sb += lds[kWaves + w]; } + a = sa; + b = sb; +} +__device__ __forceinline__ float norm_factor(float ss, int n, float eps) { + return rsqrtf(ss / (float)n + eps); +} + +struct NormArgs { + const uint16_t* a; long long a_ld; /* norm_add_norm: the block output */ + const uint16_t* d; long long d_ld; /* join_add_scale: the dense partial */ + const uint16_t* r; long long r_ld; /* the routed partial */ + uint16_t* x; long long x_ld; /* the residual stream, read and written */ + uint16_t* y; long long y_ld; /* norm_add_norm: the next norm's output */ + const float* w0; /* w_a, or w_d */ + const float* w1; /* w_y, or w_r */ + const float* w2; /* w_j */ + const float* w3; /* w_n, the next norm's gain (or null) */ + const uint16_t* s; /* the layer scalar, bf16, one element */ + /* norm_add_norm_route: the router's input, the experts' codes and their scales; the router's + * gain is w2 and the experts' w3 */ + uint16_t* rt; long long rt_ld; + uint8_t* q; long long q_ld; + float* qs; long long qs_ld; + float mult; + int n; + float eps; +}; + +/* t = norm(a) * w_a; x += t; y = norm(x) * w_y -- and with ROUTE, from the same norm of x, the + * router's input norm(x) * w_r * mult and the experts' norm(x) * w_e as E4M3 codes and scales */ +template +__global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { + __shared__ float lds[kWaves]; + __shared__ float gmax[ROUTE ? PER * kWaves : 1]; + const int tid = (int)threadIdx.x, n = A.n; + const long long m = (long long)blockIdx.x; + const uint16_t* ar = A.a + m * A.a_ld; + uint16_t* xr = A.x + m * A.x_ld; + uint16_t* yr = A.y + m * A.y_ld; + + /* every operand of the row in flight at once: the block output, the residual, the gains */ + float av[PER], xv[PER], wa[PER], wy[PER], wr[ROUTE ? PER : 1], we[ROUTE ? PER : 1]; +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + const bool in = i < n; + av[k] = in ? bf2f(ar[i]) : 0.0f; + xv[k] = in ? bf2f(xr[i]) : 0.0f; + wa[k] = in ? A.w0[i] : 0.0f; + wy[k] = in ? A.w1[i] : 0.0f; + if constexpr (ROUTE) { + wr[k] = in ? A.w2[i] : 0.0f; + we[k] = in ? A.w3[i] : 0.0f; + } + } + float ss = 0.0f; +#pragma unroll + for (int k = 0; k < PER; ++k) ss += av[k] * av[k]; + const float sa = norm_factor(block_sum(ss, lds), n, A.eps); + ss = 0.0f; +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + if (i < n) { + const float t = rbf((av[k] * sa) * wa[k]); + xv[k] = rbf(xv[k] + t); + xr[i] = f2bf(xv[k]); + } + ss += xv[k] * xv[k]; + } + const float sx = norm_factor(block_sum(ss, lds), n, A.eps); + uint16_t* rr = ROUTE ? A.rt + m * A.rt_ld : nullptr; +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + if (i < n) { + yr[i] = f2bf((xv[k] * sx) * wy[k]); + if constexpr (ROUTE) { + rr[i] = f2bf(((xv[k] * sx) * wr[k]) * A.mult); + av[k] = rbf((xv[k] * sx) * we[k]); /* the experts' row, as quantised */ + } + } else if constexpr (ROUTE) { + av[k] = 0.0f; + } + } + if constexpr (ROUTE) { + /* group 2k + tid / 128 at slot k is waves 0..3 or 4..7: each wave's max, then its four */ + const int wave = tid >> 5, half = tid >> 7; +#pragma unroll + for (int k = 0; k < PER; ++k) { + float mx = fabsf(av[k]); +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) mx = fmaxf(mx, shfl_xor(mx, d)); + if (lane_id() == 0) gmax[k * kWaves + wave] = mx; + } + __syncthreads(); + uint8_t* qr = A.q + m * A.q_ld; + float* sr = A.qs + m * A.qs_ld; +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + if (i >= n) continue; /* n is whole groups: a group is in or out */ + const float* g = gmax + k * kWaves + 4 * half; + const float am = fmaxf(fmaxf(g[0], g[1]), fmaxf(g[2], g[3])); + const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f; + const float inv = 1.0f / sc; + const float v = fminf(fmaxf(av[k] * inv, -448.0f), 448.0f); + qr[i] = (uint8_t)(__builtin_amdgcn_cvt_pk_fp8_f32(v, v, 0, false) & 0xff); + if ((tid & 127) == 0) sr[i >> 7] = sc; + } + } +} + +/* x = (x + norm(norm(d) * w_d + norm(r) * w_r) * w_j) * s, and with NEXT y = norm(x) * w_n: the + * next layer's input norm taken over the bf16 x this stores, which is what that norm would read. */ +template +__global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { + __shared__ float lds[2 * kWaves]; + const int tid = (int)threadIdx.x, n = A.n; + const long long m = (long long)blockIdx.x; + const uint16_t* dr = A.d + m * A.d_ld; + const uint16_t* rr = A.r + m * A.r_ld; + uint16_t* xr = A.x + m * A.x_ld; + + /* every operand of the row in flight at once: both arms, the residual, the three gains (four + * with the next norm's) and the layer scalar */ + float dv[PER], rv[PER], xo[PER], wd[PER], wr[PER], wj[PER], wn[NEXT ? PER : 1]; + const float sc = bf2f(*A.s); +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + const bool in = i < n; + dv[k] = in ? bf2f(dr[i]) : 0.0f; + rv[k] = in ? bf2f(rr[i]) : 0.0f; + xo[k] = in ? bf2f(xr[i]) : 0.0f; + wd[k] = in ? A.w0[i] : 0.0f; + wr[k] = in ? A.w1[i] : 0.0f; + wj[k] = in ? A.w2[i] : 0.0f; + if constexpr (NEXT) wn[k] = in ? A.w3[i] : 0.0f; + } + float sd2 = 0.0f, sr2 = 0.0f; +#pragma unroll + for (int k = 0; k < PER; ++k) { + sd2 += dv[k] * dv[k]; + sr2 += rv[k] * rv[k]; + } + block_sum2(sd2, sr2, lds); + const float sd = norm_factor(sd2, n, A.eps); + const float sr = norm_factor(sr2, n, A.eps); + /* the join, kept in dv */ + float ss = 0.0f; +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + if (i < n) { + const float u = rbf((dv[k] * sd) * wd[k]); + const float v = rbf((rv[k] * sr) * wr[k]); + dv[k] = rbf(u + v); + } + ss += dv[k] * dv[k]; + } + const float sj = norm_factor(block_sum(ss, lds), n, A.eps); + ss = 0.0f; +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + if (i < n) { + const float j = rbf((dv[k] * sj) * wj[k]); + const float x1 = rbf(xo[k] + j); + const uint16_t xn = f2bf(x1 * sc); + xr[i] = xn; + rv[k] = bf2f(xn); /* the new x, kept for the next norm */ + } else { + rv[k] = 0.0f; + } + if (NEXT) ss += rv[k] * rv[k]; + } + if (NEXT) { + const float sn = norm_factor(block_sum(ss, lds), n, A.eps); + uint16_t* yr = A.y + m * A.y_ld; +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + if (i < n) yr[i] = f2bf((rv[k] * sn) * wn[k]); + } + } +} + +/* ------------------------------------------------------------------ host: the launch adapters */ + +/* [rows..., n] of `dt` with a dense last axis: its row count and pitch, or false */ +static bool rows_as(const RadTensor* t, uint32_t dt, int64_t n, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != dt || t->rank < 1) return false; + if (rad_tensor_lastdim(t) != n || (t->stride[t->rank - 1] != 1)) return false; + *rows = rad_tensor_rows(t); + *ld = rad_tensor_row_pitch(t); + return *ld >= n || *rows <= 1; +} +static bool rows_of(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) { + return rows_as(t, RAD_BF16, n, rows, ld); +} +static bool gain(const RadTensor* w, int64_t n) { + return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n && + (w->rank == 0 || w->stride[w->rank - 1] == 1); +} + +static int params(const RadArgs* a, int64_t* n, float* eps) { + *n = rad_args_geti_or(a, "n", 0); + *eps = (float)rad_args_getf_or(a, "eps", 1e-6); + if (*n <= 0 || *n > (int64_t)kThreads * kMaxPer) return RAD_E_SHAPE; + return RAD_OK; +} + +} /* namespace r4d_join */ + +extern "C" { + +/* operands: a, w_a, x (inout), w_y, y */ +int r4d_rad_norm_add_norm_bf16(const RadArgs* a, RadStream stream) { + using namespace r4d_join; + if (!a || a->n_t < 5) return RAD_E_INVAL; + int64_t n = 0; + float eps = 0.0f; + if (int rc = params(a, &n, &eps)) return rc; + const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2), + *Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4); + if (!A_ || !X || !Y) return RAD_E_INVAL; + if (!gain(Wa, n) || !gain(Wy, n)) return RAD_E_DTYPE; + int64_t ra = 0, la = 0, rx = 0, lx = 0, ry = 0, ly = 0; + if (!rows_of(A_, n, &ra, &la) || !rows_of(X, n, &rx, &lx) || !rows_of(Y, n, &ry, &ly)) + return RAD_E_SHAPE; + const int64_t M = rx; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (ra < M || ry < M || M > 0x7fffffff) return RAD_E_SHAPE; + NormArgs P{}; + P.a = (const uint16_t*)A_->data; P.a_ld = la; + P.x = (uint16_t*)X->data; P.x_ld = lx; + P.y = (uint16_t*)Y->data; P.y_ld = ly; + P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data; + P.n = (int)n; P.eps = eps; + if (n <= (int64_t)kThreads * 12) + R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<12, false>), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); + else + R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel), dim3((unsigned)M), + dim3(kThreads), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +/* operands: a, w_a, x (inout), w_y, y, w_r, r, w_e, q, qs */ +int r4d_rad_norm_add_norm_route_bf16(const RadArgs* a, RadStream stream) { + using namespace r4d_join; + if (!a || a->n_t < 10) return RAD_E_INVAL; + int64_t n = 0; + float eps = 0.0f; + if (int rc = params(a, &n, &eps)) return rc; + if (n % 128 || rad_args_geti_or(a, "group", 0) != 128) return RAD_E_SHAPE; + const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2), + *Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4), *Wr = rad_arg_in(a, 5), + *R = rad_arg_in(a, 6), *We = rad_arg_in(a, 7), *Q = rad_arg_in(a, 8), + *S = rad_arg_in(a, 9); + if (!A_ || !X || !Y || !R || !Q || !S) return RAD_E_INVAL; + if (!gain(Wa, n) || !gain(Wy, n) || !gain(Wr, n) || !gain(We, n)) return RAD_E_DTYPE; + int64_t ra = 0, la = 0, rx = 0, lx = 0, ry = 0, ly = 0, rr = 0, lr = 0, rq = 0, lq = 0, + rs = 0, ls = 0; + if (!rows_of(A_, n, &ra, &la) || !rows_of(X, n, &rx, &lx) || !rows_of(Y, n, &ry, &ly) || + !rows_of(R, n, &rr, &lr) || !rows_as(Q, RAD_F8E4M3, n, &rq, &lq) || + !rows_as(S, RAD_F32, n / 128, &rs, &ls)) + return RAD_E_SHAPE; + const int64_t M = rx; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (ra < M || ry < M || rr < M || rq < M || rs < M || M > 0x7fffffff) return RAD_E_SHAPE; + NormArgs P{}; + P.a = (const uint16_t*)A_->data; P.a_ld = la; + P.x = (uint16_t*)X->data; P.x_ld = lx; + P.y = (uint16_t*)Y->data; P.y_ld = ly; + P.rt = (uint16_t*)R->data; P.rt_ld = lr; + P.q = (uint8_t*)Q->data; P.q_ld = lq; + P.qs = (float*)S->data; P.qs_ld = ls; + P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data; + P.w2 = (const float*)Wr->data; P.w3 = (const float*)We->data; + P.mult = (float)rad_args_getf_or(a, "mult", 1.0); + P.n = (int)n; P.eps = eps; + if (n <= (int64_t)kThreads * 12) + R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel<12, true>), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); + else + R4D_KLAUNCH(R4D_KNAME(norm_add_norm_kernel), dim3((unsigned)M), + dim3(kThreads), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +/* operands: d, w_d, r, w_r, w_j, x (inout), s, w_n?, y? -- the last two both or neither */ +int r4d_rad_join_add_scale_bf16(const RadArgs* a, RadStream stream) { + using namespace r4d_join; + if (!a || a->n_t < 7) return RAD_E_INVAL; + int64_t n = 0; + float eps = 0.0f; + if (int rc = params(a, &n, &eps)) return rc; + const RadTensor *D = rad_arg_in(a, 0), *Wd = rad_arg_in(a, 1), *R = rad_arg_in(a, 2), + *Wr = rad_arg_in(a, 3), *Wj = rad_arg_in(a, 4), *X = rad_arg_in(a, 5), + *Sc = rad_arg_in(a, 6); + if (!D || !R || !X || !Sc) return RAD_E_INVAL; + if (!gain(Wd, n) || !gain(Wr, n) || !gain(Wj, n)) return RAD_E_DTYPE; + if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE; + const RadTensor *Wn = a->n_t > 7 ? rad_arg_in(a, 7) : nullptr, + *Y = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr; + if (!Wn != !Y) return RAD_E_INVAL; + if (Wn && !gain(Wn, n)) return RAD_E_DTYPE; + int64_t rd = 0, ld = 0, rr = 0, lr = 0, rx = 0, lx = 0, ry = 0, ly = 0; + if (!rows_of(D, n, &rd, &ld) || !rows_of(R, n, &rr, &lr) || !rows_of(X, n, &rx, &lx)) + return RAD_E_SHAPE; + if (Y && !rows_of(Y, n, &ry, &ly)) return RAD_E_SHAPE; + const int64_t M = rx; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (rd < M || rr < M || (Y && ry < M) || M > 0x7fffffff) return RAD_E_SHAPE; + NormArgs P{}; + P.d = (const uint16_t*)D->data; P.d_ld = ld; + P.r = (const uint16_t*)R->data; P.r_ld = lr; + P.x = (uint16_t*)X->data; P.x_ld = lx; + P.w0 = (const float*)Wd->data; P.w1 = (const float*)Wr->data; P.w2 = (const float*)Wj->data; + P.s = (const uint16_t*)Sc->data; + if (Y) { P.w3 = (const float*)Wn->data; P.y = (uint16_t*)Y->data; P.y_ld = ly; } + P.n = (int)n; P.eps = eps; + const bool narrow = n <= (int64_t)kThreads * 12; + if (narrow && Y) + R4D_KLAUNCH(R4D_KNAME(join_add_scale_kernel<12, true>), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); + else if (narrow) + R4D_KLAUNCH(R4D_KNAME(join_add_scale_kernel<12, false>), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); + else if (Y) + R4D_KLAUNCH(R4D_KNAME(join_add_scale_kernel), dim3((unsigned)M), + dim3(kThreads), (hipStream_t)stream, P); + else + R4D_KLAUNCH(R4D_KNAME(join_add_scale_kernel), dim3((unsigned)M), + dim3(kThreads), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +} /* extern "C" */ diff --git a/libr4d/r4d_pair_argmax_f32.hip b/libr4d/r4d_pair_argmax_f32.hip new file mode 100644 index 00000000..19c23ec4 --- /dev/null +++ b/libr4d/r4d_pair_argmax_f32.hip @@ -0,0 +1,105 @@ +/* r4d_pair_argmax_f32.hip -- pair_argmax: the global argmax of a row of gathered (id, value) pairs, written as + * ONE CONTIGUOUS COLUMN of token ids. + * + * WHY THIS OP EXISTS. A vocab-sharded draft head finds each rank's best candidates with `row_topk` + * and moves them with `all_gather`. The gather moves whole 16-byte words a row, and one (int32 id, + * f32 value) pair is 8 bytes, so a rank contributes at least R = 2 (rad_block_mtp_hc.h states the + * same bound). `row_topk_merge` then returns R = 2 columns a row, and a BLOCK drafter's proposal + * is `steps` contiguous ids a sequence -- column 0 of an [S, 2] plane is not that, and nothing in + * libr4d copies a strided i32 column. This reduces the gathered row to its top-1 and writes it + * where the proposal reads it. + * + * It is row_topk_merge at R = 1 with a strided output, rule for rule: the largest value wins, a tie + * goes to the LOWER id, and a pair whose id is negative (a slot a shard could not fill) is skipped. + * A row with no valid pair writes id -1 and value -inf. One wave a row, eight rows a workgroup. + */ +#include + +#include + +#include "r4d_plugin.h" +#include "r4d_launch.h" +#include "rad_plugin.h" + +namespace r4d_pick { + +struct PickArgs { + const float* pairs; long long p_rs; /* [M, n, 2]: int32 id bits, then f32 value */ + int* tok; long long t_rs; + float* val; long long v_rs; /* optional */ + long long rows; + int n; +}; + +__device__ __forceinline__ int pk_lane() { return (int)(threadIdx.x & 31u); } +__device__ __forceinline__ int pk_xor_i(int v, int m) { + return __builtin_amdgcn_ds_bpermute((pk_lane() ^ m) << 2, v); +} +__device__ __forceinline__ float pk_xor_f(float v, int m) { + return __int_as_float(pk_xor_i(__float_as_int(v), m)); +} +/* (v, id) beats (bv, bid)? Larger value, then lower id; an invalid id (< 0) never wins. */ +__device__ __forceinline__ bool pk_better(float v, int id, float bv, int bid) { + if (id < 0) return false; + if (bid < 0) return true; + return v > bv || (v == bv && id < bid); +} + +__global__ __launch_bounds__(256) void pick_kernel(PickArgs A) { + const long long r = (long long)blockIdx.x * 8 + (threadIdx.x >> 5); + if (r >= A.rows) return; /* uniform across the wave */ + const int lane = pk_lane(); + const float* row = A.pairs + r * A.p_rs; + float bv = -__builtin_inff(); + int bid = -1; + for (int j = lane; j < A.n; j += 32) { + const int id = __float_as_int(row[2 * j]); + const float v = row[2 * j + 1]; + if (pk_better(v, id, bv, bid)) { bv = v; bid = id; } + } +#pragma unroll + for (int m = 16; m >= 1; m >>= 1) { + const float ov = pk_xor_f(bv, m); + const int oid = pk_xor_i(bid, m); + if (pk_better(ov, oid, bv, bid)) { bv = ov; bid = oid; } + } + if (lane == 0) { + A.tok[r * A.t_rs] = bid; + if (A.val) A.val[r * A.v_rs] = bv; + } +} + +} /* namespace r4d_pick */ + +/* pairs as [M, n, 2] (rank 3) or [M, 2n] (rank 2), last axes dense; the outputs one element a row + * at their own row pitch. */ +extern "C" int r4d_rad_pair_argmax_f32(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const RadTensor* p = rad_arg_in(a, 0); + const RadTensor* t = rad_arg_in(a, 1); + const RadTensor* v = rad_arg_in(a, 2); + if (!p || !t) return RAD_E_INVAL; + if (p->dtype != RAD_F32 || t->dtype != RAD_I32 || (v && v->dtype != RAD_F32)) return RAD_E_DTYPE; + const long long n = rad_args_geti_or(a, "n", 0); + if (n <= 0 || p->rank < 2) return RAD_E_SHAPE; + if (p->rank == 3) { + if (p->shape[1] < n || p->shape[2] != 2 || p->stride[2] != 1 || p->stride[1] != 2) return RAD_E_SHAPE; + } else if (p->rank == 2) { + if (p->shape[1] < 2 * n || p->stride[1] != 1) return RAD_E_SHAPE; + } else { + return RAD_E_SHAPE; + } + const int64_t rows = p->shape[0]; + if (rows == 0) return RAD_OK; + if (t->rank < 1 || t->shape[0] < rows || (v && (v->rank < 1 || v->shape[0] < rows))) return RAD_E_SHAPE; + r4d_pick::PickArgs A{}; + A.pairs = (const float*)p->data; A.p_rs = p->stride[0]; + A.tok = (int*)t->data; A.t_rs = t->rank >= 2 ? t->stride[0] : 1; + A.val = v ? (float*)v->data : nullptr; + A.v_rs = v ? (v->rank >= 2 ? v->stride[0] : 1) : 0; + A.rows = rows; + A.n = (int)n; + R4D_KLAUNCH(R4D_KNAME(r4d_pick::pick_kernel), dim3((unsigned)((rows + 7) / 8)), dim3(256), + (hipStream_t)stream, A); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 21980a6d..9c4503af 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -36,6 +36,14 @@ enum { * caller selecting an entry point by hand would make. */ R4D_PRIO_ATTN_DECODE = 70, R4D_PRIO_ATTN_PREFILL = 60, + /* The windowed kernels (r4d_attn_paged_window.hip) serve every q_len, so where their geometry + * meets another leg's -- h256 at gqa 2 -- they match in both of that leg's bands, and rank + * below both: timed by rad-kbench on two R9700s at the 31B's shapes (window 1024, fp8 cache), + * the h256/gqa2 decode kernel takes 0.26-0.71 of the windowed kernel's time at q_len 1..32 and + * its prefill kernel 0.43-0.67 at 33..512, a bf16 cache the same order. The windowed rows keep + * that geometry's non-causal band past q_len 32, and attn_paged_qrow, which no other kernel + * serves. */ + R4D_PRIO_ATTN_WINDOW = 50, /* At M<=16 with K%256==0 both bf16 skinny rows match and the m16 (dot2) kernel is taken. * The m64 WMMA kernel is faster on every shape measured, so a caller that wants it at low M @@ -97,6 +105,37 @@ int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs*); int r4d_rad_attn_decode_h256_gqa2_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa2_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs*); +/* Paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV head, any window, causal or not + * (r4d_attn_paged_window.hip): one entry point a geometry and cache dtype, serving every q_len and + * reading q at any row pitch, so the same entry points serve attn_paged and attn_paged_qrow. */ +int r4d_rad_attn_window_h256_gqa1_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_window_h256_gqa1_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_window_h256_gqa2_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_window_h256_gqa2_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_window_h256_gqa4_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_window_h256_gqa4_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_window_h256_gqa8_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_window_h256_gqa8_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_window_h512_gqa1_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_window_h512_gqa1_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_window_h512_gqa2_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_window_h512_gqa2_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_window_h512_gqa4_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_window_h512_gqa4_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_window_h512_gqa8_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_window_h512_gqa8_fp8 (const RadArgs*, RadStream); +int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*); +int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*); +/* The top-1 of a row of all-gathered (id, value) pairs, written one id a row: the vocab-sharded + * draft head's merge (r4d_pair_argmax_f32.hip). */ +int r4d_rad_pair_argmax_f32(const RadArgs*, RadStream); +/* Gemma 4's two sandwich-norm joins, each one kernel for a chain of rmsnorm / add / mul_weight + * launches (r4d_norm_join_bf16.hip), and expert_scale, the embed_lookup + mul pair that scales + * each routing weight by its expert's scale (r4d_expert_scale_bf16.hip). */ +int r4d_rad_norm_add_norm_bf16 (const RadArgs*, RadStream); +int r4d_rad_norm_add_norm_route_bf16(const RadArgs*, RadStream); +int r4d_rad_join_add_scale_bf16 (const RadArgs*, RadStream); +int r4d_rad_expert_scale_bf16 (const RadArgs*, RadStream); int r4d_rad_attn_vit (const RadArgs*, RadStream); int r4d_rad_attn_dense (const RadArgs*, RadStream); /* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256 @@ -122,15 +161,6 @@ int64_t r4d_rad_attn_decode_h256_gqa4_scratch(const RadArgs*); /* ...and its head_dim 64 prefill leg, LFM2's geometry, which serves every query length. */ int r4d_rad_attn_prefill_h64_gqa4_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_prefill_h64_gqa4_bf16(const RadArgs*, RadStream); -/* Eight queries per KV head at head_dim 512, full attention -- the Gemma 4 dense GLOBAL layers. - * Its own instantiation, not the gqa8 body above: that one's prefill tile is 48, which 512-channel - * tiles do not fit in LDS, so head_dim 512 is a stand-alone dispatch - * (r4d_attn_paged_h512_gqa8.hip). The verify width is the gqa bound, 64/8 = 8. */ -int r4d_rad_attn_prefill_h512_gqa8_fp8 (const RadArgs*, RadStream); -int r4d_rad_attn_prefill_h512_gqa8_bf16(const RadArgs*, RadStream); -int r4d_rad_attn_decode_h512_gqa8_fp8 (const RadArgs*, RadStream); -int r4d_rad_attn_decode_h512_gqa8_bf16 (const RadArgs*, RadStream); -int64_t r4d_rad_attn_decode_h512_gqa8_scratch(const RadArgs*); /* Twelve queries a KV head, head_dim 256 only -- Qwen3.8-Flash-Next's QSA layers. Same body, * different instantiation; r4d_attn_paged_h256_gqa12.hip is four lines. */ int r4d_rad_attn_prefill_h256_gqa12_fp8 (const RadArgs*, RadStream); @@ -600,6 +630,7 @@ int r4d_shape_moe_gather (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_scale_rows (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_scale (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_row_topk_merge (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_pair_argmax (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_quant_act_i8 (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_had_quant_act_i8 (const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 0642e474..10d97add 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -71,7 +71,7 @@ /* libr4d's R4D_AR_TWOSHOT_WIDE_MAX_ELEMS, restated because this file must not include r4d.h. * r4d_ar_entry.hip static_asserts the two against each other. */ -#define R4D_AR_TWOSHOT_WIDE_MAX_ELEMS 20971520 +#define R4D_AR_TWOSHOT_WIDE_MAX_ELEMS 268435456 /* The largest message, in elements, a 4- or 8-rank exact all-reduce keeps on the one-shot; above it * the two-shot rows take it. 1 MiB of a 16-bit payload. The one-shot sends (ws-1)*N bytes a rank @@ -2110,6 +2110,80 @@ static const RadOperandSpec oMergeTopk[] = { { "cand_val", RAD_OPD_OUT, 0 }, }; +/* ------------------------------------------------------- pair_argmax, the joins, expert_scale + * + * pair_argmax is libref's schema restated field for field. The other four ops are this library's + * own, and attn_paged_qrow, whose schema is attn_paged's above: libref has no row for any of them + * ON PURPOSE. A reference row would resolve them wherever this library is not loaded -- a CPU-only + * build, a --kernels list without it -- and the architecture's fallback to the chain each one + * replaces would never be taken. docs/OPS.md carries all six, which is what the ops_doc test holds + * them to. */ +static const RadParamSpec pPairArgmax[] = { + P_INT("M"), + P_INT("n"), + P_STR("dtype"), +}; +static const RadOperandSpec oPairArgmax[] = { + { "pairs", RAD_OPD_IN, 0 }, + { "idx", RAD_OPD_OUT, 0 }, + { "val", RAD_OPD_OUT, 1 }, +}; +static const RadParamSpec pNormJoin[] = { + P_INT("M"), + P_INT("n"), + P_F64("eps"), + P_STR("dtype"), +}; +static const RadOperandSpec oNormAddNorm[] = { + { "a", RAD_OPD_IN, 0 }, + { "w_a", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_INOUT, 0 }, + { "w_y", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pNormAddNormRoute[] = { + P_INT("M"), + P_INT("n"), + P_F64("eps"), + P_STR("dtype"), + P_F64("mult"), + P_INT("group"), +}; +static const RadOperandSpec oNormAddNormRoute[] = { + { "a", RAD_OPD_IN, 0 }, + { "w_a", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_INOUT, 0 }, + { "w_y", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, + { "w_r", RAD_OPD_WEIGHT, 0 }, + { "r", RAD_OPD_OUT, 0 }, + { "w_e", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "qs", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec oJoinAddScale[] = { + { "d", RAD_OPD_IN, 0 }, + { "w_d", RAD_OPD_WEIGHT, 0 }, + { "r", RAD_OPD_IN, 0 }, + { "w_r", RAD_OPD_WEIGHT, 0 }, + { "w_j", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_INOUT, 0 }, + { "s", RAD_OPD_WEIGHT, 0 }, + { "w_n", RAD_OPD_WEIGHT, 1 }, + { "y", RAD_OPD_OUT, 1 }, +}; +static const RadParamSpec pExpertScale[] = { + P_INT("M"), + P_INT("n_expert"), + P_INT("top_k"), + P_STR("dtype"), +}; +static const RadOperandSpec oExpertScale[] = { + { "ids", RAD_OPD_IN, 0 }, + { "w_e", RAD_OPD_WEIGHT, 0 }, + { "ew", RAD_OPD_INOUT, 0 }, +}; + #define SCHEMA(op, p, o, doc) { (op), ROW(p), ROW(o), (doc) } static const RadOpSchema kSchemas[] = { @@ -2302,6 +2376,17 @@ static const RadOpSchema kSchemas[] = { "paged causal attention, varlen. The ranged parameter is q_len, not M: one query row " "at decode, up to 64/gqa at a speculative verify, thousands in a prefill chunk, and " "libr4d has a different kernel for each band."), + /* attn_paged under a name of its own, for a q read at its own row pitch. The windowed kernels + * (r4d_attn_paged_window.hip) read q where a fused [q|k|v] projection left it; the other + * attn_paged kernels, this library's included, read q dense and refuse the slice + * (RAD_E_STRIDE), which stops the engine at the first step. Under attn_paged, whichever row + * resolved would decide whether the slice works; under this name the op resolves to a kernel + * that takes it or to nothing, and the architecture lifts q into a dense block for attn_paged + * where it is nothing. */ + SCHEMA("attn_paged_qrow", pAttnPaged, oAttnPaged, + "attn_paged, parameter for parameter and value for value, with q read at its own row " + "pitch: a column slice of a wider row -- the q part of a fused [q|k|v] projection -- read " + "where it lies rather than lifted into a dense block first."), SCHEMA("attn_paged_gate_quant", pAttnPagedGq, oAttnPagedGq, "attn_paged followed by gate_quant_fp8 over its output, in the split-KV merge: each " "merged (token, head) row is gated, rounded, written to `out` and quantised to E4M3 " @@ -2607,6 +2692,32 @@ static const RadOpSchema kSchemas[] = { "token order (with the shared arm folded when present) ARE the all-reduce's message, " "and the gated residual's write follows the reduction. Both wires at two ranks, the " "exact one at four."), + SCHEMA("pair_argmax", pPairArgmax, oPairArgmax, + "idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in " + "the first f32 slot and its value in the second (row_topk's `pairs`, all-gathered): ties " + "to the lower id, a negative id skipped, -1 and -inf where nothing is valid. " + "row_topk_merge at R = 1, written one element a row at the output's own pitch."), + SCHEMA("norm_add_norm", pNormJoin, oNormAddNorm, + "t = rmsnorm(a) * w_a; x = x + t; y = rmsnorm(x) * w_y, over [M, n] rows; every value " + "the unfused rmsnorm, add, rmsnorm chain stores is rounded to the activation dtype at " + "the same point. A post-norm, the residual add and the next pre-norm (Gemma's " + "sandwich)."), + SCHEMA("norm_add_norm_route", pNormAddNormRoute, oNormAddNormRoute, + "norm_add_norm, then from the same rmsnorm of the x it writes r = rmsnorm(x) * w_r * " + "mult and the E4M3 codes q of rmsnorm(x) * w_e with an f32 scale qs per (row, `group` " + "columns): rmsnorm_quant_fp8's codes, taken over the bf16-rounded norm. A MoE layer's " + "router input and its experts' fp8 input, written by the attention join that already " + "holds the norm."), + SCHEMA("join_add_scale", pNormJoin, oJoinAddScale, + "x = (x + rmsnorm(rmsnorm(d) * w_d + rmsnorm(r) * w_r) * w_j) * s, over [M, n] rows, s " + "one element; and with w_n and y, y = rmsnorm(x) * w_n over the x written. Rounding " + "where the unfused chain rounds. Two arms' post-norms, their sum, its norm, the residual " + "add, a per-layer scalar and the next layer's input norm (Gemma 4's feed-forward " + "join)."), + SCHEMA("expert_scale", pExpertScale, oExpertScale, + "ew[t, k] = ew[t, k] * w_e[ids[t, k]] over [M, top_k], w_e an [n_expert] table, an id " + "outside it reading 0; one product rounded once, so the embed_lookup + mul pair's value " + "bit for bit. Gemma 4's per_expert_scale on the renormalised routing weights."), }; /* ================================================================================ constraints @@ -2726,25 +2837,31 @@ static const RadConstraint cAttnPrefillH64G4Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; -/* Gemma 4 dense GLOBAL layers: head_dim 512, 8 queries per KV head, full attention - * (r4d_attn_paged_h512_gqa8.hip). The `q_len <= 8` bound is the gqa verify width again; window - * stays 0, which is what separates this from the sliding leg and why it needs no windowed form. */ -static const RadConstraint cAttnPrefillH512G8Fp8[] = { - C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16), - C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), -}; -static const RadConstraint cAttnPrefillH512G8Bf16[] = { - C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16), - C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), -}; -static const RadConstraint cAttnDecodeH512G8Fp8[] = { - C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16), - C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), -}; -static const RadConstraint cAttnDecodeH512G8Bf16[] = { - C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16), - C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), -}; +/* THE WINDOWED KERNELS (r4d_attn_paged_window.hip): head_dim 256 and 512, 1/2/4/8 queries per KV + * head, ANY window, causal or not -- Gemma 4's sliding layers are h256/gqa2 with a 1024-token + * window, its full layers h512 at gqa 8 (TP1/TP2), 4 (TP4) or 2 (TP8). One kernel serves every + * q_len -- decode, verify and prefill, splitting the key range where there are too few tiles to + * fill the card -- so `q_len` carries no constraint and cuts no band. `causal` and `window` are + * runtime fields of the kernel; block_size is the kernel's (RAD_DERIVED): 16. + * + * h256 AT gqa 4 AND 8 TAKE A WINDOW ONLY (C_GE 1): their window-0 band is the gqa4 / gqa8 legs' + * above (Qwen3.5-0.8B, the routed 35B-A3B), which these rows leave to them. At h256/gqa2 the + * rows overlap the sliding leg's two bands and rank below it (R4D_PRIO_ATTN_WINDOW says why); + * every other geometry here is these rows' alone. */ +#define R4D_WIN_C(NAME, HD, G, KV, WMIN) \ + static const RadConstraint NAME[] = { \ + C_EQ("head_dim", HD), C_EQ("gqa", G), C_EQ("block_size", 16), C_GE("causal", 0), \ + C_GE("window", WMIN), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", KV), \ + }; +R4D_WIN_C(cWinH256G1Bf16, 256, 1, "bf16", 0) R4D_WIN_C(cWinH256G1Fp8, 256, 1, "fp8_e4m3", 0) +R4D_WIN_C(cWinH256G2Bf16, 256, 2, "bf16", 0) R4D_WIN_C(cWinH256G2Fp8, 256, 2, "fp8_e4m3", 0) +R4D_WIN_C(cWinH256G4Bf16, 256, 4, "bf16", 1) R4D_WIN_C(cWinH256G4Fp8, 256, 4, "fp8_e4m3", 1) +R4D_WIN_C(cWinH256G8Bf16, 256, 8, "bf16", 1) R4D_WIN_C(cWinH256G8Fp8, 256, 8, "fp8_e4m3", 1) +R4D_WIN_C(cWinH512G1Bf16, 512, 1, "bf16", 0) R4D_WIN_C(cWinH512G1Fp8, 512, 1, "fp8_e4m3", 0) +R4D_WIN_C(cWinH512G2Bf16, 512, 2, "bf16", 0) R4D_WIN_C(cWinH512G2Fp8, 512, 2, "fp8_e4m3", 0) +R4D_WIN_C(cWinH512G4Bf16, 512, 4, "bf16", 0) R4D_WIN_C(cWinH512G4Fp8, 512, 4, "fp8_e4m3", 0) +R4D_WIN_C(cWinH512G8Bf16, 512, 8, "bf16", 0) R4D_WIN_C(cWinH512G8Fp8, 512, 8, "fp8_e4m3", 0) +#undef R4D_WIN_C /* TWELVE QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa12.hip) -- Qwen3.8-Flash-Next's * QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound the two * ratios above state, and it is TIGHTER than the legal speculation depths: a verify of depth 7 is @@ -3023,6 +3140,21 @@ static const RadConstraint cDflashSelect[] = { C_GE("steps", 1), C_GE("top_k", 1), C_LE("top_k", 32), C_DIV("rank", 32), C_LE("rank", 512), C_IN("dtype", "bf16"), }; +/* The sandwich-norm joins hold 24 elements a thread over a 256-thread block (n <= 6144), and the + * route form quantises in whole 128-column groups. pair_argmax takes any row; expert_scale's top_k + * is the router's, at most 64. */ +static const RadConstraint cNormJoin[] = { + C_GE("n", 1), C_LE("n", 6144), C_IN("dtype", "bf16"), +}; +static const RadConstraint cNormJoinRoute[] = { + C_GE("n", 128), C_LE("n", 6144), C_DIV("n", 128), C_EQ("group", 128), C_IN("dtype", "bf16"), +}; +static const RadConstraint cPairArgmax[] = { + C_GE("n", 1), C_IN("dtype", "f32 fp32"), +}; +static const RadConstraint cExpertScale[] = { + C_GE("top_k", 1), C_LE("top_k", 64), C_GE("n_expert", 1), C_IN("dtype", "bf16"), +}; /* ---- the routed mixture of experts ---------------------------------------------------------- * @@ -4084,7 +4216,7 @@ static const RadKernelInfo kKernels[] = { r4d_shape_unary }, { "logit_softcap_bf16", "logit_softcap", "elem", - "cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent", + "cap * tanh(x / cap), the final-logit softcap, a row spread over up to 64 blocks", "any extent; contiguous in and out", "bf16 in and out, fp32 arithmetic", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, @@ -4093,7 +4225,7 @@ static const RadKernelInfo kKernels[] = { r4d_shape_unary }, { "logit_softcap_f32", "logit_softcap", "elem", - "cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent", + "cap * tanh(x / cap), the final-logit softcap, a row spread over up to 64 blocks", "any extent; contiguous in and out", "f32 in and out — the 1.3.0 sampling chain carries the logits as f32 from the gemm", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, @@ -4537,43 +4669,37 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_attn_prefill_h64_gqa4_bf16, nullptr, nullptr, nullptr, r4d_shape_attn_paged }, -{ "attn_prefill_h512_gqa8_fp8kv", "attn_paged", "attn", - "paged causal attention, query-tiled (prefill / chunked prefill)", - "head_dim 512, 8 queries per kv head, paged block 16, varlen", - "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out", - RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, - ROW(cAttnPrefillH512G8Fp8), NOTUNE, - nullptr, nullptr, r4d_rad_attn_prefill_h512_gqa8_fp8, nullptr, nullptr, nullptr, - r4d_shape_attn_paged }, - -{ "attn_prefill_h512_gqa8_bf16kv", "attn_paged", "attn", - "paged causal attention, query-tiled (prefill / chunked prefill)", - "head_dim 512, 8 queries per kv head, paged block 16, varlen", - "bf16 query, bf16 kv cache, bf16 out", - RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, - ROW(cAttnPrefillH512G8Bf16), NOTUNE, - nullptr, nullptr, r4d_rad_attn_prefill_h512_gqa8_bf16, nullptr, nullptr, nullptr, - r4d_shape_attn_paged }, - -{ "attn_decode_h512_gqa8_fp8kv", "attn_paged", "attn", - "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", - "head_dim 512, 8 queries per kv head, paged block 16, q_len*gqa <= 64, no window", - "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials", - RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, - ROW(cAttnDecodeH512G8Fp8), ROW(tAttnSplit), nullptr, - nullptr, nullptr, r4d_rad_attn_decode_h512_gqa8_fp8, r4d_rad_attn_decode_h512_gqa8_scratch, - nullptr, nullptr, - r4d_shape_attn_paged }, - -{ "attn_decode_h512_gqa8_bf16kv", "attn_paged", "attn", - "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", - "head_dim 512, 8 queries per kv head, paged block 16, q_len*gqa <= 64, no window", - "bf16 query, bf16 kv cache, bf16 out, f16 partials", - RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, - ROW(cAttnDecodeH512G8Bf16), ROW(tAttnSplit), nullptr, - nullptr, nullptr, r4d_rad_attn_decode_h512_gqa8_bf16, r4d_rad_attn_decode_h512_gqa8_scratch, - nullptr, nullptr, - r4d_shape_attn_paged }, +/* The windowed kernels (r4d_attn_paged_window.hip), under attn_paged and, the same launches with + * the same constraints, under attn_paged_qrow. The qrow rows carry no opd_shape: libref has no row + * for that op, so there is no oracle to run them against, and tests/r4d_emu's attention cases + * already take q as a pitched slice of a wider row. */ +#define R4D_WIN_ROW(HD, G, KVN, KVS, C, KVDOC) \ +{ "attn_window_h" #HD "_gqa" #G "_" #KVN, "attn_paged", "attn", \ + "paged attention, any window, causal or not; split-KV with a merge where tiles are few", \ + "head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \ + "bf16 query, " KVDOC " kv cache, bf16 out, f32 partials", \ + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_WINDOW, \ + ROW(C), NOTUNE, \ + nullptr, nullptr, r4d_rad_attn_window_h##HD##_gqa##G##_##KVS, \ + r4d_rad_attn_window_h##HD##_scratch, \ + nullptr, nullptr, \ + r4d_shape_attn_paged }, \ +{ "attn_qrow_h" #HD "_gqa" #G "_" #KVN, "attn_paged_qrow", "attn", \ + "paged attention reading q at its own row pitch, any window, causal or not", \ + "head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \ + "bf16 query (any row pitch), " KVDOC " kv cache, bf16 out, f32 partials", \ + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, \ + ROW(C), NOTUNE, \ + nullptr, nullptr, r4d_rad_attn_window_h##HD##_gqa##G##_##KVS, \ + r4d_rad_attn_window_h##HD##_scratch, \ + nullptr, nullptr, nullptr }, +#define R4D_WIN_PAIR(HD, GQ) \ + R4D_WIN_ROW(HD, GQ, bf16kv, bf16, cWinH##HD##G##GQ##Bf16, "bf16") \ + R4D_WIN_ROW(HD, GQ, fp8kv, fp8, cWinH##HD##G##GQ##Fp8, "fp8-e4m3 (per-(seq,head) descales)") +R4D_WIN_PAIR(256, 1) R4D_WIN_PAIR(256, 2) R4D_WIN_PAIR(256, 4) R4D_WIN_PAIR(256, 8) +R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, 8) +#undef R4D_WIN_PAIR +#undef R4D_WIN_ROW { "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", @@ -6150,6 +6276,55 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_dflash_select, nullptr, nullptr, nullptr, r4d_shape_dflash_select }, +/* pair_argmax, the sandwich-norm joins and expert_scale. NO opd_shape on the joins and + * expert_scale: libref has no row for them (see their schemas), so there is no oracle to run them + * against; tests/r4d_emu runs these kernels' source on the host and holds them to the chain they + * replace, bit for bit. pair_argmax is described as libref describes it, so rad-kbench runs it + * against the oracle. */ +{ "pair_argmax_f32", "pair_argmax", "select", + "the top-1 of a row of (id, value) pairs, ties to the lower id, negative ids skipped", + "any M and n; one wave a row; the outputs one element a row at their own pitch", + "f32 pairs (int32 id bits, f32 value), i32 idx, f32 val", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cPairArgmax), NOTUNE, + nullptr, nullptr, r4d_rad_pair_argmax_f32, nullptr, nullptr, nullptr, + r4d_shape_pair_argmax }, + +{ "norm_add_norm_bf16", "norm_add_norm", "norm", + "post-norm, residual add, next pre-norm: one block a row, rounding where the chain rounds", + "n <= 6144, any M, row pitches honoured", + "bf16 activations, f32 gains", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cNormJoin), NOTUNE, + nullptr, nullptr, r4d_rad_norm_add_norm_bf16, nullptr, nullptr, nullptr, + nullptr }, + +{ "norm_add_norm_route_bf16", "norm_add_norm_route", "norm", + "norm_add_norm, and the routed arm's router input and fp8 expert input from the same norm", + "n <= 6144 in whole 128-column groups, any M, row pitches honoured", + "bf16 activations, f32 gains; E4M3 codes with an f32 scale a 128 columns", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cNormJoinRoute), NOTUNE, + nullptr, nullptr, r4d_rad_norm_add_norm_route_bf16, nullptr, nullptr, nullptr, + nullptr }, + +{ "join_add_scale_bf16", "join_add_scale", "norm", + "two arms' post-norms, sum, norm, residual add, layer scalar: one block a row", + "n <= 6144, any M, row pitches honoured", + "bf16 activations, f32 gains, bf16 scalar", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cNormJoin), NOTUNE, + nullptr, nullptr, r4d_rad_join_add_scale_bf16, nullptr, nullptr, nullptr, + nullptr }, + +{ "expert_scale_bf16", "expert_scale", "moe", + "routing weight times its expert's scale, in place: one thread an element", + "any M, top_k <= 64, row pitches honoured", + "i32 ids, bf16 table and weights", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cExpertScale), NOTUNE, + nullptr, nullptr, r4d_rad_expert_scale_bf16, nullptr, nullptr, nullptr, + nullptr }, }; /* ================================================================================== the exports */ diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 882c3caa..00ae7bbd 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -393,6 +393,7 @@ static void cross_check(const Plugin& pl) { /* The libr4d orderings the integer priority has to preserve. */ int p_ts = -1, p_os = -1, p_dec = -1, p_pre = -1, p_m16 = -1, p_m64 = -1, p_bt = -1; + int p_g2dec = -1, p_g2pre = -1, p_g2win = -1; for (int k = 0; k < nk; ++k) { const RadKernelInfo* r = pl.kernel_at(k); if (!std::strcmp(r->name, "ar_twoshot_4rank_exact")) p_ts = r->priority; @@ -402,12 +403,17 @@ static void cross_check(const Plugin& pl) { if (!std::strcmp(r->name, "gemm_bf16_nt_m16")) p_m16 = r->priority; if (!std::strcmp(r->name, "gemm_bf16_nt_m64")) p_m64 = r->priority; if (!std::strcmp(r->name, "gemm_bf16_nt_tiled")) p_bt = r->priority; + if (!std::strcmp(r->name, "attn_decode_h256_gqa2_fp8kv")) p_g2dec = r->priority; + if (!std::strcmp(r->name, "attn_prefill_h256_gqa2_fp8kv")) p_g2pre = r->priority; + if (!std::strcmp(r->name, "attn_window_h256_gqa2_fp8kv")) p_g2win = r->priority; } ok("two-shot all-reduce outranks one-shot (libr4d row order)", p_ts > p_os && p_ts > 0); ok("paged decode outranks paged prefill in the shared band", p_dec > p_pre && p_dec > 0); ok("gemm_bf16_nt_m16 outranks _m64 (libr4d row order, see the ladder)", p_m16 > p_m64); ok("gemm_bf16_nt_tiled outranks _m64 and not _m16 (M > 64 is its band)", p_bt > p_m64 && p_bt < p_m16); + ok("the h256/gqa2 legs outrank the windowed kernel in both their bands", + p_g2win > 0 && p_g2dec > p_g2win && p_g2pre > p_g2win); std::printf("\n"); } @@ -12010,7 +12016,7 @@ static void ar_three_rank(const Plugin& pl, const std::vector& devs, const * sums correctly. This one gives every element its own value, so a word reduced by the wrong * owner, gathered from the wrong slot or dropped at a short shard's end is a wrong number at a * known index. The sizes walk the uneven split: words % 3 of 0, 1 and 2, from a 16-word message - * to the row's 20971520-element ceiling, in place (how every block issues it) and once out of + * to past the old 20971520 ceiling, in place (how every block issues it) and once out of * place, back to back on ONE instance so the slot parity and the changing block count are * exercised the way a step's mixed messages exercise them. The oracle is the fold the kernel * claims -- fp32 in ascending rank order, rounded once -- so it is bit for bit, and so it is also @@ -12089,8 +12095,9 @@ static void ar_three_rank_pattern(const Plugin& pl, const std::vector& devs struct Run { const char* dtype; std::vector sizes; int oop; }; const std::vector runs = { /* bf16, the residual: words = numel / 8. 2048 x 2048 rows is words % 3 == 2, x 2049 is - * 0, x 2050 is 1; 128 is 16 words (1), 24008 is 3001 (1); 20971520 the ceiling (1). */ - { "bf16", { 4194304, 128, 4196352, 24008, 4198400, 20971520, 4194304 }, 2 }, + * 0, x 2050 is 1; 128 is 16 words (1), 24008 is 3001 (1); 20971520 the old ceiling (1); + * 46137344, Gemma 4's feed-forward reduce at an 8192-token chunk, past it (1). */ + { "bf16", { 4194304, 128, 4196352, 24008, 4198400, 20971520, 46137344, 4194304 }, 2 }, /* fp32: words = numel / 4. 8196 -> 2049 (0), 4100 -> 1025 (2), 1048580 -> 262145 (2). */ { "fp32", { 8196, 4100, 1048580 }, 0 }, }; @@ -12579,19 +12586,19 @@ static void device_phase(const Plugin& pl) { * context and the launch is the full-attention form. */ attn_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 32, "fp8_e4m3", 1, 1024); attn_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 32, "bf16", 1, 1024); - /* Gemma 4 dense global: head_dim 512, full attention. Launch-only cases at prefill q_len 32 and - * decode 1, mirroring the gqa6 leg's pair; the numeric check of the same rows follows. */ - attn_case(pl, "attn_prefill_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1); - attn_case(pl, "attn_prefill_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 1); - attn_case(pl, "attn_decode_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0); - attn_case(pl, "attn_decode_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0); + /* Gemma 4 dense global: head_dim 512, full attention, on the windowed kernel -- one row for + * every q_len, so a prefill-shaped launch (q_len 32) and a decode one (1) of the same row; the + * numeric check of both follows. */ + attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1); + attn_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 1); + attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0); + attn_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0); /* The numeric attention check: the same rows, but with random data and a comparison - * against the inline oracle, plus a negative control. h512 is prefill + decode; h256/gqa2 is - * decode-only (the windowed sliding-window leg, window 1024). */ - attn_numeric_case(pl, "attn_prefill_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 0); - attn_numeric_case(pl, "attn_prefill_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 0); - attn_numeric_case(pl, "attn_decode_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0); - attn_numeric_case(pl, "attn_decode_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0); + * against the inline oracle, plus a negative control. */ + attn_numeric_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 0); + attn_numeric_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 0); + attn_numeric_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0); + attn_numeric_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0); /* The h256/gqa2 PREFILL numeric check. Unlike the decode leg (ctx 64 < window, so the window * clamps to the context), ctx here is 2048 > window 1024, so the window actually bites: for * query row 0, pos = 2048-64 = 1984 and the visible keys are [961..1984], so the kernel's diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 9f5394d2..6662aca0 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -1519,6 +1519,21 @@ extern "C" int r4d_shape_row_topk_merge(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* pair_argmax (r4d_pair_argmax_f32.hip): row_topk_merge at R = 1 over `n` gathered pairs, so the + * same f32 plane and the same reading of it -- the value lane draws proper floats, the id lane + * their bit patterns, a negative one a pad and a positive one a legal id -- and one id and one + * value a row out. */ +extern "C" int r4d_shape_pair_argmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd((uint32_t)RAD_F32, M, n, 2), + opd((uint32_t)RAD_I32, M), + opd((uint32_t)RAD_F32, M), + }; + R4D_PICK(l); +} + /* ========================================================================================== * Quantisation, the norms and the fusions (shims in r4d_quant.cpp and r4d_fp8.cpp). * diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index 0a5e9d41..37bb1f0c 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -773,7 +773,7 @@ int ref_logit_softcap(const RadArgs* a, RadStream) { #pragma omp parallel for schedule(static) for (int64_t i = 0; i < nel; ++i) { const float v = ldt(x, offlin(x, i)); - stt(y, offlin(y, i), cap * std::tanhf(v / cap)); + stt(y, offlin(y, i), cap * std::tanh(v / cap)); } return RAD_OK; } diff --git a/libref/ref_moe.cpp b/libref/ref_moe.cpp index c130799f..18af48d2 100644 --- a/libref/ref_moe.cpp +++ b/libref/ref_moe.cpp @@ -488,6 +488,47 @@ int ref_row_topk_merge(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ pair_argmax */ +/* row_topk_merge at R = 1, for a caller that wants the winner's id as a PROPOSAL rather than as + * a candidate list: one element a row, at the output's own pitch, so a block drafter's per-position + * picks land contiguous in the token buffer it verifies. `pairs` is the same gathered plane -- + * `n` (int32 id, f32 value) pairs a row, a negative id a pad -- and the rule is the same: the + * largest value, ties to the LOWER id, so the pick equals an argmax over the unsharded row. + * + * Its own op rather than row_topk_merge with R = 1 because the shapes differ where it matters: + * row_topk_merge's `gathered` is world_size * R pairs a row, and a rank that sends R = 1 sends 8 + * bytes, which a row-interleaved all_gather moving whole 16-byte words cannot carry. So a rank + * sends R >= 2 and this takes the top-1 of all of them, whatever `n` that makes. A row with no + * valid pair writes -1 and -inf, as the merge does for a slot it cannot fill. `val` is optional. */ +int ref_pair_argmax(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *p = &a->t[0], *idx = &a->t[1]; + const RadTensor* val = t_in(a, 2); + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + if (p->dtype != RAD_F32) return RAD_E_DTYPE; /* the id is carried by bit pattern */ + /* The rows are the operand's, as on row_topk_merge: `M` is a band ceiling. */ + const int64_t M = numel(p) / (n * 2); + if (M <= 0 || numel(idx) < M || (val && numel(val) < M)) return RAD_E_SHAPE; + const float* const pf = (const float*)p->data; + + #pragma omp parallel for schedule(static) + for (int64_t m = 0; m < M; ++m) { + int32_t bid = -1; + float bv = -INFINITY; + for (int64_t j = 0; j < n; ++j) { + int32_t id; + std::memcpy(&id, pf + offlin(p, (m * n + j) * 2), sizeof id); + if (id < 0) continue; /* a pad, not a candidate */ + const float v = pf[offlin(p, (m * n + j) * 2 + 1)]; + if (bid < 0 || v > bv || (v == bv && id < bid)) { bid = id; bv = v; } + } + st_int(idx->dtype, idx->data, offlin(idx, m), bid); + if (val) stt(val, offlin(val, m), bv); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ logit_rerank */ /* EXACTLY RESCORE R CANDIDATES A ROW AGAINST THE FULL-PRECISION HEAD. * diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 907b25c4..3117c0aa 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -145,6 +145,7 @@ int ref_scale_rows (const RadArgs*, RadStream); int ref_moe_gather (const RadArgs*, RadStream); int ref_row_topk (const RadArgs*, RadStream); int ref_row_topk_merge (const RadArgs*, RadStream); +int ref_pair_argmax (const RadArgs*, RadStream); int ref_logit_rerank (const RadArgs*, RadStream); /* ---- gated delta net */ @@ -278,6 +279,7 @@ REF_SHAPE_FN(ref_scale_rows); REF_SHAPE_FN(ref_moe_gather); REF_SHAPE_FN(ref_row_topk); REF_SHAPE_FN(ref_row_topk_merge); +REF_SHAPE_FN(ref_pair_argmax); REF_SHAPE_FN(ref_logit_rerank); REF_SHAPE_FN(ref_gdn_conv_prep); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index aa89fb4c..ab592e9d 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -463,6 +463,8 @@ static const RadOperandSpec oRowTopk[] = { OPD("x"), OUT("idx"), OUT("val"), OUT static const RadParamSpec pRowTopkMerge[] = { P_INT("M"), P_INT("R"), P_INT("world_size"), P_STR("dtype") }; static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT("val") }; +static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oPairArgmax[] = { OPD("pairs"), OUT("idx"), OUT_O("val") }; static const RadParamSpec pLogitRerank[] = { P_INT("M"), P_INT("R"), P_INT("n_vocab"), P_INT("n_embd"), P_INTO("vocab_off"), P_STR("dtype") }; @@ -976,6 +978,11 @@ static const RadOpSchema kSchemas[] = { "(idx, val) form the single-rank top-R produces. `gathered` is [M, world_size * R, 2] pairs, " "rank r's at [r*R, (r+1)*R); id -1 is a pad and is dropped. Ties break on the LOWER id, which is " "what makes the merged answer agree with a top-R over the unsharded plane." }, +{ "pair_argmax", ARR(pPairArgmax), ARR(oPairArgmax), + "idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in the first " + "f32 slot and its value in the second (row_topk's `pairs`, all-gathered): ties to the lower " + "id, a negative id skipped, -1 and -inf where nothing is valid. row_topk_merge at R = 1, " + "written one element a row at the output's own pitch." }, { "logit_rerank", ARR(pLogitRerank), ARR(oLogitRerank), "Rescore R candidate ids a row EXACTLY against the full-precision head and re-sort on those " @@ -1297,6 +1304,7 @@ SIMPLE("ref_qsa_block_key", "qsa_block_key", "attn", ref_qsa_block_key), SIMPLE("ref_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, ref_row_topk), SIMPLE("ref_row_topk_merge", "row_topk_merge", "moe", "the global top-R of the gathered per-rank candidate sets", DT_FLOAT, ref_row_topk_merge), +SIMPLE("ref_pair_argmax", "pair_argmax", "moe", "the global top-1 of a row of gathered (id, value) pairs, one id a row", DT_FLOAT, ref_pair_argmax), SIMPLE("ref_logit_rerank", "logit_rerank", "moe", "R candidates a row rescored exactly against the full-precision head", DT_FLOAT, ref_logit_rerank), SIMPLE("ref_gdn_conv_prep", "gdn_conv_prep", "gdn", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 32f403e7..cbd6bf6d 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1518,6 +1518,19 @@ int ref_row_topk_merge_shape(const RadParam* p, int n_p, int operand, RadOpdDesc return o.finish("row_topk_merge", operand, out); } +/* The same plane at R = 1 a row, and fillable for the same reason the merge's is: the value lane + * draws proper floats and the id lane their bit patterns, so pads are dropped, ids compared and + * copied, and ties do not occur. */ +int ref_pair_argmax_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t((uint32_t)RAD_F32, { M, n, 2 }); /* pairs */ + o.t((uint32_t)RAD_I32, { M }); /* idx */ + o.t((uint32_t)RAD_F32, { M }); /* val */ + return o.finish("pair_argmax", operand, out); +} + /* logit_rerank DESCRIBES ITSELF, AND THE READER THAT NEEDS IT INVERTS FIRST. diff --git a/scripts/README.md b/scripts/README.md index 0fd23496..3f5acb6d 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -34,7 +34,6 @@ header lists its own). The ones that only attach to a live server need nothing b | `fntrace.sh` | A Flash-Next prefill under `rocprofv3`, with the link counters from `/stats` across the same request, so the streamed-read rate of the MoE GEMM can be computed. | | `mctrace.sh` | A MiniCPM5-2B decode trace under `rocprofv3`, formatted for `libr4d/isa/tsum.sh`. The `blocks` column is what the trace is for. | | `ident.sh` | Run-to-run reproducibility at a fixed configuration: one hash per (temperature, question), to compare against another run of the same configuration. A speculative run is not expected to match a non-speculative one byte for byte — the split-K count is chosen from M, so the two take different reduction orders and can flip a near-tie late in a long answer — but a divergence within the first sentence or two is a defect. | -| `diskstall.py` | What restoring a conversation from the disk tier costs: the returning request's time to first token, and the longest stall it puts on a stream decoding beside it. | | `cardclock.py` | What holds each card's clock under a sustained load, and which card a tensor-parallel step waits for. The step ends when its slowest rank finishes, and under a sustained load the firmware picks that rank's clock: the power limit, a temperature or current limit, or the top of its voltage/frequency curve. Reads every AMD card's `gpu_metrics` table ten times a second and counts a throttler bit only when the clock is lower while it is set (some firmware keeps a bit on at idle). The engine's own step counters sit beside it per window, so a slow window is told apart first: slower steps, fewer tokens per step (the text), or host time between steps. Drives its own greedy load, or with `--watch` only samples a server that real traffic is driving. `--compare` puts two saved runs side by side. Read-only on the cards. | | `oracle.sh` | Every op compared against libref on the operands the model actually issued, which is the gap rad-kbench cannot close: its operands are its own, dense and rank-2, and an engine's are slices of arenas and weights off a file. Reads for two things — a MISMATCH, and the NOT CHECKED lines that name the rows whose weight layout has no published inverse and therefore cannot be compared at all. | diff --git a/scripts/diskstall.py b/scripts/diskstall.py deleted file mode 100644 index 6b355c23..00000000 --- a/scripts/diskstall.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env python3 -# diskstall.py -- what bringing a conversation back from DISK costs: the returning request's time to -# first token, and the stall it puts on a conversation decoding beside it. -# -# A restore out of disk is the one tier move that reads files, and where it reads them decides who -# waits. So this measures both halves: the request that asked (TTFT, and how much of its prompt the -# cache served) and a bystander that asked for nothing (the longest gap between its streamed chunks -# while the restore ran, against its median gap outside that window). -# -# scripts/diskstall.py [--port 8100] [--session 20000] [--fill 30000] -# -# THE SERVER MUST HAVE A HOST TIER THE FILLER OVERFLOWS, or the session is restored out of host -# memory and nothing here touches the disk -- the run then says so and exits non-zero: -# --prefix-cache-host-mib 512 --prefix-cache-disk-mib 8192 --prefix-cache-dir -# holds about 27K tokens on Qwen3.8-Flash-Next, so --session 20000 --fill 30000 puts the session -# on disk. The session must still FIT the host tier: a restore reads through it. -import argparse, json, random, statistics, sys, threading, time, urllib.request - -ap = argparse.ArgumentParser() -ap.add_argument("--port", type=int, default=8100) -ap.add_argument("--host", default="127.0.0.1") -ap.add_argument("--session", type=int, default=20000, help="tokens in the returning conversation") -ap.add_argument("--fill", type=int, default=30000, help="tokens of filler that push it out of RAM") -ap.add_argument("--wait", type=int, default=240, help="seconds to wait for it to reach disk") -ap.add_argument("--seed", type=int, default=7) -a = ap.parse_args() -base = f"http://{a.host}:{a.port}" - -WORDS = ["ledger", "valve", "crate", "harbor", "signal", "copper", "lantern", "orchard", "gravel", - "tunnel", "beacon", "anchor", "quarry", "saddle", "furnace", "meadow", "cobalt", "pylon"] - -def text(seed, ntok): - r = random.Random(seed) - return " ".join(r.choice(WORDS) for _ in range(int(ntok / 1.25))) - -def post(path, body, timeout=1800): - req = urllib.request.Request(base + path, data=json.dumps(body).encode(), - headers={"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=timeout) as r: - return json.loads(r.read()) - -def get(path): - with urllib.request.urlopen(base + path, timeout=30) as r: - return json.loads(r.read()) - -def complete(prompt, n=1): - t0 = time.time() - d = post("/v1/completions", {"model": "m", "prompt": prompt, "max_tokens": n, - "temperature": 0, "stream": False}) - u = d.get("usage") or {} - cached = (u.get("prompt_tokens_details") or {}).get("cached_tokens") - return time.time() - t0, u.get("prompt_tokens"), cached - -def row_for(tokens): - for s in get("/sessions")["sessions"]: - if tokens <= s["tokens"] <= tokens + 8: - return s - return None - -session = text(a.seed, a.session) + "\nName one word above.\nAnswer:" -t, n_prompt, _ = complete(session) -print(f"session {n_prompt} tokens prefilled in {t:.1f}s") -t, n_fill, _ = complete(text(a.seed + 1, a.fill) + "\nName one word above.\nAnswer:") -print(f"filler {n_fill} tokens prefilled in {t:.1f}s") - -# ON DISK AND NOWHERE ELSE: not in VRAM (the loan takes a clean entry's blocks), not in RAM (the -# filler's copies took the slots, which the disk copy made free to give up). -t0 = time.time() -while True: - s = row_for(n_prompt) - if s and s["on_device"] == 0 and s["on_host"] == 0 and s["on_disk"] > 0 and not s["moving"]: - break - if time.time() - t0 > a.wait: - print(f"diskstall: the session never left RAM and VRAM for disk: {s}", file=sys.stderr) - sys.exit(1) - time.sleep(1) -print(f"on disk {s['on_disk']} blocks, snapshots host/disk " - f"{s['snap_host']}/{s['snap_disk']}, after {time.time()-t0:.0f}s") - -# ---- the bystander: a stream that only decodes ---------------------------------------------------- -stamps = [] -def bystander(): - req = urllib.request.Request(base + "/v1/completions", data=json.dumps({ - "model": "m", "prompt": "Write a long story about a lighthouse keeper.\n\n", - "max_tokens": 1500, "temperature": 0.7, "seed": 1, "ignore_eos": True, - "stream": True}).encode(), headers={"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=1800) as r: - for line in r: - if line.startswith(b"data:") and not line.startswith(b"data: [DONE]"): - stamps.append(time.time()) -th = threading.Thread(target=bystander) -th.start() -while len(stamps) < 40: - time.sleep(0.05) -time.sleep(2.0) - -moved0 = get("/sessions")["moved"] -t_ask = time.time() -ttft, n2, cached = complete(session + " the") -t_done = time.time() -moved1 = get("/sessions")["moved"] -time.sleep(2.0) -th.join() - -gaps_in, gaps_out = [], [] -for x, y in zip(stamps, stamps[1:]): - (gaps_in if y >= t_ask and x <= t_done else gaps_out).append(y - x) -promoted = moved1["promoted"] - moved0["promoted"] -print(f"restore {promoted} entries promoted; prompt {n2} cached {cached}; TTFT {ttft*1000:.0f} ms") -print(f"bystander median gap {statistics.median(gaps_out)*1000:.1f} ms outside the restore, " - f"longest {max(gaps_in)*1000:.1f} ms during it ({len(gaps_in)} chunks)") -if not cached or cached < n_prompt // 2: - print("diskstall: the returning request was not served from the cache", file=sys.stderr) - sys.exit(1) diff --git a/scripts/fnserve.sh b/scripts/fnserve.sh index 51eb58d9..b06af433 100755 --- a/scripts/fnserve.sh +++ b/scripts/fnserve.sh @@ -45,33 +45,26 @@ # different order and a tie can land on a different token; each chunk size is stable on its # own. Pin the chunk before recording anything to compare against later. # -# THE PREFIX CACHE IS TIERED, AND THE ENGINE LEAVES THE TIERS OFF BY DEFAULT. Both -# --prefix-cache-host-mib and --prefix-cache-disk-mib are zero unless asked for, so a server started -# without them drops a conversation's context the moment the pool needs the blocks. This deployment -# keeps finished turns in host memory and then on disk, where they cost the card nothing. +# THE PREFIX CACHE IS TIERED, AND THE ENGINE LEAVES THE HOST TIER OFF BY DEFAULT. +# --prefix-cache-mib is zero unless asked for, so a server started without it drops a conversation's +# context the moment the pool needs the blocks. This deployment keeps finished turns in host memory, +# where they cost the card nothing, for an hour of disuse (--prefix-cache-ttl's default). # # The ELASTIC half needs no flag and cannot be turned off: the pool holds the blocks it is using # plus a buffer derived from the chunk, and the expert slab takes the VRAM it releases. That leans # on --gpu-headroom-mib, which is why the 96 above matters -- startup names any shortfall and holds # it back on top of the reserve. # -# --prefix-cache-host-mib finished conversations are copied here at once and their VRAM goes -# to the expert slab; a return restores instead of re-prefilling. Part -# of it is the linear-state snapshot store, sized in proportion to what -# a session holds in snapshots against blocks; startup says how many -# snapshots it holds. On this model a snapshot is 113 MiB and -# --checkpoint-slots counts snapshots for the whole server, not per -# sequence, so the snapshot store is the binding resource: without it -# only the conversations whose snapshots are still in a device slot -# resume without re-prefilling their whole transcript. -# --prefix-cache-disk-mib every host copy is also written to disk under --prefix-cache-dir, so -# a full host tier gives its oldest slots up for nothing. Costs no RAM -# and no VRAM. It holds conversation content UNENCRYPTED. +# --prefix-cache-mib finished conversations are copied here at once and their VRAM goes to the +# expert slab; a return restores instead of re-prefilling, and a full tier +# drops its least recently used. It holds attention blocks only: the +# linear-state snapshots are in the --checkpoint-slots store, 113 MiB each on +# this model and counted for the whole server, not per sequence. # # THE HOST NUMBER IS DELIBERATELY SMALL BECAUSE OF THE N-GRAM TABLE. The tier's arena is PINNED, # and the 47.68 GiB n-gram (PLE) table is read through the container's own mmap, so it lives in # the page cache -- and pinned bytes come out of the same host RAM. Taking too much here turns a -# decode step's minor faults into major ones, a far worse trade than a smaller snapshot store. +# decode step's minor faults into major ones, a far worse trade than a smaller host tier. # Watch /proc//stat majflt across a prefill before raising it. # # THE CROSS-RANK WIRE IS THE ROTATED 6-BIT ONE (--tp-wire wht6). An all-reduce at or above @@ -98,8 +91,7 @@ nohup ./bin/radiance --model "$M" \ --max-num-seqs ${SEQS:-8} --max-model-len ${MLEN:-200000} \ --tp ${TP:-2} --placement expert_tiered --host-pool-mib ${HOSTPOOL:-12288} \ --gpu-headroom-mib ${HR:-96} --kv-cache-dtype ${KVD:-fp8} \ - --prefix-cache-host-mib ${KVHOST:-4096} \ - --prefix-cache-dir ${KVDIR:-$HOME/kvcache} --prefix-cache-disk-mib ${KVDISK:-131072} \ + --prefix-cache-mib ${KVHOST:-4096} \ --num-speculative-tokens ${NS:-3} \ --max-num-batched-tokens ${MNBT:-2048} \ --tp-wire ${WIRE:-wht6} \ diff --git a/scripts/tiercross.sh b/scripts/tiercross.sh index a9f34eac..1f00ef43 100755 --- a/scripts/tiercross.sh +++ b/scripts/tiercross.sh @@ -8,12 +8,14 @@ # cache can have -- an entry holding reassigned block ids, a checkpoint slot freed by one session # and still named by another -- need two sessions in flight to show up at all. # -# THE SCARCE RESOURCE IS THE CHECKPOINT SLOT, so run this with --checkpoint-slots low enough that -# the two sessions fight over it. That is what makes the retention policy and the victim scan run, -# which is what makes a snapshot get retired underneath a record that still names its slot: +# A HOST TIER THE FILLER OVERFLOWS, so the arena's drops run as well as its restores: # -# --checkpoint-slots 2 --prefix-cache-host-mib 512 --prefix-cache-disk-mib 16384 \ -# --prefix-cache-dir +# --prefix-cache-mib 512 +# +# AND ENOUGH SNAPSHOT SLOTS FOR BOTH SESSIONS. On a hybrid model a hit is clamped to the deepest +# snapshot it reaches, and a store too small for both makes each session retire the other's: every +# arm then re-prefills from zero and restores nothing, so the device arm's reuse is checked below. +# The default --checkpoint-slots holds both. # # EACH SESSION IS COMPARED ONLY TO ITSELF. A and B are different prompts and their answers differ # for ordinary reasons; what must hold is that A's restored answer is A's cold answer. Corrupt @@ -23,7 +25,6 @@ set -e P=${P:-8100} H=${H:-127.0.0.1} TO_HOST=${TO_HOST:-10} -TO_DISK=${TO_DISK:-180} FILL=${FILL:-1200} N=${N:-48} work=$(mktemp -d "${TMPDIR:-/tmp}/tiercross.XXXXXX") @@ -108,12 +109,11 @@ cmp_arm() { # cmp_arm