diff --git a/CHANGELOG.md b/CHANGELOG.md index 58070f9217f..49bea64dddc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Server: chat and legacy completions requests take `deadline_s` (seconds, more than 0 and at most 1,000,000; any other value is refused before the engine): at that time the server cancels the engine itself and the reply ends with `finish_reason: "deadline"`, keeping every token the engine gave and its usage; a reply the engine ended first, or a cancel that came first, keeps its own ending, and without the field nothing changes (#3438). Thanks to @jayleaton. + +- Tools: the follow-up gates (`tools/bench_concurrent.py`, `tools/clef_head_gate.py`, the image-cache turns check and the LFM3 serve check) fail by name when what they compare never ran (#3772, follows #3708). Thanks to @jschmied. + +- GLM-5.3-Flash on CUDA: the load races the classic and factored expert forms, which give the same bits, at each of its ten timed decode window widths and keeps the faster one at each (classic unless factored is more than 1% faster), instead of one form for every window; a window takes the form of the narrowest timed width that holds it, and `TF_GLM_EXPERT_FORM` names one form for every width (#3249). Thanks to @Bizuayeu. + - CI: a landing train's pull request skips GitHub's hosted checks, which our own runners already run on its tip (a red local run still starts them by hand), and a newer push cancels an older Zig format run, so main's and contributors' checks no longer queue behind trains (#4106). - Nemotron 3.5 on Metal: a request cancelled during a whole (unstepped) prompt pass keeps the prompt state that pass already landed, so the next request on that conversation resumes from it; the stepped path is unchanged (#3651, for #3618). diff --git a/docs/api.md b/docs/api.md index e5cd1909494..cf8344cf487 100644 --- a/docs/api.md +++ b/docs/api.md @@ -467,6 +467,7 @@ delete runs gets 503, an id that is not a number 400, and an id the graph does n | `reasoning_effort` | `none`, `minimal`, `low`, `medium`, `high`, `xhigh` or `max` | Both | | `thinking_budget` | Token-count limit inside reasoning | Both | | `priority` | `background` yields to foreground requests | Both | +| `deadline_s` | Seconds, more than 0 and at most 1,000,000, on chat and legacy completions: at that time the server cancels the engine itself and the reply ends with `finish_reason: "deadline"`, keeping every token the engine gave, usage and token ids. A reply that ends first, or a [cancel](#cancel-a-request) that came first, keeps its own ending; without the field nothing changes | Native | | `return_token_ids` | The reply's token ids in the response's `tensorfold.token_ids`, the tokens its `token_sha256` hashes | Native | `n` must be 1; multiple choices receive HTTP 400. diff --git a/docs/environment.md b/docs/environment.md index 6f04814c4ae..c692b0b34a2 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -63,7 +63,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_GLM_DFLASH2_LOG` | Whole unsigned 64-bit count of DFlash2 rounds whose drafts are logged; default 0 | | `TF_GLM_DRAFT_CONFIDENCE` | Finite number 0 through 1 where a DFlash2 chain's chance product stops it; default 0.7 | | `TF_GLM_CONTEXT_CEILING` | GLM-5.3-Flash on CUDA: whole token count 1 through 2147483616, the window `--context` may ask for and `--context 0` serves, in place of config.json's 1048576; read at GLM's open. Past that length the model's quality is the operator's to check. Unset keeps config.json's window | -| `TF_GLM_EXPERT_FORM` | `classic` or `factored`: the expert form GLM's CUDA decode windows use (the same bits either way), also at a load that times nothing; unset or blank races the two when a build first loads with drafts and scratch context and keeps the winner, else classic; read on rank 0, which chooses every rank's form | +| `TF_GLM_EXPERT_FORM` | `classic` or `factored`: the expert form GLM's CUDA decode windows use at every width (the same bits either way), also at a load that times nothing; unset or blank races the two at each timed width when a build first loads with drafts and scratch context and keeps each width's winner, else classic; read on rank 0, which chooses every rank's forms | | `TF_GLM_INDEX_CUDA` | GLM on CUDA: exactly `1` (both DSA indexer kernels), `0` (neither) or `scores` (scores only); unset or blank is `both` | | `TF_GLM_KV_HOST_GIB` | GLM on CUDA: a finite GiB amount of at least 0 for the DSA layers' pinned host pages; unset or blank uses one full window and 16 rows a page | | `TF_GLM_RANK` | GLM-5.3-Flash on CUDA: a whole rank index from 0 through 4294967295, set with `TF_GLM_WORLD`; unset with it gives one rank | diff --git a/docs/recipes/glm-5.3-flash-cuda.md b/docs/recipes/glm-5.3-flash-cuda.md index 4eb79aed667..19b14a6915d 100644 --- a/docs/recipes/glm-5.3-flash-cuda.md +++ b/docs/recipes/glm-5.3-flash-cuda.md @@ -135,14 +135,20 @@ range (0.25% at least), and inside the rest. Other checkpoints and sampled repli ## Window prices Decode windows reach 32 rows and MTP chains 15 drafts. With drafts and enough scratch context, rank 0 races -classic NVFP4 experts against the factored form over real text on every rank, keeping the faster form with the same -bits. MTP also times windows of 1, 2, 3, 4, 6, 8, 12, 16, 24 and 32 rows, with straight lines between them, and a -chained draft step. Its startup line reports `glm: windows (timed)` and the expert form. DFlash2 keeps the existing -seed forward and step prices in lone and shared rounds; it times only the target expert-form race and reports -`glm: expert form (timed)`. No unused DFlash2 window or draft-step table is measured or published to the lane core. -`TF_GLM_EXPERT_FORM=classic` or `factored` names the form instead and skips the race, so launches compare at one -form, and a load that times nothing still runs it (`glm: expert form (untimed)`); a named form's startup line puts -`(TF_GLM_EXPERT_FORM)` after the form's word. +classic NVFP4 experts against the factored form, which gives the same bits, over real text on every rank at windows +of 1, 2, 3, 4, 6, 8, 12, 16, 24 and 32 rows. Five untimed sweeps of every width on both forms come first, then each +width's timed windows take the two forms in turn, classic first on even rounds and factored first on odd ones, so +neither form is timed in a load's first seconds, and a drift through the race or a window right after a switch of +form falls on both alike. Each width keeps its faster form, classic unless factored is more than 1% faster, and a +window runs on the form of the narrowest timed width that holds it. `TF_GLM_EXPERT_FORM=classic` or `factored` +names one form for every width instead and skips the race, so launches compare at one form, and a load that times +nothing still runs it (`glm: expert form (untimed)`); a named form's startup line puts `(TF_GLM_EXPERT_FORM)` after +the form's word. MTP prices each width at its kept form's time, with straight lines between them, and a chained +draft step. Its startup line reports `glm: windows (timed)` and the forms: one word when every width shares one, +else the more common form and the widths where the other runs, as in `experts factored, classic at 4 and 6 rows`. +DFlash2 keeps the existing seed forward and step prices in lone and shared rounds; it times only the target +expert-form race and reports `glm: expert form (timed)`. No unused DFlash2 window or draft-step table is measured or +published to the lane core. The measurements stay in `~/.cache/tensorfold/window-costs`, keyed by the build, GPU/driver, full checkpoint and drafter identity, drafter precision, rank count, layer limit, L2-prefetch options, loaded NVFP4 decode warps, KDA and matmul diff --git a/tools/bench_concurrent.py b/tools/bench_concurrent.py index 75601e3a11d..5e6aa14fa82 100644 --- a/tools/bench_concurrent.py +++ b/tools/bench_concurrent.py @@ -8,7 +8,10 @@ ``--mixed``: request i takes prompt i % 2 and seed seed + i // 2; also reports the steady aggregate, over the time every stream is live (tokens split by the characters each stream delivered inside that window). ``--alone``: runs every request alone first and checks each concurrent reply's token-id hash (``token_sha256``) -against it; ``--serial`` checks the alone runs against ``"draft": false``. ``--no-seed``: sampled requests carry +against it; ``--serial`` checks the alone runs against ``"draft": false``. Both counts are a report, not a gate: +the cell names them ``vacuous`` when they compared nothing (``alone``: a rep in which no two streams decoded at once, +so the server served them one at a time; ``serial``: the drafted runs accepted no draft, or the plain ones drafted, +or the server reports no draft counters). ``--no-seed``: sampled requests carry no seed (mlx_lm's server batches only those), for measuring a standard; no hash checks then. Run a standard with its prompt cache off (mlx_lm: ``--prompt-cache-size 0``): a cached reply can arrive as one text piece. Tokens come from the reply's usage. A request that fails to connect or errors counts in ``failed``; one whose text came in fewer than @@ -182,6 +185,32 @@ def aggregates(runs: list[dict]) -> dict: "chunk_tpot_estimate_ms", "round_gap_p50_ms", "round_gap_p95_ms", "tokens_per_chunk") +def overlapped(runs: list[dict]) -> bool | None: + """True when two streams decoded at once (one's first token before another's last); None under two streams.""" + spans = sorted((r["first"], r["last"]) for r in runs if r.get("first") is not None and r.get("last") is not None) + return any(b[0] < a[1] for a, b in zip(spans, spans[1:])) if len(spans) > 1 else None + + +def draft_count(run: dict, key: str) -> int | None: + """A run's speculative count, None when the server reported none.""" + value = (run.get("speculative") or {}).get(key) + return value if type(value) is int and value >= 0 else None + + +def serial_evidence(alone: dict) -> dict: + """Drafts the alone runs accepted and the ``"draft": false`` runs drafted; ``vacuous`` says why that proves none.""" + accepted = [draft_count(r, "accepted") for r in alone.values()] + plain = [draft_count(r.get("serial_run") or {}, "drafted") for r in alone.values()] + out = {"accepted": sum(v or 0 for v in accepted), "plain_drafted": sum(v or 0 for v in plain)} + if None in accepted or None in plain: + out["vacuous"] = "the server reported no draft counters for some runs" + elif not out["accepted"]: + out["vacuous"] = "the drafted runs accepted no draft" + elif out["plain_drafted"]: + out["vacuous"] = f"the \"draft\": false runs drafted {out['plain_drafted']} tokens" + return out + + def median(values) -> float | None: """The median of the values that are not None, rounded to 3 places; None when there are none.""" got = [v for v in values if v is not None] @@ -306,6 +335,7 @@ def main() -> None: rep["client_intervals"] = [{"start": r["sent"], "first": r.get("first"), "last": r.get("last"), "end": r.get("completed"), **bench_timing.request(r)} for r in runs] + rep["overlapped"] = overlapped(runs) if alone: # None: the request or its solo run failed (not an exactness result) rep["equal_alone"] = [token_equal(alone[(r["prompt"], r["seed"])], r) for r in runs] @@ -340,10 +370,13 @@ def main() -> None: checks = [v for r in reps for v in r["equal_alone"]] cell["alone"] = {"equal": checks.count(True), "unequal": checks.count(False), "failed": checks.count(None)} + apart = sum(r["overlapped"] is False for r in reps) + if apart: + cell["alone"]["vacuous"] = f"{apart} of {len(reps)} reps had no two streams decoding at once" if args.serial: checks = [v.get("serial_equal") for v in alone.values()] cell["serial"] = {"equal": checks.count(True), "unequal": checks.count(False), - "failed": checks.count(None)} + "failed": checks.count(None), **serial_evidence(alone)} errors = sorted({e for r in reps for e in r["errors"]}) if errors: cell["errors"] = errors[:3] diff --git a/tools/clef_head_gate.py b/tools/clef_head_gate.py index 58a1de0971a..ea7c0c6cc5c 100644 --- a/tools/clef_head_gate.py +++ b/tools/clef_head_gate.py @@ -6,7 +6,8 @@ # clef_head_gate.py native [--piece N|whole] [--backend hip|cuda] # clef_head_gate.py compare [--report FILE] [--rule strict|margin] # The strict rule: per question type, native mean and worst error against FP64 no larger than the reference BF16 -# head's. The margin rule keeps the worst and lets the mean sit up to 10% above the reference's. +# head's. The margin rule keeps the worst and lets the mean sit up to 10% above the reference's. A question type with +# no option logits fails compare by name: an empty table would pass. # The records are clef_backbone_rows.py's; their schema text comes again from its seeded generator, so each field's # instruction and each option's description give the spans, as token ranges of the record by character offsets. import argparse, importlib.util, json, math, os, subprocess, sys @@ -206,6 +207,10 @@ def cmd_compare(a): f"{row['bf16_mean']:.3e} | {row['bf16_worst']:.3e} | {'yes' if row['strict'] else 'NO'} | " f"{'yes' if row['margin'] else 'NO'} |") total = sum(len(p["native"]) for p in pooled.values()) + unexercised = [names_of[t] for t, p in pooled.items() if not p["native"]] + if unexercised: + ok = False + print(f"unexercised: no option logits for {', '.join(unexercised)} (the cases' fields parsed to no options)") print(f"paired: {total} logits, {same} identical to the reference BF16 head's; of the rest native is nearer FP64 in " f"{nearer}, farther in {farther}, as near in {total - same - nearer - farther}") if a.report: diff --git a/tools/image_cache_turns.py b/tools/image_cache_turns.py index ba68890df3d..b8a61022a75 100644 --- a/tools/image_cache_turns.py +++ b/tools/image_cache_turns.py @@ -9,7 +9,10 @@ Per request: prompt and cached tokens (computed = prompt - cached), time to first streamed piece, total time, the server's prefill seconds and token hash. With --fresh-url (the same model served with --prompt-cache-gib 0), every -request is sent there too and its token hash must equal the resumed one. GET /v1/memory is recorded before and after. +request is sent there too and its token hash must equal the resumed one; then each fresh reply must report 0 cached +tokens, and the text, image and repeat scenarios must each resume, on some request after their first, more tokens than +their first request did (repeat: than the image chat's first; a fresh turn may resume the template's first tokens), +or resumed == fresh compared fresh with fresh and fails by name. GET /v1/memory is recorded before and after. Standard library only; Python 3.11+. python3 tools/image_cache_turns.py --url http://127.0.0.1:8080 --image a.png --image-b b.png \ @@ -117,6 +120,19 @@ def chat(first_image: str | None) -> list[list]: return out +def unexercised(name: str, rows: list[dict], first: int) -> str | None: + """Why a scenario's resumed == fresh compared nothing: a fresh reply that resumed, or no later request resumed + more than ``first``, the cached tokens of a first turn.""" + fresh = [r["turn"] for r in rows if r.get("fresh_cached_tokens") != 0] + if fresh: + return f"the fresh server's replies for turns {fresh} report cached tokens other than 0 (not fresh)" + later = rows if name == "repeat" else rows[1:] + if name != "changed" and later and not any((r.get("cached_tokens") or 0) > first for r in later): + return (f"no request after the first resumed more than a first turn's {first} cached tokens, so resumed == " + "fresh compared fresh with fresh") + return None + + def main() -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--url", default="http://127.0.0.1:8080") @@ -158,6 +174,11 @@ def main() -> int: + (f" ERROR {row['error']}" if row.get("error") else "")) failures += bool(row.get("error")) report["scenarios"][name] = rows + first = (report["scenarios"].get("image") if name == "repeat" else rows) or [{}] + problem = unexercised(name, rows, first[0].get("cached_tokens") or 0) if args.fresh_url else None + if problem: + failures += 1 + print(f"FAIL {name}: {problem}") report["memory_after"] = memory(args.url, key) if args.output: args.output.write_text(json.dumps(report, indent=1) + "\n") diff --git a/tools/test_clef_head_gate.py b/tools/test_clef_head_gate.py new file mode 100644 index 00000000000..e7b2ec4f07f --- /dev/null +++ b/tools/test_clef_head_gate.py @@ -0,0 +1,56 @@ +"""tools/clef_head_gate.py compare on planted cases: an empty table or a question type without logits fails by name. + +The gate imports numpy, which the CI jobs do not install, so these tests run only where numpy is. +""" +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +NUMPY = importlib.util.find_spec("numpy") is not None + + +def compare(types): + """compare's exit code and output over one case whose options belong to questions of ``types`` (0, 1, 2).""" + import clef_head_gate + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + for part in ("cases", "native", "bf16", "fp64"): + (root / part).mkdir() + (root / "cases" / "index.json").write_text(json.dumps({"cases": ["c"]})) + case = {"question_types": list(types), "option_question": list(range(len(types)))} + (root / "cases" / "c.json").write_text(json.dumps(case)) + for part, logit in (("native", 1.0), ("bf16", 1.5), ("fp64", 1.0)): + (root / part / "c.json").write_text(json.dumps({"logits": [logit] * len(types)})) + argv = ["clef_head_gate.py", "compare", *(str(root / p) for p in ("cases", "native", "bf16", "fp64"))] + out = io.StringIO() + with patch.object(sys, "argv", argv), contextlib.redirect_stdout(out): + code = clef_head_gate.main() + return code, out.getvalue() + + +@unittest.skipUnless(NUMPY, "clef_head_gate.py imports numpy") +class CompareTests(unittest.TestCase): + def test_every_type_with_logits_passes(self): + code, out = compare([0, 1, 2]) + self.assertEqual(code, 0, out) + + def test_no_logits_fails(self): + code, out = compare([]) + self.assertEqual(code, 1, out) + self.assertIn("unexercised: no option logits for noul, choice, score", out) + + def test_a_type_without_logits_fails(self): + code, out = compare([0, 1]) + self.assertEqual(code, 1, out) + self.assertIn("unexercised: no option logits for score", out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/fake_served_api.py b/tools/tests/fake_served_api.py index 19fc1b64267..b7ed32cae48 100644 --- a/tools/tests/fake_served_api.py +++ b/tools/tests/fake_served_api.py @@ -19,6 +19,9 @@ - serial: the server takes one request at a time, so requests sent together never overlap in it. - empty: every reply is empty (no tokens), so every pair of replies hashes the same. +``running(..., prefill=S)`` holds each JSON chat request ``S`` seconds before its reply, as a long prefill; a client +that leaves meanwhile is counted as a disconnect (the cancel faults apply), and the request gets no reply. + ``running(..., warm=S)`` keeps the server busy (one running, more waiting) for ``S`` seconds after each reply, as a server that prefills the chat's next turn in the background; ``lanes_free=False`` leaves ``capacity.lanes_free`` out of ``GET /v1/load``, as a server without lanes. @@ -52,6 +55,8 @@ import hashlib import http.server import json +import select +import socket import threading import time @@ -72,7 +77,9 @@ def doc(sha="a" * 64, cached=0, accepted=2, drafted=3, text="hi", tokens=4, sampling="greedy", prompt=9): """A chat completion body carrying the fields the kit reads.""" - return {"choices": [{"message": {"content": text}}], "tensorfold": {"token_sha256": sha, "sampling": sampling}, + runtime = {"token_sha256": sha, "token_sha": sha[:12] if isinstance(sha, str) else sha, "sampling": sampling, + "tokens_per_second": 50.0} + return {"choices": [{"message": {"content": text}}], "tensorfold": runtime, "speculative": {"rounds": int(drafted > 0), "accepted": accepted, "drafted": drafted}, "usage": {"prompt_tokens": prompt, "completion_tokens": tokens, "prompt_tokens_details": {"cached_tokens": cached}}} @@ -97,7 +104,12 @@ def messages_of(body) -> list: def text_of(body) -> str: - return " ".join(m.get("content", "") for m in messages_of(body)) + """The messages' text; a list content's text parts, and its other parts (images, videos) as JSON.""" + parts = [] + for m in messages_of(body): + content = m.get("content") or "" + parts += [content] if isinstance(content, str) else [c.get("text") or json.dumps(c) for c in content] + return " ".join(parts) def event(chunk: dict) -> bytes: @@ -193,6 +205,8 @@ def do_POST(self): if error: return self.reply(400, {"error": {"message": error, "type": "invalid_request_error"}}) key = json.dumps({k: v for k, v in body.items() if k not in ("stream", "stream_options")}, sort_keys=True) + if server.prefill and not body.get("stream") and self.left(server.prefill): + return with server.one if server.fault == "serial" else contextlib.nullcontext(): payload = self.answer(body, key) # Out of flight before the reply is written: the client's next request must not find this one counted. @@ -237,6 +251,31 @@ def answer(self, body, key) -> dict: with server.lock: server.inflight -= 1 + def left(self, seconds: float) -> bool: + """Holds the request ``seconds`` in flight; True, a disconnect counted, when its client leaves meanwhile.""" + server = self.server + with server.lock: + server.inflight += 1 + try: + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if select.select([self.connection], [], [], 0.01)[0]: + try: + gone = not self.connection.recv(1, socket.MSG_PEEK) + except OSError: + gone = True + if gone: + with server.lock: + server.disconnects += 1 + server.leaked += server.fault == "cancel_lane" + server.lost += server.fault == "cancel_free" + self.close_connection = True + return True + return False + finally: + with server.lock: + server.inflight -= 1 + def lookup(self, messages): """Cached tokens for the prompt, and whether the evict fault answers from an evicted prompt.""" server = self.server @@ -324,13 +363,13 @@ def play(self, steps, key=None): @contextlib.contextmanager -def running(cache=False, fault=None, linger=0.0, steps=None, warm=0.0, lanes_free=True): +def running(cache=False, fault=None, linger=0.0, steps=None, warm=0.0, lanes_free=True, prefill=0.0): """One fake on 127.0.0.1 port 0, yielding its base URL; stopped on exit.""" server = FixtureHTTPServer(("127.0.0.1", 0), FakeEngine) server.cache, server.fault, server.seen, server.inflight, server.linger = cache, fault, {}, 0, linger server.steps, server.kept, server.evicted, server.cut = steps, collections.OrderedDict(), set(), set() server.streams = server.leaked = server.lost = server.disconnects = server.overlaps = 0 - server.warm, server.warm_until, server.lanes_free = warm, 0.0, lanes_free + server.warm, server.warm_until, server.lanes_free, server.prefill = warm, 0.0, lanes_free, prefill server.census_at, server.census_gap = -1e9, 1e9 # no census read yet server.lock, server.one = threading.Lock(), threading.Lock() server.cond = threading.Condition(server.lock) @@ -350,7 +389,7 @@ def fake(cache, fault=None, linger=0.0, **shape): # linger: seconds each handler stays alive after its reply, widening any window between reply and exit. if fault not in (None, *FAULTS): raise ValueError(f"unknown fault {fault}") - # shape: warm and lanes_free, see ``running``. + # shape: warm, lanes_free and prefill, see ``running``. with running(cache, fault, linger, **shape) as url: yield url diff --git a/tools/tests/test_bench_prompts.py b/tools/tests/test_bench_prompts.py index ffc638a88ee..c717e5f7b7c 100644 --- a/tools/tests/test_bench_prompts.py +++ b/tools/tests/test_bench_prompts.py @@ -80,8 +80,11 @@ def test_prompts_file_sends_a_different_prompt_on_each_stream(self): self.assertEqual([c["prompt"] for c in report["cells"]], ["distinct"]) cell = report["cells"][0] self.assertEqual({sent_text(b) for b in bodies if b["max_tokens"] != 16}, {q["prompt"] for q in items[:4]}) - self.assertEqual(cell["alone"], {"equal": 4, "unequal": 0, "failed": 0}) - self.assertEqual(cell["serial"], {"equal": 4, "unequal": 0, "failed": 0}) + # The canned replies stream one after another and carry no draft counters: equal, but proving neither. + self.assertEqual(cell["alone"], {"equal": 4, "unequal": 0, "failed": 0, + "vacuous": "1 of 1 reps had no two streams decoding at once"}) + self.assertEqual(cell["serial"], {"equal": 4, "unequal": 0, "failed": 0, "accepted": 0, "plain_drafted": 0, + "vacuous": "the server reported no draft counters for some runs"}) self.assertEqual(sum(1 for b in bodies if b.get("draft") is False), 4) def test_prompts_and_mixed_are_exclusive(self): diff --git a/tools/tests/test_bench_served_evidence.py b/tools/tests/test_bench_served_evidence.py new file mode 100644 index 00000000000..e991effe204 --- /dev/null +++ b/tools/tests/test_bench_served_evidence.py @@ -0,0 +1,77 @@ +"""bench_concurrent.py and image_cache_turns.py against the fake served API: comparisons that compared nothing say so. + +bench_concurrent is a reporter: its ``alone`` and ``serial`` counts carry ``vacuous`` when no two streams decoded at +once, or no draft landed, or the plain runs drafted. image_cache_turns' resumed == fresh fails when the fresh server +resumed or no later turn did. +""" +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from fake_served_api import fake # noqa: E402 + +TOOLS = HERE.parent + + +def concurrent(fault=None): + """Each cell's ``alone`` and ``serial`` counts from a two-stream greedy run with ``--alone --serial``.""" + with tempfile.TemporaryDirectory() as folder, fake(False, fault) as url: + out = Path(folder) / "out.json" + subprocess.run([sys.executable, str(TOOLS / "bench_concurrent.py"), url, "fake", "--levels", "2", "--reps", + "1", "--temperatures", "0", "--tokens", "64", "--alone", "--serial", "--output", str(out)], + capture_output=True, text=True, timeout=120, check=True) + return [(c["alone"], c["serial"]) for c in json.loads(out.read_text())["cells"]] + + +def turns(cached_fault=None, fresh_cache=False): + """image_cache_turns' exit code and FAIL lines, the fresh side a cache-off fake unless ``fresh_cache``.""" + with tempfile.TemporaryDirectory() as folder, fake(True, cached_fault) as url, fake(fresh_cache) as fresh: + image = Path(folder) / "a.png" + image.write_bytes(b"\x89PNG") + done = subprocess.run([sys.executable, str(TOOLS / "image_cache_turns.py"), "--url", url, "--fresh-url", + fresh, "--image", str(image), "--turns", "3", "--tokens", "8"], + capture_output=True, text=True, timeout=120) + return done.returncode, [line for line in done.stdout.splitlines() if line.startswith("FAIL ")] + + +class ConcurrentEvidenceTests(unittest.TestCase): + def test_a_healthy_server_proves_both(self): + for alone, serial in concurrent(): + self.assertNotIn("vacuous", alone) + self.assertNotIn("vacuous", serial) + self.assertGreater(serial["accepted"], 0) + + def test_a_server_serving_one_at_a_time_is_named(self): + for alone, _ in concurrent("serial"): + self.assertIn("no two streams decoding at once", alone.get("vacuous", "")) + + def test_undrafted_or_plain_drafting_is_named(self): + for fault, words in (("undrafted", "accepted no draft"), ("plain_drafts", "runs drafted")): + with self.subTest(fault=fault): + for _, serial in concurrent(fault): + self.assertIn(words, serial.get("vacuous", "")) + + +class ImageTurnsTests(unittest.TestCase): + def test_a_resuming_server_against_a_fresh_one_passes(self): + self.assertEqual(turns(), (0, [])) + + def test_a_server_that_never_resumed_fails_by_name(self): + code, failed = turns("resumed") + self.assertEqual(code, 1) + self.assertEqual([line.split(":")[0] for line in failed], ["FAIL text", "FAIL image", "FAIL repeat"]) + self.assertTrue(all("compared fresh with fresh" in line for line in failed), failed) + + def test_a_fresh_server_that_resumed_fails_by_name(self): + code, failed = turns(fresh_cache=True) + self.assertEqual(code, 1) + self.assertTrue(failed and all("(not fresh)" in line for line in failed), failed) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/zig/flashnext_constraint_gate.py b/tools/zig/flashnext_constraint_gate.py index f88d4ba1b34..629a69bc6eb 100644 --- a/tools/zig/flashnext_constraint_gate.py +++ b/tools/zig/flashnext_constraint_gate.py @@ -1,4 +1,5 @@ """Flash Next Metal gate: run under the shared GPU lock with baseline and candidate native binaries.""" +# Fails by name per server: a temperature whose drafted cases accept no draft, plain drafting, or seeds 7/1904 equal. import argparse import contextlib @@ -71,6 +72,29 @@ def validate(name, reply): return ids +def drafts(row, key): + """A case row's speculative count; 0 when the server reported none.""" + value = (row.get("speculative") or {}).get(key) + return value if type(value) is int and value >= 0 else 0 + + +def exercised(rows, answers): + """Raises unless every server's drafts landed per temperature, plain drafted none and the two seeds differed.""" + for label, replies in answers.items(): + mine = [r for r in rows if r["server"] == label] + for temperature in sorted({r["request"]["temperature"] for r in mine}): + at = [r for r in mine if r["request"]["temperature"] == temperature] + if not sum(drafts(r, "accepted") for r in at if r["request"]["draft"]): + raise AssertionError(f"{label}: no draft accepted at t{temperature} (drafted/plain compared nothing)") + plain = sum(drafts(r, "drafted") for r in mine if not r["request"]["draft"]) + if plain: + raise AssertionError(f"{label}: plain cases drafted {plain} tokens (\"draft\": false not honoured)") + seeded = [(ids, replies.get(key.replace("-s7-", "-s1904-"))) + for key, ids in replies.items() if "-t0.7-s7-" in key] + if not any(a != b for a, b in seeded): + raise AssertionError(f"{label}: seeds 7 and 1904 gave the same tokens in every case (seed never sampled)") + + def post(base, body): request = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) @@ -172,7 +196,8 @@ def main(): manifest["cases"].append({"server": label, "case": key, "rep": rep, "request": body, "token_ids": ids, "cached_tokens": reply["usage"].get("prompt_tokens_details", {}).get("cached_tokens", 0), - "runtime": reply["tensorfold"], "wall_seconds": elapsed}) + "runtime": reply["tensorfold"], "speculative": reply.get("speculative"), + "wall_seconds": elapsed}) (args.output / "receipt.json").write_text(json.dumps(manifest, indent=2) + "\n") for key, name, _ in all_cases: left = answers["baseline1" if name == "plain" else "candidate2"][key] @@ -185,6 +210,7 @@ def main(): if ids != replies[key[:-1] + "0"]: raise AssertionError(f"{label}/{key}: drafted/plain token ids differ") manifest["checks"].append({"server": label, "case": key, "draft_plain_equal": True}) + exercised(manifest["cases"], answers) if args.cache_gib > 0 and args.prefix_repeats: for c in manifest["cases"]: if c["server"] == "candidate1" and not c["case"].startswith("plain-") and c["cached_tokens"] != 0: diff --git a/tools/zig/reuse_served.py b/tools/zig/reuse_served.py index 20b176ae401..3ac44f84ef5 100644 --- a/tools/zig/reuse_served.py +++ b/tools/zig/reuse_served.py @@ -4,19 +4,24 @@ import http.client import json import os +from pathlib import Path import re +import select import sys import threading import time import urllib.parse import urllib.request +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import conformance_lifecycle as lifecycle # noqa: E402 + COLD = (1024, 2048, 8192, 16384, 32768, 65536) # cold prompt lengths: a warm-up, then the PP rule's PROBE = chr(0x2063) + "probe" # the server's system-prefix probe (prompt.zig systemPrefixLen) USAGE = """modes: record BASE MODEL ROWS.jsonl every scenario on a server with the prompt cache on; cached tokens checked per reply replay BASE MODEL ROWS.jsonl OUT the same bodies, in order, on a server started with --prompt-cache-gib 0 - compare ROWS.jsonl OUT full token digests equal, drafted == "draft": false; timing apart + compare ROWS.jsonl OUT full token digests equal, drafted == "draft": false, the cancel held; timing apart evict BASE MODEL ROWS.jsonl GIB a budget that holds one conversation: alternating ones evict, a big one is refused cold BASE MODEL PROMPTS.json OUT cold prompts 2k-64k (built once through /v1/tokenize): time to first token pp OUT... cold medians by length, each run against the first @@ -40,6 +45,8 @@ class Client: + SETTLE_S = 60 # seconds a cancel waits for the server to go idle, before the cut and after it + def __init__(self, base: str, model: str) -> None: self.base, self.model = base.rstrip("/"), model @@ -66,15 +73,39 @@ def chat(self, body: dict) -> dict: "finish": choice.get("finish_reason"), "content": msg.get("content") or "", "reasoning": msg.get("reasoning_content") or "", "calls": msg.get("tool_calls") or []} + def get(self, path: str): + """A GET's status and raw body (conformance_lifecycle's census, disconnects and health read it).""" + try: + with urllib.request.urlopen(self.base + path, timeout=30) as r: + return r.status, r.read() + except urllib.error.HTTPError as e: + return e.code, e.read(1 << 16) + except OSError: + return 0, b"" + def cancel(self, body: dict, after: float) -> dict: """Sends the request and closes the socket after `after` seconds, before any reply (a cancel in prefill).""" + # "error": the reply came before the cut, 1 disconnect not counted, /v1/load not idle again, or /health not ok + settle_s = self.SETTLE_S + base, before = lifecycle.idle(self, settle_s), lifecycle.disconnects(self) u = urllib.parse.urlparse(self.base) c = http.client.HTTPConnection(u.hostname, u.port, timeout=7200) c.request("POST", "/v1/chat/completions", json.dumps(body), {"Content-Type": "application/json"}) time.sleep(after) + early = bool(select.select([c.sock], [], [], 0)[0]) # the reply already arriving: there was nothing to cancel c.sock.shutdown(2) c.close() - return {"cancelled_after": after} + seen, held = lifecycle.settle(self, lambda s: base is not None and s == base, settle_s) + now = lifecycle.disconnects(self) + counted = now - before if now is not None and before is not None else None + problems = [why for bad, why in [ + (base is None, f"no idle census from GET /v1/load within {settle_s} s before the cut"), + (early, f"the reply came before the cut at {after} s: nothing was cancelled (lower --cancel-after)"), + (counted != 1, f"the server counted {counted} disconnects for 1 cut"), + (base is not None and not held, f"the census {seen} did not return to {base} (a lane or page held)"), + (not lifecycle.healthy(self), "GET /health not ok after the cut")] if bad] + out = {"cancelled_after": after, "disconnects": counted, "census": seen} + return {**out, "error": "; ".join(problems)} if problems else out def tokens(self, messages: list, tools: list | None, thinking: bool, generation: bool) -> list[int]: body = {"model": self.model, "messages": messages, "add_generation_prompt": generation, @@ -346,10 +377,13 @@ def replay(client: Client, rows_path: str, out_path: str) -> int: def compare(rows_path: str, fresh_path: str) -> int: rows = {r["i"]: r for r in map(json.loads, open(rows_path))} fresh = {r["i"]: r["got"] for r in map(json.loads, open(fresh_path))} - bad, faster, slow, total = 0, [], [], 0 + bad, faster, slow, total, cut = 0, [], [], 0, 0 by_messages: dict[tuple, set] = {} for i, r in sorted(rows.items()): if r["arm"] == "cancel": + cut += not r["ok"] + verdict = "held" if r["ok"] else f"FAIL {r['got'].get('error')}" + print(f"{i:3d} {r['conv']:>4} t{r['turn']} cancel {verdict}") continue f, g = fresh.get(i), r["got"] total += 1 @@ -377,9 +411,11 @@ def compare(rows_path: str, fresh_path: str) -> int: print(f"drafted == plain on the same messages: {len(by_messages) - len(split)}/{len(by_messages)}") for conv, turn, arm, prompt, cached, t, ft in faster: print(f" {conv:>4} t{turn} {arm:<7} prompt {prompt:6d} cached {cached:6d}: ttft {t:6.2f} s vs fresh {ft:6.2f} s ({ft / max(t, 1e-6):5.1f}x)") - print(f"{'PASS' if bad == 0 and not split else 'FAIL'}: {total - bad}/{total} replies equal and as cached as planned") + ok = bad == 0 and not split and not cut + print(f"{'PASS' if ok else 'FAIL'}: {total - bad}/{total} replies equal and as cached as planned" + + (f"; {cut} cancels did not hold" if cut else "")) print(f"timing: {len(slow)} resumed replies no sooner than fresh{': ' + str(slow) if slow else ''}") - return 1 if bad or split else 0 + return 0 if ok else 1 def ranks(r0_path: str, r1_path: str) -> int: diff --git a/tools/zig/structured_served.py b/tools/zig/structured_served.py index 4545d2efd62..605f658be75 100644 --- a/tools/zig/structured_served.py +++ b/tools/zig/structured_served.py @@ -1,4 +1,5 @@ """Structured output on a running tensorfold-native: valid replies, drafted == plain, concurrent == solo, refusals.""" +# Equal means equal token_sha256 (reasoning too); drafted == plain also needs drafts in each mode and none in plain. from __future__ import annotations @@ -9,6 +10,10 @@ import sys import urllib.error import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from conformance import drafted_gate, reply_row, same # noqa: E402 SCHEMA = { "type": "object", @@ -108,7 +113,8 @@ def main() -> int: runs = [(name, prompt, extra, sampled, thinking) for (name, prompt, extra) in CASES + PLAIN for sampled in (False, True) for thinking in (False, True)] failures = 0 - alone: dict[tuple, str] = {} + alone: dict[tuple, dict] = {} + pairs: dict[str, list] = {"greedy": [], "sampled": []} print(f"{model}: {len(runs)} runs alone, drafted and plain") for name, prompt, extra, sampled, thinking in runs: tokens = args.thinking_tokens if thinking else args.tokens @@ -118,12 +124,17 @@ def main() -> int: print(f"FAIL {name} sampled={sampled} thinking={thinking}: HTTP {code}/{code2} {r} {r2}") failures += 1 continue - (text, why), (text2, _) = answer(r), answer(r2) - ok, same = valid(name, text), text == text2 - failures += (not ok) + (not same) - alone[(name, sampled, thinking)] = text - print(f"{'ok ' if ok and same else 'FAIL'} {name:18} sampled={sampled!s:5} thinking={thinking!s:5} " - f"valid={ok!s:5} drafted==plain={same!s:5} {why:6} {text[:60]!r}") + text, why = answer(r) + drafted, plain = reply_row(code, r), reply_row(code2, r2) + ok, equal = valid(name, text), same(plain, drafted) is True + failures += (not ok) + (not equal) + alone[(name, sampled, thinking)] = drafted + pairs["sampled" if sampled else "greedy"].append((plain, drafted)) + print(f"{'ok ' if ok and equal else 'FAIL'} {name:18} sampled={sampled!s:5} thinking={thinking!s:5} " + f"valid={ok!s:5} drafted==plain={equal!s:5} {why:6} {text[:60]!r}") + gate = drafted_gate(pairs) + failures += not gate["passed"] + print(f"{'ok ' if gate['passed'] else 'FAIL'} drafted == plain: {gate['line']}") print(f"all {len(runs)} at once, {args.concurrency} at a time") with cf.ThreadPoolExecutor(args.concurrency) as pool: @@ -137,9 +148,9 @@ def main() -> int: failures += 1 print(f"FAIL concurrent {key}: HTTP {code}") continue - if answer(r)[0] != alone[key]: + if same(alone[key], reply_row(code, r)) is not True: failures += 1 - print(f"FAIL concurrent {key}: differs from alone: {answer(r)[0][:60]!r}") + print(f"FAIL concurrent {key}: differs from alone or unverified: {answer(r)[0][:60]!r}") else: together += 1 print(f"{together} of {len(runs)} concurrent replies equal their run alone") diff --git a/tools/zig/test_flashnext_constraint_gate.py b/tools/zig/test_flashnext_constraint_gate.py index acd188d7fa7..42025b4659d 100644 --- a/tools/zig/test_flashnext_constraint_gate.py +++ b/tools/zig/test_flashnext_constraint_gate.py @@ -1,8 +1,11 @@ -"""Host checks for the gate's native-server launch.""" +"""Host checks for the gate's native-server launch, and its draft and seed checks against fake replies.""" +import contextlib +import hashlib import io import json from pathlib import Path +import sys import tempfile import unittest from unittest.mock import patch @@ -38,5 +41,51 @@ def test_non_metal_health_is_refused(self): popen.return_value.terminate.assert_called_once() +def fake_post(fault): + """``post`` for a healthy server, or one with ``fault``: undrafted, plain_drafts or unsampled (seed ignored).""" + def post(_base, body): + seed = body["seed"] if body["temperature"] and fault != "unsampled" else None + shape = [body["messages"], body.get("response_format"), body.get("tool_choice"), seed] + ids = list(hashlib.sha256(json.dumps(shape).encode()).digest()[:8]) + message = {"content": '{"n": 7}'} if "response_format" in body else {"content": "def add(a, b): ..."} + if "tools" in body: + message = {"content": "", "tool_calls": [{"function": {"name": "choose", "arguments": '{"n": 7}'}}]} + drafting = (body["draft"] or fault == "plain_drafts") and fault != "undrafted" + return {"choices": [{"finish_reason": "stop", "message": message}], "tensorfold": {"token_ids": ids}, + "usage": {"prompt_tokens_details": {"cached_tokens": 0}}, + "speculative": {"drafted": 3 * drafting, "accepted": 2 * drafting}}, 0.01 + return post + + +def run_gate(fault=None): + """The gate's main() on fake servers: None when it passes, else its AssertionError's text.""" + @contextlib.contextmanager + def serve(*_): + yield "http://fake" + with tempfile.TemporaryDirectory() as directory: + binary = Path(directory) / "tensorfold-native" + binary.write_bytes(b"binary") + argv = ["gate", "--baseline", str(binary), "--candidate", str(binary), "--model", "m", "--revision", "r", + "--quantization", "q", "--gpu", "g", "--output", str(Path(directory) / "out"), "--reps", "1"] + with patch.object(sys, "argv", argv), patch.object(gate, "serve", serve), \ + patch.object(gate, "post", fake_post(fault)), contextlib.redirect_stdout(io.StringIO()): + try: + gate.main() + except AssertionError as error: + return str(error) + return None + + +class ExercisedTests(unittest.TestCase): + def test_a_healthy_server_passes(self): + self.assertIsNone(run_gate()) + + def test_unexercised_drafts_and_seeds_fail_by_name(self): + for fault, words in (("undrafted", "no draft accepted at t0"), ("plain_drafts", "plain cases drafted"), + ("unsampled", "seeds 7 and 1904 gave the same tokens")): + with self.subTest(fault=fault): + self.assertIn(words, run_gate(fault) or "passed") + + if __name__ == "__main__": unittest.main() diff --git a/tools/zig/test_served_gates.py b/tools/zig/test_served_gates.py new file mode 100644 index 00000000000..69b0c0d327a --- /dev/null +++ b/tools/zig/test_served_gates.py @@ -0,0 +1,138 @@ +"""Served gate scripts against the fake served API: clean they pass, and each planted fault fails the gate by name.""" +# drafted == plain: no draft, plain drafting or empty replies fail; cancel: too late, a held lane or bad health fail. +import contextlib +import importlib +import io +from pathlib import Path +import subprocess +import sys +import tempfile +import types +import unittest +from unittest.mock import patch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / "tests")) +from fake_served_api import fake # noqa: E402 +import reuse_served # noqa: E402 + +DRAFT_FAULTS = ("undrafted", "plain_drafts", "empty") + + +def script(name, *argv, timeout=120): + """A tools/zig script's exit code and stdout.""" + done = subprocess.run([sys.executable, str(HERE / f"{name}.py"), *argv], capture_output=True, text=True, + timeout=timeout) + return done.returncode, done.stdout + + +def named(out, words): + """The verdict of the check line that names ``words``: True for "ok", False for "FAIL", None when absent.""" + lines = [line for line in out.splitlines() if words in line] + return None if not lines else all(line.startswith("ok") for line in lines) + + +class DraftedEqualsPlainTests(unittest.TestCase): + def structured(self, fault=None): + with fake(False, fault) as url: + _, out = script("structured_served", "--url", url, "--tokens", "8", "--thinking-tokens", "8") + rows = [line for line in out.splitlines() if "drafted==plain=" in line or "drafted == plain:" in line] + return bool(rows) and not any("drafted==plain=False" in r or r.startswith("FAIL drafted") for r in rows) + + def test_structured_served(self): + self.assertTrue(self.structured()) + for fault in (*DRAFT_FAULTS, "sampled_drafts"): + with self.subTest(fault=fault): + self.assertFalse(self.structured(fault)) + + def vision(self, fault=None): + with tempfile.TemporaryDirectory() as folder, fake(False, fault) as url: + for name in ("a.png", "b.png"): + (Path(folder) / name).write_bytes(b"\x89PNG" + name.encode()) + _, out = script("vision_served", "--url", url, "--images", folder, "--tokens", "8") + return named(out, 'drafted equals "draft": false with an image') + + def test_vision_served(self): + self.assertIs(self.vision(), True) + for fault in DRAFT_FAULTS: + with self.subTest(fault=fault): + self.assertIs(self.vision(fault), False) + + def video(self, fault=None): + ids = types.SimpleNamespace(tolist=lambda: [1, 2]) + + class Processor: + video_processor = None + + def apply_chat_template(self, *_, **__): + return "" + + def __call__(self, **_): + return {"input_ids": [ids]} + stubs = {"glm_video_fixtures": types.SimpleNamespace(load=lambda *_: (None, None)), + "transformers": types.SimpleNamespace(AutoProcessor=types.SimpleNamespace( + from_pretrained=lambda _: Processor()))} + with patch.dict(sys.modules, stubs), tempfile.TemporaryDirectory() as clips, fake(False, fault) as url: + for name in ("h264.mp4", "hevc.mp4", "h264-odd.mp4", "short.mp4"): + (Path(clips) / name).write_bytes(name.encode()) + sys.modules.pop("video_served", None) + video_served = importlib.import_module("video_served") + out = io.StringIO() + argv = ["video_served.py", "--url", url, "--model", "fake", "--clips", clips, "--tokens", "8"] + with patch.object(sys, "argv", argv), contextlib.redirect_stdout(out): + video_served.main() + sys.modules.pop("video_served", None) + return named(out.getvalue(), 'drafted equals "draft": false with a video') + + def test_video_served(self): + self.assertIs(self.video(), True) + for fault in DRAFT_FAULTS: + with self.subTest(fault=fault): + self.assertIs(self.video(fault), False) + + def xpu(self, fault=None): + with fake(False, fault) as url: + code, out = script("xpu_draft_receipt", url, "fake", "--tokens", "8", "--reps", "1") + return code, out.splitlines()[-1] + + def test_xpu_draft_receipt_exits_1_on_fail(self): + self.assertEqual(self.xpu(), (0, "DRAFT IDENTITY: PASS")) + for fault in (*DRAFT_FAULTS, "sampled_drafts"): + with self.subTest(fault=fault): + code, last = self.xpu(fault) + self.assertEqual(code, 1, last) + self.assertTrue(last.startswith("DRAFT IDENTITY: FAIL"), last) + + +class ReuseCancelTests(unittest.TestCase): + def cancel(self, fault=None, prefill=2.0): + """Failures after scenario 5's cancel row, against a fake that holds each request ``prefill`` seconds.""" + with tempfile.TemporaryDirectory() as folder, fake(False, fault, prefill=prefill) as url: + rec = reuse_served.Recorder(reuse_served.Client(url, "fake"), str(Path(folder) / "rows.jsonl"), 8) + rec.c.SETTLE_S = 1 + conv = reuse_served.Conv("C", "You audit code.", "Audit it.", None, False, False) + body = conv.body("fake", 8, False) + with contextlib.redirect_stdout(io.StringIO()) as out: + rec.row(conv, "cancel", body, rec.c.cancel(body, 0.2), None, 0) + rec.out.close() + return rec.failures, out.getvalue() + + def test_a_cut_in_prefill_holds(self): + self.assertEqual(self.cancel()[0], 0) + + def test_a_cancel_that_cancelled_nothing_fails(self): + failures, out = self.cancel(prefill=0) + self.assertEqual(failures, 1, out) + self.assertIn("the reply came before the cut", out) + + def test_a_cancel_that_holds_a_lane_or_breaks_health_fails(self): + for fault, words in (("cancel_lane", "did not return to"), ("cancel_health", "/health not ok")): + with self.subTest(fault=fault): + failures, out = self.cancel(fault) + self.assertEqual(failures, 1, out) + self.assertIn(words, out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/zig/video_served.py b/tools/zig/video_served.py index 87d012b7fc4..30b2c5654dd 100644 --- a/tools/zig/video_served.py +++ b/tools/zig/video_served.py @@ -1,4 +1,5 @@ """Video input served end to end on a running ``tensorfold-native --vision`` (#565's video checks).""" +# drafted == plain: equal token_sha256, a draft accepted when drafted and none drafted when plain, else it fails. from __future__ import annotations @@ -12,6 +13,8 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from conformance import drafted_gate, reply_row # noqa: E402 from glm_video_fixtures import load # noqa: E402 @@ -117,7 +120,8 @@ def turns(c: Path) -> tuple[list, list]: code2, r2 = ask(convo, draft=False) check("a video request answers", code == 200 and code2 == 200, f"HTTP {code}/{code2} {r.get('error', '')}") if code == 200 and code2 == 200: - check("drafted equals \"draft\": false with a video", reply(r) == reply(r2), repr(reply(r)[:60])) + gate = drafted_gate({"greedy": [(reply_row(code2, r2), reply_row(code, r))]}) + check("drafted equals \"draft\": false with a video", gate["passed"], gate["line"] + " " + repr(reply(r)[:60])) runs = [[user(video(c), text(t))] for c in (a, b) for t in ("What colours appear?", "Does anything move?")] alone = [reply(ask(m)[1]) for m in runs] with cf.ThreadPoolExecutor(len(runs)) as pool: diff --git a/tools/zig/vision_served.py b/tools/zig/vision_served.py index 1e116150e3d..d1e7a60dcaf 100644 --- a/tools/zig/vision_served.py +++ b/tools/zig/vision_served.py @@ -1,4 +1,5 @@ """Image input served end to end on a running ``tensorfold-native --vision`` (#565's served checks).""" +# drafted == plain: equal token_sha256, a draft accepted when drafted and none drafted when plain, else it fails. from __future__ import annotations @@ -11,6 +12,9 @@ import urllib.request from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from conformance import drafted_gate, reply_row # noqa: E402 + def post(url: str, body: dict) -> tuple[int, dict]: req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) @@ -78,7 +82,8 @@ def check(label: str, ok: bool, detail: str = "") -> None: plain_text = ask([user(text("Describe this image in one sentence."))])[1] check("an image request answers", code == 200 and code2 == 200, f"HTTP {code}/{code2}") if code == 200 and code2 == 200: - check("drafted equals \"draft\": false with an image", reply(r) == reply(r2), repr(reply(r)[:60])) + gate = drafted_gate({"greedy": [(reply_row(code2, r2), reply_row(code, r))]}) + check("drafted equals \"draft\": false with an image", gate["passed"], gate["line"] + " " + repr(reply(r)[:60])) check("the image's tokens are in the prompt", r["usage"]["prompt_tokens"] > plain_text["usage"]["prompt_tokens"] + 8, f"{r['usage']['prompt_tokens']} prompt tokens with the image, {plain_text['usage']['prompt_tokens']} without") diff --git a/tools/zig/xpu_draft_receipt.py b/tools/zig/xpu_draft_receipt.py index dbdbc6fdf00..fa711cb647e 100644 --- a/tools/zig/xpu_draft_receipt.py +++ b/tools/zig/xpu_draft_receipt.py @@ -1,11 +1,16 @@ #!/usr/bin/env python3 -"""Drafted == "draft": false through the server: token_sha per prompt and sampling, with tok/s and acceptance.""" +"""Drafted == "draft": false through the server: token_sha256 per prompt and sampling, with tok/s and acceptance.""" # usage: xpu_draft_receipt.py BASE_URL MODEL [--tokens N] [--reps R] import argparse import json +from pathlib import Path import statistics +import sys import urllib.request +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from conformance import drafted_gate, reply_row # noqa: E402 + PROMPTS = { "code": "Write a Python function that parses an ISO 8601 date string and returns a datetime, with error handling and tests.", "prose": "Describe a quiet harbour town at dawn in about two hundred words.", @@ -24,6 +29,7 @@ def ask(base, model, prompt, tokens, extra): out = json.load(r) rt = dict(out["tensorfold"]) rt["speculative"] = out.get("speculative") or {} + rt["row"] = reply_row(r.status, out) return rt @@ -34,25 +40,31 @@ def main(): ap.add_argument("--tokens", type=int, default=256) ap.add_argument("--reps", type=int, default=3) a = ap.parse_args() - bad = 0 + bad, by_mode = 0, {} for sname, s in SAMPLINGS.items(): for pname, p in PROMPTS.items(): plain = [ask(a.base, a.model, p, a.tokens, {**s, "draft": False}) for _ in range(a.reps)] drafted = [ask(a.base, a.model, p, a.tokens, s) for _ in range(a.reps)] - shas = {x["token_sha"] for x in plain + drafted} - same = len(shas) == 1 + by_mode.setdefault(sname, []).extend((p["row"], d["row"]) for p, d in zip(plain, drafted)) + shas = {x["row"].get("sha") if x["row"].get("tokens") else None for x in plain + drafted} + same = len(shas) == 1 and None not in shas bad += not same tp = statistics.median(x["tokens_per_second"] for x in plain) td = statistics.median(x["tokens_per_second"] for x in drafted) sp = drafted[-1]["speculative"] acc = sp.get("acceptance_rate", 0) tpr = sp.get("tokens_per_round", 0) - print(f"{sname:6s} {pname:5s} {'SAME' if same else 'DIFF'} sha {sorted(shas)[0][:12]}" - f"{'' if same else ' vs ' + ','.join(x[:12] for x in sorted(shas)[1:])} " + shown = sorted(str(x)[:12] for x in shas) + print(f"{sname:6s} {pname:5s} {'SAME' if same else 'DIFF'} sha {shown[0]}" + f"{'' if same else ' vs ' + ','.join(shown[1:])} " f"plain {tp:6.1f} tok/s drafted {td:6.1f} tok/s ({td / tp:.2f}x) acceptance {acc:.2f} tokens/round {tpr:.2f}", flush=True) + gate = drafted_gate(by_mode) + print(f"drafted == plain: {gate['line']}") + bad += not gate["passed"] print("DRAFT IDENTITY:", "PASS" if bad == 0 else f"FAIL ({bad})") + return 1 if bad else 0 # a differing or empty pair, a mode without accepted drafts, or plain replies that drafted if __name__ == "__main__": - main() + sys.exit(main()) diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index 74ff61c018c..1eeec448ff5 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -35,6 +35,7 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod eos_policy.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.tokenizer, .filters = &.{"EOS policy:"} })).step); eos_policy.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = kolibri1Module(b, host, .debug, cuda, mods.core, mods.lanes), .filters = &.{"EOS policy:"} })).step); b.step("test-serve-flags-host", "Serve flag parsing, the flat TOML reader and --config expansion, without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "--compact-at:", "flat TOML:", "serve --config:" } })).step); + b.step("test-request-deadline-host", "deadline_s: the server ends a reply at its deadline with usage and ids").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"request deadline:"} })).step); b.step("test-dory-cli-host", "Dory CUDA loop option forwarding and invalid-value refusals").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"--device and --segments:"} })).step); b.step("test-dory-chat-host", "Dory chat template, EOS, reasoning split and qwen3_coder call on the CPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"Dory chat:"} })).step); b.step("test-embeddings-protocol-host", "Embedding request and response contracts without an admitted model or GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"embeddings protocol:"} })).step); diff --git a/zig/glm_lane_costs_host.zig b/zig/glm_lane_costs_host.zig index 76518cdb770..d1ffc50ce16 100644 --- a/zig/glm_lane_costs_host.zig +++ b/zig/glm_lane_costs_host.zig @@ -1,23 +1,36 @@ //! The production load-time measurement controller over recording timers, without devices or a checkpoint. const std = @import("std"); -const costs = @import("glm").lane_costs; +const glm = @import("glm"); +const costs = glm.lane_costs; const cuda = @import("cuda"); const t = std.testing; +const m = costs.measurements; const Recording = struct { windows: [costs.widths.len]usize = @splat(0), drafts: usize = 0, - forms: [3]bool = undefined, changes: usize = 0, - fact: bool = false, - pub fn form(r: *@This(), fact: bool) !void { - if (r.changes >= r.forms.len) return error.TooManyFormChanges; - r.forms[r.changes] = fact; + fact: u64 = 0, + ratio: [costs.widths.len]f64 = @splat(0.8), // a factored window's time over a classic one's, by width + runs: usize = 0, // windows run so far + slow: usize = 0, // the first this many windows run 15 ms over, as in a load's first seconds + drift: f64 = 0, // a window's time moves by this fraction a window run before it + switched: [2]f64 = .{ 0, 0 }, // classic's and factored's fraction over right after a window on the other form + last: ?bool = null, // the last window's form, factored or not + pub fn form(r: *@This(), fact: u64) !void { r.changes += 1; r.fact = fact; } + fn classic(i: usize) f64 { + return 20 + @as(f64, @floatFromInt(costs.widths[i])); + } pub fn window(r: *@This(), i: usize) !f64 { r.windows[i] += 1; - return (20 + @as(f64, @floatFromInt(costs.widths[i]))) * @as(f64, if (r.fact) 0.8 else 1); + defer r.runs += 1; + const f = (r.fact >> @intCast(i)) & 1 != 0; + defer r.last = f; + const after = if (r.last) |l| (if (l != f) r.switched[@intFromBool(f)] else 0) else 0; + const ms = classic(i) * (if (f) r.ratio[i] else 1) * (1 + after); + return ms * (1 + r.drift * @as(f64, @floatFromInt(r.runs))) + @as(f64, if (r.runs < r.slow) 15 else 0); } pub fn draft(r: *@This(), depth: usize) !f64 { r.drafts += 1; @@ -25,52 +38,121 @@ const Recording = struct { } }; -test "GLM load prices: DFlash2 races expert forms without timing unused windows or head steps" { +/// Each width's windows in a race: the untimed sweeps on both forms, then seven timed on each. +const raced = 2 * m.sweeps + 14; + +test "GLM load prices: DFlash2 races the forms at every width without timing head steps or keeping prices" { var r: Recording = .{}; - const kept = try costs.measurements.measure(&r, true, null); - try t.expectEqual([3]bool{ false, true, true }, r.forms); + const kept = try m.measure(&r, true, null); + try t.expectEqual(m.all, r.fact); + try t.expectEqual(m.all, kept.fact); try t.expectEqual(@as(usize, 0), r.drafts); - for (r.windows, 0..) |count, i| { - const expected: usize = if (i == 1 or i == 3 or i == 5) 16 else if (i == costs.widths.len - 1) 8 else 0; - try t.expectEqual(expected, count); - } - try t.expect(costs.measurements.reusable(kept, true)); - try t.expect(!costs.measurements.reusable(kept, false)); + for (r.windows) |count| try t.expectEqual(raced, count); + try t.expect(m.reusable(kept, true)); + try t.expect(!m.reusable(kept, false)); try t.expect(costs.tableFor(kept, true) == null); } -test "GLM load prices: MTP retains every timed width and the two-level head slope" { +test "GLM load prices: MTP keeps each width's raced time as its price, then the two-level head slope" { var r: Recording = .{}; - const kept = try costs.measurements.measure(&r, false, null); - try t.expectEqual([3]bool{ false, true, true }, r.forms); - try t.expectEqual(@as(usize, 32), r.drafts); - for (r.windows, 0..) |count, i| { - const expected: usize = 8 + @as(usize, if (i == 1 or i == 3 or i == 5) 16 else if (i == costs.widths.len - 1) 8 else 0); - try t.expectEqual(expected, count); + const kept = try m.measure(&r, false, null); + try t.expectEqual(m.all, r.fact); + try t.expectEqual(@as(usize, 16), r.drafts); + for (r.windows, kept.ms, 0..) |count, ms, i| { + try t.expectEqual(raced, count); + try t.expectApproxEqAbs(Recording.classic(i) * 0.8, ms, 1e-12); } try t.expectApproxEqAbs(@as(f64, 0.5), kept.step_ms, 1e-12); - try t.expect(costs.measurements.reusable(kept, false)); - try t.expect(!costs.measurements.reusable(kept, true)); + try t.expect(m.reusable(kept, false)); + try t.expect(!m.reusable(kept, true)); try t.expect(costs.tableFor(kept, false) != null); try t.expect(costs.tableFor(kept, true) == null); } +test "GLM load prices: each width keeps the form its windows ran faster on, and classic inside the margin" { + var r: Recording = .{}; + r.ratio = .{ 0.995, 0.97, 0.97, 1.02, 1.02, 0.97, 0.97, 0.97, 0.97, 0.97 }; + const kept = try m.measure(&r, false, null); + const want = m.all & ~@as(u64, 0b1_1001); // classic at 1 row (inside the margin), 4 and 6 + try t.expectEqual(want, r.fact); + try t.expectEqual(want, kept.fact); + for (kept.ms, 0..) |ms, i| { + const f = if ((want >> @intCast(i)) & 1 != 0) r.ratio[i] else 1; + try t.expectApproxEqAbs(Recording.classic(i) * f, ms, 1e-12); + } +} + +test "GLM load prices: a dip is timed again at each width's own form, not the last raced one" { + var r: Recording = .{}; + r.ratio = @splat(0.97); + r.ratio[0] = 0.995; // inside the margin: 1 row stays classic + r.ratio[1] = 0.9; // 2 rows then dip under 1 row's price + const kept = try m.measure(&r, false, null); + try t.expectEqual(@as(u64, 0), kept.fact & 1); + try t.expect(r.windows[0] > raced); + try t.expectApproxEqAbs(Recording.classic(0), kept.ms[0], 1e-12); // a factored retime would lower it +} + test "GLM load prices: a named expert form is set once, before the warm-up, and no forms race" { for ([_]bool{ false, true }) |pin| for ([_]bool{ false, true }) |block| { var r: Recording = .{}; - const kept = try costs.measurements.measure(&r, block, pin); + const kept = try m.measure(&r, block, pin); try t.expectEqual(@as(usize, 1), r.changes); - try t.expectEqual(pin, r.forms[0]); - try t.expectEqual(@as(u64, @intFromBool(pin)), kept.fact); + try t.expectEqual(m.every(pin), r.fact); + try t.expectEqual(m.every(pin), kept.fact); try t.expectEqual(@as(usize, if (block) 0 else 16), r.drafts); - for (r.windows, 0..) |count, i| { - const warm: usize = if (i == costs.widths.len - 1) 8 else 0; - try t.expectEqual(warm + @as(usize, if (block) 0 else 8), count); - } - try t.expect(costs.measurements.reusable(kept, block)); + // as many untimed windows a width as a race's sweeps, then one fastest-of; DFlash2 times none + for (r.windows) |count| try t.expectEqual(@as(usize, if (block) 0 else 2 * m.sweeps + 8), count); + try t.expect(m.reusable(kept, block)); }; } +test "GLM load prices: a slow start outlasting the old warm-up decides no width's form and sets no price" { + var r: Recording = .{}; + r.ratio = @splat(1); // the two forms alike: classic at every width + r.slow = 48; // longer than a warm-up at the widest alone, as the slowest observed start was + const kept = try m.measure(&r, false, null); + try t.expectEqual(@as(u64, 0), kept.fact); + for (kept.ms, 0..) |ms, i| try t.expectApproxEqAbs(Recording.classic(i), ms, 1e-12); +} + +test "GLM load prices: a drift through the race falls on both forms alike" { + const Case = struct { drift: f64, ratio: f64, want: u64 }; + // faster as it runs with the forms alike, then slower with factored 2% faster at every width + for ([_]Case{ .{ .drift = -0.0002, .ratio = 1, .want = 0 }, .{ .drift = 0.0002, .ratio = 0.98, .want = m.all } }) |c| { + var r: Recording = .{}; + r.ratio = @splat(c.ratio); + r.drift = c.drift; + const kept = try m.measure(&r, true, null); + try t.expectEqual(c.want, kept.fact); + } +} + +test "GLM load prices: a window run slow right after the other form decides no width's form" { + var r: Recording = .{}; + r.ratio = @splat(0.97); + r.switched = .{ 0.04, 0.13 }; // classic 4% and factored 13% over right after the other form + const kept = try m.measure(&r, false, null); + try t.expectEqual(m.all, kept.fact); + for (kept.ms, 0..) |ms, i| try t.expectApproxEqAbs(Recording.classic(i) * 0.97, ms, 1e-12); +} + +test "GLM load prices: a window takes the form of the narrowest timed width that holds it" { + try t.expectEqual(@as(u64, 0), m.rows(0)); + try t.expectEqual(~@as(u64, 0), m.rows(m.all)); + try t.expectEqual(@as(u64, 1 << 3), m.rows(1 << 3)); // 4 rows alone + try t.expectEqual(@as(u64, 0b11 << 4), m.rows(1 << 4)); // 6 rows: 5 and 6 + try t.expectEqual(~@as(u64, 0) << 24, m.rows(1 << 9)); // 32 rows: 25 and on + var ks: glm.experts.Kernels = undefined; + ks.fact = m.rows(m.all & ~@as(u64, 0b1_1000)); + for ([_]usize{ 0, 4, 5, 6 }) |rows| try t.expect(!ks.factored(rows)); + for ([_]usize{ 1, 3, 7, 32, 33, 64, 4096 }) |rows| try t.expect(ks.factored(rows)); + var k: m.Kept = .{ .ms = @splat(1), .step_ms = 0, .fact = m.all }; + try t.expect(m.reusable(k, false)); + k.fact = m.all + 1; + try t.expect(!m.reusable(k, false)); +} + const Device = struct { fn attribute(out: *c_int, attr: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { out.* = if (attr == .compute_capability_major) 12 else 1; @@ -98,7 +180,7 @@ test "GLM load prices: an oversized NCCL setting disables the cache without reje a.free(v); } else _ = env.unsetenv(variable); } - var e: @import("glm").engine.Engine = undefined; + var e: glm.engine.Engine = undefined; e.settings = .{}; e.checkpoint_digest = @splat(1); e.share.world = 2; diff --git a/zig/src/families/glm/cuda_experts.zig b/zig/src/families/glm/cuda_experts.zig index f70972f84de..449abdc9330 100644 --- a/zig/src/families/glm/cuda_experts.zig +++ b/zig/src/families/glm/cuda_experts.zig @@ -17,7 +17,13 @@ pub const Kernels = struct { nvfp4: cuda.experts.Nvfp4Experts, b32: ?cuda.experts32.Nvfp4b32Experts, // loaded for a csf0_v1 checkpoint alone (wantsBlock32) router: cuda.grouped.Router, - fact: bool = false, // decode windows on NVFP4's factored tiles (the same bits): load timing picks it (cuda_lane_costs) + fact: u64 = 0, // bit r - 1: a decode window of r rows on NVFP4's factored tiles (the same bits); load timing picks them by width (cuda_lane_costs) + + /// Whether a decode window of `rows` runs on the factored tiles; past 64 rows, as 64 do. + pub fn factored(ks: *const Kernels, rows: usize) bool { + const r = @min(rows, 64); + return r > 0 and (ks.fact >> @intCast(r - 1)) & 1 != 0; + } /// `plans`: the loaded experts module (its plan kernels); `block32`: block 32's image too, for these values. pub fn load(d: *const cuda.Driver, plans: cuda.Module, sms: u32, block32: ?cuda.experts32.Values) !Kernels { diff --git a/zig/src/families/glm/cuda_follow.zig b/zig/src/families/glm/cuda_follow.zig index 940dceac462..1e8724243b5 100644 --- a/zig/src/families/glm/cuda_follow.zig +++ b/zig/src/families/glm/cuda_follow.zig @@ -24,7 +24,7 @@ pub const Header = extern struct { n: u32 = 0, // ids that follow depth: u32 = 0, // draft: drafts to chain; chunk: where it starts; shared: its parts flags: u32 = 0, // begin: sampled; draft: from the prompt (1), chances (2); prefill, chunk: prompt_logprobs (1); chunk: indexer rows split (2); verify, shared: whole rows; snapshots: pages shared - a: u64 = 0, // begin: the prompt cache's pages first in its table; keep: rows; prefill, chunk: the kept state it resumes (0: none); redraw: the prompt's length + a: u64 = 0, // begin: the prompt cache's pages first in its table; keep: rows; prefill, chunk: the kept state it resumes (0: none); redraw: the prompt's length; form: a bit a window's rows seed: u64 = 0, // begin: the sampling seed; prefill, chunk: the kept state's position temperature: f64 = 0, top_p: f64 = 0, @@ -323,10 +323,10 @@ pub const Leader = struct { try x.e.draftBlock(reqs); } - /// Every rank's decode windows on the factored expert form or not (the same bits; load timing picks it). - pub fn expertForm(x: Leader, fact: bool) !void { - try x.send(.{ .kind = @backingInt(Kind.form), .a = @intFromBool(fact) }, &.{}); - x.e.m.experts.fact = fact; + /// Every rank's expert forms, bit r - 1 for a window of r rows (the same bits; load timing picks them by width). + pub fn expertForm(x: Leader, forms: u64) !void { + try x.send(.{ .kind = @backingInt(Kind.form), .a = forms }, &.{}); + x.e.m.experts.fact = forms; } /// The other ranks leave their loops. @@ -420,7 +420,7 @@ pub fn follow(e: *Engine, link: *Link) !void { try e.prefillMany(decoded, &firsts); }, .keep => try e.keep(@intCast(h.a)), - .form => e.m.experts.fact = h.a != 0, + .form => e.m.experts.fact = h.a, .draft => { const ids = try e.gpa.dupe(u32, step.ids); defer e.gpa.free(ids); diff --git a/zig/src/families/glm/cuda_lane_cost_measure.zig b/zig/src/families/glm/cuda_lane_cost_measure.zig index f4d00545c80..cecfb80d04b 100644 --- a/zig/src/families/glm/cuda_lane_cost_measure.zig +++ b/zig/src/families/glm/cuda_lane_cost_measure.zig @@ -2,13 +2,21 @@ const std = @import("std"); const rule = @import("lanes").cost_rule; pub const widths = [_]u32{ 1, 2, 3, 4, 6, 8, 12, 16, 24, 32 }; -const race = [_]usize{ 1, 3, 5 }; const margin = 0.01; -const warm = 8; +/// Untimed sweeps of every width before one is timed (both forms when racing): a TP=4 load's first 4 s ran 60% slow. +pub const sweeps = 5; const levels = [2]usize{ 1, 8 }; +/// `fact` holds a bit a width, set where that width's windows run on the factored form. pub const Kept = extern struct { ms: [widths.len]f64, step_ms: f64, fact: u64 }; +/// Every width on the factored form. +pub const all: u64 = (1 << widths.len) - 1; -/// Warm the target, race its expert forms unless `pin` names one, then measure only the prices this drafter consumes. +/// Every width on one form. +pub fn every(factored: bool) u64 { + return if (factored) all else 0; +} + +/// Warm the target, race its expert forms by width unless `pin` names one, then time the prices this drafter consumes. pub fn measure(timer: anytype, block: bool, pin: ?bool) !Kept { const Window = struct { timer: @TypeOf(timer), @@ -24,31 +32,64 @@ pub fn measure(timer: anytype, block: bool, pin: ?bool) !Kept { }; const w: Window = .{ .timer = timer }; const d: Draft = .{ .timer = timer }; - if (pin) |f| try timer.form(f); - for (0..warm) |_| _ = try w.time(widths.len - 1); - const fact = pin orelse race: { - var forms: [2]f64 = .{ 0, 0 }; - for (&forms, [_]bool{ false, true }) |*sum, f| { - try timer.form(f); - for (race) |i| sum.* += try rule.fastest(w, i); - if (!block) sum.* += try rule.fastest(d, levels[0]); + var k: Kept = .{ .ms = @splat(0), .step_ms = 0, .fact = every(pin orelse false) }; + if (pin) |f| { + try timer.form(every(f)); + if (block) return k; + for (0..2 * sweeps) |_| for (0..widths.len) |i| { + _ = try w.time(i); + }; + for (&k.ms, 0..) |*m, i| m.* = try rule.fastest(w, i); + } else { + // a width runs factored only where its windows beat classic's by the margin; its time is its price + const forms = try race(timer, w); + for (forms[0], forms[1], 0..) |classic, factored, i| { + if (factored < classic * (1 - margin)) k.fact |= @as(u64, 1) << @intCast(i); } - const won = forms[1] < forms[0] * (1 - margin); - try timer.form(won); - break :race won; - }; - var k: Kept = .{ .ms = @splat(0), .step_ms = 0, .fact = @intFromBool(fact) }; - if (block) return k; - for (&k.ms, 0..) |*m, i| m.* = try rule.fastest(w, i); + try timer.form(k.fact); + if (block) return k; + for (&k.ms, forms[0], forms[1], 0..) |*m, classic, factored, i| m.* = if (on(k.fact, i)) factored else classic; + } try rule.smooth(w, &k.ms); const chain = [2]f64{ try rule.fastest(d, levels[0]), try rule.fastest(d, levels[1]) }; k.step_ms = @max(0, (chain[1] - chain[0]) / @as(f64, @floatFromInt(levels[1] - levels[0]))); return k; } +/// Each form's fastest window by width: sweeps, then turns both ways, so no load's start, drift or switch picks one. +fn race(timer: anytype, w: anytype) ![2][widths.len]f64 { + const both = [2]u64{ 0, all }; + for (0..sweeps) |_| for (0..widths.len) |i| for (both) |f| { + try timer.form(f); + _ = try w.time(i); + }; + var ms: [2][widths.len]f64 = @splat(@splat(std.math.inf(f64))); + for (0..widths.len) |i| for (0..rule.reps) |r| for (0..2) |k| { + const p = k ^ (r & 1); // classic first on even rounds, factored on odd ones: a switch weighs on both alike + try timer.form(both[p]); + ms[p][i] = @min(ms[p][i], try w.time(i)); + }; + return ms; +} + +fn on(fact: u64, i: usize) bool { + return (fact >> @intCast(i)) & 1 != 0; +} + +/// A bit a row count from 1: a window takes the form of the narrowest timed width that holds it, past 32 the widest's. +pub fn rows(fact: u64) u64 { + var out: u64 = 0; + var i: usize = 0; + for (1..65) |r| { + while (i + 1 < widths.len and widths[i] < r) i += 1; + if (on(fact, i)) out |= @as(u64, 1) << @intCast(r - 1); + } + return out; +} + /// A form-only entry cannot masquerade as a window table, or the other way around. pub fn reusable(k: Kept, block: bool) bool { - if (k.fact > 1) return false; + if (k.fact & ~all != 0) return false; if (block) { for (k.ms) |m| if (m != 0) return false; return k.step_ms == 0; diff --git a/zig/src/families/glm/cuda_lane_costs.zig b/zig/src/families/glm/cuda_lane_costs.zig index 3e798ed90c2..b69018198ab 100644 --- a/zig/src/families/glm/cuda_lane_costs.zig +++ b/zig/src/families/glm/cuda_lane_costs.zig @@ -1,4 +1,4 @@ -//! Rank 0 keeps MTP prices and each drafter's expert-form choice per build and timing identity. +//! Rank 0 keeps MTP prices and each drafter's expert forms by window width per build and timing identity. const std = @import("std"); const sys = @import("sys"); const cuda = @import("cuda"); @@ -67,7 +67,7 @@ pub fn price(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: const parts = try keyParts(e, ctx, &name, &shape, pin); const key = if (parts) |v| cache.key(gpa, io, &v) catch null else null; if (key) |k| if (cache.load(Kept, gpa, io, k)) |kept| if (reuses(kept, block, pin)) { - try x.expertForm(kept.fact != 0); + try x.expertForm(measurements.rows(kept.fact)); try x.idle(); report(kept, "kept", block, pin != null); return tableFor(kept, block); @@ -94,7 +94,7 @@ pub fn price(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: /// A kept record stands for this load when it holds prices and, under a named form, was kept at that form. fn reuses(kept: Kept, block: bool, pin: ?bool) bool { - return measurements.reusable(kept, block) and (pin == null or pin.? == (kept.fact != 0)); + return measurements.reusable(kept, block) and (pin == null or kept.fact == measurements.every(pin.?)); } /// TF_GLM_EXPERT_FORM on rank 0, which chooses every rank's form: null races classic and factored, else the one named. @@ -106,7 +106,7 @@ fn pinnedForm() !?bool { /// A load that times nothing still sends a named form to every rank; unnamed, the forms stay classic. fn untimed(x: anytype, pin: ?bool) !?Table { const f = pin orelse return null; - try x.expertForm(f); + try x.expertForm(measurements.rows(measurements.every(f))); try x.idle(); std.log.info(untimed_line, .{if (f) "factored" else "classic"}); return null; @@ -118,7 +118,8 @@ const form_line = "glm: expert form ({s}): {s}{s}; DFlash2 keeps its seed window const untimed_line = "glm: expert form (untimed): {s} (TF_GLM_EXPERT_FORM)"; fn report(k: Kept, how: []const u8, block: bool, pinned: bool) void { - const form = if (k.fact != 0) "factored" else "classic"; + var buf: [64]u8 = undefined; + const form = words(k.fact, &buf); if (block) { std.log.info(form_line, .{ how, form, named(pinned) }); return; @@ -130,6 +131,25 @@ fn named(pinned: bool) []const u8 { return if (pinned) " (TF_GLM_EXPERT_FORM)" else ""; } +/// One word when every width shares a form, else the more common form and the widths where the other runs. +fn words(fact: u64, buf: []u8) []const u8 { + if (fact == 0) return "classic"; + if (fact == measurements.all) return "factored"; + const most = @as(usize, @popCount(fact)) * 2 > widths.len; + const other = if (most) measurements.all & ~fact else fact; + const head = std.fmt.bufPrint(buf, "{s}, {s} at", .{ if (most) "factored" else "classic", if (most) "classic" else "factored" }) catch return "by width"; + var len = head.len; + var left: usize = @popCount(other); + for (widths, 0..) |w, i| { + if ((other >> @intCast(i)) & 1 == 0) continue; + left -= 1; + const sep: []const u8 = if (len == head.len) " " else if (left == 0) " and " else ", "; + len += (std.fmt.bufPrint(buf[len..], "{s}{d}", .{ sep, w }) catch return "by width").len; + } + len += (std.fmt.bufPrint(buf[len..], " {s}", .{if (other == 1) "row" else "rows"}) catch return "by width").len; + return buf[0..len]; +} + /// Cache identity: the GPU and driver, this checkpoint and drafter, the settings a window's time follows, a named form. pub fn keyParts(e: *const engine.Engine, ctx: *const cuda.Context, name: []u8, shape: []u8, pin: ?bool) !?[3][]const u8 { const at = cacheShape(e, try ctx.capability(), try ctx.d.version(), shape, pin) orelse return null; @@ -179,8 +199,8 @@ const Scratch = struct { held: [@max(max_held, engine.max_drafts)]u32 = undefined, chances: [@max(max_held, engine.max_drafts)]f64 = undefined, - pub fn form(s: *Scratch, fact: bool) !void { - try s.x.expertForm(fact); + pub fn form(s: *Scratch, fact: u64) !void { + try s.x.expertForm(measurements.rows(fact)); } pub fn window(s: *Scratch, i: usize) !f64 { @@ -303,11 +323,11 @@ test "GLM cost identity: a named form's startup line ends at (TF_GLM_EXPERT_FORM test "GLM cost identity: a load that times nothing sends a named form to every rank once, and nothing unnamed" { const Leader = struct { - form: ?bool = null, + form: ?u64 = null, sent: usize = 0, idles: usize = 0, - pub fn expertForm(l: *@This(), fact: bool) !void { - l.form = fact; + pub fn expertForm(l: *@This(), forms: u64) !void { + l.form = forms; l.sent += 1; } pub fn idle(l: *@This()) !void { @@ -317,7 +337,7 @@ test "GLM cost identity: a load that times nothing sends a named form to every r for ([_]?bool{ null, false, true }) |pin| { var l: Leader = .{}; try std.testing.expect((try untimed(&l, pin)) == null); - try std.testing.expectEqual(pin, l.form); + try std.testing.expectEqual(if (pin) |f| @as(?u64, measurements.rows(measurements.every(f))) else null, l.form); try std.testing.expectEqual(@as(usize, @intFromBool(pin != null)), l.sent); try std.testing.expectEqual(l.sent, l.idles); } @@ -354,6 +374,22 @@ test "GLM cost identity: a record kept at one named form is not reused at the ot try std.testing.expect(reuses(classic, false, false) and reuses(classic, false, null)); try std.testing.expect(!reuses(classic, false, true)); var factored = classic; - factored.fact = 1; + factored.fact = measurements.every(true); try std.testing.expect(reuses(factored, false, true) and !reuses(factored, false, false)); + // a record raced by width stands for the race alone, not for either named form + var mixed = classic; + mixed.fact = 1; + try std.testing.expect(reuses(mixed, false, null) and !reuses(mixed, false, true) and !reuses(mixed, false, false)); +} + +test "GLM cost identity: a raced line names the more common form and the widths where the other runs" { + var buf: [64]u8 = undefined; + const all = measurements.all; + try std.testing.expectEqualStrings("classic", words(0, &buf)); + try std.testing.expectEqualStrings("factored", words(all, &buf)); + try std.testing.expectEqualStrings("factored, classic at 4 and 6 rows", words(all & ~@as(u64, 0b11000), &buf)); + try std.testing.expectEqualStrings("factored, classic at 32 rows", words(all >> 1, &buf)); + try std.testing.expectEqualStrings("classic, factored at 1 row", words(1, &buf)); + try std.testing.expectEqualStrings("classic, factored at 1, 2 and 32 rows", words(0b10_0000_0011, &buf)); + try std.testing.expectEqualStrings("classic, factored at 8, 12, 16, 24 and 32 rows", words(0b11_1110_0000, &buf)); } diff --git a/zig/src/families/glm/cuda_moe.zig b/zig/src/families/glm/cuda_moe.zig index edde69f93dc..b1ec2495952 100644 --- a/zig/src/families/glm/cuda_moe.zig +++ b/zig/src/families/glm/cuda_moe.zig @@ -64,7 +64,7 @@ pub fn body(k: Kernels, stream: cuda.Stream, l: Layer, s: Scratch, x: u64, x_str if (k.prof) |p| p.mark(stream, .router); defer if (k.prof) |p| p.mark(stream, .routed); if (l.exl3) |w| return exl3.run(k.exl3, k.experts, stream, w, s.x3, s.plan, x, x_stride, s.pick, slots, rows, l.count, d, l.routed.width, l.routed.limit, prompt, s.ey, s.eact); - const plan: experts.Plan = .{ .route = s.plan, .slots = slots, .experts = l.count + 1, .prompt = prompt, .fact = !prompt and k.experts.fact and l.routed.format == .nvfp4 }; + const plan: experts.Plan = .{ .route = s.plan, .slots = slots, .experts = l.count + 1, .prompt = prompt, .fact = !prompt and k.experts.factored(rows) and l.routed.format == .nvfp4 }; try experts.route(k.experts, stream, s.pick, rows * slots, plan); try experts.run(k.experts, stream, .gate_up, l.routed, plan, x, x_stride, rows, s.eact, shared_id); try experts.run(k.experts, stream, if (prompt) .down else .down_f32, l.routed, plan, s.eact, l.routed.width, rows, s.ey, shared_id); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 8809e92f90f..705c8bf60e9 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -117,7 +117,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_GLM_DRAFT_CONFIDENCE", .scope = .glm, .kind = .real, .max = 1, .forms = "a finite chain-chance cut from 0 to 1 (default 0.7)" }, // 2^31 - 32: GLM's slots, the window and its 32 verify rows (glm/cuda_native.zig's capacity), keep i32 positions .{ .name = "TF_GLM_CONTEXT_CEILING", .scope = .glm, .kind = .u64, .first_digit = true, .min = 1, .max = 2147483616, .forms = "a whole token count from 1 to 2147483616 (the window GLM-5.3-Flash may serve in place of config.json's)" }, - .{ .name = "TF_GLM_EXPERT_FORM", .scope = .glm, .kind = .word, .words = &.{ "classic", "factored" }, .forms = "classic or factored (unset races the two when a build first loads)" }, + .{ .name = "TF_GLM_EXPERT_FORM", .scope = .glm, .kind = .word, .words = &.{ "classic", "factored" }, .forms = "classic or factored at every width (unset races the two at each width when a build first loads)" }, .{ .name = "TF_DSV41_MHC_DEFER", .scope = .dsv41, .kind = .toggle, .trim = " \t", .no_word = false, .forms = "0, 1, true, false, on, off or yes (any case)" }, .{ .name = "TF_DSV41_COEF_LATE", .scope = .dsv41, .kind = .toggle, .trim = " \t", .no_word = false, .forms = "0, 1, true, false, on, off or yes (any case)" }, .{ .name = "TF_DSV41_LOOKUP", .scope = .dsv41, .kind = .toggle, .trim = " \t", .forms = "0, 1, true, false, on, off, yes or no (any case); blank turns lookup drafts off" }, diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 3eb1098fd7f..caef5606bee 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -137,6 +137,7 @@ pub const Prepared = struct { stops: fields_mod.Stops, preparing: bool, frames: []const ?api.Size = &.{}, // each image part's tower input size, in part order (prompt.Rendered.frames) + deadline_ns: ?i96 = null, // "deadline_s": the server ends the reply there itself (finish_reason "deadline") }; /// Render ``input`` and run every check that can refuse it, before anything reaches the client or the engine. @@ -225,8 +226,13 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa request.logprobs = input.logprobs; request.prompt_logprobs = input.prompt_logprobs; if (try engine_refusal.of(srv.engine, cx, &request)) |message| return cx.refuse(message); + const deadline: ?i96 = if (f.get("deadline_s")) |v| blk: { + const s = (if (v == .bool) null else v.float64()) orelse return cx.refuse("deadline_s must be a number of seconds"); + if (!(s > 0 and s <= 1e6)) return cx.refuse("deadline_s must be more than 0 and at most 1000000 seconds"); + break :blk received + @as(i96, @intFromFloat(s * std.time.ns_per_s)); + } else null; if (input.trace) |trace| trace.prepared(&request, thinking, effort); - return .{ .input = input, .request = request, .prompt_len = rendered.ids.len, .received = received, .thinking = thinking, .reasoning = reasoning, .effort = effort, .sampled = sampling != null, .drafts = drafts, .token_ids = fields_mod.flag(f, "return_token_ids") orelse false, .stops = stops_opt, .preparing = preparing, .frames = rendered.frames }; + return .{ .input = input, .request = request, .prompt_len = rendered.ids.len, .received = received, .thinking = thinking, .reasoning = reasoning, .effort = effort, .sampled = sampling != null, .drafts = drafts, .token_ids = fields_mod.flag(f, "return_token_ids") orelse false, .stops = stops_opt, .preparing = preparing, .frames = rendered.frames, .deadline_ns = deadline }; } /// Submit a prepared request and collect its reply; ``sink`` hears the stream (null: not streamed). @@ -269,7 +275,7 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an }; srv.release(preparing, null); // a background request waits only while a foreground one prepares preparing = false; - var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = fields_mod.flag(input.fields, "tool_call_single") orelse false, .recover = input.prompt == null and request.structure == null }; + var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = fields_mod.flag(input.fields, "tool_call_single") orelse false, .recover = input.prompt == null and request.structure == null, .deadline_ns = prepared.deadline_ns }; defer srv.noteRequest(prepared.prompt_len, cached_tokens.within(box.cached, prepared.prompt_len), gen.collected.items.len, box.stats.drafted, box.stats.accepted, box.stats.rounds, received, gen.first_ns, gen.last_ns, box.stats.prefill_seconds, if (box.stats.prefill_seconds != null) box.stats.queued_seconds else null); errdefer if (!gen.engine_done) gen.cancel(); // the engine writes to the mailbox until it says finished if (srv.recipients and input.prompt == null) gen.recipient = try recipient_reply.Reading.of(a, srv.text, request.prompt, input.tools, prepared.reasoning); diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index 0c5bbfb3c3d..198578fa736 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -74,6 +74,8 @@ pub const Generation = struct { lp: ?@import("logprob_parts.zig").Live = null, // the request asked for logprobs: its rows, copied with each round loop_stop: bool = false, // --loop-guard-stop: the engine ends the reply where the loop guard fires recover: bool = false, // a chat request with no forced tool or structure: an unclosed think block may be the answer + deadline_ns: ?i96 = null, // "deadline_s": when the server ends the reply itself + deadline_hit: bool = false, // it did: the engine was cancelled there; what it gave before its end still lands fn eos(g: *const Generation, t: u32) bool { return !g.ignore_eos and std.mem.indexOfScalar(u32, g.srv.eos, t) != null; @@ -263,6 +265,16 @@ pub const Generation = struct { g.srv.engine.cancel(g.id); g.cancel_sent = true; }; + // a client's cancel came first: the reply ends "cancelled", not at a deadline that passes afterwards + if (g.deadline_ns) |d| if (!g.deadline_hit and !g.cancel_sent and g.reason == null and nowNs(g.srv.io) >= d) { + m.mutex.lockUncancelable(m.io); + const ended_first = m.finished; // still draining a reply the engine already ended: it keeps that end + m.mutex.unlock(m.io); + if (ended_first) g.deadline_ns = null else { + g.deadline_hit = true; + g.srv.engine.cancel(g.id); // the engine ends the stream: its tokens and usage stay whole + } + }; if (chunk == null and @hasDecl(Gone, "beat")) { // queueing and a long prefill send nothing: a client that times out a silent stream would leave const now = nowNs(g.srv.io); @@ -282,13 +294,15 @@ pub const Generation = struct { const a = g.a; const m = g.box; if (!g.engine_done) g.drain(); - const ended: []const u8 = g.reason orelse switch (m.reason) { + const natural: []const u8 = g.reason orelse switch (m.reason) { .stop => "stop", .length => "length", .silence => return cx.other("the text engine returned a speech-only finish reason"), .cancelled => "cancelled", .failed => return cx.other(if (m.message.len > 0) try a.dupe(u8, m.message) else "the reply failed"), }; + // the server ended the reply at its deadline: a late token's EOS, stop string or cap never hides that + const ended = if (g.deadline_hit) "deadline" else natural; const stopped: ?u32 = if (g.loop_stop) m.stats.loop_period else null; const reason = if (stopped != null) @import("loop_stop.zig").finish_reason else ended; const finished_ns = nowNs(g.srv.io); diff --git a/zig/src/server/openai.zig b/zig/src/server/openai.zig index 3b23478828c..19658c629f9 100644 --- a/zig/src/server/openai.zig +++ b/zig/src/server/openai.zig @@ -129,7 +129,7 @@ pub fn plan(srv: *Server, cx: *Cx, is_chat: bool, raw: Value, format: ?[]const u input.temperature = if (t == .float) t.float else std.fmt.parseFloat(f64, t.int) catch 0; }; const sampling = try json.newObject(cx.a); - for ([_][]const u8{ "temperature", "top_p", "top_k", "min_p", "presence_penalty", "frequency_penalty", "seed", "priority", "model", "draft", "thinking_budget", "ignore_eos", "return_token_ids", "stop", "grammar_budget" } ++ grammar.fields) |k| if (body.get(k)) |v| try sampling.put(cx.a, k, v); + for ([_][]const u8{ "temperature", "top_p", "top_k", "min_p", "presence_penalty", "frequency_penalty", "seed", "priority", "model", "draft", "thinking_budget", "ignore_eos", "return_token_ids", "stop", "grammar_budget", "deadline_s" } ++ grammar.fields) |k| if (body.get(k)) |v| try sampling.put(cx.a, k, v); try grammar.refusal(cx, body); if (input.tools.len > 0 and try tool_specs.choiceRequiresCall(cx.a, body.get("tool_choice"))) try sampling.put(cx.a, "tool_call_required", .{ .bool = true }); if (body.field("parallel_tool_calls")) |p| if (p == .bool and !p.bool) try sampling.put(cx.a, "tool_call_single", .{ .bool = true }); diff --git a/zig/src/server/request_deadline_http_test.zig b/zig/src/server/request_deadline_http_test.zig new file mode 100644 index 00000000000..670968a0ffe --- /dev/null +++ b/zig/src/server/request_deadline_http_test.zig @@ -0,0 +1,253 @@ +//! "deadline_s" through the OpenAI HTTP handler: chat and completions, whole and streamed, no sockets or GPU. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const openai = @import("openai.zig"); +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const model_text = @import("model_text.zig"); +const Allocator = std.mem.Allocator; + +const eos_id: u32 = 'z'; + +/// One byte a token; `z` is EOS. +const Bytes = struct { + fn text(t: *Bytes) model_text.Text { + return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocab, .eos_ids = eos, .render = render, .template_source = template } }; + } + fn encode(_: *anyopaque, a: Allocator, input: []const u8, _: bool) model_text.Error![]u32 { + const ids = try a.alloc(u32, input.len); + for (input, ids) |byte, *id| id.* = byte; + return ids; + } + fn decode(_: *anyopaque, a: Allocator, ids: []const u32) Allocator.Error![]u8 { + const out = try a.alloc(u8, ids.len); + for (out, ids) |*v, id| v.* = @intCast(id); + return out; + } + fn tokenId(_: *anyopaque, _: []const u8) ?u32 { + return null; + } + fn tokenString(_: *anyopaque, a: Allocator, id: u32) ![]u8 { + return std.fmt.allocPrint(a, "{d}", .{id}); + } + fn vocab(_: *anyopaque) u32 { + return 256; + } + fn eos(_: *anyopaque) []const u32 { + return &.{eos_id}; + } + fn render(_: *anyopaque, a: Allocator, _: json.Value, _: model_text.RenderOptions, _: *[]const u8) model_text.Error!model_text.Rendered { + return .{ .text = try a.dupe(u8, "prompt") }; + } + fn template(_: *anyopaque) []const u8 { + return ""; + } +}; + +/// Gives `abc`; `hangs`: then waits for a cancel and gives `late` before its end, else ends by itself with `de` (stop). +const Script = struct { + hangs: bool, + late: []const u32 = &.{'d'}, + sink: ?api.Sink = null, + id: api.Id = 0, + mutex: std.Io.Mutex = .init, + done: std.atomic.Value(bool) = .init(false), + submitted: bool = false, + cancelled: bool = false, + linger_ms: u32 = 0, // after ending by itself, submit returns this late: the server first reads past the deadline + fn engine(s: *Script) api.Engine { + return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 8192 }; + } + fn submit(ctx: *anyopaque, id: api.Id, _: *const api.Request, sink: api.Sink) api.SubmitError!void { + const s: *Script = @ptrCast(@alignCast(ctx)); + s.sink = sink; + s.id = id; + s.submitted = true; + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + sink.event(sink.ctx, id, &.{ .tokens = &.{ 'a', 'b', 'c' } }); + if (!s.hangs) s.end(&.{ 'd', 'e' }, .stop); + if (s.linger_ms > 0) std.Io.sleep(std.testing.io, .fromMilliseconds(s.linger_ms), .awake) catch {}; + } + fn end(s: *Script, tokens: []const u32, reason: api.Reason) void { + s.mutex.lockUncancelable(std.testing.io); + defer s.mutex.unlock(std.testing.io); + if (s.done.load(.acquire)) return; + s.done.store(true, .release); + const sink = s.sink.?; + sink.event(sink.ctx, s.id, &.{ .tokens = tokens }); + sink.event(sink.ctx, s.id, &.{ .finished = .{ .reason = reason } }); + } + fn cancel(ctx: *anyopaque, _: api.Id) void { + const s: *Script = @ptrCast(@alignCast(ctx)); + if (!s.done.load(.acquire)) s.cancelled = true; + s.end(s.late, .cancelled); + } + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } + /// A hung reply the deadline never ended ends after 3 s with `XY` (stop), so a lost field fails instead of hanging. + fn watchdog(s: *Script) void { + var waited: u32 = 0; + while (!s.done.load(.acquire) and waited < 3000) : (waited += 10) std.Io.sleep(std.testing.io, .fromMilliseconds(10), .awake) catch {}; + if (s.sink != null) s.end(&.{ 'X', 'Y' }, .stop); + } +}; + +const Reply = struct { + a: Allocator, + slow: bool = false, // the first streamed event takes 100 ms to write + status: ?u16 = null, + whole: ?json.Value = null, + events: std.ArrayList(json.Value) = .empty, + fn out(r: *Reply) openai.Out { + return .{ .ctx = r, .vt = &.{ .open = open, .event = event, .reply = reply } }; + } + fn open(_: *anyopaque, _: usize) error{Closed}!void {} + fn event(ctx: *anyopaque, value: ?json.Value) error{Closed}!void { + const r: *Reply = @ptrCast(@alignCast(ctx)); + if (r.slow and r.events.items.len == 0) std.Io.sleep(std.testing.io, .fromMilliseconds(100), .awake) catch {}; + if (value) |v| r.events.append(r.a, v) catch return error.Closed; + } + fn reply(ctx: *anyopaque, status_code: u16, value: json.Value) void { + const r: *Reply = @ptrCast(@alignCast(ctx)); + r.status = status_code; + r.whole = value; + } +}; + +/// What a client reads: the finish, the text, usage, the tensorfold block and (streamed) each event's choices. +const Got = struct { status: u16, finish: []const u8 = "", text: []const u8 = "", tokens: i64 = 0, ids: []const u8 = "", tensorfold: ?json.Value = null, choices: []const []const u8 = &.{} }; + +const Case = struct { chat: bool, stream: bool }; +const cases = [_]Case{ .{ .chat = true, .stream = false }, .{ .chat = true, .stream = true }, .{ .chat = false, .stream = false }, .{ .chat = false, .stream = true } }; + +/// POSTs one body through openai.run; `extra`: more fields, each led by a comma. +fn post(a: Allocator, s: *Script, c: Case, max_tokens: u32, extra: []const u8) !Got { + var bytes: Bytes = .{}; + const srv = try Server.init(std.testing.allocator, std.testing.io, s.engine(), bytes.text(), .{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }, null); + defer srv.deinit(); + const input = if (c.chat) "\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}]" else "\"prompt\":\"hi\""; + const text = try std.fmt.allocPrint(a, "{{\"model\":\"m\",{s},\"max_tokens\":{d},\"stream\":{},\"return_token_ids\":true{s}}}", .{ input, max_tokens, c.stream, extra }); + const body = (try json.parse(a, text)).ok; + var conn = Conn{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; + var response = Reply{ .a = a, .slow = s.linger_ms > 0 }; + const dog = try std.Thread.spawn(.{}, Script.watchdog, .{s}); + openai.run(srv, a, response.out(), .{ .conn = &conn }, c.chat, body); + s.done.store(true, .release); + dog.join(); + if (response.status) |code| if (code != 200) return .{ .status = code }; + var got: Got = .{ .status = 200 }; + var content: std.ArrayList(u8) = .empty; + var choices: std.ArrayList([]const u8) = .empty; + var final: ?json.Value = response.whole; + for (response.events.items) |v| { + const cs = v.get("choices") orelse continue; + try choices.append(a, try json.stringify(a, cs, .{})); + if (cs.array.len == 0) continue; + const ch = cs.array[0]; + try content.appendSlice(a, json.strOr(if (c.chat) (ch.get("delta") orelse continue).get("content") else ch.get("text"))); + if (ch.get("finish_reason")) |r| if (r == .string) { + final = v; + }; + } + const value = final orelse return error.MissingFinalReply; + const ch = value.get("choices").?.array[0]; + got.finish = json.strOr(ch.get("finish_reason")); + got.text = if (c.stream) content.items else json.strOr(if (c.chat) ch.get("message").?.get("content") else ch.get("text")); + got.tokens = value.get("usage").?.get("completion_tokens").?.int64().?; + got.tensorfold = value.get("tensorfold"); + got.ids = try json.stringify(a, (got.tensorfold orelse return error.MissingTensorfold).get("token_ids") orelse return error.MissingTokenIds, .{}); + got.choices = choices.items; + return got; +} + +test "request deadline: HTTP deadline_s reaches the engine, finish deadline with the late token, usage and ids" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (cases) |c| { + var s: Script = .{ .hangs = true }; + const got = try post(a, &s, c, 100, ",\"deadline_s\":0.05"); + try std.testing.expect(s.cancelled); + try std.testing.expectEqualStrings("deadline", got.finish); + try std.testing.expectEqualStrings("abcd", got.text); + try std.testing.expectEqual(4, got.tokens); + try std.testing.expectEqualStrings("[97, 98, 99, 100]", got.ids); + } +} + +test "request deadline: HTTP without deadline_s, or with one the reply never meets, the reply and stream are the same" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (cases) |c| { + var s_off: Script = .{ .hangs = false }; + var s_late: Script = .{ .hangs = false }; + const off = try post(a, &s_off, c, 100, ""); + // the largest deadline_s (11.6 days): a paused test process never reaches it before the script ends by itself + const late = try post(a, &s_late, c, 100, ",\"deadline_s\":1000000"); + for ([_]Got{ off, late }, [_]*Script{ &s_off, &s_late }) |g, s| { + try std.testing.expect(!s.cancelled); + try std.testing.expectEqualStrings("stop", g.finish); + try std.testing.expectEqualStrings("abcde", g.text); + try std.testing.expectEqualStrings("[97, 98, 99, 100, 101]", g.ids); + } + try std.testing.expectEqualStrings(off.tensorfold.?.get("token_sha256").?.string, late.tensorfold.?.get("token_sha256").?.string); + try std.testing.expectEqual(off.choices.len, late.choices.len); + for (off.choices, late.choices) |x, y| try std.testing.expectEqualStrings(x, y); + } +} + +test "request deadline: HTTP refuses deadline_s that is not a positive number of seconds, before the engine" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (cases) |c| for ([_][]const u8{ "0", "-1", "\"300\"", "true", "1e7" }) |bad| { + var s: Script = .{ .hangs = false }; + const got = try post(a, &s, c, 100, try std.fmt.allocPrint(a, ",\"deadline_s\":{s}", .{bad})); + try std.testing.expectEqual(400, got.status); + try std.testing.expect(!s.submitted); + }; +} + +test "request deadline: HTTP a late EOS, stop string or token cap after the deadline still ends deadline, every token kept" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Collision = struct { late: []const u32, max: u32, extra: []const u8, text: []const u8, ids: []const u8 }; + const all = [_]Collision{ + .{ .late = &.{eos_id}, .max = 100, .extra = "", .text = "abc", .ids = "[97, 98, 99, 122]" }, + .{ .late = &.{'d'}, .max = 100, .extra = ",\"stop\":[\"d\"]", .text = "abc", .ids = "[97, 98, 99, 100]" }, + .{ .late = &.{ 'd', 'e' }, .max = 4, .extra = "", .text = "abcd", .ids = "[97, 98, 99, 100]" }, + }; + for (cases) |c| for (all) |x| { + var s: Script = .{ .hangs = true, .late = x.late }; + const got = try post(a, &s, c, x.max, try std.fmt.allocPrint(a, ",\"deadline_s\":0.05{s}", .{x.extra})); + try std.testing.expect(s.cancelled); + try std.testing.expectEqualStrings("deadline", got.finish); + try std.testing.expectEqualStrings(x.text, got.text); + try std.testing.expectEqual(4, got.tokens); + try std.testing.expectEqualStrings(x.ids, got.ids); + }; +} + +test "request deadline: HTTP a reply the engine ended before the deadline keeps finish stop when the server reads it late" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (cases) |c| { + var s: Script = .{ .hangs = false, .linger_ms = 100 }; + const got = try post(a, &s, c, 100, ",\"deadline_s\":0.05"); + try std.testing.expect(!s.cancelled); + try std.testing.expectEqualStrings("stop", got.finish); + try std.testing.expectEqualStrings("abcde", got.text); + try std.testing.expectEqualStrings("[97, 98, 99, 100, 101]", got.ids); + } +} diff --git a/zig/src/server/request_deadline_test.zig b/zig/src/server/request_deadline_test.zig new file mode 100644 index 00000000000..bc5153c7c1d --- /dev/null +++ b/zig/src/server/request_deadline_test.zig @@ -0,0 +1,198 @@ +//! "deadline_s": the server ends a reply at its deadline itself, with finish_reason "deadline", usage and ids. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const server = @import("server.zig"); +const chat = @import("chat.zig"); +const model_text = @import("model_text.zig"); +const Cx = @import("errors.zig").Cx; + +const gpa = std.testing.allocator; + +/// One byte a token. +const Bytes = struct { + fn text(t: *Bytes) model_text.Text { + return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocab, .eos_ids = eos, .render = render, .template_source = template } }; + } + fn encode(_: *anyopaque, a: std.mem.Allocator, input: []const u8, _: bool) model_text.Error![]u32 { + const ids = try a.alloc(u32, input.len); + for (input, ids) |byte, *id| id.* = byte; + return ids; + } + fn decode(_: *anyopaque, a: std.mem.Allocator, ids: []const u32) std.mem.Allocator.Error![]u8 { + const out = try a.alloc(u8, ids.len); + for (out, ids) |*v, id| v.* = @intCast(id); + return out; + } + fn tokenId(_: *anyopaque, _: []const u8) ?u32 { + return null; + } + fn tokenString(_: *anyopaque, a: std.mem.Allocator, id: u32) ![]u8 { + return std.fmt.allocPrint(a, "{d}", .{id}); + } + fn vocab(_: *anyopaque) u32 { + return 256; + } + fn eos(_: *anyopaque) []const u32 { + return &.{}; + } + fn render(_: *anyopaque, a: std.mem.Allocator, _: json.Value, _: model_text.RenderOptions, _: *[]const u8) model_text.Error!model_text.Rendered { + return .{ .text = try a.dupe(u8, "prompt") }; + } + fn template(_: *anyopaque) []const u8 { + return ""; + } +}; + +/// Gives `abc`; then ends by itself later (`de`, stop), or, cancelled, gives the `d` it had made. +const Script = struct { + sink: ?api.Sink = null, + id: api.Id = 0, + done: bool = false, + cancelled: bool = false, + cancels: usize = 0, // every cancel the server sent, before or after the end + lazy: bool = false, // a cancel is only noted; the stream ends at the 40th check, as a slow engine's would + quick: bool = false, // ends by itself (`de`, stop) inside submit, before any deadline + fn engine(s: *Script) api.Engine { + return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 8192 }; + } + fn submit(ctx: *anyopaque, id: api.Id, _: *const api.Request, sink: api.Sink) api.SubmitError!void { + const s: *Script = @ptrCast(@alignCast(ctx)); + s.* = .{ .sink = sink, .id = id, .lazy = s.lazy, .quick = s.quick }; + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + sink.event(sink.ctx, id, &.{ .tokens = &.{ 'a', 'b', 'c' } }); + if (s.quick) s.end(&.{ 'd', 'e' }, .stop); + } + fn end(s: *Script, tokens: []const u32, reason: api.Reason) void { + if (s.done) return; + s.done = true; + const sink = s.sink.?; + sink.event(sink.ctx, s.id, &.{ .tokens = tokens }); + sink.event(sink.ctx, s.id, &.{ .finished = .{ .reason = reason } }); + } + fn cancel(ctx: *anyopaque, _: api.Id) void { + const s: *Script = @ptrCast(@alignCast(ctx)); + s.cancels += 1; + if (!s.done) s.cancelled = true; + if (!s.lazy) s.end(&.{'d'}, .cancelled); + } + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +/// The client never leaves; the engine ends by itself at the 40th check (~2 s), a stuck reply fails at the 400th. +const Gone = struct { + s: *Script, + checks: *usize, + pub fn check(g: @This()) bool { + if (g.s.sink == null) return false; + g.checks.* += 1; + if (g.checks.* == 40) if (g.s.cancelled) g.s.end(&.{'d'}, .cancelled) else g.s.end(&.{ 'd', 'e' }, .stop); + return g.checks.* > 400; + } +}; + +const Deltas = struct { + a: std.mem.Allocator, + out: std.ArrayList([]const u8) = .empty, + slow: bool = false, // the first write takes 100 ms, as a slow client's would + fn call(ctx: *anyopaque, delta: json.Value) error{Closed}!void { + const d: *Deltas = @ptrCast(@alignCast(ctx)); + if (d.slow and d.out.items.len == 0) std.Io.sleep(std.testing.io, .fromMilliseconds(100), .awake) catch {}; + d.out.append(d.a, json.stringify(d.a, delta, .{}) catch return error.Closed) catch return error.Closed; + } +}; + +const Run = struct { reply: chat.Reply, deltas: []const []const u8, cancelled: bool, cancels: usize }; + +fn run(a: std.mem.Allocator, deadline: ?json.Value) !Run { + return runAsked(a, deadline, null, false); +} + +/// `asked`: the cancel route's ask (the engine then ends late on cancel); `slow`: ends in submit, first write 100 ms. +fn runAsked(a: std.mem.Allocator, deadline: ?json.Value, asked: ?*const std.atomic.Value(bool), slow: bool) !Run { + var script: Script = .{ .lazy = asked != null, .quick = slow }; + var bytes: Bytes = .{}; + const srv = try server.Server.init(gpa, std.testing.io, script.engine(), bytes.text(), .{ .served_name = "test", .model_ids = &.{"test"}, .enable_thinking = false }, null); + defer srv.deinit(); + const fields = try json.newObject(a); + try fields.put(a, "return_token_ids", .{ .bool = true }); + if (deadline) |d| try fields.put(a, "deadline_s", d); + var deltas: Deltas = .{ .a = a, .slow = slow }; + var checks: usize = 0; + var cx: Cx = .{ .a = a }; + const input: chat.Input = .{ .id = "chatcmpl-deadline", .prompt = .{ .text = "prompt" }, .max_tokens = 100, .fields = .{ .object = fields }, .cancel = asked }; + const reply = try chat.run(srv, &cx, input, .{ .ctx = &deltas, .call = Deltas.call }, Gone{ .s = &script, .checks = &checks }); + return .{ .reply = reply, .deltas = deltas.out.items, .cancelled = script.cancelled, .cancels = script.cancels }; +} + +fn tokenIds(a: std.mem.Allocator, reply: chat.Reply) ![]const u8 { + return json.stringify(a, reply.runtime.get("token_ids").?, .{}); +} + +test "request deadline: the server ends the reply at deadline_s with finish deadline, every token and its ids" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const got = try run(a, .{ .float = 0.05 }); + try std.testing.expect(got.cancelled); + try std.testing.expectEqualStrings("deadline", got.reply.finish_reason); + try std.testing.expectEqualStrings("abcd", got.reply.content); // the token the engine made before its end lands + try std.testing.expectEqual(4, got.reply.completion_tokens); + try std.testing.expectEqualStrings("[97, 98, 99, 100]", try tokenIds(a, got.reply)); +} + +test "request deadline: without deadline_s, or with one the reply ends before, the reply and stream are the same" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const off = try run(a, null); + // the largest deadline_s (11.6 days): a paused test process never reaches it before the script ends by itself + const late = try run(a, .{ .int = "1000000" }); + for ([_]Run{ off, late }) |r| { + try std.testing.expect(!r.cancelled); + try std.testing.expectEqualStrings("stop", r.reply.finish_reason); + try std.testing.expectEqualStrings("abcde", r.reply.content); + try std.testing.expectEqualStrings("[97, 98, 99, 100, 101]", try tokenIds(a, r.reply)); + } + try std.testing.expectEqualStrings(off.reply.runtime.get("token_sha256").?.string, late.reply.runtime.get("token_sha256").?.string); + try std.testing.expectEqual(off.deltas.len, late.deltas.len); + for (off.deltas, late.deltas) |x, y| try std.testing.expectEqualStrings(x, y); +} + +test "request deadline: deadline_s that is not a positive number of seconds is refused" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + for ([_]json.Value{ .{ .int = "0" }, .{ .float = -1 }, .{ .string = "300" }, .{ .bool = true } }) |bad| + try std.testing.expectError(error.Refused, run(a, bad)); +} + +test "request deadline: a client's cancel that came first keeps finish cancelled when the deadline passes later" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const asked: std.atomic.Value(bool) = .init(true); + const got = try runAsked(a, .{ .float = 0.05 }, &asked, false); + try std.testing.expect(got.cancelled); + try std.testing.expectEqualStrings("cancelled", got.reply.finish_reason); + try std.testing.expectEqualStrings("abcd", got.reply.content); +} + +test "request deadline: a slow writer draining a reply the engine already ended keeps finish stop and sends no cancel" { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const got = try runAsked(a, .{ .float = 0.05 }, null, true); + try std.testing.expectEqualStrings("stop", got.reply.finish_reason); + try std.testing.expectEqual(0, got.cancels); + try std.testing.expectEqualStrings("abcde", got.reply.content); + try std.testing.expectEqualStrings("[97, 98, 99, 100, 101]", try tokenIds(a, got.reply)); +} diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 0f5b6dd08ca..b18825b700f 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -41,6 +41,8 @@ test { _ = @import("done_times_test.zig"); _ = @import("drain_test.zig"); _ = @import("keepalive_test.zig"); + _ = @import("request_deadline_test.zig"); + _ = @import("request_deadline_http_test.zig"); _ = @import("idle_unload.zig"); _ = @import("idle_unload_test.zig"); _ = @import("wait_reason_test.zig");