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
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.
41 changes: 41 additions & 0 deletions patches/qwen35-clover/INSTALL.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Установка — фикс автоопределения блока Clover (`clover_moe`)

**Что исправляет.** GGUF архитектуры `clover_moe` бывают двух видов: с «блоком догадок» в GDN-блоке
(`ssm_conv1d.weight_right`, `ssm_bd_logit_scale.weight`, `ssm_bd_history.*`) и без него. С включённым
`--clover-masks` движок безусловно требовал эти тензоры и падал при загрузке файла, в котором их нет.
Патч проверяет наличие `ssm_conv1d.weight_right` послойно: bd-тензоры грузятся только если он есть, а
запрос `--clover-masks` на файле без них сам себя отключает (блок работает как обычный GDN) вместо
падения.

Вторая половина прежнего Clover-фикса — чтение `ssm_a` как `A_log` (`-exp(A_log)`) для `clover_moe` —
уже есть в `main`; этот патч её не повторяет.

**Базовый коммит.** `df2c3ff30` (текущий `main`). `git apply --check` проверен 04.12.2026; дерево
собирается без ошибок и с патчем, и без него (цель `strata-poly`, Linux CUDA).

## Применение

```bash
cd <копия PolyStrata> # чистый main
git apply patches/qwen35-clover/qwen35-clover.patch
cmake --build terminal/build-poly --target strata-poly -j 10
```

## Откат

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

(или просто `git checkout -- engine/src/poly/qwen35.cpp` и пересобрать.)

## Как проверить, что помогло

Загрузите GGUF `clover_moe` без `ssm_conv1d.weight_right` с `--clover-masks <id>`:

* до патча: загрузка падает с ошибкой отсутствующего тензора, называющей `ssm_conv1d.weight_right`;
* после патча: модель загружается и работает, маска просто остаётся выключенной.

Clover-файл **с** bd-тензорами не затрагивается: с `--clover-masks` блок сохраняет «сторону догадок»
ровно как раньше.
17 changes: 17 additions & 0 deletions patches/qwen35-clover/qwen35-clover.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
diff --git a/engine/src/poly/qwen35.cpp b/engine/src/poly/qwen35.cpp
index 68fee3bc8..d751fb535 100644
--- a/engine/src/poly/qwen35.cpp
+++ b/engine/src/poly/qwen35.cpp
@@ -158,7 +158,11 @@ void Qwen35::load_layer(int il) {
B.beta = mat("ssm_beta.weight", n_embd_, v_heads_);
B.o_norm = f32("ssm_norm.weight", s_dim_);
B.wo = mat("ssm_out.weight", d_inner_, n_embd_);
- if (mask_ >= 0) {
+ // Clover's guessed-token side of the block - the right conv half and the bd terms - is in some Clover
+ // files only. Without those tensors the block is plain GDN: --clover-masks then disables itself.
+ const bool clover_block = clover_ && tensor(il, "ssm_conv1d.weight_right") != nullptr;
+ if (mask_ >= 0 && !clover_block) mask_ = -1;
+ if (clover_block && mask_ >= 0) {
B.conv_right = f32("ssm_conv1d.weight_right", kConv - 1, conv_dim_);
B.bd_scale = f32("ssm_bd_logit_scale.weight", v_heads_);
B.bd_hist_b = f32("ssm_bd_history.bias", v_heads_);
Loading