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
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
55 changes: 52 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,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 @@ -653,6 +686,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 +1085,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
30 changes: 30 additions & 0 deletions patches/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# PolyStrata patch bundle — Qwen4-35B-A3B support (+ Clover fix)

Archive: **`polystrata-patches-qwen4-support-2026-12-04.zip`** (this directory zipped, minus scratch).

Two self-contained patch bundles for the `strata-poly` engine:

| Bundle | Adds | Base commit | Install doc |
| --- | --- | --- | --- |
| [`qwen4exp-full-port/`](qwen4exp-full-port/) | **Qwen4-35B-A3B support** on `strata-poly`: a standalone `qwen4exp` architecture engine (hybrid GDN+attention, 4-stream hyper-connections, routed+shared MoE with CPU expert offload, and the PLE n-gram table read row by row from SSD through `strata::ngram::PleReader` — the Flash Next mechanism) | `4106d1a7c` | [INSTALL.md](qwen4exp-full-port/INSTALL.md) / [INSTALL.ru.md](qwen4exp-full-port/INSTALL.ru.md) (рус.) |
| [`qwen35-clover/`](qwen35-clover/) | Clover (`clover_moe`) fix: auto-detect the block-of-guesses tensors, so `--clover-masks` disables itself instead of crashing on files without `ssm_conv1d.weight_right` | `df2c3ff30` | [INSTALL.md](qwen35-clover/INSTALL.md) / [INSTALL.ru.md](qwen35-clover/INSTALL.ru.md) (рус.) |

Both patches were produced and verified on 2026-12-04 on the same Linux/CUDA box (RTX 3080 Ti).

## Which bundle do I need?

* **Qwen4 support, full port**: only if your tree is at `4106d1a7c` (or you want the standalone
`qwen4exp` derivation as it was tested). Current `main` already carries the upstream `qwen4.cpp`
architecture engine; PR #440 moves this bundle's direct-from-SSD PLE reader into it. On a current
`main`, you do **not** need the full port.
* **Clover fix**: applies on current `main` (`df2c3ff30`+). Upstream `main` already contains the
`ssm_a = -exp(A_log)` conversion half of the old Clover fix; this patch adds the missing half
(the bd / guessed-token side auto-detection).

## Regenerating bundle artifacts

* `qwen4exp-full-port/docs/metadata.json` — the model's full GGUF key/value dump, produced by the
`gguf_keys.py`-style parse of both shards; it is documentation, not an input.
* The CPU-reference stage dumps (`*.f32`, ~400 MB) are **not** in the zip: regenerate them with
the bundle's `verify/q4_dump.cpp` (compile against the GGUFs, it writes
`/tmp/opencode/q4_dump/`; point `Q4DUMP` at wherever you put it).
29 changes: 29 additions & 0 deletions patches/README.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Бандл патчей PolyStrata — поддержка Qwen4-35B-A3B (+ фикс Clover)

Архив: **`polystrata-patches-qwen4-support-2026-12-04.zip`** (этот каталог в zip, без временных файлов прогонов).

Два самодостаточных набора патчей для движка `strata-poly`:

| Набор | Что добавляет | Базовый коммит | Документация по установке |
| --- | --- | --- | --- |
| [`qwen4exp-full-port/`](qwen4exp-full-port/) | **Поддержка Qwen4-35B-A3B** в `strata-poly`: отдельная архитектура `qwen4exp` (гибрид GDN+attention, гипер-связи из 4 потоков, маршрутизированные + общие эксперты с выгрузкой на CPU, и PLE-таблица n-грамм, читаемая строками прямо с SSD через `strata::ngram::PleReader` — тот же механизм, что у Flash Next) | `4106d1a7c` | [INSTALL.ru.md](qwen4exp-full-port/INSTALL.ru.md) / [INSTALL.md](qwen4exp-full-port/INSTALL.md) (EN) |
| [`qwen35-clover/`](qwen35-clover/) | Фикс Clover (`clover_moe`): автоопределение тензоров «блока догадок», поэтому `--clover-masks` сам себя отключает вместо падения на файлах без `ssm_conv1d.weight_right` | `df2c3ff30` | [INSTALL.ru.md](qwen35-clover/INSTALL.ru.md) / [INSTALL.md](qwen35-clover/INSTALL.md) (EN) |

Оба патча созданы и проверены 04.12.2026 на той же Linux/CUDA машине (RTX 3080 Ti).

## Какой набор нужен?

* **Полный порт поддержки Qwen4**: только если ваше дерево на коммите `4106d1a7c` (или вам нужен ровно
тот автономный порт `qwen4exp`, каким он был протестирован). Текущий `main` уже содержит апстримовый
движок архитектуры `qwen4.cpp`; PR #440 переносит в него direct-чтение PLE с SSD из этого бандла.
На текущем `main` полный порт **не нужен**.
* **Фикс Clover**: ставится на текущий `main` (`df2c3ff30`+). Половину прежнего Clover-фикса
(`ssm_a = -exp(A_log)`) апстрим уже содержит; этот патч добавляет недостающую половину
(автоопределение bd-половины / «блока догадок»).

## Как заново получить артефакты бандла

* `qwen4exp-full-port/docs/metadata.json` — полный дамп ключей/значений GGUF обеих шард; это
документация, а не входные данные.
* Дампы стадий CPU-эталона (`*.f32`, ~400 МБ) в zip **не входят**: воссоздайте их утилитой
`verify/q4_dump.cpp` (пишет в `/tmp/opencode/q4_dump/`; переменной `Q4DUMP` укажите своё место).
41 changes: 41 additions & 0 deletions patches/qwen35-clover/INSTALL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Install — Clover (`clover_moe`) block auto-detection fix

**What it fixes.** Clover `clover_moe` GGUFs come in two shapes: with the "block of guesses" side of
the GDN block (`ssm_conv1d.weight_right`, `ssm_bd_logit_scale.weight`, `ssm_bd_history.*`) and without
it. With `--clover-masks` set, the engine used to demand those tensors unconditionally and crashed on
loading a file that has none of them. The patch detects `ssm_conv1d.weight_right` per layer: the bd
tensors are loaded only when it exists, and a `--clover-masks` request on a file without them disables
itself (the block runs plain GDN) instead of crashing.

The other half of the old Clover fix — reading `ssm_a` as `A_log` (`-exp(A_log)`) for `clover_moe`
files — is already in `main`; this patch does not repeat it.

**Base commit.** `df2c3ff30` (current `main`). `git apply --check` verified on 2026-12-04; the tree
builds clean with and without the patch (`strata-poly` target, Linux CUDA).

## Apply

```bash
cd <PolyStrata checkout> # on main, clean tree
git apply patches/qwen35-clover/qwen35-clover.patch
cmake --build terminal/build-poly --target strata-poly -j 10
```

## Revert

```bash
git apply -R patches/qwen35-clover/qwen35-clover.patch
cmake --build terminal/build-poly --target strata-poly -j 10
```

(Or just `git checkout -- engine/src/poly/qwen35.cpp` and rebuild.)

## Check it worked

Load a `clover_moe` GGUF that has no `ssm_conv1d.weight_right` with `--clover-masks <id>`:

* before the patch: the load throws a missing-tensor error naming `ssm_conv1d.weight_right`;
* after the patch: the model loads and runs, the mask path simply stays off.

A Clover file **with** the bd tensors is unaffected: with `--clover-masks` the block keeps its guessed-
token side exactly as before.
Loading