diff --git a/CMakeLists.txt b/CMakeLists.txt index 49aa2180..adfcf6fc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1549,6 +1549,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/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 diff --git a/docs/KVA.md b/docs/KVA.md index 556f7197..5274bd3e 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,94 @@ 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 (2048, or `STRATA_KVA_SUFFIX`) are always read exactly. + +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. + +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. + +`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`) + +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` | 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 | +| `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 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). ## Measured (Tesla P100 16 GB, Qwen3.8-Flash-Next IQ3_XXS, chunk 1024, expert cache 1500, MTP window 2048) @@ -96,7 +146,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..38fe8f01 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -26,6 +26,7 @@ #include +#include #include #include #include @@ -166,7 +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; } @@ -271,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 212522a5..874566d2 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. +// +// 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, 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 #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 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 { + 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 + 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 = 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: 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 @@ -42,12 +79,45 @@ 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. + 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 && 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 + /// 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 (n < min_prompt) { + if (routine) *routine = true; + return "the prompt is shorter than STRATA_KVA_MIN_PROMPT"; + } + if (n <= effective_suffix() + 64) { + if (routine) *routine = true; + return "the suffix leaves too few positions to approximate"; + } + return nullptr; } }; @@ -63,41 +133,49 @@ 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); + 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; + 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/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 78ff2891..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 {}; } @@ -340,6 +341,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/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/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; diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 297b7bd3..07b88f48 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -4358,8 +4358,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 @@ -4422,7 +4433,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; @@ -4430,10 +4441,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); } @@ -4511,7 +4523,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; 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 new file mode 100644 index 00000000..be6f2ef8 --- /dev/null +++ b/src/prefill/kva_test.cpp @@ -0,0 +1,182 @@ +// 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; + +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", "STRATA_KVA_DRAFT_FLOOR"}) + 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 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(); + CHECK(c.effective_suffix() == kKvaSuffixDefault && kKvaSuffixDefault == 2048); + put("STRATA_KVA_SUFFIX", "3000"); + const KvaConfig e = kva_config_from_env(); + CHECK(e.effective_suffix() == 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; + 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(); + // no draft layer at all: nothing to cover + // 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(); + + // ---- "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; +} diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index f0b09e55..8fd781a5 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -2716,12 +2716,19 @@ 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(); + 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) + 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()) @@ -2856,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) @@ -5272,25 +5280,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 28f6fb1a..f9fb57fd 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -72,6 +72,8 @@ #include "strata/core/dflash2.hpp" #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" @@ -1982,6 +1984,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); @@ -3563,10 +3581,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"); @@ -4092,9 +4113,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", @@ -5507,6 +5529,30 @@ 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) 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(); + 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()); + } + mtp.enable_cell_floor(kc.wants_cell_floor(ke, !o.mtp.empty() && o.spec >= 2)); + } + } if (!o.mtp.empty()) { if (o.spec < 2) { std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n"); @@ -9435,6 +9481,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()); @@ -9944,6 +9993,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) @@ -13123,6 +13175,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; @@ -13565,7 +13621,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) @@ -15906,6 +15967,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)];