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
4 changes: 3 additions & 1 deletion docs/models/qwen4.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ Useful options:
top-scoring cold blocks from pinned RAM, passing 100% of NIAH checks through 256K on RTX 4090 D (`UD-IQ2_XS`). See
[docs/BASINKV.md](../BASINKV.md) for flags and full 8K–256K measurements.
- **Bring your own GGUF:** pass `--custom-gguf <path>` or inspect headers without downloading via
`START-HERE.bat --inspect <file-or-folder>`.
`START-HERE.bat --inspect <file-or-folder>`. A single-file GGUF without the MTP block (converted with llama.cpp's
`--no-mtp`) drafts from its MTP file: put `mtp-<name>-<quant>.gguf` in the same folder and setup passes it via
`--draft-model`. Without that file the model runs without drafting, and setup says so.

## Quantization choices

Expand Down
52 changes: 51 additions & 1 deletion terminal/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12715,6 +12715,44 @@ def qwen4_recommended_size(fam: dict, ram: float) -> str:
return "UD-IQ2_XS" if "UD-IQ2_XS" in fam["models"] else next(iter(fam["models"]))


def qwen4_mtp_sidecar(shards: list[Path]) -> tuple[bool, Path | None]:
"""A Qwen4 GGUF of one's own (--custom-gguf): (whether the file carries the draft block itself, the MTP sidecar
beside it). Unsloth's files carry the block (blk.40, nextn_predict_layers = 1). A file converted with llama.cpp's
--no-mtp (ggml-org's recipe: OpenUncensored's single-file GGUFs) has 40 blocks and its MTP head in a file of its
own, mtp-<name>-<quant>.gguf, which strata-poly reads with --draft-model. Of several sidecars: one named after
this model (mtp-<name>-...) before one of another model, then the one of the model's own quantization, else Q8_0,
else the smallest. A sidecar is taken only if its header has the block after the model's last one."""
from quantscope import Source, read_gguf
main = shards[0]
meta, tensors = read_gguf(Source(name=main.name, size=main.stat().st_size, path=str(main)))
arch = meta.get("general.architecture") or "qwen4exp"
blocks = int(meta.get(f"{arch}.block_count") or 0)
nextn = int(meta.get(f"{arch}.nextn_predict_layers") or 0)
trunk = blocks - nextn
probe = f"blk.{trunk}.nextn.eh_proj.weight"
if nextn == 1 and any(t["name"] == probe for t in tensors):
return True, None
def named(f: Path) -> tuple[str, str]: # (the name before the quantization, the quantization)
m_q = GGUF_QUANT.search(f.name)
return (f.name[:m_q.start()] if m_q else f.stem).lower(), (m_q.group(1).lower() if m_q else "")

base, quant = named(main)

def rank(f: Path) -> tuple[bool, bool, bool, int]:
b, q = named(f)
return b != "mtp-" + base, not (quant and q == quant), q != "q8_0", f.stat().st_size

cands = [f for f in main.parent.glob("*.gguf") if f.name.lower().startswith("mtp-")]
for f in sorted(cands, key=rank):
try:
m2, t2 = read_gguf(Source(name=f.name, size=f.stat().st_size, path=str(f)))
except (OSError, ValueError):
continue
if m2.get("general.architecture") == arch and any(t["name"] == probe for t in t2):
return False, f
return False, None


