Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/models/qwen4.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
4 changes: 3 additions & 1 deletion engine/src/poly/engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) :
Expand Down
6 changes: 6 additions & 0 deletions engine/src/poly/engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions engine/src/poly/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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;
Expand Down
60 changes: 57 additions & 3 deletions engine/src/poly/qwen4.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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_);
Expand All @@ -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<strata::ngram::PleReader>();
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;
}

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<uint32_t> 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_);
}
};
Expand Down
15 changes: 13 additions & 2 deletions engine/src/poly/qwen4.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 <array>
#include <atomic>
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<uint64_t> 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<strata::ngram::PleReader> 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<std::array<int32_t, kPleRing>> ple_ring_;
std::vector<int64_t> ple_idx_;
float* h_ple_emb_ = nullptr; ///< pinned [rows_, ple_dim_]
Expand Down