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/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/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 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/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 6869de7a..76ac5e5e 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 @@ -709,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. diff --git a/setup.py b/setup.py index cb7d1e4d..09950e2d 100644 --- a/setup.py +++ b/setup.py @@ -633,7 +633,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 @@ -823,6 +823,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.""" @@ -1391,18 +1440,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 " @@ -2158,7 +2221,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: @@ -2215,13 +2278,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: @@ -2308,13 +2397,20 @@ 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"]) - 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")} @@ -2354,7 +2450,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 @@ -2368,7 +2464,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 @@ -2389,7 +2485,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)] @@ -2412,7 +2508,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) @@ -2421,7 +2517,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): @@ -2526,7 +2622,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 @@ -2700,7 +2796,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): @@ -2849,7 +2948,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}" @@ -3030,6 +3134,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] @@ -3272,13 +3379,15 @@ 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( "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() @@ -3291,6 +3400,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() diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index ceb9d565..a00a6502 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 = {} 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.""" diff --git a/tools/test_setup_risk.py b/tools/test_setup_risk.py index 1fbb59de..5d567121 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."""