From 889660726894ee5785f72bc284d11678a261c8d8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 09:30:24 +0200 Subject: [PATCH 1/7] serve: "messages" sent as a JSON string is decoded; a non-object entry is a 400 (#460) openai_to_messages and anthropic_to_messages iterated req["messages"] directly, so a client that double-encodes the array as a JSON string had its characters iterated and the request crashed on m.get. The new _object_list decodes such a string and requires a list of objects; anything else raises ValueError("messages must be a list of objects"), which the server answers with a 400. A message's tool_calls get the same guard. --- serve/frontend.py | 25 ++++++++++++++++++++++--- serve/test_server.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 3 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index 9e73ae0a..07e369d0 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -143,10 +143,27 @@ def _late_system_to_user(messages: list[dict]) -> list[dict]: return [dict(m, role="user") if m.get("role") == "system" and i > 0 else m for i, m in enumerate(messages)] +def _object_list(value, name: str) -> list[dict]: + """#460: a request's "messages" (or a message's "tool_calls") as a list of objects. Some clients send the array + double-encoded, as a JSON string, which used to be iterated character by character and crashed on m.get: such a + string is decoded. Anything that is still not a list of objects is a ValueError, which the server answers with + a 400 naming the field. None (or no field) is an empty list, as a missing field always was.""" + if value is None: + return [] + if isinstance(value, str): + try: + value = json.loads(value) + except ValueError: + raise ValueError(f"{name} must be a list of objects (a string was sent that is not JSON)") from None + if not isinstance(value, list) or not all(isinstance(m, dict) for m in value): + raise ValueError(f"{name} must be a list of objects") + return value + + def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] - for m in req.get("messages", []): + for m in _object_list(req.get("messages"), "messages"): role = m.get("role") if role == "developer": role = "system" @@ -155,8 +172,10 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: out["reasoning_content"] = m["reasoning_content"] if m.get("tool_calls"): calls = [] - for c in m["tool_calls"]: + for c in _object_list(m["tool_calls"], "tool_calls"): fn = c.get("function", c) + if not isinstance(fn, dict): + raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)") args = fn.get("arguments") if isinstance(args, str): # the template requires a mapping, not a JSON string args = json.loads(args) if args.strip() else {} @@ -186,7 +205,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d system = req.get("system") if system: messages.append({"role": "system", "content": _text_of(system)}) - for m in req.get("messages", []): + for m in _object_list(req.get("messages"), "messages"): content = m.get("content") if isinstance(content, str): messages.append({"role": m["role"], "content": content}) diff --git a/serve/test_server.py b/serve/test_server.py index 6869de7a..ad2e9831 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -474,6 +474,18 @@ class ClientShapes(unittest.TestCase): "messages": [{"role": "user", "content": "hi"}]}) self.assertEqual(status, 200, b) # the server goes on + def test_messages_as_a_json_string_over_http(self): + # #460: a double-encoded "messages" is answered; one that is not a list of objects is a 400, not a 500 + encoded = json.dumps([{"role": "user", "content": "1+1?"}]) + for path in ("/v1/chat/completions", "/v1/messages"): + with self.subTest(path=path): + status, b = self.post(path, {"model": "x", "max_tokens": 20, "messages": encoded}) + self.assertEqual(status, 200, b) + self.assertIn("1+1?", self.prompt_text()) + status, b = self.post(path, {"model": "x", "max_tokens": 20, "messages": ["hi"]}) + self.assertEqual(status, 400, b) + self.assertIn("messages must be a list of objects", b["error"]["message"]) + def test_vision_temp_image_removed_when_the_pipe_fails(self): # #352: the temporary image goes even when the encoder's pipe raises from serve.server import Vision @@ -499,6 +511,32 @@ class ClientShapes(unittest.TestCase): msgs, _, _ = anthropic_to_messages({"system": "S", "messages": [{"role": "user", "content": "u"}]}) self.assertEqual([m["role"] for m in msgs], ["system", "user"]) + def test_messages_sent_as_a_json_string(self): + # #460: a client that double-encodes "messages" (and "tool_calls") as a JSON string gets them decoded; what is + # still not a list of objects is a ValueError (the server's 400), not an AttributeError on m.get + from serve.frontend import anthropic_to_messages, openai_to_messages + call = [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{\"x\": 1}"}}] + listed = [{"role": "user", "content": "u"}, {"role": "assistant", "content": "", "tool_calls": call}] + encoded = [listed[0], dict(listed[1], tool_calls=json.dumps(call))] + want = openai_to_messages({"messages": listed})[0] + self.assertEqual(want[1]["tool_calls"], [{"function": {"name": "f", "arguments": {"x": 1}}}]) + self.assertEqual(openai_to_messages({"messages": json.dumps(listed)})[0], want) + self.assertEqual(openai_to_messages({"messages": json.dumps(encoded)})[0], want) + anth = [{"role": "user", "content": "u"}] + self.assertEqual(anthropic_to_messages({"messages": json.dumps(anth)})[0], + anthropic_to_messages({"messages": anth})[0]) + self.assertEqual(openai_to_messages({})[0], []) # no field: nothing, as before + self.assertEqual(openai_to_messages({"messages": None})[0], []) + for bad in ("not json", "\"a string\"", json.dumps({"role": "user"}), ["hi"], [{"role": "user"}, 3], 5, + {"role": "user", "content": "u"}): + for fn in (openai_to_messages, anthropic_to_messages): + with self.subTest(bad=bad, fn=fn.__name__): + with self.assertRaisesRegex(ValueError, "messages must be a list of objects"): + fn({"messages": bad}) + for calls in (["f"], "[1]", [{"function": "f"}], "{"): + with self.subTest(calls=calls), self.assertRaisesRegex(ValueError, "tool_calls must be a list of objects"): + openai_to_messages({"messages": [{"role": "assistant", "content": "", "tool_calls": calls}]}) + class SamplingKeys(unittest.TestCase): """The GEN line's sampling keys: top_k 0 ("off") or wider than the engine's 64 get the widest list, 64 (they used From ce2d83b62daa9c81d15220a30a1bd77298f39eef Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 09:31:55 +0200 Subject: [PATCH 2/7] setup: an earlier config that does not parse is skipped, not a crash; configs are written atomically (#459) A fresh copy of Strata set itself up like the newest strata-*.json of another Strata folder and crashed with JSONDecodeError when that file was empty or cut off. previous_config now takes the newest one that parses as a JSON object; each one that does not gets a one-line warning naming it, and with none the copy is set up as a fresh install. Every place setup writes a run config now goes through write_config (a .tmp file, then os.replace), so a setup stopped half-way no longer leaves an empty config behind. --- setup.py | 50 ++++++++++++++++++++++++++++++---------- tools/test_setup_risk.py | 48 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 12 deletions(-) diff --git a/setup.py b/setup.py index 67fdd4f5..c8aba719 100644 --- a/setup.py +++ b/setup.py @@ -607,7 +607,7 @@ def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: ok("from now on this model runs on " + " + ".join(gpu_name(g) for g in pair)) else: ok("staying on one GPU (START-HERE.bat --gpus " + ",".join(str(g["index"]) for g in pair) + " switches)") - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + write_config(cfg_path, cfg) return cfg @@ -2105,7 +2105,7 @@ def repoint_config(cfg_file: Path, old: Path, new: Path) -> None: new_cfg = fix(cfg) if new_cfg != cfg: - cfg_file.write_text(json.dumps(new_cfg, indent=1), encoding="utf-8") + write_config(cfg_file, new_cfg) def data_folder(requested: str | None) -> tuple: @@ -2162,13 +2162,39 @@ def data_folder(requested: str | None) -> tuple: return dest, elsewhere +def write_config(path: Path, cfg: dict): + """A run config, written whole or not at all (#459): to a temporary file first, then moved over the old one, so + a setup stopped half-way (a closed window, a full disk) never leaves an empty strata-*.json behind.""" + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + os.replace(tmp, path) + + +def readable_config(path: Path) -> bool: + """#459: a config that parses as a JSON object; any other gets a one-line warning naming it.""" + text = None + try: + text = path.read_text(encoding="utf-8-sig") + if isinstance(json.loads(text), dict): + return True + why = "not a JSON object" + except OSError as e: + why = e.strerror or str(e) + except ValueError: # JSONDecodeError, or bytes that are not UTF-8 + why = "the file is empty" if text is not None and not text.strip() else "not valid JSON" + warn(f"skipped the earlier config {path} ({why}): setting this copy up without it") + return False + + def previous_config(elsewhere_first: list, settings: dict): - """The most recently used model config of another Strata folder on this PC, for a folder that has none yet.""" + """The most recently used model config of another Strata folder on this PC, for a folder that has none yet. One + that does not parse (an empty or cut-off file, #459) is skipped with a warning: the newest readable one is used, + and with none this copy is set up as a fresh install.""" cands = [] for folder in [*elsewhere_first, *other_installs(settings)]: cands += list(folder.glob("strata-*.json")) cands = [c for c in dict.fromkeys(cands) if c.is_file()] - return max(cands, key=lambda p: p.stat().st_mtime) if cands else None + return next((c for c in sorted(cands, key=lambda p: p.stat().st_mtime, reverse=True) if readable_config(c)), None) def choices_from_config(cfg_path: Path) -> dict: @@ -2261,7 +2287,7 @@ def calibrate_config(cfg_path: Path) -> bool: warn(f"the tuning did not finish ({e}): the default settings stay") return False cfg["args"] = CAL.apply(cfg["args"], res["settings"]) - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + write_config(cfg_path, cfg) st = load_settings() st.setdefault("calibration", {})[hardware_key(cfg)] = {"settings": res["settings"], "tok_s": res["report"].get("tok_s"), "date": time.strftime("%Y-%m-%d")} @@ -2301,7 +2327,7 @@ def upgrade_config(cfg_path: Path, cfg: dict) -> dict: changed = True ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM") if changed: - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + write_config(cfg_path, cfg) return cfg @@ -2315,7 +2341,7 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ keep = {k: v for k, v in (keep or {}).items() if v is not None} if keep and any(cfg.get(k) != v for k, v in keep.items()): # #179: a --host/--api-key on a start was ignored cfg.update(keep) - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + write_config(cfg_path, cfg) ok("saved for this model: " + ", ".join("api key" if k == "api_key" else f"{k.replace('_', ' ')} {v}" for k, v in keep.items())) cfg_path.touch() # the most recently used model @@ -2334,7 +2360,7 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ "set it up for these cards: ./setup.sh --setup --backend hip --gpus " + ",".join(map(str, gpu))) cfg["gpu"], cfg["gpus_asked"] = gpu, True cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + write_config(cfg_path, cfg) gpu = None elif gpu is not None: cmd += ["--gpu", str(gpu)] @@ -2357,7 +2383,7 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ check_gpus(gpu, found, yes=yes, named=True) cfg["gpu"], cfg["gpus_asked"] = gpu, True cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + write_config(cfg_path, cfg) gpu = None elif gpu is not None: # --gpu N: this start only, on that card check_gpus([gpu], found) @@ -2366,7 +2392,7 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ cfg = offer_together(cfg_path, cfg, yes) use = gpu if gpu is not None else cfg.get("gpu") if isinstance(use, list) and split_mmap(cfg): # #364 #384: a resident low-RAM config on several GPUs - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + write_config(cfg_path, cfg) if cfg.get("backend") == "hip": pass elif isinstance(use, list): @@ -2471,7 +2497,7 @@ def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: build_engine({**main, "archs": archs}, vision, yes, get_llama_cpp()) dirs = json.loads(info.read_text()).get("cuda_dirs") or [] cfg["lib_dirs"] = dirs + [d for d in cfg.get("lib_dirs") or [] if d not in dirs] - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + write_config(cfg_path, cfg) return cfg @@ -3217,7 +3243,7 @@ def main() -> int: import calibrate as CAL cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {}) ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else "")) - cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + write_config(cfg_path, cfg) script = write_run_script(tag, cfg_path, port) # offered only when someone answers: --yes installs and adopted earlier installs are not held up by it if cal is None and not hip and not a.no_start and not a.yes and ask( diff --git a/tools/test_setup_risk.py b/tools/test_setup_risk.py index 05aa399e..39e0defc 100644 --- a/tools/test_setup_risk.py +++ b/tools/test_setup_risk.py @@ -10,6 +10,7 @@ from __future__ import annotations import contextlib import io import json +import os import sys import tempfile import unittest @@ -135,6 +136,53 @@ class Context(unittest.TestCase): self.assertTrue(started.called) +class BrokenEarlierConfig(unittest.TestCase): + """#459: a new copy of Strata set up like an earlier install skips an earlier config that does not parse (an + empty strata-*.json crashed START-HERE with JSONDecodeError) and goes on as a fresh install; configs are written + whole (a temporary file moved over the old one).""" + RAM64, GPU32 = PROFILES["64GB-1x32GB"] + + def setup_with(self, files): + with tempfile.TemporaryDirectory() as d: + for i, (name, text) in enumerate(files): # in order, oldest first + (Path(d) / name).write_text(text, encoding="utf-8") + os.utime(Path(d) / name, (1_700_000_000 + i, 1_700_000_000 + i)) + return install(self.RAM64, self.GPU32, [], extra=[ + mock.patch.object(setup, "other_installs", lambda settings: [Path(d)]), + mock.patch.object(setup, "start", mock.Mock(return_value=0))]) + + def test_an_empty_config_is_skipped(self): + for text, why in (("", "the file is empty"), ("{\"args\": [", "not valid JSON"), ("[1]", "not a JSON object")): + with self.subTest(text=text): + code, out, cfg, _ = self.setup_with([("strata-iq3_s.json", text)]) + self.assertEqual(code, 0, out) + self.assertIn("skipped the earlier config ", out) + self.assertIn(f"strata-iq3_s.json ({why}): setting this copy up without it", out) + self.assertNotIn("Found your earlier install", out) + self.assertIsNotNone(cfg) # the fresh install's config + + def test_the_newest_readable_config_is_used(self): + good = json.dumps({"args": ["--max-context", "262144", "--kv", "int8"], "port": 8080}) + code, out, cfg, _ = self.setup_with([("strata-iq3_s.json", good), ("strata-q2_0.json", "")]) + self.assertEqual(code, 0, out) + self.assertIn("strata-q2_0.json (the file is empty)", out) + self.assertIn("Found your earlier install", out) + self.assertIn("(iq3_s)", out) + self.assertEqual(arg(cfg, "--max-context"), "262144") + + def test_write_config_leaves_no_partial_file(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-iq3_s.json" + p.write_text("old", encoding="utf-8") + setup.write_config(p, {"args": ["--kv", "int8"]}) + self.assertEqual(p.read_text(encoding="utf-8"), json.dumps({"args": ["--kv", "int8"]}, indent=1)) + self.assertEqual([f.name for f in Path(d).iterdir()], ["strata-iq3_s.json"]) # no .tmp left + with mock.patch.object(Path, "write_text", side_effect=OSError(28, "No space left on device")): + with self.assertRaises(OSError): + setup.write_config(p, {"args": []}) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), {"args": ["--kv", "int8"]}) # kept whole + + class LowRamGpus(unittest.TestCase): """S2/S3 (#364 #384): one GPU recommended in the low-RAM mode, all of them when asked for.""" From cd49a498c816196b42179a96252ecdbbb4c271cc Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 09:33:17 +0200 Subject: [PATCH 3/7] setup (--backend hip): a system ROCm without the HIP development files falls back to the wheels (#446) rocm_root took /opt/rocm when bin/hipcc and lib/libhipblas.so* were there and the version was 7.0 or newer. A runtime-only ROCm 7 (no -dev packages) has both, and the engine's cmake configure then failed on the missing hip-lang package. The system ROCm now also needs lib/cmake/hip-lang/hip-lang-config.cmake (lib, lib64 or the multiarch lib folder, where CMake looks) and include/hip/hip_runtime.h; without them setup warns, naming what is missing, and takes the TheRock wheels path, as it already does for a ROCm older than 7.0. --- setup.py | 24 +++++++++++++++++++----- tools/test_setup_amd.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/setup.py b/setup.py index c8aba719..a8898796 100644 --- a/setup.py +++ b/setup.py @@ -1338,18 +1338,32 @@ def rocm_version(root): return None +def rocm_dev_missing(sysroot: Path) -> list: + """#446: the HIP development files the engine's build needs that a system ROCm lacks (a runtime-only install has + hipcc and libhipblas but not these, and cmake's enable_language(HIP) then fails on the hip-lang package).""" + lang = "cmake/hip-lang/hip-lang-config.cmake" # where CMake's HIP support looks for it + need = {"lib/" + lang: [sysroot / d / lang for d in ("lib", "lib64", "lib/x86_64-unknown-linux-gnu")], + "include/hip/hip_runtime.h": [sysroot / "include" / "hip" / "hip_runtime.h"]} + return [name for name, paths in need.items() if not any(p.is_file() for p in paths)] + + def rocm_root(archs): """ROCm for compiling and running the HIP engine for `archs` (one arch or a list: the cards of a layer split): - (root, library folders). A system ROCm 7 with hipcc and hipBLAS, else AMD's TheRock wheels (ROCM_VERSION, from the - card family's index) installed into .venv.""" + (root, library folders). A system ROCm 7 with hipcc, hipBLAS and the HIP development files (#446), else AMD's + TheRock wheels (ROCM_VERSION, from the card family's index) installed into .venv.""" archs = [archs] if isinstance(archs, str) else list(archs) sysroot = Path(os.environ.get("ROCM_PATH") or "/opt/rocm") if (sysroot / "bin" / "hipcc").exists() and list((sysroot / "lib").glob("libhipblas.so*")): ver = rocm_version(sysroot) - if ver is None or ver >= ROCM_SYSTEM_MIN: + missing = rocm_dev_missing(sysroot) + if (ver is None or ver >= ROCM_SYSTEM_MIN) and not missing: return sysroot, [str(sysroot / "lib")] - warn(f"the ROCm in {sysroot} is {ver[0]}.{ver[1]}; Strata needs {ROCM_SYSTEM_MIN[0]}.{ROCM_SYSTEM_MIN[1]} or " - "newer: using AMD's wheels in .venv instead") + if ver is not None and ver < ROCM_SYSTEM_MIN: + warn(f"the ROCm in {sysroot} is {ver[0]}.{ver[1]}; Strata needs {ROCM_SYSTEM_MIN[0]}.{ROCM_SYSTEM_MIN[1]} " + "or newer: using AMD's wheels in .venv instead") + else: # #446: a runtime-only ROCm (no -dev packages): cmake would fail + warn(f"the ROCm in {sysroot} has no HIP development files ({', '.join(missing)}): using AMD's wheels in " + ".venv instead (or install them, e.g. AMD's amdrocm-core-dev package for your ROCm and card)") indexes = list(dict.fromkeys(rocm_index(a) for a in archs)) if len(indexes) > 1: # TheRock's wheels hold one GPU family's libraries fail(f"cards of two GPU families ({', '.join(archs)}) need a system ROCm 7 (in /opt/rocm): AMD's Python " diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index fdca0eb4..940169b9 100644 --- a/tools/test_setup_amd.py +++ b/tools/test_setup_amd.py @@ -117,6 +117,40 @@ class GpuLists(unittest.TestCase): else: setup.os.environ["ROCM_PATH"] = old + def test_runtime_only_system_rocm_falls_back_to_the_wheels(self): + """#446: a system ROCm 7 with hipcc and libhipblas but no HIP development files (no hip-lang CMake package, no + hip_runtime.h) is not used for the build: a warning says what is missing and the wheels path follows (here + it stops at the two-family check, which only the wheels path makes); with the files it is used as before.""" + said = [] + setup.say = lambda msg="": said.append(msg) # tearDown puts the real one back + with tempfile.TemporaryDirectory() as d: + sysroot = Path(d) + for rel, text in (("bin/hipcc", ""), ("lib/libhipblas.so.3", ""), + ("include/rocm-core/rocm_version.h", + "#define ROCM_VERSION_MAJOR 7\n#define ROCM_VERSION_MINOR 14\n")): + (sysroot / rel).parent.mkdir(parents=True, exist_ok=True) + (sysroot / rel).write_text(text) + with mock.patch.dict(setup.os.environ, {"ROCM_PATH": d}): + with self.assertRaises(SystemExit): + setup.rocm_root(["gfx1100", "gfx1201"]) + self.assertIn(f"the ROCm in {sysroot} has no HIP development files (lib/cmake/hip-lang/hip-lang-" + "config.cmake, include/hip/hip_runtime.h): using AMD's wheels", "\n".join(said)) + self.assertIn("two GPU families", "\n".join(said)) + for lib in ("lib64", "lib"): # either place CMake looks + with self.subTest(lib=lib): + cfg = sysroot / lib / "cmake/hip-lang/hip-lang-config.cmake" + cfg.parent.mkdir(parents=True, exist_ok=True) + cfg.write_text("") + said.clear() + with self.assertRaises(SystemExit): + setup.rocm_root(["gfx1100", "gfx1201"]) + self.assertIn("(include/hip/hip_runtime.h)", "\n".join(said)) + (sysroot / "include/hip").mkdir(parents=True, exist_ok=True) + (sysroot / "include/hip/hip_runtime.h").write_text("") + self.assertEqual(setup.rocm_root(["gfx1100", "gfx1201"]), (sysroot, [str(sysroot / "lib")])) + cfg.unlink() + (sysroot / "include/hip/hip_runtime.h").unlink() + def test_build_for_every_arch(self): """build_engine_hip compiles for the set of the chosen cards' archs and records it in BUILD.json.""" calls = {} From 0e4c3e8727c17355f2a8db333a02182b1a9f604a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 09:35:26 +0200 Subject: [PATCH 4/7] calibrate: the engine's arguments come from the server's engine_args; a failed tuning says why (#447) tools/calibrate.py read any "gpu" list as a layer split and added --layer-split auto, so a one-card config with a helper card for the expert tier ("gpu": [0] + --expert-cache-device1) was refused by the engine before it read a weight, a "0,2" string never got its split, and split_skip_if_fits was ignored. The tuner now builds the arguments with serve.server.engine_args, the same as a normal start. When the tuning fails, setup prints the engine's own last error line from the log (only lines written during the tuning), and says the failure again where it is not lost: before --calibrate starts the model, and in the "All set." summary of an install that tuned. --- setup.py | 19 ++++++++-- tools/calibrate.py | 28 ++++++++++++--- tools/test_calibrate.py | 77 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 118 insertions(+), 6 deletions(-) diff --git a/setup.py b/setup.py index a8898796..81e60e34 100644 --- a/setup.py +++ b/setup.py @@ -2295,10 +2295,17 @@ def calibrate_config(cfg_path: Path) -> bool: say() say(" Tuning Strata for this PC: the output speed is measured with a few engine settings (the PCIe share, the") say(" draft depth, the CPU threads). It takes about 5-10 minutes; the PC is busy meanwhile.") + try: + since = os.path.getsize(cfg["log"]) if cfg.get("log") and os.path.isfile(cfg["log"]) else 0 + except OSError: + since = 0 try: res = CAL.run(cfg, say=say) except Exception as e: # never stops an install: the defaults stay warn(f"the tuning did not finish ({e}): the default settings stay") + why = CAL.engine_error(cfg.get("log"), since) # #447: the engine's own reason, not only "see the log" + if why: + say(f" the engine said: {why}") return False cfg["args"] = CAL.apply(cfg["args"], res["settings"]) write_config(cfg_path, cfg) @@ -2685,7 +2692,10 @@ def main() -> int: for i, c in enumerate(have, 1): say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") pick_cfg = have[int(ask("Tune which one?", [str(i) for i in range(1, len(have) + 1)], "1", a.yes)) - 1] - calibrate_config(pick_cfg) + if not calibrate_config(pick_cfg): # #447: said again where it is not lost above the start + say() + warn("this PC is NOT tuned: the tuning failed (the reason is above); the model " + + ("keeps" if a.no_start else "starts with") + " the default settings") return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab}) if have and not (a.setup or a.model or a.family or a.check or a.no_start): @@ -3263,7 +3273,9 @@ def main() -> int: if cal is None and not hip and not a.no_start and not a.yes and ask( "Tune Strata for this PC now? It measures a few engine settings (about 5-10 minutes; the PC is busy " "meanwhile; later: START-HERE --calibrate)", ["y", "n"], "y", a.yes) == "y": - calibrate_config(cfg_path) + tuned = calibrate_config(cfg_path) + else: + tuned = None # not asked for: nothing to repeat below ok(f"start script: {script.name}") say() @@ -3276,6 +3288,9 @@ def main() -> int: say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away") if vision != "none": say(" Images: send them in the chat page, in chat.py (/image ) or over the API") + if tuned is False: # #447: a failed tuning is repeated here, not only above + say(" Tuning: FAILED (the reason is above): the default settings stay - " + f"{'START-HERE.bat' if WIN else './setup.sh'} --calibrate tries again") if a.no_start: return 0 return start(cfg_path, port) diff --git a/tools/calibrate.py b/tools/calibrate.py index b237c93b..77900562 100644 --- a/tools/calibrate.py +++ b/tools/calibrate.py @@ -119,10 +119,30 @@ def run(cfg: dict, say=print, start_engine=None) -> dict: tok = ST.Tokenizer(toks, (tpath / "merges.txt").read_text(encoding="utf-8").split("\n"), json.loads((tpath / "token_type.json").read_text())) ids_list = [chat_ids(tok, p) for p in PROMPTS] - args = list(cfg["args"]) - if isinstance(cfg.get("gpu"), list) and "--layer-split" not in args: # several cards: measured as it runs - args += ["--layer-split", str(cfg.get("layer_split") or "auto")] - return measure(args, ids_list, start_engine, say) + return measure(engine_args(cfg), ids_list, start_engine, say) + + +def engine_args(cfg: dict) -> list[str]: + """The arguments the server starts this config's engine with (serve.server.engine_args), so the tuning measures + the engine as it runs. #447: this used to read any "gpu" list as a layer split and add --layer-split auto, which + broke a one-card config with a helper card for the expert tier ("gpu": [0] + --expert-cache-device1: the engine + refuses a split that leaves no card without a stage), missed the "0,2" spelling, and ignored split_skip_if_fits.""" + from serve.server import engine_args as server_args + return server_args(cfg) + + +def engine_error(log: str | None, since: int = 0) -> str | None: + """#447: the engine's own reason for a failed start - the last line of its log written after byte `since` that is + its own ("strata ..." or "ERR ..."), else the last line there; None without a log or a new line.""" + if not log: + return None + try: + with open(log, "rb") as f: + f.seek(since) + lines = [x.strip() for x in f.read()[-16384:].decode("utf-8", "replace").splitlines() if x.strip()] + except OSError: + return None + return next((x for x in reversed(lines) if x.startswith(("strata", "ERR"))), lines[-1] if lines else None) def measure(base_args: list[str], ids_list, start_engine, say=print) -> dict: diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py index c97d348f..a03286c5 100644 --- a/tools/test_calibrate.py +++ b/tools/test_calibrate.py @@ -11,6 +11,7 @@ import sys import tempfile import unittest from pathlib import Path +from unittest import mock ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tools")) @@ -91,6 +92,53 @@ class Calibrate(unittest.TestCase): self.assertIsNone(CAL.arg_value(b, "--pool-workers")) self.assertEqual(b.count("--spec-min-p"), 1) + def test_engine_args_are_the_servers(self): + # #447: a "gpu" list is a layer split only with two or more cards; "0,2" is one too; split_skip_if_fits counts + helper = {"args": BASE + ["--expert-cache-device1", "1800"], "gpu": [0], "env": {"CUDA_VISIBLE_DEVICES": "0,1"}} + self.assertEqual(CAL.engine_args(helper), helper["args"]) # one stage + a helper card: no split + self.assertEqual(CAL.engine_args({"args": BASE, "gpu": 1}), BASE) + self.assertEqual(CAL.engine_args({"args": BASE, "gpu": [0, 2]}), BASE + ["--layer-split", "auto"]) + self.assertEqual(CAL.engine_args({"args": BASE, "gpu": "0,2", "layer_split": "18"}), + BASE + ["--layer-split", "18"]) + self.assertEqual(CAL.engine_args({"args": BASE, "gpu": [0, 1], "split_skip_if_fits": True}), + BASE + ["--layer-split", "auto", "--split-skip-if-fits"]) + own = BASE + ["--layer-split", ""] # the config's own value wins + self.assertEqual(CAL.engine_args({"args": own, "gpu": [0, 1]}), own) + + def test_run_measures_with_the_servers_args(self): + with tempfile.TemporaryDirectory() as d: + tok = Path(d) + (tok / "vocab.json").write_text(json.dumps({"a": 0, "b": 1})) + (tok / "merges.txt").write_text("") + (tok / "token_type.json").write_text(json.dumps([1, 1])) + seen = [] + saved = CAL.measure + CAL.measure = lambda args, ids_list, start_engine, say=print: seen.append(args) or {} + fake = type("ST", (), {"Tokenizer": lambda *a: type("T", (), {"encode": lambda s, t, **k: [0]})()}) + try: + with mock.patch.dict(sys.modules, {"strata_tokenizer": fake}): + CAL.run({"tokenizer": d, "args": list(BASE), "gpu": [0]}, start_engine=lambda a: None) + finally: + CAL.measure = saved + self.assertEqual(seen, [BASE]) + + def test_engine_error(self): + with tempfile.TemporaryDirectory() as d: + log = Path(d) / "strata-x.log" + log.write_text("strata generate: an old error\n", encoding="utf-8") + since = log.stat().st_size + with open(log, "a", encoding="utf-8") as f: + f.write("loading ...\nstrata generate: --expert-cache-remote with a layer split needs a GPU that runs " + "no stage (2 visible, 2 used by the split)\n\n") + self.assertEqual(CAL.engine_error(str(log), since), "strata generate: --expert-cache-remote with a layer " + "split needs a GPU that runs no stage (2 visible, 2 used by the split)") + with open(log, "a", encoding="utf-8") as f: + f.write("Segmentation fault\n") + self.assertIn("--expert-cache-remote", CAL.engine_error(str(log), since)) # the engine's own line first + self.assertEqual(CAL.engine_error(str(log), log.stat().st_size), None) # nothing new since + self.assertIsNone(CAL.engine_error(None)) + self.assertIsNone(CAL.engine_error(str(Path(d) / "missing.log"))) + def test_worker_candidates(self): self.assertEqual(CAL.worker_candidates(6), [6, 4, 3]) self.assertEqual(CAL.worker_candidates(23), [23, 15, 12]) @@ -152,6 +200,35 @@ class SetupIntegration(unittest.TestCase): self.assertEqual(json.loads(cfg_path.read_text())["args"], BASE) self.assertIsNone(self.S.saved_calibration({"args": BASE, "model_name": "m"})) + def test_failed_calibration_says_the_engines_reason(self): + # #447: the engine's last error line is printed, and the --calibrate run repeats the failure before it starts + import contextlib + import io + log = Path(self.tmp.name) / "strata-q2_0.log" + log.write_text("strata generate: an error of an earlier start\n", encoding="utf-8") + cfg_path = Path(self.tmp.name) / "strata-q2_0.json" + cfg_path.write_text(json.dumps({"exe": "x", "args": list(BASE), "model_name": "m", "log": str(log)})) + + def boom(*a, **k): + with open(log, "a", encoding="utf-8") as f: + f.write("strata generate: --expert-cache-remote with a layer split needs a GPU that runs no stage\n") + raise RuntimeError(f"the engine exited before it was ready (see {log})") + CAL.run = boom + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertFalse(self.S.calibrate_config(cfg_path)) + self.assertIn("the engine said: strata generate: --expert-cache-remote with a layer split", out.getvalue()) + self.assertNotIn("an earlier start", out.getvalue()) + out = io.StringIO() + with mock.patch.object(self.S, "ROOT", Path(self.tmp.name)), \ + mock.patch.object(self.S, "data_folder", lambda d: (Path(self.tmp.name) / "data", [])), \ + mock.patch.object(self.S, "update_installed_engine", lambda *a: None), \ + mock.patch.object(sys, "argv", ["setup.py", "--calibrate", "--no-start"]), \ + contextlib.redirect_stdout(out): + self.assertEqual(self.S.main(), 0) + self.assertIn("this PC is NOT tuned: the tuning failed (the reason is above); the model keeps the default " + "settings", out.getvalue()) + if __name__ == "__main__": unittest.main() From 95f28602313479f2abd87d4f9f5d8ab8f6753f15 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 09:36:41 +0200 Subject: [PATCH 5/7] /metrics: each request's speculative draft counts, and their sums in the totals (#457) The server already read drafts_offered / drafts_accepted from the engine's DONE line but only returned them in a response's timings (draft_n / draft_n_accepted). Each /metrics request entry now carries both (null when the engine did not report them) and the totals keep their running sums since the server started, so a dashboard such as llm-visuals can show the acceptance. Additive: no existing field changes. --- docs/DETAILS.md | 3 ++- serve/server.py | 10 ++++++++-- serve/test_server.py | 45 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index c85f5f29..e0737ce8 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -159,7 +159,8 @@ RTX 5070, against ~3 tokens/s before these changes. RAM copy, blobs and MB from the files, the time spent reading them; `routing prefetch`: how many of the file reads had been warmed). The server log has the same per request (`expert tiers: GPU ... hits ...; RAM ... blobs, files ... blobs ... MB read`), and `GET /metrics` lists `ram_blobs`, `file_blobs` and `file_mb` for each recent request (with -engine 0.1.31 or newer). +engine 0.1.31 or newer). It also lists each request's speculative drafts, `drafts_offered` and `drafts_accepted` +(`null` when the engine did not report them), and their sums since the server started in `totals` (#457). Time to first token is prompt length / prompt speed: with Q2_0 about 4 s at 4K, 25 s at 32K, under 2 minutes at 128K and 4.5 minutes at 262K (engine 0.1.13 made long prompts about twice as fast, below). diff --git a/serve/server.py b/serve/server.py index ec736b0f..f611530b 100644 --- a/serve/server.py +++ b/serve/server.py @@ -765,7 +765,8 @@ class Service: self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics) # since the server started (the Monitor's totals, issue #35) self.totals = {"since": time.time(), "requests": 0, "prompt_tokens": 0, "reused": 0, "output_tokens": 0, - "prompt_ms": 0.0, "decode_ms": 0.0} + "prompt_ms": 0.0, "decode_ms": 0.0, + "drafts_offered": 0, "drafts_accepted": 0} # #457: the MTP drafts, summed where reported self.last_timings = None # the last finished request's, llama.cpp's names (/v1/status) self.last_request_at = None # when a request last started or finished self.started_at = time.time() @@ -1338,7 +1339,10 @@ class Service: "decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1) if n and last.get("generated") and last.get("decode_ms") else None, "hit_rate": hit_rate, "ram_blobs": last.get("ram_blobs"), - "file_blobs": last.get("file_blobs"), "file_mb": last.get("file_mb")}) + "file_blobs": last.get("file_blobs"), "file_mb": last.get("file_mb"), + # #457: the speculative drafts from the DONE line (None: the engine did not say) + "drafts_offered": last.get("drafts_offered"), + "drafts_accepted": last.get("drafts_accepted")}) t = self.totals t["requests"] += 1 t["prompt_tokens"] += len(ids) @@ -1346,6 +1350,8 @@ class Service: t["output_tokens"] += n t["prompt_ms"] += last.get("prompt_ms") or 0.0 t["decode_ms"] += last.get("decode_ms") or 0.0 + t["drafts_offered"] += last.get("drafts_offered") or 0 + t["drafts_accepted"] += last.get("drafts_accepted") or 0 fresh = getattr(self.engine, "last", None) if fresh is not None and fresh is not before: # the engine's clock for THIS request timings = request_timings(len(ids), n, last) diff --git a/serve/test_server.py b/serve/test_server.py index ad2e9831..76ac5e5e 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -747,6 +747,51 @@ class EngineDeath(unittest.TestCase): httpd.server_close() +class DoneLineEngine(MockEngine): + """The mock engine whose `last` comes from a DONE line, parsed as StrataEngine parses it.""" + + def __init__(self, *a, done_lines=(), **kw): + super().__init__(*a, **kw) + self.done_lines = list(done_lines) + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + try: + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + finally: + StrataEngine._parse_done(self, self.done_lines.pop(0)) + + +class DraftCounts(unittest.TestCase): + """#457: GET /metrics gives each request's speculative draft counts (offered / accepted, from the engine's DONE + line; None when the line has no such fields) and their running sums in the totals.""" + + def test_drafts_in_history_and_totals(self): + tok = ByteTokenizer() + engine = DoneLineEngine(tok, "\n\nok", max_context=CTX, done_lines=[ + "DONE 4 20 40.0 30.0 stop 7 12 0", # 7 of 12 drafts accepted + "DONE 4 20 40.0 30.0 stop", # an engine that reports no drafts + "DONE 4 20 40.0 30.0 stop 3 5 0 9 10"]) + svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.assertEqual((svc.totals["drafts_offered"], svc.totals["drafts_accepted"]), (0, 0)) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + for _ in range(3): + body = json.dumps({"model": "m", "max_tokens": 10, "messages": [{"role": "user", "content": "hi"}]}) + with urllib.request.urlopen(urllib.request.Request(base + "/v1/chat/completions", data=body.encode(), + headers={"Content-Type": "application/json"}), + timeout=30) as r: + self.assertEqual(r.status, 200) + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + m = json.loads(r.read()) + finally: + httpd.shutdown() + httpd.server_close() + rows = m["requests"] # newest first + self.assertEqual([(r["drafts_offered"], r["drafts_accepted"]) for r in rows], [(5, 3), (None, None), (12, 7)]) + self.assertEqual((m["totals"]["drafts_offered"], m["totals"]["drafts_accepted"]), (17, 10)) + + class LiveRate(unittest.TestCase): """The Monitor's Speed readout: live.tok_s is a rate, and a request that never got a DONE keeps no counters. From 6cc16bee092d13bff875e9b5ae00209ae1b36f4e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 09:38:48 +0200 Subject: [PATCH 6/7] setup (--gguf-dir): GGUFs Strata cannot run are named as such, with the --family/--model to use (#444) With Unsloth's UD-IQ3_XXS or UD-Q2_K_XL in the folder, setup either said only "has no IQ3_XXS model file" (--family unsloth --model IQ3_XXS) or took the UD-IQ3_XXS file for the GSQ-RCO IQ3_XXS by the size in its name. Now: - a chosen shard whose name is a quantization setup has no size for (UD-IQ3_XXS, UD-Q2_K_XL, a K-quant) stops with " is UD-IQ3_XXS, a GGUF Strata cannot run" and what Strata runs: ISTA-DASLab's GSQ-RCO files (and Swift 1.5's and the Coder's) and Unsloth's UD-Q4_K_XL only; - a folder without the chosen file but with other GGUFs lists the ones Strata cannot use and the --family/--model of the ones it can (an empty folder keeps check_shards' "missing"); - a size the family does not have names the families that do (--family qwen --model IQ3_XXS), and with --gguf-dir also what Strata runs. --- setup.py | 59 ++++++++++++++++++++++++++++++++++++- tools/test_setup_choices.py | 58 ++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 81e60e34..c91ca2f1 100644 --- a/setup.py +++ b/setup.py @@ -797,6 +797,55 @@ def gguf_dir_shards(folder: Path, fam: dict, model: str) -> list[Path]: return [first.with_name("%s-%05d-of-%05d.gguf" % (stem, i, total)) for i in range(1, total + 1)] +# #444: the quantization in a GGUF's name (Unsloth's UD-IQ3_XXS, a K-quant's Q2_K_XL, a GSQ-RCO IQ3_S, ...) +GGUF_QUANT = re.compile(r"(? str | None: + """#444: the quantization a GGUF's name says, when it is one Strata cannot run (not a setup size); else None.""" + m = GGUF_QUANT.search(name) + return m.group(1) if m and m.group(1).upper() not in MODELS and not name.lower().startswith("mmproj") else None + + +def gguf_choice(name: str) -> tuple | None: + """#444: (--family, --model) whose published first shard this file is, or None (the Coder's IQ1_M is named like + the original's sizes: the size tells them apart).""" + for f, d in FAMILIES.items(): + for m in MODELS: + if f in MODELS[m].get("families", ("qwen", "swift")) and name == d["file"].format(q=m, i=1): + return f, m + return None + + +def gguf_dir_problem(folder: Path, first: Path, fam: dict, model: str) -> tuple | None: + """#444: (message, hint) when --gguf-dir has no file setup can use for this choice: the chosen shard is a GGUF + Strata cannot run (Unsloth's UD-IQ3_XXS taken for IQ3_XXS by its name), or it is missing and the folder holds + other GGUFs - then the hint names the --family/--model of the usable ones. None otherwise (a missing shard in a + folder without GGUFs stays check_shards' "missing").""" + bad = gguf_unsupported(first.name) if first.exists() else None + if bad: + return f"{first.name} is {bad}, a GGUF Strata cannot run", SUPPORTED_GGUFS + if first.exists(): + return None + firsts = sorted(p.name for p in folder.glob("*.gguf") + if not p.name.lower().startswith("mmproj") and (not SHARD_NAME.search(p.name) + or SHARD_NAME.search(p.name).group(1) == "00001")) + usable = list(dict.fromkeys(c for c in map(gguf_choice, firsts) if c)) + unusable = [n for n in firsts if gguf_unsupported(n)] + if not usable and not unusable: + return None + hint = SUPPORTED_GGUFS + if unusable: + hint += ".\n Not usable here: " + ", ".join(unusable) + if usable: + hint += ".\n Usable here: " + ", ".join(f"--family {f} --model {m}" for f, m in usable) + return f"{folder} has no {fam['title']} {model} file", hint + + def verify_sha256(s: Path, size: int, sha: str) -> None: """A shard's size and SHA-256 against the pinned values (the Unsloth file); the result is kept in its finish mark, so the ~5 minutes of hashing 111 GB happen once. A wrong file is deleted, so the next run downloads it again.""" @@ -2844,7 +2893,12 @@ def main() -> int: say() names = [m for m in MODELS if family in MODELS[m].get("families", ("qwen", "swift"))] if a.model and a.model not in names: - fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names)) + # #444: say which family has that size, and (with --gguf-dir) which files Strata can run at all + elsewhere_fams = [f for f in FAMILIES if f in MODELS[a.model].get("families", ("qwen", "swift"))] + fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names) + + (f" (or {a.model}: " + ", ".join(f"--family {f} --model {a.model}" for f in elsewhere_fams) + ")" + if elsewhere_fams else "") + + (f".\n {SUPPORTED_GGUFS}" if a.gguf_dir else "")) for i, m in enumerate(names, 1): d = MODELS[m] fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}" @@ -3025,6 +3079,9 @@ def main() -> int: models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag shards = gguf_dir_shards(models_dir, fam, model) if a.gguf_dir else \ [models_dir / fam["file"].format(q=model, i=i) for i in range(1, fam.get("shards", 2) + 1)] + problem = gguf_dir_problem(models_dir, shards[0], fam, model) if a.gguf_dir else None + if problem: # #444: files Strata cannot run, or another choice's files + fail(*problem) if not a.gguf_dir and not all(sh.exists() and done(sh) for sh in shards): for r in elsewhere: # already downloaded in a Strata folder on another drive cand = [r / "models" / tag / sh.name for sh in shards] diff --git a/tools/test_setup_choices.py b/tools/test_setup_choices.py index 756a6d4a..cebc2f77 100644 --- a/tools/test_setup_choices.py +++ b/tools/test_setup_choices.py @@ -92,6 +92,64 @@ class GgufDirShards(unittest.TestCase): self.assertEqual(self.shards(["a-00001-of-00002.gguf", "b-00001-of-00002.gguf"]), want) # ambiguous +class GgufDirUnsupported(unittest.TestCase): + """#444: --gguf-dir with GGUFs Strata cannot run (Unsloth's UD-IQ3_XXS, UD-Q2_K_XL) says so, names the files it + runs (ISTA-DASLab's GSQ-RCO, the Coder's, Unsloth's UD-Q4_K_XL) and the --family/--model of the usable ones.""" + UD = ["Qwen3.8-Flash-Next-UD-IQ3_XXS-%05d-of-00003.gguf" % i for i in range(1, 4)] + \ + ["Qwen3.8-Flash-Next-UD-Q2_K_XL-%05d-of-00003.gguf" % i for i in range(1, 4)] + + def problem(self, names, family="qwen", model="IQ3_XXS"): + with tempfile.TemporaryDirectory() as d: + for n in names: + (Path(d) / n).write_bytes(b"") + fam = setup.FAMILIES[family] + first = setup.gguf_dir_shards(Path(d), fam, model)[0] + p = setup.gguf_dir_problem(Path(d), first, fam, model) + return p and (p[0].replace(d, ""), p[1]) + + def test_quant_names(self): + for name, want in (("Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf", "UD-IQ3_XXS"), + ("Qwen3.8-Flash-Next-UD-Q2_K_XL-00001-of-00003.gguf", "UD-Q2_K_XL"), + ("model-Q4_K_M.gguf", "Q4_K_M"), + ("Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", None), + ("Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", None), + ("my-IQ3_XXS-00001-of-00003.gguf", None), ("mmproj-F16.gguf", None), + ("a-00001-of-00002.gguf", None)): + self.assertEqual(setup.gguf_unsupported(name), want, name) + + def test_an_unsloth_ud_file_is_not_taken_for_a_gsq_rco_size(self): + msg, hint = self.problem(self.UD) # IQ3_XXS: UD-IQ3_XXS has the size in its name + self.assertEqual(msg, "Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf is UD-IQ3_XXS, a GGUF Strata " + "cannot run") + self.assertIn("ISTA-DASLab's GSQ-RCO files", hint) + self.assertIn("Unsloth's UD-Q4_K_XL only", hint) + + def test_a_folder_without_the_choice_names_what_is_there(self): + gsq = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-%05d-of-00002.gguf" % i for i in (1, 2)] + msg, hint = self.problem(self.UD + gsq, "unsloth", "UD-Q4_K_XL") + self.assertEqual(msg, " has no Qwen3.8-Flash-Next (Unsloth) UD-Q4_K_XL file") + self.assertIn("Not usable here: Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf, " + "Qwen3.8-Flash-Next-UD-Q2_K_XL-00001-of-00003.gguf", hint) + self.assertIn("Usable here: --family coder --model IQ1_M", hint) + + def test_usable_folders_are_left_alone(self): + good = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-%05d-of-00002.gguf" % i for i in (1, 2)] + self.assertIsNone(self.problem(good + self.UD)) + self.assertIsNone(self.problem(["my-IQ3_XXS-%05d-of-00003.gguf" % i for i in (1, 2, 3)])) + self.assertIsNone(self.problem([])) # nothing there: check_shards' "missing", as before + + def test_the_size_of_another_family(self): + from test_setup_golden import PROFILES, install + ram, found = PROFILES["64GB-1x32GB"] + with tempfile.TemporaryDirectory() as d: + code, out, _, _ = install(ram, found, ["--gguf-dir", d, "--family", "unsloth", "--model", "IQ3_XXS"]) + self.assertEqual(code, 1) + self.assertIn("has no IQ3_XXS model file", out) + self.assertIn("choose one of: UD-Q4_K_XL (or IQ3_XXS: --family qwen --model IQ3_XXS, --family swift --model " + "IQ3_XXS)", out) + self.assertIn("Strata runs ISTA-DASLab's GSQ-RCO files", out) + + class ExperimentalSm60(unittest.TestCase): """#295: Pascal (6.x) and Volta (7.0) only with STRATA_EXPERIMENTAL_SM60=1, built with -DSTRATA_EXPERIMENTAL_SM60=ON and a CUDA 12.x toolkit; nothing changes without the variable.""" From 6f8536aed13bde3c64551141c663e32bcacf26ed Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 09:39:14 +0200 Subject: [PATCH 7/7] docs: the Coder is weaker outside code, Chinese/CJK text included; the unpruned sizes for that (#438) README and docs/MODELS.md said only "Weaker outside coding". #438 measured Chinese answers wrong or looping on the Coder where English was fine; both now say plainly that this includes Chinese and other CJK text and point to the sizes that keep every expert (Q2_0, IQ2_XS, IQ3_S). --- README.md | 3 ++- docs/MODELS.md | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c15b378e..10812dcb 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,8 @@ is faster, larger is a bit smarter. | **96 GB or more** | **IQ3_S**, or Unsloth's 4-bit (experimental) | room for the largest sizes with everything else open | - **[Coder](docs/MODELS.md#coder)** - a coding version with half of the experts removed: 91% of the full model's - SWE-bench Verified score (by its authors), fits 32 GB of RAM. Weaker outside coding. + SWE-bench Verified score (by its authors), fits 32 GB of RAM. Weaker outside code, including Chinese and other + CJK text (#438): for those, take Q2_0, IQ2_XS or IQ3_S, which keep every expert. - **[Swift 1.5](docs/MODELS.md#swift-15)** - a fine-tune that thinks much shorter before it answers, so you get the answer sooner, at about the same quality. - **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)** (experimental) - the closest to the full diff --git a/docs/MODELS.md b/docs/MODELS.md index 4f3a7b6c..fb411700 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -94,7 +94,10 @@ The original, in all four sizes. With images, and with the half of the experts removed, keeping the ones that code, tool use and images need (91% of the full model's SWE-bench Verified score, 99% of LiveCodeBench, by its authors). One size (IQ1_M: its experts stored like IQ3_S): shard 1 is **29.6 GB**, so it fits a PC with **32 GB of RAM**, runs 262K context on 64 GB, and reads long prompts the fastest of -all. Weaker outside coding. More: [details](DETAILS.md#or-the-coder-half-the-experts-for-code). +all. It is weaker outside code, and that includes Chinese and other CJK text (#438: Chinese answers came out wrong +or looping where English was fine). For general chat or CJK text, take a size that keeps every expert: Q2_0, +IQ2_XS or IQ3_S. +More: [details](DETAILS.md#or-the-coder-half-the-experts-for-code). ``` START-HERE.bat --setup --family coder