Skip to content
Closed
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
5 changes: 4 additions & 1 deletion docs/models/qwen4.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ Useful options:
All downloads come from [unsloth/Qwen4-35B-A3B-GGUF](https://huggingface.co/unsloth/Qwen4-35B-A3B-GGUF) pinned to commit
`742bc191ff171a5678cc369d5d82436612426e23` and checked by SHA-256. Each tier is a 2-shard GGUF: shard 1 holds the trunk
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.
table). `strata-poly` opens shard 1 via `--model` and reaches shard 2's table row by row straight from disk: 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 is not mapped and its bytes stay out of RAM; `--ple-mmap` asks for the full host map instead,
and Apple Silicon keeps the map there anyway (its gathers need no copy at all).

| Size | Download (GB) | Routed experts (GB) | Dense weights (GB) | PLE table (GB) | Estimated RAM floor (GB) |
| --- | ---: | ---: | ---: | ---: | ---: |
Expand Down
4 changes: 3 additions & 1 deletion engine/include/strata/ngram/ple_reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,10 @@ class PleReader {
/// `io_thread` (default): a worker thread submits and reaps reads, so `issue` costs the caller no ReadFile
/// calls. false: the caller's thread does it (A/B arm).
/// `row_bytes`: one row's size in the file (90 IQ4_NL, 160 FP8), at most one page.
/// `read_threads`: DirectFile::open()'s `threads` (0: its default).
bool open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight,
uint64_t cache_rows, std::string& err, bool io_thread = true, uint32_t row_bytes = ROW_BYTES);
uint64_t cache_rows, std::string& err, bool io_thread = true, uint32_t row_bytes = ROW_BYTES,
int read_threads = 0);
uint32_t row_bytes() const;
void close();
bool is_open() const;
Expand Down
4 changes: 3 additions & 1 deletion engine/include/strata/platform/direct_file.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ class DirectFile {
DirectFile(const DirectFile&) = delete;
DirectFile& operator=(const DirectFile&) = delete;

bool open(const std::string& path, std::string& err);
/// `threads`: the reads issued at once, where a thread issues one blocking read at a time (not Windows, whose
/// threads only submit); 0: the default (16). STRATA_IO_THREADS overrides either.
bool open(const std::string& path, std::string& err, int threads = 0);
void close();
bool is_open() const;
uint64_t size() const;
Expand Down
4 changes: 2 additions & 2 deletions engine/src/ngram/ple_reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -345,11 +345,11 @@ PleReader::~PleReader() {
}

bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight,
uint64_t cache_rows, std::string& err, bool io_thread, uint32_t row_bytes) {
uint64_t cache_rows, std::string& err, bool io_thread, uint32_t row_bytes, int read_threads) {
close();
if (max_inflight == 0 || max_inflight > 1024) { err = "PleReader: max_inflight must be 1..1024"; return false; }
if (row_bytes == 0 || row_bytes > PAGE) { err = "PleReader: row_bytes must be 1..4096"; return false; }
if (!impl_->file.open(path, err)) return false;
if (!impl_->file.open(path, err, read_threads)) return false;
impl_->row_bytes = row_bytes;
if (table_offset + n_rows * (uint64_t) row_bytes > impl_->file.size()) {
err = "PleReader: the table extends past the end of " + path;
Expand Down
7 changes: 4 additions & 3 deletions engine/src/platform/direct_file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ DirectFile::~DirectFile() {
delete impl_;
}

bool DirectFile::open(const std::string& path, std::string& err) {
bool DirectFile::open(const std::string& path, std::string& err, int threads) {
close();
const int wlen = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
std::wstring wpath((size_t) (wlen > 0 ? wlen : 1), L'\0');
Expand Down Expand Up @@ -192,6 +192,7 @@ bool DirectFile::open(const std::string& path, std::string& err) {
}
// Completions of reads that finish synchronously are still queued to the port, so every issued read
// produces exactly one packet; `wait` is the only completion path.
(void) threads; // the threads here only submit overlapped reads
const int n = io_threads(4);
for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { strata::aux_cpus::pin_current_thread(); impl_->worker(); });
return true;
Expand Down Expand Up @@ -316,7 +317,7 @@ struct DirectFile::Impl {
DirectFile::DirectFile() : impl_(new Impl) {}
DirectFile::~DirectFile() { close(); delete impl_; }

bool DirectFile::open(const std::string& path, std::string& err) {
bool DirectFile::open(const std::string& path, std::string& err, int threads) {
close();
#if defined(__APPLE__) // macOS has no O_DIRECT: F_NOCACHE keeps the reads out of the unified buffer cache
impl_->fd = ::open(path.c_str(), O_RDONLY);
Expand All @@ -328,7 +329,7 @@ bool DirectFile::open(const std::string& path, std::string& err) {
struct stat st;
if (fstat(impl_->fd, &st) != 0) { err = "DirectFile: cannot size " + path; close(); return false; }
impl_->size = (uint64_t) st.st_size;
const int n = io_threads(16);
const int n = io_threads(threads > 0 ? threads : 16);
for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { strata::aux_cpus::pin_current_thread(); impl_->worker(); });
return true;
}
Expand Down
3 changes: 3 additions & 0 deletions engine/src/poly/engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,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 = true; ///< a qwen4exp PLE n-gram table read row by row from disk through the Direct row
///< reader (the default, the Flash Next engine's own mechanism); --ple-mmap maps
///< the whole table on host instead
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
4 changes: 4 additions & 0 deletions engine/src/poly/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2308,6 +2308,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-mmap read a qwen4exp PLE n-gram table from a full host map of its file; by default\n"
" its rows come straight from disk through the same Direct n-gram row reader the\n"
" Flash Next engine uses (unbuffered reads, a ~100 MB row cache, SSD keep-alive)\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 @@ -2545,6 +2548,7 @@ int main(int argc, char** argv) {
}
o.basinkv_beta = x;
}
else if (a == "--ple-mmap") o.ple_direct = false;
else if (a == "--kv") {
const std::string fmt = val();
if (fmt == "fp16") o.kv_format = KvFmt::kFp16;
Expand Down
57 changes: 54 additions & 3 deletions engine/src/poly/qwen4.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ void Qwen4::begin_pass() {

Qwen4::~Qwen4() {
stop_ple_warmer();
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);
}
#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 @@ -224,13 +232,16 @@ 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. By default 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. --ple-mmap asks for the map; a reader that cannot open the file falls back to it.
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_;
Expand All @@ -242,6 +253,30 @@ 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;
// 64 reads at once: a prompt's call asks for 16,384 rows, and on Linux each of the reader's threads
// issues one blocking read (16 by default, the Flash Next decode's need)
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_, 64)) {
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 @@ -653,6 +688,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 @@ -1049,11 +1087,24 @@ 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 (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);
}
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
11 changes: 8 additions & 3 deletions engine/src/poly/qwen4.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@
// 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
// begin_step() before blk.0). Optional 1-layer 4-stream MTP draft block (blk.40) reading raw trunk residual.
// Optional Per-Layer Embedding (PLE) n-gram engram on blk.1 (its rows read straight from disk through the Direct
// n-gram row reader, ~100 MB row cache --ple-mmap maps the table; 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

#include "basinkv.hpp"
#include "dflash2_poly.hpp"
#include "engine.hpp"
#include "gdn_mma_control.hpp"
#include "strata/ngram/ple_reader.hpp"

#include <array>
#include <atomic>
Expand Down Expand Up @@ -254,10 +256,13 @@ 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;
std::unique_ptr<strata::ngram::PleReader> ple_reader_; ///< rows straight from disk (the default); null when mapped
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