From 07b4a6263ab957f79d8f20db5e3fc9b98403896c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 25 Sep 2026 06:13:46 +0200 Subject: [PATCH] Engine v0.1.2: streaming tool calls, live status, real cancel; fix requests stalling on a full GPU Streaming - tool calls stream as they are written (OpenAI tool_calls deltas, Anthropic input_json_delta) - keep-alives while a long prompt is read, progress in the server window, GET /status - closing the connection or pressing stop really stops the engine (STOP) Stalled requests (mostly image turns) - the expert cache is sized after its slots are written (Windows only counts GPU memory once it is touched), so the reserve really stays free instead of the card running at 0 MiB and paging - the prompt chunk shrinks when its buffers do not fit in the cache, instead of allocating on top - the image encoder warms up before the engine starts; images are encoded in request order - the log shows the VRAM left once everything is loaded setup.py now requires engine 0.1.2 (downloaded automatically on the next START-HERE.bat). --- docs/DETAILS.md | 7 + include/strata/prefill/prefill.hpp | 3 + serve/frontend.py | 139 +++++++++++++++++- serve/server.py | 222 +++++++++++++++++++++++++---- setup.py | 12 +- src/core/expert_source.cpp | 11 ++ src/prefill/prefill.cpp | 2 + src/program/generate.cpp | 160 ++++++++++++++++++--- tools/vision/strata_vision.cpp | 24 ++++ 9 files changed, 526 insertions(+), 54 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 71c87303..51bfc551 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -161,6 +161,7 @@ The server listens on `http://127.0.0.1:8080` (change with `--port` in setup, or | OpenAI Chat Completions (stream and non-stream, tools) | `POST /v1/chat/completions` | | Anthropic Messages (stream and non-stream, tools) | `POST /v1/messages` | | Model list / health | `GET /v1/models`, `GET /health` | +| What the model is doing right now | `GET /status` | ```bash curl http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" -d '{ @@ -186,6 +187,11 @@ print(r.choices[0].message.content) Without a setting the model uses its own default, **high**. `none` answers at once (fastest); `low` keeps the thinking short. The levels are instructions the model was trained with, not a hard token limit: on easy questions all three think briefly, on hard ones `high` thinks longest and is most accurate. +- **Streaming.** With `"stream": true` everything arrives as it is made: the thinking, the answer, and tool calls + (the tool's name first, then its arguments piece by piece, like OpenAI and Anthropic do). While the model reads a + long prompt the stream sends keep-alives, so agents do not time out; the server window prints progress every + 15 s, and `GET /status` says what it is doing (`reading the prompt`, `answering`, tokens so far). Closing the + connection or pressing stop in your app really stops the model, so the next request starts at once. - **Chat apps.** Any app with an "OpenAI-compatible" provider works: base URL `http://127.0.0.1:8080/v1`, any API key. - **Context.** Chosen in setup (8K-262K). Requests longer than that are refused, never silently cut. - **From other devices / the internet.** The server listens on your PC only (`127.0.0.1`). To reach it from elsewhere, @@ -289,6 +295,7 @@ test images. | `this server was started without the vision encoder` | The model was set up for text only: run setup again with `--vision gpu`. | | A picture is refused or `cannot read the image` | The file is not a picture Pillow can open (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF work). | | Pictures are slow (10-30 s) | The encoder runs on the CPU: run setup again with `--vision gpu` (needs ~1.4 GB of VRAM). | +| A request never finishes (older engines, mostly with pictures) | Run `START-HERE.bat` once to get engine 0.1.2 or newer. It keeps a real margin of VRAM free: the log says `... MiB of VRAM free with everything loaded` and warns when it is close to 0. | | Anything else | The engine log is `strata-.log` in this folder. | --- diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 11c0baef..a5bd063e 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -62,6 +62,9 @@ public: /// K/V from them. The prefill stream is synchronized before the call. std::function on_chunk; + /// Checked before every chunk: true stops the prompt early (`run` returns false with err "cancelled"). + std::function should_stop; + /// The vision path: HOST rows (n_embd floats) indexed by absolute position, read in place of the token /// embedding where non-null (an image's <|image_pad|> cells). Null (default): every position embeds its token. const float* const* embd_rows = nullptr; diff --git a/serve/frontend.py b/serve/frontend.py index de7a0b03..dfa29817 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -270,11 +270,127 @@ class OutputParser: """Incremental parser of the model's text. Feed deltas; get events. A tag split across deltas is held back until it is complete, so clients never see ` between -> str|raw -> ... -> done + self.scall = None # the ToolCall being streamed (its id is reused by the final event) + self.sfirst = True + self.sval_started = False + self.sdeclared = {} + + def _scan(self) -> list[Event]: + """Advance the streaming view of the call body in self.buf (see stream_tools).""" + out = [] + + def args(s): + if s: + out.append(Event("tool_args", s, call=self.scall)) + while True: + rest = self.buf[self.sp:] + if self.ss == "name": + a = rest.find("", a + 10) if a >= 0 else -1 + if b < 0: + return out + name = rest[a + 10:b] + self.scall = ToolCall(name=name, arguments={}) + props = ((self.schemas.get(name) or {}).get("parameters") or {}).get("properties") or {} + self.sdeclared = {k: (v or {}).get("type") for k, v in props.items()} + out.append(Event("tool_start", call=self.scall)) + args("{") + self.sp += b + 1 + self.ss = "between" + elif self.ss == "between": + stripped = rest.lstrip() + self.sp += len(rest) - len(stripped) + if stripped.startswith("") + if b < 0: + return out + pname = stripped[11:b] + args(("" if self.sfirst else ",") + json.dumps(pname) + ":") + self.sfirst = False + self.sp += b + 1 + if self.sdeclared.get(pname) == "string": + args('"') + self.ss, self.sval_started = "str", False + else: + self.ss = "raw" + elif stripped.startswith(""): + args("}") + self.sp += len("") + self.ss = "done" + else: + return out # a tag still arriving (or trailing text): wait + elif self.ss == "str": + if not self.sval_started: + if not rest: + return out + if rest[0] == "\n": # the value's leading newline is not part of it + self.sp += 1 + rest = rest[1:] + self.sval_started = True + end = rest.find("") + if end >= 0: + value = rest[:end] + if value.endswith("\n"): + value = value[:-1] + args(json.dumps(value)[1:-1] + '"') + self.sp += end + len("") + self.ss = "between" + continue + safe = len(rest) - self._hold(rest, ("",)) + if safe > 0 and rest[safe - 1] == "\n": # may be the trailing newline before + safe -= 1 + if safe > 0: + args(json.dumps(rest[:safe])[1:-1]) + self.sp += safe + return out + elif self.ss == "raw": + end = rest.find("") + if end < 0: + return out + value = rest[:end] + if value.startswith("\n"): + value = value[1:] + if value.endswith("\n"): + value = value[:-1] + try: + v = json.loads(value) + except ValueError: + v = value + args(json.dumps(v, ensure_ascii=False)) + self.sp += end + len("") + self.ss = "between" + else: + return out + + def _close_scan(self) -> list[Event]: + """A streamed call that ended without a clean : close its JSON so clients can still parse it.""" + out = [] + if self.scall is None or self.ss == "done": + return out + tail = "" + if self.ss == "str": + tail += '"' + elif self.ss == "raw": + tail += json.dumps(self.buf[self.sp:].strip("\n")) + tail += "}" + out.append(Event("tool_args", tail, call=self.scall)) + self.ss = "done" + return out def _hold(self, text: str, tags: tuple[str, ...]) -> int: """Length of the longest suffix of `text` that is a proper prefix of one of `tags`.""" @@ -325,17 +441,36 @@ class OutputParser: self.state = "call" else: i = self.buf.find(CALL_END) + if self.stream_tools: + if i >= 0: + whole, self.buf = self.buf, self.buf[:i] # scan only the body + out += self._scan() + out += self._close_scan() + self.buf = whole + else: + out += self._scan() if i < 0: return out body = self.buf[:i] self.buf = self.buf[i + len(CALL_END):] name = body.strip()[len("", 1)[0] - out.append(Event("tool_call", call=parse_tool_call(body, self.schemas.get(name)))) + call = parse_tool_call(body, self.schemas.get(name)) + if self.scall is not None: + call.id = self.scall.id + out.append(Event("tool_call", call=call)) + self._reset_scan() self.state, self.lead = "content", True def finish(self) -> list[Event]: """End of generation: flush whatever is held (an unterminated tool call is returned as content).""" out = [] + if self.state == "call" and self.stream_tools and self.scall is not None: + out += self._scan() # the output ended inside a call that was already announced + out += self._close_scan() + out.append(Event("tool_call", call=self.scall)) + self.buf = "" + self._reset_scan() + return out if self.buf: kind = {"reasoning": "reasoning", "content": "content"}.get(self.state, "content") text = self.buf if self.state != "call" else CALL_START + self.buf diff --git a/serve/server.py b/serve/server.py index a42eda25..16a7d3e4 100644 --- a/serve/server.py +++ b/serve/server.py @@ -22,6 +22,7 @@ import base64 import hashlib import json import os +import queue import subprocess import sys import tempfile @@ -78,38 +79,75 @@ class StrataEngine: self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) self.max_context = 0 + self.can_stop = False # the engine honours a STOP line mid-request (READY stop) self.last = {} for line in self.proc.stdout: if line.startswith("READY"): - self.max_context = int(line.split()[1]) + f = line.split() + self.max_context = int(f[1]) + self.can_stop = "stop" in f[2:] break if self.max_context <= 0: raise RuntimeError("the engine exited before it was ready" + (f" (see {log})" if log else "")) + # the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks) + self.lines: queue.Queue = queue.Queue() + threading.Thread(target=self._pump, daemon=True).start() + + def _pump(self): + for line in self.proc.stdout: + self.lines.put(line) + self.lines.put(None) + + def _parse_done(self, line): + f = line.split() + self.last = {"generated": int(f[1]), "prompt_tokens": int(f[2]), "prompt_ms": float(f[3]), + "decode_ms": float(f[4]), "finish": f[5]} def generate(self, ids, max_new, sampling, cancel, embeddings=None): + """Yields token ids, and None as a heartbeat every 10 s while the engine is quiet (reading a long prompt): + the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that + has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" head = f"GENI {int(max_new)} {embeddings}" if embeddings else f"GEN {int(max_new)}" self.proc.stdin.write(f"{head} {','.join(str(int(t)) for t in ids)}\n") self.proc.stdin.flush() done = False try: - for line in self.proc.stdout: + while True: + try: + line = self.lines.get(timeout=10) + except queue.Empty: + if cancel.is_set(): + return + yield None + continue + if line is None: + done = True + raise RuntimeError("the engine process ended") if line.startswith("T "): - if not cancel.is_set(): - yield int(line[2:]) + if cancel.is_set(): + return + yield int(line[2:]) elif line.startswith("DONE"): - f = line.split() - self.last = {"generated": int(f[1]), "prompt_tokens": int(f[2]), "prompt_ms": float(f[3]), - "decode_ms": float(f[4]), "finish": f[5]} + self._parse_done(line) done = True return elif line.startswith("ERR"): done = True raise ValueError(line[4:].strip()) - raise RuntimeError("the engine process ended") finally: - if not done: # the consumer stopped early: drain to DONE - for line in self.proc.stdout: - if line.startswith("DONE") or line.startswith("ERR"): + if not done: # the consumer stopped early: stop the engine, drain to DONE + if self.can_stop: + try: + self.proc.stdin.write("STOP\n") + self.proc.stdin.flush() + except OSError: + pass + while True: + line = self.lines.get() + if line is None or line.startswith("ERR"): + break + if line.startswith("DONE"): + self._parse_done(line) break def close(self): @@ -274,6 +312,8 @@ 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) + self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now + self.status_lock = threading.Lock() self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) + tokenizer.encode("<|endoftext|>", parse_special=True)) @@ -287,7 +327,12 @@ class Service: raise ValueError("this server was started without the vision encoder (run setup again and choose " "'vision'), so it cannot read images") pad = self.tok.encode(IMAGE_PAD, parse_special=True)[0] - encoded = [self.vision.encode(src) for src in images] + # Encode only while the engine is idle: the engine and the image encoder (a separate process) must not + # run on the GPU at the same time - an encode during a running request left that request stuck at + # "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the + # same FIFO as the requests. + with self.fifo: + encoded = [self.vision.encode(src) for src in images] out, k = [], 0 for t in ids: # one <|image_pad|> per image -> one per image token if t == pad and k < len(encoded): @@ -308,24 +353,79 @@ class Service: f"({self.engine.max_context}); requests are never truncated") return ids, kwargs.get("enable_thinking", True) is not False + def _note(self, n, evs): + with self.status_lock: + s = self.status + s["generated"] = n + if s.get("first_token") is None: + s["first_token"] = time.time() + for ev in evs: + if ev.kind == "reasoning": + s["phase"] = "thinking" + elif ev.kind == "content": + s["phase"] = "answering" + elif ev.kind == "tool_start": + s["phase"], s["tool"] = f"writing a tool call: {ev.call.name}", ev.call.name + elif ev.kind == "tool_call": + s["phase"] = "tool call complete" + s["tail"] = (s["tail"] + (ev.text or ""))[-600:] + + def _progress(self, last_print, every=15.0): + """A progress line in the server window every `every` seconds while a request runs.""" + now = time.time() + if now - last_print < every: + return last_print + with self.status_lock: + s = dict(self.status) + el = now - s.get("started", now) + if s.get("first_token") is None: + print(f"[strata] reading the prompt: {s.get('prompt_tokens', 0)} tokens, {el:.0f} s so far", flush=True) + else: + rate = s["generated"] / max(1e-6, now - s["first_token"]) + print(f"[strata] {s['phase']}: {s['generated']} of max {s.get('max_tokens')} tokens, {rate:.1f} tok/s, " + f"{el:.0f} s", flush=True) + return now + def run(self, ids, thinking, tools, max_new, sampling, cancel) -> Iterator[tuple[str, object]]: """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}).""" - parser, detok, n, finish = OutputParser(thinking=thinking, tools=tools), Detokenizer(self.tok), 0, "length" + parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True) + detok, n, finish = Detokenizer(self.tok), 0, "length" emb = getattr(self.embeddings, "path", None) + with self.status_lock: + self.status["queued"] += 1 try: with self.fifo: + with self.status_lock: + self.status["queued"] -= 1 + self.status.update(busy=True, phase="reading the prompt", prompt_tokens=len(ids), generated=0, + started=time.time(), first_token=None, tool=None, tail="", max_tokens=max_new) + last_print = time.time() gen = self.engine.generate(ids, max_new, sampling, cancel, embeddings=emb) if emb else \ self.engine.generate(ids, max_new, sampling, cancel) for t in gen: + if t is None: # heartbeat while the engine is quiet + last_print = self._progress(last_print) + yield "ping", None + continue n += 1 if t in self.stop_ids: finish = "stop" break - for ev in parser.feed(detok.push(t)): + evs = parser.feed(detok.push(t)) + self._note(n, evs) + last_print = self._progress(last_print) + for ev in evs: yield "event", ev + if cancel.is_set(): + finish = "cancel" finally: if emb: Path(emb).unlink(missing_ok=True) + with self.status_lock: + if self.status.get("busy"): + el = time.time() - self.status.get("started", time.time()) + print(f"[strata] done: {n} tokens in {el:.0f} s ({finish})", flush=True) + self.status["busy"] = False for ev in parser.finish(): yield "event", ev yield "done", {"finish": finish, "completion_tokens": n} @@ -341,20 +441,32 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel yield chunk({"role": "assistant", "content": ""}) calls = 0 + streamed = {} # tool call id -> index, for calls sent piece by piece for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel): - if kind == "event": + if kind == "ping": + yield None + elif kind == "event": ev: Event = x if ev.kind == "reasoning" and ev.text: yield chunk({"reasoning_content": ev.text}) elif ev.kind == "content" and ev.text: yield chunk({"content": ev.text}) + elif ev.kind == "tool_start": + streamed[ev.call.id] = calls + calls += 1 + yield chunk({"tool_calls": [{"index": streamed[ev.call.id], "id": ev.call.id, "type": "function", + "function": {"name": ev.call.name, "arguments": ""}}]}) + elif ev.kind == "tool_args": + yield chunk({"tool_calls": [{"index": streamed[ev.call.id], "function": {"arguments": ev.text}}]}) + elif ev.kind == "tool_call" and ev.call.id in streamed: + continue elif ev.kind == "tool_call": yield chunk({"tool_calls": [{"index": calls, "id": ev.call.id, "type": "function", "function": {"name": ev.call.name, "arguments": json.dumps(ev.call.arguments, ensure_ascii=False)}}]}) calls += 1 else: - finish = "tool_calls" if calls and x["finish"] == "stop" else x["finish"] + finish = "tool_calls" if calls and x["finish"] == "stop" else {"cancel": "stop"}.get(x["finish"], x["finish"]) last = chunk({}, finish) last["usage"] = {"prompt_tokens": len(ids), "completion_tokens": x["completion_tokens"], "total_tokens": len(ids) + x["completion_tokens"]} @@ -362,13 +474,22 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel def openai_collect(chunks) -> dict: - content, reasoning, calls, last = [], [], [], None + content, reasoning, by_index, last = [], [], {}, None for c in chunks: + if c is None: # a heartbeat + continue d = c["choices"][0]["delta"] content.append(d.get("content") or "") reasoning.append(d.get("reasoning_content") or "") - calls += [{k: v for k, v in tc.items() if k != "index"} for tc in d.get("tool_calls") or []] + for tc in d.get("tool_calls") or []: # streamed calls arrive in pieces: merge them by index + cur = by_index.setdefault(tc.get("index", len(by_index)), {"id": None, "type": "function", + "function": {"name": "", "arguments": ""}}) + cur["id"] = tc.get("id") or cur["id"] + fn = tc.get("function") or {} + cur["function"]["name"] += fn.get("name") or "" + cur["function"]["arguments"] += fn.get("arguments") or "" last = c + calls = [by_index[i] for i in sorted(by_index)] msg = {"role": "assistant", "content": "".join(content) or None} if "".join(reasoning): msg["reasoning_content"] = "".join(reasoning) @@ -390,12 +511,25 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can def close(): return ("content_block_stop", {"type": "content_block_stop", "index": index}) + streamed = set() for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel): + if kind == "ping": + yield None + continue if kind == "event": ev: Event = x - want = {"reasoning": "thinking", "content": "text", "tool_call": "tool_use"}[ev.kind] - if ev.kind != "tool_call" and not ev.text: + if ev.kind == "tool_args": + yield "content_block_delta", {"type": "content_block_delta", "index": index, + "delta": {"type": "input_json_delta", "partial_json": ev.text}} continue + if ev.kind == "tool_call" and ev.call.id in streamed: + continue + want = {"reasoning": "thinking", "content": "text", "tool_call": "tool_use", "tool_start": "tool_use"}[ev.kind] + if ev.kind not in ("tool_call", "tool_start") and not ev.text: + continue + if ev.kind == "tool_start": + streamed.add(ev.call.id) + used_tool = True if open_kind != want or want == "tool_use": if open_kind is not None: yield close() @@ -412,6 +546,8 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can elif want == "text": yield "content_block_delta", {"type": "content_block_delta", "index": index, "delta": {"type": "text_delta", "text": ev.text}} + elif ev.kind == "tool_start": + pass # its input follows as tool_args pieces else: used_tool = True yield "content_block_delta", {"type": "content_block_delta", "index": index, "delta": { @@ -420,7 +556,7 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can if open_kind is not None: yield close() stop = "tool_use" if used_tool and x["finish"] == "stop" else \ - {"stop": "end_turn", "length": "max_tokens"}[x["finish"]] + {"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]] yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None}, "usage": {"output_tokens": x["completion_tokens"]}} yield "message_stop", {"type": "message_stop"} @@ -428,7 +564,10 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can def anthropic_collect(events) -> dict: msg, blocks = None, [] - for name, e in events: + for item in events: + if item is None: # a heartbeat + continue + name, e = item if name == "message_start": msg = e["message"] elif name == "content_block_start": @@ -439,8 +578,11 @@ def anthropic_collect(events) -> dict: b["text"] += d["text"] elif d["type"] == "thinking_delta": b["thinking"] += d["thinking"] - else: - b["input"] = json.loads(d["partial_json"]) + else: # input_json_delta pieces: parsed when complete + b["_json"] = b.get("_json", "") + d["partial_json"] + elif name == "content_block_stop" and blocks and "_json" in blocks[-1]: + b = blocks[-1] + b["input"] = json.loads(b.pop("_json") or "{}") elif name == "message_delta": msg["stop_reason"] = e["delta"]["stop_reason"] msg["usage"]["output_tokens"] = e["usage"]["output_tokens"] @@ -486,6 +628,17 @@ def make_handler(svc: Service): elif path == "/health": self._json(200, {"status": "ok", "max_context": svc.engine.max_context, "model": svc.model, "images": svc.vision is not None, "api_key": bool(svc.api_key)}) + elif path == "/status": + with svc.status_lock: + s = dict(svc.status) + now = time.time() + if s.get("busy"): + s["elapsed_s"] = round(now - s["started"], 1) + if s.get("first_token"): + s["tokens_per_s"] = round(s["generated"] / max(1e-6, now - s["first_token"]), 1) + for k in ("started", "first_token"): + s.pop(k, None) + self._json(200, s) elif path == "/v1/models": if self._authorized(): self._json(200, {"object": "list", "data": [{"id": svc.model, "object": "model"}]}) @@ -523,11 +676,15 @@ def make_handler(svc: Service): self._sse() try: for c in chunks: - self.wfile.write(b"data: " + json.dumps(c, ensure_ascii=False).encode() + b"\n\n") + if c is None: + self.wfile.write(b": keep-alive\n\n") # an SSE comment: clients ignore it + else: + self.wfile.write(b"data: " + json.dumps(c, ensure_ascii=False).encode() + b"\n\n") self.wfile.flush() self.wfile.write(b"data: [DONE]\n\n") except OSError: - cancel.set() # client went away: stop at the next step + cancel.set() # client went away: stop the engine + chunks.close() def _anthropic(self, req): messages, tools, kw = anthropic_to_messages(req) @@ -539,12 +696,17 @@ def make_handler(svc: Service): return self._json(200, anthropic_collect(events)) self._sse() try: - for name, e in events: - self.wfile.write(f"event: {name}\n".encode() + b"data: " + - json.dumps(e, ensure_ascii=False).encode() + b"\n\n") + for item in events: + if item is None: + self.wfile.write(b": keep-alive\n\n") + else: + name, e = item + self.wfile.write(f"event: {name}\n".encode() + b"data: " + + json.dumps(e, ensure_ascii=False).encode() + b"\n\n") self.wfile.flush() except OSError: cancel.set() + events.close() return Handler @@ -575,7 +737,7 @@ def main() -> int: ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", ""), help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY") a = ap.parse_args() - cfg = json.loads(Path(a.config).read_text(encoding="utf-8")) if a.config else {} + cfg = json.loads(Path(a.config).read_text(encoding="utf-8-sig")) if a.config else {} # Notepad adds a BOM try: # before the minutes of loading: is the port free? Server((a.host, a.port), BaseHTTPRequestHandler).server_close() except OSError: diff --git a/setup.py b/setup.py index f53493f7..a17eb68c 100644 --- a/setup.py +++ b/setup.py @@ -54,7 +54,7 @@ PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" # the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"] MIN_DRIVER = 580 # CUDA 13.0 -MIN_ENGINE = (0, 1, 1) # the ready-made engine that reads split models (Swift 1.5) +MIN_ENGINE = (0, 1, 2) # split models (Swift 1.5), STOP, cache sized after the slots are written PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow"] MODELS = { @@ -82,9 +82,9 @@ FAMILIES = { "license": "Swift Open License 1.0: https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"}, } MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" -# the image encoder on the GPU: ~0.9 GB of weights + ~0.3 GB of work buffers at 1024 image tokens, kept free of -# expert slots (the engine's default reserve is 700 MiB) -VISION = {"gpu": {"max_tokens": 1024, "reserve_mib": 2100}, +# the image encoder on the GPU (~1.2 GB at 1024 image tokens) warms up before the engine starts, so the engine +# sizes its expert slots around it and the default reserve (700 MiB) is enough; engines before 0.1.2 need more +VISION = {"gpu": {"max_tokens": 1024, "reserve_mib": 700}, "cpu": {"max_tokens": 300, "reserve_mib": 700}} EXE = "strata.exe" if WIN else "strata" VEXE = "strata-vision.exe" if WIN else "strata-vision" @@ -572,7 +572,7 @@ def installed_configs(): def start(cfg_path: Path, port: int | None, open_browser=True) -> int: - cfg = json.loads(cfg_path.read_text(encoding="utf-8")) + cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()] if missing: fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run it again with --setup to repair") @@ -631,7 +631,7 @@ def main() -> int: return start(have[0], None) say() for i, c in enumerate(have, 1): - say(f" {i}) {json.loads(c.read_text(encoding='utf-8')).get('model_name', c.stem)}") + say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") say(f" {len(have) + 1}) install another model / change settings") pick = int(ask("Which one?", [str(i) for i in range(1, len(have) + 2)], "1", a.yes)) if pick <= len(have): diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 3eb65e9d..0ab1ce13 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -263,8 +264,14 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 if (native && d.nact_multi.size() < (size_t) MAXT * kNativeActBytes) d.nact_multi.resize((size_t) MAXT * kNativeActBytes); if (d.job_of.size() != (size_t) d.n_expert) d.job_of.assign((size_t) d.n_expert, (int16_t) -1); if (d.jobs_multi.size() < (size_t) (n_tok * k)) d.jobs_multi.resize((size_t) (MAXT * k)); + static const bool ptrace = std::getenv("STRATA_POOL_TRACE") != nullptr; + auto pt = [&](const char* what, long long a = -1) { + if (ptrace) { std::fprintf(stderr, "pool trace: layer %lld %s %lld\n", (long long) d.layers, what, a); std::fflush(stderr); } + }; const auto c0 = std::chrono::steady_clock::now(); + pt("begin"); d.src->begin_layer(d.layers, ids, n_tok * k); + pt("begun"); if (!d.usage.empty()) for (int64_t i = 0; i < n_tok * k; ++i) if (ids[i] >= 0 && ids[i] < d.n_expert) d.usage[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] += 1.0f; @@ -348,7 +355,9 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 P.counts[1] = entries; P.counts[2] = fetches; std::atomic_thread_fence(std::memory_order_seq_cst); + pt("publish", fetches); if (P.publish) P.publish(P.ctx); + pt("fetch", fetches); if (P.fetch) P.fetch(P.ctx, dma_src, P.pcie_mode != 0 ? 0 : fetches, (size_t) bb); // the copy engine, beside the CPU's work } else { for (int64_t i = 0; i < n; ++i) { @@ -409,9 +418,11 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 ++d.multi_entries; } const auto c3 = std::chrono::steady_clock::now(); + pt("run", njobs); if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs); else d.pool->run_split_multi(d.jobs_multi.data(), njobs); const auto c4 = std::chrono::steady_clock::now(); + pt("ran"); auto ms = [](auto a, auto b) { return std::chrono::duration(b - a).count(); }; d.ms_plan += ms(c0, c1); d.ms_actq += ms(c1, c2); diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 6c9aa5e7..a25288c6 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -261,6 +261,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; for (int64_t c0 = 0; c0 < n; c0 += m.T) { + if (should_stop && should_stop()) { err = "cancelled"; return false; } + if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); } const int64_t T = std::min(m.T, n - c0), p0 = pos0 + c0; ++stats_.chunks; // ---- embeddings, broadcast to the four streams diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 863dde91..e82d7dda 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -48,6 +48,10 @@ #include #include #include +#include +#include +#include +#include #include #include #include @@ -422,6 +426,15 @@ void drive_pool_multi(void* user, const float* x_f, const int32_t* ids, int64_t ++t->calls; } +/// STRATA_TRACE=1: the VRAM left at a step of the startup (finds what fills the card after the cache is sized) +void mem_mark(const char* where) { + static const bool on = std::getenv("STRATA_TRACE") != nullptr; + if (!on) return; + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + std::fprintf(stderr, "strata trace: %lld MiB free after %s\n", (long long) (free_b >> 20), where); +} + int argmax(const std::vector& v) { int best = 0; for (size_t i = 1; i < v.size(); ++i) @@ -1003,6 +1016,7 @@ int main(int argc, char** argv) { // ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open` // sees the memory this process actually has left rather than the card's idle figure - and refuses with both // numbers if the slots do not fit, instead of handing back a cache smaller than it was asked for. + mem_mark("the weights, the session and the drafter"); strata::core::ExpertCache xcache; std::vector> profile; if (!o.expert_profile.empty()) { @@ -1018,6 +1032,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: profile %s: %zu ranked pairs, built for %lld slots\n", o.expert_profile.c_str(), profile.size(), (long long) pslots); } + const bool auto_cache = o.expert_cache < 0; if (o.expert_cache < 0) { size_t free_b = 0, total_b = 0; cudaMemGetInfo(&free_b, &total_b); @@ -1053,15 +1068,51 @@ int main(int argc, char** argv) { o.expert_cache = (int) sized_slots.size(); } if (o.expert_cache > 0) { - const bool ok = sized_slots.empty() - ? xcache.open(o.expert_cache, g.n_layers, g.n_expert, (int64_t) strata::kernels::cpu::expert_layout().max_blob, err) - : xcache.open_sized(sized_slots, g.n_layers, g.n_expert, err); - if (!ok) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; + // With `--expert-cache auto` the reserve must still be free once the slots are WRITTEN: under WDDM an + // allocation is not resident until it is touched, and the free figure read before it can be ~1 GB too + // high. A cache sized from it filled the card to 0 MiB, the driver then paged, and a request that needed a + // page back while the verify graph spun on a host flag never finished. So the slots are zeroed and the + // free figure read again; while it is short of the reserve the cache is reopened smaller. + for (int attempt = 0;; ++attempt) { + const bool ok = sized_slots.empty() + ? xcache.open(o.expert_cache, g.n_layers, g.n_expert, (int64_t) strata::kernels::cpu::expert_layout().max_blob, err) + : xcache.open_sized(sized_slots, g.n_layers, g.n_expert, err); + if (!ok) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + if (!auto_cache || attempt >= 6) break; + cudaMemset(xcache.device_slot(0), 0, (size_t) xcache.bytes()); + cudaDeviceSynchronize(); + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + const int64_t want = (int64_t) o.vram_reserve_mib << 20; + if ((int64_t) free_b >= want - (64ll << 20)) break; + // short by (want - free); a figure of 0 only says "at least", so then give back a quarter as well + int64_t give = want - (int64_t) free_b + (64ll << 20); + if (free_b < ((size_t) 16 << 20)) give = std::max(give, xcache.bytes() / 4); + const int64_t keep_bytes = xcache.bytes() - give; + std::fprintf(stderr, "strata generate: only %lld MiB free once the slots are written (reserve %d MiB); " + "shrinking the expert cache\n", (long long) (free_b >> 20), o.vram_reserve_mib); + xcache.close(); + if (keep_bytes <= 0) { o.expert_cache = 0; sized_slots.clear(); break; } + if (!sized_slots.empty()) { + int64_t used = 0; + size_t keep = 0; + while (keep < sized_slots.size() && used + (sized_slots[keep] + 255) / 256 * 256 <= keep_bytes) + used += (sized_slots[keep++] + 255) / 256 * 256; + sized_slots.resize(keep); + o.expert_cache = (int) keep; + } else { + o.expert_cache = (int) (keep_bytes / (int64_t) strata::kernels::cpu::expert_layout().max_blob); + } + if (o.expert_cache <= 0) { o.expert_cache = 0; sized_slots.clear(); break; } } + } + if (o.expert_cache > 0) { std::fprintf(stderr, "strata generate: expert cache %lld slots, %.2f GiB of VRAM; policy is\n", (long long) xcache.slots(), xcache.gib()); + mem_mark("opening the expert cache"); xcache.set_per_layer_admission(o.expert_cache_per_layer); // **ROUND 328: THE HIT PATH IS PROVABLY WRONG, AND THIS SAYS SO OUT LOUD RATHER THAN LETTING IT // CORRUPT A RUN QUIETLY.** With the cache on, the generated tokens DIVERGE from the cache-off run: @@ -1109,12 +1160,13 @@ int main(int argc, char** argv) { // **AND ONE SLOT IS READ BACK AND COMPARED.** A residency table that is right about indices and wrong // about bytes produces a plausible token, which is this project's most expensive failure mode; the // cache's own `verify_slot` is the check and it costs one 1.38 MB D2H at startup. - if (!xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second), + if (prefilled > 0 && !xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second), srcp->blob(profile[0].first, profile[0].second), err, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[0].first))) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + mem_mark("the profile fill"); std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile; slot 0 verified\n", (long long) prefilled, (long long) want); } @@ -1172,6 +1224,7 @@ int main(int argc, char** argv) { drive.d.hit_done = (void*) hit_done; drive.d.hit_poke = !o.no_hit_poke; drive.d.h_dst.resize((size_t) K); + mem_mark("the R4 hit path"); std::fprintf(stderr, "strata generate: R4 hit path ON - resident experts are computed on the GPU\n"); } // ---- P0.S8: the routing trace. Only meaningful with the pool running, because the ids arrive through @@ -1289,6 +1342,7 @@ int main(int argc, char** argv) { return 2; } + mem_mark("the expert cache and the graphs"); std::fprintf(stderr, "strata generate: session is up; locating the head\n"); const strata::core::WeightRef* wo = wt.find("output.weight"); if (wo == nullptr) { std::fprintf(stderr, "strata generate: output.weight is missing\n"); return 1; } @@ -1773,8 +1827,11 @@ int main(int argc, char** argv) { void* borrow = nullptr; uint64_t borrow_bytes = 0; int32_t lend_first = -1; - if (!o.no_prefill_borrow && d_res != nullptr) { - const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ss, o.prefill_chunk); + // a cache too small to lend the prompt path its buffers would make it allocate them on top - on a card the + // cache already filled to its reserve, that is the over-subscription the auto sizing avoids - so the + // prompt chunk is halved until its buffers fit in the lendable slots (a smaller chunk only reads slower) + for (int64_t chunk = o.prefill_chunk; !o.no_prefill_borrow && d_res != nullptr && chunk >= 256; chunk /= 2) { + const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ss, chunk); const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; int64_t k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); if (xcache.slot_offsets() != nullptr) { @@ -1783,16 +1840,27 @@ int main(int argc, char** argv) { (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]) < need) ++k; } if (k + 128 <= xcache.slots()) { + if (chunk != o.prefill_chunk) + std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens so its buffers fit in the " + "expert cache\n", (long long) o.prefill_chunk, (long long) chunk); + o.prefill_chunk = chunk; lend_first = (int32_t) (xcache.slots() - k); borrow = xcache.device_slot(lend_first); borrow_bytes = xcache.slot_offsets() ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[lend_first]) : (uint64_t) k * (uint64_t) blob; + break; } } + if (borrow != nullptr) + std::fprintf(stderr, "strata serve: the prompt path borrows %lld cache slots (%.2f GiB)\n", + (long long) (xcache.slots() - lend_first), (double) borrow_bytes / 1073741824.0); + else + std::fprintf(stderr, "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)\n"); if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) { std::fprintf(stderr, "strata serve: %s\n", err.c_str()); return 1; } + mem_mark("the head and the prompt path"); strata::core::Verifier ver; strata::core::VerifyHits vh; vh.d_res = thits.d_res; @@ -1803,6 +1871,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata serve: %s\n", err.c_str()); return 1; } + mem_mark("the verifier and the drafter's binding"); ver.set_split(o.spec_split); ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : o.pcie_mode == "kernel" ? 2 : native_pack ? 0 : 2); // auto: DMA for the native packs, the copy kernel for Q2_0 @@ -1875,7 +1944,52 @@ int main(int argc, char** argv) { for (float& v : drive.d.usage) v *= 0.7f; return true; }; - std::printf("READY %lld\n", (long long) o.max_context); + // stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went + // away, or pressed Esc): the flag is checked between prompt chunks and between verify windows. + std::atomic stop_req{false}; + std::mutex in_mu; + std::condition_variable in_cv; + std::deque in_lines; + bool in_eof = false; + std::thread([&] { + std::string l; + while (std::getline(std::cin, l)) { + if (!l.empty() && l.back() == '\r') l.pop_back(); + if (l == "STOP") { stop_req.store(true); continue; } + std::lock_guard lk(in_mu); + in_lines.push_back(l); + in_cv.notify_one(); + } + std::lock_guard lk(in_mu); + in_eof = true; + in_cv.notify_one(); + }).detach(); + auto next_line = [&](std::string& out) -> bool { + std::unique_lock lk(in_mu); + in_cv.wait(lk, [&] { return !in_lines.empty() || in_eof; }); + if (in_lines.empty()) return false; + out = std::move(in_lines.front()); + in_lines.pop_front(); + return true; + }; + sp.should_stop = [&] { return stop_req.load(); }; + // STRATA_TRACE=1: one stderr line per step of a request (the log shows where a request stops) + const bool trace = std::getenv("STRATA_TRACE") != nullptr; + auto tr = [&](const char* what, long long a = -1, long long b = -1) { + if (!trace) return; + std::fprintf(stderr, "strata trace: %s %lld %lld\n", what, a, b); + std::fflush(stderr); + }; + { + // what is left once everything is allocated: under WDDM a GPU filled to the brim does not fail, it pages - + // and a page-in while the verify graph spins on a host flag stalls the request for good + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded%s\n", + (long long) (free_b >> 20), free_b < ((size_t) 128 << 20) + ? " - LOW: requests may stall; lower --max-context or raise --vram-reserve-mib" : ""); + } + std::printf("READY %lld stop\n", (long long) o.max_context); // "stop": this engine honours STOP std::fflush(stdout); std::string line; int64_t rounds = 0; @@ -1888,9 +2002,9 @@ int main(int argc, char** argv) { bool mrope_identity = true; std::vector img_rows; std::vector row_ptr; - while (std::getline(std::cin, line)) { - if (!line.empty() && line.back() == '\r') line.pop_back(); + while (next_line(line)) { if (line == "QUIT") break; + stop_req.store(false); // a STOP that arrived between requests is stale const bool geni = line.rfind("GENI ", 0) == 0; if (!geni && line.rfind("GEN ", 0) != 0) { std::printf("ERR expected: GEN or GENI \n"); @@ -1968,7 +2082,9 @@ int main(int argc, char** argv) { if (ve.empty() && n > 0 && ids[(size_t) (n - 1)] == kImagePad) ve = "the prompt cannot end in an image"; for (int64_t c = n; ve.empty() && c < cells; ++c) put(c, p + (c - n), p + (c - n), p + (c - n)); } + tr("positions built", (long long) img_rows.size()); cudaDeviceSynchronize(); + tr("device idle"); if (ve.empty() && cudaMemcpy(d_mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess) ve = "the image position upload failed"; @@ -1996,6 +2112,7 @@ int main(int argc, char** argv) { const Clock::time_point r0 = Clock::now(); strata::core::session_zero(ss, g, nullptr, main_cs); cudaStreamSynchronize(main_stream); + tr("request", n, geni ? 1 : 0); mtp.set_prompt_len(n); std::vector> lent_now; apply_pending(true); @@ -2007,10 +2124,15 @@ int main(int argc, char** argv) { } cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); } + bool cancelled = false; + tr("prompt start", n - 1); if (n > 1 && !sp.run(ids.data(), n - 1, 0, err)) { - std::fprintf(stderr, "strata serve: %s\n", err.c_str()); - std::printf("ERR %s\n", err.c_str()); - return 1; + if (!stop_req.load()) { + std::fprintf(stderr, "strata serve: %s\n", err.c_str()); + std::printf("ERR %s\n", err.c_str()); + return 1; + } + cancelled = true; // stopped while reading the prompt: refill the lent slots below, then DONE cancel } for (const auto& [i, slot] : lent_now) { const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert); @@ -2023,6 +2145,7 @@ int main(int argc, char** argv) { } if (!lent_now.empty()) cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + tr("prompt done (slots refilled)"); const double prompt_ms = std::chrono::duration(Clock::now() - r0).count(); // the verify windows: the first holds the last prompt token alone int64_t p = n - 1; @@ -2033,7 +2156,8 @@ int main(int argc, char** argv) { int64_t produced_n = 0; const char* finish = "length"; const Clock::time_point d0 = Clock::now(); - while (produced_n < max_new) { + if (cancelled) finish = "cancel"; + while (!cancelled && produced_n < max_new) { int T = S; if (o.spec_min_p > 0.0) { T = 1; @@ -2047,6 +2171,7 @@ int main(int argc, char** argv) { drive.d.experts = 0; drive.d.failed = false; apply_pending(false); + tr("window", p, T); if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err) || drive.d.failed) { std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str()); return 1; @@ -2083,6 +2208,7 @@ int main(int argc, char** argv) { return 1; } if (eos) { finish = "stop"; break; } + if (stop_req.load()) { finish = "cancel"; break; } x = outv[(size_t) a]; p += a + 1; } @@ -2426,6 +2552,7 @@ int main(int argc, char** argv) { "--expert-cache and the token graph)\n"); return 2; } + mem_mark("the head and the prompt path"); strata::core::Verifier ver; strata::core::VerifyHits vh; vh.d_res = thits.d_res; @@ -2440,6 +2567,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + mem_mark("the verifier and the drafter's binding"); ver.set_split(o.spec_split); ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : o.pcie_mode == "kernel" ? 2 : native_pack ? 0 : 2); // auto: DMA for the native packs, the copy kernel for Q2_0 diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index 0c53c835..a2a32c1e 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -99,6 +99,30 @@ int main(int argc, char** argv) { if (gg) gguf_free(gg); } if (n_embd <= 0) { std::printf("ERR the vision encoder has no projection_dim\n"); std::fflush(stdout); return 1; } + // Warm up at the LARGEST picture before READY: the encoder's GPU work buffers are allocated now, not at the first + // real picture. The server starts this process before the engine, so the engine sizes its expert cache from + // what is really left; allocating ~1 GB later, on a GPU the engine has filled, made Windows page GPU memory and + // the engine crawl to a standstill. (A square image well above any cap; mtmd scales it to the token limit.) + { + const uint32_t side = 2048; + std::vector rgb((size_t) side * side * 3, 128); + mtmd_bitmap* bm = mtmd_bitmap_init(side, side, rgb.data()); + mtmd_input_chunks* chunks = mtmd_input_chunks_init(); + const std::string marker = mtmd_default_marker(); + mtmd_input_text txt{marker.c_str(), marker.size(), false, true}; + const mtmd_bitmap* bms[1] = {bm}; + int warm_tokens = 0; + if (bm && mtmd_tokenize(ctx, chunks, &txt, bms, 1) == 0) { + for (size_t c = 0; c < mtmd_input_chunks_size(chunks); ++c) { + const mtmd_input_chunk* ch = mtmd_input_chunks_get(chunks, c); + if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE && mtmd_encode_chunk(ctx, ch) == 0) + warm_tokens = (int) mtmd_input_chunk_get_n_tokens(ch); + } + } + std::fprintf(stderr, "strata-vision: warmed up at %d image tokens\n", warm_tokens); + mtmd_input_chunks_free(chunks); + if (bm) mtmd_bitmap_free(bm); + } std::printf("READY %d\n", n_embd); std::fflush(stdout);