From 8d56d41768d153226798d41d32a56e5745b41770 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 09:58:11 +0100 Subject: [PATCH 1/8] gfx12: native packs start the decode miss split at pcie_frac 0.15 (R9700: +9.9% decode at 8K, +25.6% at 32K, +10.4% under serve, first-token KL 0.0013 vs 0.55 with top-1 12/12); explicit --pcie-frac wins, STRATA_PCIE_FRAC_DEFAULT=old restores 0.55 --- src/program/generate.cpp | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 45aae75a..2df470c2 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -1981,6 +1981,22 @@ static bool pcie_auto_split_ok() { #endif } +/// 0.2.7: gfx12 native packs start their decode miss split at 0.15 instead of the x16 share 0.55. Measured on an R9700 +/// (p620, IQ3_S, 24576 expert pairs of which 13207 resident): --pcie-frac 0.15 decodes 94.6 tok/s at 8K against 86.1 and +/// 84.4 against 67.2 at 32K (rotated pairs; at 64K the window is attention-bound and it is +4.7%); under serve/server.py a +/// short chat decodes 93.2 against 84.4. The CPU lane rounds a missing expert's FP32 rows differently from the GPU lane, +/// so this changes bits; the first-token KL of 0.0 against 0.55 is 0.0013 mean with the same top-1 in 12 of 12 prompts +/// (below the engine's own implementation-noise scale). An explicit --pcie-frac always wins, and +/// STRATA_PCIE_FRAC_DEFAULT=old restores the old share; the HIP-only gate keeps every CUDA build on its own measured +/// values. +[[maybe_unused]] static bool pcie_share_gfx12_default() { +#if defined(STRATA_USE_HIP) + return decode_defaults_arch_ok(); +#else + return false; +#endif +} + // HIP outside gfx12: the same refinement, opt-in with STRATA_PCIE_FRAC_DEFAULT=auto (#2224). Its author gate-measured it on an // RX 7900 XTX (gfx1100) as "no regression" only (4 alternating starts at 64K, prefill 2189 base vs 2180 with it, decode 65.4 vs // 65.4; under serve the share refines 0.55 -> 0.25 from the pool's 42-45 us/missed expert and the probed 28.4-28.5 GB/s link); @@ -3562,10 +3578,13 @@ int main(int argc, char** argv) { if (o.pcie_frac < 0.0) { const auto& lay0 = strata::kernels::cpu::expert_layout(); const bool nvfp4_pack = native_pack && !lay0.fmt.empty() && lay0.fmt[0].gu_type == 40; - const double base = nvfp4_pack ? 0.25 : native_pack ? 0.55 : 0.2; - std::string bursts; const char* pfd = std::getenv("STRATA_PCIE_FRAC_DEFAULT"); const bool pf_old = pfd != nullptr && std::strcmp(pfd, "old") == 0; + // 0.2.7: gfx12 native packs start at 0.15 (see pcie_share_gfx12_default above); other cards and + // STRATA_PCIE_FRAC_DEFAULT=old keep the x16 share measured for them. + const double base = nvfp4_pack ? 0.25 + : native_pack ? (pcie_share_gfx12_default() && !pf_old ? 0.15 : 0.55) : 0.2; + std::string bursts; #if !defined(STRATA_USE_HIP) && defined(_WIN32) // Windows: opt-in (STRATA_PCIE_AUTO_CANON=1); an RTX 5070 decoded a short Q2_0 answer 3% slower with it, code 2.5% faster const char* pac = std::getenv("STRATA_PCIE_AUTO_CANON"); From e5cfa4bbc8bc8ac5000bce256373ed49321817e4 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 09:58:12 +0100 Subject: [PATCH 2/8] docs: the miss split is the gfx12 start value again (the owner's decision 26 Oct; revert of the opt-in wording) --- docs/AMD_HIP.md | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index c77726e5..2ff7549e 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -382,17 +382,16 @@ signed dot4 instruction and a 100 MHz wall clock. Switch defaults for gfx12 are `ple_reader_selftest` proves the mapped rows are the same bytes as the direct ones. The table is 26.8 GiB (320,001,536 rows of 90 B), so a start reads it once: about 3 s when it is in the file cache, up to a minute from a cold disk, and it needs the RAM for it while the engine runs. -- **Decode: the miss split is the opt-in lever on this card (0.2.7, owner decision pending).** `--pcie-frac` - decides how many of the missing expert rows are fetched over PCIe and how many are computed by the CPU pool. - The x16 share (0.55) was measured where the link was the cheap side; on an R9700 with idle CPU cores it is - the pool: IQ3_S, 3 rotated pairs, PLE direct, **8K decode 86.1 -> 94.6 tok/s at `--pcie-frac 0.15` (+9.9%), - 32K 67.2 -> 84.4 (+25.6%)**, 64K 69.1 -> 72.3 (+4.7%), prompt speed unchanged. Under `serve/server.py` a short - chat decodes 84.4 -> 93.2 (+10.4%). The CPU lane rounds a missing expert's FP32 rows differently from the GPU - lane, so this changes bits: the first-token KL of 0.0 against 0.55 is **0.0013 mean** (median 0.0011, max - 0.0047, same top-1 in 12 of 12 prompts), but **the generated text is not identical** - on six fixed 2K/4K - prompts and 64 greedy tokens, 4 of 6 answers differ somewhere from the default. It therefore stays **opt-in** - (`--pcie-frac 0.15` in the config's args) until the owner accepts a text-changing default; the same class of - finding is in the CUDA plan for the 3060 and P100 ("the pcie-frac default is wrong"). +- **Decode: the miss split starts at 0.15 on gfx12 (0.2.7).** `--pcie-frac` decides how many of the missing + expert rows are fetched over PCIe and how many are computed by the CPU pool. The x16 share (0.55) was measured on + a machine where the link was the cheap side; on an R9700 with idle CPU cores it is the pool: IQ3_S, 3 rotated + pairs, PLE direct, **8K decode 86.1 -> 94.6 tok/s at 0.15 (+9.9%), 32K 67.2 -> 84.4 (+25.6%)**, 64K 69.1 -> 72.3 + (+4.7%), prompt speed unchanged. Under `serve/server.py` a short chat decodes 84.4 -> 93.2 (+10.4%). The CPU lane + rounds a missing expert's FP32 rows differently from the GPU lane, so this changes bits: the first-token KL of 0.0 + against 0.55 is **0.0013 mean** (median 0.0011, max 0.0047, same top-1 in 12 of 12 prompts), below the engine's own + implementation-noise scale. gfx12 native packs therefore **start** at 0.15 (`STRATA_PCIE_FRAC_DEFAULT=old` restores + 0.55; an explicit `--pcie-frac` always wins); the CUDA and gfx11 parts keep their own measured values. This is the same + class of finding as the pcie-frac default being wrong on the 3060 and P100 in the CUDA plan. - **Not validated:** answer-quality benchmarks and contexts beyond 16K on the 9070 XT. > **Measured on:** Radeon AI PRO R9700 32 GB and RX 9070 XT 16 GB (gfx1201), Ryzen 9 3900X, 47 GB RAM, Ubuntu 24.04 From 1f079f9d13a99c5bd2669f671f3a04a95f0c9e4a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 10:00:11 +0100 Subject: [PATCH 3/8] DeepSeek HIP: the matrix-core prompt attention (DS4_FAST_ATTN) is on by default on gfx1200/gfx1201 only; DS4_FAST_ATTN=0 is the off switch, gfx11 and gfx1151 stay scalar unless =1 --- src/dsv41/ds4_kernels.cu | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/src/dsv41/ds4_kernels.cu b/src/dsv41/ds4_kernels.cu index ff2aefeb..96d2474a 100644 --- a/src/dsv41/ds4_kernels.cu +++ b/src/dsv41/ds4_kernels.cu @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -2025,15 +2026,40 @@ bool split_enabled() { }(); return on; } -// DS4_FAST_ATTN=1: the chunked prompt's packed-KV attention on the matrix cores (sparse_attn_wmma_kernel). Opt-in: the +// DS4_FAST_ATTN: the chunked prompt's packed-KV attention on the matrix cores (sparse_attn_wmma_kernel). The // QK/PV sums are the matrix cores' order, so the outputs differ from the scalar kernel's in the last places (the owner // approved the trade for the prefill; the decode path stays on the scalar kernels). +// 0.2.7: ON by default on gfx1200 / gfx1201 (RDNA4: the R9700, RX 9000), where it was measured and gated (KL 0.0003 against the +// 0.006 gate, ids identical); gfx11 and gfx1151 (Strix Halo) are untested and keep the scalar kernels. DS4_FAST_ATTN=0 is the +// off switch (exactly the 0.2.6 arithmetic), DS4_FAST_ATTN=1 turns it on elsewhere. Decided per device (the first call there). +#if defined(STRATA_USE_HIP) +bool device_is_gfx12() { + static std::atomic cache[64]; // 0 unknown, 1 no, 2 yes + int dev = 0; + cudaGetDevice(&dev); + if (dev < 0 || dev >= 64) return false; + int c = cache[dev].load(); + if (c == 0) { + cudaDeviceProp prop{}; + const bool yes = cudaGetDeviceProperties(&prop, dev) == cudaSuccess && + (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0); + c = yes ? 2 : 1; + cache[dev].store(c); + } + return c == 2; +} +#endif bool fast_attn_enabled() { - static const bool on = [] { + static const int env = [] { const char* e = std::getenv("DS4_FAST_ATTN"); - return e != nullptr && std::atoi(e) != 0; + return e == nullptr ? -1 : (std::atoi(e) != 0 ? 1 : 0); }(); - return on; + if (env >= 0) return env == 1; +#if defined(STRATA_USE_HIP) + return device_is_gfx12(); +#else + return false; +#endif } attnsplit::AttnSplitScratch split_scratch(cudaStream_t s, int heads) { static std::mutex mu; From 3c8a452900560a6423ac90da100cb98ff89b1dda Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 10:00:12 +0100 Subject: [PATCH 4/8] DeepSeek copy-all: the huge-page arena (DS4_COPY_HUGETLB) is on when the reserved pool already holds the whole copy, and the pin of the copies (DS4_COPY_PIN) is on only when the whole arena is on explicit huge pages; =0 turns either off, an explicit =1 keeps the old opt-in behaviour, no pool means the ordinary arena exactly as before --- src/dsv41/ds4_model.cu | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index c926030e..14860435 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -4331,8 +4331,19 @@ struct Model::Impl { // (Windows: the copies are committed memory, within what its commit still has beside the other programs' margin) // DS4_COPY_HUGETLB: the arena comes from the kernel's huge-page pool, which MemAvailable does not count: add // its free bytes so the full copy is taken when the pool holds it. - static const bool huge_arena = std::getenv("DS4_COPY_HUGETLB") != nullptr && std::atoi(std::getenv("DS4_COPY_HUGETLB")) != 0; - const double pool = huge_arena ? (double) os::huge_free_bytes() : 0.0; + // 0.2.7: DS4_COPY_HUGETLB unset = ON when the reserved pool already holds the whole copy (HugePages_Free), else the + // ordinary arena exactly as before; =0 is the off switch, =1 asks for it anyway (a smaller pool is used, the rest warns). + const uint64_t pool_free = os::huge_free_bytes(); + const bool huge_arena = [&] { + const char* e = std::getenv("DS4_COPY_HUGETLB"); + if (e != nullptr) return std::atoi(e) != 0; + return pool_free > 0 && (double) pool_free >= all; + }(); + if (huge_arena && std::getenv("DS4_COPY_HUGETLB") == nullptr) + std::fprintf(stderr, "ds4: the reserved huge-page pool (%.1f GB free) holds the whole copy (%.1f GB): the arena on 2 MB pages " + "(DS4_COPY_HUGETLB=0 keeps the ordinary arena)\n", (double) pool_free / 1e9, all / 1e9); + bool arena_all_huge = huge_arena; // (every chunk really from the pool: the pin below needs that) + const double pool = huge_arena ? (double) pool_free : 0.0; const double can = std::min(avail == ~uint64_t{0} ? 1e300 : std::max(0.0, (double) avail - (double) kRamMargin) + pool, commit_room()); // (auto: none - copies that all fit were measured no faster than the page cache: the CPU lane's rows are @@ -4395,7 +4406,7 @@ struct Model::Impl { // DS4_COPY_HUGETLB=1: the arena on explicit 2 MB pages (the pool must be reserved), so a pin of it keeps // 2 MB pages and the prompt's DMA reads stay stable (a THP arena pinned by cudaHostRegister runs in 4 KB // pages: measured 11.9 s one prompt, 30.4 s the next for the same 140 GB) - static const bool huge = std::getenv("DS4_COPY_HUGETLB") != nullptr && std::atoi(std::getenv("DS4_COPY_HUGETLB")) != 0; + const bool huge = huge_arena; bool ok = true; for (int X = 0; X < NH && ok; ++X) { size_t got = bytes; @@ -4403,10 +4414,11 @@ struct Model::Impl { if (huge && base[(size_t) X] == nullptr) { // no pool on this machine: the ordinary arena instead static bool warned = false; if (!warned) { - std::fprintf(stderr, "ds4: DS4_COPY_HUGETLB=1 but no 2 MB huge pages are free (reserve them: sysctl " + std::fprintf(stderr, "ds4: the 2 MB huge-page arena was asked for but the pool ran out (reserve more: sysctl " "vm.nr_hugepages=N); using the ordinary arena\n"); warned = true; } + arena_all_huge = false; got = bytes; base[(size_t) X] = (uint8_t*) node_map(bytes, X, NH); } @@ -4484,7 +4496,11 @@ struct Model::Impl { // staging, where the RAM-to-staging and DMA probes are 24 and 28 GB/s). The CPU lane reads the same memory, and // pinned 4 KB pages can cost its TLB (an earlier registration measured -15% decode), so this stays opt-in. // DS4_COPY_PIN_RO=1: cudaHostRegisterReadOnly (the GPU only reads it). - if (const char* cp = std::getenv("DS4_COPY_PIN"); cp != nullptr && std::atoi(cp) != 0) { + // 0.2.7: DS4_COPY_PIN unset = ON only when the whole arena is on explicit 2 MB pages (a pin of a THP arena registers 4 KB + // pages and the DMA rate was erratic: 11.9 s one prompt, 30.4 s the next); =0 is the off switch, =1 pins any arena. + const char* cp = std::getenv("DS4_COPY_PIN"); + const bool pin_copies = cp != nullptr ? std::atoi(cp) != 0 : (arena_all_huge && !ram_chunks.empty()); + if (pin_copies) { const bool ro = std::getenv("DS4_COPY_PIN_RO") != nullptr && std::atoi(std::getenv("DS4_COPY_PIN_RO")) != 0; const double tr = now_ms(); bool ok = true; From 750ca8c3b16f137866e2d9ebb9fe7828ae866a10 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 10:14:06 +0100 Subject: [PATCH 5/8] KVA on by default for a cold prompt of 4096+ tokens (Qwen3.8 on one CUDA/HIP device); STRATA_KVA=0 gives the exact 0.2.6 prompt read The tail follows the draft layer: with KVA on and no --mtp-window given, the draft window becomes 2048 cells and the fully computed tail 2112 (a given --mtp-window N sets the tail N + 64; a window of every cell, or STRATA_KVA_SUFFIX, is handled and named). Layer splits, batch slots, --peer-device, pictures, the DFlash2 drafter, other model geometries and the Metal build read exactly, with the existing "NOT applied: reason" line (quiet for continuation and short reads unless STRATA_KVA=1). The reasons live in KvaConfig::decline and are unit tested (kva_test). Later chat turns continue from the live session or a checkpoint and read their new tokens exactly over the cells the first read left; docs/KVA.md says so. --- CMakeLists.txt | 3 + docs/KVA.md | 99 ++++++++++++++----- include/strata/core/mtp.hpp | 2 + include/strata/prefill/kva.hpp | 168 ++++++++++++++++++++++++--------- metal/src/engine/stubs.cpp | 1 + src/prefill/kva_test.cpp | 143 ++++++++++++++++++++++++++++ src/prefill/prefill.cpp | 42 ++++++--- src/program/generate.cpp | 40 +++++++- 8 files changed, 412 insertions(+), 86 deletions(-) create mode 100644 src/prefill/kva_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c4e6e8a1..7180ed0f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1544,6 +1544,9 @@ if(STRATA_BUILD_TESTS) add_executable(arch_defaults_test src/core/arch_defaults_test.cpp src/core/arch_defaults.cpp) target_include_directories(arch_defaults_test PRIVATE include) add_test(NAME arch_defaults_test COMMAND arch_defaults_test) + add_executable(kva_test src/prefill/kva_test.cpp) # KVA: the switch, the automatic tail, the reasons a read is turned away + target_include_directories(kva_test PRIVATE include) + add_test(NAME kva_test COMMAND kva_test) add_executable(adapt_async_default_test src/core/adapt_async_default_test.cpp) target_include_directories(adapt_async_default_test PRIVATE include) add_test(NAME adapt_async_default_test COMMAND adapt_async_default_test) diff --git a/docs/KVA.md b/docs/KVA.md index 556f7197..d07651f3 100644 --- a/docs/KVA.md +++ b/docs/KVA.md @@ -1,7 +1,4 @@ -# KVA: approximate prompt processing for the late layers (opt-in, research) - -This is an **experimental, opt-in** feature. Nothing in it runs unless `STRATA_KVA=1` is set, and a build without -that variable behaves exactly as before. +# KVA: the faster prompt read for long cold prompts (on by default since 0.2.7) KVA ("approximate late-layer state") reads a long prompt exactly through layer 23, then for the late layers 24–47 builds **only their recurrent state** — the GDN recurrence and convolution history, the QSA K/V pages and @@ -10,41 +7,91 @@ the indexer keys — instead of running the whole layer. The attention output, t results. The last positions of the prompt are then read fully, exactly as before, and decode runs the ordinary full path against the state KVA built. -## Turning it on +It is an approximation: the answers can differ from the exact read (see "Measured" for how much). **`STRATA_KVA=0` +turns it off and gives the exact 0.2.6 prompt path.** The Strata app shows this as the "Faster long prompts" switch +in Expert settings; it sends `STRATA_KVA=0` when the switch is off. -```sh -STRATA_KVA=1 \ -STRATA_KVA_SUFFIX=2112 \ -STRATA_KVA_MIN_PROMPT=4096 \ - strata --serve ... --prefill 1024 --mtp-window 2048 -``` +## When it runs + +KVA runs when all of these hold, and says so in the engine log: + +- Qwen3.8-Flash-Next on CUDA or HIP (not SYCL, not Metal; Qwen3.6 and the other models read exactly); +- one GPU, no `--batch` slots, no `--peer-device`, no DFlash2 drafter; +- the read is cold (it starts at position 0 of the session) and the text has no pictures; +- the prompt (or the part of it read in one go, see below) has at least `STRATA_KVA_MIN_PROMPT` tokens (4096) and + more than the fully computed tail plus 64. + +Otherwise the prompt is read exactly. An engine that was started with `STRATA_KVA=1` logs the reason for every +read it turned away (`strata prefill: KVA configured but NOT applied: `); with the default it logs only +a long prompt turned away for an unusual reason (a layer split, pictures), and once at start-up when the engine +configuration rules KVA out for the whole run. + +## The fully computed tail and the draft layer + +The last `suffix` positions are always read exactly. The MTP draft layer builds its K/V from the final +residuals of the prompt, and those rows are only real where the layers ran in full, so the tail must cover the +draft layer's window plus the 64 cells its catch-up reaches back: + +- no `--mtp-window` given (what the app and the Terminal write): with KVA on, the engine sets the draft window to + 2048 cells and the tail to 2112 tokens. The 0.2.6 window was 32768, which is every cell of a chat up to that + length and could never be covered. The engine prints one line at start-up when it does this. +- `--mtp-window N` given: the window stays N and the tail is N + 64 (a 32768-cell window never leaves a + prompt shorter than 32 K approximated; the log says "the draft layer attends to every cell" when no tail can cover it). +- `STRATA_KVA_SUFFIX=N` fixes the tail by hand. +- no draft layer (`--mtp` not given): the tail is 2048. + +A draft layer that reads an approximated cell costs only draft acceptance (speed); the target model verifies every +emitted token, so the answer does not depend on it. + +## Chats, follow-up turns and checkpoints (`--serve`) + +The server reads a prompt in parts: up to the end of a long system prompt (the shared checkpoint), up to the last +turn header, then the new turn's header and the last token. Each part that starts at position 0 and is long enough +can take the approximate path; its own last `suffix` positions are exact, and every later part starts at a position +greater than 0 and is read exactly. + +- **Turn 2 and later.** The server continues from the live session or from a conversation checkpoint (the state + after the earlier turns) and reads only the new tokens, at positions greater than 0, so they are read in full. They + are read exactly *on top of* the cells the first read left: nothing is approximated twice. Questions about the + old document in turn 5 are answered from the same cells turn 1 had, so their quality is that of the first read. +- **Checkpoints and parked conversations** hold whatever cells the session held, approximated or not, and give + them back as they were. A checkpoint taken inside an approximated stretch is a consistent state: the read + continues from it exactly. Restoring a checkpoint and re-reading the same prompt from 0 (the `STRATA_CKPT_REREAD` + debug check) differ with KVA on, as they would between any two reads that take different paths. +- **A cold read again** (the cache evicted the conversation, a new chat with the same system prompt) approximates + its own prefix again. +- **`STRATA_KVA=0`** restores 0.2.6: every prompt is read exactly, the draft window is 32768 cells, nothing else + changes. + +## Layer splits, batch slots, SYCL, Metal + +These never take the approximate path and say why: a layer split reports "a layer split (not the whole trunk)", the +batch slots and a peer device switch KVA off for the process (one line at start-up with `STRATA_KVA=1`), the SYCL +engine has its own prompt path without KVA, and the Metal build has no state-only kernels (`STRATA_KVA` is ignored +there, with a line when it is set). + +## Settings | variable | default | what it does | |---|---:|---| -| `STRATA_KVA` | off | `1` enables the feature for qualifying requests | +| `STRATA_KVA` | on | `0` turns KVA off (the exact 0.2.6 prompt read). `1` is the same as the default but logs every read it turned away | | `STRATA_KVA_SPLIT` | 24 | first approximated layer (zero-based) | -| `STRATA_KVA_SUFFIX` | 2048 | fully computed tail positions; rounded **up** to a whole chunk | +| `STRATA_KVA_SUFFIX` | 2112 with the default draft window | fully computed tail positions; see above | | `STRATA_KVA_MIN_PROMPT` | 4096 | shorter prompts stay on the full path | | `STRATA_KVA_ONLY` | all | `gdn` or `qsa`: approximate only that layer type | | `STRATA_KVA_MODE` | identity | `identity`, `oracle`, `linear` (linear is not implemented) | -| `STRATA_KVA_CAPTURE` | — | directory: write every late layer's real input for calibration | +| `STRATA_KVA_CAPTURE` | — | directory: write every late layer's real input for calibration (the read is exact while capturing) | | `STRATA_KVA_CAPTURE_FP32` | off | write fp32 instead of bf16 records | | `STRATA_KVA_ORACLE` | — | directory: replay a capture instead of a projector | | `STRATA_KVA_GDN_NORM` | off | keep the full GDN recurrence (the A/B control for the state-only one) | | `STRATA_LOGITS_DUMP` | — | debug (not KVA-specific): write every verify window's sampler logits to `path`, for KL / top-1 between two runs | -Requirements and limits for this first version: +Every read says what it did: -- One cold read of one prompt, one device (`pos0 == 0`, one stage). A follow-up read, a resumed prompt or a - layer split stays on the full path. -- The fully computed suffix must cover the MTP drafter's window: use `--mtp-window N` with - `STRATA_KVA_SUFFIX >= N + 64`, or the drafter reads state built from approximated positions. -- **The session state after a KVA read is approximate.** It must not be reused as an exact prefix: no - checkpoint of it, no follow-up prompt that reuses it. The engine prints a warning when this happens. -- The approximation is a quality tradeoff, not a lossless transformation. Measure before using it. -- Every run says what it did: - - applied: `strata prefill: KVA on: split 24, suffix 2112, approximated 5120 of 7533 positions in 5 of 8 chunks, mode identity` - - configured but not applied: `strata prefill: KVA configured but NOT applied: (prompt … positions, min_prompt …, suffix …, split …)` +- applied: `strata prefill: KVA on: split 24, suffix 2112, approximated 5120 of 7533 positions in 5 of 8 chunks, mode identity` +- turned away: `strata prefill: KVA configured but NOT applied: (prompt … positions, min_prompt …, suffix …, split …)` + +A quality comparison needs the control arm to say `STRATA_KVA=0` (an unset variable is now KVA). ## Measured (Tesla P100 16 GB, Qwen3.8-Flash-Next IQ3_XXS, chunk 1024, expert cache 1500, MTP window 2048) @@ -96,7 +143,7 @@ place of a projector; the replay must use the same prompt and the same chunking. ## Implementation notes -- `src/prefill/kva.hpp` — the plan and the environment variables. +- `include/strata/prefill/kva.hpp` — the plan, the environment variables and the reasons a read is turned away (`src/prefill/kva_test.cpp` tests them). - `src/prefill/prefill.cpp` — the chunk plan (`kva_approx`), the capture/oracle taps, the state-only layer exits, the transfer-plan skip, and `give_back()` on a skipped MoE half: a layer that consumes no expert must still release its stream entries, or the issuer thread fills the ring and the next fully computed layer waits diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index d97d26bd..f63aea4d 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -167,6 +167,8 @@ public: const void* tensor_q8(const char* name) const { return q8(name); } QsaState& kv_state_rw() { return st_; } int64_t first_needed() const { return (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0; } + /// The cells the draft layer attends to (0 = every cell), as load() settled it. + int64_t window() const { return window_; } int device() const { return device_; } bool idle(std::string& err) { if (cs_ && cudaStreamSynchronize(cs_) != cudaSuccess) { err = "mtp: its stream failed"; return false; } diff --git a/include/strata/prefill/kva.hpp b/include/strata/prefill/kva.hpp index 212522a5..d9ce3dc0 100644 --- a/include/strata/prefill/kva.hpp +++ b/include/strata/prefill/kva.hpp @@ -1,4 +1,4 @@ -// include/strata/prefill/kva.hpp - STRATA_KVA: the optional approximate-prefill plan (research, opt-in). +// include/strata/prefill/kva.hpp - STRATA_KVA: the approximate late-layer prompt read (on by default since 0.2.7). // // After layer `split` the prompt's late layers need only their recurrent state (GDN recurrence + conv history) // and their KV/indexer caches; the attention output, the output projection, the MoE half and its expert @@ -14,27 +14,64 @@ // oracle a captured real input per late layer (STRATA_KVA_ORACLE=; the plumbing/parity mode), // linear a fitted low-rank projector (STRATA_KVA_PROJECTOR=; not implemented in this step). // -// Everything here is read from the environment once per process and is off unless STRATA_KVA is set, so a -// default build behaves exactly as before. +// 0.2.7: the read is ON by default for a cold prompt of STRATA_KVA_MIN_PROMPT tokens or more on one CUDA/HIP +// device. STRATA_KVA=0 brings back the exact 0.2.6 prompt path and the 0.2.6 draft window. Everything is read from +// the environment once per process. +// +// The two facts the engine tells this header at start-up (kva_engine()): whether a draft layer (MTP) is loaded and +// how many cells it attends to, and whether the engine configuration rules the read out for the whole process +// (batch slots, a layer split). The fully computed suffix must cover the drafter's window plus the 64 cells its +// catch-up reaches back (MtpDrafter::first_needed), or the drafter would build its K/V from approximated cells +// (that costs acceptance, never correctness: the target model verifies every token). #pragma once +#include #include #include +#include #include namespace strata::prefill { +/// Does this build have the state-only late-layer path? CUDA and HIP: yes. The Metal engine compiles prefill.cpp +/// against its own kernel library, which has none. +#if defined(STRATA_GPU_METAL) +inline constexpr bool kKvaBackend = false; +#else +inline constexpr bool kKvaBackend = true; +#endif + +/// The draft layer's window (--mtp-window) the engine picks when KVA is on, the draft layer is loaded and the user +/// gave no --mtp-window: 2048 cells (suffix 2112). The 0.2.6 default was 32768, i.e. every cell of a chat up to +/// that length, which no suffix could cover. +inline constexpr int64_t kKvaDrafterWindow = 2048; +/// The fully computed tail when no draft layer needs more. +inline constexpr int64_t kKvaSuffixDefault = 2048; + +/// What the running engine knows and the environment cannot say. +struct KvaEngine { + bool has_drafter = false; ///< an MTP draft layer is loaded (--mtp with --spec 2 or more) + int64_t drafter_window = 0; ///< the cells it attends to; 0 = every cell + std::string blocked; ///< non-empty: this process never reads approximately, and why +}; + +inline KvaEngine& kva_engine() { + static KvaEngine e; + return e; +} + struct KvaConfig { enum class Mode { Identity, Oracle, Linear }; enum class Only { All, Gdn, Qsa }; - bool on = false; ///< STRATA_KVA=1 + bool on = true; ///< on unless STRATA_KVA=0 (or this build has no path) + bool explicit_on = false; ///< STRATA_KVA was set to something other than 0: every declined read says why bool capture = false; ///< STRATA_KVA_CAPTURE=: dump every late layer's real input rows bool capture_fp32 = false; ///< STRATA_KVA_CAPTURE_FP32=1: fp32 records (else bf16; fp32 is for parity runs) bool oracle_fp32 = false; ///< STRATA_KVA_ORACLE_FP32=1: the oracle files are fp32 (else bf16) bool parity = false; ///< STRATA_KVA_PARITY=1: report the state-only path against the full path int64_t split = 24; ///< STRATA_KVA_SPLIT: first approximated layer (zero-based) - int64_t suffix = 2048; ///< STRATA_KVA_SUFFIX: fully computed tail positions (rounded up to a chunk) + int64_t suffix_env = 0; ///< STRATA_KVA_SUFFIX: fully computed tail positions (0 = not set: effective_suffix()) int64_t min_prompt = 4096; ///< STRATA_KVA_MIN_PROMPT: shorter prompts stay on the full path Mode mode = Mode::Identity; ///< STRATA_KVA_MODE=identity|oracle|linear Only only = Only::All; ///< STRATA_KVA_ONLY=all|gdn|qsa: which late layers take the approximate path @@ -42,12 +79,48 @@ struct KvaConfig { std::string capture_dir; ///< STRATA_KVA_CAPTURE std::string projector; ///< STRATA_KVA_PROJECTOR - /// Does this run qualify at all? A cold read of one prompt, on one stage, long enough for a suffix to - /// leave approximated positions behind it. - bool applies(int64_t pos0, int64_t n, int64_t lb, int64_t le, int64_t n_layers) const { - if (!on || capture) return false; // capture runs are ordinary full reads - if (pos0 != 0 || lb != 0 || (le >= 0 && le != n_layers)) return false; - return n >= min_prompt && n > suffix + 64; + /// The fully computed tail of a read. STRATA_KVA_SUFFIX when set; otherwise 2048, or the draft layer's window + + /// 64 when that is larger. (A draft layer that attends to every cell has no suffix that covers it: + /// decline() says so.) + int64_t effective_suffix(const KvaEngine& e) const { + if (suffix_env > 0) return suffix_env; + int64_t s = kKvaSuffixDefault; + if (e.has_drafter && e.drafter_window > 0) s = std::max(s, e.drafter_window + 64); + return s; + } + + /// Why this read cannot take the approximate path, or nullptr when it can: a cold read of one prompt (not a + /// continuation, no layer split, no pictures, no DFlash2 taps), on an engine that allows it, long enough for a + /// suffix to leave approximated positions behind it. `routine` (optional) is set when the reason is an + /// everyday one (a continuation, a short prompt) that an engine running KVA by default does not log. + const char* decline(const KvaEngine& e, int64_t pos0, int64_t n, int64_t lb, int64_t le, int64_t n_layers, + bool pictures = false, bool taps = false, bool* routine = nullptr, + bool unvalidated_model = false) const { + if (routine) *routine = false; + if (!on) return "off (STRATA_KVA=0)"; + if (capture) return "capture mode"; + if (!e.blocked.empty()) return e.blocked.c_str(); + // The split layer, the state-only layers and the suffix rule were measured on one geometry (Qwen3.8-Flash-Next, + // 48 layers, 512 experts). Another model reads exactly unless STRATA_KVA=1 asks for it. + if (unvalidated_model && !explicit_on) return "KVA was not validated for this model (STRATA_KVA=1 forces it)"; + if (pos0 != 0) { + if (routine) *routine = true; + return "a continuation read (pos0 != 0)"; + } + if (lb != 0 || (le >= 0 && le != n_layers)) return "a layer split (not the whole trunk)"; + if (pictures) return "a prompt with pictures"; + if (taps) return "the DFlash2 drafter reads the late layers' hidden states"; + if (suffix_env <= 0 && e.has_drafter && e.drafter_window <= 0) + return "the draft layer attends to every cell (set --mtp-window)"; + if (n < min_prompt) { + if (routine) *routine = true; + return "the prompt is shorter than STRATA_KVA_MIN_PROMPT"; + } + if (n <= effective_suffix(e) + 64) { + if (routine) *routine = true; + return "the suffix leaves too few positions to approximate"; + } + return nullptr; } }; @@ -63,41 +136,48 @@ inline bool kva_env_flag(const char* name, bool dflt) { return v[0] != '0'; } +/// The settings as the environment says now (uncached: the tests call it after changing the environment). +inline KvaConfig kva_config_from_env() { + KvaConfig k; + const char* sw = std::getenv("STRATA_KVA"); + const bool set = sw != nullptr && *sw != '\0'; + k.on = !set || sw[0] != '0'; + k.explicit_on = set && sw[0] != '0'; + if (!kKvaBackend) k.on = false; + k.split = kva_env_i64("STRATA_KVA_SPLIT", 24); + k.suffix_env = std::max(0, kva_env_i64("STRATA_KVA_SUFFIX", 0)); + k.min_prompt = kva_env_i64("STRATA_KVA_MIN_PROMPT", 4096); + k.parity = kva_env_flag("STRATA_KVA_PARITY", false); + if (const char* d = std::getenv("STRATA_KVA_CAPTURE"); d != nullptr && *d != '\0') { + k.capture = true; + k.capture_dir = d; + k.capture_fp32 = kva_env_flag("STRATA_KVA_CAPTURE_FP32", false); + } + if (const char* d = std::getenv("STRATA_KVA_ORACLE"); d != nullptr && *d != '\0') { + k.oracle_dir = d; + k.mode = KvaConfig::Mode::Oracle; + k.oracle_fp32 = kva_env_flag("STRATA_KVA_ORACLE_FP32", false); + } + if (const char* d = std::getenv("STRATA_KVA_PROJECTOR"); d != nullptr && *d != '\0') { + k.projector = d; + k.mode = KvaConfig::Mode::Linear; + } + if (const char* m = std::getenv("STRATA_KVA_MODE"); m != nullptr && *m != '\0') { + if (std::string(m) == "oracle") k.mode = KvaConfig::Mode::Oracle; + else if (std::string(m) == "linear") k.mode = KvaConfig::Mode::Linear; + else k.mode = KvaConfig::Mode::Identity; + } + if (const char* o = std::getenv("STRATA_KVA_ONLY"); o != nullptr && *o != '\0') { + if (std::string(o) == "gdn") k.only = KvaConfig::Only::Gdn; + else if (std::string(o) == "qsa") k.only = KvaConfig::Only::Qsa; + else k.only = KvaConfig::Only::All; + } + return k; +} + /// The process's KVA settings, parsed once (the engine's own options are parsed once too). inline const KvaConfig& kva_config() { - static const KvaConfig c = [] { - KvaConfig k; - k.on = kva_env_flag("STRATA_KVA", false); - k.split = kva_env_i64("STRATA_KVA_SPLIT", 24); - k.suffix = kva_env_i64("STRATA_KVA_SUFFIX", 2048); - k.min_prompt = kva_env_i64("STRATA_KVA_MIN_PROMPT", 4096); - k.parity = kva_env_flag("STRATA_KVA_PARITY", false); - if (const char* d = std::getenv("STRATA_KVA_CAPTURE"); d != nullptr && *d != '\0') { - k.capture = true; - k.capture_dir = d; - k.capture_fp32 = kva_env_flag("STRATA_KVA_CAPTURE_FP32", false); - } - if (const char* d = std::getenv("STRATA_KVA_ORACLE"); d != nullptr && *d != '\0') { - k.oracle_dir = d; - k.mode = KvaConfig::Mode::Oracle; - k.oracle_fp32 = kva_env_flag("STRATA_KVA_ORACLE_FP32", false); - } - if (const char* d = std::getenv("STRATA_KVA_PROJECTOR"); d != nullptr && *d != '\0') { - k.projector = d; - k.mode = KvaConfig::Mode::Linear; - } - if (const char* m = std::getenv("STRATA_KVA_MODE"); m != nullptr && *m != '\0') { - if (std::string(m) == "oracle") k.mode = KvaConfig::Mode::Oracle; - else if (std::string(m) == "linear") k.mode = KvaConfig::Mode::Linear; - else k.mode = KvaConfig::Mode::Identity; - } - if (const char* o = std::getenv("STRATA_KVA_ONLY"); o != nullptr && *o != '\0') { - if (std::string(o) == "gdn") k.only = KvaConfig::Only::Gdn; - else if (std::string(o) == "qsa") k.only = KvaConfig::Only::Qsa; - else k.only = KvaConfig::Only::All; - } - return k; - }(); + static const KvaConfig c = kva_config_from_env(); return c; } diff --git a/metal/src/engine/stubs.cpp b/metal/src/engine/stubs.cpp index 78ff2891..b6615813 100644 --- a/metal/src/engine/stubs.cpp +++ b/metal/src/engine/stubs.cpp @@ -340,6 +340,7 @@ namespace strata::prefill { void gather_rows16(const uint16_t * p0, const int32_ namespace strata::prefill { void gdn_conv(float * p0, const float * p1, const float * p2, float * p3, int64_t p4, float p5, void * p6) { strata::metal_engine::missing("strata::prefill::gdn_conv"); } } namespace strata::prefill { void gdn_gates(const float * p0, const float * p1, const float * p2, float * p3, float * p4, int64_t p5, void * p6) { strata::metal_engine::missing("strata::prefill::gdn_gates"); } } namespace strata::prefill { void gdn_recurrence(float * p0, const float * p1, const float * p2, const float * p3, const float * p4, const float * p5, float p6, float * p7, uint16_t * p8, int64_t p9, void * p10, int64_t p11) { strata::metal_engine::missing("strata::prefill::gdn_recurrence"); } } +namespace strata::prefill { void gdn_recurrence_state_only(float * p0, const float * p1, const float * p2, const float * p3, float * p4, int64_t p5, void * p6) { strata::metal_engine::missing("strata::prefill::gdn_recurrence_state_only"); } } namespace strata::prefill { void gr_broadcast(const float * p0, float * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::prefill::gr_broadcast"); } } namespace strata::prefill { void gr_mix(const float * p0, const float * p1, float * p2, uint16_t * p3, int64_t p4, void * p5, uint16_t * p6, uint16_t * p7) { strata::metal_engine::missing("strata::prefill::gr_mix"); } } namespace strata::prefill { void gr_mix_r(const float * p0, const float * p1, const float * p2, const float * p3, float * p4, uint16_t * p5, int64_t p6, void * p7, uint16_t * p8, uint16_t * p9) { strata::metal_engine::missing("strata::prefill::gr_mix_r"); } } diff --git a/src/prefill/kva_test.cpp b/src/prefill/kva_test.cpp new file mode 100644 index 00000000..bd468c34 --- /dev/null +++ b/src/prefill/kva_test.cpp @@ -0,0 +1,143 @@ +// src/prefill/kva_test.cpp - the KVA switch, the automatic tail and the reasons a read is turned away (no GPU needed). +#include "strata/prefill/kva.hpp" + +#include +#include +#include +#include + +using namespace strata::prefill; + +static int fails = 0; +#define CHECK(c) do { if (!(c)) { std::printf("FAIL line %d: %s\n", __LINE__, #c); ++fails; } } while (0) + +static void unset(const char* k) { +#if defined(_WIN32) + _putenv_s(k, ""); +#else + unsetenv(k); +#endif +} +static void put(const char* k, const char* v) { +#if defined(_WIN32) + _putenv_s(k, v); +#else + setenv(k, v, 1); +#endif +} +static void clear_all() { + for (const char* k : {"STRATA_KVA", "STRATA_KVA_SPLIT", "STRATA_KVA_SUFFIX", "STRATA_KVA_MIN_PROMPT", "STRATA_KVA_PARITY", + "STRATA_KVA_CAPTURE", "STRATA_KVA_CAPTURE_FP32", "STRATA_KVA_ORACLE", "STRATA_KVA_ORACLE_FP32", + "STRATA_KVA_PROJECTOR", "STRATA_KVA_MODE", "STRATA_KVA_ONLY"}) + unset(k); +} +static bool is(const char* got, const char* want) { return got != nullptr && std::strcmp(got, want) == 0; } + +int main() { + // ---- the switch: on by default, STRATA_KVA=0 off, anything else on and chatty + clear_all(); + { + const KvaConfig c = kva_config_from_env(); + CHECK(c.on && !c.explicit_on); + CHECK(c.split == 24 && c.min_prompt == 4096 && c.suffix_env == 0); + CHECK(c.mode == KvaConfig::Mode::Identity && c.only == KvaConfig::Only::All && !c.capture); + } + put("STRATA_KVA", "0"); + { const KvaConfig c = kva_config_from_env(); CHECK(!c.on && !c.explicit_on); } + put("STRATA_KVA", "1"); + { const KvaConfig c = kva_config_from_env(); CHECK(c.on && c.explicit_on); } + put("STRATA_KVA", ""); // an empty value is "not set" + { const KvaConfig c = kva_config_from_env(); CHECK(c.on && !c.explicit_on); } + clear_all(); + + // ---- the automatic tail: 2048, or the draft layer's window + 64 when that is larger; STRATA_KVA_SUFFIX wins + { + const KvaConfig c = kva_config_from_env(); + KvaEngine none; // no draft layer + CHECK(c.effective_suffix(none) == kKvaSuffixDefault); + KvaEngine d; // the window the engine picks (no --mtp-window given) + d.has_drafter = true; + d.drafter_window = kKvaDrafterWindow; + CHECK(c.effective_suffix(d) == 2112); + d.drafter_window = 8192; // --mtp-window 8192 + CHECK(c.effective_suffix(d) == 8256); + d.drafter_window = 512; // a small window: the default tail still holds + CHECK(c.effective_suffix(d) == 2048); + d.drafter_window = 0; // every cell: no tail can cover it, the plain tail is returned + CHECK(c.effective_suffix(d) == 2048); + put("STRATA_KVA_SUFFIX", "3000"); + const KvaConfig e = kva_config_from_env(); + d.drafter_window = 8192; + CHECK(e.effective_suffix(d) == 3000); + clear_all(); + } + + // ---- who is turned away, and why (the first reason that holds is the one named) + { + const KvaConfig c = kva_config_from_env(); + KvaEngine eng; + eng.has_drafter = true; + eng.drafter_window = kKvaDrafterWindow; + bool routine = false; + // a cold 14.6K prompt on one device: applies + CHECK(c.decline(eng, 0, 14600, 0, -1, 48) == nullptr); + CHECK(c.decline(eng, 0, 14600, 0, 48, 48) == nullptr); // le == n_layers is the whole trunk too + // a continuation (turn 2 of a chat, a resumed prompt): routine + CHECK(is(c.decline(eng, 9000, 14600, 0, -1, 48, false, false, &routine), "a continuation read (pos0 != 0)") && routine); + // short prompts and a prompt the tail would swallow: routine + CHECK(is(c.decline(eng, 0, 3000, 0, -1, 48, false, false, &routine), "the prompt is shorter than STRATA_KVA_MIN_PROMPT") && routine); + CHECK(c.decline(eng, 0, 4096, 0, -1, 48) == nullptr); // 4096 > 2112 + 64: it applies + put("STRATA_KVA_SUFFIX", "5000"); + { const KvaConfig s = kva_config_from_env(); + CHECK(is(s.decline(eng, 0, 5000, 0, -1, 48, false, false, &routine), "the suffix leaves too few positions to approximate") && routine); } + clear_all(); + // not routine: the user may want to know + CHECK(is(c.decline(eng, 0, 14600, 24, -1, 48, false, false, &routine), "a layer split (not the whole trunk)") && !routine); + CHECK(is(c.decline(eng, 0, 14600, 0, 24, 48), "a layer split (not the whole trunk)")); + CHECK(is(c.decline(eng, 0, 14600, 0, -1, 48, true), "a prompt with pictures")); + CHECK(is(c.decline(eng, 0, 14600, 0, -1, 48, false, true), "the DFlash2 drafter reads the late layers' hidden states")); + // a model the split and the tail were not measured on reads exactly unless STRATA_KVA=1 asks + CHECK(is(c.decline(eng, 0, 14600, 0, -1, 40, false, false, &routine, true), + "KVA was not validated for this model (STRATA_KVA=1 forces it)") && !routine); + put("STRATA_KVA", "1"); + { const KvaConfig f = kva_config_from_env(); CHECK(f.decline(eng, 0, 14600, 0, -1, 40, false, false, nullptr, true) == nullptr); } + clear_all(); + // a draft layer that attends to every cell has no tail that covers it + KvaEngine all = eng; + all.drafter_window = 0; + CHECK(is(c.decline(all, 0, 14600, 0, -1, 48), "the draft layer attends to every cell (set --mtp-window)")); + put("STRATA_KVA_SUFFIX", "2112"); // ... unless the user fixes the tail by hand + { const KvaConfig s = kva_config_from_env(); CHECK(s.decline(all, 0, 14600, 0, -1, 48) == nullptr); } + clear_all(); + // no draft layer at all: nothing to cover + KvaEngine nod; + CHECK(c.decline(nod, 0, 14600, 0, -1, 48) == nullptr); + // the engine rules the whole process out (batch slots, a layer split, a peer device) + KvaEngine blocked = eng; + blocked.blocked = "batch slots (--batch)"; + CHECK(is(c.decline(blocked, 0, 14600, 0, -1, 48, false, false, &routine), "batch slots (--batch)") && !routine); + // off wins over everything, capture over the rest + put("STRATA_KVA", "0"); + { const KvaConfig o = kva_config_from_env(); CHECK(is(o.decline(eng, 0, 14600, 0, -1, 48), "off (STRATA_KVA=0)")); } + put("STRATA_KVA", "1"); + put("STRATA_KVA_CAPTURE", "/tmp/kva-cap"); + { const KvaConfig o = kva_config_from_env(); CHECK(o.capture && is(o.decline(eng, 0, 14600, 0, -1, 48), "capture mode")); } + clear_all(); + } + + // ---- the research modes still parse + put("STRATA_KVA_ORACLE", "/tmp/o"); + put("STRATA_KVA_ORACLE_FP32", "1"); + put("STRATA_KVA_ONLY", "qsa"); + put("STRATA_KVA_SPLIT", "30"); + put("STRATA_KVA_MIN_PROMPT", "1024"); + { + const KvaConfig c = kva_config_from_env(); + CHECK(c.mode == KvaConfig::Mode::Oracle && c.oracle_fp32 && c.oracle_dir == "/tmp/o"); + CHECK(c.only == KvaConfig::Only::Qsa && c.split == 30 && c.min_prompt == 1024); + } + clear_all(); + + if (fails == 0) std::printf("kva_test: ok\n"); + return fails == 0 ? 0 : 1; +} diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index f0b09e55..741c3d8f 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -2716,9 +2716,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // STRATA_KVA: the approximate-prefix plan of this run, if it qualifies (a cold read of one long prompt, one // stage, no capture). Positions [0, kva_frontier) are approximated in the layers at and after the split. const KvaConfig& kva = kva_config(); - const bool kva_run = kva.applies(pos0, n, LB, LE < 0 ? -1 : LE, (int64_t) g.n_layers); + const KvaEngine& kva_eng = kva_engine(); + const int64_t kva_suffix = kva.effective_suffix(kva_eng); + bool kva_routine = false; + const char* kva_why_not = kva.decline(kva_eng, pos0, n, LB, LE < 0 ? -1 : LE, (int64_t) g.n_layers, + embd_rows != nullptr, !tap_layers_.empty(), &kva_routine, + g.n_layers != 48 || g.n_expert != 512); + const bool kva_run = kva_why_not == nullptr; const int64_t kva_split = std::min(std::max(kva.split, 1), g.n_layers); - const int64_t kva_frontier = std::max(0, n - kva.suffix); + const int64_t kva_frontier = std::max(0, n - kva_suffix); static KvaTap kva_capture; // process-wide: one cold read at a time, so the per-layer position is enough static KvaTap kva_oracle; int64_t kva_positions = 0, kva_chunks = 0; // what actually took the approximate path (diagnostics) @@ -5272,25 +5278,31 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri : kva.only == KvaConfig::Only::Qsa ? ", qsa layers only" : ""; std::fprintf(stderr, "strata prefill: KVA %s: split %lld, suffix %lld, approximated %lld of %lld positions " "in %lld of %lld chunks, mode %s%s%s\n", - kva_run ? "on" : "off (capture)", (long long) kva_split, (long long) kva.suffix, + kva_run ? "on" : "off (capture)", (long long) kva_split, (long long) kva_suffix, (long long) kva_positions, (long long) n, (long long) kva_chunks, (long long) (n > 0 && m.T > 0 ? (n + m.T - 1) / m.T : 0), mode, only, kva.capture ? ", capturing the late layers' inputs" : ""); - if (kva_positions > 0) - std::fprintf(stderr, "strata prefill: KVA: the session state holds approximated cells; it is not an exact " - "prefix and must not be reused as one (no checkpoint, no follow-up reuse)\n"); - } else if (kva.on) { + if (kva_positions > 0) { + // What a later turn does with this state (serve): it continues from the live session or a checkpoint of + // it and reads only the new tokens, exactly, over the cells this read left; nothing is approximated twice. + // The answer quality of those turns is that of this read. STRATA_KVA=0 reads exactly. + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "strata prefill: KVA: the late layers (%lld and up) hold approximated cells for " + "the first %lld positions of this prompt; a follow-up turn that continues from " + "this state reads its new tokens exactly on top of them (nothing is approximated " + "twice); STRATA_KVA=0 reads every prompt exactly\n", + (long long) kva_split, (long long) kva_frontier); + } + } else if (kva.on && (kva.explicit_on || (n >= kva.min_prompt && !kva_routine && kva_eng.blocked.empty()))) { // KVA-8 (observability): a run that was configured for KVA but fell back completely must say so and why, - // or an operator cannot tell it apart from a run where the feature was never asked for. - const char* why = pos0 != 0 ? "a continuation read (pos0 != 0)" - : (LB != 0 || (LE >= 0 && LE != g.n_layers)) ? "a layer split (not the whole trunk)" - : kva.capture ? "capture mode" - : n < kva.min_prompt ? "the prompt is shorter than STRATA_KVA_MIN_PROMPT" - : n <= kva.suffix + 64 ? "the suffix leaves too few positions to approximate" - : "not applicable"; + // or an operator cannot tell it apart from a run where the feature was never asked for. With KVA on by + // default only a long prompt that was turned away for an unusual reason is worth a line (STRATA_KVA=1 asks + // for every reason). std::fprintf(stderr, "strata prefill: KVA configured but NOT applied: %s (prompt %lld positions, " "min_prompt %lld, suffix %lld, split %lld)\n", - why, (long long) n, (long long) kva.min_prompt, (long long) kva.suffix, (long long) kva_split); + kva_why_not != nullptr ? kva_why_not : "not applicable", (long long) n, (long long) kva.min_prompt, + (long long) kva_suffix, (long long) kva_split); } if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr) { // debug: the GDN states as the prompt path leaves them cudaStreamSynchronize(m.cs); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 45aae75a..213e3640 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -71,6 +71,7 @@ #include "strata/core/dflash2.hpp" #include "strata/core/draft_cap.hpp" #endif +#include "strata/prefill/kva.hpp" #include "strata/prefill/prefill.hpp" #if defined(STRATA_PREFILL_MMQ) #include "strata/prefill/moe_mmq.hpp" @@ -680,6 +681,7 @@ struct Options { /// Plan v0.3 P6: the MTP draft layer's runtime directory (tools/mtp_rt.py); drafts come from it. std::string mtp; int64_t mtp_window = 32768; ///< the draft layer attends to the last N cells (0 = every cell) + bool mtp_window_given = false; ///< --mtp-window was given (KVA picks the window itself only when it was not) /// Plan v0.3 P6: the share (0..1) of each layer's distinct missed experts the GPU reads over PCIe from the /// pinned arena while the CPU computes the rest (verify windows). double pcie_frac = -1.0; ///< < 0: the model's default (0.2 direct for the Q2_0 pack, 0.55 DMA for native packs) @@ -2626,7 +2628,7 @@ int main(int argc, char** argv) { else if (a == "--spec-follow") o.spec_follow = next("--spec-follow"); else if (a == "--window-hashes") o.window_hashes = next("--window-hashes"); else if (a == "--mtp") o.mtp = next("--mtp"); - else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window")); + else if (a == "--mtp-window") { o.mtp_window = std::atoll(next("--mtp-window")); o.mtp_window_given = true; } else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac")); else if (a == "--adapt-every") { o.adapt_every = std::atoi(next("--adapt-every")); o.adapt_every_given = true; } else if (a == "--adapt-decay") o.adapt_decay = (float) std::atof(next("--adapt-decay")); @@ -5496,6 +5498,37 @@ int main(int argc, char** argv) { // slots' draft-KV copies use this one too static const strata::core::ModelGeometry draft_geometry{}; std::vector> slot_mtp; + // KVA (0.2.7: on by default, STRATA_KVA=0 is the exact 0.2.6 path): what only the engine knows. A layer split and + // the batch slots read their prompts in pieces and in stages, which the one-device, one-cold-read rule of the + // approximate prompt read cannot follow, so they stay on the exact path (and say so here, once). The draft layer + // (MTP) must find exact cells in its window: with no --mtp-window given the window becomes 2048 cells (the 0.2.6 + // default, 32768, is every cell of a chat up to that length, which no fully computed tail could cover) and the + // tail 2112; a window the user gave keeps its value and sets the tail (window + 64). + { + const strata::prefill::KvaConfig& kc = strata::prefill::kva_config(); + strata::prefill::KvaEngine& ke = strata::prefill::kva_engine(); + if (kc.explicit_on && !strata::prefill::kKvaBackend) + std::fprintf(stderr, "strata generate: STRATA_KVA is set, but this build has no state-only late-layer path; " + "every prompt is read exactly\n"); + if (kc.on) { + if (multi_gpu) ke.blocked = "a layer split across GPUs"; + else if (o.batch > 0) ke.blocked = "batch slots (--batch)"; + else if (o.peer_device >= 0) ke.blocked = "a peer device (--peer-device)"; + if (!ke.blocked.empty()) { + if (kc.explicit_on) + std::fprintf(stderr, "strata generate: KVA (the approximate late-layer prompt read) is off here: %s\n", + ke.blocked.c_str()); + } else if (!o.mtp.empty() && o.spec >= 2 && !o.mtp_window_given && kc.suffix_env <= 0) { + if (o.mtp_window != strata::prefill::kKvaDrafterWindow) + std::fprintf(stderr, "strata generate: KVA on (the faster prompt read for long cold prompts): the draft layer " + "attends to the last %lld cells (--mtp-window %lld); STRATA_KVA=0 keeps the " + "exact 0.2.6 prompt read and its %lld-cell window\n", + (long long) strata::prefill::kKvaDrafterWindow, (long long) strata::prefill::kKvaDrafterWindow, + (long long) o.mtp_window); + o.mtp_window = strata::prefill::kKvaDrafterWindow; + } + } + } if (!o.mtp.empty()) { if (o.spec < 2) { std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n"); @@ -5515,6 +5548,11 @@ int main(int argc, char** argv) { if (o.pipeline_windows >= 2) mtp.set_force_capture(true); if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st && !mtp_first ? last_st->ss : ss, mtp_t, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; } mtp.set_ple_session(&ss); + if (!o.mtp.empty()) { // KVA: the cells the draft layer attends to now (0 = every cell) set the tail that must be exact + strata::prefill::KvaEngine& ke = strata::prefill::kva_engine(); + ke.has_drafter = true; + ke.drafter_window = mtp.window(); + } #if defined(STRATA_HAVE_DFLASH2) if (o.draft == "dflash2") { const char* why = o.mtp.empty() ? "it needs --mtp (the fallback) and --spec 2 or more" From bc5f84fd62b23310a59cfcab87133ca48649cc54 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 10:55:20 +0100 Subject: [PATCH 6/8] PLE residency policy: the load log also says the expert arena size the rule counted (the proof that the layout is initialised and the sum is not 0) --- src/program/generate.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 745c79f8..53736e86 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -4111,9 +4111,10 @@ int main(int argc, char** argv) { if (ple_table.open(o.ple_gguf, ram_err, pio)) { ple_auto_ram = true; std::fprintf(stderr, "strata generate: --ple-io ram chosen by the residency policy (the table is " - "%.1f GiB and %.1f GiB of RAM is available; STRATA_PLE_AUTO_RAM=0 keeps the " - "direct reads, --ple-io direct forces them)\n", - (double) need / (1ull << 30), (double) *available / (1ull << 30)); + "%.1f GiB, the expert arena still to fill %.1f GiB and %.1f GiB of RAM is available; " + "STRATA_PLE_AUTO_RAM=0 keeps the direct reads, --ple-io direct forces them)\n", + (double) need / (1ull << 30), (double) experts_ram / (1ull << 30), + (double) *available / (1ull << 30)); } else { // Back to what was asked for; a table that cannot be mapped must not stop the engine. std::fprintf(stderr, "strata generate: resident PLE table failed (%s); keeping direct reads\n", From 7a34c60d61c779f1afefadcab728678b765410c7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 12:14:30 +0100 Subject: [PATCH 7/8] KVA: leave the draft window alone; a per-session cell floor keeps the draft layer off approximated cells The first default-on build set --mtp-window 2048 once per process whenever KVA was on, so short prompts (where KVA never applies) lost draft context and decode speed. Now the draft layer keeps its window (32768 by default) and MtpDrafter::set_cell_floor() names the first draft cell built from a real row: a KVA read raises it to the end of its approximated chunks (they are neither built nor read), the draft attention starts at max(floor, pos - window) (window_ids_floor, window_start.hpp), and KvaFloorRegistry gives every state a request continues from (live, checkpoint, parked) the floor of its own tokens. A session KVA did not approximate has floor 0 and attends exactly as with STRATA_KVA=0; with STRATA_KVA=0 or a process KVA is ruled out for the draft layer's code is 0.2.6's. The tail is 2048 whatever the window. Unit tests: window_start with floor 0 equals the plain window, the registry, wants_cell_floor. --- docs/KVA.md | 36 +++++++----- include/strata/core/mtp.hpp | 22 ++++++- include/strata/kernels/verify_kernels.hpp | 5 ++ include/strata/kernels/window_start.hpp | 26 ++++++++ include/strata/prefill/kva.hpp | 43 ++++++-------- include/strata/prefill/kva_floor.hpp | 72 +++++++++++++++++++++++ include/strata/prefill/prefill.hpp | 5 ++ metal/src/engine/stubs.cpp | 1 + src/core/mtp.cpp | 9 ++- src/kernels/cuda/verify_kernels.cu | 25 ++++++++ src/prefill/kva_test.cpp | 32 ++-------- src/prefill/prefill.cpp | 4 +- src/program/generate.cpp | 42 +++++++------ 13 files changed, 234 insertions(+), 88 deletions(-) create mode 100644 include/strata/kernels/window_start.hpp create mode 100644 include/strata/prefill/kva_floor.hpp diff --git a/docs/KVA.md b/docs/KVA.md index d07651f3..c53c6abd 100644 --- a/docs/KVA.md +++ b/docs/KVA.md @@ -28,20 +28,28 @@ configuration rules KVA out for the whole run. ## The fully computed tail and the draft layer -The last `suffix` positions are always read exactly. The MTP draft layer builds its K/V from the final -residuals of the prompt, and those rows are only real where the layers ran in full, so the tail must cover the -draft layer's window plus the 64 cells its catch-up reaches back: +The last `suffix` positions (2048, or `STRATA_KVA_SUFFIX`) are always read exactly. -- no `--mtp-window` given (what the app and the Terminal write): with KVA on, the engine sets the draft window to - 2048 cells and the tail to 2112 tokens. The 0.2.6 window was 32768, which is every cell of a chat up to that - length and could never be covered. The engine prints one line at start-up when it does this. -- `--mtp-window N` given: the window stays N and the tail is N + 64 (a 32768-cell window never leaves a - prompt shorter than 32 K approximated; the log says "the draft layer attends to every cell" when no tail can cover it). -- `STRATA_KVA_SUFFIX=N` fixes the tail by hand. -- no draft layer (`--mtp` not given): the tail is 2048. +The MTP draft layer builds its K/V from the final residuals of the prompt, and an approximated chunk has none. The +draft layer's window is **not changed**: it stays what it was (`--mtp-window`, default 32768 cells). Instead the +engine keeps a *cell floor* per session, the first draft cell built from a real row: -A draft layer that reads an approximated cell costs only draft acceptance (speed); the target model verifies every -emitted token, so the answer does not depend on it. +- A read that KVA approximated raises the floor to the end of its approximated chunks. The draft layer builds no + cell below it and its attention starts no lower, so it reads the window `[max(floor, pos - window), pos)`: the + exactly computed tail, growing with the conversation, never an approximated cell. The target model verifies + every token either way. +- The floor follows the *tokens* of the state a request continues from (the live session, a conversation checkpoint, + a parked conversation): the engine remembers which token prefixes a KVA read approximated, and a state's floor + is how much of its tokens agree with one of them. A state no KVA read produced (a short chat, another document, + every prompt of a `STRATA_KVA=0` run) has floor 0. +- With floor 0 the draft layer attends to exactly the window it attended to with `STRATA_KVA=0` + (`window_start`, unit tested for every length). The only added work is one tiny kernel that picks the cells. + With `STRATA_KVA=0`, with the engine configurations that rule KVA out and with a build without a draft layer, + the draft layer's code is 0.2.6's own. + +Measured on the P100 (14K prompt, 256 tokens, auto cache and prefill), the draft layer's window made no difference +to decode (38.7 tok/s with the 32768-cell window, 40.1 with 2048); on faster cards a smaller window costs +acceptance, which is why the window is left alone. ## Chats, follow-up turns and checkpoints (`--serve`) @@ -76,7 +84,7 @@ there, with a line when it is set). |---|---:|---| | `STRATA_KVA` | on | `0` turns KVA off (the exact 0.2.6 prompt read). `1` is the same as the default but logs every read it turned away | | `STRATA_KVA_SPLIT` | 24 | first approximated layer (zero-based) | -| `STRATA_KVA_SUFFIX` | 2112 with the default draft window | fully computed tail positions; see above | +| `STRATA_KVA_SUFFIX` | 2048 | fully computed tail positions; see above | | `STRATA_KVA_MIN_PROMPT` | 4096 | shorter prompts stay on the full path | | `STRATA_KVA_ONLY` | all | `gdn` or `qsa`: approximate only that layer type | | `STRATA_KVA_MODE` | identity | `identity`, `oracle`, `linear` (linear is not implemented) | @@ -88,7 +96,7 @@ there, with a line when it is set). Every read says what it did: -- applied: `strata prefill: KVA on: split 24, suffix 2112, approximated 5120 of 7533 positions in 5 of 8 chunks, mode identity` +- applied: `strata prefill: KVA on: split 24, suffix 2048, approximated 5120 of 7533 positions in 5 of 8 chunks, mode identity` - turned away: `strata prefill: KVA configured but NOT applied: (prompt … positions, min_prompt …, suffix …, split …)` A quality comparison needs the control arm to say `STRATA_KVA=0` (an unset variable is now KVA). diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index f63aea4d..38fe8f01 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -26,6 +26,7 @@ #include +#include #include #include #include @@ -166,9 +167,25 @@ public: const uint16_t* tensor_bf16(const char* name) const { return bf16(name); } const void* tensor_q8(const char* name) const { return q8(name); } QsaState& kv_state_rw() { return st_; } - int64_t first_needed() const { return (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0; } + /// The first cell whose K/V the draft layer can still read: the window's start for this prompt, and never below + /// the KVA floor (cells built from approximated rows are not read, so they are not built either). + int64_t first_needed() const { + const int64_t w = (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0; + return std::max(w, cell_floor_); + } /// The cells the draft layer attends to (0 = every cell), as load() settled it. int64_t window() const { return window_; } + /// KVA: call before load(). The draft layer's attention then reads its cell range through a floor, which stays 0 + /// (the plain window, cell for cell) until set_cell_floor() raises it. Off (the default): the code is 0.2.6's. + void enable_cell_floor(bool on) { floor_on_ = on; } + bool cell_floor_enabled() const { return floor_on_ && m_floor_ != nullptr; } + /// KVA: the first draft cell that holds a K/V built from a real (not approximated) row. The attention starts no + /// lower; draft_kv / prefill build no cell below it. Between requests (the drafter idle). 0 = every cell is real. + void set_cell_floor(int64_t cell) { + cell_floor_ = std::max(0, cell); + if (m_floor_ != nullptr) *(volatile int32_t*) h_floor_ = (int32_t) std::min(cell_floor_, 0x7fffffff); + } + int64_t cell_floor() const { return cell_floor_; } int device() const { return device_; } bool idle(std::string& err) { if (cs_ && cudaStreamSynchronize(cs_) != cudaSuccess) { err = "mtp: its stream failed"; return false; } @@ -273,6 +290,9 @@ private: int64_t n_dvocab_ = 0; std::string rt_dir_; int64_t window_ = 0; // attention over the last window_ cells (0 = every cell) + int64_t cell_floor_ = 0; // KVA: no draft cell below this one is read or built (set_cell_floor) + bool floor_on_ = false; // enable_cell_floor: the attention goes through window_ids_floor + int32_t *h_floor_ = nullptr, *m_floor_ = nullptr; // the floor, mapped: the kernel reads it when it runs int64_t prompt_len_ = 0; const int32_t* rr_res_ = nullptr; float rr_margin_ = 0.0f; diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index a5e35181..b2ff4a0d 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -192,5 +192,10 @@ void dense_steps(const int32_t* cells, int n, int32_t* steps, void* stream); /// A sliding attention window: for `n` step records (kStepCount ints each, n_kv at [1]) the selection becomes the /// last `window` cells: ids[q * ids_stride + j] = max(0, n_kv - window) + j and the record's width = the count. void window_ids(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, void* stream); +/// window_ids whose window starts no lower than the cell `*floor_cell` (device-visible memory, read when the kernel +/// runs; KVA: the first draft cell built from a real row). `window` may be INT_MAX for "every cell". A floor of 0 +/// selects exactly what window_ids selects. CUDA / HIP only. +void window_ids_floor(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, const int32_t* floor_cell, + void* stream); } // namespace strata::kernels diff --git a/include/strata/kernels/window_start.hpp b/include/strata/kernels/window_start.hpp new file mode 100644 index 00000000..8b094435 --- /dev/null +++ b/include/strata/kernels/window_start.hpp @@ -0,0 +1,26 @@ +// include/strata/kernels/window_start.hpp - the first cell the draft layer's attention reads. +// +// The draft layer attends to the last `window` cells. KVA (docs/KVA.md) can leave cells in the draft layer's K/V +// that were built from approximated rows; `floor` is the first cell that holds a real one, so the attention starts +// there when it is higher. floor = 0 (every session KVA did not approximate) gives exactly the plain window. +// One function for the device kernel and for the host test. +#pragma once + +#if defined(__CUDACC__) || defined(__HIPCC__) +#define STRATA_WINDOW_START_HD __host__ __device__ +#else +#define STRATA_WINDOW_START_HD +#endif + +namespace strata::kernels { + +/// The first cell of the attention for a sequence of `n_kv` cells. The width n_kv - start is at least 1 whenever +/// n_kv is (a floor at or past the end must not leave the attention with nothing to read). +STRATA_WINDOW_START_HD inline int window_start(int n_kv, int window, int floor) { + int start = n_kv > window ? n_kv - window : 0; + if (floor > start) start = floor; + if (start > n_kv - 1) start = n_kv > 0 ? n_kv - 1 : 0; + return start; +} + +} // namespace strata::kernels diff --git a/include/strata/prefill/kva.hpp b/include/strata/prefill/kva.hpp index d9ce3dc0..80e8bdb0 100644 --- a/include/strata/prefill/kva.hpp +++ b/include/strata/prefill/kva.hpp @@ -18,11 +18,15 @@ // device. STRATA_KVA=0 brings back the exact 0.2.6 prompt path and the 0.2.6 draft window. Everything is read from // the environment once per process. // -// The two facts the engine tells this header at start-up (kva_engine()): whether a draft layer (MTP) is loaded and -// how many cells it attends to, and whether the engine configuration rules the read out for the whole process -// (batch slots, a layer split). The fully computed suffix must cover the drafter's window plus the 64 cells its -// catch-up reaches back (MtpDrafter::first_needed), or the drafter would build its K/V from approximated cells -// (that costs acceptance, never correctness: the target model verifies every token). +// What the engine tells this header at start-up (kva_engine()): whether its configuration rules the read out for the +// whole process (batch slots, a layer split, a peer device). +// +// The draft layer (MTP) builds its K/V from the final rows of the prompt, which an approximated chunk does not have. +// Its window is NOT changed: the draft layer's attention starts at the "cell floor" (MtpDrafter::set_cell_floor), the +// first cell built from a real row, and the cells below it are neither built nor read. A session KVA did not +// approximate has a floor of 0 and is bit for bit what STRATA_KVA=0 runs (kva_floor.hpp keeps the floor with the +// tokens of the session, window_start.hpp is the one rule the kernel and the tests share). The target model verifies +// every token whatever the draft read. #pragma once #include @@ -41,17 +45,11 @@ inline constexpr bool kKvaBackend = false; inline constexpr bool kKvaBackend = true; #endif -/// The draft layer's window (--mtp-window) the engine picks when KVA is on, the draft layer is loaded and the user -/// gave no --mtp-window: 2048 cells (suffix 2112). The 0.2.6 default was 32768, i.e. every cell of a chat up to -/// that length, which no suffix could cover. -inline constexpr int64_t kKvaDrafterWindow = 2048; -/// The fully computed tail when no draft layer needs more. +/// The fully computed tail of every approximated read. inline constexpr int64_t kKvaSuffixDefault = 2048; /// What the running engine knows and the environment cannot say. struct KvaEngine { - bool has_drafter = false; ///< an MTP draft layer is loaded (--mtp with --spec 2 or more) - int64_t drafter_window = 0; ///< the cells it attends to; 0 = every cell std::string blocked; ///< non-empty: this process never reads approximately, and why }; @@ -71,7 +69,7 @@ struct KvaConfig { bool oracle_fp32 = false; ///< STRATA_KVA_ORACLE_FP32=1: the oracle files are fp32 (else bf16) bool parity = false; ///< STRATA_KVA_PARITY=1: report the state-only path against the full path int64_t split = 24; ///< STRATA_KVA_SPLIT: first approximated layer (zero-based) - int64_t suffix_env = 0; ///< STRATA_KVA_SUFFIX: fully computed tail positions (0 = not set: effective_suffix()) + int64_t suffix_env = 0; ///< STRATA_KVA_SUFFIX: fully computed tail positions (0 = not set: kKvaSuffixDefault) int64_t min_prompt = 4096; ///< STRATA_KVA_MIN_PROMPT: shorter prompts stay on the full path Mode mode = Mode::Identity; ///< STRATA_KVA_MODE=identity|oracle|linear Only only = Only::All; ///< STRATA_KVA_ONLY=all|gdn|qsa: which late layers take the approximate path @@ -79,14 +77,13 @@ struct KvaConfig { std::string capture_dir; ///< STRATA_KVA_CAPTURE std::string projector; ///< STRATA_KVA_PROJECTOR - /// The fully computed tail of a read. STRATA_KVA_SUFFIX when set; otherwise 2048, or the draft layer's window + - /// 64 when that is larger. (A draft layer that attends to every cell has no suffix that covers it: - /// decline() says so.) - int64_t effective_suffix(const KvaEngine& e) const { - if (suffix_env > 0) return suffix_env; - int64_t s = kKvaSuffixDefault; - if (e.has_drafter && e.drafter_window > 0) s = std::max(s, e.drafter_window + 64); - return s; + /// The fully computed tail of a read: STRATA_KVA_SUFFIX when set, otherwise 2048. + int64_t effective_suffix() const { return suffix_env > 0 ? suffix_env : kKvaSuffixDefault; } + + /// Does the draft layer need the cell floor at all? Only when a read can approximate something: KVA on, not ruled + /// out for the process, and a draft layer loaded. Otherwise the draft layer's attention is 0.2.6's own code. + bool wants_cell_floor(const KvaEngine& e, bool has_drafter) const { + return kKvaBackend && on && e.blocked.empty() && has_drafter; } /// Why this read cannot take the approximate path, or nullptr when it can: a cold read of one prompt (not a @@ -110,13 +107,11 @@ struct KvaConfig { if (lb != 0 || (le >= 0 && le != n_layers)) return "a layer split (not the whole trunk)"; if (pictures) return "a prompt with pictures"; if (taps) return "the DFlash2 drafter reads the late layers' hidden states"; - if (suffix_env <= 0 && e.has_drafter && e.drafter_window <= 0) - return "the draft layer attends to every cell (set --mtp-window)"; if (n < min_prompt) { if (routine) *routine = true; return "the prompt is shorter than STRATA_KVA_MIN_PROMPT"; } - if (n <= effective_suffix(e) + 64) { + if (n <= effective_suffix() + 64) { if (routine) *routine = true; return "the suffix leaves too few positions to approximate"; } diff --git a/include/strata/prefill/kva_floor.hpp b/include/strata/prefill/kva_floor.hpp new file mode 100644 index 00000000..50189c7d --- /dev/null +++ b/include/strata/prefill/kva_floor.hpp @@ -0,0 +1,72 @@ +// include/strata/prefill/kva_floor.hpp - which cells of a session were built from approximated rows (KVA). +// +// A KVA read leaves the draft layer's K/V with cells [0, floor) built from rows the late layers never computed. The +// draft layer must not attend to them (it would only cost draft acceptance, but that is the decode speed), and a +// session that KVA did not approximate must not lose any draft context at all. The floor therefore follows the +// SESSION'S TOKENS, not the process: after a KVA read the registry remembers the prefix (its token ids) that was +// approximated; whatever state a later request continues from (the live session, a conversation checkpoint, a parked +// conversation), the floor of that state is how much of its tokens agree with a remembered prefix, capped by the +// prefix's floor. A state no KVA read produced has no common prefix, so its floor is 0 and its draft layer attends +// to the whole window, as with STRATA_KVA=0. +// +// A mislabel can only cost draft cells (an exact state that shares a prefix with an approximated one reports the +// floor too high); it can never make the draft attend to approximated cells that were registered, and the target +// model verifies every token whatever the draft read. +#pragma once + +#include +#include +#include + +namespace strata::prefill { + +class KvaFloorRegistry { +public: + explicit KvaFloorRegistry(size_t cap = 8) : cap_(cap) {} + + /// A KVA read approximated the cells [0, floor) of the prompt `ids` (at least `floor` tokens). + template + void note(const Token* ids, int64_t floor) { + if (floor <= 0) return; + ++clock_; + for (Entry& e : v_) + if ((int64_t) e.ids.size() == floor && std::equal(e.ids.begin(), e.ids.end(), ids)) { e.used = clock_; return; } + Entry e; + e.ids.assign(ids, ids + floor); + e.used = clock_; + if (v_.size() >= cap_) { + size_t lru = 0; + for (size_t i = 1; i < v_.size(); ++i) if (v_[i].used < v_[lru].used) lru = i; + v_.erase(v_.begin() + (std::ptrdiff_t) lru); + } + v_.push_back(std::move(e)); + } + + /// The first cell of a state holding the tokens ids[0, n) that is NOT an approximated one: the longest common + /// prefix with a remembered read, over the remembered reads. 0 when the tokens match none. + template + int64_t floor_for(const Token* ids, int64_t n) const { + int64_t best = 0; + for (const Entry& e : v_) { + const int64_t m = std::min(n, (int64_t) e.ids.size()); + int64_t i = 0; + while (i < m && (int64_t) ids[i] == e.ids[(size_t) i]) ++i; + best = std::max(best, i); + } + return best; + } + + size_t size() const { return v_.size(); } + void clear() { v_.clear(); } + +private: + struct Entry { + std::vector ids; + uint64_t used = 0; + }; + std::vector v_; + size_t cap_; + uint64_t clock_ = 0; +}; + +} // namespace strata::prefill diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index f9bbca02..39ed8557 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -209,6 +209,10 @@ public: /// for its grouping on the host; a policy may count them. Not called on the paths that keep the ids on the GPU. std::function on_routes; int64_t stopped_at() const { return stopped_at_; } + /// KVA: the end of the positions the last run approximated (they are a prefix: chunks from the run's first position + /// on), i.e. the first position whose final rows are real; 0 when that run approximated nothing. Raised chunk by + /// chunk, before on_chunk reports the chunk, so the draft layer can skip the chunk's cells. Reset by every run. + int64_t kva_floor() const { return kva_floor_; } /// Grows this stage's (and the later stages') pinned upload slots to what a text chunk of `T` tokens uploads, so /// a run of such chunks allocates no pinned memory (STRATA_PIPED_CONCURRENT: an allocation or free on the read's /// thread takes the driver's lock). Before the run, with nothing of this path in flight. False: a slot could @@ -270,6 +274,7 @@ private: Prefill* helper_ = nullptr; ///< set_stage_helper bool single_chunk_ = false; ///< a later stage: the prompt is one chunk (set by the stage before) int64_t stopped_at_ = -1; ///< stop_at_chunk ended the last run after this many tokens (-1: it read all) + int64_t kva_floor_ = 0; ///< kva_floor() bool pipe_chunked_ = false; ///< a later stage: the chunks came from a --prefill-pipe plan (set likewise) int64_t force_chunk_ = 0; ///< force_chunk, for the next run (0: none) bool force_single_ = false, force_planned_ = false; diff --git a/metal/src/engine/stubs.cpp b/metal/src/engine/stubs.cpp index b6615813..7facf9a2 100644 --- a/metal/src/engine/stubs.cpp +++ b/metal/src/engine/stubs.cpp @@ -325,6 +325,7 @@ namespace strata::kernels { void topk_512_step(const float * p0, const QsaShapes namespace strata::kernels { void wait_flag_ge(const uint32_t * p0, uint32_t p1, void * p2) { strata::metal_engine::missing("strata::kernels::wait_flag_ge"); } } namespace strata::kernels { void wait_flag_ge_or(const uint32_t * p0, uint32_t p1, const uint32_t * p2, void * p3) { strata::metal_engine::missing("strata::kernels::wait_flag_ge_or"); } } namespace strata::kernels { void window_ids(int32_t * p0, int p1, int p2, int32_t * p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::window_ids"); } } +namespace strata::kernels { void window_ids_floor(int32_t * p0, int p1, int p2, int32_t * p3, int64_t p4, const int32_t * p5, void * p6) { strata::metal_engine::missing("strata::kernels::window_ids_floor"); } } auto strata::prefill::Gemm::bf16(const uint16_t * p0, const uint16_t * p1, float * p2, int64_t p3, int64_t p4, int64_t p5, int64_t p6, float p7, int64_t p8, bool p9) -> void { strata::metal_engine::missing("strata::prefill::Gemm::bf16"); } auto strata::prefill::Gemm::bf16_converts_x() const -> bool { strata::metal_engine::missing("strata::prefill::Gemm::bf16_converts_x"); return {}; } auto strata::prefill::Gemm::bf16_hcd_exact(const uint16_t * p0, int64_t p1, const uint16_t * p2, float * p3, int64_t p4, int64_t p5, int64_t p6) -> bool { strata::metal_engine::missing("strata::prefill::Gemm::bf16_hcd_exact"); return {}; } diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index f4b82b33..292a5d2b 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -163,7 +163,7 @@ MtpDrafter::~MtpDrafter() { if (owns_draft_head_ && dvocab_) cudaFree(dvocab_); if (ev_chain_) cudaEventDestroy(ev_chain_); for (cudaEvent_t e : ev_step_) if (e) cudaEventDestroy(e); - void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_, h_force_}; + void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_, h_force_, h_floor_}; for (void* h : hosts) if (h) cudaFreeHost(h); } @@ -370,6 +370,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session // ---- buffers window_ = (window > 0 && window < max_cells) ? window : 0; + if (floor_on_ && !mapped(64, (void**) &h_floor_, (void**) &m_floor_)) { err = "mtp: the window floor does not fit"; return false; } cap_ = (((window_ > 0 ? window_ : max_cells) + 63) / 64) * 64; attn_scratch_floats_ = (int64_t) strata::kernels::qsa_decode_attn_scratch_floats(cap_, s); const uint64_t T = (uint64_t) max_t, N = (uint64_t) g.n_embd, HC = (uint64_t) g.hc, K = (uint64_t) ss.k; @@ -1027,7 +1028,9 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) { if (st_.kv_rot) fwht256_inplace_cuda(qcur_, (int64_t) T * NH, cs); g_mp.stamp(5, cs); const QsaAttnPools pools = qsa_attn_pools(st_); - if (window_ > 0) window_ids(const_cast(step), T, (int) window_, ident_, cap_, cs); + if (floor_on_ && m_floor_ != nullptr) // KVA: the window (or every cell) from the first real draft cell on + window_ids_floor(const_cast(step), T, window_ > 0 ? (int) window_ : 0x7fffffff, ident_, cap_, m_floor_, cs); + else if (window_ > 0) window_ids(const_cast(step), T, (int) window_, ident_, cap_, cs); // STRATA_QSA_SPLIT_ATTN=1: the draft layer's attention over its window, split the same way static const bool split_attn = [] { const char* v = std::getenv("STRATA_QSA_SPLIT_ATTN"); return v != nullptr && std::atoi(v) != 0; }(); if (!(split_attn && qsa_decode_attn_split(qcur_, pools, ident_, step, cap_, s, attn_scratch_, (uint64_t) attn_scratch_floats_, attn_, T, cs))) @@ -1423,7 +1426,7 @@ bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_ const Clock::time_point t0 = Clock::now(); const int64_t HCN = g_->hc * g_->n_embd; // cells the window can never reach again need no K/V - const int64_t first_needed = (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0; + const int64_t first_needed = this->first_needed(); // E-4: every group's token / step / position records uploaded at once; each group is then device copies and a // graph on the one stream, with a single sync at the end (a group of <= max_t rows used to be staged in mapped // memory and synced before the next: ~5,500 host round trips on a 32K prompt). The same work in the same diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index a9f570b9..26566475 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -6,6 +6,7 @@ #include "strata/core/geometry.hpp" #include "strata/core/emulate.hpp" #include "strata/kernels/q8_1_finite.hpp" // #606: q8_1_ds +#include "strata/kernels/window_start.hpp" // KVA: the draft layer's window floor #include "strata/kernels/dp4a.hpp" #include "strata/kernels/pdl.hpp" @@ -1016,6 +1017,30 @@ void window_ids(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_str check("window_ids"); } +namespace { +// window_ids with a floor read from (mapped) memory when the kernel RUNS: the captured graph keeps the pointer, the +// value changes between sessions. A floor of 0 gives window_ids' selection exactly (strata::kernels::window_start). +__global__ void window_ids_floor_kernel(int32_t* steps, int window, int32_t* ids, long long stride, + const volatile int32_t* floor_cell) { + const int q = blockIdx.y; + int32_t* st = steps + q * 4; + const int n_kv = st[1]; + const int start = strata::kernels::window_start(n_kv, window, *floor_cell); + const int width = n_kv - start; + for (int j = blockIdx.x * blockDim.x + threadIdx.x; j < width; j += gridDim.x * blockDim.x) + ids[q * stride + j] = start + j; + __syncthreads(); + if (blockIdx.x == 0 && threadIdx.x == 0) st[3] = width; +} +} // namespace + +void window_ids_floor(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, const int32_t* floor_cell, + void* stream) { + window_ids_floor_kernel<<>>(steps, window, ids, (long long) ids_stride, + floor_cell); + check("window_ids_floor"); +} + void dense_steps(const int32_t* cells, int n, int32_t* steps, void* stream) { dense_steps_kernel<<<1, 64, 0, (cudaStream_t) stream>>>(cells, n, steps); check("dense_steps"); diff --git a/src/prefill/kva_test.cpp b/src/prefill/kva_test.cpp index bd468c34..937d0ca1 100644 --- a/src/prefill/kva_test.cpp +++ b/src/prefill/kva_test.cpp @@ -1,10 +1,13 @@ // src/prefill/kva_test.cpp - the KVA switch, the automatic tail and the reasons a read is turned away (no GPU needed). +#include "strata/kernels/window_start.hpp" #include "strata/prefill/kva.hpp" +#include "strata/prefill/kva_floor.hpp" #include #include #include #include +#include using namespace strata::prefill; @@ -50,25 +53,13 @@ int main() { { const KvaConfig c = kva_config_from_env(); CHECK(c.on && !c.explicit_on); } clear_all(); - // ---- the automatic tail: 2048, or the draft layer's window + 64 when that is larger; STRATA_KVA_SUFFIX wins + // ---- the tail: 2048, or STRATA_KVA_SUFFIX; the draft window plays no part (the cell floor protects the draft layer) { const KvaConfig c = kva_config_from_env(); - KvaEngine none; // no draft layer - CHECK(c.effective_suffix(none) == kKvaSuffixDefault); - KvaEngine d; // the window the engine picks (no --mtp-window given) - d.has_drafter = true; - d.drafter_window = kKvaDrafterWindow; - CHECK(c.effective_suffix(d) == 2112); - d.drafter_window = 8192; // --mtp-window 8192 - CHECK(c.effective_suffix(d) == 8256); - d.drafter_window = 512; // a small window: the default tail still holds - CHECK(c.effective_suffix(d) == 2048); - d.drafter_window = 0; // every cell: no tail can cover it, the plain tail is returned - CHECK(c.effective_suffix(d) == 2048); + CHECK(c.effective_suffix() == kKvaSuffixDefault && kKvaSuffixDefault == 2048); put("STRATA_KVA_SUFFIX", "3000"); const KvaConfig e = kva_config_from_env(); - d.drafter_window = 8192; - CHECK(e.effective_suffix(d) == 3000); + CHECK(e.effective_suffix() == 3000); clear_all(); } @@ -76,8 +67,6 @@ int main() { { const KvaConfig c = kva_config_from_env(); KvaEngine eng; - eng.has_drafter = true; - eng.drafter_window = kKvaDrafterWindow; bool routine = false; // a cold 14.6K prompt on one device: applies CHECK(c.decline(eng, 0, 14600, 0, -1, 48) == nullptr); @@ -102,16 +91,7 @@ int main() { put("STRATA_KVA", "1"); { const KvaConfig f = kva_config_from_env(); CHECK(f.decline(eng, 0, 14600, 0, -1, 40, false, false, nullptr, true) == nullptr); } clear_all(); - // a draft layer that attends to every cell has no tail that covers it - KvaEngine all = eng; - all.drafter_window = 0; - CHECK(is(c.decline(all, 0, 14600, 0, -1, 48), "the draft layer attends to every cell (set --mtp-window)")); - put("STRATA_KVA_SUFFIX", "2112"); // ... unless the user fixes the tail by hand - { const KvaConfig s = kva_config_from_env(); CHECK(s.decline(all, 0, 14600, 0, -1, 48) == nullptr); } - clear_all(); // no draft layer at all: nothing to cover - KvaEngine nod; - CHECK(c.decline(nod, 0, 14600, 0, -1, 48) == nullptr); // the engine rules the whole process out (batch slots, a layer split, a peer device) KvaEngine blocked = eng; blocked.blocked = "batch slots (--batch)"; diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 741c3d8f..8fd781a5 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -2717,7 +2717,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri // stage, no capture). Positions [0, kva_frontier) are approximated in the layers at and after the split. const KvaConfig& kva = kva_config(); const KvaEngine& kva_eng = kva_engine(); - const int64_t kva_suffix = kva.effective_suffix(kva_eng); + const int64_t kva_suffix = kva.effective_suffix(); bool kva_routine = false; const char* kva_why_not = kva.decline(kva_eng, pos0, n, LB, LE < 0 ? -1 : LE, (int64_t) g.n_layers, embd_rows != nullptr, !tap_layers_.empty(), &kva_routine, @@ -2728,6 +2728,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri static KvaTap kva_capture; // process-wide: one cold read at a time, so the per-layer position is enough static KvaTap kva_oracle; int64_t kva_positions = 0, kva_chunks = 0; // what actually took the approximate path (diagnostics) + kva_floor_ = 0; // this run's: raised below as chunks are approximated if (kva.capture && kva_capture.f.empty()) kva_capture.open(kva.capture_dir, kva.capture_fp32); if (kva.capture && pos0 == 0 && hand_in_ == nullptr) kva_capture.begin_prompt(); // one prompt per capture if (kva_run && kva.mode == KvaConfig::Mode::Oracle && kva_oracle.f.empty()) @@ -2862,6 +2863,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (kva_approx) { kva_positions += T; ++kva_chunks; + kva_floor_ = p0 + T; // the chunks are a prefix of the run: this is the first position with real rows } core::progress_at("reading the prompt (batched): preparing the chunk from token", p0); // #251 #if defined(STRATA_HAVE_DFLASH2) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 82a6c945..dbc5b6b0 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -73,6 +73,7 @@ #include "strata/core/draft_cap.hpp" #endif #include "strata/prefill/kva.hpp" +#include "strata/prefill/kva_floor.hpp" #include "strata/prefill/prefill.hpp" #if defined(STRATA_PREFILL_MMQ) #include "strata/prefill/moe_mmq.hpp" @@ -682,7 +683,6 @@ struct Options { /// Plan v0.3 P6: the MTP draft layer's runtime directory (tools/mtp_rt.py); drafts come from it. std::string mtp; int64_t mtp_window = 32768; ///< the draft layer attends to the last N cells (0 = every cell) - bool mtp_window_given = false; ///< --mtp-window was given (KVA picks the window itself only when it was not) /// Plan v0.3 P6: the share (0..1) of each layer's distinct missed experts the GPU reads over PCIe from the /// pinned arena while the CPU computes the rest (verify windows). double pcie_frac = -1.0; ///< < 0: the model's default (0.2 direct for the Q2_0 pack, 0.55 DMA for native packs) @@ -2629,7 +2629,7 @@ int main(int argc, char** argv) { else if (a == "--spec-follow") o.spec_follow = next("--spec-follow"); else if (a == "--window-hashes") o.window_hashes = next("--window-hashes"); else if (a == "--mtp") o.mtp = next("--mtp"); - else if (a == "--mtp-window") { o.mtp_window = std::atoll(next("--mtp-window")); o.mtp_window_given = true; } + else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window")); else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac")); else if (a == "--adapt-every") { o.adapt_every = std::atoi(next("--adapt-every")); o.adapt_every_given = true; } else if (a == "--adapt-decay") o.adapt_decay = (float) std::atof(next("--adapt-decay")); @@ -5512,9 +5512,9 @@ int main(int argc, char** argv) { // KVA (0.2.7: on by default, STRATA_KVA=0 is the exact 0.2.6 path): what only the engine knows. A layer split and // the batch slots read their prompts in pieces and in stages, which the one-device, one-cold-read rule of the // approximate prompt read cannot follow, so they stay on the exact path (and say so here, once). The draft layer - // (MTP) must find exact cells in its window: with no --mtp-window given the window becomes 2048 cells (the 0.2.6 - // default, 32768, is every cell of a chat up to that length, which no fully computed tail could cover) and the - // tail 2112; a window the user gave keeps its value and sets the tail (window + 64). + // (MTP) keeps its window, whatever it is: a session KVA approximated tells it the first cell built from a real row + // (the cell floor, set per request below) and every session KVA did not approximate attends exactly as with + // STRATA_KVA=0. { const strata::prefill::KvaConfig& kc = strata::prefill::kva_config(); strata::prefill::KvaEngine& ke = strata::prefill::kva_engine(); @@ -5529,15 +5529,8 @@ int main(int argc, char** argv) { if (kc.explicit_on) std::fprintf(stderr, "strata generate: KVA (the approximate late-layer prompt read) is off here: %s\n", ke.blocked.c_str()); - } else if (!o.mtp.empty() && o.spec >= 2 && !o.mtp_window_given && kc.suffix_env <= 0) { - if (o.mtp_window != strata::prefill::kKvaDrafterWindow) - std::fprintf(stderr, "strata generate: KVA on (the faster prompt read for long cold prompts): the draft layer " - "attends to the last %lld cells (--mtp-window %lld); STRATA_KVA=0 keeps the " - "exact 0.2.6 prompt read and its %lld-cell window\n", - (long long) strata::prefill::kKvaDrafterWindow, (long long) strata::prefill::kKvaDrafterWindow, - (long long) o.mtp_window); - o.mtp_window = strata::prefill::kKvaDrafterWindow; } + mtp.enable_cell_floor(kc.wants_cell_floor(ke, !o.mtp.empty() && o.spec >= 2)); } } if (!o.mtp.empty()) { @@ -5559,11 +5552,6 @@ int main(int argc, char** argv) { if (o.pipeline_windows >= 2) mtp.set_force_capture(true); if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st && !mtp_first ? last_st->ss : ss, mtp_t, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; } mtp.set_ple_session(&ss); - if (!o.mtp.empty()) { // KVA: the cells the draft layer attends to now (0 = every cell) set the tail that must be exact - strata::prefill::KvaEngine& ke = strata::prefill::kva_engine(); - ke.has_drafter = true; - ke.drafter_window = mtp.window(); - } #if defined(STRATA_HAVE_DFLASH2) if (o.draft == "dflash2") { const char* why = o.mtp.empty() ? "it needs --mtp (the fallback) and --spec 2 or more" @@ -9473,6 +9461,9 @@ int main(int argc, char** argv) { // a reporter's prompts failed there every time and passed with --short-read 0. bool nf_prompt_windows = false, short_read_off_once = false; std::vector checks; + // KVA: which prefixes of token ids a KVA read approximated, so the draft layer knows, for whatever state a request + // continues from, the first cell built from a real row (kva_floor.hpp). Empty without KVA. + strata::prefill::KvaFloorRegistry kva_floors; // STRATA_CKPT_POOL: the dropped checkpoints' storage, reused. STRATA_SLOT_CKPT_MOVE turns it on too: a moved // checkpoint frees nothing at the next prune, so every save would fault in fresh pages (17 -> 40-60 ms) CheckpointPool ckpt_pool(ckpt_pool_env() || slot_ckpt_move_env()); @@ -9982,6 +9973,9 @@ int main(int argc, char** argv) { // come from Q8_1 x Q8_0 MMQ rather than mmvq: drafts may differ, the target's tokens never. static const bool split_mtp_batch = strata::program::draft_kv::split_env_on(std::getenv("STRATA_SPLIT_MTP_BATCH")); sp.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool { + // KVA: a chunk the late layers did not compute has no real final rows: its draft cells are neither built + // nor read (the floor rises before the cells are built, so they are skipped) + if (use_mtp && mtp.cell_floor_enabled() && sp.kva_floor() > mtp.cell_floor()) mtp.set_cell_floor(sp.kva_floor()); std::vector nxt((size_t) T); for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) cur[(size_t) (p0 + t + 1)]; // E-9: batched through the prompt path when it can (a layer split: only with STRATA_SPLIT_MTP_BATCH=1) @@ -13161,6 +13155,10 @@ int main(int argc, char** argv) { tr("request", n, geni ? 1 : 0); req_times = ReqTimes{}; if (use_mtp) mtp.set_prompt_len(n); + // KVA: the draft layer's first real cell for the state this request continues from (0 for a cold read - the + // first segment raises it if KVA approximates it - and for any state no KVA read produced) + if (use_mtp && mtp.cell_floor_enabled()) + mtp.set_cell_floor(resume > 0 && reread_to <= 0 ? kva_floors.floor_for(ids.data(), resume) : 0); const int64_t read_from = reread_to > 0 ? 0 : resume; conversations.limit_reuse(read_from); pp_total = n; @@ -13603,7 +13601,12 @@ int main(int argc, char** argv) { } seg_plan_scope{seg_plan}; auto run = [&](int64_t q, int64_t r) -> bool { if (planned) sp.force_chunk(plan.chunk, plan_single, plan.chunked); - return sp.run(ids.data() + q, r - q, q, e); + const bool run_ok = sp.run(ids.data() + q, r - q, q, e); + if (run_ok && q == 0 && sp.kva_floor() > 0) { // KVA approximated the start of this prompt: remember which tokens + kva_floors.note(ids.data(), sp.kva_floor()); + if (use_mtp && mtp.cell_floor_enabled()) mtp.set_cell_floor(sp.kva_floor()); + } + return run_ok; }; // (a layer split reads its stages as a pipeline over one run's chunks: beside slots a chunk at a time, with // none decoding in pieces of STRATA_BATCH_YIELD_CHUNKS chunks (default 8; 0 = one run) so a BYIELD is taken) @@ -15944,6 +15947,7 @@ int main(int argc, char** argv) { return 1; } prefill.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool { + if (mtp.cell_floor_enabled() && prefill.kva_floor() > mtp.cell_floor()) mtp.set_cell_floor(prefill.kva_floor()); // KVA // cell i pairs R_i with the token at i + 1 (every such token is in the prompt) std::vector nxt((size_t) T); for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) o.tokens[(size_t) (p0 + t + 1)]; From 6c00851ac1438a02ff37db974c258d6fc7e17b86 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 26 Oct 2026 13:03:41 +0100 Subject: [PATCH 8/8] KVA: the draft layer is untouched by default (window 32768, cells built for approximated chunks, no floor); the cell floor is STRATA_KVA_DRAFT_FLOOR=1 Measured on a 5070 (IQ3_S) the cell floor cut decode after a 14K / 30K approximated prompt by 22 / 34 percent (drafts accepted 100 -> 83 / 73 percent): a draft layer that reads only the exact tail loses its context. The approximated chunks' draft cells are usable, so by default nothing about the draft layer changes: not the window, not the cells built, not the attention. The floor machinery (MtpDrafter::set_cell_floor, window_ids_floor, KvaFloorRegistry) stays behind STRATA_KVA_DRAFT_FLOOR=1 for research. kva_test now really covers window_start with floor 0, the registry and wants_cell_floor. --- docs/KVA.md | 31 ++++++++--------- include/strata/prefill/kva.hpp | 15 +++++---- src/prefill/kva_test.cpp | 61 +++++++++++++++++++++++++++++++++- 3 files changed, 82 insertions(+), 25 deletions(-) diff --git a/docs/KVA.md b/docs/KVA.md index c53c6abd..5274bd3e 100644 --- a/docs/KVA.md +++ b/docs/KVA.md @@ -30,26 +30,20 @@ configuration rules KVA out for the whole run. The last `suffix` positions (2048, or `STRATA_KVA_SUFFIX`) are always read exactly. -The MTP draft layer builds its K/V from the final residuals of the prompt, and an approximated chunk has none. The -draft layer's window is **not changed**: it stays what it was (`--mtp-window`, default 32768 cells). Instead the -engine keeps a *cell floor* per session, the first draft cell built from a real row: +The MTP draft layer builds its K/V from the final residuals of the prompt. An approximated chunk has no final +residual of its own, so its draft cells are built from the rows that chunk does have. By default nothing about the +draft layer changes: its window is whatever it was (`--mtp-window`, default 32768 cells), it builds the same cells and +attends to the same cells as with `STRATA_KVA=0`. The target model verifies every token, so the draft only decides +how many tokens a verify window keeps (decode speed), never the answer. -- A read that KVA approximated raises the floor to the end of its approximated chunks. The draft layer builds no - cell below it and its attention starts no lower, so it reads the window `[max(floor, pos - window), pos)`: the - exactly computed tail, growing with the conversation, never an approximated cell. The target model verifies - every token either way. -- The floor follows the *tokens* of the state a request continues from (the live session, a conversation checkpoint, - a parked conversation): the engine remembers which token prefixes a KVA read approximated, and a state's floor - is how much of its tokens agree with one of them. A state no KVA read produced (a short chat, another document, - every prompt of a `STRATA_KVA=0` run) has floor 0. -- With floor 0 the draft layer attends to exactly the window it attended to with `STRATA_KVA=0` - (`window_start`, unit tested for every length). The only added work is one tiny kernel that picks the cells. - With `STRATA_KVA=0`, with the engine configurations that rule KVA out and with a build without a draft layer, - the draft layer's code is 0.2.6's own. +Measured on the P100 (IQ3_XXS, auto cache and prefill, 14K and 30K prompts, 256 tokens), the draft layer attends to +those cells with acceptance within noise of the exact read. A forced small window (the first default-on build set +`--mtp-window 2048` for every session) and the research option below both cost acceptance on faster cards. -Measured on the P100 (14K prompt, 256 tokens, auto cache and prefill), the draft layer's window made no difference -to decode (38.7 tok/s with the 32768-cell window, 40.1 with 2048); on faster cards a smaller window costs -acceptance, which is why the window is left alone. +`STRATA_KVA_DRAFT_FLOOR=1` (research): the draft layer gets a *cell floor* per session, the first cell built from a real +row. It builds no draft cell below it and attends to `[max(floor, pos - window), pos)`, the exact tail growing with +the conversation. The floor follows the tokens of the state a request continues from (`kva_floor.hpp`); a state no KVA +read produced has floor 0. It is off by default because it costs draft acceptance after long prompts. ## Chats, follow-up turns and checkpoints (`--serve`) @@ -86,6 +80,7 @@ there, with a line when it is set). | `STRATA_KVA_SPLIT` | 24 | first approximated layer (zero-based) | | `STRATA_KVA_SUFFIX` | 2048 | fully computed tail positions; see above | | `STRATA_KVA_MIN_PROMPT` | 4096 | shorter prompts stay on the full path | +| `STRATA_KVA_DRAFT_FLOOR` | off | `1`: the draft layer skips the draft cells of approximated chunks (research) | | `STRATA_KVA_ONLY` | all | `gdn` or `qsa`: approximate only that layer type | | `STRATA_KVA_MODE` | identity | `identity`, `oracle`, `linear` (linear is not implemented) | | `STRATA_KVA_CAPTURE` | — | directory: write every late layer's real input for calibration (the read is exact while capturing) | diff --git a/include/strata/prefill/kva.hpp b/include/strata/prefill/kva.hpp index 80e8bdb0..874566d2 100644 --- a/include/strata/prefill/kva.hpp +++ b/include/strata/prefill/kva.hpp @@ -22,11 +22,12 @@ // whole process (batch slots, a layer split, a peer device). // // The draft layer (MTP) builds its K/V from the final rows of the prompt, which an approximated chunk does not have. -// Its window is NOT changed: the draft layer's attention starts at the "cell floor" (MtpDrafter::set_cell_floor), the -// first cell built from a real row, and the cells below it are neither built nor read. A session KVA did not -// approximate has a floor of 0 and is bit for bit what STRATA_KVA=0 runs (kva_floor.hpp keeps the floor with the -// tokens of the session, window_start.hpp is the one rule the kernel and the tests share). The target model verifies -// every token whatever the draft read. +// Its window is NOT changed, and by default neither is anything else: the draft cells of an approximated chunk are +// built from the rows that chunk has and the draft layer attends to them (measured: draft acceptance after a KVA +// read stays within noise on the P100). The research option STRATA_KVA_DRAFT_FLOOR=1 gives the draft layer a "cell +// floor" per session (MtpDrafter::set_cell_floor; kva_floor.hpp keeps it with the tokens of the session, +// window_start.hpp is the one rule the kernel and the tests share): the first cell built from a real row, below +// which no draft cell is built or read. The target model verifies every token whatever the draft read. #pragma once #include @@ -68,6 +69,7 @@ struct KvaConfig { bool capture_fp32 = false; ///< STRATA_KVA_CAPTURE_FP32=1: fp32 records (else bf16; fp32 is for parity runs) bool oracle_fp32 = false; ///< STRATA_KVA_ORACLE_FP32=1: the oracle files are fp32 (else bf16) bool parity = false; ///< STRATA_KVA_PARITY=1: report the state-only path against the full path + bool draft_floor = false; ///< STRATA_KVA_DRAFT_FLOOR=1: the draft layer skips the cells of approximated chunks (research; default: it reads them) int64_t split = 24; ///< STRATA_KVA_SPLIT: first approximated layer (zero-based) int64_t suffix_env = 0; ///< STRATA_KVA_SUFFIX: fully computed tail positions (0 = not set: kKvaSuffixDefault) int64_t min_prompt = 4096; ///< STRATA_KVA_MIN_PROMPT: shorter prompts stay on the full path @@ -83,7 +85,7 @@ struct KvaConfig { /// Does the draft layer need the cell floor at all? Only when a read can approximate something: KVA on, not ruled /// out for the process, and a draft layer loaded. Otherwise the draft layer's attention is 0.2.6's own code. bool wants_cell_floor(const KvaEngine& e, bool has_drafter) const { - return kKvaBackend && on && e.blocked.empty() && has_drafter; + return kKvaBackend && on && draft_floor && e.blocked.empty() && has_drafter; } /// Why this read cannot take the approximate path, or nullptr when it can: a cold read of one prompt (not a @@ -143,6 +145,7 @@ inline KvaConfig kva_config_from_env() { k.suffix_env = std::max(0, kva_env_i64("STRATA_KVA_SUFFIX", 0)); k.min_prompt = kva_env_i64("STRATA_KVA_MIN_PROMPT", 4096); k.parity = kva_env_flag("STRATA_KVA_PARITY", false); + k.draft_floor = kva_env_flag("STRATA_KVA_DRAFT_FLOOR", false); if (const char* d = std::getenv("STRATA_KVA_CAPTURE"); d != nullptr && *d != '\0') { k.capture = true; k.capture_dir = d; diff --git a/src/prefill/kva_test.cpp b/src/prefill/kva_test.cpp index 937d0ca1..be6f2ef8 100644 --- a/src/prefill/kva_test.cpp +++ b/src/prefill/kva_test.cpp @@ -31,7 +31,7 @@ static void put(const char* k, const char* v) { static void clear_all() { for (const char* k : {"STRATA_KVA", "STRATA_KVA_SPLIT", "STRATA_KVA_SUFFIX", "STRATA_KVA_MIN_PROMPT", "STRATA_KVA_PARITY", "STRATA_KVA_CAPTURE", "STRATA_KVA_CAPTURE_FP32", "STRATA_KVA_ORACLE", "STRATA_KVA_ORACLE_FP32", - "STRATA_KVA_PROJECTOR", "STRATA_KVA_MODE", "STRATA_KVA_ONLY"}) + "STRATA_KVA_PROJECTOR", "STRATA_KVA_MODE", "STRATA_KVA_ONLY", "STRATA_KVA_DRAFT_FLOOR"}) unset(k); } static bool is(const char* got, const char* want) { return got != nullptr && std::strcmp(got, want) == 0; } @@ -118,6 +118,65 @@ int main() { } clear_all(); + // ---- "not applied => identical to STRATA_KVA=0", the parts that need no GPU + // (1) by default the draft layer is 0.2.6's own code; the cell floor is a research option, wired only when asked + { + KvaEngine eng; + const KvaConfig on = kva_config_from_env(); + CHECK(!on.draft_floor && !on.wants_cell_floor(eng, true)); + put("STRATA_KVA_DRAFT_FLOOR", "1"); + const KvaConfig fl = kva_config_from_env(); + CHECK(fl.draft_floor && fl.wants_cell_floor(eng, true)); + CHECK(!fl.wants_cell_floor(eng, false)); // no draft layer: nothing to wire + KvaEngine blocked; + blocked.blocked = "batch slots (--batch)"; + CHECK(!fl.wants_cell_floor(blocked, true)); // ruled out for the process: 0.2.6's own attention code + put("STRATA_KVA", "0"); + const KvaConfig off = kva_config_from_env(); + CHECK(!off.wants_cell_floor(eng, true)); // STRATA_KVA=0: untouched + clear_all(); + } + // (2) with a floor of 0 the window is exactly the plain window, for every length and every window + { + using strata::kernels::window_start; + bool same = true; + for (int window : {1, 2, 64, 2048, 32768, 0x7fffffff}) + for (int n_kv : {0, 1, 2, 63, 64, 65, 2047, 2048, 2049, 4096, 14000, 32768, 32769, 100000}) { + const int plain = n_kv > window ? n_kv - window : 0; // what window_ids always selected + if (window_start(n_kv, window, 0) != plain) same = false; + } + CHECK(same); + CHECK(window_start(14000, 32768, 11264) == 11264); // a floor inside the window raises the start + CHECK(window_start(14000, 2048, 11264) == 11952); // a floor below the window changes nothing + CHECK(window_start(14000, 32768, 20000) == 13999); // a floor past the end keeps one cell + CHECK(window_start(14000, 32768, 14000) == 13999); + CHECK(window_start(1, 32768, 5) == 0); + CHECK(window_start(0, 32768, 5) == 0); + } + // (3) the floor follows the session's tokens: a state no KVA read produced has floor 0 + { + KvaFloorRegistry reg; + std::vector doc; + for (int i = 0; i < 20000; ++i) doc.push_back(1000 + (i * 7919) % 5000); + CHECK(reg.floor_for(doc.data(), (int64_t) doc.size()) == 0); // nothing remembered + reg.note(doc.data(), 11264); // a KVA read approximated [0, 11264) + CHECK(reg.floor_for(doc.data(), 20000) == 11264); // the live session / a later turn of it + CHECK(reg.floor_for(doc.data(), 5000) == 5000); // a checkpoint inside the approximated part + std::vector other(doc); + for (int i = 0; i < 20000; ++i) other[(size_t) i] += 1; // a different prompt entirely + CHECK(reg.floor_for(other.data(), 20000) == 0); // short chats, other documents: floor 0 + std::vector shared(doc.begin(), doc.begin() + 3000); // a new chat sharing the first 3000 tokens + for (int i = 3000; i < 9000; ++i) shared.push_back(900000 + i); + CHECK(reg.floor_for(shared.data(), 9000) == 3000); + reg.note(doc.data(), 11264); // the same read again: no second entry + CHECK(reg.size() == 1); + KvaFloorRegistry small(2); + for (int k = 0; k < 5; ++k) { std::vector d(100, k); small.note(d.data(), 100); } + CHECK(small.size() == 2); // bounded + reg.clear(); + CHECK(reg.floor_for(doc.data(), 20000) == 0); + } + if (fails == 0) std::printf("kva_test: ok\n"); return fails == 0 ? 0 : 1; }