def install_qwen4(a, family, gpu, hip, cuda_tk, multi, ram, data, elsewhere, port, adopted):
"""Steps 2-7 for Qwen4-35B-A3B (--family qwen4) on strata-poly: uses the standard strata-poly engine
(prebuilt release archive or local --build), pinned 2-shard Unsloth Dynamic GGUFs (read natively by strata-poly
Expand Down Expand Up @@ -12809,12 +12847,22 @@ def install_qwen4(a, family, gpu, hip, cuda_tk, multi, ram, data, elsewhere, por

drafter = getattr(a, "drafter", None)
draft_choice = poly_draft_on(a, [cfg_path, earlier])
mtp_sidecar = None
if drafter == "dflash2" and draft_choice:
ok("drafter: DFlash2 (RadixArk/Qwen4-35B-A3B-Dflash2)")
elif not draft_choice:
ok("drafting: off (--no-draft; kept in the run config until --mtp on)")
else:
ok("drafter: embedded MTP layer (native strata-poly)")
embedded = True
if _sg: # one's own file: it may keep its MTP head in a sidecar
embedded, mtp_sidecar = qwen4_mtp_sidecar(list(_sg))
if mtp_sidecar is not None:
ok(f"drafter: MTP sidecar {mtp_sidecar.name} (--draft-model)")
elif embedded:
ok("drafter: embedded MTP layer (native strata-poly)")
else:
warn(f"{Path(_sg[0]).name} has no draft block of its own and no mtp-*.gguf of this model is beside it: "
"it runs without drafting (put the MTP file in the same folder and run setup again)")

folder = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag
shards = list(_sg) if _sg else [folder / fam["file"].format(q=model, i=i) for i in range(1, fam["shards"] + 1)]
Expand Down Expand Up @@ -12934,6 +12982,8 @@ def install_qwen4(a, family, gpu, hip, cuda_tk, multi, ram, data, elsewhere, por
args = ["--model", str(shards[0]), "--max-context", str(ctx), "--expert-profile", str(profile)]
if dflash2_dir is not None:
args += ["--draft-model", str(dflash2_dir / "model.safetensors")]
elif mtp_sidecar is not None:
args += ["--draft-model", str(mtp_sidecar)]
elif not draft_choice:
args.append("--no-draft")
if conv:
Expand Down
92 changes: 92 additions & 0 deletions terminal/tools/test_setup_qwen4.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def _write_synthetic_gguf(
experts: int = 256,
pre: str = "qwen4",
include_merges: bool = True,
extra_tensors: tuple[str, ...] = (),
) -> None:
"""Write a minimal valid GGUF v3 file with bounded metadata + small F32/Q8_0 tensors for inspect & preflight tests."""
kvs: list[tuple[str, int, bytes]] = [
Expand All @@ -79,6 +80,7 @@ def _write_synthetic_gguf(
("output_norm.weight", [embd], 0, embd * 4),
("blk.0.ffn_gate_exps.weight", [32, 1, 1], 8, 34),
(f"blk.{last_blk}.ffn_gate_exps.weight", [32, 1, 1], 8, 34),
*((name, [8], 0, 32) for name in extra_tensors),
]
buf = bytearray()
buf += b"GGUF" + struct.pack("<IQQ", 3, len(tensor_specs), len(kvs))
Expand Down Expand Up @@ -320,6 +322,96 @@ def test_mtp_off_passes_no_draft_and_shard2_hardlink_reuses_ple_across_tiers(sel
s2 = t / "models" / "qwen4-ud-q4_k_xl" / "Qwen4-35B-A3B-UD-Q4_K_XL-00002-of-00002.gguf"
self.assertEqual(s2.read_bytes(), b"ple-table-data")

def _single_file_model(self, folder: Path, *sidecars: str, probe: bool = True) -> Path:
"""A single-file GGUF without the draft block (llama.cpp --no-mtp: 40 blocks, no nextn key) and MTP sidecars."""
main = folder / "Qwen4-35B-A3B-Uncensored-Q4_K_M.gguf"
_write_synthetic_gguf(main, blocks=40, nextn=0)
for name in sidecars:
_write_synthetic_gguf(folder / name, blocks=41, nextn=1,
extra_tensors=("blk.40.nextn.eh_proj.weight",) if probe else ())
return main

def test_mtp_sidecar_is_found_for_a_file_without_the_draft_block(self):
with tempfile.TemporaryDirectory() as tmp:
t = Path(tmp)
# Unsloth's layout: the block is in the file (blk.40, nextn_predict_layers = 1): no sidecar is looked for
own = t / "own" / "Qwen4-35B-A3B-UD-Q4_K_XL-00001-of-00002.gguf"
_write_synthetic_gguf(own, blocks=41, nextn=1, extra_tensors=("blk.40.nextn.eh_proj.weight",))
_write_synthetic_gguf(own.with_name("mtp-Qwen4-35B-A3B-Q8_0.gguf"), blocks=41, nextn=1,
extra_tensors=("blk.40.nextn.eh_proj.weight",))
self.assertEqual(setup.qwen4_mtp_sidecar([own]), (True, None))

# the model's own quantization before Q8_0, Q8_0 before any other
both = self._single_file_model(t / "both", "mtp-Qwen4-35B-A3B-Uncensored-BF16.gguf",
"mtp-Qwen4-35B-A3B-Uncensored-Q8_0.gguf",
"mtp-Qwen4-35B-A3B-Uncensored-Q4_K_M.gguf")
self.assertEqual(setup.qwen4_mtp_sidecar([both]),
(False, both.with_name("mtp-Qwen4-35B-A3B-Uncensored-Q4_K_M.gguf")))
q8 = self._single_file_model(t / "q8", "mtp-Qwen4-35B-A3B-Uncensored-BF16.gguf",
"mtp-Qwen4-35B-A3B-Uncensored-Q8_0.gguf")
self.assertEqual(setup.qwen4_mtp_sidecar([q8]),
(False, q8.with_name("mtp-Qwen4-35B-A3B-Uncensored-Q8_0.gguf")))

# a sidecar named after this model before another model's, whatever its quantization; another model's
# is taken when it is the only one
mixed = self._single_file_model(t / "mixed", "mtp-Qwen4-35B-A3B-Q4_K_M.gguf",
"mtp-Qwen4-35B-A3B-Uncensored-Q8_0.gguf")
self.assertEqual(setup.qwen4_mtp_sidecar([mixed]),
(False, mixed.with_name("mtp-Qwen4-35B-A3B-Uncensored-Q8_0.gguf")))
other = self._single_file_model(t / "other", "mtp-Qwen4-35B-A3B-Q8_0.gguf")
self.assertEqual(setup.qwen4_mtp_sidecar([other]),
(False, other.with_name("mtp-Qwen4-35B-A3B-Q8_0.gguf")))

# no sidecar, or one without the block after the model's last: nothing to pass
self.assertEqual(setup.qwen4_mtp_sidecar([self._single_file_model(t / "none")]), (False, None))
bad = self._single_file_model(t / "bad", "mtp-Qwen4-35B-A3B-Uncensored-Q4_K_M.gguf", probe=False)
self.assertEqual(setup.qwen4_mtp_sidecar([bad]), (False, None))

def test_custom_single_file_gguf_passes_its_mtp_sidecar_as_draft_model(self):
with tempfile.TemporaryDirectory() as tmp:
t = Path(tmp)
main = self._single_file_model(t / "mine", "mtp-Qwen4-35B-A3B-Uncensored-Q4_K_M.gguf")
sidecar = main.with_name("mtp-Qwen4-35B-A3B-Uncensored-Q4_K_M.gguf")
fam = setup.QWEN4_FAMILIES["qwen4"]
size = dict(fam["models"]["UD-Q4_K_XL"], about="your own file")
with mock.patch.dict(fam["models"], {"Q4_K_M": size}):
a = self._base_args(t, model="Q4_K_M", vision="no", _custom_gguf_shards=[main])
rc, out, _eng, _cmds, dl = self._run_install(t, a)
self.assertEqual(rc, 0)
self.assertEqual(dl, []) # one's own files: nothing is downloaded
self.assertIn("MTP sidecar mtp-Qwen4-35B-A3B-Uncensored-Q4_K_M.gguf", out)
cfg = json.loads((t / "strata-qwen4-qwen4-35b-a3b-uncensored-q4_k_m.json").read_text(encoding="utf-8"))
args = cfg["args"]
self.assertEqual(args[args.index("--model") + 1], str(main))
self.assertEqual(args[args.index("--draft-model") + 1], str(sidecar))
self.assertNotIn("--no-draft", args)
self.assertNotIn("drafting", cfg) # the model's own MTP, not DFlash2
# the server keeps a .gguf draft block for strata-poly, with drafting unset and with "mtp" asked by name
for asked in (cfg, {**cfg, "drafting": "mtp"}):
resolved = S.engine_args(asked, announce=False)
self.assertEqual(resolved[resolved.index("--draft-model") + 1], str(sidecar))

# --mtp off: no sidecar is passed
a = self._base_args(t, model="Q4_K_M", vision="no", mtp="off", _custom_gguf_shards=[main])
rc, _out, _eng, _cmds, _dl = self._run_install(t, a)
self.assertEqual(rc, 0)
cfg = json.loads((t / "strata-qwen4-qwen4-35b-a3b-uncensored-q4_k_m.json").read_text(encoding="utf-8"))
self.assertNotIn("--draft-model", cfg["args"])
self.assertIn("--no-draft", cfg["args"])

# without a sidecar the model is installed, with a warning, and runs without drafting (a folder of its own:
# the config above keeps "mtp": false until --mtp on)
with tempfile.TemporaryDirectory() as tmp:
t = Path(tmp)
alone = self._single_file_model(t / "alone")
with mock.patch.dict(fam["models"], {"Q4_K_M": size}):
a = self._base_args(t, model="Q4_K_M", vision="no", _custom_gguf_shards=[alone])
rc, out, _eng, _cmds, _dl = self._run_install(t, a)
self.assertEqual(rc, 0)
self.assertIn("no draft block of its own", out)
cfg = json.loads((t / "strata-qwen4-qwen4-35b-a3b-uncensored-q4_k_m.json").read_text(encoding="utf-8"))
self.assertNotIn("--draft-model", cfg["args"])

def test_choices_from_config_prefers_longest_tag_without_shadowing_feed_models(self):
with tempfile.TemporaryDirectory() as tmp:
t = Path(tmp)
Expand Down