From 640ac438be9e79af219c8fb022cbb03cf3a477c5 Mon Sep 17 00:00:00 2001 From: Maxim Mazurok Date: Tue, 13 Oct 2026 09:29:20 +1100 Subject: [PATCH] --prefill-head-alias (opt-in, --serve, one GPU): the output head's VRAM holds the prompt buffers while a prompt is read The native output head is needed only to generate, the batched prompt path's buffers only to read a prompt. With the flag the head is unloaded while a prompt is read (its VRAM counted into the auto cache and the prompt path's hybrid borrowed/owned layout) and read back in before the first decode window. On an 8 GB RTX PRO 2000 Laptop (Windows, IQ3_XXS, 590 MiB reserve) the prompt chunk went from 512 to 2,048 tokens and prefill from 292.5 to 667.1 tok/s on a 29,854-token prompt; reads of up to 512 fresh tokens cost about 0.6-0.75 s more. Off by default: every new path is behind the flag. docs/PREFILL_HEAD_ALIAS.md has the measurements and limits. --- docs/DETAILS.md | 6 + docs/PREFILL_HEAD_ALIAS.md | 170 ++++++++++++++++++++++++++++ include/strata/core/mtp.hpp | 1 + include/strata/core/native_head.hpp | 1 + include/strata/prefill/prefill.hpp | 3 +- src/core/native_head.cpp | 6 + src/prefill/prefill.cpp | 16 ++- src/program/generate.cpp | 143 ++++++++++++++++++----- sycl/src/prefill/prefill.cpp | 6 +- 9 files changed, 319 insertions(+), 33 deletions(-) create mode 100644 docs/PREFILL_HEAD_ALIAS.md diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 6525c0e9..d703d9c0 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1763,6 +1763,12 @@ the pairs in which the switched arm won). They are here so you can try them on y tier's copies for layer 45 never landed" (RTX 4070 SUPER, driver 617.42). `STRATA_ADAPT_SIGNAL=copy` asks for the copy there; the engine now flushes the copy stream after queueing the swaps, which is meant to fix it but has not been run on Windows yet. +- **`--prefill-head-alias` (`--serve`, one GPU): the output head's VRAM holds the prompt buffers while a prompt is read**, + and the head is read back in before the first generated token. It was not measured with the paired method above. On + an 8 GB RTX PRO 2000 Laptop (Windows, IQ3_XXS, 590 MiB reserve) it let the prompt path use 2,048-token chunks + instead of 512: prefill 292.5 -> 667.1 tok/s on a 29,854-token prompt (medians of 12 and 6 fresh-engine trials). + Reads of up to 512 fresh tokens cost about 0.6-0.75 s more per request, and the card had 0 MiB free while decoding. + Details, limits and the measurement: [PREFILL_HEAD_ALIAS.md](PREFILL_HEAD_ALIAS.md). ## Thread placement: `--aux-cpus` (Linux, off by default) diff --git a/docs/PREFILL_HEAD_ALIAS.md b/docs/PREFILL_HEAD_ALIAS.md new file mode 100644 index 00000000..b0506303 --- /dev/null +++ b/docs/PREFILL_HEAD_ALIAS.md @@ -0,0 +1,170 @@ +# Lend the output head's VRAM to the prompt path (`--prefill-head-alias`, opt-in) + +Two large VRAM users never work at the same time. The native output head (417 MiB for the Q5_K head of +IQ3_XXS) turns the last hidden state into logits, so it is needed only while tokens are generated. The batched prompt +path's buffers are needed only while a prompt is read. With `--prefill-head-alias` the engine takes turns: the head's +VRAM holds prompt buffers while a prompt is read, and the head is read back in before the first generated token. + +The flag is off by default. With it off, the engine does exactly what it did before. + +## Why + +On an 8 GB card the prompt chunk is as large as the free VRAM allows, and prefill speed follows the chunk closely. Here +is the same 29,854-token prompt with a fresh engine per trial and one request each. The card and settings are listed +under [Measurements](#measurements). + +| Prompt chunk | Trials | Prefill, median (range) | How the engine got there | Free VRAM after start | +|---:|---:|---:|---|---:| +| 256 | 4 | 185.5 (177.8-195.9) tok/s | `--prefill auto`, reserve 686-745 MiB | 383-443 MiB | +| 512 | 12 | 292.5 (281.0-306.1) tok/s | `--prefill auto`, reserve 442-667 MiB (590 is our tuned value) | 137-365 MiB | +| 768 | 7 | 387.4 (375.8-397.2) tok/s | `--prefill auto`, reserve 331-405 MiB | 27-103 MiB | +| 1,024 | 4 | 442.9 (440.8-444.1) tok/s | `--prefill auto`, reserve 239-295 MiB | 0 MiB | +| 1,280 | 5 | 514.5 (512.8-517.3) tok/s | `--prefill auto`, reserve 147-221 MiB | 0 MiB | +| 1,536 | 2 | 573.6 (571.0-576.3) tok/s | `--prefill auto`, reserve 73-110 MiB | 0 MiB | +| 1,792 | 3 | 631.4 (628.7-632.9) tok/s | `--prefill auto`, reserve 0-36 MiB | 0 MiB | +| **2,048** | **6** | **667.1 (661.5-667.7) tok/s** | **`--prefill-head-alias`, reserve 590 MiB** | **289 MiB** | + +Without the flag, every chunk above 768 tokens came only from lowering `--vram-reserve-mib`, and that left 0 MiB free. +Under WDDM that is the state in which Windows starts paging. With the flag, the 2,048-token chunk came with the 590 MiB +reserve unchanged. + +## What it does + +1. **At start**, after the MTP draft layer has copied its draft-head rows from the output head, the head is unloaded. + The auto expert cache is then sized with the head's VRAM counted as free (on our card: 749 slots instead of 508). + The prompt path borrows cache slots 1 to N (slot 0 stays). Whatever does not fit there is allocated by the prompt + path itself, which makes a "hybrid" layout. The chunk is the largest of 2,048, 1,536, 1,024 and 512 tokens whose + buffers fit in the borrowed slots plus free VRAM with 512 MiB to spare. +2. **For each request**: + 1. If the head is loaded, unload it and lay the prompt path out again (median 20 ms). + 2. Read the prompt. + 3. Refill the lent slots and free the prompt path's own buffers. + 4. Load the head again (median 255 ms) before the first decode window. +3. **Graph safety.** The verify windows' CUDA graphs are captured during the first decode and hold the head's address. + If a later reload puts the head at a different address, the engine stops with an error, and the server starts it + again. It does not run graphs that point at freed memory. We never saw this happen; see + [Open questions](#open-questions). + +The engine refuses the flag, with the reason, without `--serve`, with more than one GPU or a layer split, with +`--batch`, with `--pipeline-windows`, with `--short-read` above 0, with a fixed `--expert-cache` above 1, without `--mtp`, +or without the native output head. + +## Costs + +- **Short reads get slower.** Each request reloads the head (median 255 ms over 2,717 restores, p90 261 ms, max + 495 ms) and rebuilds the prompt path (20 ms). It also lends and then refills almost the whole cache, even for a few + tokens. The engine's own prompt time, which includes all of this, by fresh tokens read (production, medians): + + | Fresh tokens read | Default | Head alias | + |---:|---:|---:| + | 1-64 | 671 ms (293 requests) | 1,311 ms (614) | + | 65-512 | 1,703 ms (409) | 2,453 ms (955) | + | 513-2,048 | 4,062 ms (278) | 3,331 ms (618) | + | 2,049-8,192 | 15,206 ms (118) | 6,876 ms (277) | + + So the flag costs about 0.6-0.75 s on reads of up to 512 tokens and pays off from somewhere between 513 and 2,048 + tokens. In the agent loop, 614 of 2,717 requests read 64 fresh tokens or fewer. +- **Less free VRAM while decoding.** In the default run, the verify windows were captured with 207-287 MiB free. With + the flag, they were captured with 0 MiB free. Over 2,717 requests (about 26 hours) we saw no paging symptoms: decode + held about 29 tok/s from the first request to the last (table below). This is the main risk on other cards and + drivers. +- **More slots to refill after each prompt.** The prompt path borrows almost the whole cache (748 of 749 slots instead + of 328 of 508), so more experts are copied back after each prompt. That time is counted in the prompt time above. + +## Measurements + +Card and settings for every number on this page: + +- NVIDIA RTX PRO 2000 Blackwell Laptop GPU, 8,151 MiB, Windows 11 Pro (WDDM, driver 597.16), CUDA 13.0, sm_120. +- Intel Core Ultra 9 285H (AVX2), 64 GiB RAM, PCIe probe 25 GB/s (`pcie_frac` 0.55 picked by auto). +- Qwen3.8-Flash-Next IQ3_XXS native pack, `--max-context 262144`, `--kv q4_0`, `--kv-resident 32768`, `--spec 4`, + `--spec-min-p 0.5`, MTP with the English draft vocabulary, `--prompt-cache 3`, `--vram-reserve-mib 590`, + `--expert-cache auto`, `--prefill auto`. +- The engine was a local 0.1.41 build with this change. Both sides also used a local `STRATA_ARENA_REGISTER=0` switch + that is not part of this change: it skips `cudaHostRegister` of the 40 GiB arena on this machine. + +### Controlled: one prompt, one forced output + +Each trial ran a fresh engine on the 29,854-token prompt. The same 3,072-token continuation was forced one verify row per +token, with no speculative drafts, so the decode numbers compare the same work. A local benchmark switch did the forcing; +it is not part of this change. + +| Setting | Trials | Expert slots | Prompt chunk | Prefill | Decode | Expert-cache hits | +|---|---:|---:|---:|---:|---:|---:| +| 1-slot cache | 4 | 1 | 1,024 (own buffers) | 441.0 tok/s | 22.26 tok/s | 0.2% | +| 1-slot cache + head alias | 2 | 1 | 2,048 | 666.3 tok/s | 24.50 tok/s | 0.2% | +| auto cache + head alias | 3 | 749 | 2,048 | 667.7 tok/s | 26.21 tok/s | 24.9% | + +We did not run the default (auto cache, no head alias) in this forced mode. Its free-running result on the same prompt +is the 512-token row of the first table: one trial at the 590 MiB reserve read 306.1 tok/s and decoded 27.9 tok/s, and +six head-alias trials decoded 26.6-29.0 tok/s (median 27.9). Free-running outputs differ from trial to trial, so their +decode rates are only a rough comparison. + +### Production: an agent loop + +The workload was OpenCode agents (worker, reviewer and retrospective) running a coding loop against `/v1/chat/completions`. +Prompts went up to about 150K tokens, with `--prompt-cache 3` prefix reuse. + +- Default: 1,200 requests over 8 loop cycles. +- `--prefill-head-alias`: 2,649 requests over 20 cycles. + +The flag also needs `--short-read 0`; the default run had 64. Everything else was the same. Rates come from the engine's +own lines (`reading the prompt` progress over at least 5 s, and the decode rate of requests with at least 32 output +tokens). They are compared inside 16K-token context bands, so a heavier or lighter mix of prompts on either side does not +count as a speed change. Intervals are 95% bootstrap intervals. + +| | Default | Head alias | Change within context bands | +|---|---:|---:|---:| +| Prefill, median | 256 tok/s | 583 tok/s | +125% (+123% to +129%) | +| Decode, median | 24.8 tok/s | 29.2 tok/s | +19% (+17% to +23%) | +| Expert-cache hits, median | 20.8% | 25.9% | 508 -> 749 slots | + +The decode difference needs care. The default runs alternated between long stretches near 27.5 tok/s and long stretches +near 19.5 tok/s. A rolling median over 51 requests showed plateaus of hundreds of requests each, and in one run the +switch from slow to fast came with no engine restart. In the head-alias run, each twelfth of the 2,649 requests had a +median decode of 28.7-29.8 tok/s. Against the default's +fast stretches only, decode was about 6% faster. We do not know what caused the slow stretches, so we do not claim that +this change removes them. + +The engine binary was also rebuilt between the two runs, to add prompt-cache support to this change. The controlled +table above is the comparison that holds the binary fixed. + +## Port check on 0.1.43.1 + +This change was moved to upstream main (0.1.43.1) and checked on the same PC. Both runs used the same build, a fresh +engine each, and `STRATA_ARENA_PIN_GIB=auto`: without it, the full sliced arena pin on this 64 GB PC left WDDM with +0 GiB free for the cache (#243). The requests were the 29,842-token prompt cold, then a 31-token follow-up on its +prefix, two 45-token prompts, and the long prompt again. Output was capped at 768 tokens with low reasoning, and +generation was free (not forced). + +| | Default | Head alias | +|---|---:|---:| +| Expert slots, prompt chunk | 507, 512 | 753, 2,048 | +| Free VRAM when the verify windows were captured | 207-245 MiB | 0 MiB | +| Cold 29,842-token prompt, two runs | 276.5, 277.1 tok/s | 643.1, 649.7 tok/s | +| Decode on those two | 35.7, 34.7 tok/s | 34.1, 31.6 tok/s | +| 31-token follow-up (29,837 reused), prompt time | 632 ms | 1,721 ms | +| 45-46-token prompts, prompt time | 871, 1,005 ms | 1,780, 1,424 ms | + +All five requests completed with coherent answers. The head came back at the same address every time, so the guard +never fired. 0.1.43.1's new start-of-request warning ("below 1024 MiB free") appears with both settings, at 289 MiB +for the default and 0 MiB with the flag. + +## Open questions + +- **A fixed address for the head.** The head goes back with `cudaMalloc`, which does not promise the same address. The + check above makes a moved head a clean engine restart. A cleaner design would keep the head's virtual range and swap + its backing (CUDA VMM), or lay prompt buffers directly into the head's allocation instead of freeing it. +- **Skip the swap for short reads.** A request that reads a few dozen fresh tokens pays about 0.6 s (table above) for a + 2,048-token chunk it does not need. A threshold on fresh tokens, below which the head stays and the read goes through + the decode windows as `--short-read` does, would remove that cost. +- **Other cards.** We measured only the 8 GB card above, on Windows. A larger card already gets a large chunk without + the flag, so we expect the gain to be smaller there. + +## Not tested + +- This change on upstream main (0.1.43.1) was compiled for CUDA (13.0, sm_120, MSVC, Windows) and checked with the + short run above. The longer measurements come from the 0.1.41 build. +- HIP (the same sources) and SYCL. On SYCL, `Prefill::init` refuses the hybrid layout; the SYCL engine has no flag + for it. +- Linux, multi-GPU, `--batch` and `--pipeline-windows` (all refused), and models other than Qwen3.8-Flash-Next IQ3_XXS. diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index 205f2385..d3c05a98 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -82,6 +82,7 @@ public: /// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each). bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err, const MtpDrafter* shared = nullptr); + void set_window_R(const float* window_R) { window_R_ = window_R; } /// Prompt cells [cell0, cell0 + n): residual rows `R_rows` (device, hc*n_embd each) and `next_tokens` (host, /// the token at position cell+1). Runs in batches of up to max_t rows. `sync` false: returns without waiting diff --git a/include/strata/core/native_head.hpp b/include/strata/core/native_head.hpp index 54562949..501f6ec2 100644 --- a/include/strata/core/native_head.hpp +++ b/include/strata/core/native_head.hpp @@ -20,6 +20,7 @@ public: NativeHead& operator=(const NativeHead&) = delete; bool load(const std::vector& shards, int64_t n_in, int64_t n_out, std::string& err); + void unload(); bool run(const float* mixed, float* logits, void* stream, std::string& err) const; uint64_t weight_bytes() const { return bytes_; } bool loaded() const { return weights_ != nullptr; } diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 1f0ad13f..b4f100df 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -69,7 +69,8 @@ public: /// lent for the prompt and refilled after it); null = allocate normally. bool init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss, core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk, - void* stream, std::string& err, void* borrow = nullptr, uint64_t borrow_bytes = 0); + void* stream, std::string& err, void* borrow = nullptr, uint64_t borrow_bytes = 0, + bool borrow_spill = false); /// With borrowed buffers: lay them out again for chunks of `chunk` tokens (at most `init`'s) in `borrow` - a /// request lends only the slots its prompt needs. The stream must be idle (between prompts). diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp index 93ec0fd2..daa381e7 100644 --- a/src/core/native_head.cpp +++ b/src/core/native_head.cpp @@ -13,9 +13,15 @@ namespace strata::core { NativeHead::~NativeHead() { + unload(); +} + +void NativeHead::unload() { if (weights_) strata::kernels::native_q6_k_unpack(weights_); if (scratch_) cudaFree(scratch_); if (weights_) cudaFree(weights_); + scratch_ = nullptr; + weights_ = nullptr; } bool NativeHead::load(const std::vector& shards, int64_t n_in, int64_t n_out, std::string& err) { diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 3f537abd..87614659 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -376,6 +376,7 @@ struct Alloc { uint64_t failed_bytes = 0; ///< the take that could not be allocated; the failure message names it uint64_t granule = 0; ///< count_only: each take rounds up to this (cudaMalloc's 2 MiB pages: owned buffers) bool count_only = false; + bool spill = false, spilled = false; std::vector* owned = nullptr; template T* take(size_t n, bool& ok) { uint64_t bytes = ((uint64_t) n * sizeof(T) + 256 + 255) & ~255ull; @@ -384,14 +385,15 @@ struct Alloc { used += bytes; return nullptr; } - if (base != nullptr) { - if (used + bytes > cap) { ok = false; failed_bytes = bytes; return nullptr; } + if (base != nullptr && !spilled && used + bytes <= cap) { T* p = (T*) (base + used); used += bytes; return p; } + if (base != nullptr && !spill) { ok = false; failed_bytes = bytes; return nullptr; } void* p = nullptr; if (cudaMalloc(&p, bytes) != cudaSuccess) { ok = false; failed_bytes = bytes; return nullptr; } + spilled = true; owned->push_back(p); used += bytes; return (T*) p; @@ -746,7 +748,7 @@ struct Prefill::Impl { const core::ExpertCache* cache = nullptr; const int32_t* host_res = nullptr; int64_t T = 0, T_max = 0; - bool borrowed = false; + bool borrowed = false, borrow_spill = false; cudaStream_t cs = nullptr, copy = nullptr; Gemm gemm; std::vector owned; @@ -1060,7 +1062,7 @@ uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) { bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss, core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk, - void* stream, std::string& err, void* borrow, uint64_t borrow_bytes) { + void* stream, std::string& err, void* borrow, uint64_t borrow_bytes, bool borrow_spill) { Impl& m = *impl_; m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res; m.T = chunk; m.cs = (cudaStream_t) stream; m.stats = &stats_; @@ -1093,6 +1095,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co const size_t T = (size_t) chunk; m.T_max = chunk; m.borrowed = borrow != nullptr; + m.borrow_spill = m.borrowed && borrow_spill; bool ok = true; // one-time: events, the stager, the host buffers (for the largest chunk), the identity page table for (int i = 0; i < ring_cap(); ++i) { @@ -1182,6 +1185,7 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co Alloc o; o.base = (uint8_t*) borrow; o.cap = borrow_bytes; + o.spill = m.borrow_spill; o.owned = &m.owned; { uint16_t* gs = o.take((size_t) GEMM_SCRATCH, ok); @@ -1310,6 +1314,10 @@ bool Prefill::carve(size_t T, void* alloc) { bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err) { Impl& m = *impl_; + if (m.borrow_spill) { + err = "prefill: a hybrid borrowed/owned layout cannot be changed between requests"; + return false; + } if (!m.borrowed || borrow == nullptr || chunk <= 0 || chunk > m.T_max) { err = "prefill: relayout needs borrowed buffers and a chunk of at most " + std::to_string(m.T_max); return false; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 94e5ff0f..b417aab3 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -645,6 +645,7 @@ struct Options { /// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always /// the batched path) int64_t short_read = 64; + bool prefill_head_alias = false; // lend the native output head's VRAM to prompt buffers between request phases /// --pipeline-windows N (--serve, a layer split on exactly two GPUs; opt-in): 1 = a prompt's short reads through /// the verify windows run with the stages overlapped (stage 0 reads window K+1 while stage 1 reads window K); /// 2 = the decode windows too: stage 0 runs window K+1 speculatively while stage 1 verifies window K (rolled back @@ -800,6 +801,8 @@ void usage() { " the conversation checkpoint (a trailing effort turn; default -1 = off)\n" " --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" " of the batched prompt path (default 64, 0 = off)\n" + " --prefill-head-alias --serve: unload the native output head while each fresh prompt is read,\n" + " then release prompt buffers and reload it before decode\n" " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" " when it pays (default 3; 0 = MTP only)\n" " --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n" @@ -2083,6 +2086,7 @@ int main(int argc, char** argv) { else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token")); else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token")); else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); + else if (a == "--prefill-head-alias") o.prefill_head_alias = true; else if (a == "--pipeline-windows") o.pipeline_windows = std::max(0, std::min(2, std::atoi(next("--pipeline-windows")))); else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); @@ -4598,6 +4602,31 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: the logits buffer failed%s\n", vram_free_note().c_str()); return 1; } + bool prefill_head_alias_bound = false; + const void* prefill_head_alias_at = nullptr; // where the head came back the first time + if (o.prefill_head_alias) { + const char* why = !o.serve ? "it needs --serve" + : multi_gpu || !stages.empty() ? "it supports one GPU only" + : o.batch > 0 ? "it does not support --batch" + : o.pipeline_windows > 0 ? "it does not support --pipeline-windows" + : o.short_read > 0 ? "it needs --short-read 0" + : o.expert_cache != 1 && o.expert_cache >= 0 ? "it needs --expert-cache 1 or auto" + : o.mtp.empty() ? "it needs --mtp" + : !native_head.loaded() ? "it needs the native output head" + : nullptr; + if (why != nullptr) { + std::fprintf(stderr, "strata generate: --prefill-head-alias is unavailable: %s\n", why); + return 2; + } + if (!mtp.bind(wt, &native_head, nullptr, err)) { + std::fprintf(stderr, "strata generate: --prefill-head-alias: %s\n", err.c_str()); + return 1; + } + native_head.unload(); + prefill_head_alias_bound = true; + std::fprintf(stderr, "strata generate: --prefill-head-alias: the %llu-byte output head is prompt workspace\n", + (unsigned long long) native_head.weight_bytes()); + } // Create the additional contexts after MTP has secured CUDA0 memory, but // before the host arena maps its expert pages into their address spaces. for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && !early_remote) { @@ -4909,6 +4938,10 @@ int main(int argc, char** argv) { if (o.expert_cache < 0) { size_t free_b = 0, total_b = 0; free_b = strata::core::device_free_bytes(); (void) total_b; + if (free_b == 0 && o.prefill_head_alias) { + (void) cudaGetLastError(); + free_b = strata::core::device_free_bytes(); + } // Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here - // under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls. // (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is @@ -7309,6 +7342,27 @@ int main(int argc, char** argv) { } else if (o.prefill_auto && d_res == nullptr) { o.prefill_chunk = 1024; // #85: no expert cache at all (a full 8 GB card): small buffers of its own } + if (o.prefill_head_alias) { + for (PfPart& p : pf_parts) { + p.first = p.cache->slots() > 1 ? 1 : -1; + p.first_now = p.first; + } + lend_first = pf_parts[0].first; + borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; + borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + static constexpr int64_t candidates[] = {2048, 1536, 1024, 512}; + for (const int64_t candidate : candidates) + if (strata::prefill::Prefill::bytes_needed(g, ss, candidate) + (512ull << 20) <= + free_b + borrow_bytes) { + o.prefill_chunk = candidate; + break; + } + std::fprintf(stderr, "strata serve: prompt chunk head alias: %lld tokens with %lld MiB borrowed and " + "%lld MiB free\n", + (long long) o.prefill_chunk, (long long) (borrow_bytes >> 20), (long long) (free_b >> 20)); + } bool any_loan = borrow != nullptr; for (size_t i = 1; i < pf_parts.size(); ++i) any_loan = any_loan || pf_parts[i].first >= 0; if (any_loan) { @@ -7369,7 +7423,8 @@ int main(int argc, char** argv) { } if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp); if (share_pool) sp.set_cpu_pool(&pool); - if (!sp.init(wt, g, ss, prefill_src, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) + if (!sp.init(wt, g, ss, prefill_src, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes, + o.prefill_head_alias)) return err.find("do not fit") != std::string::npos ? 2 : 1; return 0; }; @@ -7700,13 +7755,14 @@ int main(int argc, char** argv) { } ver.set_remote_expert_opt(remote_opt.get()); if (batch_mtp) ver.set_batch_graph_limit(64); // --batch-mtp only: slot rotation makes many layouts (LRU); 0.1.39 keeps all - if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, + if (!ver.init(wt, g, ss, vh, native_head.loaded() || prefill_head_alias_bound ? &native_head : nullptr, batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, o.batch), err) || - (use_mtp && !mtp.bind(last_st && !mtp_first ? last_st->wt : wt, last_st ? &last_st->head : &native_head, + (use_mtp && !prefill_head_alias_bound && !mtp.bind(last_st && !mtp_first ? last_st->wt : wt, last_st ? &last_st->head : &native_head, pipe ? pl_mtp_R : ver.final_R_all(), err))) { std::fprintf(stderr, "strata serve: %s\n", err.c_str()); return 1; } + if (prefill_head_alias_bound) mtp.set_window_R(ver.final_R_all()); if (pipe) mtp.set_source_R(ver.final_R_all()); // the serial decode's rows (the last stage's even verifier) auto free_slot_mtp_rows = [](float* p) { if (p != nullptr) (void) cudaFree(p); }; std::vector> slot_mtp_rows; @@ -10515,6 +10571,17 @@ int main(int argc, char** argv) { std::printf("ERR %s\n", err.c_str()); return 1; } + if (o.prefill_head_alias && native_head.loaded()) { + const auto head_t0 = Clock::now(); + native_head.unload(); + sp.reset(); + if (init_prompt_paths() != 0) { + std::printf("ERR rebuilding the head-alias prompt path failed: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata serve: --prefill-head-alias: prompt workspace rebuilt in %.1f ms\n", + std::chrono::duration(Clock::now() - head_t0).count()); + } auto kv_quiesce = [&] { cudaDeviceSynchronize(); apply_pending(true); }; if (kvg.on) { // the elastic K/V: this prompt's cells (it gives back what it does not need below) // a failed growth may leave the tier half-changed: the engine stops (as for any CUDA failure) @@ -11082,8 +11149,9 @@ int main(int argc, char** argv) { // prompt needs, so a large chunk costs a short prompt nothing const int64_t want_full = equal_chunk(tokens, o.prefill_chunk); // #340: a short enough request reads in the stages' own S-token chunks (nothing lent) - const int64_t want = split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small) - : want_full; + const int64_t want = o.prefill_head_alias ? o.prefill_chunk + : split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small) + : want_full; if (want <= 0) { e = "prefill: cannot lend buffers for an empty request segment"; return false; @@ -11099,30 +11167,34 @@ int main(int argc, char** argv) { if (!refill_one(p, e)) return false; } const strata::core::OnDevice on(p.dev); - // #2090: the loan a chunk needs is NOT monotonic in the chunk: a chunk above the scan's small_max - // lays out the byte-budget ring (199 slots at 5120), one at or below it 0.1.39's (384 at 4096), so - // a request's smaller chunk can need MORE slots than the auto chunk's region (p.first) holds. The - // loan starts where the chunk itself needs it (the 128-slot floor aside); a chunk that cannot be - // lent even then is halved until it can, instead of ending the engine. int64_t want_p = want; - int64_t need_p = part_slots(p, want_p); - while ((need_p <= 0 || need_p + 128 > p.cache->slots()) && want_p > 256) { - want_p = std::max(256, want_p / 2 / 256 * 256); - need_p = part_slots(p, want_p); + int32_t first = p.first_now; + // --prefill-head-alias: the loan laid out at start (slot 1 on) is kept; a hybrid layout cannot relayout + if (!o.prefill_head_alias) { + // #2090: the loan a chunk needs is NOT monotonic in the chunk: a chunk above the scan's small_max + // lays out the byte-budget ring (199 slots at 5120), one at or below it 0.1.39's (384 at 4096), so + // a request's smaller chunk can need MORE slots than the auto chunk's region (p.first) holds. The + // loan starts where the chunk itself needs it (the 128-slot floor aside); a chunk that cannot be + // lent even then is halved until it can, instead of ending the engine. + int64_t need_p = part_slots(p, want_p); + while ((need_p <= 0 || need_p + 128 > p.cache->slots()) && want_p > 256) { + want_p = std::max(256, want_p / 2 / 256 * 256); + need_p = part_slots(p, want_p); + } + if (need_p <= 0 || need_p + 128 > p.cache->slots()) { + e = "prefill: no chunk of this request fits the slots that can be lent (#2090)"; + return false; + } + if (want_p != want) + std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens for this request: its " + "buffers do not fit the slots that can be lent (#2090)\n", (long long) want, + (long long) want_p); + if (need_p > p.cache->slots() - p.first) // the case that ended the engine before (#2090) + std::fprintf(stderr, "strata serve: the loan for a chunk of %lld tokens (%lld slots) is larger than the " + "auto chunk's (%lld slots): starting it earlier (#2090)\n", (long long) want_p, + (long long) need_p, (long long) (p.cache->slots() - p.first)); + first = (int32_t) (p.cache->slots() - need_p); } - if (need_p <= 0 || need_p + 128 > p.cache->slots()) { - e = "prefill: no chunk of this request fits the slots that can be lent (#2090)"; - return false; - } - if (want_p != want) - std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens for this request: its " - "buffers do not fit the slots that can be lent (#2090)\n", (long long) want, - (long long) want_p); - if (need_p > p.cache->slots() - p.first) // the case that ended the engine before (#2090) - std::fprintf(stderr, "strata serve: the loan for a chunk of %lld tokens (%lld slots) is larger than the " - "auto chunk's (%lld slots): starting it earlier (#2090)\n", (long long) want_p, - (long long) need_p, (long long) (p.cache->slots() - p.first)); - const int32_t first = (int32_t) (p.cache->slots() - need_p); if (want_p != p.sp->chunk() || first != p.first_now) { if (!p.sp->relayout(want_p, p.cache->device_slot(first), part_bytes(p, first), e)) return false; p.first_now = first; @@ -11421,6 +11493,23 @@ int main(int argc, char** argv) { std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); return 1; } + if (o.prefill_head_alias) { + sp.reset(); + const auto head_t0 = Clock::now(); + if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) { + std::printf("ERR restoring the native output head failed: %s\n", err.c_str()); + return 1; + } + // the verify windows' captured graphs read the head at the address of their capture + if (prefill_head_alias_at == nullptr) prefill_head_alias_at = native_head.weights(); + if (native_head.weights() != prefill_head_alias_at) { + std::printf("ERR --prefill-head-alias: the output head was reloaded at another address, so the " + "captured verify graphs would read freed memory\n"); + return 1; + } + std::fprintf(stderr, "strata serve: --prefill-head-alias: output head restored in %.1f ms before decode\n", + std::chrono::duration(Clock::now() - head_t0).count()); + } tr("prompt done (slots refilled)"); if (il_parts > 0) std::fprintf(stderr, "strata batch: the prompt was read in %lld parts, the slots decoding %.0f ms between " diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp index bebb039f..8b0b3892 100644 --- a/sycl/src/prefill/prefill.cpp +++ b/sycl/src/prefill/prefill.cpp @@ -930,7 +930,11 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g, core::SessionState &ss, core::ExpertSource *src, const core::ExpertCache *cache, const int32_t *host_res, int64_t chunk, void *stream, std::string &err, void *borrow, - uint64_t borrow_bytes) try { + uint64_t borrow_bytes, bool borrow_spill) try { + if (borrow_spill) { + err = "prefill: a hybrid borrowed/owned layout (--prefill-head-alias) is not in the SYCL port"; + return false; + } Impl& m = *impl_; m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res; m.T = chunk; m.cs = strata::q_of(stream); m.stats = &stats_;