From 8f1703c7e0f26643f8bc620f40af2ab0be22c178 Mon Sep 17 00:00:00 2001 From: Sarah Date: Sun, 6 Dec 2026 08:57:06 +0100 Subject: [PATCH 1/2] [Engine] qwen4: opt-in --ple-direct: the PLE table's rows from disk, and the VRAM reserve does not count them --ple-direct (off by default, CUDA and HIP) reads the PLE n-gram table's rows straight from disk through strata::ngram::PleReader, the Direct reader the Flash Next engine uses for its own PLE, in place of the host map of shard 2: unbuffered reads, a 1M-row (~100 MB) row cache, the SSD keep-alive, one issue a step over its whole row set, collected in begin_step()'s PLE slot and dequantized from pinned raw rows into h_ple_emb_. The reader is PR #440's (closed); here it is opt-in, since it read prompts about 3.4 times slower than the map on a Windows PC with a PCIe 3.0 SSD (PR #440's report). A file the reader cannot open falls back to the map. Not on Metal: there the map is kept (the reader is not compiled in), as its gathers need no copy. With the reader open the table needs no page cache, so fill_expert_cache() no longer counts it among the files whose page cache its tight-RAM test keeps room for (Engine::direct_file_bytes(), default 0; Qwen4 returns the table's bytes only while the reader is open). Before, a 30 GB PC with UD-IQ4_XS (20.5 + 11.5 GB of files) got the doubled reserve. Without --ple-direct nothing changes: the table is mapped and direct_file_bytes() is 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018j62UGHq9crCFFy7fHrCcW --- docs/models/qwen4.md | 7 +++++ engine/src/poly/engine.cpp | 4 ++- engine/src/poly/engine.hpp | 6 ++++ engine/src/poly/main.cpp | 4 +++ engine/src/poly/qwen4.cpp | 60 ++++++++++++++++++++++++++++++++++++-- engine/src/poly/qwen4.hpp | 15 ++++++++-- 6 files changed, 90 insertions(+), 6 deletions(-) diff --git a/docs/models/qwen4.md b/docs/models/qwen4.md index 0f6ab6d91..2d19b0425 100644 --- a/docs/models/qwen4.md +++ b/docs/models/qwen4.md @@ -56,6 +56,13 @@ All downloads come from [unsloth/Qwen4-35B-A3B-GGUF](https://huggingface.co/unsl and embedded MTP weights, and shard 2 holds the PLE n-gram table (shared by hardlink across tiers that use the same PLE table). `strata-poly` opens shard 1 via `--model` and maps shard 2 automatically. +`--ple-direct` (opt-in, CUDA and HIP) reads the table's rows straight from disk instead of the map: the same Direct +n-gram row reader the Flash Next engine uses for its own PLE (unbuffered reads, a ~100 MB row cache, an SSD +keep-alive), so the table's bytes stay out of RAM and the VRAM reserve no longer counts them as files that need page +cache. A prompt's rows then come from the SSD while it is read: on a Windows PC with a PCIe 3.0 SSD prompts were read +about 3.4 times slower than with the map (PR #440's report), so it is not the default. Apple Silicon always keeps the +map (its gathers need no copy at all). + | Size | Download (GB) | Routed experts (GB) | Dense weights (GB) | PLE table (GB) | Estimated RAM floor (GB) | | --- | ---: | ---: | ---: | ---: | ---: | | **UD-IQ2_XS** | 24.5 | 10.18 | 2.27 | 11.52 (IQ4_NL) | 16 | diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 0da6fe0bf..8637ad913 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -2879,7 +2879,9 @@ void Engine::fill_expert_cache() { if (!opt_.gpu_experts || n_moe_ == 0) return; size_t free_b = 0, total_b = 0; ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo"); - const size_t ram = ram_available(), files = gg_->bytes() + (dg_ ? dg_->bytes() : 0); + // (not what the architecture reads from its file with no page cache, direct_file_bytes(): it takes no RAM) + const size_t all_files = gg_->bytes() + (dg_ ? dg_->bytes() : 0); + const size_t ram = ram_available(), files = all_files - std::min(all_files, direct_file_bytes()); ram_tight_ = ram > 0 && files + (5ULL << 30) > ram; // 256 MiB at least, whatever was asked: the launches recorded later take theirs out of the reserve (mind_vram()) reserve_mib_ = opt_.vram_reserve_mib >= 0 ? std::max(opt_.vram_reserve_mib, 256) : diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index 546ea67f4..445da74e9 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -130,6 +130,9 @@ struct Options { std::string basinkv_kv_quant = "int8"; ///< BasinKV pinned host KV format: "int8" or "wht_int4" (--basinkv-kv-quant) float basinkv_alpha = -1.f; ///< BasinKV Quest shrunk-box radius weight in [0, 1]; < 0: auto (0.25 if D>=256 else 1.0) float basinkv_beta = 0.10f; ///< BasinKV SphereIndex subspace radius weight beta >= 0 (--basinkv-beta) + bool ple_direct = false; ///< --ple-direct (opt-in, not Metal): a qwen4exp PLE n-gram table read row by row from + ///< disk through the Direct row reader (the Flash Next engine's own); by default the + ///< table is mapped on host, as before bool freeze_experts = false; ///< the experts' split held still for the whole run, as STRATA_FREEZE_EXPERTS=1 #if defined(STRATA_GPU_METAL) KvFmt kv_format = KvFmt::kAuto; ///< Q8 for compatible Qwen35MoE geometry, otherwise fp16 @@ -699,6 +702,9 @@ class Engine { /// A token's experts outside VRAM may go to the host's threads through the doorbell (h_bell_): the architecture /// routes on the card (route_card()) and sums a token's experts in moe_card() when moe_sum_later() is false. virtual bool bells() const { return false; } + /// Bytes of the model's files the architecture reads straight from disk, with no page cache (Qwen4's PLE n-gram + /// table through the Direct reader): they are not RAM the files need, which fill_expert_cache()'s reserve counts. + virtual size_t direct_file_bytes() const { return 0; } /// follow(): the tokens over which an expert's recent uses halve (kSwapHalf for every family but Inkling 2). virtual int swap_half() const; /// Options::expert_swaps when it is not given (-1): the uploads on their way into the cache at a time. diff --git a/engine/src/poly/main.cpp b/engine/src/poly/main.cpp index ffd84f260..425dcd33e 100644 --- a/engine/src/poly/main.cpp +++ b/engine/src/poly/main.cpp @@ -2208,6 +2208,9 @@ void usage() { " --basinkv-alpha F BasinKV Quest shrunk-box radius weight in [0, 1] (default -1 = auto:\n" " 0.25 for head_dim >= 256, 1.0 below)\n" " --basinkv-beta F BasinKV SphereIndex subspace radius weight >= 0 (default 0.10)\n" + " --ple-direct opt-in: read a qwen4exp PLE n-gram table's rows straight from disk through the\n" + " Direct n-gram row reader the Flash Next engine uses (unbuffered reads, a ~100 MB\n" + " row cache, SSD keep-alive) in place of a host map of its file; not on Metal\n" " --kv fmt the K and V attention caches' format, opt-in: fp16 (default,\n" " unchanged); q8_0 (ggml Q8_0 blocks: half the KV VRAM, slightly\n" " different answers; qwen35moe's, kolibri1's, Flint's and Inkling 2's,\n" @@ -2454,6 +2457,7 @@ int main(int argc, char** argv) { } o.basinkv_beta = x; } + else if (a == "--ple-direct") o.ple_direct = true; else if (a == "--kv") { const std::string fmt = val(); if (fmt == "fp16") o.kv_format = KvFmt::kFp16; diff --git a/engine/src/poly/qwen4.cpp b/engine/src/poly/qwen4.cpp index 73fb10286..434b4896a 100644 --- a/engine/src/poly/qwen4.cpp +++ b/engine/src/poly/qwen4.cpp @@ -79,6 +79,16 @@ Qwen4::~Qwen4() { stop_ple_warmer(); if (bell_pending_) bell_unwind(); if (st_) cudaStreamSynchronize(cs(st_)); +#if !defined(STRATA_GPU_METAL) + if (ple_reader_ && ple_reader_->is_open()) { // the n-gram reads, reported the way Flash Next reports its own + const auto s = ple_reader_->snapshot(); + std::fprintf(stderr, + "strata-poly: qwen4: PLE table: %llu rows asked, %llu from the row cache, %llu SSD reads of " + "%llu bytes, collect waited %.1f ms\n", + (unsigned long long) s.requests, (unsigned long long) s.cache_hits, (unsigned long long) s.reads, + (unsigned long long) s.bytes, s.wait_us / 1000.0); + } +#endif #if !defined(STRATA_GPU_METAL) && !defined(STRATA_USE_HIP) if (prev_b6_rows_ >= 0) kernels::native_mmvq_set_b6_rows(prev_b6_rows_); #endif @@ -237,16 +247,20 @@ void Qwen4::load_geometry() { need(ple_vocab_sizes_[(size_t) i] > 0, "zero ple.head_vocab_sizes entry"); } - // Keep the 11+ GB PLE table mmap'd on host; never upload to VRAM. + // The 11+ GB PLE table never goes to VRAM; it is mapped on host. With --ple-direct (opt-in) its rows come + // straight off the disk through the same Direct n-gram row reader the Flash Next engine uses for its own + // PLE: unbuffered reads, a ~100 MB row cache, a keep-alive for the SSD - a few tens of MB of host RAM for a + // 150M-row table instead of paging a full map. A reader that cannot open the file falls back to the map. const TensorInfo* pt = gg_->find("per_layer_token_embd.weight"); need(pt != nullptr && pt->shape.size() == 2 && (int) pt->shape[0] == ple_head_dim_, "missing or bad per_layer_token_embd.weight"); ple_type_ = pt->type; ple_table_rows_ = pt->shape[1]; - ple_table_ = gg_->data(*pt); + const uint8_t* table_bytes = gg_->data(*pt); const size_t payload = gg_->payload(*pt); need(ple_table_rows_ > 0 && payload % ple_table_rows_ == 0, "bad per_layer_token_embd payload"); ple_row_bytes_ = payload / (size_t) ple_table_rows_; + ple_table_bytes_ = payload; need(ple_type_ == kTypeF32 || type_converts(ple_type_), "unsupported per_layer_token_embd type"); if (ple_type_ != kTypeF32 && ple_type_ != kTypeF16 && ple_type_ != kTypeBF16) { const int bv = type_block_values(ple_type_); @@ -255,6 +269,28 @@ void Qwen4::load_geometry() { for (int i = 0; i < ple_n_heads_; ++i) need(ple_offsets_[(size_t) i] + ple_vocab_sizes_[(size_t) i] <= ple_table_rows_, "ple head offset + vocab_size exceeds per_layer_token_embd rows"); +#if !defined(STRATA_GPU_METAL) + // Metal keeps the map: its unified-memory path writes small gathers into ple_emb_'s host view with no + // copy at all, and there the map costs nothing extra. Everywhere else the reader's own reads replace it. + if (opt_.ple_direct) { + const auto [file, off] = gg_->place(table_bytes); + if (file >= 0) { + ple_reader_ = std::make_unique(); + std::string err; + if (ple_reader_->open(gg_->paths()[(size_t) file], (uint64_t) off, ple_table_rows_, 256, 1u << 20, + err, true, (uint32_t) ple_row_bytes_)) { + ple_reader_->set_keepalive(100.0, 60.0); // the Flash Next serve's own defaults + ple_direct_ = true; + } else { + std::fprintf(stderr, "strata-poly: qwen4: the direct PLE table reader would not open (%s); " + "mapping the table instead\n", + err.c_str()); + ple_reader_.reset(); + } + } + } +#endif + if (!ple_direct_) ple_table_ = table_bytes; has_ple_ = true; } @@ -793,6 +829,9 @@ void Qwen4::alloc_caches() { for (auto& rg : ple_ring_) rg.fill(ple_eos_); ple_idx_.resize((size_t) rows_ * (size_t) ple_n_heads_); h_ple_emb_ = (float*) hmalloc((size_t) rows_ * (size_t) ple_dim_ * sizeof(float), "pinned PLE embeddings"); + if (ple_direct_) + h_ple_raw_ = (uint8_t*) hmalloc((size_t) rows_ * (size_t) ple_n_heads_ * ple_row_bytes_, + "pinned PLE table rows"); cudaStream_t pst = nullptr; ck(cudaStreamCreateWithFlags(&pst, cudaStreamNonBlocking), "ple_stream"); ple_stream_ = pst; @@ -1284,11 +1323,26 @@ void Qwen4::prepare_ple(const int32_t* tokens, int n, bool async_stream, bool di float* direct_dst = nullptr; #endif float* emb_dst = direct_dst ? direct_dst : h_ple_emb_; +#if !defined(STRATA_GPU_METAL) + if (ple_direct_) { + // the whole step's rows at once: the reader dedupes them, sorts them by page and runs its reads on its + // io thread, and collect blocks only for the ones the disk still owes - the same issue/collect pair the + // Flash Next engine runs for its own n-gram PLE, over the same table layout + std::vector asked((size_t) n * (size_t) ple_n_heads_); + for (size_t i = 0; i < asked.size(); ++i) asked[i] = (uint32_t) ple_idx_[i]; + const strata::ngram::PleReader::Ticket tk = ple_reader_->issue(asked.data(), asked.size(), h_ple_raw_); + std::string err; + if (!ple_reader_->collect(tk, err)) + throw std::runtime_error("qwen4: the direct PLE table read failed: " + err); + } +#endif auto dequant_tok = [&](int t) { const int64_t* idx = ple_idx_.data() + (size_t) t * (size_t) ple_n_heads_; float* dst = emb_dst + (size_t) t * (size_t) ple_dim_; for (int h = 0; h < ple_n_heads_; ++h) { - const uint8_t* src = ple_table_ + (size_t) idx[h] * ple_row_bytes_; + const uint8_t* src = ple_direct_ + ? h_ple_raw_ + ((size_t) t * (size_t) ple_n_heads_ + (size_t) h) * ple_row_bytes_ + : ple_table_ + (size_t) idx[h] * ple_row_bytes_; type_to_floats(ple_type_, src, dst + (size_t) h * (size_t) ple_head_dim_, ple_head_dim_); } }; diff --git a/engine/src/poly/qwen4.hpp b/engine/src/poly/qwen4.hpp index 29d597b42..fb1273847 100644 --- a/engine/src/poly/qwen4.hpp +++ b/engine/src/poly/qwen4.hpp @@ -3,7 +3,8 @@ // Hyper-connections (hc parallel residual streams, default 4) with gated residual read/write around every token mixer // and MoE FFN, and a final output_hc_* mixer in place of output_norm. Hybrid layers: 3/4 Gated Delta Net (sigmoid // output gate) + 1/4 Query-Sparse Attention (QSA, block-4 mean-pooled indexer selecting top-512 blocks + tail). -// Optional Per-Layer Embedding (PLE) n-gram engram on blk.1 (table stays mmap'd on host; lookup + H2D prefetched in +// Optional Per-Layer Embedding (PLE) n-gram engram on blk.1 (table mapped on host, or with --ple-direct its rows read +// straight from disk through the Direct n-gram row reader with a ~100 MB row cache; lookup + H2D prefetched in // begin_step() before blk.0). Optional 1-layer 4-stream MTP draft block (blk.40) reading raw trunk residual. #pragma once @@ -12,6 +13,9 @@ #include "engine.hpp" #include "gdn_mma_control.hpp" #include "qwen4_loop.hpp" +#if !defined(STRATA_GPU_METAL) +#include "strata/ngram/ple_reader.hpp" +#endif #include #include @@ -93,6 +97,7 @@ class Qwen4 final : public Engine { void output_rows(int first, int rows, float* h) override; void route(int il, const float* logits, int32_t token, int* ids, float* w, float* tmp) const override; bool route_card(int il, int n, int32_t* ids, float* w) override; + size_t direct_file_bytes() const override { return ple_direct_ ? ple_table_bytes_ : 0; } bool moe_sum_later(int n) const override { #if defined(STRATA_GPU_METAL) (void) n; @@ -315,10 +320,16 @@ class Qwen4 final : public Engine { int ple_conv_k_ = 4, ple_dil_ = 3, ple_hist_len_ = 9; int32_t ple_eos_ = 0, ple_img_ = 0; std::vector ple_mult_, ple_offsets_, ple_vocab_sizes_; - const uint8_t* ple_table_ = nullptr; + const uint8_t* ple_table_ = nullptr; ///< the mapped table, only when the rows are not read from disk uint32_t ple_type_ = 0; size_t ple_row_bytes_ = 0; uint64_t ple_table_rows_ = 0; + size_t ple_table_bytes_ = 0; ///< the table's bytes in its file +#if !defined(STRATA_GPU_METAL) + std::unique_ptr ple_reader_; ///< rows straight from disk (--ple-direct); null when mapped +#endif + uint8_t* h_ple_raw_ = nullptr; ///< pinned [rows_, ple_n_heads_ * ple_row_bytes_] of rows the reader collected + bool ple_direct_ = false; ///< the reader is open; ple_table_ stays null with it std::vector> ple_ring_; std::vector ple_idx_; float* h_ple_emb_ = nullptr; ///< pinned [rows_, ple_dim_] From eeadc989716e979ec92a540174c1d642409a9531 Mon Sep 17 00:00:00 2001 From: Sarah Date: Sun, 6 Dec 2026 08:58:15 +0100 Subject: [PATCH 2/2] [Engine] qwen4: with --ple-direct, read PLE rows ahead: a decode window's while its guesses are drafted, a prompt's while its first layers run With the opt-in Direct PLE reader (--ple-direct) each verify window waited for its tokens' n-gram rows (16 a token) before its first layer: prepare_ple() issued them in begin_step() and blocked in collect(). Now: - decode: the window's tokens are known one by one while the MTP block drafts them, so draft_step() asks the reader for each token's rows as soon as the token is known (ple_read_ahead()); the window's own read in prepare_ple() first waits for them (ple_drain_ahead()) and then takes them from the row cache. The last guess is read with the window. - prompt: read() hands an architecture all of a read's tokens before the first call (Engine::read_begins(), one sequence, no co-reads). Qwen4 hashes them as prepare_ple() does and asks for their rows in chunks of 1,024 tokens, up to 4,096 tokens ahead of the call being read (ple_prompt_issue()); each call waits for the chunks that start before its end (ple_prompt_drain()) and asks for the next ones. The same rows and sums; only when the reads happen changes. STRATA_QWEN4_PLE_AHEAD=0 turns both off. Without --ple-direct, and on Metal (no reader there), nothing changes. RTX 4060 Laptop 8 GB, i9-12900H, RS1D0TSSD710, UD-IQ4_XS, --kv q8_0, with the reader: decode, 33-token prompt, 500 tokens, 6 interleaved runs, 86.05 +- 1.00 tokens/s against 82.88 +- 2.86 off, the reader's collect wait 68 against 203 ms a run; frozen experts, 2,048-token prompt 1,031.1 against 987.2 tokens/s, 6,000 tokens 1,138.7 against 1,088.7, the same tokens. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018j62UGHq9crCFFy7fHrCcW --- docs/SETTINGS.md | 3 +- docs/models/qwen4.md | 7 ++ engine/src/poly/engine.cpp | 1 + engine/src/poly/engine.hpp | 3 + engine/src/poly/qwen4.cpp | 129 +++++++++++++++++++++++++++ engine/src/poly/qwen4.hpp | 34 +++++++ terminal/data/settings-register.json | 30 +++++++ 7 files changed, 206 insertions(+), 1 deletion(-) diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index 74a529334..1c2747ead 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -386,7 +386,7 @@ Off unless you set them. The last column says where each one is described. | `STRATA_WDDM_BUDGET` | number | AMD, Intel Arc | [AMD_HIP.md](AMD_HIP.md) | | `STRATA_WDDM_MARGIN_MIB` | number | AMD | [AMD_HIP.md](AMD_HIP.md) | -## Switches that go back to earlier behaviour (137) +## Switches that go back to earlier behaviour (138) These behaviours are on by default. Setting the switch returns the earlier behaviour; the notes in the register say which version made it the default. @@ -497,6 +497,7 @@ version made it the default. | `STRATA_QUANT_NVFP4_X4` | on / off | NVIDIA and AMD | - | [inkling.md](models/inkling.md) | | `STRATA_QUANT_ROWS4` | on / off | NVIDIA and AMD | - | - | | `STRATA_QWEN4_KERNEL_TABLES` | on / off | NVIDIA | - | [qwen4.md](models/qwen4.md) | +| `STRATA_QWEN4_PLE_AHEAD` | on / off | NVIDIA and AMD | - | [qwen4.md](models/qwen4.md) | | `STRATA_RDNA_KQ_ALL` | on / off | NVIDIA and AMD | v0.2.19 | - | | `STRATA_REMOTE_SPIN` | on / off | NVIDIA, AMD, Intel Arc | v0.2.16 | - | | `STRATA_RESIDENT_PIN` | on / off | NVIDIA and AMD, Intel Arc | v0.2.16 | [DETAILS.md](DETAILS.md), [TROUBLESHOOTING.md](TROUBLESHOOTING.md), [UNSLOTH_Q4.md](UNSLOTH_Q4.md) | diff --git a/docs/models/qwen4.md b/docs/models/qwen4.md index 2d19b0425..b96ee3f51 100644 --- a/docs/models/qwen4.md +++ b/docs/models/qwen4.md @@ -63,6 +63,13 @@ cache. A prompt's rows then come from the SSD while it is read: on a Windows PC about 3.4 times slower than with the map (PR #440's report), so it is not the default. Apple Silicon always keeps the map (its gathers need no copy at all). +With `--ple-direct` the reader also reads ahead (`STRATA_QWEN4_PLE_AHEAD=0` turns it off): a verify window's rows are +asked for while its guesses are drafted, and a prompt's rows in chunks of 1,024 tokens up to 4,096 tokens ahead of the +call being read. On an RTX 4060 Laptop 8 GB with an RS1D0TSSD710 SSD and UD-IQ4_XS, `--kv q8_0`, decode went from +82.88 ± 2.86 to 86.05 ± 1.00 tokens/s (6 interleaved runs, 500 tokens) and a 6,000-token prompt from 1,088.7 to +1,138.7 tokens/s (frozen experts), the same tokens. The reader's reads run on `STRATA_IO_THREADS` threads (16 by +default on Linux); 64 read a long prompt at 1,012.8 tokens/s against 977.8 with 16 on that SSD. + | Size | Download (GB) | Routed experts (GB) | Dense weights (GB) | PLE table (GB) | Estimated RAM floor (GB) | | --- | ---: | ---: | ---: | ---: | ---: | | **UD-IQ2_XS** | 24.5 | 10.18 | 2.27 | 11.52 (IQ4_NL) | 16 | diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 8637ad913..a41df1957 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -11093,6 +11093,7 @@ bool Engine::read(const int32_t* tokens, int n, const Mark* marks, int n_marks, } hold(lead); cover(pos_ + n); + if (n_co == 0) read_begins(tokens, n); // On several cards, each reads through its own layers and hands the rows on, and `turn` hears of a card's // turns as its share of the model's layers: [lo_, to). const std::function* asked = turn; diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index 445da74e9..630ea64fe 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -650,6 +650,9 @@ class Engine { virtual void reset_call() {} /// Optional host hook called in run() and step() after r_ (and at_) upload, before any layer or CUDA Graph launch. virtual void begin_step(const int32_t* tokens, int n) { (void) tokens; (void) n; } + /// A read's tokens, all of them, before its first call (read(), one sequence at pos_): an architecture may start + /// fetching what the calls will need of them. + virtual void read_begins(const int32_t* tokens, int n) { (void) tokens; (void) n; } /// Optional hook called by copy_seq() to duplicate any architecture-private per-sequence host state. virtual void on_copy_seq(int from, int to) { (void) from; (void) to; } /// Optional architecture lifecycle hooks (no-op by default; used by opt-in BasinKV). diff --git a/engine/src/poly/qwen4.cpp b/engine/src/poly/qwen4.cpp index 434b4896a..cae165d5e 100644 --- a/engine/src/poly/qwen4.cpp +++ b/engine/src/poly/qwen4.cpp @@ -80,6 +80,11 @@ Qwen4::~Qwen4() { if (bell_pending_) bell_unwind(); if (st_) cudaStreamSynchronize(cs(st_)); #if !defined(STRATA_GPU_METAL) + try { + ple_drain_ahead(); // the reads' landing places go before the reader + if (ple_reader_) ple_prompt_drain(INT64_MAX); + } catch (...) { + } if (ple_reader_ && ple_reader_->is_open()) { // the n-gram reads, reported the way Flash Next reports its own const auto s = ple_reader_->snapshot(); std::fprintf(stderr, @@ -281,6 +286,10 @@ void Qwen4::load_geometry() { err, true, (uint32_t) ple_row_bytes_)) { ple_reader_->set_keepalive(100.0, 60.0); // the Flash Next serve's own defaults ple_direct_ = true; + const char* ahead = std::getenv("STRATA_QWEN4_PLE_AHEAD"); + ple_ahead_ = !(ahead && ahead[0] == '0'); + if (ple_ahead_) + ple_ahead_raw_.resize((size_t) kPleAhead * (size_t) ple_n_heads_ * ple_row_bytes_); } else { std::fprintf(stderr, "strata-poly: qwen4: the direct PLE table reader would not open (%s); " "mapping the table instead\n", @@ -1328,6 +1337,13 @@ void Qwen4::prepare_ple(const int32_t* tokens, int n, bool async_stream, bool di // the whole step's rows at once: the reader dedupes them, sorts them by page and runs its reads on its // io thread, and collect blocks only for the ones the disk still owes - the same issue/collect pair the // Flash Next engine runs for its own n-gram PLE, over the same table layout + ple_drain_ahead(); // the rows read ahead are in the row cache now + if (!ple_pr_.empty() || ple_pr_next_ < ple_pr_pos0_ + (int64_t) ple_pr_tok_.size()) { // a prompt's (read_begins()) + ple_prompt_drain(pos_ + n); + const int64_t pr_end = ple_pr_pos0_ + (int64_t) ple_pr_tok_.size(); + if (pos_ >= ple_pr_pos0_ && pos_ < pr_end) ple_prompt_issue(pos_ + n + kPleAheadToks); + if (ple_pr_.empty() && ple_pr_next_ >= pr_end) ple_pr_tok_.clear(); // the read's rows are all in + } std::vector asked((size_t) n * (size_t) ple_n_heads_); for (size_t i = 0; i < asked.size(); ++i) asked[i] = (uint32_t) ple_idx_[i]; const strata::ngram::PleReader::Ticket tk = ple_reader_->issue(asked.data(), asked.size(), h_ple_raw_); @@ -1374,6 +1390,116 @@ void Qwen4::prepare_ple(const int32_t* tokens, int n, bool async_stream, bool di } } +#if !defined(STRATA_GPU_METAL) // the --ple-direct reader's read-ahead (the reader is not on Metal) +void Qwen4::ple_read_ahead(int32_t token, int64_t pos) { + if (!ple_direct_ || !ple_ahead_ || rows_of_ || ple_ahead_raw_.empty()) return; + const int i = (int) (pos - pos_); + if (i == 0) { // a new window: whatever the last round asked for has been taken or is not wanted + ple_drain_ahead(); + ple_ahead_next_ = 0; + } + // the window's tokens in order, from its first: the rows of each need the two before it + if (i != ple_ahead_next_ || ple_ahead_n_ >= kPleAhead) return; + const int32_t cur = image_at(pos) ? ple_img_ : token; + ple_ahead_tok_[i] = cur; + ++ple_ahead_next_; + // prepare_ple()'s hash of a token, its earlier tokens from the window read ahead so far and then the ring + const auto& rg = ple_ring_[(size_t) bound_]; + int64_t ctx[8]; + ctx[0] = (int64_t) cur; + bool cut = false; + for (int s = 1; s < ple_ngram_; ++s) { + const int64_t pp = pos - s; + int32_t pt = -1; + if (pp >= pos_) pt = ple_ahead_tok_[(size_t) (pp - pos_)]; + else if (pp >= 0) pt = rg[(size_t) (pp & (kPleRing - 1))]; + pt = cut ? -1 : pt; + cut = cut || pt < 0 || pt == ple_eos_; + ctx[s] = cut ? (int64_t) ple_eos_ : (int64_t) pt; + } + uint32_t asked[64]; + if (ple_n_heads_ > 64) return; + for (int ng = 2; ng <= ple_ngram_; ++ng) { + uint64_t mixed = (uint64_t) ctx[0] * ple_mult_[0]; + for (int j = 1; j < ng; ++j) mixed ^= (uint64_t) ctx[j] * ple_mult_[(size_t) j]; + const int base = (ng - 2) * ple_per_gram_; + for (int g = 0; g < ple_per_gram_; ++g) { + const int h = base + g; + asked[h] = (uint32_t) (mixed % ple_vocab_sizes_[(size_t) h] + ple_offsets_[(size_t) h]); + } + } + uint8_t* land = ple_ahead_raw_.data() + (size_t) ple_ahead_n_ * (size_t) ple_n_heads_ * ple_row_bytes_; + ple_ahead_tk_[ple_ahead_n_++] = ple_reader_->issue(asked, (size_t) ple_n_heads_, land); +} + +// A prompt read's rows: read() hands over all its tokens before the first call, and the reader fetches them in +// chunks while the first layers run; each call's prepare_ple() waits for the chunks it needs and finds the rows in the +// row cache. Only with the Direct reader and one sequence (read() has no co-reads then). + +void Qwen4::read_begins(const int32_t* tokens, int n) { + if (!ple_direct_ || !ple_ahead_ || !has_ple_ || !runs(ple_layer_) || n < 2) return; + ple_prompt_drain(INT64_MAX); + ple_pr_tok_.resize((size_t) n); + for (int t = 0; t < n; ++t) ple_pr_tok_[(size_t) t] = image_at(pos_ + t) ? ple_img_ : tokens[t]; + ple_pr_pos0_ = ple_pr_next_ = pos_; + ple_prompt_issue(pos_ + std::min(n, kPleAheadToks)); +} + +void Qwen4::ple_prompt_issue(int64_t to) { + const int64_t end = std::min(to, ple_pr_pos0_ + (int64_t) ple_pr_tok_.size()); + const auto& rg = ple_ring_[(size_t) bound_]; + std::vector asked; + while (ple_pr_next_ < end) { + const int64_t p0 = ple_pr_next_; + const int m = (int) std::min(kPleChunk, end - p0); + asked.resize((size_t) m * (size_t) ple_n_heads_); + for (int t = 0; t < m; ++t) { // prepare_ple()'s hash, the earlier tokens from the read and then the ring + const int64_t p = p0 + t; + int64_t ctx[8]; + ctx[0] = (int64_t) ple_pr_tok_[(size_t) (p - ple_pr_pos0_)]; + bool cut = false; + for (int s = 1; s < ple_ngram_; ++s) { + const int64_t pp = p - s; + int32_t pt = -1; + if (pp >= ple_pr_pos0_) pt = ple_pr_tok_[(size_t) (pp - ple_pr_pos0_)]; + else if (pp >= 0) pt = rg[(size_t) (pp & (kPleRing - 1))]; + pt = cut ? -1 : pt; + cut = cut || pt < 0 || pt == ple_eos_; + ctx[s] = cut ? (int64_t) ple_eos_ : (int64_t) pt; + } + uint32_t* dst = asked.data() + (size_t) t * (size_t) ple_n_heads_; + for (int ng = 2; ng <= ple_ngram_; ++ng) { + uint64_t mixed = (uint64_t) ctx[0] * ple_mult_[0]; + for (int j = 1; j < ng; ++j) mixed ^= (uint64_t) ctx[j] * ple_mult_[(size_t) j]; + const int base = (ng - 2) * ple_per_gram_; + for (int g = 0; g < ple_per_gram_; ++g) { + const int h = base + g; + dst[h] = (uint32_t) (mixed % ple_vocab_sizes_[(size_t) h] + ple_offsets_[(size_t) h]); + } + } + } + PleChunk& c = ple_pr_.emplace_back(); + c.p0 = p0; + c.raw.resize(asked.size() * ple_row_bytes_); + c.tk = ple_reader_->issue(asked.data(), asked.size(), c.raw.data()); + ple_pr_next_ = p0 + m; + } +} + +void Qwen4::ple_prompt_drain(int64_t end) { + std::string err; // a failed read fails the reader: the call's own read reports it + size_t k = 0; + while (k < ple_pr_.size() && ple_pr_[k].p0 < end) (void) ple_reader_->collect(ple_pr_[k++].tk, err); + ple_pr_.erase(ple_pr_.begin(), ple_pr_.begin() + (ptrdiff_t) k); +} + +void Qwen4::ple_drain_ahead() { + std::string err; // a failed read fails the reader: the window's own read reports it + for (int k = 0; k < ple_ahead_n_; ++k) (void) ple_reader_->collect(ple_ahead_tk_[k], err); + ple_ahead_n_ = 0; +} +#endif + void Qwen4::ple(Block& B, int n) { if (!recording_) { if (ple_prepared_rows_ >= n) { @@ -3068,6 +3194,9 @@ void Qwen4::draft_step(int32_t token, int i) { Layer& L = layers_[(size_t) n_layer_]; Block& B = blocks_[(size_t) n_layer_]; float* own = hn_ + hc_dim_; +#if !defined(STRATA_GPU_METAL) + ple_read_ahead(token, pos_ + i); // the next window's rows of this token, read while the guesses are drafted +#endif draft_input_q4(&token, pos_ + i, i == 0 ? hn_ : own, 1, /*synced_metal=*/true); block_attend(pos_ + i, 1); gr_read_after_write(B.hc_ffn, r_, ao_, gr_inj_attn_, xn_, xq_, gr_inj_ffn_, 1); diff --git a/engine/src/poly/qwen4.hpp b/engine/src/poly/qwen4.hpp index fb1273847..118171e0c 100644 --- a/engine/src/poly/qwen4.hpp +++ b/engine/src/poly/qwen4.hpp @@ -82,6 +82,9 @@ class Qwen4 final : public Engine { int streams() const override { return hc_; } void reset_call() override; void begin_step(const int32_t* tokens, int n) override; +#if !defined(STRATA_GPU_METAL) + void read_begins(const int32_t* tokens, int n) override; // --ple-direct's prompt read-ahead; not on Metal +#endif void on_copy_seq(int from, int to) override; void layer_head(Layer& L, int il, int n) override; void layer_tail(Layer& L, int il, int n) override; @@ -258,6 +261,18 @@ class Qwen4 final : public Engine { void gr_finish(const GrWeights& w, bool q_first, float* out_mixed, void* out_xq, float* out_inj, int n); void prepare_ple(const int32_t* tokens, int n, bool async_stream, bool direct_metal = false); +#if !defined(STRATA_GPU_METAL) // the --ple-direct reader's read-ahead (the reader is not on Metal) + /// The direct PLE reader's rows of `token` at `pos`, the verify window's token at pos - pos_, asked for while + /// the guesses after it are drafted: the reads land in the reader's row cache, and the window's own read in + /// prepare_ple() takes them from there. Rows only; nothing the model computes changes. + void ple_read_ahead(int32_t token, int64_t pos); + /// Waits for the reads ple_read_ahead() asked for (before the window's own read, and before the reader closes). + void ple_drain_ahead(); + /// A prompt's rows read ahead (read_begins()): the chunks from ple_pr_next_ up to `to` (positions) asked for. + void ple_prompt_issue(int64_t to); + /// Waits for the prompt chunks that start before `end` (all of them: INT64_MAX). + void ple_prompt_drain(int64_t end); +#endif void ple(Block& B, int n); void gdn(Block& B, CacheSlot& S, int n); void attn(Block& B, CacheSlot& S, int il, int64_t pos, int n); @@ -329,6 +344,25 @@ class Qwen4 final : public Engine { std::unique_ptr ple_reader_; ///< rows straight from disk (--ple-direct); null when mapped #endif uint8_t* h_ple_raw_ = nullptr; ///< pinned [rows_, ple_n_heads_ * ple_row_bytes_] of rows the reader collected +#if !defined(STRATA_GPU_METAL) + static constexpr int kPleAhead = 8; ///< a window's tokens read ahead at most + std::vector ple_ahead_raw_; ///< kPleAhead tokens' rows, the reads' landing place + strata::ngram::PleReader::Ticket ple_ahead_tk_[kPleAhead]; ///< the reads ple_read_ahead() has out + int32_t ple_ahead_tok_[kPleAhead] = {}; ///< the window's tokens read ahead, from pos_ + int ple_ahead_n_ = 0; ///< tickets out + int ple_ahead_next_ = 0; ///< the window's next token to read ahead + bool ple_ahead_ = true; ///< STRATA_QWEN4_PLE_AHEAD=0: off + struct PleChunk { + int64_t p0 = 0; ///< its first position + strata::ngram::PleReader::Ticket tk; + std::vector raw; ///< the reads' landing place + }; + static constexpr int kPleChunk = 1024; ///< a prompt's tokens a chunk of reads (read_begins()) + static constexpr int kPleAheadToks = 4096; ///< a prompt's tokens asked for ahead of the call being read + std::vector ple_pr_; ///< a prompt's chunks asked for and not yet waited for + std::vector ple_pr_tok_; ///< the read's tokens (images as ple_img_), from ple_pr_pos0_ + int64_t ple_pr_pos0_ = 0, ple_pr_next_ = 0; ///< the read's first position, and the next one to ask for +#endif bool ple_direct_ = false; ///< the reader is open; ple_table_ stays null with it std::vector> ple_ring_; std::vector ple_idx_; diff --git a/terminal/data/settings-register.json b/terminal/data/settings-register.json index 71439bf66..d3c8374c8 100644 --- a/terminal/data/settings-register.json +++ b/terminal/data/settings-register.json @@ -42684,6 +42684,36 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_QWEN4_PLE_AHEAD", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/qwen4.cpp", + "line": 289, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "flag", + "default_state": "on", + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [ + "docs/models/qwen4.md:66" + ], + "status": "rollback", + "owner": "poly", + "note": "Qwen4 (qwen4exp) with the opt-in Direct PLE reader (--ple-direct; not Metal): rows are asked for before they are needed and land in the reader's row cache, where prepare_ple() then finds them. In decode, draft_step() asks for each verify-window token's rows while the MTP block drafts the guesses after it (ple_read_ahead()); in a prompt read, read_begins() asks for the prompt's rows in chunks of 1,024 tokens, up to 4,096 ahead of the call being read, while the first layers run. The same rows and sums. On with --ple-direct; =0 reads each step's rows when it starts, as before (engine/src/poly/qwen4.cpp)", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_RAM_ADAPT", "backends": [