Support Orca IQ3_XXS with explicit BF16 compatibility packing

This commit is contained in:
acrogenesis committed 2026-09-27 14:10:52 -06:00
1 parent 6255c8fd14
commit b9da8e7bde
5 files changed
+319 -11

No files matched your search

+3
View File
@@ -63,6 +63,9 @@ lower the RAM needed.
Not sure? Take **IQ2_XS**. You can add another one later with `START-HERE.bat --setup`.
For **OrcaRouter's Flash-Next Uncensored IQ3_XXS**, see the [manual compatibility setup](docs/ORCA.md).
It needs an explicit packing conversion and is not an installer menu option.
## Install
**You need:** an NVIDIA RTX 30, 40 or 50 card with 12 GB of VRAM or more, enough RAM for the size you pick (above),
+95
View File
@@ -0,0 +1,95 @@
# OrcaRouter IQ3_XXS compatibility
Validated on Linux with an RTX 5090 (32 GB), Ryzen 9 9950X3D and 128 GB RAM on 2026-09-27.
The target is `orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF`, **IQ3_XXS** (two shards, 85.20 GB total).
It has Strata's Qwen4Exp geometry, but ordinary quantization also compresses the hyperconnection,
small attention and PLE projections which Strata's kernels read as BF16.
`tools/iq_pack.py --compat-bf16` expands only those projections, rounding to BF16 using nearest-even.
This adds rounding relative to the GGUF's dequantized weights; it does not recover the original BF16
checkpoint or its quality. Expert weights, native attention weights, embeddings and the 28.8 GB PLE
lookup table remain unchanged. The latter stays on disk. The pack records its conversions in
`compat-bf16.json`.
The native loader retains this pack's converted PLE key. Its existing native Q2_0 key path remains
available to the original model. Hugging Face snapshot symlinks are supported; all split shards must
finish downloading before packing. Pass the snapshot filename, not its hash-named blob target.
## Preparation
Build Strata normally using the pinned llama.cpp dependency. Python needs numpy, regex and gguf-py
from that dependency (`STRATA_GGUF_PY` can point to its `gguf-py` directory).
```sh
.venv/bin/python tools/iq_pack.py \
--gguf /path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf \
--out packs/orca-iq3_xxs --compat-bf16
```
Use this model's own tokenizer exported into the pack. Do not share another model's `dense.bin`,
and do not rename the Orca files to impersonate one of setup's GSQ-RCO models.
Strata's persistent server also requires the MTP runtime, prepared by the existing tools:
```sh
.venv/bin/python tools/mtp_fetch.py fetch --out mtp
.venv/bin/python tools/mtp_pack.py --src mtp --experts q2_0 --out mtp/mtp-q2_0.gguf
.venv/bin/python tools/mtp_rt.py --gguf mtp/mtp-q2_0.gguf --out mtp/rt
cp data/draft_vocab.bin mtp/rt/draft_vocab.bin
```
This uses the original model's draft head, as setup does for Swift. The target model verifies its
proposals; draft acceptance and performance must be measured for this fine-tune.
## Local server
Save the following as `strata-orca-iq3_xxs.json` at the repository root, replacing both `/path/to/`
entries with the **same first shard**. Orca's PLE table is in shard 1. Start with a 32K context and
512-token prefill chunks; the expert cache sizes itself to available VRAM. The expert arena alone
needs about 49.8 GiB of available system RAM, plus draft/runtime buffers and other applications.
```json
{
"exe": "build/strata",
"args": [
"--pack", "packs/orca-iq3_xxs",
"--native", "/path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf",
"--ple-gguf", "/path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf",
"--expert-profile", "data/expert-profile.bin", "--expert-cache", "auto",
"--prefill", "512", "--spec", "4", "--spec-min-p", "0.5",
"--mtp", "mtp/rt", "--max-context", "32768", "--kv", "int8"
],
"cwd": ".",
"tokenizer": "packs/orca-iq3_xxs/tokenizer",
"model_name": "orcarouter-qwen3.8-flash-next-uncensored-iq3_xxs",
"log": "strata-orca-iq3_xxs.log",
"host": "127.0.0.1",
"port": 8080
}
```
Run from the repository root:
```sh
.venv/bin/python -m serve.server --engine strata --config strata-orca-iq3_xxs.json --port 8080
```
The web interface is at `http://127.0.0.1:8080`; API clients use `http://127.0.0.1:8080/v1`.
Vision is not configured in this text-only example. Performance of the original GSQ-RCO model
does not establish this fine-tune's speed or accuracy.
## Scope and validation
- IQ3_XXS is the target of this change; other Orca quantizations are not validated.
- IQ3_M additionally uses Q5_0 expert down matrices, which the native GPU expert path does not support.
- The installer model menu is unchanged. This is an explicit local packing workflow.
- Focused conversion and split-file tests: `.venv/bin/python -m unittest discover -s tools -p test_iq_pack.py`.
- All eight packing tests, 17 server tests and the GPU gated-residual parity check passed.
- The complete model packed successfully: 460 tensors converted, 1.39 GiB of converted BF16 weights;
1.43 GiB total packed dense weights. The 48 expert layers remain IQ3_XXS gate/up and IQ4_NL down.
- Real server checks passed: arithmetic, Python code, translation, a longer explanation, multi-turn context
reuse (25 prompt tokens reused), streaming cancellation and a subsequent correct response. The engine
PID stayed unchanged. These are smoke tests, not a quality benchmark or a full-context stress test.
- With the configuration above, a 111-token explanation generated at 77.7 tokens/s (engine decode timing);
total request time was 1.77 seconds. This single short measurement is not a general throughput claim.
+7 -4
View File
@@ -13,9 +13,12 @@
namespace strata::core {
namespace {
bool eligible(const std::string& name, bool include_ple_key) {
bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) {
const auto& name = tensor.name;
if (name.rfind("blk.", 0) != 0) return false;
if (include_ple_key && name == "blk.1.ple_key.weight") return true;
// The native PLE kernel accepts Q2_0. Other quantized keys can be converted to BF16 by iq_pack;
// keep their packed bytes resident instead of overriding them with an unsupported native key.
if (name == "blk.1.ple_key.weight") return include_ple_key && tensor.type == 42;
static const char* suffixes[] = {".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight",
".attn_q.weight", ".attn_k.weight", ".attn_v.weight", ".attn_output.weight",
".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", ".ffn_down_shexp.weight"};
@@ -38,7 +41,7 @@ bool NativeDense::served_names(const std::vector<std::string>& shards, bool incl
for (const auto& path : shards) {
strata::GgufFile gguf(path);
for (const auto& tensor : gguf.tensors())
if (eligible(tensor.name, include_ple_key) && strata::kernels::native_mmvq_supported(tensor.type) &&
if (eligible(tensor, include_ple_key) && strata::kernels::native_mmvq_supported(tensor.type) &&
tensor.shape.size() == 2)
out.insert(tensor.name);
}
@@ -124,7 +127,7 @@ bool NativeDense::load(const std::vector<std::string>& shards, WeightTable& tabl
}
}
for (const auto& tensor : gguf.tensors()) {
if (!eligible(tensor.name, include_ple_key)) continue;
if (!eligible(tensor, include_ple_key)) continue;
if (!seen.insert(tensor.name).second) {
err = "native dense: duplicate tensor " + tensor.name; return false;
}
+74 -7
View File
@@ -21,6 +21,10 @@ Split files: every shard of the model is read (<name>-0000N-of-0000M.gguf beside
split anyhow (Swift 1.5's GGUFs put layers 13-47 in shard 2 and the PLE table in shard 1). A layer whose experts
are not in shard 1 names its shard in native_experts.txt (v3). Router tensors stored as F32 whose values are
exactly BF16 (Swift 1.5) are written as BF16, the form the engine's router takes; anything else is refused.
For ordinary quants, --compat-bf16 dequantizes the small projections that the engine reads as BF16, using
round-to-nearest-even. This introduces BF16 rounding; it does not reconstruct the original full-precision
weights. Experts, native attention projections, token embeddings and the disk-backed PLE table stay unchanged.
"""
from __future__ import annotations
@@ -42,6 +46,37 @@ FLOAT = {"BF16", "F32", "F16"}
ROUTERS = ("ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight")
NOT_IN_PACK = {"per_layer_token_embd.weight"} # the 28.8 GB PLE table: read from its GGUF by the engine
# These small projections are read as BF16 by the residual, router, GDN, QSA and PLE kernels.
# GSQ-RCO files already store them that way. Ordinary GGUF quants (including OrcaRouter's IQ3_XXS)
# quantize them too; --compat-bf16 explicitly dequantizes and rounds ONLY these tensors.
BF16_PROJECTIONS = (
"hc_attn_down.weight", "hc_attn_up.weight", "hc_attn_inject.weight",
"hc_ffn_down.weight", "hc_ffn_up.weight", "hc_ffn_inject.weight",
"ssm_alpha.weight", "ssm_beta.weight", "indexer.q_proj.weight", "indexer.k_proj.weight",
"ple_value.weight", *ROUTERS,
)
BF16_OUTPUT = {"output_hc_down.weight", "output_hc_up.weight"}
def needs_bf16(name: str, type_name: str) -> bool:
if name in BF16_OUTPUT:
return True
if not name.startswith("blk."):
return False
# The existing native PLE key supports Q2_0 only. Other key encodings use the BF16 path.
return name.endswith(BF16_PROJECTIONS) or (name == "blk.1.ple_key.weight" and type_name != "Q2_0")
def bf16_bytes(raw: np.ndarray, type_name: str) -> bytes:
from _paths import add_gguf_py
add_gguf_py()
from gguf import GGMLQuantizationType as Q, quants
values = quants.dequantize(raw, Q[type_name])
if not np.isfinite(values).all():
raise ValueError("cannot convert non-finite weights to BF16")
# ggml's round-to-nearest-even conversion, including correct halfway rounding.
return quants.quantize(values, Q.BF16).tobytes()
class Model:
"""All shards of one model: name -> (GGUFFile, TensorInfo, memmap, shard path)."""
@@ -54,13 +89,20 @@ class Model:
total = int(m.group(2))
paths = [first.with_name(first.name[:m.start()] + "-%05d-of-%05d.gguf" % (i, total))
for i in range(1, total + 1)]
paths = [p for p in paths if p.exists()]
missing = [str(p) for p in paths if not p.is_file()]
if missing:
raise FileNotFoundError("missing model shards (wait for the download): " + ", ".join(missing))
self.paths = paths
self.where = {}
for p in paths:
g = G.GGUFFile(p)
mm = np.memmap(p, dtype=np.uint8, mode="r")
for t in g.tensors:
size = t.expected_bytes()
if size is None or g.data_start + t.offset + size > mm.size:
raise ValueError(f"{p.name}: unsupported or truncated tensor {t.name}")
if t.name in self.where:
raise ValueError(f"{p.name}: duplicate tensor {t.name}")
self.where[t.name] = (g, t, mm, p)
def bytes(self, name) -> np.ndarray:
@@ -91,11 +133,18 @@ def is_expert(name: str) -> bool:
return name.startswith("blk.") and name.endswith(("_exps.weight",))
def index_standalone(src, out, model: Model) -> int:
def index_standalone(src, out, model: Model, compat_bf16: bool = False) -> int:
"""Every non-expert tensor of the model: floats into dense.bin as stored (exact-BF16 F32 routers as BF16),
quantized ones native-only."""
if not compat_bf16:
for name, (_, t, _, _) in model.where.items():
if needs_bf16(name, t.type_name) and t.type_name != "BF16" and not (
t.type_name == "F32" and name.endswith(ROUTERS)):
print(f"{name} is {t.type_name}, but the engine requires BF16; use --compat-bf16")
return 1
rows, at = [], 0
served = 0
converted = []
with open(out / "dense.bin", "wb") as fo:
for name, (g, t, mm, _) in model.where.items():
if is_expert(t.name) or t.name in NOT_IN_PACK:
@@ -105,10 +154,16 @@ def index_standalone(src, out, model: Model) -> int:
return 1
ne0 = int(t.shape[0])
ne1 = int(t.shape[1]) if len(t.shape) > 1 else 0
if t.type_name in FLOAT:
convert = compat_bf16 and needs_bf16(t.name, t.type_name) and t.type_name != "BF16"
if t.type_name in FLOAT or convert:
raw = tensor_bytes(mm, g, t).tobytes()
kind = {"BF16": "4", "F16": "5", "F32": "2"}[t.type_name]
if t.type_name == "F32" and t.name.endswith(ROUTERS):
if convert:
raw = bf16_bytes(np.frombuffer(raw, dtype=np.uint8), t.type_name)
kind = "4"
converted.append({"name": t.name, "source_type": t.type_name, "bytes": len(raw)})
else:
kind = {"BF16": "4", "F16": "5", "F32": "2"}[t.type_name]
if not convert and t.type_name == "F32" and t.name.endswith(ROUTERS):
u = np.frombuffer(raw, dtype=np.uint32)
if np.count_nonzero(u & 0xFFFF):
print("router %s is F32 with values that are not BF16; the engine's router is BF16" % t.name)
@@ -125,6 +180,12 @@ def index_standalone(src, out, model: Model) -> int:
served += 1
rows.append([t.name, "0", "0", "0", "0", "0", "0", str(ne0), str(ne1), "8", "0", "32"] + ["0"] * 7)
write_index(out, rows, src, served, 0)
if compat_bf16:
(out / "compat-bf16.json").write_text(json.dumps({
"source": str(src), "rounding": "nearest-even", "tensors": converted,
}, indent=2) + "\n", encoding="utf-8")
print("compat-bf16: %d tensors, %.2f GiB; expert and PLE table bytes unchanged"
% (len(converted), sum(t["bytes"] for t in converted) / 2**30))
return 0
@@ -198,10 +259,16 @@ def main() -> int:
ap.add_argument("--base", help="optional: a Q2_0 canonical pack whose dense.bin holds the shared float tensors")
ap.add_argument("--out", required=True)
ap.add_argument("--skip-experts", action="store_true", help="rewrite the index only")
ap.add_argument("--compat-bf16", action="store_true",
help="dequantize small non-native projections to BF16 for ordinary Qwen4Exp GGUFs "
"(rounds weights; leaves experts and the PLE table unchanged)")
ap.add_argument("--experts-bin", action="store_true",
help="also write experts.bin (the engine otherwise reads the experts from the GGUF itself)")
a = ap.parse_args()
src = pathlib.Path(a.gguf).resolve()
if a.compat_bf16 and a.base:
ap.error("--compat-bf16 cannot reuse --base dense weights")
# HF snapshot files are symlinks to hash-named blobs. Keep the shard filename for discovery.
src = pathlib.Path(a.gguf).absolute()
base = pathlib.Path(a.base).resolve() if a.base else None
out = pathlib.Path(a.out)
out.mkdir(parents=True, exist_ok=True)
@@ -218,7 +285,7 @@ def main() -> int:
return 1
rc = index_from_base(a, src, base, out, g, {t.name: t for t in g.tensors}, mm)
else:
rc = index_standalone(src, out, model)
rc = index_standalone(src, out, model, a.compat_bf16)
if rc:
return rc
if not (out / "tokenizer" / "vocab.json").exists() or not (out / "tokenizer" / "chat_template.jinja").exists():
+140
View File
@@ -0,0 +1,140 @@
"""Focused pack compatibility tests; run .venv/bin/python -m unittest discover -s tools -p test_iq_pack.py."""
import contextlib
import io
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
import numpy as np
from _paths import add_gguf_py
add_gguf_py()
from gguf import GGUFWriter, GGMLQuantizationType as Q, quants
import iq_pack
def write_gguf(path, tensors):
writer = GGUFWriter(path, "qwen4exp")
for name, values, kind in tensors:
writer.add_tensor(name, quants.quantize(values, kind), raw_dtype=kind)
writer.write_header_to_file()
writer.write_kv_data_to_file()
writer.write_tensors_to_file()
writer.close()
class CompatibilityTests(unittest.TestCase):
def test_bf16_halfway_rounds_to_even(self):
values = np.array([0x3F808000, 0x3F818000, 0xBF808000, 0xBF818000], dtype=np.uint32)
got = np.frombuffer(iq_pack.bf16_bytes(values.view(np.uint8), "F32"), dtype=np.uint16)
np.testing.assert_array_equal(got, [0x3F80, 0x3F82, 0xBF80, 0xBF82])
def test_nonfinite_conversion_refused(self):
with self.assertRaisesRegex(ValueError, "non-finite"):
iq_pack.bf16_bytes(np.array([np.nan], dtype=np.float32).view(np.uint8), "F32")
def test_projection_conversion_and_native_bytes(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
source = root / "model.gguf"
values = np.linspace(-1, 1, 256, dtype=np.float32).reshape(2, 128)
router = np.full((2, 128), 0.10001, dtype=np.float32)
names = ["blk.0.hc_attn_down.weight", "output_hc_up.weight", "blk.1.ple_key.weight",
"blk.0.ssm_alpha.weight", "blk.3.indexer.q_proj.weight", "blk.1.ple_value.weight"]
write_gguf(source, [(n, values, Q.Q8_0) for n in names] + [
("blk.0.ffn_gate_inp.weight", router, Q.F32),
("blk.0.attn_qkv.weight", values, Q.Q8_0),
("per_layer_token_embd.weight", values, Q.Q8_0),
])
before = source.read_bytes()
model = iq_pack.Model(source)
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(iq_pack.index_standalone(source, root, model, True), 0)
_, rows = iq_pack.read_index(root / "index.txt")
dense = (root / "dense.bin").read_bytes()
# A scalar oracle independent of the BF16 encoder: choose the nearest BF16 value,
# using the even representation at exact ties.
decoded = quants.dequantize(quants.quantize(values, Q.Q8_0), Q.Q8_0).ravel()
def rounded(x):
bits = int(np.float32(x).view(np.uint32))
return (bits >> 16) + ((bits & 65535) > 32768 or
((bits & 65535) == 32768 and (bits >> 16) & 1))
expected = np.array([rounded(x) for x in decoded], dtype=np.uint16)
for name in names:
row = rows[name]
self.assertEqual(row[2], "4")
offset, size = int(row[3]), int(row[4])
np.testing.assert_array_equal(np.frombuffer(dense[offset:offset + size], dtype=np.uint16), expected)
native = rows["blk.0.attn_qkv.weight"]
self.assertEqual(native[4], "0")
self.assertEqual(native[9], "8")
self.assertNotIn("per_layer_token_embd.weight", rows)
self.assertEqual(source.read_bytes(), before)
self.assertEqual(len(json.loads((root / "compat-bf16.json").read_text())["tensors"]), 7)
def test_default_still_refuses_inexact_f32_router(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
source = root / "model.gguf"
write_gguf(source, [("blk.0.ffn_gate_inp.weight", np.full((2, 32), 0.10001, np.float32), Q.F32)])
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1)
def test_existing_bf16_pack_remains_byte_identical(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
source = root / "model.gguf"
values = np.linspace(-2, 2, 256, dtype=np.float32).reshape(2, 128)
write_gguf(source, [("blk.0.hc_attn_down.weight", values, Q.BF16)])
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 0)
self.assertEqual((root / "dense.bin").read_bytes(), quants.quantize(values, Q.BF16).tobytes())
def test_quantized_control_weights_need_explicit_conversion(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
source = root / "model.gguf"
write_gguf(source, [("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0)])
(root / "dense.bin").write_bytes(b"previous pack")
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1)
self.assertEqual((root / "dense.bin").read_bytes(), b"previous pack")
def test_q2_ple_and_large_tensors_stay_native(self):
self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q2_0"))
for name in ["blk.0.ffn_gate_exps.weight", "token_embd.weight", "output.weight",
"per_layer_token_embd.weight", "blk.0.attn_qkv.weight"]:
self.assertFalse(iq_pack.needs_bf16(name, "IQ3_XXS"))
def test_snapshot_symlinks_keep_split_discovery(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
snap = root / "snapshot"
snap.mkdir()
first = snap / "model-00001-of-00002.gguf"
second = snap / "model-00002-of-00002.gguf"
write_gguf(root / "blob1", [("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0)])
write_gguf(root / "blob2", [(f"blk.0.ffn_{r}_exps.weight", np.ones((512, 2, 32), np.float32), Q.Q8_0)
for r in ("gate", "up", "down")])
first.symlink_to(root / "blob1")
with self.assertRaisesRegex(FileNotFoundError, "missing model shards"):
iq_pack.Model(first)
second.symlink_to(root / "blob2")
out = root / "pack"
(out / "tokenizer").mkdir(parents=True)
for name in ["vocab.json", "chat_template.jinja"]:
(out / "tokenizer" / name).touch()
with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(first), "--out", str(out), "--compat-bf16"]):
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(iq_pack.main(), 0)
self.assertIn(second.name, (out / "native_experts.txt").read_text())
(root / "blob2").write_bytes((root / "blob2").read_bytes()[:-64])
with self.assertRaisesRegex(ValueError, "truncated tensor"):
iq_pack.Model(first)
if __name__ == "__main__":
unittest.main()