Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

server: "return_progress": true puts the prompt's PP line on the stream as llama.cpp's prompt_progress

Elias Klughammeradd41aef65a7
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index 737b08563..c566b06e8 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -534,6 +534,15 @@ print(r.choices[0].message.content)
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.
+- **Prefill progress in the stream (opt-in).** `"return_progress": true` puts that progress on the stream instead of
+ sending only the keep-alive, as one extra field on a chunk with an empty delta: `prompt_progress` with `total`,
+ `cache`, `processed` and `time_ms`. Those are llama.cpp's four fields and mean the same there (`time_ms` is the time
+ since the prompt started reading, and the work still to do is `(total-cache) - (processed-cache)`), so a client that
+ draws a prefill bar for llama.cpp draws one here too. It is off unless the request asks, as it is in llama.cpp.
+ The engine says one line per `--prefill` chunk, so that chunk is the step: measured on two RTX 3090s with
+ `--prefill auto` (8192 tokens), a 42,131 token prompt read in 15 s sent six of them. A prompt shorter than one chunk
+ sends nothing, and that is on purpose: its only line arrives once the prompt is read, because the last tokens go
+ through the verify windows rather than the batched path, so it stops up to `--short-read` tokens short of the end.
- **Chat apps.** Any app with an "OpenAI-compatible" provider works: base URL `http://127.0.0.1:8080/v1`, any API key.
- **OpenCode** (#543). A starting point for `opencode.jsonc` (in your project, or `~/.config/opencode/`); the field
names are OpenCode's, so check its config docs if your version differs:
diff --git a/serve/server.py b/serve/server.py
index 6f4bdf9d6..5681e71cf 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -440,6 +440,8 @@ class StrataEngine:
self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab)
self.prefill_tok_s_mean = None
self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines
+ self.progress_ms = 0 # PP's own milliseconds since the prompt started (its third field)
+ self.reused = 0 # RESUME: prompt tokens not read again (a client takes them out of the work)
self.silent_note = None
try: # a ready-made engine's BUILD.json says its version
self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version")
@@ -766,6 +768,7 @@ class StrataEngine:
f = line.split()
if len(f) >= 3 and f[1].isdigit() and f[2].isdigit():
self.progress = (int(f[1]), int(f[2]))
+ self.progress_ms = float(f[3]) if len(f) >= 4 else 0.0
self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None
if not stopped and cancel.is_set():
# #879: a Stop during the prompt read went out only after the first token (or after 10 s of
@@ -901,7 +904,7 @@ class StrataEngine:
admission to its BADM, a slot is BSTOPped and freed at its BDONE."""
if not self.alive():
raise EngineDied("the engine is unavailable; this request was not sent")
- self.progress = None
+ self.progress, self.progress_ms, self.reused = None, 0, 0
keys = self.sampling_keys(sampling or {})
out: list[int] = []
pending: list[int] = []
@@ -1146,7 +1149,7 @@ class StrataEngine:
if getattr(self, "batch", 0):
yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings)
return
- self.progress = None
+ self.progress, self.progress_ms, self.reused = None, 0, 0
self.prefill_tok_s_mean = None
# an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked)
head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \
@@ -1192,6 +1195,7 @@ class StrataEngine:
f = line.split()
if len(f) >= 3 and f[1].isdigit() and f[2].isdigit():
self.progress = (int(f[1]), int(f[2])) # prompt progress, one per chunk: also a heartbeat (the
+ self.progress_ms = float(f[3]) if len(f) >= 4 else 0.0
self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None
rate, chunk = self.prefill_tok_s_mean or 0.0, int(f[1]) - read_to
read_to = int(f[1])
@@ -1202,7 +1206,7 @@ class StrataEngine:
yield None
elif line.startswith("RESUME "): # the reused tokens: the first chunk starts after them
try:
- read_to = int(line.split()[1])
+ read_to = self.reused = int(line.split()[1])
except (IndexError, ValueError):
pass
elif line.startswith("DONE"):
@@ -1293,6 +1297,7 @@ class StrataEngine:
self.proc = None
self.ended = True
self.progress, self.last = None, {}
+ self.progress_ms, self.reused = 0, 0
IMAGE_URL_MAX = 32 << 20 # an image URL is read up to this (the web app attaches pictures of up to 20 MB)
@@ -2838,11 +2843,41 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new,
# ------------------------------------------------------------------------------------------------ OpenAI
+# The engine's last PP line stops short of the prompt: up to `--short-read` tokens (generate.cpp's `short_read`, 64 by
+# default) are read through the verify windows instead of the batched path, so the batched path never reports the whole
+# prompt. A PP that close to the end says the prompt is read. It matters because a prompt shorter than one `--prefill`
+# chunk sends exactly one PP, that one: a client would see a bar that appears already full. Such a line is dropped, and
+# the answer's first token ends the progress for the client anyway.
+PP_DONE_TAIL = 64
+
+
+def prompt_progress(svc: Service):
+ """The last PP line as llama.cpp's `prompt_progress`, so a client written for llama.cpp reads both servers: the
+ same four fields, `time_ms` elapsed since prompt reading started, and `processed` counting from token 0 so that a
+ client takes the reused prefix out with `cache` (llama.cpp's rule: the timed progress is
+ `(processed-cache)/(total-cache)`). None when there is nothing to say: no PP yet, or the line that says the prompt
+ is read. An engine too old to print RESUME gives `cache` 0, which only makes a reused prefix count as work."""
+ engine = svc.engine
+ if getattr(engine, "batch", 0): # --batch: the engine's progress is one global line, not this request's
+ return None
+ progress = getattr(engine, "progress", None)
+ if not progress:
+ return None
+ read, total = progress
+ if total <= 0 or total - read <= PP_DONE_TAIL:
+ return None
+ return {"total": int(total), "cache": int(getattr(engine, "reused", 0) or 0), "processed": int(read),
+ "time_ms": int(getattr(engine, "progress_ms", 0) or 0)}
+
+
def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None, force=None):
"""`run`: the events to send instead of Service.run's (run_with_mcp); its ("mcp", {...}) items become chunks with
an empty delta and a `strata_mcp` field, which only the web app reads. `force`: see Service.run."""
cid, created = "chatcmpl-" + uuid.uuid4().hex[:24], int(time.time())
model = svc.model_for(req)
+ # llama.cpp's flag, and its default: a client that wants prompt progress asks for it, and nothing changes for one
+ # that does not. Strata already sends a keep-alive comment on every PP line, so this only fills that line in.
+ want_progress = bool(req.get("return_progress"))
def chunk(delta, finish=None):
return {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model,
@@ -2854,7 +2889,10 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel
finished = set() # ... and the ones whose final tool_call came (#211)
for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel, force=force):
if kind == "ping":
- yield None
+ # a PP line: the prompt is being read and there is nothing to say yet. It used to be only the SSE comment;
+ # now it carries the progress when the client asked, and stays the comment when there is nothing to report.
+ pp = prompt_progress(svc) if want_progress else None
+ yield None if pp is None else {**chunk({}), "prompt_progress": pp}
elif kind == "mcp":
c = chunk({})
c["strata_mcp"] = x
@@ -2944,11 +2982,12 @@ def structured_chunks(chunks, validator):
heartbeat = time.monotonic()
try:
for chunk in chunks:
- if chunk is not None:
- buffered.append(chunk)
- if chunk is None or time.monotonic() - heartbeat >= 1:
+ progress = chunk is not None and "prompt_progress" in chunk
+ if chunk is not None and not progress:
+ buffered.append(chunk) # a progress chunk carries no content: there is nothing in it to validate
+ if chunk is None or progress or time.monotonic() - heartbeat >= 1:
heartbeat = time.monotonic()
- yield None
+ yield chunk if progress else None
result = openai_collect(buffered)
choice = result["choices"][0]
content = validated_json(choice["message"]["content"], validator, choice["finish_reason"])
diff --git a/serve/test_server.py b/serve/test_server.py
index 133db7d3e..498ace481 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -21,9 +21,9 @@ from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from serve.frontend import ChatTemplate # noqa: E402
-from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, Service, StrataEngine, # noqa: E402
- engine_args, layer_split_value, prompt_tokens_seen, request_timings, serve,
- start_failure_hint)
+from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, PP_DONE_TAIL, Service, # noqa: E402
+ StrataEngine, engine_args, layer_split_value, prompt_progress, prompt_tokens_seen,
+ request_timings, serve, start_failure_hint)
from types import SimpleNamespace # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
@@ -1747,6 +1747,79 @@ class LiveRate(unittest.TestCase):
httpd.server_close()
+class PromptProgress(unittest.TestCase):
+ """`return_progress: true` puts the engine's PP line on the stream as llama.cpp's `prompt_progress`, so a client
+ written for llama.cpp shows prefill progress from either server. Off by default, as it is in llama.cpp."""
+
+ TOKENS, TOTAL = 40, 25000
+
+ class Reading(MockEngine):
+ """A prompt read in three chunks and then answered: the engine's PP lines reach the HTTP layer as pings."""
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.progress, self.progress_ms, self.reused, self.total = None, 0.0, 0, 0
+
+ def generate(self, ids, max_new, sampling, cancel, embeddings=None):
+ for read, ms in ((8192, 2200.0), (16384, 4400.0), (24576, 6600.0)):
+ self.progress, self.progress_ms = (read, self.total), ms
+ yield None
+ yield from super().generate(ids, max_new, sampling, cancel, embeddings)
+
+ def setUp(self):
+ tok = ByteTokenizer()
+ self.engine = self.Reading(tok, "y" * self.TOKENS, max_context=CTX)
+ self.engine.total = self.TOTAL
+ self.engine.reused = 4096 # RESUME: the conversation checkpoint's reused prefix
+ self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
+ self.httpd = serve(self.svc, port=0)
+ self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
+
+ def tearDown(self):
+ self.httpd.shutdown()
+ self.httpd.server_close()
+
+ def stream(self, **req):
+ body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "stream": True,
+ "messages": [{"role": "user", "content": "hi"}], **req}).encode()
+ with urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=body,
+ headers={"Content-Type": "application/json"}),
+ timeout=30) as r:
+ return r.read().decode()
+
+ def test_a_client_that_asks_gets_one_progress_per_chunk(self):
+ steps = [json.loads(line[6:]) for line in self.stream(return_progress=True).splitlines()
+ if line.startswith("data: ") and "prompt_progress" in line]
+ self.assertEqual([s["prompt_progress"] for s in steps],
+ [{"total": self.TOTAL, "cache": 4096, "processed": 8192, "time_ms": 2200},
+ {"total": self.TOTAL, "cache": 4096, "processed": 16384, "time_ms": 4400},
+ {"total": self.TOTAL, "cache": 4096, "processed": 24576, "time_ms": 6600}],
+ "llama.cpp's four fields, time_ms elapsed since the read started")
+ self.assertTrue(all(s["choices"][0]["delta"] == {} for s in steps), "a progress chunk carries no content")
+
+ def test_a_client_that_does_not_ask_gets_nothing(self):
+ text = self.stream()
+ self.assertNotIn("prompt_progress", text)
+ self.assertIn(": keep-alive", text, "the PP line still keeps the connection alive as it used to")
+
+ def test_the_line_that_says_the_prompt_is_read_is_dropped(self):
+ # the batched path leaves up to --short-read tokens to the verify windows, so its last PP stops short of the
+ # prompt. A prompt under one --prefill chunk sends only that line, and it would show a bar already full.
+ for short in (PP_DONE_TAIL, PP_DONE_TAIL - 1, 1):
+ self.engine.progress, self.engine.progress_ms = (self.TOTAL - short, self.TOTAL), 6600.0
+ self.assertIsNone(prompt_progress(self.svc), f"a PP {short} token(s) short of the end says it is read")
+ self.engine.progress = (self.TOTAL - PP_DONE_TAIL - 1, self.TOTAL)
+ self.assertEqual(prompt_progress(self.svc)["processed"], self.TOTAL - PP_DONE_TAIL - 1)
+
+ def test_nothing_before_the_first_chunk(self):
+ self.engine.progress = None
+ self.assertIsNone(prompt_progress(self.svc), "no PP line yet: there is no rate to show")
+ self.engine.progress = (8192, self.TOTAL)
+ self.engine.reused = 0 # an engine too old to print RESUME never sets it
+ self.assertEqual(prompt_progress(self.svc)["cache"], 0,
+ "an engine too old to print RESUME counts the reused prefix as work")
+
+
class SharedSettings(unittest.TestCase):
"""The web app's "Use for other apps too": POST /settings makes its Chat settings every client's defaults."""
@@ -3558,3 +3631,15 @@ class AnswerBeforeTheBody(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
+
+
+class PromptProgressBatch(unittest.TestCase):
+ """#837: under --batch the engine's progress is one global line: prompt_progress() says nothing."""
+
+ def test_nothing_under_batch(self):
+ from serve.server import prompt_progress
+ engine = SimpleNamespace(progress=(512, 4096), progress_ms=900, reused=0, batch=0)
+ svc = SimpleNamespace(engine=engine)
+ self.assertEqual(prompt_progress(svc), {"total": 4096, "cache": 0, "processed": 512, "time_ms": 900})
+ engine.batch = 2
+ self.assertIsNone(prompt_progress(svc))