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++

A prompt cancelled mid-read is logged and recorded with the tokens it read (#471)

Niko1221512ae42f7c96
diff --git a/serve/server.py b/serve/server.py
index f611530ba..e50c01d58 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -123,7 +123,9 @@ class GpuBusy(RuntimeError):
ENGINE_REQUEST = re.compile(
- r"prompt (?P<prompt>\d+) tokens = (?P<reused>\d+) reused \+ \d+ read in (?P<read>[\d.]+) ms \((?P<pp>[\d.]+) tok/s\), "
+ # "+ 12288 of 98179 read": a request cancelled while its prompt was read (#471)
+ r"prompt (?P<prompt>\d+) tokens = (?P<reused>\d+) reused \+ \d+(?: of \d+)? read in (?P<read>[\d.]+) ms "
+ r"\((?P<pp>[\d.]+) tok/s\), "
r"(?P<gen>\d+) generated in (?P<gen_ms>[\d.]+) ms \((?P<tg>[\d.]+) tok/s\)")
@@ -338,6 +340,8 @@ class StrataEngine:
self.last.update(hits=int(f[9]), lookups=int(f[10]))
if len(f) >= 14: # the expert tiers (engine 0.1.31+): RAM / file blobs, file MB
self.last.update(ram_blobs=int(f[11]), file_blobs=int(f[12]), file_mb=float(f[13]))
+ if len(f) >= 15: # #471 (engine 0.1.36+): the prompt tokens actually read
+ self.last.update(prompt_read=int(f[14]))
@staticmethod
def sampling_keys(sampling: dict) -> str:
@@ -1329,11 +1333,14 @@ class Service:
cvec = (getattr(self.engine, "info", {}) or {}).get("cvec", 0)
loaded = str(cvec) not in ("0", "", "None")
hit_rate = round(last["hits"] / last["lookups"], 3) if last.get("lookups") else None
+ seen = prompt_tokens_seen(len(ids), last) # #471: < len(ids) when cancelled mid-read
self.history.append({
"projection": (sampling or {}).get("experimental_speed_projection") is not False
if loaded else None,
"time": started, "duration_s": round(time.time() - started, 1), "finish": finish,
- "prompt_tokens": len(ids), "reused": last.get("reused"), "output_tokens": n,
+ "prompt_tokens": seen, "reused": last.get("reused"), "output_tokens": n,
+ # the request's whole prompt, and the tokens read of it (None: an older engine)
+ "prompt_total": len(ids), "prompt_read": last.get("prompt_read"),
"engine_generated": last.get("generated"),
"prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"),
"decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1)
@@ -1345,7 +1352,7 @@ class Service:
"drafts_accepted": last.get("drafts_accepted")})
t = self.totals
t["requests"] += 1
- t["prompt_tokens"] += len(ids)
+ t["prompt_tokens"] += seen
t["reused"] += last.get("reused") or 0
t["output_tokens"] += n
t["prompt_ms"] += last.get("prompt_ms") or 0.0
@@ -1354,7 +1361,7 @@ class Service:
t["drafts_accepted"] += last.get("drafts_accepted") or 0
fresh = getattr(self.engine, "last", None)
if fresh is not None and fresh is not before: # the engine's clock for THIS request
- timings = request_timings(len(ids), n, last)
+ timings = request_timings(seen, n, last)
self.last_timings = dict(timings, at=int(time.time())) if timings else None
self.last_request_at = time.time()
now = time.time()
@@ -1378,6 +1385,17 @@ class Service:
"timings": timings}
+def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int:
+ """#471: the prompt tokens a request got through - all of them, unless the engine's DONE line says a cancel stopped
+ its prompt read part-way (then the reused ones plus those read). /metrics' history and totals count these, so a
+ cancelled read is neither recorded as the whole prompt nor given a rate from tokens it never read. An engine
+ before 0.1.36 does not say (no `prompt_read`): the whole prompt, as before."""
+ read = last.get("prompt_read")
+ if read is None or last.get("finish") != "cancel":
+ return prompt_tokens
+ return min(prompt_tokens, int(last.get("reused") or 0) + int(read))
+
+
def request_timings(prompt_tokens: int, generated: int, last: dict) -> dict | None:
"""One request's `timings` in llama.cpp's names (what its clients show as speed), from the engine's own clock
(StrataEngine.last): prompt_n is what was read, cache_n what the conversation cache already held. None when the
diff --git a/serve/test_server.py b/serve/test_server.py
index 76ac5e5e5..85192668a 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -18,7 +18,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, request_timings, serve # noqa: E402
+from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, Service, StrataEngine, # noqa: E402
+ prompt_tokens_seen, request_timings, serve)
+from types import SimpleNamespace # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
CTX = 4096
@@ -95,6 +97,13 @@ class MaxTokens(unittest.TestCase):
m = ENGINE_REQUEST.search(line)
self.assertIsNotNone(m)
self.assertEqual((m["prompt"], m["reused"], m["gen"], m["tg"]), ("1200", "1000", "30", "100.0"))
+ # #471: a request cancelled while its prompt was read says how far it got
+ m = ENGINE_REQUEST.search("strata serve: prompt 98179 tokens = 0 reused + 12288 of 98179 read in 17565 ms "
+ "(699.6 tok/s), 0 generated in 0 ms (0.0 tok/s), drafts accepted 0 of 0, "
+ "0 checkpoints (cancelled)")
+ self.assertIsNotNone(m)
+ self.assertEqual((m["prompt"], m["reused"], m["read"], m["pp"], m["gen"]),
+ ("98179", "0", "17565", "699.6", "0"))
def test_unset_budget_is_the_rest_of_the_context(self):
cases = {"openai": [{"max_tokens": -1}, {"max_tokens": 0}, {}, {"max_tokens": None},
@@ -792,6 +801,54 @@ class DraftCounts(unittest.TestCase):
self.assertEqual((m["totals"]["drafts_offered"], m["totals"]["drafts_accepted"]), (17, 10))
+class CancelledRead(unittest.TestCase):
+ """#471: a request cancelled while its prompt was read is recorded with the tokens the engine read (the DONE
+ line's 15th field), not the whole prompt; an older engine's line (no such field) keeps the whole prompt."""
+
+ def test_parse_done_read_field(self):
+ e = SimpleNamespace()
+ StrataEngine._parse_done(e, "DONE 0 98179 17565.0 0.0 cancel 0 0 0 0 0 0 0 0.0 12288")
+ self.assertEqual((e.last["prompt_tokens"], e.last["prompt_read"], e.last["finish"]), (98179, 12288, "cancel"))
+ StrataEngine._parse_done(e, "DONE 0 98179 17565.0 0.0 cancel 0 0 0 0 0 0 0 0.0")
+ self.assertNotIn("prompt_read", e.last)
+
+ def test_prompt_tokens_seen(self):
+ last = {"finish": "cancel", "reused": 1000, "prompt_read": 2000}
+ self.assertEqual(prompt_tokens_seen(98179, last), 3000)
+ self.assertEqual(prompt_tokens_seen(98179, {**last, "finish": "stop"}), 98179) # read in full: all of it
+ self.assertEqual(prompt_tokens_seen(98179, {"finish": "cancel", "reused": 0}), 98179) # an older engine
+ self.assertEqual(prompt_tokens_seen(98179, {}), 98179) # no DONE at all
+ self.assertEqual(prompt_tokens_seen(10, {**last, "prompt_read": 50}), 10) # never past the prompt
+
+ def test_history_and_totals(self):
+ tok = ByteTokenizer()
+ engine = DoneLineEngine(tok, "</think>\n\nok", max_context=CTX, done_lines=[
+ "DONE 0 20 400.0 0.0 cancel 0 0 0 0 0 0 0 0.0 8", # stopped after 8 prompt tokens
+ "DONE 4 20 40.0 30.0 stop 0 0 0 0 0 0 0 0.0 20",
+ "DONE 0 20 400.0 0.0 cancel 0 0 0"]) # an older engine: no read count
+ svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
+ httpd = serve(svc, port=0)
+ base = f"http://127.0.0.1:{httpd.server_address[1]}"
+ try:
+ for _ in range(3):
+ body = json.dumps({"model": "m", "max_tokens": 10, "messages": [{"role": "user", "content": "hi"}]})
+ with urllib.request.urlopen(urllib.request.Request(base + "/v1/chat/completions", data=body.encode(),
+ headers={"Content-Type": "application/json"}),
+ timeout=30) as r:
+ self.assertEqual(r.status, 200)
+ with urllib.request.urlopen(base + "/metrics", timeout=10) as r:
+ m = json.loads(r.read())
+ finally:
+ httpd.shutdown()
+ httpd.server_close()
+ rows = m["requests"][::-1] # oldest first
+ total = rows[0]["prompt_total"]
+ self.assertGreater(total, 8)
+ self.assertEqual([r["prompt_total"] for r in rows], [total] * 3)
+ self.assertEqual([(r["prompt_tokens"], r["prompt_read"]) for r in rows], [(8, 8), (total, 20), (total, None)])
+ self.assertEqual(m["totals"]["prompt_tokens"], 8 + 2 * total)
+
+
class LiveRate(unittest.TestCase):
"""The Monitor's Speed readout: live.tok_s is a rate, and a request that never got a DONE keeps no counters.
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 53c38a00a..60b07ca4a 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -3697,7 +3697,7 @@ int main(int argc, char** argv) {
// and each generated token is written to stdout as `T <id>` as soon as its verify window is done, followed by
//
// DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> <stop|length|cancel> <drafts accepted>
- // <drafts offered> <prompt tokens reused>
+ // <drafts offered> <prompt tokens reused> ... <prompt tokens read> (see the DONE line below; #471)
//
// Before that, `RESUME <n>` (n prompt tokens are not read again), `PP <position> <prompt_tokens> <ms> <tok/s>`
// after every prompt chunk, and `REUSED <n>` once the prompt is read. (`ERR <message>` instead when a request
@@ -4373,6 +4373,9 @@ int main(int argc, char** argv) {
return true;
};
int64_t pp_total = 0, pp_from = 0, pp_next_check = 0;
+ // #471: the position the prompt pass has read up to (a chunk's or a window's end): what a request cancelled
+ // mid-read reports as read, instead of the whole prompt
+ int64_t pp_reached = 0;
Clock::time_point pp_t0 = Clock::now();
auto imgs_below = [&](const std::vector<ImgKey>& all, int64_t L) {
std::vector<ImgKey> v;
@@ -4436,6 +4439,7 @@ int main(int argc, char** argv) {
batched ? "batched" : "token", mtp.kv_state().kv_mode, (long long) T);
// progress for the server window: PP <position reached> <prompt tokens> <ms> <fresh tokens/s>
const int64_t done = p0 + T;
+ pp_reached = done;
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - pp_t0).count();
std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) pp_total, ms,
ms > 0.0 ? 1000.0 * (double) (done - pp_from) / ms : 0.0);
@@ -5063,6 +5067,7 @@ int main(int argc, char** argv) {
conversations.limit_reuse(read_from);
pp_total = n;
pp_from = read_from;
+ pp_reached = read_from;
pp_t0 = r0;
pp_next_check = reread_to > 0 ? INT64_MAX : resume + o.prompt_cache_every;
{
@@ -5128,6 +5133,7 @@ int main(int argc, char** argv) {
return false;
if (!ver.commit(T, e) || !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e)) return false;
q += T;
+ pp_reached = q; // #471
}
// the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first
if (!ver.wait_commit(e)) return false;
@@ -5628,20 +5634,30 @@ int main(int argc, char** argv) {
}
const int64_t req_hits = drive.d.cache_hits - decode_hits0;
const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0;
+ // #471: the prompt tokens this request read - all the fresh ones, or as far as the prompt pass got when a
+ // cancel stopped it part-way (a cancelled request used to be logged and counted as having read them all)
+ const int64_t fresh = n - resume;
+ const int64_t read_n = cancelled ? std::clamp<int64_t>(pp_reached - resume, 0, fresh) : fresh;
// DONE <generated> <prompt> <prompt ms> <decode ms> <finish> <drafts accepted> <drafts offered> <reused> [hits] [lookups]
// [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest)
- std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f\n", (long long) produced_n,
+ // [prompt tokens read] (#471: fewer than <prompt> - <reused> when a cancel stopped the read)
+ std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld\n", (long long) produced_n,
(long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,
(long long) resume, (long long) req_hits, (long long) req_look,
(long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),
- (double) (src.file_read_bytes() - file_bytes0) / 1e6);
+ (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n);
std::fflush(stdout);
if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session
- const int64_t fresh = n - resume;
- std::fprintf(stderr, "strata serve: prompt %lld tokens = %lld reused + %lld read in %.0f ms (%.1f tok/s), "
+ // "12288 of 98179" when cancelled mid-read (#471), the rate from what was read
+ char read_txt[64];
+ if (cancelled)
+ std::snprintf(read_txt, sizeof(read_txt), "%lld of %lld", (long long) read_n, (long long) fresh);
+ else
+ std::snprintf(read_txt, sizeof(read_txt), "%lld", (long long) fresh);
+ std::fprintf(stderr, "strata serve: prompt %lld tokens = %lld reused + %s read in %.0f ms (%.1f tok/s), "
"%lld generated in %.0f ms (%.1f tok/s), drafts accepted %lld of %lld, %zu checkpoints%s\n",
- (long long) n, (long long) resume, (long long) fresh, prompt_ms,
- prompt_ms > 0 ? 1000.0 * fresh / prompt_ms : 0.0, (long long) produced_n, decode_ms,
+ (long long) n, (long long) resume, read_txt, prompt_ms,
+ prompt_ms > 0 ? 1000.0 * read_n / prompt_ms : 0.0, (long long) produced_n, decode_ms,
decode_ms > 0 ? 1000.0 * produced_n / decode_ms : 0.0, (long long) draft_accepted,
(long long) draft_offered, checks.size(), cancelled ? " (cancelled)" : "");
// the VRAM share of the experts the pool looked up while decoding; experts it sent over PCIe for the GPU