diff --git a/README.md b/README.md index 1c3c93b6..26282f49 100644 --- a/README.md +++ b/README.md @@ -149,7 +149,8 @@ More: [where your chats are stored](docs/INSTALL.md#where-things-are-stored), [t - **It says port 8080 is already in use.** Strata is already running - look for its window. More problems and their fixes: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Still stuck? Open an -[issue](https://github.com/Niko1221/Strata/issues) and attach `strata-.log` from the Strata folder. +[issue](https://github.com/Niko1221/Strata/issues) and attach `strata-.log` from the Strata folder. A +security problem? Report it privately: [SECURITY.md](SECURITY.md). ## How does it work? diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..94be4ead --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,44 @@ +# Security + +## Reporting a vulnerability + +Please report anything that should not be public until it is fixed **privately**, through GitHub's private +vulnerability reporting: the repository's **Security** tab, **Report a vulnerability** +([direct link](https://github.com/Niko1221/Strata/security/advisories/new)). Say what you found, how to reproduce it +(the request, the config keys involved, the Strata version), and what an attacker gains. We answer there, fix it in +a release, and credit you in the advisory unless you ask us not to. + +Ordinary hardening ideas and findings that are safe to discuss in public are welcome as an +[issue](https://github.com/Niko1221/Strata/issues) (#544 collects audit findings) or as a pull request, which we +review like our own code. + +Supported: the latest release. Fixes go into the next release, not into older ones. + +## What the server exposes + +Strata runs a model on your PC and serves it over HTTP (`serve/server.py`). Out of the box it is reachable from +this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAILS.md) ("From other devices", +"Host names", "Web pages without an API key", "Tools from MCP servers"). + +- **Where it listens.** `127.0.0.1` by default. `--host 0.0.0.0` (or `"host"` in `strata-.json`) opens it to + your network, and the server then warns when no API key is set. +- **API key.** `"api_key"` in the run config (or `STRATA_API_KEY`) is required on `/v1/*` and on every endpoint + that shows the model's state, requests or answers (`/status`, `/metrics`, `/settings`, `/mcp`, `/props`, `/slots`, + `/api/requests`, `/config`) and on every `POST`. It is compared in constant time. Set one before you open the + server to your network or put a tunnel in front of it. +- **Host check (DNS rebinding, 0.1.38).** Without an API key the server answers only requests whose `Host` is a name + it knows (`localhost`, an IP address, the address it listens on and, when it listens beyond this PC, this PC's + name). Others get 403. `"allowed_hosts"` adds names; with an API key the key decides. +- **Origin check (0.1.38).** Without an API key, a browser `POST` to `/v1/*` from another web site's page (it carries + an `Origin` header) gets 403 unless that origin is Strata's own page, `localhost`, an allowed host, or listed in + `"trusted_origins"` / `"cors_origins"`. Changing settings (`/settings`, and `/config`: the few run config keys the + page's Model settings may change - never the network, key, MCP or program keys), `/load` and `/unload` and the + MCP tools are accepted only as JSON from Strata's own page (or `"trusted_origins"`), so a page elsewhere cannot + change settings or run tools. +- **CORS** is off unless `"cors_origins"` lists origins, and then only for `/v1/*`. +- **MCP tools** are opt-in: only the servers you put in the run config, only for requests from Strata's own page + that ask for them. They run with your user's rights, and the model decides when to call them. +- **The request monitor** (`/api-monitor`, which keeps the last prompts and answers in memory) is off unless + `"api_monitor": true` is set. + +Strata has not had an outside security audit yet. diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 0b8d0cce..c4475a94 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -490,6 +490,14 @@ print(r.choices[0].message.content) server ends it there with `finish_reason` `"length"` and says so in its window: a model in a loop, or a broken state that answers one token forever (#606 saw 36,689 tokens of `!`). `"repeat_stop_tokens": N` in `strata-.json` sets the run length; `0` turns it off (for a request that really wants one token many times). +- **Changing the effort without re-reading the prompt (opt-in, 0.1.39, #458).** The effort's instruction is the + first thing in the prompt, so a request that only changes the effort (an agent's "think harder" switch, `none` for + a quick tool step) reads the whole conversation again. `"effort_position": "end"` in `strata-.json` renders + every request's prompt start as the default effort's and puts a `low` / `medium` effort in a short system turn + right before the answer (no thinking: the empty thinking block, as always); the engine (0.1.39+, which the server + checks) keeps its checkpoint in front of that turn, so the next request reuses the conversation whatever its + effort. The default (`"start"`) prompt is unchanged. The model sees a level that is not the default in another + place than it was trained with; how well it follows it there is not measured yet. - **Anthropic requests that don't ask for thinking (opt-in, 0.1.32, #278).** By default a `/v1/messages` request with no `"thinking"`, effort or budget thinks as the model's template does. `"anthropic_thinking": "on_request"` in `strata-.json` renders such a request without thinking - Anthropic's own rule, and what Claude Code's short @@ -544,6 +552,14 @@ print(r.choices[0].message.content) - **Model aliases** (0.1.32). `"aliases": ["qwen", "local-model"]` in `strata-.json` lists the model under those names too in `/v1/models` (each with its own `id`, and in the model's `aliases`), like llama-server's `--alias`; a request naming one is answered under that name. Any other name is still served, as before. +- **Model settings in the web page (0.1.39, #564).** The About tab's Model settings card shows and changes a few of + the keys above in `strata-.json`: the `sampling` defaults (temperature, top_p, top_k, min_p), + `reasoning_budget_tokens`, `fit_max_tokens`, `anthropic_thinking`, `effort_position`, `aliases`, `idle_unload_s`, + `lazy_load`, `engine_silence_s`, `api_monitor`, `open_browser` and `--vram-reserve-mib`. An empty field removes the + key (its default). Every other key of the file stays as it is, the earlier file is kept as + `strata-.json.bak`, and the model uses the change from its next start. Only Strata's own page can save + (JSON, the API key when one is set, as for the Chat settings); the network, key, MCP and program keys are not + editable there. - **From other devices on your network.** The server listens on your PC only (`127.0.0.1`) unless you say otherwise: run setup with `START-HERE.bat --setup --host 0.0.0.0 --api-key some-long-secret` (or add `"host": "0.0.0.0"` and `"api_key": "..."` to `strata-.json`). The server window then prints this PC's addresses @@ -605,6 +621,11 @@ INT8, Q4_0 and identity-layout K8V4 snapshots are supported; the K8V4 draft ring remains INT8, as in upstream. Windows/HIP and multi-GPU runtime coverage must be reported separately from Linux/CUDA evidence. +The web page's Monitor tab has a **Conversation cache** card (0.1.39, #596): the parked conversations against the +slots and the RAM budget, how many were parked, restored and evicted, and the last switch (read from the engine's +log), and for every setup how many prompt tokens the cache gave back - in the last request and since the start. +`/metrics` has the same under `"conversation_cache"`. + Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V. They add host RAM, not another model or VRAM allocation. The byte budget also counts an incoming snapshot during a switch. After a restore, unchanged K/V pages can be @@ -765,6 +786,17 @@ helper (`strata-vision`, from llama.cpp's `mtmd` library) and adds it to your st A picture becomes up to 1,024 tokens of the context (a 640x480 photo: 300). The same picture sent again, as chat apps do on every turn, is encoded only once. +**More image tokens (0.1.39, #625):** `--vision-tokens N` at setup (`START-HERE.bat --setup --vision cpu +--vision-tokens 768`) sets the most tokens a picture becomes - `"max_tokens"` in the `"vision"` section of +`strata-.json`, which you can also edit by hand. More tokens keep more detail (small text, charts, screenshots) +and take longer to encode, on the CPU most of all; a setup run again keeps the value. + +**A Q8_0 encoder (#625):** `"mmproj"` in the `"vision"` section can point to another mmproj file of this model, for +example a Q8_0 one (llama.cpp's `convert_hf_to_gguf.py --mmproj --outtype q8_0` makes one): the encoder's library +reads quantized weights, the file is half the size, and on the CPU it can encode faster than BF16. Setup downloads +the BF16 file, and a setup run again keeps a file of your own that still exists. We have not measured its accuracy +against BF16 yet; numbers are welcome in #625. + **A spare GPU for the encoder (0.1.33, #408):** with a card the engine doesn't use, add `"cuda_device": 2` (numbered like `nvidia-smi`) to the `"vision"` section of `strata-.json`: the encoder then runs on that card alone. Lower `--vram-reserve-mib` in `"args"` to 700 as well, so the engine's cards keep that VRAM for the expert cache. The diff --git a/docs/INSTALL.md b/docs/INSTALL.md index aec9d89d..bc77768b 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -145,7 +145,11 @@ says so and starts the engine you had. kept, only their names. Another browser or a private window starts empty; clearing the site's data deletes them. - **How the model starts:** `strata-.json` in the Strata folder (context, GPUs, host, API key, ...), written by setup; next to it `run-.bat` / `.sh`, the log `strata-.log` and, when you use "Use for other - apps too", `strata-.shared-settings.json`. + apps too", `strata-.shared-settings.json`. Running setup again for the same model (another context, say) + rewrites the keys setup writes (`exe`, `args`, `port`, `gpu`, `host`, `api_key`, `vision`, ...) and keeps the + ones you added (`sampling`, `mcp_servers`, `mcp`, `cors_origins`, ...); the earlier file is kept as + `strata-.json.bak` (0.1.39). Engine options you added to `"args"` by hand are not carried over: setup names + them, and you add them again. - **The model files** (`models/`, `packs/`, `mtp/`, 70-120 GB): in **`Strata-data` next to the Strata folder**, or wherever `--data-dir` put them. - **Where that data folder is:** `%APPDATA%\Strata\settings.json` on Windows, `~/.config/strata/settings.json` on @@ -190,6 +194,8 @@ START-HERE.bat --port 8081 another port START-HERE.bat --gpu 1 another GPU (setup picks the one with the most VRAM) START-HERE.bat --gpus 0,2 several GPUs sharing the model START-HERE.bat --vram-reserve-mib 2048 leave 2 GB of VRAM free for other programs (remembered) +START-HERE.bat --no-browser do not open the chat page when the model is ready (remembered; + --browser undoes it) START-HERE.bat --setup --backend hip the AMD engine on a PC that also has an NVIDIA card START-HERE.bat --setup --host 0.0.0.0 --api-key reachable from other devices, with a key START-HERE.bat --calibrate tune the engine for this PC (about 5-10 minutes), then start diff --git a/serve/frontend.py b/serve/frontend.py index 07e369d0..02a1d2f9 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -16,6 +16,7 @@ and the formats change often; the engine boundary is token ids in, text deltas o from __future__ import annotations import json +import re import uuid from dataclasses import dataclass, field from pathlib import Path @@ -135,6 +136,81 @@ def images_of(messages: list[dict]) -> list[str]: for item in m["content"] if item.get("type") == "image"] +# #537: a literal / inside a message's text is plain text, not the model's reasoning markers. The +# tokenizer matches those two strings as their special tokens everywhere (GGUF token type 4, as llama.cpp does), so +# a user quoting "" used to hand the model a real end-of-reasoning token. Before the template is rendered +# they are swapped for these private-use characters, and the server encodes the spans they mark as ordinary text. +THINK_TAGS = {"": "\U000F0E01", "": "\U000F0E02"} +THINK_MARKS = {v: k for k, v in THINK_TAGS.items()} + + +def _mark(text: str) -> str: + for tag, mark in THINK_TAGS.items(): + text = text.replace(tag, mark) + return text + + +def _mark_deep(v): + if isinstance(v, str): + return _mark(v) + if isinstance(v, dict): + return {k: _mark_deep(x) for k, x in v.items()} + if isinstance(v, list): + return [_mark_deep(x) for x in v] + return v + + +def _has_tag(v) -> bool: + if isinstance(v, str): + return "" in v or "" in v + if isinstance(v, dict): + return any(_has_tag(x) for x in v.values()) + if isinstance(v, list): + return any(_has_tag(x) for x in v) + return False + + +def mark_think_literals(messages: list[dict], tools: list[dict] | None): + """#537: (messages, tools) with every literal / in their text swapped for THINK_TAGS' marks, and + whether there was one (None: no change, the same objects back - a prompt without them renders as it always did). + An assistant message whose content opens with a whole ... block (clients that send the reasoning + inline) keeps that one block as the model's markers, as before.""" + if not _has_tag(messages) and not _has_tag(tools): + return messages, tools, False + out = [] + for m in messages: + m = dict(m) + content = m.get("content") + for k, v in m.items(): + if k != "role": + m[k] = _mark_deep(v) + if m.get("role") == "assistant" and isinstance(content, str) and content.lstrip().startswith("") \ + and "" in content: + i, j = content.index("") + len(""), content.index("") + m["content"] = content[:i] + _mark(content[i:j]) + "" + _mark(content[j + len(""):]) + out.append(m) + return out, _mark_deep(tools), True + + +_THINK_MARK_RE = re.compile("|".join(THINK_MARKS)) + + +def unmark_think_literals(prompt: str) -> tuple[str, list[tuple[int, int]]]: + """The rendered prompt with THINK_TAGS' marks turned back into the tags' text, and the (start, end) spans of those + tags in it: the server encodes them as ordinary text (the tokenizer's encode_plain_spans).""" + out, spans, pos, n = [], [], 0, 0 + for m in _THINK_MARK_RE.finditer(prompt): + out.append(prompt[pos:m.start()]) + n += m.start() - pos + tag = THINK_MARKS[m.group(0)] + out.append(tag) + spans.append((n, n + len(tag))) + n += len(tag) + pos = m.end() + out.append(prompt[pos:]) + return "".join(out), spans + + def _late_system_to_user(messages: list[dict]) -> list[dict]: """The chat template takes a system message only at the start ("System message must be at the beginning"). Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user @@ -160,6 +236,27 @@ def _object_list(value, name: str) -> list[dict]: return value +def _tool_list(value, wrapper: str | None) -> list[dict]: + """#592: a request's "tools" as a list of tool objects, each with a name - in the OpenAI shape + {"type": "function", "function": {"name": ...}} (`wrapper` "function"; a bare {"name": ...} is still taken), or + in the Anthropic shape {"name": ...} (`wrapper` None). A value that is not (a string such as "auto", a list of + names, an object without a name) is a ValueError - a 400 naming the field - where it used to take the request + thread down with no reply at all. No value (or an empty one) is no tools, as always.""" + if not value: + return [] + shape = ('{"type": "function", "function": {"name": ..., "parameters": {...}}}' if wrapper else + '{"name": ..., "input_schema": {...}}') + try: + tools = _object_list(value, "tools") + except ValueError: + raise ValueError(f"tools must be a list of tool objects, each {shape}") from None + for i, t in enumerate(tools): + fn = t.get(wrapper, t) if wrapper and t.get("type") == wrapper else t + if not isinstance(fn, dict) or not isinstance(fn.get("name"), str) or not fn["name"]: + raise ValueError(f"tools[{i}] has no name: each tool must be {shape}") + return tools + + def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] @@ -182,8 +279,8 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: calls.append({"function": {"name": fn.get("name"), "arguments": args or {}}}) out["tool_calls"] = calls messages.append(out) - tools = [t.get("function", t) if isinstance(t, dict) and t.get("type") == "function" else t - for t in req.get("tools") or []] or None + tools = [t.get("function", t) if t.get("type") == "function" else t + for t in _tool_list(req.get("tools"), "function")] or None kwargs = {} # OpenAI Chat Completions: "reasoning_effort"; Responses style: "reasoning": {"effort": ...} reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {} @@ -233,7 +330,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d out["tool_calls"] = calls messages.append(out) tools = [{"name": t["name"], "description": t.get("description", ""), "parameters": t.get("input_schema", {})} - for t in req.get("tools") or []] or None + for t in _tool_list(req.get("tools"), None)] or None kwargs = {} # Anthropic: "thinking": {"type": "disabled"} or {"type": "enabled", "budget_tokens": N}; # "output_config": {"effort": "low" | "medium" | "high"} diff --git a/serve/runconfig.py b/serve/runconfig.py new file mode 100644 index 00000000..472b0021 --- /dev/null +++ b/serve/runconfig.py @@ -0,0 +1,179 @@ +"""serve/runconfig.py - #564: the web page's Settings view of the run config (strata-.json). + +A short list of documented keys can be read and changed from Strata's own page (GET / POST /config). Everything +else in the file - the keys setup writes, the network and security keys (host, api_key, cors_origins, +trusted_origins, allowed_hosts), the MCP servers and before_load (which run programs), sampling keys not listed +here - is kept as it is: a change touches only the keys it names (as setup run again keeps the user's keys, #629). +The earlier file is kept as strata-.json.bak. The server reads the config when it starts, so a change is +used from the next start on. +""" +from __future__ import annotations + +import json +import os +import shutil +from pathlib import Path + +# (key, kind, help). kind: "bool", "int>=0", "num>=0", ("enum", values), "names", or ("sampling", check) for a key +# of the "sampling" block, ("arg", flag) for an engine option kept in "args". +EDITABLE = [ + ("sampling.temperature", ("sampling", "num>=0"), + "Default temperature for requests that send none (0 = greedy, the default without a sampling block)"), + ("sampling.top_p", ("sampling", "0=0", "Cap the thinking of every request at this many tokens (0 or empty: no cap)"), + ("fit_max_tokens", "bool", "Shorten a max_tokens that does not fit the context instead of answering 400"), + ("anthropic_thinking", ("enum", ["model", "on_request"]), + "Anthropic requests that do not ask for thinking: think as the model does (model) or not (on_request)"), + ("effort_position", ("enum", ["start", "end"]), + "Where a non-default reasoning effort goes: start (the default) or end (keeps the cache when it changes)"), + ("aliases", "names", "Other model names the server lists and answers to (comma-separated)"), + ("idle_unload_s", "num>=0", "Unload the model after this many seconds without requests (0 or empty: never)"), + ("lazy_load", "bool", "Start without loading the model; the first request loads it (text only)"), + ("engine_silence_s", "num>=0", "End a request when the engine says nothing for this long (default 300 s, 0 = wait)"), + ("api_monitor", "bool", "Keep the last 100 requests' prompts and answers in memory for /api-monitor"), + ("open_browser", "bool", "Open the chat page in the browser when the model is ready"), + ("vram_reserve_mib", ("arg", "--vram-reserve-mib"), + "VRAM in MiB the engine leaves free for other programs (engine default 700)"), +] +SPEC = {k: kind for k, kind, _ in EDITABLE} + + +def _arg(cfg: dict, flag: str): + a = cfg.get("args") if isinstance(cfg.get("args"), list) else [] + if flag in a[:-1]: + v = str(a[a.index(flag) + 1]) + return int(v) if v.isdigit() else v + return None + + +def value_of(cfg: dict, key: str): + kind = SPEC[key] + if isinstance(kind, tuple) and kind[0] == "sampling": + s = cfg.get("sampling") + return s.get(key.split(".", 1)[1]) if isinstance(s, dict) else None + if isinstance(kind, tuple) and kind[0] == "arg": + return _arg(cfg, kind[1]) + return cfg.get(key) + + +def view(cfg: dict, path: str | Path) -> dict: + """GET /config: the editable keys with their values (None: not set, the default applies).""" + out = [] + for key, kind, help_ in EDITABLE: + k = kind[0] if isinstance(kind, tuple) else kind + out.append({"key": key, "value": value_of(cfg, key), "help": help_, + "kind": "number" if k in ("sampling", "arg", "int>=0", "num>=0") else k, + **({"choices": kind[1]} if k == "enum" else {})}) + return {"file": Path(path).name, "keys": out, + "note": "Saved to the run config; used from the next start of the model."} + + +def _number(key, v, whole=False, lo=0.0, hi=None, lo_open=False): + if isinstance(v, bool) or not isinstance(v, (int, float)) or (whole and v != int(v)) or \ + (v <= lo if lo_open else v < lo) or (hi is not None and v > hi): + rng = f"{'more than' if lo_open else 'at least'} {lo:g}" + (f" and at most {hi:g}" if hi is not None else "") + raise ValueError(f"{key}: expected a {'whole ' if whole else ''}number, {rng}, not {v!r}") + return int(v) if whole else v + + +def check(key: str, v, cfg: dict): + """The value to store for `key`, or a ValueError naming what is expected. None removes the key (its default).""" + if key not in SPEC: + raise ValueError(f"{key!r} cannot be changed here (only the keys the Settings view lists)") + if v is None: + return None + kind = SPEC[key] + k = kind[0] if isinstance(kind, tuple) else kind + if k == "bool": + if not isinstance(v, bool): + raise ValueError(f"{key}: expected true or false, not {v!r}") + if key == "lazy_load" and v and cfg.get("vision"): + raise ValueError("lazy_load: lazy loading is text-only, and this model reads images (\"vision\")") + return v + if k == "enum": + if v not in kind[1]: + raise ValueError(f"{key}: expected one of {', '.join(kind[1])}, not {v!r}") + return v + if k == "names": + if isinstance(v, str): + v = [x.strip() for x in v.split(",") if x.strip()] + if not isinstance(v, list) or not all(isinstance(x, str) and x.strip() and len(x) <= 128 for x in v): + raise ValueError(f"{key}: expected a list of model names, not {v!r}") + return v or None + if k == "int>=0": + return _number(key, v, whole=True) + if k == "num>=0": + return _number(key, v) + if k == "arg": + return _number(key, v, whole=True) + rule = kind[1] # a sampling key: the server's own rules + if rule == "num>=0": + return float(_number(key, v)) + if rule == "0 tuple[dict, list[str]]: + """The config with `changes` ({key: value or None}) made, and the keys that changed. Every value is checked + first, so a request with one bad value changes nothing (ValueError).""" + if not isinstance(changes, dict) or not changes: + raise ValueError('send {"set": {"": , ...}}') + checked = {k: check(k, v, cfg) for k, v in changes.items()} + new = json.loads(json.dumps(cfg)) # a deep copy: the caller's dict is left alone + changed = [] + for key, v in checked.items(): + if value_of(new, key) == v: + continue + kind = SPEC[key] + if isinstance(kind, tuple) and kind[0] == "sampling": + s = dict(new.get("sampling") or {}) if isinstance(new.get("sampling"), dict) else {} + sub = key.split(".", 1)[1] + if v is None: + s.pop(sub, None) + else: + s[sub] = v + if s: + new["sampling"] = s + else: + new.pop("sampling", None) + elif isinstance(kind, tuple) and kind[0] == "arg": + a = list(new.get("args") or []) + flag = kind[1] + if flag in a[:-1]: + i = a.index(flag) + if v is None: + del a[i:i + 2] + else: + a[i + 1] = str(v) + elif v is not None: + a += [flag, str(v)] + new["args"] = a + elif v is None: + new.pop(key, None) + else: + new[key] = v + changed.append(key) + return new, changed + + +def save(path: str | Path, cfg: dict) -> Path: + """The config written whole (a temporary file moved over the old one), the earlier one kept as .bak.""" + path = Path(path) + bak = path.with_name(path.name + ".bak") + shutil.copyfile(path, bak) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + os.replace(tmp, path) + return bak + + +def load(path: str | Path) -> dict: + cfg = json.loads(Path(path).read_text(encoding="utf-8-sig")) + if not isinstance(cfg, dict): + raise ValueError(f"{Path(path).name} is not a JSON object") + return cfg diff --git a/serve/server.py b/serve/server.py index 6178f12d..60174b71 100644 --- a/serve/server.py +++ b/serve/server.py @@ -51,13 +51,21 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tools")) sys.path.insert(0, str(ROOT)) # run as a script (run-.bat) as well as a module from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 - images_of, openai_to_messages) + images_of, mark_think_literals, openai_to_messages, unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 +from serve import runconfig # noqa: E402 from serve.winjob import contain # noqa: E402 from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" +# #458: the trailing effort turn ("effort_position": "end"); low is the template's own sentence, medium (which the +# template says nothing for: no xhigh sentence is medium there) says it, since the xhigh one stays at the top +EFFORT_TURN = "<|im_start|>system\n{}<|im_end|>\n" +EFFORT_TEXT = {"low": "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the " + "conclusion without unnecessary elaboration.", + "medium": "Reasoning effort is set to medium. Think as much as the task needs, without unnecessary " + "elaboration."} VISION_START = "<|vision_start|>" # #606: a reply that repeats one token this many times in a row is ended there ("length"): a model in a loop, or a # broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens" @@ -296,6 +304,76 @@ def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, print(f"[strata] still starting ({time.time() - t0:.0f} s) - please wait ...", flush=True) +class ConvCacheLog: + """#596: the engine's conversation cache as its log tells it (the engine writes "strata serve: conversation + cache: parked N tokens ...; parked=P bytes=B evictions=E" and "restored N tokens ...; parked=P bytes=B" to stderr, + which is the log): read on from where it was last read, from the start of the engine's current run.""" + EVENT = re.compile(r"conversation cache: (parked|skipped|restored) (\d+) tokens.*?parked=(\d+) bytes=(\d+)" + r"(?: evictions=(\d+))?") + DROPPED = re.compile(r"conversation cache: dropped \d+ superseded .*?parked=(\d+)") + READ_MAX = 1 << 20 # at most the last MiB of new lines per read + + def __init__(self): + self.key, self.pos = None, 0 + self.reset() + + def reset(self): + self.state = {"parked": 0, "bytes": 0, "evictions": 0, "parks": 0, "restores": 0, "last_event": None, + "last_tokens": None, "last_at": None} + + def poll(self, path, start) -> dict: + """The state after the log's new lines; `start` is where the engine's current run began in it.""" + if not path or start is None: + return dict(self.state) + if self.key != (path, start): # another start of the engine: its cache starts empty + self.key, self.pos = (path, start), start + self.reset() + try: + size = os.path.getsize(path) + if size < self.pos: # the log was emptied or replaced + self.pos = 0 + if size - self.pos > self.READ_MAX: + self.pos = size - self.READ_MAX + with open(path, "rb") as f: + f.seek(self.pos) + data = f.read(size - self.pos) + except OSError: + return dict(self.state) + end = data.rfind(b"\n") + 1 # whole lines only: the rest is read next time + self.pos += end + now = time.time() + for line in data[:end].decode("utf-8", "replace").splitlines(): + if "conversation cache:" not in line: + continue + m = self.EVENT.search(line) + if m: + st = self.state + st["parked"], st["bytes"] = int(m.group(3)), int(m.group(4)) + if m.group(5) is not None: + st["evictions"] = int(m.group(5)) + if m.group(1) != "skipped": + st["parks" if m.group(1) == "parked" else "restores"] += 1 + st["last_event"], st["last_tokens"], st["last_at"] = m.group(1), int(m.group(2)), now + continue + m = self.DROPPED.search(line) + if m: + self.state["parked"] = int(m.group(1)) + return dict(self.state) + + +def conversation_cache_view(info: dict, hist: list, totals: dict, parked: dict) -> dict: + """#596: the Monitor's Conversation cache card: the parked conversations (the engine's opt-in + --conversation-cache-mib: budget, slots, what its log says) and how much of the prompts the cache gave back.""" + mib = info.get("conversation_cache_mib") + last = hist[-1] if hist else None + return {"enabled": isinstance(mib, int) and mib > 0, "budget_mib": mib if isinstance(mib, int) else None, + "slots": info.get("conversation_cache_slots"), **parked, + "requests": len(hist), "requests_reused": sum(1 for r in hist if (r.get("reused") or 0) > 0), + "reused_tokens": totals.get("reused", 0), "prompt_tokens": totals.get("prompt_tokens", 0), + "last_reused": last.get("reused") if last else None, + "last_prompt": last.get("prompt_tokens") if last else None} + + class StrataEngine: """The resident engine: `strata --serve` reads `GEN ` lines and streams `T ` lines, then `DONE ...`. Requests are serialized by the service's FIFO, so one pipe is enough. @@ -332,6 +410,7 @@ class StrataEngine: self.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULL loading = threading.Event() # set once READY: the narrator below stops log_start = os.path.getsize(log) if log else 0 # where this start's lines begin (start_failure_hint) + self.log_start = log_start # #596: the Monitor's conversation cache reads from here if log: threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading), daemon=True).start() @@ -784,6 +863,31 @@ def gpu_list(cfg: dict) -> list[int]: return [int(str(x).strip()) for x in items if str(x).strip() != ""] +def effort_end_args(cfg: dict, exe: str, tok) -> list[str] | None: + """#458 (opt-in): the engine arguments for "effort_position": "end" - the id of "system" as --tail-role-token, so + the engine checkpoints in front of the trailing effort turn - or None when the config leaves it at the top (the + default) or the engine is too old for it (said once; the prompt stays the default one). ValueError for a value + other than "start" / "end".""" + pos = cfg.get("effort_position", "start") + if pos not in ("start", "end"): + raise ValueError(f'"effort_position" must be "start" (the default) or "end", not {pos!r}') + if pos == "start": + return None + try: + with open(exe, "rb") as f: + known = b"--tail-role-token" in f.read() + except OSError: + known = False + role = tok.encode("system", parse_special=True) + if not known or len(role) != 1: + print("[strata] effort_position \"end\" needs engine 0.1.39 or newer (--tail-role-token): the reasoning " + "effort stays at the top of the prompt", flush=True) + return None + print("[strata] effort_position end: a request's non-default reasoning effort goes right before the answer, so " + "changing it keeps the cached conversation", flush=True) + return ["--tail-role-token", str(role[0])] + + def engine_silence_s(cfg: dict) -> float: """#481: the config's "engine_silence_s" - seconds an engine may print nothing during a request before the server ends it (default ENGINE_SILENCE_S; 0 = wait forever). ValueError for anything but a number >= 0.""" @@ -933,11 +1037,14 @@ class ByteTokenizer: """Tiny stand-in tokenizer for tests without the pack: one id per UTF-8 byte, specials as ids >= 256.""" SPECIALS = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<|vision_end|>"] - def encode(self, text, parse_special=False): + ALWAYS = () # specials matched without parse_special (type 4, as ) + + def encode(self, text, parse_special=False, plain=()): out, i = [], 0 while i < len(text): for k, s in enumerate(self.SPECIALS): - if parse_special and text.startswith(s, i): + if (parse_special or s in self.ALWAYS) and text.startswith(s, i) and not any( + a <= i < b for a, b in plain): out.append(256 + k) i += len(s) break @@ -995,6 +1102,12 @@ class Service: self.fifo = threading.Lock() self.embeddings = threading.local() # the current request's image embeddings file (GENI) self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) + # #458 (opt-in, the config's "effort_position": "end"): a non-default reasoning effort goes in a short system + # turn before the answer instead of the top of the prompt, so switching it keeps the cached conversation + self.effort_end = False + self.conv_log = ConvCacheLog() # #596: the parked conversations, from the engine's log + self.config_path = None # #564: the run config the web page's Settings view edits + self.config_lock = threading.Lock() # #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that # matters); empty = no CORS headers at all, as before self.cors_origins: list[str] = [] @@ -1332,7 +1445,9 @@ class Service: engine = {"model": self.model, "max_context": self.engine.max_context, "images": self.vision is not None, **dict(getattr(self.engine, "info", {}) or {})} tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "history": {}, "static": {}} + parked = self.conv_log.poll(getattr(self.engine, "log_path", None), getattr(self.engine, "log_start", None)) return {"engine": engine, "live": live, "requests": hist[::-1][:None if all_requests else 12], + "conversation_cache": conversation_cache_view(engine, hist, totals, parked), "requests_kept": len(hist), "totals": totals, "hardware": tel["now"], "hardware_static": tel["static"], "history": tel["history"], "time": now} @@ -1375,11 +1490,38 @@ class Service: "ram": {"used_gib": scaled(hw.get("ram_used"), 2 ** 30, 1), "total_gib": scaled(hw.get("ram_total"), 2 ** 30, 1)} if hw.get("ram_total") else None}} + def render_prompt(self, messages, tools, kwargs) -> str: + """The template rendered. #458: with `effort_end`, a request with a non-default effort (low, medium or no + thinking) is rendered as a default one up to the answer - the same prompt start, so the conversation cache + keeps it - and its effort follows in a short system turn right before the answer (thinking off: the template's + empty thinking block). The engine (--tail-role-token) checkpoints in front of that turn.""" + effort = kwargs.get("reasoning_effort") + off = kwargs.get("enable_thinking") is False + if not self.effort_end or (not off and effort in (None, "", "xhigh", "high")): + return self.template.render(messages, tools=tools, **kwargs) + base = {k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")} + history = self.template.render(messages, tools=tools, add_generation_prompt=False, **base) + full = self.template.render(messages, tools=tools, add_generation_prompt=True, **kwargs) + mine = self.template.render(messages, tools=tools, add_generation_prompt=False, **kwargs) + if not full.startswith(mine): # a template this cannot take apart: rendered as asked + return full + tail = "" if off else EFFORT_TURN.format(EFFORT_TEXT.get(effort, EFFORT_TEXT["medium"])) + return history + tail + full[len(mine):] + + def encode_prompt(self, messages, tools, kwargs) -> list[int]: + """The request's prompt: the template rendered and tokenized. #537: a / written inside a + message's text is encoded as the text it is, not as the model's reasoning markers (the template's own are).""" + marked, marked_tools, changed = mark_think_literals(messages, tools) + prompt = self.render_prompt(marked, marked_tools, kwargs) + if not changed: + return self.tok.encode(prompt, parse_special=True) + prompt, plain = unmark_think_literals(prompt) + return self.tok.encode(prompt, parse_special=True, plain=plain) + def prepare(self, messages, tools, kwargs, max_new=None): """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": the rest of the context.""" - prompt = self.template.render(messages, tools=tools, **kwargs) - ids = self.tok.encode(prompt, parse_special=True) + ids = self.encode_prompt(messages, tools, kwargs) self.embeddings.path = None images = images_of(messages) if images: @@ -2216,6 +2358,10 @@ def make_handler(svc: Service): if self._authorized(): self._json(200, {"shared": bool(svc.shared), "defaults": svc.shared}) return + if path == "/config": # #564: the Settings view's keys of the run config + if self._authorized(): + self._config_get() + return if path == "/mcp": # the MCP servers, their state and tools (the web app's switch and Monitor card) if self._authorized(): @@ -2285,6 +2431,9 @@ def make_handler(svc: Service): if path == "/settings": self._settings() return + if path == "/config": + self._config_post() + return # JSON from Strata's own page only, as /settings: else a plain form POST from any site unloads the model if path in ("/unload", "/load") and not self._own_page("the model can be loaded or unloaded"): return @@ -2411,6 +2560,44 @@ def make_handler(svc: Service): return False return True + def _config_get(self): + if not svc.config_path: + self._json(404, {"error": {"message": "this server was started without a run config"}}) + return + try: + cfg = runconfig.load(svc.config_path) + except (OSError, ValueError) as e: + self._json(500, {"error": {"type": "server_error", "message": f"the run config cannot be read: {e}"}}) + return + self._json(200, runconfig.view(cfg, svc.config_path)) + + def _config_post(self): + """#564: change a few documented keys of the run config - JSON from Strata's own page only, as + /settings (the key is checked before); every other key of the file stays as it is.""" + body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + if not self._own_page("the run config can be changed"): + return + if not svc.config_path: + self._json(404, {"error": {"message": "this server was started without a run config"}}) + return + try: + req = json.loads(body or b"{}") + with svc.config_lock: + cfg = runconfig.load(svc.config_path) + new, changed = runconfig.apply(cfg, req.get("set") if isinstance(req, dict) else None) + if changed: + bak = runconfig.save(svc.config_path, new) + except ValueError as e: + self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) + return + except OSError as e: + self._json(500, {"error": {"type": "server_error", "message": f"the run config cannot be written: {e}"}}) + return + if changed: + print(f"[strata] the Settings view changed {', '.join(changed)} in {Path(svc.config_path).name} " + f"(the earlier file: {bak.name}); used from the next start", flush=True) + self._json(200, {**runconfig.view(new, svc.config_path), "changed": changed}) + def _settings(self): # They change what every client gets, so only the app's own page may set them body = self.rfile.read(int(self.headers.get("Content-Length", 0))) @@ -2478,7 +2665,7 @@ def make_handler(svc: Service): svc.load() max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest use_mcp = req.get("strata_mcp") is True and svc.mcp is not None # the web app's opt-in (serve/mcp.py) - own = {t.get("name") for t in tools or []} + own = {t.get("name") for t in tools or [] if isinstance(t, dict)} # #592: a second line of defence if use_mcp: if not self._own_page("MCP tools can be used"): # tools run with the user's rights on this PC return @@ -2530,8 +2717,7 @@ def make_handler(svc: Service): read for the same request, rendered and tokenized - the model does not run.""" req = svc.with_shared(req, "anthropic") messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) - prompt = svc.template.render(messages, tools=tools, **kw) - self._json(200, {"input_tokens": len(svc.tok.encode(prompt, parse_special=True))}) + self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw))}) def _anthropic(self, req): svc.load() @@ -2985,7 +3171,12 @@ def main() -> int: silence = engine_silence_s(cfg) # #481: checked before the (minutes-long) start except ValueError as e: raise SystemExit(f"[strata] config {e}") - engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy) + try: + effort_end = effort_end_args(cfg, exe, tok) # #458 + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + engine = StrataEngine(exe, engine_args(cfg) + (effort_end or []), cwd=cfg.get("cwd"), log=cfg.get("log"), + env=env, lazy=lazy) engine.silence_s = silence # an attribute of its own: restart() keeps it warn_tight_ram(engine.info.get("arena_mib")) note = desktop_vram_note(cfg.get("backend"), engine.info.get("vram_free_mib"), engine.spawn[1], @@ -2993,6 +3184,7 @@ def main() -> int: if note: # #560 #516: before --open starts a browser on that card print(note, flush=True) else: + effort_end = None engine, vision, sampling_defaults = MockEngine(tok, a.script or [ "Thinking about it.\n\nHello from the mock engine."]), None, {} # the model's own chat template (exported with its tokenizer), else the original model's @@ -3044,6 +3236,7 @@ def main() -> int: if isinstance(rs, bool) or not isinstance(rs, int) or rs < 0: raise SystemExit(f"[strata] config \"repeat_stop_tokens\" must be a whole number >= 0 (0 = off), not {rs!r}") svc.repeat_stop_tokens = rs + svc.effort_end = bool(effort_end) # #458: "effort_position": "end" with an engine that has it if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request try: svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"] @@ -3056,6 +3249,8 @@ def main() -> int: svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51) svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112) svc.backend = cfg.get("backend") # "hip": the AMD cards' readings come from sysfs (#301) + if a.config: + svc.config_path = a.config # #564: the web page's Settings view if a.config: # the Chat settings shared with other apps, from last time svc.shared_path = str(Path(a.config).with_suffix("")) + ".shared-settings.json" try: @@ -3094,8 +3289,8 @@ def main() -> int: "in an admin PowerShell:\n New-NetFirewallRule -DisplayName \"Strata " + str(a.port) + "\" " "-Direction Inbound -Protocol TCP -LocalPort " + str(a.port) + " -Action Allow -Profile Private\n" " (and set this network to Private in Windows' network settings)", flush=True) - if a.open: - import webbrowser + if a.open and cfg.get("open_browser") is not False: # #609: the config's "open_browser": false wins (an older + import webbrowser # run-.bat still passes --open) webbrowser.open(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{a.port}/") # #96: docker stop sends SIGTERM, which Python ignores by default, so the container's PID 1 would be killed after # the grace period with the engine still running. SIGTERM takes Ctrl+C's path below (QUIT to the engine). diff --git a/serve/test_monitor.py b/serve/test_monitor.py index ad554e00..0c82cb0b 100644 --- a/serve/test_monitor.py +++ b/serve/test_monitor.py @@ -194,5 +194,68 @@ class Monitor(unittest.TestCase): self.assertEqual(self.request("/web/../server.py")[0], 404) +class ConversationCacheCard(unittest.TestCase): + """#596: /metrics' "conversation_cache": the parked conversations from the engine's log lines, the budget and + slots from its INFO line, and how much of the prompts the cache gave back.""" + + PARK = ("strata serve: conversation cache: parked 5000 tokens in 12.0 ms; parked=1 bytes=104857600 evictions=0 " + "snapshot_bytes=104857600 reused_kv_bytes=0\n") + RESTORE = "strata serve: conversation cache: restored 4000 tokens (exact) in 30.0 ms; parked=2 bytes=209715200\n" + + def test_the_log(self): + from serve.server import ConvCacheLog + import tempfile + with tempfile.TemporaryDirectory() as d: + log = Path(d) / "strata.log" + log.write_text("an earlier run\n" + self.PARK, encoding="utf-8") + start = log.stat().st_size # this run starts here: the earlier run's park is not counted + c = ConvCacheLog() + self.assertEqual(c.poll(str(log), start)["parked"], 0) + with open(log, "a", encoding="utf-8") as f: + f.write("strata serve: something else\n" + self.PARK + self.RESTORE + "strata serve: conversation ca") + st = c.poll(str(log), start) + self.assertEqual((st["parked"], st["bytes"], st["parks"], st["restores"]), (2, 209715200, 1, 1)) + self.assertEqual((st["last_event"], st["last_tokens"]), ("restored", 4000)) + with open(log, "a", encoding="utf-8") as f: # the cut line is read once it is whole + f.write("che: dropped 1 superseded copy of this conversation; parked=1\n") + self.assertEqual(c.poll(str(log), start)["parked"], 1) + self.assertEqual(c.poll(str(log), log.stat().st_size)["parked"], 0) # the engine started again + self.assertEqual(c.poll(None, None)["parked"], 0) + + def test_metrics(self): + tok = ByteTokenizer() + engine = MockEngine(tok, "Thought.\nHello.", max_context=4096) + engine.info = {"conversation_cache_mib": 8192, "conversation_cache_slots": 4} + svc = Service(engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + c = json.loads(r.read())["conversation_cache"] + self.assertEqual((c["enabled"], c["budget_mib"], c["slots"], c["parked"], c["requests"]), + (True, 8192, 4, 0, 0)) + req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"messages": [{"role": "user", "content": "hi"}]}).encode()) + with urllib.request.urlopen(req, timeout=10) as r: + r.read() + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + c = json.loads(r.read())["conversation_cache"] + self.assertEqual(c["requests"], 1) + self.assertGreater(c["last_prompt"], 0) + engine.info = {} + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + self.assertFalse(json.loads(r.read())["conversation_cache"]["enabled"]) # off: the reuse lines only + finally: + httpd.shutdown() + httpd.server_close() + + def test_the_card_is_on_the_page(self): + web = Path(__file__).parent / "web" + html, js = (web / "index.html").read_text(encoding="utf-8"), (web / "app.js").read_text(encoding="utf-8") + for el in ("cc-card", "cc-slots-text", "cc-mem-text", "cc-facts", "cc-note"): + self.assertIn(f'id="{el}"', html) + self.assertIn(f'"{el}"', js) + + if __name__ == "__main__": unittest.main() diff --git a/serve/test_runconfig.py b/serve/test_runconfig.py new file mode 100644 index 00000000..bb171196 --- /dev/null +++ b/serve/test_runconfig.py @@ -0,0 +1,165 @@ +"""serve/test_runconfig.py - #564: the web page's Settings view of the run config (GET / POST /config), against the +mock engine: only the listed keys change, every other key of the file stays, a bad value changes nothing, and only +Strata's own page may write it (JSON, no foreign Origin, the API key when one is set). + + python -m unittest serve.test_runconfig +""" +from __future__ import annotations + +import contextlib +import io +import json +import tempfile +import unittest +import urllib.error +import urllib.request +from pathlib import Path + +from serve import runconfig +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, MockEngine, Service, serve + +ROOT = Path(__file__).resolve().parents[1] +CFG = {"exe": "engine/strata.exe", "args": ["--pack", "data/packs/q2_0", "--kv", "int8", "--spec-min-p", "0.5"], + "model_name": "qwen3.8-flash-next-q2_0", "port": 8080, "host": "0.0.0.0", "api_key": "", + "sampling": {"temperature": 0.7, "presence_penalty": 1.5}, + "mcp_servers": {"files": {"command": "npx", "args": ["-y", "server-filesystem", "."]}}, + "cors_origins": ["http://localhost:3000"]} + + +class Apply(unittest.TestCase): + def test_only_the_named_keys_change(self): + new, changed = runconfig.apply(CFG, {"sampling.top_p": 0.95, "reasoning_budget_tokens": 4096, + "vram_reserve_mib": 2048, "aliases": "qwen, local", "lazy_load": True}) + self.assertEqual(changed, ["sampling.top_p", "reasoning_budget_tokens", "vram_reserve_mib", "aliases", + "lazy_load"]) + self.assertEqual(new["sampling"], {"temperature": 0.7, "presence_penalty": 1.5, "top_p": 0.95}) + self.assertEqual(new["args"][-2:], ["--vram-reserve-mib", "2048"]) + self.assertEqual(new["aliases"], ["qwen", "local"]) + for k in ("exe", "model_name", "port", "host", "api_key", "mcp_servers", "cors_origins"): + self.assertEqual(new[k], CFG[k], k) + self.assertEqual(CFG["sampling"], {"temperature": 0.7, "presence_penalty": 1.5}) # the input is left alone + + def test_null_is_the_default_again(self): + cfg, _ = runconfig.apply(CFG, {"vram_reserve_mib": 2048, "fit_max_tokens": True}) + new, changed = runconfig.apply(cfg, {"vram_reserve_mib": None, "fit_max_tokens": None, + "sampling.temperature": None, "idle_unload_s": None}) + self.assertEqual(changed, ["vram_reserve_mib", "fit_max_tokens", "sampling.temperature"]) + self.assertEqual(new["args"], CFG["args"]) + self.assertNotIn("fit_max_tokens", new) + self.assertEqual(new["sampling"], {"presence_penalty": 1.5}) + new, _ = runconfig.apply({"sampling": {"top_k": 20}}, {"sampling.top_k": None}) + self.assertNotIn("sampling", new) # an empty block goes + + def test_refused(self): + for changes in ({"api_key": "x"}, {"host": "0.0.0.0"}, {"mcp_servers": {}}, {"before_load": "calc.exe"}, + {"args": []}, {"exe": "evil.exe"}, {"trusted_origins": ["*"]}, {"allowed_hosts": ["*"]}, + {"sampling.temperature": -1}, {"sampling.top_p": 0}, {"sampling.top_k": 65}, + {"sampling.min_p": 2}, {"reasoning_budget_tokens": 1.5}, {"fit_max_tokens": "yes"}, + {"effort_position": "middle"}, {"vram_reserve_mib": -5}, {"idle_unload_s": True}, + {"aliases": [1]}, {}, None, ["x"]): + with self.subTest(changes=changes), self.assertRaises(ValueError): + runconfig.apply(CFG, changes) + with self.assertRaises(ValueError): # one bad value: nothing is applied + runconfig.apply(CFG, {"fit_max_tokens": True, "sampling.top_k": 0}) + with self.assertRaises(ValueError): + runconfig.apply({**CFG, "vision": {"gpu": True}}, {"lazy_load": True}) + + def test_view(self): + v = runconfig.view({**CFG, "args": CFG["args"] + ["--vram-reserve-mib", "1500"]}, "x/strata-q2_0.json") + self.assertEqual(v["file"], "strata-q2_0.json") + got = {k["key"]: k for k in v["keys"]} + self.assertEqual(got["sampling.temperature"]["value"], 0.7) + self.assertEqual(got["vram_reserve_mib"]["value"], 1500) + self.assertIsNone(got["fit_max_tokens"]["value"]) + self.assertEqual(got["anthropic_thinking"]["choices"], ["model", "on_request"]) + self.assertNotIn("api_key", got) + self.assertNotIn("mcp_servers", got) + + +class Http(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.path = Path(self.dir.name) / "strata-q2_0.json" + self.path.write_text(json.dumps(CFG, indent=1), encoding="utf-8") + tok = ByteTokenizer() + self.svc = Service(MockEngine(tok, "ok", max_context=4096), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.svc.config_path = str(self.path) + self.httpd = serve(self.svc, port=0) + self.host = f"127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + self.dir.cleanup() + + def call(self, method, body=None, headers=None): + h = {"Content-Type": "application/json", **(headers or {})} + req = urllib.request.Request(f"http://{self.host}/config", method=method, headers=h, + data=None if body is None else (body if isinstance(body, bytes) + else json.dumps(body).encode())) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def saved(self): + return json.loads(self.path.read_text(encoding="utf-8")) + + def test_read_and_write_from_the_page(self): + status, v = self.call("GET") + self.assertEqual(status, 200, v) + self.assertEqual({k["key"]: k["value"] for k in v["keys"]}["sampling.temperature"], 0.7) + with contextlib.redirect_stdout(io.StringIO()): + status, v = self.call("POST", {"set": {"sampling.temperature": 1.0, "open_browser": False}}, + {"Origin": f"http://{self.host}"}) + self.assertEqual(status, 200, v) + self.assertEqual(v["changed"], ["sampling.temperature", "open_browser"]) + cfg = self.saved() + self.assertEqual(cfg["sampling"]["temperature"], 1.0) + self.assertIs(cfg["open_browser"], False) + for k in ("mcp_servers", "cors_origins", "host", "args", "exe"): + self.assertEqual(cfg[k], CFG[k], k) + self.assertEqual(json.loads((self.path.parent / "strata-q2_0.json.bak").read_text(encoding="utf-8")), CFG) + status, v = self.call("POST", {"set": {"open_browser": False}}) # no Origin (a script on this PC): allowed + self.assertEqual((status, v["changed"]), (200, [])) + + def test_only_from_strata_s_own_page(self): + before = self.path.read_bytes() + status, _ = self.call("POST", {"set": {"fit_max_tokens": True}}, {"Origin": "https://evil.example"}) + self.assertEqual(status, 403) + status, _ = self.call("POST", b'{"set": {"fit_max_tokens": true}}', {"Content-Type": "text/plain"}) + self.assertEqual(status, 415) + for body in ({"set": {"api_key": ""}}, {"set": {"mcp_servers": {"x": {"command": "calc"}}}}, + {"set": {"sampling.top_k": 0}}, {"nothing": 1}, b"not json"): + status, b = self.call("POST", body, {"Origin": f"http://{self.host}"}) + self.assertEqual(status, 400, (body, b)) + self.assertEqual(self.path.read_bytes(), before) # nothing was written + self.assertFalse((self.path.parent / "strata-q2_0.json.bak").exists()) + + def test_the_api_key(self): + self.svc.api_key = "secret" + self.assertEqual(self.call("GET")[0], 401) + self.assertEqual(self.call("POST", {"set": {"fit_max_tokens": True}})[0], 401) + with contextlib.redirect_stdout(io.StringIO()): + status, _ = self.call("POST", {"set": {"fit_max_tokens": True}}, {"Authorization": "Bearer secret"}) + self.assertEqual(status, 200) + self.assertIs(self.saved()["fit_max_tokens"], True) + + def test_without_a_run_config(self): + self.svc.config_path = None + self.assertEqual(self.call("GET")[0], 404) + self.assertEqual(self.call("POST", {"set": {"fit_max_tokens": True}})[0], 404) + + def test_the_page_has_the_view(self): + web = ROOT / "serve" / "web" + html, js = (web / "index.html").read_text(encoding="utf-8"), (web / "app.js").read_text(encoding="utf-8") + for el in ("cfg-card", "cfg-form", "cfg-save", "cfg-msg"): + self.assertIn(f'id="{el}"', html) + self.assertIn('fetch("config", {method: "POST", headers: headers(true)', js) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_server.py b/serve/test_server.py index 546fb0c4..acf99ed6 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -243,6 +243,190 @@ class ImageMarkers(unittest.TestCase): svc.embeddings.path.unlink(missing_ok=True) +class ThinkTokenizer(ByteTokenizer): + """The byte tokenizer with the model's reasoning markers as specials that are matched even without parse_special, + as the real tokenizer does (GGUF token type 4).""" + SPECIALS = ByteTokenizer.SPECIALS + ["", ""] + ALWAYS = ("", "") + + +class LiteralThinkTags(unittest.TestCase): + """#537: a / written inside a message is text, not the model's reasoning markers: a quoted + "" no longer ends the model's reasoning before it starts. The template's own markers stay special.""" + + @classmethod + def setUpClass(cls): + cls.tok = ThinkTokenizer() + cls.svc = Service(MockEngine(cls.tok, "ok", max_context=CTX), cls.tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.open, cls.close = (cls.tok.encode(t)[0] for t in ("", "")) + + def ids(self, messages, tools=None, **kw): + return self.svc.prepare(messages, tools, kw)[0] + + def old_ids(self, messages, tools=None, **kw): + return self.tok.encode(self.svc.template.render(messages, tools=tools, **kw), parse_special=True) + + def test_a_quoted_tag_in_a_user_message(self): + text = "Quote this exact literal string, then explain it: and " + ids = self.ids([{"role": "user", "content": text}]) + self.assertEqual(ids.count(self.close), 0) + self.assertEqual(ids.count(self.open), 1) # the generation prompt's own + self.assertEqual(ids[-2:], [self.open, ord("\n")]) + self.assertIn(text, self.tok.decode(ids)) # the text is all there, as text + self.assertEqual(ids.count(self.close), 0) + # thinking off: the template's empty block stays two specials, the user's tag is text + ids = self.ids([{"role": "user", "content": text}], enable_thinking=False) + self.assertEqual((ids.count(self.open), ids.count(self.close)), (1, 1)) + + def test_without_a_tag_the_prompt_is_unchanged(self): + msgs = [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "1+1?"}, + {"role": "assistant", "content": "2", "reasoning_content": "easy"}, {"role": "user", "content": "x"}] + self.assertEqual(self.ids(msgs), self.old_ids(msgs)) + self.assertEqual(self.ids(msgs, enable_thinking=False), self.old_ids(msgs, enable_thinking=False)) + + def test_history_tool_results_and_tools(self): + msgs = [{"role": "user", "content": "go"}, + {"role": "assistant", "content": "It wrote here.", "reasoning_content": "the tag", + "tool_calls": [{"function": {"name": "write", "arguments": {"text": "a b"}}}]}, + {"role": "tool", "content": "file has in it"}, + {"role": "user", "content": "why did you write "}] + tools = [{"name": "write", "description": "writes text (may contain )", "parameters": {}}] + ids = self.ids(msgs, tools) + # the template's markers: the history turn's ... and the generation prompt's + self.assertEqual((ids.count(self.open), ids.count(self.close)), (2, 1)) + text = self.tok.decode(ids) + for part in ("It wrote here.", "the tag", "a b", "file has in it", + "why did you write ", "may contain "): + self.assertIn(part, text) + + def test_a_client_that_sends_the_reasoning_inline(self): + # an assistant turn whose content opens with its own ... block keeps that block's markers + msgs = [{"role": "user", "content": "hi"}, + {"role": "assistant", "content": "\nplan: say hello\n\n\nHello, is a tag."}, + {"role": "user", "content": "again"}] + ids = self.ids(msgs) + self.assertEqual((ids.count(self.open), ids.count(self.close)), (3, 2)) # template's + the inline block's + self.assertIn("Hello, is a tag.", self.tok.decode(ids)) + + def test_the_real_tokenizer_reads_the_tag_as_text(self): + import strata_tokenizer as ST + b2u = ST.bytes_to_unicode() + tokens = [b2u[b] for b in range(256)] + ["", "", "<|im_end|>"] + tok = ST.Tokenizer(tokens, [], [1] * 256 + [4, 4, 3]) + text = "say now<|im_end|>" + self.assertEqual(tok.encode(text, parse_special=True), [*b"say ", 257, *b" now", 258]) + start = text.index("") + plain = tok.encode(text, parse_special=True, plain=[(start, start + len(""))]) + self.assertEqual(plain, [*b"say now", 258]) # the tag as text, im_end still special + + +class EffortAtTheEnd(unittest.TestCase): + """#458 (opt-in "effort_position": "end"): a non-default effort goes in a system turn right before the answer, so + a request that changes only the effort keeps the cached conversation. The engine's checkpoint rule is simulated + on the token ids (src/program/generate.cpp: the last <|im_start|>, and with --tail-role-token the one in front + of a trailing system turn); the default prompt does not change.""" + + TURN = 256 # the byte tokenizer's <|im_start|> + ROLE = ord("s") # "system"'s first byte stands for its token + + def setUp(self): + self.tok = ByteTokenizer() + self.svc = Service(MockEngine(self.tok, "ok", max_context=1 << 20), self.tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + + def ids(self, messages, end, **kw): + self.svc.effort_end = end + return self.svc.encode_prompt(messages, None, kw) + + def checkpoint(self, ids, tail, resume=0): + """Where the engine checkpoints a prompt (the tokens before it), as generate.cpp's serve loop does.""" + turn_at = next((i for i in range(len(ids) - 1, resume, -1) if ids[i] == self.TURN), -1) + if turn_at > 0 and tail: + i = next((i for i in range(turn_at - 1, resume, -1) if ids[i] == self.TURN), None) + if i is not None and ids[i + 1] == self.ROLE: + turn_at = i + return ids[:turn_at] + + def session(self, requests, end, tail): + """The reused tokens of each request after the first: the longest earlier checkpoint it starts with.""" + checks, reused = [], [] + for messages, kw in requests: + ids = self.ids(messages, end, **kw) + reused.append(max([len(c) for c in checks if ids[:len(c)] == c], default=0)) + checks.append(self.checkpoint(ids, tail)) + return reused[1:] + + CHAT = [{"role": "system", "content": "You are a careful assistant. " * 40}, + {"role": "user", "content": "Explain the conversation cache. " * 20}] + REPLY = {"role": "assistant", "content": "It keeps the prompt's state. " * 20, "reasoning_content": "ok"} + NEXT = {"role": "user", "content": "And the checkpoints?"} + + def test_the_default_prompt_is_unchanged(self): + for kw in ({}, {"reasoning_effort": "xhigh"}): + self.assertEqual(self.ids(self.CHAT, True, **kw), self.ids(self.CHAT, False, **kw)) + self.assertEqual(self.ids(self.CHAT, True, **kw), + self.tok.encode(self.svc.template.render(self.CHAT, **kw), parse_special=True)) + for kw in ({"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, {"enable_thinking": False}): + self.assertEqual(self.ids(self.CHAT, False, **kw), # off: every effort renders as before + self.tok.encode(self.svc.template.render(self.CHAT, **kw), parse_special=True)) + + def test_the_trailing_turn(self): + text = self.tok.decode(self.ids(self.CHAT, True, reasoning_effort="low")) + self.assertTrue(text.endswith("<|im_end|>\n<|im_start|>system\nReasoning effort is set to low. Keep your " + "thinking brief and focused, moving directly to the conclusion without " + "unnecessary elaboration.<|im_end|>\n<|im_start|>assistant\n\n"), text[-300:]) + self.assertIn("Reasoning effort is set to xhigh", text) # the top stays the default's + text = self.tok.decode(self.ids(self.CHAT, True, enable_thinking=False)) + self.assertTrue(text.endswith("<|im_start|>assistant\n\n\n\n\n")) + self.assertNotIn("<|im_start|>system\nReasoning effort", text[-200:]) + default = self.ids(self.CHAT, True) + for kw in ({"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, {"enable_thinking": False}): + ids = self.ids(self.CHAT, True, **kw) + head = len(self.checkpoint(default, False)) # all before the answer's turn + self.assertEqual(ids[:head], default[:head], kw) # the same prompt up to the answer + + def test_changing_the_effort_keeps_the_conversation(self): + efforts = [{}, {"reasoning_effort": "low"}, {"enable_thinking": False}, {"reasoning_effort": "medium"}, {}] + history = len(self.checkpoint(self.ids(self.CHAT, False), False)) + # at the top (the default): another effort differs a few tokens in, and the whole prompt is read again + self.assertEqual(self.session([(self.CHAT, kw) for kw in efforts], False, False)[:2], [0, 0]) + # at the end, with the engine's rule: every request reuses the whole conversation + self.assertEqual(self.session([(self.CHAT, kw) for kw in efforts], True, True), [history] * 4) + + def test_the_next_turn_reuses_the_checkpoint(self): + turn1, turn2 = self.CHAT, self.CHAT + [self.REPLY, self.NEXT] + low = {"reasoning_effort": "low"} + first = len(self.checkpoint(self.ids(turn1, True, **low), True)) + # the engine's rule: the next turn (the same effort) reuses the first turn's whole conversation + self.assertEqual(self.session([(turn1, low), (turn2, low)], True, True), [first]) + # without it the checkpoint held the effort turn and the next turn reused nothing (what #458 measured) + self.assertEqual(self.session([(turn1, low), (turn2, low)], True, False), [0]) + + def test_the_config(self): + from serve.server import effort_end_args + + class Tok: + def encode(self, text, parse_special=False): + return [8678] if text == "system" else [1, 2] + + with tempfile.TemporaryDirectory() as d: + new, old = Path(d) / "new.exe", Path(d) / "old.exe" + new.write_bytes(b"... --tail-role-token ID --serve: ...") + old.write_bytes(b"... --turn-token ID ...") + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertIsNone(effort_end_args({}, str(new), Tok())) + self.assertIsNone(effort_end_args({"effort_position": "start"}, str(new), Tok())) + self.assertEqual(effort_end_args({"effort_position": "end"}, str(new), Tok()), + ["--tail-role-token", "8678"]) + self.assertIsNone(effort_end_args({"effort_position": "end"}, str(old), Tok())) + self.assertIsNone(effort_end_args({"effort_position": "end"}, str(new), ByteTokenizer())) + self.assertIn("needs engine 0.1.39 or newer", out.getvalue()) + with self.assertRaises(ValueError): + effort_end_args({"effort_position": "middle"}, str(new), Tok()) + + class StatusNeedsTheKey(unittest.TestCase): """#212: /status shows the end of the answer being written, so it needs the key like /v1/*.""" @@ -501,6 +685,36 @@ class ClientShapes(unittest.TestCase): self.assertEqual(status, 400, b) self.assertIn("messages must be a list of objects", b["error"]["message"]) + def test_malformed_tools_are_a_400(self): + # #592: a "tools" value that is not a list of named tool objects is a 400 naming the field, on both APIs, + # not a dropped connection (an AttributeError/TypeError in the request thread) + msgs = [{"role": "user", "content": "hi"}] + bad = ("auto", ["get_weather"], [{"description": "no name"}], {"name": "x"}, + [{"type": "function", "function": "get_weather"}], [{"type": "function", "function": {"name": ""}}]) + for path in ("/v1/chat/completions", "/v1/messages"): + for tools in bad: + with self.subTest(path=path, tools=tools): + status, b = self.post(path, {"model": "x", "max_tokens": 8, "messages": msgs, "tools": tools}) + self.assertEqual(status, 400, b) + self.assertIn("tools", b["error"]["message"]) + status, b = self.post("/v1/chat/completions", {"model": "x", "max_tokens": 8, "messages": msgs}) + self.assertEqual(status, 200, b) # the server goes on + + def test_well_formed_tools_still_work(self): + msgs = [{"role": "user", "content": "hi"}] + fn = {"name": "get_weather", "description": "the weather", "parameters": {"type": "object", "properties": {}}} + for path, tools in (("/v1/chat/completions", [{"type": "function", "function": fn}]), + ("/v1/chat/completions", [fn]), # the bare shape some clients send + ("/v1/chat/completions", json.dumps([{"type": "function", "function": fn}])), + ("/v1/chat/completions", []), ("/v1/chat/completions", None), + ("/v1/messages", [{"name": "get_weather", "input_schema": {"type": "object"}}]), + ("/v1/messages", [])): + with self.subTest(path=path, tools=tools): + status, b = self.post(path, {"model": "x", "max_tokens": 8, "messages": msgs, "tools": tools}) + self.assertEqual(status, 200, b) + if tools: + self.assertIn("get_weather", self.prompt_text()) + 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 diff --git a/serve/web/app.css b/serve/web/app.css index 4e8363d4..dd9a3e1f 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -115,7 +115,18 @@ main { flex: 1; min-height: 0; display: flex; } .table-wrap.all { max-height: 420px; overflow-y: auto; } .req-totals { margin: 0; font-size: var(--st-fs-sm); } .req-totals:empty { display: none; } +.cc-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.cc-bars { display: grid; grid-template-columns: 1fr 1fr; gap: var(--st-s-2) var(--st-s-6); } +.cc-bars[hidden] { display: none; } +.cc-note { margin: 0; } +.cc-note:empty { display: none; } .mcp-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.cfg-form { display: grid; grid-template-columns: minmax(180px, max-content) minmax(0, 1fr); gap: var(--st-s-3) var(--st-s-4); + align-items: center; } +.cfg-form label { font-size: var(--st-fs-sm); font-weight: var(--st-fw-medium); } +.cfg-form label code { font: 400 12px var(--st-font-mono); color: var(--st-ink-muted); display: block; } +.cfg-form .st-input { height: 38px; width: 100%; max-width: 360px; } +.cfg-actions { display: flex; align-items: center; gap: var(--st-s-3); } .mcp-server { display: flex; flex-direction: column; gap: var(--st-s-2); padding-top: var(--st-s-3); border-top: 1px solid var(--st-line-soft); } .mcp-server:first-child { padding-top: 0; border-top: 0; } .mcp-server__head { display: flex; align-items: center; gap: var(--st-s-2); flex-wrap: wrap; font-size: var(--st-fs-sm); } @@ -155,6 +166,9 @@ main { flex: 1; min-height: 0; display: flex; } @media (max-width: 1000px) { .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } .monitor-row { grid-template-columns: 1fr; } + .cc-bars { grid-template-columns: 1fr; } + .cfg-form { grid-template-columns: 1fr; gap: 4px; } + .cfg-form .st-input { margin-bottom: var(--st-s-2); } } @media (max-width: 640px) { .st-header { padding: 0 var(--st-s-3); gap: var(--st-s-2); } diff --git a/serve/web/app.js b/serve/web/app.js index f6e56374..ade19016 100644 --- a/serve/web/app.js +++ b/serve/web/app.js @@ -79,6 +79,7 @@ function showTab(name) { if (location.hash.slice(1) !== tab) history.replaceState(null, "", tab === "chat" ? location.pathname : `#${tab}`); if (tab === "chat") $("input").focus(); if (tab === "monitor") loadMcp(); + if (tab === "about") loadConfig(); if (lastMetrics) render(lastMetrics); } for (const b of document.querySelectorAll(".st-tab")) b.onclick = () => showTab(b.dataset.tab); @@ -190,9 +191,43 @@ function render(m) { } if (live.queued > 0) setPill("queued", `${live.queued} queued`); if (tab === "monitor") renderMonitor(live, hw, st, eng, h, last, m.requests || [], m.totals, m.requests_kept); + if (tab === "monitor") renderConvCache(m.conversation_cache); if (tab === "about") renderAbout(eng, hw, st); } +// #596: the conversation cache - the prompt's state the engine keeps between requests (always), and the whole +// conversations it parks in RAM when "--conversation-cache-mib N" is in the run config's args (opt-in) +function since(t) { + if (!t) return ""; + const s = Math.max(0, Date.now() / 1000 - t); + return s < 60 ? "just now" : s < 3600 ? `${fmt(s / 60)} min ago` : `${fmt(s / 3600, 1)} h ago`; +} +function renderConvCache(c) { + $("cc-card").hidden = !c; + if (!c) return; // an older server + const pct = (a, b) => (b ? `${Math.min(100, (100 * a) / b)}%` : "0%"); + $("cc-bars").hidden = !c.enabled; + if (c.enabled) { + $("cc-slots-text").textContent = `${fmt(c.parked)} / ${fmt(c.slots)}`; + $("cc-slots-bar").style.width = pct(c.parked, c.slots); + const budget = c.budget_mib * 1048576; + $("cc-mem-text").textContent = `${gb(c.bytes)} / ${gb(budget)} GB`; + $("cc-mem-bar").style.width = pct(c.bytes, budget); + } + $("cc-sum").textContent = c.requests ? `${fmt(c.requests_reused)} of ${fmt(c.requests)} requests reused part of their prompt` : ""; + const share = c.prompt_tokens ? ` (${fmt((100 * c.reused_tokens) / c.prompt_tokens)}% of all prompt tokens)` : ""; + const event = c.last_event ? `${c.last_event === "parked" ? "Parked" : "Restored"} ${fmt(c.last_tokens)} tokens, ${since(c.last_at)}` : null; + facts($("cc-facts"), [ + ["Last request", c.last_prompt != null ? `${fmt(c.last_reused || 0)} of ${fmt(c.last_prompt)} prompt tokens reused` : null], + ["Reused since start", c.requests ? `${fmt(c.reused_tokens)} tokens${share}` : null], + ["Parked / restored", c.enabled ? `${fmt(c.parks)} / ${fmt(c.restores)}${c.evictions ? ` ยท ${fmt(c.evictions)} evicted` : ""}` : null], + ["Last switch", c.enabled ? event : null], + ]); + $("cc-note").textContent = c.enabled + ? "A request that continues a parked conversation gets its state back instead of reading it again; the oldest goes when the slots or the memory are full." + : "The engine keeps the last conversation's state, so a follow-up reads only what is new. To keep several conversations (agents taking turns), add \"--conversation-cache-mib\", \"8192\" to the run config's args (docs/DETAILS.md)."; +} + function renderTotals(t) { if (!t || !t.requests) return ""; const since = new Date(t.since * 1000).toLocaleString([], {weekday: "short", hour: "2-digit", minute: "2-digit"}); @@ -396,6 +431,62 @@ function renderMcp() { }).join(""); } +// ------------------------------------------------------------------ Model settings (GET / POST /config, #564) +// A few documented keys of the run config (strata-.json), for every client, from the next start on. The +// server lists them, checks every value and keeps every other key of the file as it is. +let cfgKeys = []; +async function loadConfig() { + let r; + try { r = await fetch("config", {headers: headers()}); } catch (e) { return; } + if (!r.ok) { $("cfg-card").hidden = true; return; } // no run config, an older server, or no key yet + const c = await r.json(); + cfgKeys = c.keys || []; + $("cfg-file").textContent = c.file || ""; + $("cfg-form").innerHTML = cfgKeys.map((k, i) => { + const id = `cfg-${i}`, v = k.value; + let input; + if (k.kind === "bool" || k.kind === "enum") { + const opts = k.kind === "bool" ? [["true", "on"], ["false", "off"]] : k.choices.map((x) => [x, x]); + const cur = v == null ? "" : String(v); + input = ``; + } else { + const text = v == null ? "" : Array.isArray(v) ? v.join(", ") : String(v); + input = ``; + } + return `${input}`; + }).join(""); + $("cfg-card").hidden = false; +} +function configValue(k, el) { + const s = el.value.trim(); + if (s === "") return null; + if (k.kind === "bool") return s === "true"; + if (k.kind === "number") return Number(s); + return s; // enum, or names (the server splits them at commas) +} +$("cfg-save").addEventListener("click", async () => { + const set = {}; + cfgKeys.forEach((k, i) => { + const v = configValue(k, $(`cfg-${i}`)); + const old = Array.isArray(k.value) ? k.value.join(", ") : k.value; + if (JSON.stringify(v) !== JSON.stringify(old ?? null)) set[k.key] = v; + }); + if (!Object.keys(set).length) { $("cfg-msg").textContent = "Nothing changed."; return; } + try { + const r = await fetch("config", {method: "POST", headers: headers(true), body: JSON.stringify({set})}); + const b = await r.json(); + if (!r.ok) throw new Error((b.error || {}).message || `HTTP ${r.status}`); + $("cfg-msg").textContent = b.changed.length + ? `Saved (${b.changed.join(", ")}); the earlier file is ${b.file}.bak. Start the model again to use it.` : "Nothing changed."; + loadConfig(); + } catch (e) { + $("cfg-msg").textContent = ""; + toast("error", "Not saved", String(e.message || e), 6000); + } +}); + // ------------------------------------------------------------------ Markdown (escaped first, then formatted) function inline(s) { const codes = []; diff --git a/serve/web/index.html b/serve/web/index.html index fbccdad0..5c26ad82 100644 --- a/serve/web/index.html +++ b/serve/web/index.html @@ -125,6 +125,18 @@ +
+
Conversation cache
+ +
+

+
+ + diff --git a/setup.py b/setup.py index c4c9ce64..6a4c18d9 100644 --- a/setup.py +++ b/setup.py @@ -2422,6 +2422,86 @@ def write_config(path: Path, cfg: dict): os.replace(tmp, path) +# #629: the run config's keys setup writes itself (and rewrites on every setup run); any other key is the user's - a +# "sampling" or "mcp_servers" block, "allowed_hosts", "cors_origins", "open_browser" - and is kept when setup runs again +SETUP_KEYS = frozenset({"exe", "args", "cwd", "tokenizer", "model_name", "log", "lib_dirs", "port", "backend", "env", + "gpu", "gpus_asked", "layer_split", "host", "api_key", "draft_vocab", "vision"}) +SETUP_ENV = frozenset({"STRATA_HIPBLASLT_TUNING", "STRATA_RESIDENT_PIN"}) # the "env" entries setup writes +SETUP_VISION = frozenset({"exe", "mmproj", "model", "gpu", "max_tokens", "threads"}) + + +def carry_over(old: dict, cfg: dict) -> list[str]: + """#629: setup run again for an installed model keeps what the user added to its run config: every key setup does + not write (`SETUP_KEYS`), the "env" entries setup does not write, and in "vision" the keys setup does not write + plus an mmproj of their own (a Q8_0 one, #625) that still exists. `cfg` (the new config) is updated in place; + the names of what was kept are returned. Engine options added by hand to "args" are not merged (setup chooses + those): `args_dropped` names them.""" + kept = [] + for k, v in old.items(): + if k not in SETUP_KEYS and k not in cfg: + cfg[k] = v + kept.append(k) + env = {k: v for k, v in (old.get("env") or {}).items() if k not in SETUP_ENV and k not in (cfg.get("env") or {})} \ + if isinstance(old.get("env"), dict) else {} + if env: + cfg["env"] = {**(cfg.get("env") or {}), **env} + kept += [f"env {k}" for k in env] + ov, nv = old.get("vision"), cfg.get("vision") + if isinstance(ov, dict) and isinstance(nv, dict): + for k, v in ov.items(): + if k not in SETUP_VISION and k not in nv: + nv[k] = v + kept.append(f"vision {k}") + mm = ov.get("mmproj") # a file of the user's own: not the one setup downloads + if isinstance(mm, str) and Path(mm).name != Path(str(nv.get("mmproj"))).name and Path(mm).is_file(): + nv["mmproj"] = mm + kept.append("vision mmproj") + return kept + + +def args_dropped(old: dict, cfg: dict) -> list[str]: + """#629: the engine options of the earlier run config that the new one has no more (by flag name): options added + by hand, which a setup run does not carry over - the start of the line that names them.""" + def flags(c): + a = c.get("args") if isinstance(c.get("args"), list) else [] + return [str(x) for x in a if str(x).startswith("--")] + new = set(flags(cfg)) + return list(dict.fromkeys(f for f in flags(old) if f not in new)) + + +def write_setup_config(cfg_path: Path, cfg: dict, source: Path | None = None) -> None: + """#629: setup's run config, written over an earlier one for the same model without losing what the user added + to it: the keys setup does not write are carried over (carry_over), and the earlier file is kept as + strata-.json.bak when it changes. `source`: an earlier install's config to carry the keys over from when + this folder has none yet (a copy set up like the last one). A line says what was kept, one what was not.""" + old_path = cfg_path if cfg_path.is_file() else source + old = None + if old_path is not None and old_path.is_file(): + try: + old = json.loads(old_path.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + pass + if not isinstance(old, dict): + old = None + kept = carry_over(old, cfg) if old is not None else [] + bak = None + if cfg_path.is_file() and old != cfg: + bak = cfg_path.with_name(cfg_path.name + ".bak") + try: + shutil.copyfile(cfg_path, bak) + except OSError as e: + warn(f"could not keep a copy of the earlier {cfg_path.name} ({e.strerror or e})") + bak = None + write_config(cfg_path, cfg) + if kept: + ok(f"kept from your earlier {old_path.name}: " + ", ".join(kept)) + if bak is not None: + dropped = args_dropped(old, cfg) if old is not None else [] + say(f" the earlier run config is kept as {bak.name}" + ( + f"; engine options it had that this one has not (setup chooses those): {' '.join(dropped)}" + if dropped else "")) + + 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 @@ -2671,6 +2751,8 @@ def settings_summary(cfg: dict, port=None) -> str: srv = [f"{cfg.get('host', '127.0.0.1')}:{port or cfg.get('port', 8080)}"] if cfg.get("api_key"): srv.append("api key set") + if cfg.get("open_browser") is False: # #609 + srv.append("no browser") for k in ("gpu", "layer_split", "draft_vocab", "fit_max_tokens", "reasoning_budget_tokens", "anthropic_thinking"): if cfg.get(k) is not None: v = cfg[k] @@ -2699,8 +2781,9 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ 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) 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())) + ok("saved for this model: " + ", ".join( + "api key" if k == "api_key" else ("the browser opens" if v else "no browser") if k == "open_browser" + else f"{k.replace('_', ' ')} {v}" for k, v in keep.items())) cfg_path.touch() # the most recently used model if "--mtp" in cfg["args"][:-1]: refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) @@ -2768,7 +2851,8 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ if g is not None: cfg = ensure_engine_for([g], cfg_path, cfg, yes) ok("GPU: " + gpu_name(g)) - if open_browser: + browser = open_browser and cfg.get("open_browser") is not False # #609: "open_browser": false, --no-browser + if browser: cmd.append("--open") gb = 0.0 if "--native" in cfg["args"]: @@ -2788,7 +2872,8 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ say(f" Starting {cfg.get('model_name', 'the model')}: it loads {size} into RAM and locks part of it for the " "GPU.") say(" While it does, YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES (longer the first time after a") - say(" restart). That is normal: please wait and don't close this window - the browser opens when it is ready.") + say(" restart). That is normal: please wait and don't close this window - " + ( + "the browser opens when it is ready." if browser else "the server says when it is ready.")) say(" Later, closing this window stops the model.") say(" " + "-" * 100) for n, line in enumerate(textwrap.wrap(f"Settings ({cfg_path.name}): {settings_summary(cfg, port)}", 100, @@ -2819,6 +2904,31 @@ def saved_draft_vocab(cfg_path: Path) -> str | None: return v if v in DRAFT_VOCABS else None +def vision_tokens(asked: int | None, vision: str, earlier: Path | None) -> int: + """#625: the most image tokens a picture becomes (the config's vision.max_tokens): --vision-tokens N, else what an + earlier config of this model chose for the same encoder device (a setup run again keeps it), else the device's + default (VISION). More is allowed with a note on the time it takes: setup recommends, it does not cap.""" + default = VISION[vision]["max_tokens"] + if asked is None and earlier is not None: + try: + v = json.loads(earlier.read_text(encoding="utf-8-sig")).get("vision") + except (OSError, ValueError, AttributeError): + v = None + mt = v.get("max_tokens") if isinstance(v, dict) and bool(v.get("gpu")) == (vision == "gpu") else None + if isinstance(mt, int) and mt > 0 and mt != default: + asked = mt + if asked is None: + return default + note = "" + if vision == "cpu" and asked > default: + note = (" - on the CPU a picture takes longer to encode the more tokens it gets (several seconds more at " + "1,024 than at 300)") + elif asked > VISION["gpu"]["max_tokens"]: + note = " - more than the encoder's default needs more VRAM and context per picture" + ok(f"images: up to {asked} image tokens per picture (--vision-tokens; default {default}){note}") + return asked + + DRAFT_VOCAB_MIB = {"cjk": 348, "cyrillic": 193, "en": 133} # the draft head's VRAM per subset (IQ3_S: the largest) SMALL_DRAFT_VRAM_GB = 14 # #474: below this the default subset's head can be what does not fit @@ -2933,9 +3043,10 @@ def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: return cfg -def write_run_script(model, cfg_path, port): +def write_run_script(model, cfg_path, port, open_browser=True): + """run-.bat / .sh: the server with this config; `open_browser` False (#609: --no-browser) leaves --open out.""" serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), - "--port", str(port), "--open"] + "--port", str(port)] + (["--open"] if open_browser else []) if WIN: script = ROOT / f"run-{model.lower()}.bat" script.write_text("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" + @@ -3003,6 +3114,10 @@ def main() -> int: "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"], help="let the model read images (yes = the encoder on the GPU)") + ap.add_argument("--vision-tokens", type=int, metavar="N", + help="the most image tokens a picture becomes (default 1024 with the encoder on the GPU, 300 on " + "the CPU): more reads small text and charts better, and takes longer to encode; remembered " + "for this model") ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF", help="EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection " "(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md") @@ -3018,6 +3133,11 @@ def main() -> int: ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " "devices on your network (issue #26; set --api-key too)") ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0)") + ap.add_argument("--no-browser", dest="browser", action="store_false", default=None, + help="do not open the chat page in the browser when the model is ready (for a harness or an app " + "that uses the API; remembered for this model, also in run-.bat/.sh)") + ap.add_argument("--browser", dest="browser", action="store_true", + help="open the chat page again when the model is ready (the default; undoes --no-browser)") ap.add_argument("--data-dir", help="where the model files go (~70-120 GB): default Strata-data next to this folder, " "remembered for every Strata folder on this PC") ap.add_argument("--models-dir", help="where the GGUF files go (default: /models)") @@ -3060,6 +3180,8 @@ def main() -> int: a = ap.parse_args() if a.resident_budget_gib is not None and not a.resident_budget_gib > 0: ap.error("--resident-budget-gib takes a number of GiB above 0, e.g. --resident-budget-gib 32") + if a.vision_tokens is not None and a.vision_tokens < 1: + ap.error("--vision-tokens takes a number of image tokens, 1 or more, e.g. --vision-tokens 768") if a.vram_reserve_mib is not None and a.vram_reserve_mib < 0: ap.error("--vram-reserve-mib takes a number of MiB, 0 or more, e.g. --vram-reserve-mib 2048") if a.gpu is not None: # --gpu 0,2 means --gpus 0,2 (a user tried it: issue report) @@ -3080,6 +3202,7 @@ def main() -> int: if a.update: # #475: UPDATE.bat / update.sh - never starts the model return update_install(have, a) explicit = a.setup or a.model or a.family or a.check or a.no_start + adopted = None # #629: the earlier install this copy is set up like if not have and not explicit: # a new copy of Strata (an update unzipped elsewhere): set it prev = previous_config(elsewhere, load_settings()) # up like the last one, from the files already here if prev is not None: @@ -3088,6 +3211,7 @@ def main() -> int: say(f" Found your earlier install in {prev.parent} ({prev.stem[len('strata-'):]}): setting up this " "copy the same way - the model files are reused, nothing big is downloaded.") a.family, a.model, a.context = ch["family"], ch["model"], a.context or ch["context"] + adopted = prev a.kv = a.kv or ch["kv"] a.vision = a.vision or ch["vision"] a.experimental_speed_projection = a.experimental_speed_projection or ch["esp"] @@ -3122,14 +3246,14 @@ def main() -> int: + ("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, - "vram_reserve_mib": a.vram_reserve_mib}) + "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) if have and not (a.setup or a.model or a.family or a.check or a.no_start): if not a.build: update_installed_engine(a.prebuilt) if len(have) == 1: return start(have[0], 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, - "vram_reserve_mib": a.vram_reserve_mib}) + "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) say() for i, c in enumerate(have, 1): say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") @@ -3138,7 +3262,7 @@ def main() -> int: if pick <= len(have): return start(have[pick - 1], 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, - "vram_reserve_mib": a.vram_reserve_mib}) + "vram_reserve_mib": a.vram_reserve_mib, "open_browser": a.browser}) # ---- 1. the PC step(1, "checking your PC") @@ -3741,11 +3865,17 @@ def main() -> int: cfg["api_key"] = a.api_key if draft_vocab: cfg["draft_vocab"] = draft_vocab + if a.browser is not None: # #609: only when given (else an earlier choice is carried over) + cfg["open_browser"] = a.browser if vision != "none": + old_cfg = ROOT / f"strata-{tag.lower()}.json" + vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted) cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]), - "gpu": vision == "gpu", "max_tokens": VISION[vision]["max_tokens"]} + "gpu": vision == "gpu", "max_tokens": vt} if vision == "cpu": cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) + elif a.vision_tokens is not None: + warn("--vision-tokens: images are off for this model, so it is not used") cfg_path = ROOT / f"strata-{tag.lower()}.json" cal = None if hip else saved_calibration(cfg) # tools/calibrate.py is NVIDIA-only for now if cal is not None: @@ -3753,8 +3883,8 @@ 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 "")) - write_config(cfg_path, cfg) - script = write_run_script(tag, cfg_path, port) + write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None) + script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) # 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 " diff --git a/src/program/generate.cpp b/src/program/generate.cpp index b342b6fb..bb9037e8 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -429,6 +429,11 @@ struct Options { /// --serve: the token that opens a chat turn (<|im_start|>). The last one in a prompt is where the chat's /// history ends and the new assistant turn begins, which is the checkpoint the next request can reuse. int64_t turn_token = 248045; + /// --serve (#458, opt-in): the role token of a short turn the server puts right before the new assistant turn + /// (the "system" of a trailing reasoning-effort turn). When the turn before the last <|im_start|> opens with it, + /// the checkpoint goes in front of that turn instead, so it holds the conversation and not the effort text. + /// -1 = off (the checkpoint at the last <|im_start|>, as before). + int64_t tail_role_token = -1; /// --serve: a text part of the prompt of at most N tokens (a chat message, the assistant header, a short tool /// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always /// the batched path) @@ -533,6 +538,8 @@ void usage() { " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n" " --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" " --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" + " --tail-role-token ID --serve: a turn of this role right before the last turn is left out of\n" + " the conversation checkpoint (a trailing effort turn; default -1 = off)\n" " --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" " of the batched prompt path (default 64, 0 = off)\n" " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" @@ -1316,6 +1323,7 @@ int main(int argc, char** argv) { else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every"))); else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root"))); else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token")); + else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token")); else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); @@ -5093,7 +5101,7 @@ int main(int argc, char** argv) { "expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d " "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " - "conversation_cache_min_free_mib=%lld engine=" STRATA_VERSION "\n", + "conversation_cache_min_free_mib=%lld tail_role_token=%lld engine=" STRATA_VERSION "\n", (long long) o.max_context, o.kv.c_str(), (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1 ? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0), @@ -5104,7 +5112,7 @@ int main(int argc, char** argv) { (long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20), pool.workers(), o.pcie_frac, o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots, - (long long) o.conversation_cache_min_free_mib); + (long long) o.conversation_cache_min_free_mib, (long long) o.tail_role_token); } // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on // a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the @@ -5704,6 +5712,15 @@ int main(int argc, char** argv) { if (o.prompt_cache > 0 && o.turn_token >= 0) for (int64_t i = n - 1; i > resume; --i) if (ids[(size_t) i] == o.turn_token) { turn_at = i; break; } + // #458 (opt-in): a short turn of --tail-role-token's role right before the new assistant turn (the + // server's trailing reasoning-effort turn) stays out of the checkpoint, so the next request - another + // effort, or the next turn of the chat - finds the conversation without it + if (turn_at > 0 && o.tail_role_token >= 0) + for (int64_t i = turn_at - 1; i > resume; --i) + if (ids[(size_t) i] == o.turn_token) { + if (ids[(size_t) i + 1] == o.tail_role_token) turn_at = i; + break; + } // A prompt read from token 0 also stops at its FIRST turn boundary: the end of the system prompt (with // the tools), which every new chat of the same client shares. That checkpoint becomes the chain's root, // which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it. diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py index c14492cb..8b794191 100644 --- a/tools/strata_tokenizer.py +++ b/tools/strata_tokenizer.py @@ -213,18 +213,21 @@ class Tokenizer: out.append(i) return out - def _encode_matching(self, text: str, pat) -> list[int]: + def _encode_matching(self, text: str, pat, plain=()) -> list[int]: """Encode `text`, emitting any literal `pat` matches as single tokens and BPE-ing the rest. The split happens on the RAW text, before the byte mapping, because a special token's string is a literal to match rather than bytes to decompose. Everything between the matches is tokenized - normally - which is why a near-miss like `<|im_star` still costs ordinary tokens. + normally - which is why a near-miss like `<|im_star` still costs ordinary tokens. A match that starts + inside one of the `plain` (start, end) spans is left to the text around it (#537). """ if pat is None: return self._encode_plain(text) out: list[int] = [] pos = 0 for m in pat.finditer(text): + if plain and any(a <= m.start() < b for a, b in plain): + continue if m.start() > pos: out.extend(self._encode_plain(text[pos:m.start()])) out.append(self.special_tokens[m.group(0)]) @@ -233,13 +236,15 @@ class Tokenizer: out.extend(self._encode_plain(text[pos:])) return out - def encode(self, text: str, parse_special: bool = False) -> list[int]: + def encode(self, text: str, parse_special: bool = False, plain=()) -> list[int]: """Tokenize `text`. `parse_special` controls only the type-3 CONTROL literals such as `<|im_end|>`; the type-4 USER_DEFINED ones such as `` are matched either way. See the note in `__init__`. + `plain`: (start, end) spans of `text` that are ordinary text even where they spell a literal - a + `` quoted in a message (#537) - and are tokenized with the text around them. """ - return self._encode_matching(text, self._special_re if parse_special else self._always_re) + return self._encode_matching(text, self._special_re if parse_special else self._always_re, plain) def token_bytes(self, i: int) -> bytes: """The raw bytes of one token (a multi-byte character can be split across tokens).""" diff --git a/tools/test_setup_config.py b/tools/test_setup_config.py new file mode 100644 index 00000000..cd297645 --- /dev/null +++ b/tools/test_setup_config.py @@ -0,0 +1,244 @@ +"""Tests for what setup keeps in a model's run config when it runs again (#629), the browser choice (#609) and the +image-token flag (#625). Every outside effect is mocked (tools/test_setup_golden.py's install()). + + python -m unittest tools.test_setup_config +""" +from __future__ import annotations + +import contextlib +import io +import json +import sys +import tempfile +import unittest +import unittest.mock +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 +from test_setup_golden import PROFILES, install # noqa: E402 + + +def quiet(fn, *args, **kw): + out = io.StringIO() + with contextlib.redirect_stdout(out): + return fn(*args, **kw), out.getvalue() + + +USER = {"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0}, + "mcp_servers": {"files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]}}, + "mcp": {"timeout_s": 60, "max_result_chars": 16000, "max_rounds": 8}, + "cors_origins": ["http://localhost:3000"], "reasoning_effort": "low"} + + +class CarryOver(unittest.TestCase): + """#629: setup run again (a different --context) keeps the keys it does not write and keeps the old file as .bak.""" + + def setUp(self): + self.ram, self.found = PROFILES["64GB-1x32GB"] + + def run_setup(self, *extra, configs=()): + return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra], + configs=configs) + + def test_user_keys_survive_a_rerun(self): + code, out, first, _ = self.run_setup("--context", "65536") + self.assertEqual(code, 0, out) + old = {**first, **USER, "args": first["args"] + ["--hand-option", "7"]} + code, out, cfg, _ = self.run_setup("--context", "131072", configs=[("strata-q2_0.json", old)]) + self.assertEqual(code, 0, out) + for k, v in USER.items(): + self.assertEqual(cfg[k], v, k) + a = cfg["args"] + self.assertEqual(a[a.index("--max-context") + 1], "131072") # the new choice is used + self.assertNotIn("--hand-option", a) # setup chooses the engine options... + self.assertIn("kept from your earlier strata-q2_0.json: sampling, mcp_servers, mcp, cors_origins, " + "reasoning_effort", out) + self.assertIn("kept as strata-q2_0.json.bak", out) + self.assertIn("--hand-option", out) # ...and says which ones it did not keep + + def test_a_first_install_is_unchanged(self): + code, out, cfg, _ = self.run_setup() + self.assertEqual(code, 0, out) + self.assertNotIn("kept from", out) + self.assertNotIn(".bak", out) + self.assertFalse(set(cfg) - setup.SETUP_KEYS) # setup writes only its own keys + + def test_setup_keys_are_rewritten(self): + code, out, first, _ = self.run_setup() + old = {**first, "model_name": "renamed", "port": 9999, "draft_vocab": "en", "host": "0.0.0.0"} + code, out, cfg, _ = self.run_setup(configs=[("strata-q2_0.json", old)]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["model_name"], first["model_name"]) + self.assertEqual(cfg["port"], first["port"]) + self.assertNotIn("host", cfg) # as before: --host is given to setup + self.assertEqual(cfg["draft_vocab"], "en") # kept by its own rule (saved_draft_vocab) + self.assertNotIn("kept from", out) + + def test_write_setup_config(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-x.json" + mm = Path(d) / "mmproj-Q8_0.gguf" + mm.write_bytes(b"") + old = {"exe": "e", "args": ["--kv", "int8", "--threads", "8"], "sampling": {"temperature": 0.7}, + "env": {"STRATA_RESIDENT_PIN": "0", "MY_VAR": "1"}, + "vision": {"exe": "v", "mmproj": str(mm), "gpu": False, "max_tokens": 300, "min_tokens": 64}} + p.write_text(json.dumps(old), encoding="utf-8") + new = {"exe": "e2", "args": ["--kv", "int8"], + "vision": {"exe": "v2", "mmproj": str(Path(d) / "mmproj-BF16.gguf"), "gpu": False, "max_tokens": 300}} + _, out = quiet(setup.write_setup_config, p, new) + got = json.loads(p.read_text(encoding="utf-8")) + self.assertEqual(got["sampling"], {"temperature": 0.7}) + self.assertEqual(got["env"], {"MY_VAR": "1"}) # setup's own env entry is setup's to write + self.assertEqual(got["vision"]["mmproj"], str(mm)) # a Q8_0 mmproj of the user's own (#625) + self.assertEqual(got["vision"]["min_tokens"], 64) + self.assertEqual(got["exe"], "e2") + self.assertEqual(json.loads((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8")), old) + self.assertIn("--threads", out) + # the same again: nothing changes, so no new copy is made + (Path(d) / "strata-x.json.bak").unlink() + again = {"exe": "e2", "args": ["--kv", "int8"], + "vision": {"exe": "v2", "mmproj": str(Path(d) / "mmproj-BF16.gguf"), "gpu": False, + "max_tokens": 300}} + quiet(setup.write_setup_config, p, again) + self.assertFalse((Path(d) / "strata-x.json.bak").exists()) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), got) + + def test_an_unreadable_earlier_config_is_replaced_with_a_copy(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-x.json" + p.write_text("{cut off", encoding="utf-8") + quiet(setup.write_setup_config, p, {"exe": "e", "args": []}) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), {"exe": "e", "args": []}) + self.assertEqual((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8"), "{cut off") + + def test_a_missing_mmproj_is_not_carried(self): + old = {"vision": {"mmproj": "/nowhere/mmproj-Q8_0.gguf", "gpu": True}} + new = {"vision": {"mmproj": "/data/mmproj-BF16.gguf", "gpu": True}} + self.assertEqual(setup.carry_over(old, new), []) + self.assertEqual(new["vision"]["mmproj"], "/data/mmproj-BF16.gguf") + + def test_a_copy_set_up_like_the_last_one_keeps_them_too(self): + with tempfile.TemporaryDirectory() as d: + src = Path(d) / "other" / "strata-x.json" + src.parent.mkdir() + src.write_text(json.dumps({"exe": "old", "mcp_servers": {"a": {"command": "x"}}}), encoding="utf-8") + p = Path(d) / "strata-x.json" + quiet(setup.write_setup_config, p, {"exe": "new"}, src) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), + {"exe": "new", "mcp_servers": {"a": {"command": "x"}}}) + self.assertFalse((Path(d) / "strata-x.json.bak").exists()) # nothing here was replaced + + +class NoBrowser(unittest.TestCase): + """#609 (#631): --no-browser keeps the chat page from opening: "open_browser": false in the run config, no --open + on the start's server command or in run-.bat/.sh. Without the flag nothing changes.""" + + def setUp(self): + self.ram, self.found = PROFILES["64GB-1x32GB"] + + def run_setup(self, *extra, configs=()): + return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra], + configs=configs) + + def test_at_setup(self): + code, out, cfg, _ = self.run_setup("--no-browser") + self.assertEqual(code, 0, out) + self.assertIs(cfg["open_browser"], False) + code, out, cfg, _ = self.run_setup() + self.assertNotIn("open_browser", cfg) # not given: the config as before + # setup run again without the flag keeps the choice (#629); --browser undoes it + code, out, cfg, _ = self.run_setup(configs=[("strata-q2_0.json", {"open_browser": False})]) + self.assertIs(cfg["open_browser"], False) + code, out, cfg, _ = self.run_setup("--browser", configs=[("strata-q2_0.json", {"open_browser": False})]) + self.assertIs(cfg["open_browser"], True) + + def test_run_script(self): + with tempfile.TemporaryDirectory() as d, unittest.mock.patch.object(setup, "ROOT", Path(d)): + text = lambda p: p.read_text(encoding="utf-8") # noqa: E731 + self.assertIn('"--open"', text(setup.write_run_script("Q2_0", Path(d) / "strata-q2_0.json", 8080))) + script = setup.write_run_script("Q2_0", Path(d) / "strata-q2_0.json", 8080, False) + self.assertNotIn("--open", text(script)) + self.assertIn('"--port" "8080"', text(script)) + + def start_cmd(self, cfg, keep=None): + with tempfile.TemporaryDirectory() as d: + exe = Path(d) / "strata.exe" + exe.write_bytes(b"") + p = Path(d) / "strata-q2_0.json" + p.write_text(json.dumps({"exe": str(exe), "args": ["--kv", "int8"], "gpu": 0, "gpus_asked": True, **cfg})) + call = unittest.mock.Mock(return_value=0) + with unittest.mock.patch.object(setup, "gpus", lambda: self.found), \ + unittest.mock.patch.object(setup, "is_wsl", lambda: False), \ + unittest.mock.patch.object(setup, "ensure_engine_for", lambda cards, path, c, yes: c), \ + unittest.mock.patch.object(setup.subprocess, "call", call): + _, out = quiet(setup.start, p, None, None, True, True, None, keep) + return call.call_args[0][0], out, json.loads(p.read_text()) + + def test_on_a_start(self): + cmd, out, _ = self.start_cmd({}) + self.assertIn("--open", cmd) # the default, as before + self.assertIn("the browser opens when it is ready", out) + cmd, out, _ = self.start_cmd({"open_browser": False}) + self.assertNotIn("--open", cmd) + self.assertNotIn("the browser opens", out) + self.assertIn("no browser", out) # the Settings line says so + cmd, out, saved = self.start_cmd({}, {"open_browser": False}) # START-HERE --no-browser: kept from now on + self.assertNotIn("--open", cmd) + self.assertIs(saved["open_browser"], False) + self.assertIn("saved for this model: no browser", out) + cmd, out, saved = self.start_cmd({"open_browser": False}, {"open_browser": True}) + self.assertIn("--open", cmd) + self.assertIs(saved["open_browser"], True) + + +class VisionTokens(unittest.TestCase): + """#625: --vision-tokens N sets the config's vision.max_tokens (the most image tokens a picture becomes); a setup + run again keeps it for the same encoder device; without it the device's default, as before.""" + + def setUp(self): + self.ram, self.found = PROFILES["64GB-1x32GB"] + + def run_setup(self, *extra, configs=()): + return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra], + configs=configs) + + def test_the_flag(self): + code, out, cfg, _ = self.run_setup("--vision", "cpu") + self.assertEqual(code, 0, out) + self.assertEqual(cfg["vision"]["max_tokens"], 300) # the default, as before + self.assertNotIn("--vision-tokens", out) + code, out, cfg, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "768") + self.assertEqual(code, 0, out) + self.assertEqual(cfg["vision"]["max_tokens"], 768) + self.assertIn("up to 768 image tokens", out) + self.assertIn("longer to encode", out) # a note, not a cap + code, out, cfg, _ = self.run_setup("--vision", "gpu", "--vision-tokens", "2048") + self.assertEqual(cfg["vision"]["max_tokens"], 2048) + self.assertIn("more VRAM", out) + + def test_kept_when_setup_runs_again(self): + code, out, first, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "768") + old = [("strata-q2_0.json", first)] + code, out, cfg, _ = self.run_setup("--vision", "cpu", "--context", "65536", configs=old) + self.assertEqual(cfg["vision"]["max_tokens"], 768) + code, out, cfg, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "300", configs=old) + self.assertEqual(cfg["vision"]["max_tokens"], 300) # given again: the new value + code, out, cfg, _ = self.run_setup("--vision", "gpu", configs=old) + self.assertEqual(cfg["vision"]["max_tokens"], 1024) # another device: its own default + + def test_refused_and_unused(self): + with contextlib.redirect_stderr(io.StringIO()) as err: + code, out, cfg, _ = self.run_setup("--vision-tokens", "0") + self.assertEqual(code, 2) + self.assertIn("--vision-tokens takes a number", err.getvalue()) + code, out, cfg, _ = self.run_setup("--vision", "no", "--vision-tokens", "768") + self.assertEqual(code, 0, out) + self.assertNotIn("vision", cfg) + self.assertIn("images are off", out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_golden.py b/tools/test_setup_golden.py index 136b156d..a3c0a2d8 100644 --- a/tools/test_setup_golden.py +++ b/tools/test_setup_golden.py @@ -114,7 +114,7 @@ def install(ram, found, argv, answers=None, extra=(), avx512=False, configs=()): mock.patch.object(setup, "run", lambda *a, **k: None), mock.patch.object(setup, "mtp_corrupt", lambda *a, **k: False), mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), - mock.patch.object(setup, "write_run_script", lambda tag, cfg, port: t / f"run-{tag}.bat"), + mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: t / f"run-{tag}.bat"), mock.patch.object(setup, "saved_calibration", lambda cfg: None), mock.patch.object(setup, "calibrate_config", mock.Mock(side_effect=AssertionError("calibrated"))), mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}), diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index dab1e74c..38caa4e6 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -175,7 +175,7 @@ class Base(unittest.TestCase): mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.verified.append((s.name, size, sha))), mock.patch.object(setup, "run", fake_run), mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), - mock.patch.object(setup, "write_run_script", lambda tag, cfg, port: self.t / f"start-{tag}.bat"), + mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: self.t / f"start-{tag}.bat"), mock.patch.object(setup, "saved_calibration", lambda cfg: None), mock.patch.object(setup, "start", mock.Mock(side_effect=AssertionError("started"))), mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}),