diff --git a/CHANGELOG.md b/CHANGELOG.md index 73db1d63321..f87ef2a911b 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: the tokenizer's memo keeps segments of 64 bytes or more, not 1,024, so a chat's short earlier messages and tool calls are tokenized once instead of on each of a request's renders, with the same ids. On real agent conversations (Qwen3.8-27B tokenizer, up to 60K tokens) a warm encode of the longest takes about 150 µs instead of 690 µs, and a one-off prompt is no slower (#2509). Thanks to @mrv777. + +- Persisted prompt states (the prompt cache's disk tier and `--learn-conversations`): every family that saves states to disk now keys them by what its loaded run actually computed with, not only the flags as set: resolved arithmetic and kernel choices, every indexed weight shard (subfolders included), and external loaded inputs such as the CUDA Qwen rotary table, a Flash Next pack outside its folder, Flash Next on CUDA's chunk heights and kernel forms, and Nemotron's precision, expert ranks, ModelOpt lane and captured attention variant. A state computed differently now misses instead of resuming, and a resumed state still equals a fresh one. Upgrading starts every kept state once cold, and so does changing a GLM or Qwen Metal prompt chunk height. `GLM_EHPROJ_NAX` now takes only `0` or `1`; other text, which used to read as on, is refused at start (#2287, part of #2131). + +- Conformance: the cancel and evict gates check that a cut reply and an evicted prompt leave the server as a fresh one, with a planted fault for each; the Qwen3.8-27B Metal profile skips evict with its measured reason, and the CUDA profiles run both (#2611). Thanks to @jschmied. + - HIP: the qwen3_5 engine builds the DFlash2 drafter's kernels (tap gathers, key ring, dynamic conv, block attention), tested and in the kernel contract; nothing launches them yet (#2545, part 3 of #1563). Thanks to @AbrahamCete. - CUDA: Qwen3.8-27B can draft with Tencent's DSpine-b16 when `--drafter` names its folder (never the default). Its code bridge and exact-sender table run on affine-4 projections, and the draft tree walker moves into `core/lanes` so every backend shares it. Replies are unchanged: every drafted reply equals the same request with drafts off. On a GB10, agent-shaped requests decoded 3-20% faster than with DFlash2, and chat and code 9-19% slower, which is why it is opt-in (#2633, refs #2592). Thanks to @jschmied. @@ -307,6 +313,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel is refused by name; `TF_LANE_TRACE` gains a `cancel` line for a request cancelled between two prompt calls (#2458, part of #2324). Thanks to @laudney. +- Docs: a reply that quotes a template marker can finish with `ignore_eos` and a stop list for the model's end-of-text and next-turn-open spellings, then a strip of the trailing turn marker; measured on two Qwen checkpoints on a GB10, with the agent-shaped runs reported in #2399 (#2437, refs #2399). Thanks to @javierbits and @robertung88. + ## 1.2.4 - Docs: four subcommand-flag fixes checked against the code: `slide audit --threshold`'s range, `benchmark --context` and `--kv-cache`, `info` on Flash Next, and `run --device` and `--carveout` on CUDA builds (#2348). diff --git a/docs/api.md b/docs/api.md index 211d8e57281..10c9691f2ee 100644 --- a/docs/api.md +++ b/docs/api.md @@ -341,6 +341,32 @@ token or the reply limit; the server returns the reply only up to the match. Whe `ignore_eos`, end tokens inside the reply are decoded into its text, as on MLX, and `finish_reason` is `length` unless a stop string or a tool call ended the reply. +### Replies that quote a template marker + +Some templates encode their turn-end spelling as one added token: Qwen3.8-Flash-Next's tokenizer encodes +`<|im_end|>` to one id, while `<|tool_call_begin|>` stays seven ordinary tokens, as `POST /tokenize` with +`{"prompt": "", "add_special_tokens": false}` shows ([#2399]). A reply can quote that spelling with +ordinary tokens and finish normally; when it draws the one-token spelling instead, the turn ends there even inside +a code span. The server stops on the token the model drew; it does not sample past the end token and decide +afterwards, because that would change the reply. + +A plain request already finishes on the checkpoints measured so far: they spell a quoted marker with ordinary +tokens, and the server stops on the end token when the model draws it. A client that still uses `ignore_eos` +should stop on `["<|endoftext|>", "<|im_start|>"]` and not on `<|im_end|>` or end-of-text alone. With +`ignore_eos`, the end token no longer stops the reply, and behind an agent prompt the model often opens the next +turn instead of writing end-of-text, so a stop on end-of-text alone never fires; the invented turns run on, and a +tool parser returns their tool calls ([#2399]). Strip a trailing `<|im_end|>` and the whitespace after it before +display. The cost is the same for both stops: a stop string matches the spelling however it is tokenized, so a +reply that quotes `<|endoftext|>`, `<|im_start|>` or `<|im_end|>` as text is cut there. A `stop` for `<|im_end|>` +cuts at least where the end token would, and also where the reply spells it with ordinary tokens. + +Measured greedy on a GB10 with a finished tool call and its result in the conversation, on Qwen3.5-2B MLX +4-bit and Qwen3.6-35B-A3B NVFP4: both checkpoints wrote the quoted marker with ordinary tokens, so the plain request +finished; with `ignore_eos` and `stop: ["<|endoftext|>", "<|im_start|>"]` all replies stopped right after their +first end, and each ended with the drawn `<|im_end|>` for the client to strip. On an agent-shaped body, the runs +reported in #2399 gave 0/9 runaways with the pair, against 7/9 with end-of-text alone, on stock Qwen3.8-Flash-Next +weights. + On MLX, `--parallel auto` is the default: requests share rounds within the configured concurrency and memory budget. Every admitted prompt prefills a chunk at a time beside the others. Each chunk goes to a foreground prompt before a background one, then to the prompt with the fewest tokens left, and a prompt passed over for 8 chunks takes diff --git a/docs/environment.md b/docs/environment.md index 5697b9e04be..5579c5f4c6a 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -42,6 +42,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_GLM_DRAFT_CONFIDENCE` | Finite number 0 through 1 where a DFlash2 chain's chance product stops it; default 0.7 | | `TF_PROMPT_ROWS` | Native serving: a multiple of 16 from 128 through 2048; unset keeps the chip/family default | | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | +| `GLM_EHPROJ_NAX` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `0` serves the MTP head's prompt eh_proj on the scalar kernel; default 1, the tile kernel where it builds | | `XPU_A8_BITS` | Exactly `4` or `8`, for the XPU quantization study; unset keeps the study's existing setting | | `LFM3_FUSE` | Whole u32 fusion mask; default 7 | | `TF_SLIDE_POCKET_KEY` | Exactly `auto`, `reply`, `subject` or `both`; default `auto` | diff --git a/docs/recipes/persisted-serving-keys.md b/docs/recipes/persisted-serving-keys.md index caccd2f0725..8227679621a 100644 --- a/docs/recipes/persisted-serving-keys.md +++ b/docs/recipes/persisted-serving-keys.md @@ -7,13 +7,13 @@ Old files remain in their original namespace and follow the existing cache budge | Persistence owner | Source and arithmetic | Checkpoint | KV and draft state | Weight learning | | --- | --- | --- | --- | --- | -| Nemotron, Metal | Binary, kernel texts, precision mode, probe, OS build and GPU | Config, index, shard stamps and MTP header | Canonical snapshot, head flag and probe | Shared host clears RAM and detaches disk stores when weights move | -| Dense Qwen hybrid, Metal | Binary, shared/family shader texts, tensor/ANE modes, probe, OS build and GPU | Config, index and shard stamps for target and external drafter | Canonical recurrence/KV/tap image and draft end | Unsupported learners refuse; the store remains scoped to its loaded model | -| GLM, Metal | Binary, compiled source hash, rank/chunk modes, probe, OS build and GPU | Config/index identity plus current shard stamps | Canonical KDA/MLA image and checked snapshot header | Unsupported learner on this adapter | -| Flash Next, Metal | Binary, actual loaded shader texts/bindings, rotary/precision policy, probe, OS build and GPU | Pack metadata identity plus current shard stamps | Checked snapshot layout; canonical session image | Unsupported learner on this adapter | -| Nemotron, CUDA | Binary, embedded images, captured manifest and cubin bytes, probe, GPU and driver | Config, index and shard stamps | Head flag and canonical state image | Shared host clears RAM and detaches disk stores when weights move | -| Qwen dense/MoE hybrids, CUDA | Same shared CUDA identity | Same shared checkpoint identity | Explicit BF16/FP8 format, tap flag and prompt-int8 mode; image states stay off disk | Same shared learning barrier | -| Flash Next, CUDA | Same shared CUDA identity | Same shared checkpoint identity | Head flag and canonical recurrence/KV/PLE image; tensor-rank disk persistence is refused | Same shared learning barrier | +| Nemotron, Metal | Binary, kernel texts, precision mode, prompt step, loaded coop K-slice split and its scratch rows, probe, OS build and GPU | Config, index, shard stamps and MTP header | Canonical snapshot, head flag and probe | Shared host clears RAM and detaches disk stores when weights move | +| Dense Qwen hybrid, Metal | Binary, shared/family shader texts, tensor mode, loaded ANE columns and prompt policy, probe, OS build and GPU | Config, index and shard stamps for target and external drafter | Canonical recurrence/KV/tap image and draft end | Unsupported learners refuse; the store remains scoped to its loaded model | +| GLM, Metal | Binary, compiled source hash, resolved rank/route/prompt policy, probe, OS build and GPU | Config/index identity plus current shard stamps | Canonical KDA/MLA image and checked snapshot header | Unsupported learner on this adapter | +| Flash Next, Metal | Binary, actual loaded shader texts/bindings, rotary/precision and resolved execution policy, probe, OS build and GPU | Pack metadata identity, current source and loaded-pack stamps, loaded reference bytes | Checked snapshot layout; canonical session image | Unsupported learner on this adapter | +| Nemotron, CUDA | Binary, embedded images, captured manifest and cubin bytes, resolved checkpoint math, expert ranks, NVFP4 decode form, lane half-tile threshold, expert grids and captured attention variant, probe, GPU and driver | Config, index and shard stamps | Head flag and canonical state image | Shared host clears RAM and detaches disk stores when weights move | +| Qwen dense/MoE hybrids, CUDA | Same shared CUDA identity | Same shared checkpoint identity | Explicit BF16/FP8 format, tap flag, prompt-int8 mode and actual rotary table; image states stay off disk | Same shared learning barrier | +| Flash Next, CUDA | Same shared CUDA identity, plus resolved prompt chunk heights, prompt kernel forms and tile thresholds, expert grids and captured-set use | Same shared checkpoint identity | Head flag and canonical recurrence/KV/PLE image; tensor-rank disk persistence is refused | Same shared learning barrier | | DeepSeek sessions, CUDA reference path | Config/options/mode, checkpoint digest, rank, selected layers and piece layout | Checkpoint digest required | Versioned lossless session pieces and exact token prefix | No learner; the disk tier starts fresh for each process | Other native family adapters have no attached cross-process serving-state tier. Their snapshots remain owned by one @@ -28,11 +28,40 @@ boundaries, while the shared cache compares decoded spans and image identities. rendered answer text. No separate hot-swappable LoRA state is admitted by these persistence adapters; checkpoint changes and supported external drafters use the identities above. -GLM and Flash Next now include safetensors shard names, sizes, inode and modification/change stamps. A weight +Checkpoint keys include every validated indexed shard path, including subfolders and any suffix accepted by the loader, plus +auxiliary top-level safetensors files. Their names, sizes, inodes and modification/change stamps are bound. A weight write with unchanged config, index, tensor header and size moves their namespace even when a fixed probe does not visit the changed tensor. Flash Next also hashes the loaded variant text and input/output/meta bindings in sorted function-name order. Captured CUDA sets hash each cubin named by the parsed manifest, through the same loader -paths and size limit. A missing or changed file fails identity construction instead of opening an old namespace. +paths and size limit. A missing or changed file fails identity construction instead of opening an old namespace; +a shard the index names but the folder lacks is refused as `IndexedShardMissing`, as the loaders refuse it. + +Resolved policies are bound even when a fixed startup probe does not exercise their difference. The Metal Qwen +key includes loaded ANE columns and the prompt chunk height, not the frame's buffer rows. GLM includes effective +rank slices, routing, its prompt chunk height and sparse kernel, and whether the MTP head's prompt eh_proj runs on +the tile kernel as the load built it (`GLM_EHPROJ_NAX=0` or a failed tile build: scalar). A different chunk height +starts these two stores cold: GLM's prompt windows and chunks sum in different orders (#743), and Qwen's may too. +Flash Next includes its resolved execution branches, including the DeltaNet window kernels, but not the serial +encoder choice, which orders the same launches. It also binds stamps of the files actually indexed (including an +external weight pack) and the bytes of loaded metadata such as a supplied reference. Descriptor and mapping order +do not change that key. CUDA Qwen keys include the rotary table the target consumes, for dense and routed +checkpoints. These additions change the optional disk namespace; snapshot payloads and layouts are unchanged. + +Flash Next on CUDA keys what its prompt passes resolved at load: the solo and busy chunk heights (a different +`TF_FLASHNEXT_CHUNK` or `_CHUNK_SOLO`, or `--parallel 1` taking the larger pass, starts cold), the DeltaNet, read-out, +hyper-connection and in-pass mark forms, the NVFP4 prompt-tile threshold, K32 tile, BF16 prompt tiles and the SM count +they are weighed against, the lane's half-tile threshold (`TF_QMMF_HALF_BELOW`), the experts' decode warps and resident +grids, and whether a captured set runs with which entries on our glue. `TF_FLASHNEXT_KV_PAGES` and `_KV_PAGES_ALL` are +keyed through the profile rows. Its draft, window, round, graph, lane-parts (`TF_FLASHNEXT_LANE_PARTS`), load-thread, I/O and dense-split settings and +`TF_FLASHNEXT_KV_PAGE_TEST` are not keyed: kept states come only from prompt passes, which those settings either never +reach, reach with the same launches or the same kernels addressing pages, or refuse for disk at `--tp 2`. +Nemotron on CUDA keys `--precision checkpoint`'s math, the expert ranks of `TF_NEMOTRON_WORLD`, a ModelOpt +checkpoint's NVFP4 decode warps and lane half-tile threshold, the experts' resident grids and, with a captured set, the +attention variant `--context` picks by its chunk count. Its pages, poison fill, carveout, segments, graph log and trace, +and the context on our own glue, are not keyed: they place memory, fill pages before use, log, run only passes that +keep no state (segments), or set a stride our merge ignores. Nemotron on Metal also keys `TF_COOP_SPLIT` as loaded and, +with the split on, the scratch rows a prompt chunk's partials must fit; its page plan and stream count otherwise only +size buffers. The executable and kernel fingerprints use a 32 KiB read buffer and check file stamps across the read. Checkpoints, executables and kernel assets must remain stable while a model opens and serves. The existing learner owns runtime @@ -43,6 +72,7 @@ Host checks: ```sh zig build test-persistence-identity-host test-cuda-persistence-source-host compile-persistence-host -j1 zig build test-checkpoint-identity test-cuda-disk-open-host test-sessions test-frame-cache-identity-host -j1 +zig build test-disk-identity-host -j1 ``` The first command's Metal consumer compile and checkpoint fixtures require a macOS host but execute no GPU call. diff --git a/tools/conformance.py b/tools/conformance.py index 409aaf73202..d49f94e10cd 100644 --- a/tools/conformance.py +++ b/tools/conformance.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Served exactness gates for one family profile: drafted, repeat, concurrent, resumed and refusals. +"""Served exactness gates for one family profile: drafted, repeat, concurrent, resumed, refusals, cancel and evict. Each gate prints one PASS or FAIL line with its counts; any FAIL exits 1. Equality is the reply's full token-id hash (``tensorfold.token_sha256``), so a reply without one is unverified and fails its gate. @@ -16,15 +16,18 @@ resume their own last chat without the prompt cache (``TF_QWEN27_SLOT_RESUME=0`` on Metal); with ``--fresh-url``, start that server with it yourself. - refusals: each named request the profile lists is refused with its status and error text. +- cancel, evict: a reply cut mid-stream and a prompt pushed out of the cache leave the server as a fresh one + (``conformance_lifecycle.py``). A profile's ``skip`` names either one its family lacks, with the reason; it prints + SKIP, and ``--plant`` refuses it. ``--binary`` starts the servers itself (the cache-off one first, then the cached one), one at a time, from the profile's flags; ``--url`` and ``--fresh-url`` run against servers you started. ``--plant GATE`` plants a fault that must turn that gate red (the arm under test gets another seed, the cached server keeps no prompts, or a refusal is -sent without its refused field). ``--stream`` asks for every exactness reply as a stream and reads it through the -benchmark clients' reader (``bench_stream``), with the same hash, counts and text; a stream that errs or ends before -``[DONE]`` is unverified. Refusals stay plain JSON requests: the server answers a streamed context-window refusal -with an error event after a 200 head, not with the status the profile lists. Standard library only, like its sibling -``bench_stream``. +sent without its refused field; cancel and evict: see ``conformance_lifecycle.py``). ``--stream`` asks for every +exactness reply as a stream and reads it through the benchmark clients' reader (``bench_stream``), with the same +hash, counts and text; a stream that errs or ends before ``[DONE]`` is unverified. Refusals stay plain JSON requests: +the server answers a streamed context-window refusal with an error event after a 200 head, not with the status the +profile lists. Standard library only, like its sibling ``bench_stream``. python3 tools/conformance.py tools/conformance_profiles/qwen35-cuda.json --binary BIN --model-dir DIR \\ --drafter DRAFTER --output receipt.json @@ -47,7 +50,16 @@ import bench_stream -GATES = ("drafted", "repeat", "concurrent", "resumed", "refusals") +GATES = ("drafted", "repeat", "concurrent", "resumed", "refusals", "cancel", "evict") +SKIPPABLE = ("cancel", "evict") # a family may lack these; the exactness gates hold for every family +NEEDS = {"cancel": "prompt", "evict": "fill_prompts"} # the key each lifecycle block cannot run without + + +def lifecycle_gaps(profile: dict) -> list[str]: + """Names each lifecycle gate the profile neither runs (its block with its key set) nor skips with a reason.""" + skip = profile.get("skip") or {} + return [g for g in SKIPPABLE if not (isinstance(skip, dict) and skip.get(g)) + and not (isinstance(profile.get(g), dict) and profile[g].get(NEEDS[g]))] SHA256 = re.compile(r"[0-9a-f]{64}") @@ -162,7 +174,8 @@ def refusals_gate(results) -> dict: def print_gate(gate: dict) -> None: - print(("PASS " if gate["passed"] else "FAIL ") + gate["gate"] + ": " + gate["line"], flush=True) + word = "SKIP " if gate.get("skipped") else "PASS " if gate["passed"] else "FAIL " + print(word + gate["gate"] + ": " + gate["line"], flush=True) class Client: @@ -191,6 +204,16 @@ def post(self, body: dict, stream: bool | None = None) -> dict: except Exception as exc: # noqa: BLE001 - a failed request is evidence, not a crash return {"status": 0, "error": f"{type(exc).__name__}: {exc}"} + def get(self, path: str): + """A GET's status and raw body; status 0 when the server did not answer.""" + try: + with urllib.request.urlopen(self.base + path, timeout=30) as reply: + return reply.status, reply.read() + except urllib.error.HTTPError as exc: + return exc.code, exc.read(1 << 16) + except Exception: # noqa: BLE001 - an unanswered probe is evidence, not a crash + return 0, b"" + class Plan: """A profile's requests: prompts, sampling modes, seeds and the planted fault.""" @@ -312,13 +335,29 @@ def refusals(self) -> dict: return refusals_gate(results) +def turn_text(plan: Plan, turn: int) -> str: + """The chat's user text at ``turn``; the first carries the profile's long document, if it names one.""" + text = plan.profile["conversation"][turn] + if turn == 0 and plan.profile.get("conversation_context_items"): + text = inventory(plan.profile["conversation_context_items"]) + "\n\n" + text + return text + + +def last_turn(plan: Plan, rows) -> list: + """The chat's last request, its history carrying the replies in ``rows``.""" + history = [] + for turn in range(len(plan.profile["conversation"])): + history.append({"role": "user", "content": turn_text(plan, turn)}) + if turn < len(plan.profile["conversation"]) - 1: + history.append({"role": "assistant", "content": rows[turn].get("text", "")}) + return history + + def conversation(client: Client, plan: Plan, mode: str, draft: bool) -> list: """One multi-turn chat; each turn's history carries this server's own earlier replies.""" history, rows = [], [] - for turn, text in enumerate(plan.profile["conversation"]): - if turn == 0 and plan.profile.get("conversation_context_items"): - text = inventory(plan.profile["conversation_context_items"]) + "\n\n" + text - history.append({"role": "user", "content": text}) + for turn in range(len(plan.profile["conversation"])): + history.append({"role": "user", "content": turn_text(plan, turn)}) row = client.post(plan.body(list(history), mode, draft, ignore_eos=False)) row["turn"] = turn rows.append(row) @@ -394,10 +433,15 @@ def __exit__(self, *_): def run_gates(runner: Runner, gates, fresh) -> list: - """The selected gates in order; resumed runs last so the others see no conversation in the cache.""" - out = [] + """The selected gates in order; resumed follows the gates that want no conversation in the cache.""" + import conformance_lifecycle as lifecycle + out, skip = [], runner.plan.profile.get("skip") or {} for name in gates: - if name == "resumed": + if name in skip: + gate = {"gate": name, "passed": True, "skipped": True, "counts": {}, "line": str(skip[name])} + elif name in ("cancel", "evict"): + gate = getattr(lifecycle, name)(runner, fresh) + elif name == "resumed": if fresh is None: gate = {"gate": "resumed == fresh", "passed": False, "counts": {}, "line": "no cache-off server (pass --fresh-url or --binary)"} @@ -434,6 +478,13 @@ def parse(argv=None): p.error("--binary needs --model-dir") if args.plant and args.plant not in args.gates: p.error(f"--plant {args.plant} needs that gate in --gates") + skip = json.loads(args.profile.read_text()).get("skip") or {} + if not isinstance(skip, dict) or not all(isinstance(why, str) and why.strip() for why in skip.values()): + p.error(f"the profile's skip must map each skipped gate to its reason, a non-empty string: {skip!r}") + if bad := sorted(set(skip) - set(SKIPPABLE)): + p.error(f"the profile skips {bad}: only {' and '.join(SKIPPABLE)} can be skipped") + if args.plant in skip: + p.error(f"--plant {args.plant}: the profile skips that gate ({skip[args.plant]}), so nothing would turn red") return args @@ -446,7 +497,7 @@ def main(argv=None) -> int: if args.binary: receipt["binary_sha256"] = hashlib.sha256(args.binary.read_bytes()).hexdigest() logs = Path(tempfile.mkdtemp(prefix="conformance-")) - if "resumed" in args.gates: + if {"resumed", "evict"} & set(args.gates): with Server(args, profile, 0, logs) as server: receipt["servers"].append({"cmd": server.cmd, "log": server.log.name}) client = Client(server.base, profile["name"], stream=args.stream) @@ -457,7 +508,7 @@ def main(argv=None) -> int: runner = Runner(Client(server.base, profile["name"], stream=args.stream), plan) receipt["gates"] = run_gates(runner, args.gates, fresh) else: - if args.fresh_url and "resumed" in args.gates: + if args.fresh_url and {"resumed", "evict"} & set(args.gates): client = Client(args.fresh_url, profile["name"], stream=args.stream) fresh = {mode: conversation(client, plan, mode, False) for mode in plan.modes} url = args.fresh_url if args.plant == "resumed" and args.fresh_url else args.url @@ -465,7 +516,8 @@ def main(argv=None) -> int: receipt["gates"] = run_gates(runner, args.gates, fresh) receipt["rows"] = runner.rows failed = sum(not g["passed"] for g in receipt["gates"]) - print(f"{profile['name']}: {len(receipt['gates']) - failed} passed, {failed} failed" + skipped = sum(bool(g.get("skipped")) for g in receipt["gates"]) + print(f"{profile['name']}: {len(receipt['gates']) - failed - skipped} passed, {failed} failed, {skipped} skipped" + (f" (planted: {args.plant})" if args.plant else ""), flush=True) if args.output: args.output.write_text(json.dumps(receipt, indent=1) + "\n") diff --git a/tools/conformance_lifecycle.py b/tools/conformance_lifecycle.py new file mode 100644 index 00000000000..79ff9c035cb --- /dev/null +++ b/tools/conformance_lifecycle.py @@ -0,0 +1,238 @@ +"""The conformance kit's lifecycle gates: a cancelled reply and an evicted prompt leave the server as a fresh one. + +- cancel: a streamed reply is closed mid-way. The server must count the disconnect, stay healthy, settle back to the + census it showed before the cut (``GET /v1/load``: running, waiting, active chat requests, free lanes, and each + pool's promised and unheld tokens), and answer the same request again exactly as its solo reply. A reply that + ended before the cut, or a cut the server did not count, fails the gate as vacuous. +- evict: the chat's last turn (the cache-off server's history) is asked twice, so the second resumes from the kept + prompt; the profile's fill prompts then push it out of the prompt cache. Asked once more it must equal the cache-off + server's reply, resume fewer tokens than before, and leave the census as it was. Nothing cached before the fill + fails as vacuous; the same cached count after it fails as not evicted. + +Each gate first waits for the server to go idle (no request running, queued or open), up to the block's ``settle_s`` +or else the profile's (default 60 s): a server that prefills a chat's next turn in the background after each reply +needs longer. A server that does not go idle in time fails the gate; it is never compared against a busy census. The +census holds only the fields the server reports (a server without ``capacity.lanes_free`` is compared without it). + +Each gate reads its block from the profile (``cancel``, ``evict``); a family without the capability names the gate +under the profile's ``skip`` with a reason. ``--plant cancel`` asks the repeat after each cut with another seed; +``--plant evict`` sends no fill prompts, so nothing is evicted. +""" +import http.client +import json +import re +import socket +import time +import urllib.parse + +from conformance import equal_line, last_turn, tally + +DISCONNECTS = re.compile(r"^tensorfold:client_disconnections_total (\d+)$", re.M) + + +def census(client): + """The counts an idle server must return to, from ``GET /v1/load``; None when it serves none.""" + status, raw = client.get("/v1/load") + try: + doc = json.loads(raw) if status == 200 else None + except ValueError: + doc = None + if not isinstance(doc, dict) or "running" not in doc: + return None + active = doc.get("http_active") if isinstance(doc.get("http_active"), dict) else {} + out = {"running": doc.get("running"), "waiting": doc.get("waiting"), "active": active.get("chat_completions")} + capacity = doc.get("capacity") if isinstance(doc.get("capacity"), dict) else {} + if "lanes_free" in capacity: + out["lanes_free"] = capacity["lanes_free"] + pools = [p for p in capacity.get("pools") or [] if isinstance(p, dict)] + if pools: + out["pools"] = [{"promised": p.get("promised_tokens"), "unheld": unheld(p)} for p in pools] + return out + + +def unheld(pool: dict): + """A pool's tokens no request holds: available plus reclaimable.""" + return (pool.get("available_tokens") or 0) + (pool.get("reclaimable_tokens") or 0) + + +def quiet(seen) -> bool: + """No request running, queued or open.""" + return bool(seen) and not seen.get("running") and not seen.get("waiting") and not seen.get("active") + + +def idle(client, seconds: float): + """The census once the server is idle, or None when it is not idle within ``seconds``.""" + seen, held = settle(client, quiet, seconds) + return seen if held else None + + +def wait_s(plan, spec: dict) -> float: + """Seconds a gate waits for the server to settle: its block's, else the profile's, else 60.""" + return spec.get("settle_s", plan.profile.get("settle_s", 60)) + + +def settle(client, until, seconds: float): + """Polls the census until ``until(census)`` holds or the deadline passes; returns (census, held).""" + deadline = time.monotonic() + seconds + while True: + seen = census(client) + if seen is not None and until(seen): + return seen, True + if time.monotonic() >= deadline: + return seen, False + time.sleep(0.25) + + +def disconnects(client): + """The server's count of replies a client left, from ``GET /metrics``; None when it reports none.""" + status, raw = client.get("/metrics") + found = DISCONNECTS.search(raw.decode(errors="replace")) if status == 200 else None + return int(found.group(1)) if found else None + + +def healthy(client) -> bool: + status, raw = client.get("/health") + try: + return status == 200 and json.loads(raw).get("status") == "ok" + except (ValueError, AttributeError): + return False + + +def stream_cut(client, body: dict, after: int) -> dict: + """Streams the request, reads ``after`` chunks, then closes the connection; reports what it saw before the cut.""" + url = urllib.parse.urlsplit(client.base) + conn = http.client.HTTPConnection(url.hostname, url.port, timeout=client.timeout) + out = {"chunks": 0, "ended": False} + try: + conn.request("POST", "/v1/chat/completions", json.dumps({"model": client.model, **body, "stream": True}), + {"Content-Type": "application/json"}) + sock, reply = conn.sock, conn.getresponse() + if reply.status != 200: + out["error"] = f"HTTP {reply.status}" + return out + while out["chunks"] < after: + line = reply.readline() + if not line: + out["ended"] = True + break + data = line.decode(errors="replace").strip() + if not data.startswith("data:"): + continue + data = data[5:].strip() + if data == "[DONE]" or any(c.get("finish_reason") for c in json.loads(data).get("choices", [])): + out["ended"] = True + break + out["chunks"] += 1 + sock.shutdown(socket.SHUT_RDWR) + except (OSError, ValueError, http.client.HTTPException) as exc: + out["error"] = f"{type(exc).__name__}: {exc}" + finally: + conn.close() + return out + + +def cancel_gate(pairs, cuts, settled, health, counted, base) -> dict: + """cancel == solo: every repeat after a cut equals its solo reply, and every cut was clean and counted.""" + counts = tally(pairs) + clean = sum(c["chunks"] > 0 and not c["ended"] and not c.get("error") for c in cuts) + problems = [] + if base is None: + problems.append("no idle census from GET /v1/load (busy past settle_s)") + if clean < len(cuts): + problems.append(f"{len(cuts) - clean} cuts came after the reply ended or failed (vacuous)") + if counted != len(cuts): + problems.append(f"the server counted {counted} disconnects for {len(cuts)} cuts") + if sum(settled) < len(cuts): + problems.append(f"{len(cuts) - sum(settled)} censuses did not return to {base} (a lane or page held)") + if sum(health) < len(cuts): + problems.append(f"{len(cuts) - sum(health)} health checks not ok") + passed = bool(pairs) and counts["unequal"] == 0 and counts["unverified"] == 0 and not problems + line = (equal_line(counts) + f" after a cut; {clean}/{len(cuts)} cut mid-reply, {counted} disconnects counted, " + f"{sum(settled)}/{len(cuts)} censuses back to {base}, {sum(health)}/{len(cuts)} healthy") + if problems: + line += "; " + "; ".join(problems) + return {"gate": "cancel", "passed": passed, "counts": {**counts, "cuts": len(cuts), "clean": clean, + "counted": counted, "settled": sum(settled)}, "line": line} + + +def cancel(runner, _fresh=None) -> dict: + """Cuts the profile's prompt mid-reply, ``rounds`` times in each sampling mode, drafted.""" + spec, plan, client = runner.plan.profile.get("cancel") or {}, runner.plan, runner.client + if "prompt" not in spec: + return missing("cancel") + wait = wait_s(plan, spec) + bodies = {m: {**plan.ask(spec["prompt"], m, True), "max_tokens": spec.get("tokens", 256)} for m in plan.modes} + solos = {m: runner.record("cancel-solo", (m,), client.post(b)) for m, b in bodies.items()} + base = idle(client, wait) + before = disconnects(client) + pairs, cuts, settled, health = [], [], [], [] + for mode, body in bodies.items(): + for r in range(spec.get("rounds", 2)): + cuts.append(stream_cut(client, body, spec.get("after_chunks", 4))) + runner.rows.append({"kind": "cancel-cut", "key": [mode, r], **cuts[-1]}) + seen, held = settle(client, lambda s: base is not None and s == base, wait) + settled.append(held) + health.append(healthy(client)) + again = {**body, "seed": body["seed"] + 1} if plan.plant == "cancel" else body + pairs.append((solos[mode], runner.record("cancel-again", (mode, r), client.post(again)))) + after = disconnects(client) + counted = after - before if after is not None and before is not None else None + return cancel_gate(pairs, cuts, settled, health, counted, base) + + +def filler(k: int, items: int) -> str: + """A long prompt sharing no text with the chat, so keeping it pushes the chat out of the prompt cache.""" + parts = " ".join(f"part{(i + k) % 83}/{(i * 4093 + k) % 991}" for i in range(items)) + return f"Document {k}, a parts list: {parts}" + + +def evict_gate(fresh, warm, again, fills, held, base) -> dict: + """evict == fresh: kept and evicted replies equal the cache-off reply, the eviction shows, the census holds.""" + pairs = [(fresh, w) for w in warm] + [(fresh, again)] + counts = tally(pairs) + kept, now = warm[-1].get("cached"), again.get("cached") + failed = [i for i, f in enumerate(fills) if f.get("error")] + problems = [] + if not kept: + problems.append(f"the kept turn resumed {kept} tokens (vacuous: nothing cached to evict)") + elif now is None or now >= kept: + problems.append(f"still resumed {now} of {kept} after {len(fills)} fill prompts (nothing evicted)") + if failed: + problems.append(f"fill prompts {failed} failed") + if base is None: + problems.append("no idle census from GET /v1/load (busy past settle_s)") + elif not held: + problems.append(f"census did not return to {base} (a lane or page held)") + passed = counts["unequal"] == 0 and counts["unverified"] == 0 and not problems + line = (equal_line(counts) + f" against cache-off (kept, resumed, evicted); cached {kept} -> {now} after " + f"{len(fills)} fill prompts; census {'back to ' + str(base) if held else 'changed'}") + if problems: + line += "; " + "; ".join(problems) + return {"gate": "evict", "passed": passed, "counts": {**counts, "kept": kept, "evicted_to": now, + "fills": len(fills)}, "line": line} + + +def evict(runner, fresh) -> dict: + """Keeps the chat's last turn, fills the prompt cache past its budget, then asks the turn again.""" + spec, plan, client = runner.plan.profile.get("evict") or {}, runner.plan, runner.client + if "fill_prompts" not in spec: + return missing("evict") + if fresh is None: + return {"gate": "evict", "passed": False, "counts": {}, "line": "no cache-off server (pass --fresh-url or " + "--binary)"} + wait = wait_s(plan, spec) + base = idle(client, wait) + body = plan.body(last_turn(plan, fresh["greedy"]), "greedy", True, ignore_eos=False) + warm = [runner.record("evict-kept", (i,), client.post(body)) for i in range(2)] + fills = [] + for k in range(0 if plan.plant == "evict" else spec["fill_prompts"]): + fill = plan.body([{"role": "user", "content": filler(k, spec.get("fill_items", 900))}], "greedy", True) + fills.append(runner.record("evict-fill", (k,), client.post({**fill, "max_tokens": spec.get("fill_tokens", 1)}))) + again = runner.record("evict-again", (), client.post(body)) + _, held = settle(client, lambda s: base is not None and s == base, wait) + return evict_gate(fresh["greedy"][-1], warm, again, fills, held, base) + + +def missing(name: str) -> dict: + return {"gate": name, "passed": False, "counts": {}, + "line": f"the profile has no {name} block (add one, or name the gate under skip with a reason)"} diff --git a/tools/conformance_profiles/gemma4-cuda.json b/tools/conformance_profiles/gemma4-cuda.json index 1f854acba0f..0ffe9069b42 100644 --- a/tools/conformance_profiles/gemma4-cuda.json +++ b/tools/conformance_profiles/gemma4-cuda.json @@ -75,5 +75,18 @@ "status": 400, "error": "This server's maximum context length is" } - ] + ], + "cancel": { + "prompt": "count", + "tokens": 256, + "after_chunks": 4, + "rounds": 2, + "settle_s": 60 + }, + "evict": { + "fill_prompts": 6, + "fill_items": 900, + "fill_tokens": 1, + "settle_s": 60 + } } diff --git a/tools/conformance_profiles/qwen27-metal.json b/tools/conformance_profiles/qwen27-metal.json index 64bf6ddbdc2..a87b6049753 100644 --- a/tools/conformance_profiles/qwen27-metal.json +++ b/tools/conformance_profiles/qwen27-metal.json @@ -72,7 +72,17 @@ "error": "This server's maximum context length is" } ], + "settle_s": 240, "fresh_env": { "TF_QWEN27_SLOT_RESUME": "0" + }, + "cancel": { + "prompt": "count", + "tokens": 256, + "after_chunks": 4, + "rounds": 2 + }, + "skip": { + "evict": "on a 36 GB M3 Pro the 27B leaves 3.2 GiB free, the prompt cache gets 2.0 GiB, and macOS memory pressure (warning) stops new kept prompt states, so 12 fills left cached 0 -> 0 and the evicted turn was never cached; run evict on a Mac with headroom" } } diff --git a/tools/conformance_profiles/qwen35-cuda.json b/tools/conformance_profiles/qwen35-cuda.json index 05642224860..9d18df2fd84 100644 --- a/tools/conformance_profiles/qwen35-cuda.json +++ b/tools/conformance_profiles/qwen35-cuda.json @@ -75,5 +75,18 @@ "status": 400, "error": "This server's maximum context length is" } - ] + ], + "cancel": { + "prompt": "count", + "tokens": 256, + "after_chunks": 4, + "rounds": 2, + "settle_s": 60 + }, + "evict": { + "fill_prompts": 10, + "fill_items": 900, + "fill_tokens": 1, + "settle_s": 60 + } } diff --git a/tools/tests/fake_served_api.py b/tools/tests/fake_served_api.py index e020b4c6ec7..619091c1bcd 100644 --- a/tools/tests/fake_served_api.py +++ b/tools/tests/fake_served_api.py @@ -5,11 +5,26 @@ - drafted: a drafted reply to the copy prompt differs from its plain reply. - repeat: a drafted reply to the sky prompt differs the second time that request arrives. - concurrent: a reply differs while another request is in flight. -- resumed: the cached server reports no cached prompt tokens. +- resumed: a later chat turn reports no cached tokens unless its whole prompt was asked before. - refusals: an out-of-range presence_penalty is answered instead of refused. +- cancel_lane: a streamed reply the client leaves keeps its lane busy. +- cancel_free: a streamed reply the client leaves ends, but its lane never returns to the free ones. +- cancel_reply: the request a client left answers differently the next time it arrives. +- cancel_health: a server a client left answers ``/health`` with an error. +- evict: a chat turn pushed out of the prompt cache reports it (0 cached) but answers from the stale state. -A request with ``"stream": true`` gets the same reply as SSE, as the server streams it with ``include_usage``: the -content in pieces, a finishing chunk carrying ``tensorfold`` and ``speculative``, a usage-only chunk, then ``[DONE]``. +``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. + +The cached server reports five cached tokens for a later chat turn (more than one message). It keeps the prompts it +answered in an LRU of ``CAPACITY`` entries; a prompt pushed out reports 0 until it is asked again. ``GET /v1/load``, +``/metrics`` and ``/health`` show the lanes open streams hold, the disconnects counted and the server's health. + +A request with ``"stream": true`` gets the same reply as SSE, as the server streams it with ``include_usage``: one +event a token, ``TOKEN_GAP`` apart (the content two characters an event, empty once the text is out), a finishing +chunk carrying ``tensorfold`` and ``speculative``, a usage-only chunk, then ``[DONE]``. A client that leaves a stream +is counted as a disconnect, and its lane is freed. ``serve`` plays a scripted SSE reply instead, for the benchmark clients' tests. A reply is a list of tokens, each ``(choice, kind, text)`` for content and reasoning or ``(choice, "tool", index, field, text)`` for a tool call's @@ -18,6 +33,7 @@ Standard library only; no device, no network beyond 127.0.0.1. """ +import collections import contextlib import hashlib import http.server @@ -25,10 +41,14 @@ import threading import time -FAULTS = ("drafted", "repeat", "concurrent", "resumed", "refusals") +FAULTS = ("drafted", "repeat", "concurrent", "resumed", "refusals", "cancel_lane", "cancel_free", "cancel_reply", + "cancel_health", "evict") BATCH_WINDOW = 0.15 # seconds a lone request waits for a partner under the concurrent fault DONE = b"data: [DONE]\n\n" HASHES = {"token_sha": "d" * 12, "token_sha256": "d" * 64} +CAPACITY = 4 # prompt cache entries the cached server keeps +LANES = 8 +TOKEN_GAP = 0.0002 # seconds between streamed events def doc(sha="a" * 64, cached=0, accepted=2, drafted=3, text="hi"): @@ -59,14 +79,15 @@ def event(chunk: dict) -> bytes: return b"data: " + json.dumps(chunk).encode() + b"\n\n" -def streamed(payload: dict) -> list: - """``payload`` (a ``doc``) as server-sent events: content two characters an event, the finish, usage, [DONE].""" +def streamed(payload: dict, tokens: int = 0, gap: float = 0.0) -> list: + """``payload`` (a ``doc``) as ``play`` steps: ``tokens`` content events ``gap`` apart, the finish, usage, [DONE].""" text = payload["choices"][0]["message"]["content"] pieces = [{"choices": [{"index": 0, "delta": {"content": text[i:i + 2]}, "finish_reason": None}]} - for i in range(0, len(text), 2)] + for i in range(0, max(len(text), 2 * tokens), 2)] last = {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], "tensorfold": payload["tensorfold"], "speculative": payload["speculative"]} - return [event(c) for c in pieces + [last, {"choices": [], "usage": payload["usage"]}]] + [DONE] + steps = [s for c in pieces for s in (event(c), gap) if s] + return steps + [event(c) for c in (last, {"choices": [], "usage": payload["usage"]})] + [DONE] def delta(group: list[tuple], label: str) -> list[dict]: @@ -116,6 +137,18 @@ def log_message(self, *_): pass def do_GET(self): + server = self.server + if self.path == "/v1/load": + with server.lock: + busy, warming = server.streams + server.leaked, time.monotonic() < server.warm_until + capacity = {"mode": "window", "lanes_free": LANES - busy - server.lost} if server.lanes_free else {} + return self.reply(200, {"lanes": LANES, "running": busy + warming, "waiting": 19 * warming, + "http_active": {"chat_completions": busy}, "capacity": capacity}) + if self.path == "/metrics": + return self.reply(200, f"tensorfold:client_disconnections_total {server.disconnects}\n") + if self.path == "/health": + sick = server.fault == "cancel_health" and server.disconnects + return self.reply(503 if sick else 200, {"status": "error" if sick else "ok"}) self.reply(200, {"object": "list", "data": [{"id": "fake", "object": "model"}]}) def do_POST(self): @@ -126,17 +159,21 @@ def do_POST(self): error = refusal(body, server.fault) if error: return self.reply(400, {"error": {"message": error, "type": "invalid_request_error"}}) - key = json.dumps(body, sort_keys=True) + key = json.dumps({k: v for k, v in body.items() if k not in ("stream", "stream_options")}, sort_keys=True) with server.lock: server.seen[key] = server.seen.get(key, 0) + 1 arrival = server.seen[key] server.inflight += 1 + after_cut = key in server.cut + server.cut.discard(key) try: batched = self.batched() if server.fault == "concurrent" else False seed = body["seed"] if body.get("temperature") else None - salt = self.salt(body, arrival, batched) + cached, stale = self.lookup(body["messages"]) + salt = "stale" if stale else "after a cut" if after_cut and server.fault == "cancel_reply" else None + salt = salt or self.salt(body, arrival, batched) sha = hashlib.sha256(json.dumps([body["messages"], seed, salt]).encode()).hexdigest() - cached = 5 if server.cache and server.fault != "resumed" and len(body["messages"]) > 1 else 0 + self.keep(body["messages"]) accepted = 2 if body.get("draft", True) else 0 payload = doc(sha=sha, cached=cached, accepted=accepted, drafted=accepted, text="r" + sha[:6]) finally: @@ -144,11 +181,37 @@ def do_POST(self): server.inflight -= 1 # Out of flight before the reply is written: the client's next request must not find this one still counted. if body.get("stream"): - self.play(streamed(payload)) + self.play(streamed(payload, body.get("max_tokens", 16), TOKEN_GAP), key) else: self.reply(200, payload) + with server.lock: + server.warm_until = time.monotonic() + server.warm time.sleep(server.linger) + def lookup(self, messages): + """Cached tokens for the prompt, and whether the evict fault answers from an evicted prompt.""" + server = self.server + if not server.cache or len(messages) < 2: + return 0, False + with server.lock: + whole = json.dumps(messages) + if whole in server.evicted: + return 0, server.fault == "evict" + return (0 if server.fault == "resumed" and whole not in server.kept else 5), False + + def keep(self, messages): + """The prompt enters the LRU; the oldest prompts leave it.""" + server = self.server + if not server.cache: + return + with server.lock: + whole = json.dumps(messages) + server.kept[whole] = True + server.kept.move_to_end(whole) + server.evicted.discard(whole) + while len(server.kept) > CAPACITY: + server.evicted.add(server.kept.popitem(last=False)[0]) + def batched(self) -> bool: """True when another request shares the server with this one within the batch window.""" server = self.server @@ -168,35 +231,48 @@ def salt(self, body, arrival, batched): return None def reply(self, status, payload): - raw = json.dumps(payload).encode() + raw = payload.encode() if isinstance(payload, str) else json.dumps(payload).encode() self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(raw))) self.end_headers() self.wfile.write(raw) - def play(self, steps): + def play(self, steps, key=None): """An event stream: headers first, then each step (bytes written and flushed, a float slept).""" - self.send_response(200) - self.send_header("Content-Type", "text/event-stream") - self.end_headers() + server = self.server + with server.lock: + server.streams += 1 try: + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() for step in steps: if isinstance(step, bytes): self.wfile.write(step) self.wfile.flush() else: time.sleep(step) - except (BrokenPipeError, ConnectionResetError): - pass + except ConnectionError: # Windows raises ConnectionAbortedError (10053) on a cut + with server.lock: + server.disconnects += 1 + server.cut.add(key) + server.leaked += server.fault == "cancel_lane" + server.lost += server.fault == "cancel_free" + finally: + with server.lock: + server.streams -= 1 + self.close_connection = True @contextlib.contextmanager -def running(cache=False, fault=None, linger=0.0, steps=None): +def running(cache=False, fault=None, linger=0.0, steps=None, warm=0.0, lanes_free=True): """One fake on 127.0.0.1 port 0, yielding its base URL; stopped on exit.""" server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), FakeEngine) server.cache, server.fault, server.seen, server.inflight, server.linger = cache, fault, {}, 0, linger - server.steps = steps + server.steps, server.kept, server.evicted, server.cut = steps, collections.OrderedDict(), set(), set() + server.streams = server.leaked = server.lost = server.disconnects = 0 + server.warm, server.warm_until, server.lanes_free = warm, 0.0, lanes_free server.lock = threading.Lock() server.cond = threading.Condition(server.lock) thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True) @@ -210,12 +286,13 @@ def running(cache=False, fault=None, linger=0.0, steps=None): @contextlib.contextmanager -def fake(cache, fault=None, linger=0.0): +def fake(cache, fault=None, linger=0.0, **shape): """A running fake on 127.0.0.1 port 0, yielding its base URL; cache=False is the cache-off server.""" # 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}") - with running(cache, fault, linger) as url: + # shape: warm and lanes_free, see ``running``. + with running(cache, fault, linger, **shape) as url: yield url diff --git a/tools/tests/test_bench_conformance.py b/tools/tests/test_bench_conformance.py index f1a64f6a84c..45daa86425b 100644 --- a/tools/tests/test_bench_conformance.py +++ b/tools/tests/test_bench_conformance.py @@ -4,13 +4,15 @@ import json from pathlib import Path import sys +import tempfile import unittest sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import conformance from conformance import drafted_gate, equality_gate, refusals_gate, reply_row, resumed_gate, same, tally +from conformance_lifecycle import cancel_gate, census, evict_gate sys.path.insert(0, str(Path(__file__).resolve().parent)) -from fake_served_api import doc, fake, script, serve +from fake_served_api import FAULTS, doc, fake, script, serve PROFILE = Path(__file__).resolve().parents[1] / "conformance_profiles" / "qwen35-cuda.json" @@ -81,25 +83,81 @@ def test_refusals_need_status_and_text(self): self.assertFalse(refusals_gate([])["passed"]) +class LifecycleVerdictTests(unittest.TestCase): + """The cancel and evict verdicts: vacuous, uncounted, held and unevicted runs fail with their reason.""" + + A, B = reply_row(200, doc()), reply_row(200, doc(sha="b" * 64)) + CUT, BASE = {"chunks": 4, "ended": False}, {"running": 0, "waiting": 0, "active": 0, "lanes_free": 8} + + def test_cancel_needs_clean_counted_settled_cuts(self): + ok = cancel_gate([(self.A, self.A)], [self.CUT], [True], [True], 1, self.BASE) + self.assertTrue(ok["passed"], ok["line"]) + cases = {"vacuous": ([(self.A, self.A)], [{"chunks": 4, "ended": True}], [True], [True], 1, self.BASE), + "counted 0": ([(self.A, self.A)], [self.CUT], [True], [True], 0, self.BASE), + "counted 2": ([(self.A, self.A)], [self.CUT], [True], [True], 2, self.BASE), + "did not return": ([(self.A, self.A)], [self.CUT], [False], [True], 1, self.BASE), + "not ok": ([(self.A, self.A)], [self.CUT], [True], [False], 1, self.BASE), + "no idle census": ([(self.A, self.A)], [self.CUT], [True], [True], 1, None), + "1 unequal": ([(self.A, self.B)], [self.CUT], [True], [True], 1, self.BASE)} + for why, args in cases.items(): + with self.subTest(why=why): + gate = cancel_gate(*args) + self.assertFalse(gate["passed"]) + self.assertIn(why, gate["line"]) + + def test_evict_needs_a_kept_prompt_that_leaves(self): + def row(cached, sha="a"): + return {**reply_row(200, doc(sha=sha * 64)), "cached": cached} + ok = evict_gate(row(0), [row(0), row(25)], row(0), [row(0)], True, self.BASE) + self.assertTrue(ok["passed"], ok["line"]) + cases = {"vacuous": (row(0), [row(0), row(0)], row(0), [row(0)], True, self.BASE), + "nothing evicted": (row(0), [row(0), row(25)], row(25), [], True, self.BASE), + "1 unequal": (row(0), [row(0), row(25)], row(0, "b"), [row(0)], True, self.BASE), + "did not return": (row(0), [row(0), row(25)], row(0), [row(0)], False, self.BASE), + "failed": (row(0), [row(0), row(25)], row(0), [{"status": 0, "error": "x"}], True, self.BASE)} + for why, args in cases.items(): + with self.subTest(why=why): + gate = evict_gate(*args) + self.assertFalse(gate["passed"]) + self.assertIn(why, gate["line"]) + + def test_the_census_keeps_every_pool(self): + pools = [{"promised_tokens": 0, "available_tokens": 90, "reclaimable_tokens": 10}, + {"promised_tokens": 64, "available_tokens": 7}] + load = {"running": 0, "waiting": 0, "http_active": {"chat_completions": 0}, "capacity": {"pools": pools}} + client = type("Stub", (), {"get": lambda _self, path: (200, json.dumps(load).encode())})() + self.assertEqual(census(client)["pools"], [{"promised": 0, "unheld": 100}, {"promised": 64, "unheld": 7}]) + + class GateRunTests(unittest.TestCase): """Every gate passes on the clean fake; each fault the fake plants turns exactly its gate red.""" NAMES = {"drafted": "drafted == plain", "repeat": "repeat == first", "concurrent": "concurrent == solo", - "resumed": "resumed == fresh", "refusals": "refusals"} - - def run_kit(self, *extra, fault=None): + "resumed": "resumed == fresh", "refusals": "refusals", "cancel": "cancel", "evict": "evict", + "cancel_lane": "cancel", "cancel_free": "cancel", "cancel_reply": "cancel", "cancel_health": "cancel"} + GATE_OF = {fault: name.split()[0] for fault, name in NAMES.items() if fault in FAULTS} # the gate a fault turns red + + def run_kit(self, *extra, fault=None, shape=None, **changes): + profile = json.loads(PROFILE.read_text()) + for block in ("cancel", "evict"): + profile[block]["settle_s"] = 1 # a held lane fails in a second, not a minute + profile.update(changes) out = io.StringIO() - with fake(True, fault) as url, fake(False) as fresh, contextlib.redirect_stdout(out): - code = conformance.main([str(PROFILE), "--url", url, "--fresh-url", fresh, *extra]) - return code, [line for line in out.getvalue().splitlines() if line.startswith(("PASS", "FAIL"))] - - def assert_only_red(self, fault): + with tempfile.TemporaryDirectory() as tmp, fake(True, fault, **(shape or {})) as url, fake(False) as fresh, \ + contextlib.redirect_stdout(out): + path = Path(tmp) / "profile.json" + path.write_text(json.dumps(profile)) + code = conformance.main([str(path), "--url", url, "--fresh-url", fresh, *extra]) + return code, [line for line in out.getvalue().splitlines() if line.startswith(("PASS", "FAIL", "SKIP"))] + + def assert_only_red(self, fault, also=()): code, lines = self.run_kit(fault=fault) self.assertEqual(code, 1, lines) self.assertEqual(len(lines), len(conformance.GATES), lines) red = [line for line in lines if line.startswith("FAIL")] - self.assertEqual(len(red), 1, lines) + self.assertEqual(len(red), 1 + len(also), lines) self.assertTrue(red[0].startswith("FAIL " + self.NAMES[fault]), lines) + self.assertEqual([line.split(":")[0] for line in red[1:]], ["FAIL " + g for g in also], lines) def test_clean_fake_passes_every_gate(self): code, lines = self.run_kit() @@ -122,6 +180,62 @@ def test_fault_resumed_reports_no_cached_tokens(self): def test_fault_listed_refusal_accepted(self): self.assert_only_red("refusals") + def test_fault_cancel_keeps_a_lane(self): + # A request left running keeps the server from ever going idle, so evict has no idle census either. + self.assert_only_red("cancel_lane", also=("evict",)) + + def test_fault_cancel_loses_only_a_free_lane(self): + self.assert_only_red("cancel_free") + + def test_fault_cancel_changes_the_next_reply(self): + self.assert_only_red("cancel_reply") + + def test_fault_cancel_leaves_the_server_unhealthy(self): + self.assert_only_red("cancel_health") + + def test_fault_evict_answers_from_stale_state(self): + self.assert_only_red("evict") + + def test_skip_names_the_gate_and_its_reason(self): + code, lines = self.run_kit("--gates", "cancel,evict", skip={"evict": "no prompt cache"}) + self.assertEqual(code, 0, lines) + self.assertEqual(lines[1], "SKIP evict: no prompt cache") + code, lines = self.run_kit("--gates", "cancel", cancel={}) + self.assertEqual(code, 1, lines) + self.assertIn("no cancel block", lines[0]) + + def test_skip_takes_only_cancel_and_evict_and_plant_refuses_a_skipped_gate(self): + cases = {"only cancel and evict": ("--gates", "drafted", {"drafted": "x"}), + "skips that gate": ("--gates", "evict", "--plant", "evict", {"evict": "no prompt cache"}), + "a non-empty string": ("--gates", "evict", {"evict": True}), + "each skipped gate": ("--gates", "evict", ["evict"])} + for why, (*argv, skip) in cases.items(): + with self.subTest(why=why), contextlib.redirect_stderr(io.StringIO()) as err: + with self.assertRaises(SystemExit) as exit_: + self.run_kit(*argv, skip=skip) + self.assertEqual(exit_.exception.code, 2) + self.assertIn(why, err.getvalue()) + + def test_a_stream_that_ends_before_the_cut_is_vacuous(self): + short = {"prompt": "count", "tokens": 2, "after_chunks": 8, "rounds": 1, "settle_s": 1} + code, lines = self.run_kit("--gates", "cancel", cancel=short) + self.assertEqual(code, 1, lines) + self.assertIn("2 cuts came after the reply ended or failed (vacuous)", lines[0]) # one a sampling mode + + def test_a_server_busy_after_each_reply_and_without_lanes_free_settles_first(self): + # Like Metal qwen27: no capacity.lanes_free, and each reply is followed by a background prefill of the next turn. + profile = json.loads(PROFILE.read_text()) + blocks = {b: {k: v for k, v in profile[b].items() if k != "settle_s"} for b in ("cancel", "evict")} + shape = {"warm": 0.4, "lanes_free": False} + code, lines = self.run_kit("--gates", "cancel,evict", shape=shape, settle_s=5, **blocks) + self.assertEqual(code, 0, lines) + self.assertTrue(all(line.startswith("PASS") for line in lines), lines) + self.assertIn("censuses back to {'running': 0, 'waiting': 0, 'active': 0}", lines[0]) + code, lines = self.run_kit("--gates", "cancel,evict", shape=shape, settle_s=0.1, **blocks) + self.assertEqual(code, 1, lines) + self.assertTrue(all(line.startswith("FAIL") for line in lines), lines) + self.assertIn("no idle census from GET /v1/load (busy past settle_s)", lines[0]) + def test_each_plant_flag_turns_its_gate_red(self): for gate in conformance.GATES: with self.subTest(gate=gate): @@ -143,9 +257,9 @@ def test_streamed_replies_pass_clean_and_each_fault_turns_its_gate_red(self): self.assertEqual(code, 0, lines) self.assertEqual(len(lines), len(conformance.GATES)) self.assertTrue(all(line.startswith("PASS") for line in lines), lines) - for fault in conformance.GATES: + for fault, gate in self.GATE_OF.items(): with self.subTest(fault=fault): - code, lines = self.run_kit("--stream", "--gates", fault, fault=fault) + code, lines = self.run_kit("--stream", "--gates", gate, fault=fault) self.assertEqual(code, 1, lines) self.assertEqual(len(lines), 1) self.assertTrue(lines[0].startswith("FAIL " + self.NAMES[fault]), lines) @@ -210,6 +324,15 @@ def test_profiles_parse_and_name_their_gates(self): self.assertTrue(all(r["name"] and r["error"] for r in profile["refusals"])) self.assertGreater(profile["sampled"]["temperature"], 0) self.assertTrue(all(isinstance(v, str) for v in profile.get("fresh_env", {}).values())) + self.assertEqual(conformance.lifecycle_gaps(profile), []) # each lifecycle gate runs or says why not + + def test_an_empty_lifecycle_block_is_a_gap(self): + base = {"cancel": {"prompt": "count"}, "evict": {"fill_prompts": 12}} + self.assertEqual(conformance.lifecycle_gaps(base), []) + for gate, block in (("cancel", {}), ("evict", {}), ("evict", {"fill_prompts": 0}), ("cancel", {"prompt": ""})): + with self.subTest(gate=gate, block=block): + self.assertEqual(conformance.lifecycle_gaps({**base, gate: block}), [gate]) + self.assertEqual(conformance.lifecycle_gaps({**base, gate: block, "skip": {gate: "why"}}), []) if __name__ == "__main__": diff --git a/zig/build/cuda_family_host.zig b/zig/build/cuda_family_host.zig index 7162558897d..404f9bb9f18 100644 --- a/zig/build/cuda_family_host.zig +++ b/zig/build/cuda_family_host.zig @@ -8,8 +8,12 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B b.step("test-qwen35-metal-scope-host", "Metal 2B format admission without device or Metal compiler").dependOn(&metal_scope.step); @import("load_prefetch_host.zig").tests(b, mods.core, step); const captured = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/cuda/aot_identity.zig"), .target = host, .link_libc = true }), .filters = &.{"persistence identity: captured CUDA"} })); - b.step("test-cuda-persistence-source-host", "Captured CUDA source keys without loading a driver").dependOn(&captured.step); + const wiring = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/nemotron_key_wiring_test.zig"), .target = host }) })); + const source_keys = b.step("test-cuda-persistence-source-host", "Captured CUDA source keys and Nemotron key wiring without loading a driver"); + source_keys.dependOn(&captured.step); + source_keys.dependOn(&wiring.step); step.dependOn(&captured.step); + step.dependOn(&wiring.step); b.step("test-qwen35-request-starts-host", "Request-start and shared-KV startup refusal without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"request starts:"} })).step); @import("minimax_cuda.zig").hostTests(b, host, cuda, mods.core, mods.lanes, step); diff --git a/zig/nemotron_key_wiring_test.zig b/zig/nemotron_key_wiring_test.zig new file mode 100644 index 00000000000..bc7c191734f --- /dev/null +++ b/zig/nemotron_key_wiring_test.zig @@ -0,0 +1,45 @@ +//! Nemotron's disk and learned keys take their resolved policies where the keys are made, read from the source. +const std = @import("std"); + +/// The block of the function `head` opens, brace to matching brace, with no whitespace or line comments. +fn body(a: std.mem.Allocator, source: []const u8, head: []const u8) ![]const u8 { + const at = std.mem.indexOf(u8, source, head) orelse return error.FunctionMissing; + const open = at + (std.mem.indexOf(u8, source[at..], "{\n") orelse return error.FunctionMissing); + var out: std.ArrayList(u8) = .empty; + var depth: usize = 0; + var lines = std.mem.splitScalar(u8, source[open..], '\n'); + while (lines.next()) |whole| { + const line = if (std.mem.indexOf(u8, whole, "//")) |c| whole[0..c] else whole; + for (line) |ch| { + if (!std.ascii.isWhitespace(ch)) try out.append(a, ch); + if (ch == '{') depth += 1; + if (ch == '}') { + depth -= 1; + if (depth == 0) return out.items; + } + } + } + return error.FunctionUnclosed; +} + +fn expectCall(source: []const u8, head: []const u8, call: []const u8) !void { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const b = try body(arena.allocator(), source, head); + if (std.mem.indexOf(u8, b, call) == null) std.debug.print("`{s}` no longer has `{s}`\n", .{ head, call }); + try std.testing.expect(std.mem.indexOf(u8, b, call) != null); +} + +test "persistence identity: Nemotron CUDA's disk key extends its identity with the policy the engine resolved" { + try expectCall(@embedFile("src/native/cuda_disk.zig"), "pub fn identity(", "return.{.id=withPolicy(id,t.e),"); +} + +test "persistence identity: Nemotron Metal's learned key extends its identity with the backend's policy" { + try expectCall(@embedFile("src/native/metal_identity.zig"), "pub fn learned(", "return.{.id=withPolicy(h.final(),b),"); +} + +test "persistence identity: Nemotron Metal's backend keeps TF_COOP_SPLIT as its forward pass resolves it" { + const source = @embedFile("src/families/nemotron/backend.zig"); + try std.testing.expect(std.mem.indexOf(u8, source, "\nconst fwd = @import(\"forward.zig\");\n") != null); + try expectCall(source, "pub fn init(gpa: std.mem.Allocator, m: *Model,", ".coop_split=fwd.splitOn(),"); +} diff --git a/zig/persistence_checkpoint_test.zig b/zig/persistence_checkpoint_test.zig new file mode 100644 index 00000000000..38112b66c94 --- /dev/null +++ b/zig/persistence_checkpoint_test.zig @@ -0,0 +1,52 @@ +//! Indexed subfolders are admitted loader inputs that a top-level scan cannot stamp. +const std = @import("std"); +const disk = @import("src/native/disk_identity.zig"); +const nemo = @import("src/native/metal_identity.zig"); +const fixture = @import("src/native/persistence_fixture.zig"); +const t = std.testing; +const Family = enum { nemo, qwen, glm, flash }; + +fn key(a: std.mem.Allocator, dir: []const u8, family: Family) !u64 { + var h = std.hash.Wyhash.init(@backingInt(family)); + if (family == .nemo) try nemo.shardStamps(&h, a, t.io, dir) else try disk.checkpoint(&h, a, t.io, dir); + return h.final(); +} +fn nestedMiss(comptime family: Family) !void { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a); + try tmp.dir.createDirPath(t.io, "tensors"); + try tmp.dir.writeFile(t.io, .{ .sub_path = "config.json", .data = "{}" }); + try tmp.dir.writeFile(t.io, .{ .sub_path = "model.safetensors.index.json", .data = "{\"weight_map\":{\"unprobed.weight\":\"tensors/native-QB.safetensors\"}}" }); + const header = "{\"unprobed.weight\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,4]}}"; + var shard: [8 + header.len + 4]u8 = @splat(0); + std.mem.writeInt(u64, shard[0..8], header.len, .little); + @memcpy(shard[8..][0..header.len], header); + try tmp.dir.writeFile(t.io, .{ .sub_path = "tensors/native-QB.safetensors", .data = &shard }); + const before = try key(a, dir, family); + const same = try key(a, dir, family); + shard[shard.len - 1] = 1; + try fixture.rewrite(tmp.dir, "tensors/native-QB.safetensors", &shard); + try fixture.misses(before, same, &.{try key(a, dir, family)}); + try tmp.dir.deleteFile(t.io, "tensors/native-QB.safetensors"); + try t.expectError(error.IndexedShardMissing, key(a, dir, family)); +} + +test "persistence identity: Nemotron Metal indexed shard rewrite misses with the same probe" { + try nestedMiss(.nemo); +} +test "persistence identity: Qwen Metal indexed shard rewrite misses with the same probe" { + try nestedMiss(.qwen); +} +test "persistence identity: GLM Metal indexed shard rewrite misses with the same probe" { + try nestedMiss(.glm); +} +test "persistence identity: Flash Next Metal indexed shard rewrite misses with the same probe" { + try nestedMiss(.flash); +} +test { + _ = nemo; // its top-level shard rewrite test +} diff --git a/zig/persistence_identity_test.zig b/zig/persistence_identity_test.zig index 1c878973d70..df446705510 100644 --- a/zig/persistence_identity_test.zig +++ b/zig/persistence_identity_test.zig @@ -4,6 +4,7 @@ const disk = @import("src/native/disk_identity.zig"); const glm = @import("src/families/glm/load_plan.zig"); const pack = @import("src/families/flashnext/pack_io.zig"); const Imprint = @import("engine_api").prompt_imprint.Imprint; +const fixture = @import("src/native/persistence_fixture.zig"); const binary = @import("sys").file_identity; const t = std.testing; const io = t.io; @@ -50,9 +51,8 @@ fn changedWeightMiss(kind: Kind) !void { try t.expect(state.best(&tokens, &.{}, false, 0) != null); } // An unvisited tensor can change without changing a fixed probe, config, index or shard header. - try std.Io.sleep(io, .fromMilliseconds(5), .awake); shard[shard.len - 1] = 1; - try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = &shard }); + try fixture.rewrite(tmp.dir, "model.safetensors", &shard); try t.expectEqual(old, try legacy(a, dir, kind)); const after = try disk.scoped(a, io, dir, old); var fresh = try Imprint.open(a, root, after, 1 << 20); @@ -149,3 +149,11 @@ test "persistence identity: tokenizer and template edits reuse only identical ca try t.expect(kept.best(&.{ 5, 7, 13 }, &.{ 1, 2 }, true, 0) == null); try t.expect(kept.best(&ids, &.{ 0, 2 }, true, 0) == null); } + +test { + _ = @import("persistence_policy_test.zig"); +} + +test { + _ = @import("persistence_checkpoint_test.zig"); +} diff --git a/zig/persistence_policy_test.zig b/zig/persistence_policy_test.zig new file mode 100644 index 00000000000..58a2d735680 --- /dev/null +++ b/zig/persistence_policy_test.zig @@ -0,0 +1,195 @@ +//! A fixed probe cannot stand in for resolved policies or the actual loaded weight pack. +const std = @import("std"); +const fixture = @import("src/native/persistence_fixture.zig"); +const qwen = @import("src/native/qwen27_disk.zig"); +const glm = @import("src/native/glm_disk.zig"); +const flash = @import("src/native/flashnext_disk.zig"); +const nemo = @import("src/native/metal_identity.zig"); +const t = std.testing; + +// These expose only the resolved fields the production key producers consume, without a GPU owner. +test "persistence identity: Qwen Metal loaded ANE columns miss with the same probe" { + const Share = struct { columns: u32 }; + var share: Share = .{ .columns = 1024 }; + var h: struct { model: struct { ane: ?*Share, frame: struct { capacity: u32 } }, back: struct { chunk: usize } } = .{ .model = .{ .ane = @as(?*Share, &share), .frame = .{ .capacity = @as(u32, 128) } }, .back = .{ .chunk = @as(usize, 128) } }; + const before = qwen.withPolicy(7, &h); + const matching = qwen.withPolicy(7, &h); + share.columns = 2048; + const other_share = qwen.withPolicy(7, &h); + share.columns = 1024; + h.model.frame.capacity = 256; // buffer rows only: the same states + try t.expectEqual(before, qwen.withPolicy(7, &h)); + h.back.chunk = 256; // another chunk height starts cold + try fixture.misses(before, matching, &.{ other_share, qwen.withPolicy(7, &h) }); +} + +test "persistence identity: GLM Metal resolved policy misses with the same probe" { + const Config = @import("src/families/glm/config.zig").Config; + const Prompt = struct { rows: u32 = 4096, sparse_nax: bool = true }; + const Head = struct { eh_bf16: ?u8 = 1 }; + const Wide = struct { bf16_nax: ?u8 = 1 }; + var prompt: Prompt = .{}; + var weights: struct { mtp: ?Head = .{} } = .{}; + var kernels: struct { wide: ?Wide = .{} } = .{}; + var e: struct { c: Config, pr: ?*Prompt, fused_route: bool, w: @TypeOf(&weights), k: @TypeOf(&kernels) } = .{ .c = Config{}, .pr = @as(?*Prompt, &prompt), .fused_route = true, .w = &weights, .k = &kernels }; + try t.expect(glm.ehTile(&e)); + const before = glm.withPolicy(7, &e); + var changed: std.ArrayList(u64) = .empty; + defer changed.deinit(t.allocator); + e.fused_route = false; + try changed.append(t.allocator, glm.withPolicy(7, &e)); + e.fused_route = true; + inline for (.{ "run", "tp_rank", "dense_inter", "kda_heads", "mla_heads" }) |field| { + @field(e.c, field) += 1; + try changed.append(t.allocator, glm.withPolicy(7, &e)); + @field(e.c, field) -= 1; + } + inline for (.{ "own", "inter" }) |field| { + @field(e.c, field)[0] += 1; + try changed.append(t.allocator, glm.withPolicy(7, &e)); + @field(e.c, field)[0] -= 1; + } + prompt.sparse_nax = false; + try changed.append(t.allocator, glm.withPolicy(7, &e)); + prompt.sparse_nax = true; + prompt.rows = 8192; // another chunk height starts cold + try changed.append(t.allocator, glm.withPolicy(7, &e)); + prompt.rows = 4096; + kernels.wide.?.bf16_nax = null; // GLM_EHPROJ_NAX=0 or a failed tile build: the prompt's eh_proj is scalar + try t.expect(!glm.ehTile(&e)); + const scalar = glm.withPolicy(7, &e); + try changed.append(t.allocator, scalar); + kernels.wide = null; + try t.expectEqual(scalar, glm.withPolicy(7, &e)); + kernels.wide = .{}; + weights.mtp.?.eh_bf16 = null; // a quantized head runs neither bf16 kernel + try t.expectEqual(scalar, glm.withPolicy(7, &e)); + weights.mtp = null; + try t.expectEqual(scalar, glm.withPolicy(7, &e)); + weights.mtp = .{}; + e.pr = null; + try t.expect(!glm.ehTile(&e)); + try changed.append(t.allocator, glm.withPolicy(7, &e)); + e.pr = &prompt; + try fixture.misses(before, glm.withPolicy(7, &e), changed.items); +} + +const flags = .{ "fused_xsum", "dense", "dense_target", "split", "gdn_step", "hc_mma", "grouped", "xpack", "xfused", "xsx", "copy", "prefetch", "lane_new", "rotary_enabled" }; +const Gx = struct { min_rows: usize }; +const Tp = struct { rank: u32 }; +const Run = struct { + fused_xsum: bool = false, + serial: bool = false, + dense: bool = false, + dense_target: bool = false, + split: bool = false, + gdn_step: bool = false, + hc_mma: bool = false, + grouped: bool = false, + xpack: bool = false, + xfused: bool = false, + xsx: bool = false, + copy: bool = false, + prefetch: bool = false, + lane_new: bool = false, + rotary_enabled: bool = false, + skip: u32 = 0, + hcskip: u32 = 0, + gskip: u32 = 0, + lane_pf: usize = 1, + gdn_pipe: ?u8 = null, + gdn_kept: ?u8 = null, + gx: ?*const Gx = null, + tp: ?*const Tp = null, +}; + +test "persistence identity: Flash Next Metal resolved branches miss with the same probe" { + var r: Run = .{}; + const before = flash.withPolicy(7, &r); + r.serial = true; // a serial encoder in place of barriers: the same launches in the same order + try t.expectEqual(before, flash.withPolicy(7, &r)); + r.serial = false; + var changed: std.ArrayList(u64) = .empty; + defer changed.deinit(t.allocator); + inline for (flags) |field| { + @field(r, field) = true; + try changed.append(t.allocator, flash.withPolicy(7, &r)); + @field(r, field) = false; + } + inline for (.{ "skip", "hcskip", "gskip", "lane_pf" }) |field| { + @field(r, field) += 1; + try changed.append(t.allocator, flash.withPolicy(7, &r)); + @field(r, field) -= 1; + } + r.gdn_pipe = 1; + try changed.append(t.allocator, flash.withPolicy(7, &r)); + r.gdn_pipe = null; + r.gdn_kept = 1; + try changed.append(t.allocator, flash.withPolicy(7, &r)); + r.gdn_kept = null; + var gx: Gx = .{ .min_rows = 4 }; + r.gx = &gx; + try changed.append(t.allocator, flash.withPolicy(7, &r)); + gx.min_rows = 8; + try changed.append(t.allocator, flash.withPolicy(7, &r)); + r.gx = null; + var tp: Tp = .{ .rank = 0 }; + r.tp = &tp; + try changed.append(t.allocator, flash.withPolicy(7, &r)); + tp.rank = 1; + try changed.append(t.allocator, flash.withPolicy(7, &r)); + r.tp = null; + try fixture.misses(before, flash.withPolicy(7, &r), changed.items); +} + +test "persistence identity: Nemotron Metal coop K-slice split misses with the same probe" { + var b: struct { coop_split: bool, scratch: struct { rows: usize } } = .{ .coop_split = true, .scratch = .{ .rows = 64 } }; + const before = nemo.withPolicy(7, &b); + const matching = nemo.withPolicy(7, &b); + b.scratch.rows = 128; // a chunk of 65 to 128 rows splits only when the scratch holds its partials + const wider = nemo.withPolicy(7, &b); + b.coop_split = false; // TF_COOP_SPLIT=0 + const off = nemo.withPolicy(7, &b); + b.scratch.rows = 64; // with no split, the scratch rows decide nothing + try t.expectEqual(off, nemo.withPolicy(7, &b)); + try fixture.misses(before, matching, &.{ wider, off }); +} + +test "persistence identity: Flash Next Metal actual pack rewrite misses with the same source and probe" { + const a = t.allocator; + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const header = "{\"unprobed.weight\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,4]}}"; + var pack_bytes: [8 + header.len + 4]u8 = @splat(0); + std.mem.writeInt(u64, pack_bytes[0..8], header.len, .little); + @memcpy(pack_bytes[8..][0..header.len], header); + try tmp.dir.writeFile(t.io, .{ .sub_path = "pack.safetensors", .data = &pack_bytes }); + try tmp.dir.writeFile(t.io, .{ .sub_path = "other.safetensors", .data = &pack_bytes }); + const file = try tmp.dir.openFile(t.io, "pack.safetensors", .{}); + defer file.close(t.io); + const other = try tmp.dir.openFile(t.io, "other.safetensors", .{}); + defer other.close(t.io); + const files = [_]c_int{ file.handle, other.handle }; + const before = try flash.withFiles(7, a, t.io, &files); + const matching = try flash.withFiles(7, a, t.io, &.{ other.handle, file.handle }); + pack_bytes[pack_bytes.len - 1] = 1; + try fixture.rewrite(tmp.dir, "pack.safetensors", &pack_bytes); + try fixture.misses(before, matching, &.{try flash.withFiles(7, a, t.io, &files)}); + try t.expectError(error.IdentityFileUnavailable, flash.withFiles(7, a, t.io, &.{-1})); +} + +test "persistence identity: Flash Next Metal mapped reference bytes miss with the same probe" { + var first = [_]u8{ 1, 2, 3, 4 }; + const second = [_]u8{ 5, 6, 7, 8 }; + const Map = struct { bytes: []const u8, size: usize }; + const maps = [_]Map{ .{ .bytes = &first, .size = 4 }, .{ .bytes = &second, .size = 4 } }; + var run = .{ .files = .{ .items = @as([]const c_int, &.{}) }, .maps = .{ .items = @as([]const Map, &maps) } }; + const before = try flash.withInputs(7, t.allocator, t.io, &run); + const matching = try flash.withInputs(7, t.allocator, t.io, &run); + first[3] ^= 1; + try fixture.misses(before, matching, &.{try flash.withInputs(7, t.allocator, t.io, &run)}); + first[3] ^= 1; + const reversed = [_]Map{ maps[1], maps[0] }; + run.maps.items = &reversed; + try t.expectEqual(before, try flash.withInputs(7, t.allocator, t.io, &run)); +} diff --git a/zig/src/core/checkpoint_config.zig b/zig/src/core/checkpoint_config.zig index 8e5189f1983..7a22afb770c 100644 --- a/zig/src/core/checkpoint_config.zig +++ b/zig/src/core/checkpoint_config.zig @@ -1,5 +1,6 @@ //! One bounded checkpoint-config reader for info, serve and benchmark metadata. const std = @import("std"); +pub const index = @import("checkpoint_names.zig"); pub const limit: usize = 64 << 20; /// Missing is distinct from a failed read; diagnostics never replace an I/O error with a missing checkpoint. diff --git a/zig/src/core/checkpoint_index.zig b/zig/src/core/checkpoint_index.zig index 1d60cf31142..a5bfd644849 100644 --- a/zig/src/core/checkpoint_index.zig +++ b/zig/src/core/checkpoint_index.zig @@ -3,42 +3,10 @@ const std = @import("std"); pub const max_bytes = 64 << 20; -pub fn plainName(name: []const u8) bool { - if (name.len == 0 or name[name.len - 1] == '.' or name[name.len - 1] == ' ') return false; - for (name) |c| if (c < 0x20 or c == 0x7f) return false; - if (std.mem.indexOfAny(u8, name, "/\\:<>\"|?*") != null) return false; - const stem = name[0 .. std.mem.indexOfScalar(u8, name, '.') orelse name.len]; - for ([_][]const u8{ "CON", "PRN", "AUX", "NUL" }) |reserved| - if (std.ascii.eqlIgnoreCase(stem, reserved)) return false; - if (stem.len == 4 and stem[3] >= '1' and stem[3] <= '9' and - (std.ascii.eqlIgnoreCase(stem[0..3], "COM") or std.ascii.eqlIgnoreCase(stem[0..3], "LPT"))) return false; - return true; -} - -/// An index's shard: a plain name, or plain names joined by '/' with none starting with '.', inside the model folder. -pub fn shardName(name: []const u8) bool { - if (std.mem.indexOfScalar(u8, name, '/') == null) return plainName(name); - var parts = std.mem.splitScalar(u8, name, '/'); - while (parts.next()) |part| if (!plainName(part) or part[0] == '.') return false; - return true; -} - -pub fn weightMap(root: std.json.Value) error{BadIndex}!std.json.ObjectMap { - if (root != .object) return error.BadIndex; - const map = root.object.get("weight_map") orelse return error.BadIndex; - if (map != .object) return error.BadIndex; - for (map.object.values()) |value| { - if (value != .string or !shardName(value.string)) return error.BadIndex; - } - return map.object; -} - -/// The weight map with each shard directly in the model folder, as writes need: shard_edit.linked sees only those. -pub fn plainWeightMap(root: std.json.Value) error{BadIndex}!std.json.ObjectMap { - const map = try weightMap(root); - for (map.values()) |value| if (!plainName(value.string)) return error.BadIndex; - return map; -} +pub const plainName = @import("checkpoint_config").index.plainName; +pub const shardName = @import("checkpoint_config").index.shardName; +pub const weightMap = @import("checkpoint_config").index.weightMap; +pub const plainWeightMap = @import("checkpoint_config").index.plainWeightMap; test "portable shard names exclude path and Windows device aliases" { const bad = [_][]const u8{ diff --git a/zig/src/core/checkpoint_names.zig b/zig/src/core/checkpoint_names.zig new file mode 100644 index 00000000000..d4b2f02ef49 --- /dev/null +++ b/zig/src/core/checkpoint_names.zig @@ -0,0 +1,39 @@ +//! Shared checkpoint index schema and portable shard-name validation. +const std = @import("std"); + +pub fn plainName(name: []const u8) bool { + if (name.len == 0 or name[name.len - 1] == '.' or name[name.len - 1] == ' ') return false; + for (name) |c| if (c < 0x20 or c == 0x7f) return false; + if (std.mem.indexOfAny(u8, name, "/\\:<>\"|?*") != null) return false; + const stem = name[0 .. std.mem.indexOfScalar(u8, name, '.') orelse name.len]; + for ([_][]const u8{ "CON", "PRN", "AUX", "NUL" }) |reserved| + if (std.ascii.eqlIgnoreCase(stem, reserved)) return false; + if (stem.len == 4 and stem[3] >= '1' and stem[3] <= '9' and + (std.ascii.eqlIgnoreCase(stem[0..3], "COM") or std.ascii.eqlIgnoreCase(stem[0..3], "LPT"))) return false; + return true; +} + +/// An index's shard: a plain name, or plain names joined by '/' with none starting with '.', inside the model folder. +pub fn shardName(name: []const u8) bool { + if (std.mem.indexOfScalar(u8, name, '/') == null) return plainName(name); + var parts = std.mem.splitScalar(u8, name, '/'); + while (parts.next()) |part| if (!plainName(part) or part[0] == '.') return false; + return true; +} + +pub fn weightMap(root: std.json.Value) error{BadIndex}!std.json.ObjectMap { + if (root != .object) return error.BadIndex; + const map = root.object.get("weight_map") orelse return error.BadIndex; + if (map != .object) return error.BadIndex; + for (map.object.values()) |value| { + if (value != .string or !shardName(value.string)) return error.BadIndex; + } + return map.object; +} + +/// The weight map with each shard directly in the model folder, as writes need: shard_edit.linked sees only those. +pub fn plainWeightMap(root: std.json.Value) error{BadIndex}!std.json.ObjectMap { + const map = try weightMap(root); + for (map.values()) |value| if (!plainName(value.string)) return error.BadIndex; + return map; +} diff --git a/zig/src/core/tokenizer/memo.zig b/zig/src/core/tokenizer/memo.zig index 32efad876f8..7d499f98bcd 100644 --- a/zig/src/core/tokenizer/memo.zig +++ b/zig/src/core/tokenizer/memo.zig @@ -1,11 +1,19 @@ -//! Token ids of long text segments between added tokens: a chat's earlier messages are tokenized once, not each render. +//! Token ids of text segments between added tokens: a chat's earlier messages are tokenized once, not each render. const std = @import("std"); const Allocator = std.mem.Allocator; /// Segments shorter than this are tokenized each time: their lookup would cost about what their encode does. -pub const min_bytes = 1024; +pub const min_bytes = 64; const Entry = struct { text: []u8, first: bool, ids: []u32, previous: ?u64 = null, next: ?u64 = null }; +/// Bytes a kept segment costs beyond its text and ids: its entry and its key in the map. +pub const overhead = @sizeOf(Entry) + @sizeOf(u64); + +/// A segment's bytes against the cap: its text, its ids and the fixed `overhead`; null past usize. +pub fn bytes(text: usize, ids: usize) ?usize { + const id_bytes = std.math.mul(usize, ids, @sizeOf(u32)) catch return null; + return std.math.add(usize, text, std.math.add(usize, id_bytes, overhead) catch return null) catch null; +} /// A bounded segment cache; successful reads refresh recency under the same lock as saves and eviction. pub const Memo = struct { @@ -46,8 +54,7 @@ pub const Memo = struct { /// Copies a completed segment; concurrent duplicate saves retain the existing copy and refresh its recency. pub fn put(m: *Memo, text: []const u8, first: bool, ids: []const u32) void { - const id_bytes = std.math.mul(usize, ids.len, @sizeOf(u32)) catch return; - const size = std.math.add(usize, text.len, id_bytes) catch return; + const size = bytes(text.len, ids.len) orelse return; if (size > m.cap) return; const k = key(text, first); m.lock(); @@ -99,7 +106,7 @@ pub const Memo = struct { fn remove(m: *Memo, k: u64) void { m.unlink(k); const e = m.map.fetchRemove(k).?.value; - m.held -= e.text.len + e.ids.len * @sizeOf(u32); + m.held -= bytes(e.text.len, e.ids.len).?; free(m.gpa, e); } @@ -127,7 +134,7 @@ test { test "a kept segment comes back only for the same text and first flag, and the oldest goes past the cap" { const gpa = std.testing.allocator; - const m = try Memo.create(gpa, 60); + const m = try Memo.create(gpa, 60 + overhead); defer m.destroy(); var ids: std.ArrayList(u32) = .empty; defer ids.deinit(gpa); @@ -135,7 +142,23 @@ test "a kept segment comes back only for the same text and first flag, and the o try std.testing.expect(!try m.append("abcd", true, gpa, &ids)); try std.testing.expect(try m.append("abcd", false, gpa, &ids)); try std.testing.expectEqualSlices(u32, &.{ 1, 2 }, ids.items); - m.put("0123456789012345678901234567890123456789", false, &.{ 3, 4, 5 }); // 52 bytes: "abcd" (12) goes + m.put("0123456789012345678901234567890123456789", false, &.{ 3, 4, 5 }); // 52 bytes and an overhead: "abcd" goes try std.testing.expect(!try m.append("abcd", false, gpa, &ids)); - try std.testing.expectEqual(@as(usize, 52), m.held); + try std.testing.expectEqual(52 + overhead, m.held); +} + +test "each kept segment counts its entry against the cap, so short segments cannot outgrow it" { + const gpa = std.testing.allocator; + const payload = min_bytes + 16 * @sizeOf(u32); // a segment's text and ids alone + const m = try Memo.create(gpa, 10 * payload); + defer m.destroy(); + var text: [min_bytes]u8 = @splat('x'); + for (0..20) |i| { + text[0] = @intCast(i); + m.put(&text, false, &(@as([16]u32, @splat(@intCast(i))))); + } + // ten segments' text and ids no longer fit: their entries and keys count too + try std.testing.expect(m.map.count() < 10); + try std.testing.expectEqual(10 * payload / bytes(min_bytes, 16).?, m.map.count()); + try std.testing.expect(m.held <= m.cap); } diff --git a/zig/src/core/tokenizer/memo_reuse_test.zig b/zig/src/core/tokenizer/memo_reuse_test.zig index 67b148dd066..89ea912ae6a 100644 --- a/zig/src/core/tokenizer/memo_reuse_test.zig +++ b/zig/src/core/tokenizer/memo_reuse_test.zig @@ -1,6 +1,8 @@ //! Memo recency protects successful reads and avoids copying duplicate completed segments. const std = @import("std"); const Memo = @import("memo.zig").Memo; +/// A one-byte segment with one id: what each entry below holds against the cap. +const one = @import("memo.zig").bytes(1, 1).?; const t = std.testing; const a = t.allocator; fn expect(m: *Memo, text: []const u8, first: bool, wanted: ?[]const u32) !void { @@ -11,7 +13,7 @@ fn expect(m: *Memo, text: []const u8, first: bool, wanted: ?[]const u32) !void { if (wanted) |ids| try t.expectEqualSlices(u32, ids, out.items); } test "memo recency: a successful hit protects the oldest insertion from eviction" { - const m = try Memo.create(a, 15); + const m = try Memo.create(a, 3 * one); defer m.destroy(); m.put("a", false, &.{1}); m.put("b", false, &.{2}); @@ -22,11 +24,11 @@ test "memo recency: a successful hit protects the oldest insertion from eviction try expect(m, "a", false, &.{1}); try expect(m, "c", false, &.{3}); try expect(m, "d", false, &.{4}); - try t.expectEqual(@as(usize, 15), m.held); + try t.expectEqual(3 * one, m.held); } test "memo recency: duplicate inserts keep owned IDs with no replacement allocation" { var counted = t.FailingAllocator.init(a, .{}); - const m = try Memo.create(counted.allocator(), 10); + const m = try Memo.create(counted.allocator(), 2 * one); defer m.destroy(); var original = [_]u32{1}; m.put("a", true, &original); @@ -39,11 +41,11 @@ test "memo recency: duplicate inserts keep owned IDs with no replacement allocat try expect(m, "b", true, null); try expect(m, "a", true, &.{1}); try expect(m, "c", true, &.{3}); - try t.expectEqual(@as(usize, 10), m.held); + try t.expectEqual(2 * one, m.held); } test "memo recency: failed reads and mismatched first mode do not promote an entry" { for ([_]bool{ false, true }) |allocation_fails| { - const m = try Memo.create(a, 10); + const m = try Memo.create(a, 2 * one); defer m.destroy(); m.put("a", false, &.{1}); m.put("b", false, &.{2}); @@ -61,7 +63,7 @@ test "memo recency: failed reads and mismatched first mode do not promote an ent } } test "memo recency: links survive map growth and a thousand cold arrivals within the payload bound" { - const m = try Memo.create(a, 48 * 8); + const m = try Memo.create(a, 76 * one); defer m.destroy(); for (0..48) |i| { var text: [4]u8 = undefined; @@ -77,7 +79,7 @@ test "memo recency: links survive map growth and a thousand cold arrivals within try expect(m, "0000", false, &.{0}); try expect(m, "1047", false, &.{1047}); const held = m.held; - m.put("an entry that does not fit", false, &(@as([128]u32, @splat(1)))); + m.put("an entry that does not fit", false, &(@as([76 * one / 4]u32, @splat(1)))); try t.expectEqual(held, m.held); try expect(m, "0000", false, &.{0}); } diff --git a/zig/src/core/tokenizer/tokenizer.zig b/zig/src/core/tokenizer/tokenizer.zig index 4a3108eb326..45e0dcded9f 100644 --- a/zig/src/core/tokenizer/tokenizer.zig +++ b/zig/src/core/tokenizer/tokenizer.zig @@ -259,7 +259,7 @@ pub const Tokenizer = struct { } } - /// encodeText through the memo for a long segment: its kept ids, else encoded and kept. + /// encodeText through the memo for a segment of `min_bytes` or more: its kept ids, else encoded and kept. fn encodeSegment(t: *const Tokenizer, ctx: *steps.Context, text: []const u8, first: bool, ids: *std.ArrayList(u32)) Error!void { const m = t.memo orelse return t.encodeText(ctx, text, first, ids); if (text.len < @import("memo.zig").min_bytes) return t.encodeText(ctx, text, first, ids); diff --git a/zig/src/core/tokenizer/tokenizer_test.zig b/zig/src/core/tokenizer/tokenizer_test.zig index c59bc01be4a..61ae7b5e39a 100644 --- a/zig/src/core/tokenizer/tokenizer_test.zig +++ b/zig/src/core/tokenizer/tokenizer_test.zig @@ -67,6 +67,40 @@ test "with the memo, long segments encode as without it, and the second encode t try std.testing.expectEqual(@as(u64, 2), t.memo.?.hits); // both segments, the second time } +test "the memo keeps a 64-byte segment and tokenizes one under min_bytes each time" { + const json = + \\{"added_tokens":[{"id":7,"content":"<|end|>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true}], + \\ "pre_tokenizer":{"type":"Sequence","pretokenizers":[{"type":"Split","pattern":{"Regex":" ?\\S+|\\s+"},"behavior":"Isolated","invert":false},{"type":"ByteLevel","add_prefix_space":false,"trim_offsets":false,"use_regex":false}]}, + \\ "model":{"type":"BPE","dropout":null,"unk_token":null,"continuing_subword_prefix":"","end_of_word_suffix":"","fuse_unk":false,"byte_fallback":false,"ignore_merges":false, + \\ "vocab":{"a":0,"b":1,"Ġ":2,"ab":3,"Ġa":4,"Ġab":5,"c":6},"merges":[["Ġ","a"],"a b","Ġa b"]}} + ; + const a = std.testing.allocator; + var t = try parse(a, json); + defer t.deinit(); + const under = @import("memo.zig").min_bytes - 1; + const bytes = try a.alloc(u8, @max(64, under)); + defer a.free(bytes); + for (bytes, 0..) |*c, i| c.* = "ab c"[i % 4]; + // 64 bytes, a short chat message, is kept; one byte under the minimum is not + for ([_][]const u8{ bytes[0..64], bytes[0..under] }, [_]u64{ 1, 0 }) |segment, hits| { + const text = try std.mem.concat(a, u8, &.{ "<|end|>", segment, "<|end|>" }); + defer a.free(text); + const plain = try t.encode(a, text); + defer a.free(plain); + t.memo = try Memo.create(a, 1 << 20); + defer { + t.memo.?.destroy(); + t.memo = null; + } + for (0..2) |_| { + const kept = try t.encode(a, text); + defer a.free(kept); + try std.testing.expectEqualSlices(u32, plain, kept); + } + try std.testing.expectEqual(hits, t.memo.?.hits); + } +} + test "a kept segment's ids equal a fresh encode's wherever the segment sits" { const added = \\{"added_tokens":[{"id":20,"content":"<|end|>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true}, @@ -86,9 +120,14 @@ test "a kept segment's ids equal a fresh encode's wherever the segment sits" { , }; const a = std.testing.allocator; + // a long body and a short chat message's, both kept and read back in every position + for ([_]usize{ 200, 10 }) |repeats| try keptEverywhere(a, kinds, repeats); // 1,400 and 70 bytes +} + +fn keptEverywhere(a: std.mem.Allocator, kinds: anytype, repeats: usize) !void { var body: std.ArrayList(u8) = .empty; defer body.deinit(a); - for (0..200) |i| try body.appendSlice(a, if (i % 3 == 0) "ab abc " else "cab ab "); + for (0..repeats) |i| try body.appendSlice(a, if (i % 3 == 0) "ab abc " else "cab ab "); const b = body.items; // first or not, after lstrip and rstrip tokens, with a leading space, around a lossy byte, repeated in one prompt const texts = [_][]const []const u8{ diff --git a/zig/src/families/flashnext/cuda_batch.zig b/zig/src/families/flashnext/cuda_batch.zig index 27dbe914166..bd1b87e63fb 100644 --- a/zig/src/families/flashnext/cuda_batch.zig +++ b/zig/src/families/flashnext/cuda_batch.zig @@ -203,7 +203,7 @@ pub fn Pass(comptime Tri: type) type { try self.tri.hcNormalize(h, pss, hc_w.scale.ptr, norm, eps, n, dims, streams); return hc.readoutNative(self, hc_w, r0, n); } - if (n >= @import("cuda_chunk.zig").readoutTileRows() and self.tri.readoutTilesOwned() and std.meta.eql(keep, HcKeep{})) return tiles.readout(self.tri, self.k, self.stream, self.s, hc_w, r0, n); + if (n >= self.k.forms.readout_rows and self.tri.readoutTilesOwned() and std.meta.eql(keep, HcKeep{})) return tiles.readout(self.tri, self.k, self.stream, self.s, hc_w, r0, n); try self.copy(keep.h, h, n * wide * 2); if (hc_sk * n * hc_w.n_down * 4 > s.hc_part_bytes) return error.UnexpectedTensor; try self.tri.hcDown(h, pss, hc_w.scale.ptr, norm, hc_w.down.w.ptr, hc_w.down.s.ptr, hc_w.down.b.ptr, s.dn, s.hc_part, eps, n, hc_w.n_down, wide, dims, dims / 256, streams, hc_sk); @@ -258,7 +258,7 @@ pub fn Pass(comptime Tri: type) type { try self.copy(keep.hist, self.seq.conv[li].ptr, (gdn.taps - 1) * cd * 2); } // every row's conv, norms and gates, the recurrence, then the gated norm: the one-block chain's bits - const fused = self.lanes.len == 0 and (n >= 64 or marks.inPass(self)) and gdn_fused.on(); + const fused = self.lanes.len == 0 and (n >= 64 or marks.inPass(self)) and self.k.forms.gdn_fused; const cuts = try marks.cuts(self, li, fused); if (fused and keep.log != 0) return error.UnexpectedTensor; if (fused) { diff --git a/zig/src/families/flashnext/cuda_batch_hc.zig b/zig/src/families/flashnext/cuda_batch_hc.zig index a4970fbd155..16648ae0638 100644 --- a/zig/src/families/flashnext/cuda_batch_hc.zig +++ b/zig/src/families/flashnext/cuda_batch_hc.zig @@ -20,7 +20,7 @@ pub fn on() bool { /// Whether hc_w's read-out takes its normed rows from the writeback: native, nothing kept, 64 rows or more, our glue. pub fn fuses(pass: anytype, hc_w: wt.HcW, n: usize, keep: parts.HcKeep) bool { return n >= 64 and hc_w.down.native != null and std.meta.eql(keep, parts.HcKeep{}) and dims == 2560 and - streams == 4 and pass.tri.writebackOwned() and on(); + streams == 4 and pass.tri.writebackOwned() and pass.k.forms.hc_fuse; } /// The pass's pending writeback with hc_w's normalize in the same launch: the normed rows readoutNative reads. diff --git a/zig/src/families/flashnext/cuda_batch_kernels.zig b/zig/src/families/flashnext/cuda_batch_kernels.zig index db222615eef..548a10b6ccc 100644 --- a/zig/src/families/flashnext/cuda_batch_kernels.zig +++ b/zig/src/families/flashnext/cuda_batch_kernels.zig @@ -34,7 +34,27 @@ pub const Gdn = struct { } }; +/// The prompt pass's kernel forms, each switch read once at load: the pass and the disk key read these. +pub const Forms = struct { + gdn_fused: bool = true, // TF_FLASHNEXT_GDN_FUSED + hc_fuse: bool = true, // TF_FLASHNEXT_HC_FUSE + in_pass: bool = true, // TF_FLASHNEXT_KEEP_INPASS + readout_rows: usize = 64, // TF_FLASHNEXT_READOUT_ROWS (maxInt: never) + fact_rows: usize = 64, // TF_FLASHNEXT_FACT_ROWS (maxInt: never) + + pub fn resolve() Forms { + return .{ + .gdn_fused = @import("cuda_gdn_fused.zig").on(), + .hc_fuse = @import("cuda_batch_hc.zig").on(), + .in_pass = @import("cuda_lanes_snap.zig").keepInPass(), + .readout_rows = @import("cuda_chunk.zig").readoutTileRows(), + .fact_rows = @import("cuda_nvfp4_tile.zig").factRows(), + }; + } +}; + pub const Kernels = struct { + forms: Forms = .{}, qmm: cuda.Module, experts: cuda.Module, rows: cuda.Module, @@ -77,6 +97,7 @@ pub const Kernels = struct { if (!cuda.kernels.available) return error.BuiltWithoutKernels; const tile_mode = try cuda.experts_tile.mode(if (std.c.getenv("TF_FLASHNEXT_PROMPT_EXPERT_TILE")) |v| std.mem.span(v) else null); var k: Kernels = undefined; + k.forms = Forms.resolve(); k.expert_tile = null; k.qmm = try cuda.Module.load(d, cuda.kernels.qmm); errdefer k.qmm.unload(); diff --git a/zig/src/families/flashnext/cuda_chunk.zig b/zig/src/families/flashnext/cuda_chunk.zig index e30bcdb67a3..07c2c4ba61a 100644 --- a/zig/src/families/flashnext/cuda_chunk.zig +++ b/zig/src/families/flashnext/cuda_chunk.zig @@ -33,15 +33,10 @@ pub fn passRows(lanes: anytype, own: anytype, solo: usize, busy: usize) usize { return solo_chunk.passRows(lanes, own, "filled", solo, busy); } -var readout_rows: ?usize = null; - -/// Rows from which a read-out takes the tiles (TF_FLASHNEXT_READOUT_ROWS, default 64, 0 never): same bits, only speed. +/// Rows from which a read-out takes the tiles (TF_FLASHNEXT_READOUT_ROWS, default 64, 0 never), read once at load. pub fn readoutTileRows() usize { - if (readout_rows == null) { - const r = if (std.c.getenv("TF_FLASHNEXT_READOUT_ROWS")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch 64 else 64; - readout_rows = if (r == 0) std.math.maxInt(usize) else r; - } - return readout_rows.?; + const r = if (std.c.getenv("TF_FLASHNEXT_READOUT_ROWS")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch 64 else 64; + return if (r == 0) std.math.maxInt(usize) else r; } test "TF_FLASHNEXT_CHUNK takes 1 to the largest measured pass and refuses the rest" { diff --git a/zig/src/families/flashnext/cuda_disk.zig b/zig/src/families/flashnext/cuda_disk.zig index dc2e032e2cd..fcf1dd94587 100644 --- a/zig/src/families/flashnext/cuda_disk.zig +++ b/zig/src/families/flashnext/cuda_disk.zig @@ -139,6 +139,43 @@ pub fn Kept(comptime F: type) type { pub fn facts(target: *anyopaque) [1]u64 { return .{@intFromBool(of(target).head != null)}; } + + /// The native key extends with policyOf under this domain (native/cuda_disk.zig keptKey). + pub const policy_domain = "flash-cuda-policy-v1"; + pub fn policy(target: *anyopaque) [13]u64 { + return policyOf(of(target)); + } + }; +} + +/// What a prompt pass that writes a kept state was resolved with at load: its rows, kernel forms and expert grids. +pub fn policyOf(c: anytype) [13]u64 { + const e = c.engine; + const k = &e.batch_k; + const f = k.forms; + var grids = std.hash.Wyhash.init(0); // resident blocks a grid takes, which pick the experts' decode forms + grids.update(std.mem.asBytes(&k.nvfp4.resident)); + grids.update(std.mem.asBytes(&k.fp8.resident)); + if (k.expert_tile) |x| grids.update(std.mem.asBytes(&x.resident)); + grids.update(std.mem.asBytes(&k.native_lane.prompt_sms)); // a BF16 prompt tile runs over half these SMs' worth + return .{ + // TF_FLASHNEXT_CHUNK_SOLO and _CHUNK as resolved: a pass's rows alone, and beside a decoding stream + e.chunk, + e.busy_chunk, + @intFromBool(f.gdn_fused), + @intFromBool(f.hc_fuse), + @intFromBool(f.in_pass), + f.readout_rows, + f.fact_rows, + // TF_FLASHNEXT_PROMPT_EXPERT_TILE, _PROMPT_BF16 and TF_NVFP4_DECODE_WARPS as the kernels loaded + if (k.expert_tile) |x| 1 + @as(u64, @backingInt(x.selection)) else 0, + @intFromBool(k.native_lane.prompt != null), + // TF_QMMF_HALF_BELOW: a pass of 16 rows or fewer takes the lane's 32-column BF16 and MXFP8 tile below it + k.native_lane.half_below, + k.nvfp4.warps, + grids.final(), + // a captured set in use, and the entries TF_FLASHNEXT_OWNED runs on our glue beside it + if (c.set != null) 1 + @as(u64, c.glue.mixed) else 0, }; } diff --git a/zig/src/families/flashnext/cuda_lanes_snap.zig b/zig/src/families/flashnext/cuda_lanes_snap.zig index ffd73fd4423..9666c28debd 100644 --- a/zig/src/families/flashnext/cuda_lanes_snap.zig +++ b/zig/src/families/flashnext/cuda_lanes_snap.zig @@ -4,14 +4,14 @@ const lanes = @import("lanes"); const snap = @import("cuda_snap.zig"); const parts = @import("cuda_batch_state.zig"); +/// Marks inside a chunk kept without cutting the pass (TF_FLASHNEXT_KEEP_INPASS=0: cut there), read once at load. +pub fn keepInPass() bool { + const v = std.c.getenv("TF_FLASHNEXT_KEEP_INPASS") orelse return true; + return !std.mem.eql(u8, std.mem.span(v), "0"); +} + pub fn Snaps(comptime Cuda: type) type { return struct { - /// Prompt cache marks inside a chunk kept without cutting the pass (TF_FLASHNEXT_KEEP_INPASS=0: cut there). - pub fn keepInPass() bool { - const v = std.c.getenv("TF_FLASHNEXT_KEEP_INPASS") orelse return true; - return !std.mem.eql(u8, std.mem.span(v), "0"); - } - /// The n-gram history (the last two tokens) at position `to` of a pass from `from` that began at `old`. pub fn historyAt(old: [2]i64, ids: []const u32, from: usize, to: usize) [2]i64 { if (to - from >= 2) return .{ ids[to - 2], ids[to - 1] }; @@ -22,7 +22,8 @@ pub fn Snaps(comptime Cuda: type) type { /// The chunk's stop: the first cache mark in [at, stop0) it cannot keep on the way; kept ones into `marks`. pub fn cut(self: *Cuda, s: *lanes.Stream, l: anytype, ids: []const u32, at: usize, stop0: usize, marks: *[parts.max_marks]parts.Mark) struct { stop: usize, kept: usize } { var n: usize = 0; - const inpass = keepInPass() and self.ranks == null and l.seq.media == null and @import("cuda_gdn_fused.zig").on(); + const forms = self.engine.batch_k.forms; // TF_FLASHNEXT_KEEP_INPASS and _GDN_FUSED as the load read them + const inpass = forms.in_pass and self.ranks == null and l.seq.media == null and forms.gdn_fused; for (s.reuse.marks) |m| if (m > at and m < stop0) { if (inpass and n < parts.max_marks) { if (snap.prepare(self.gpa, self.engine.driver, m, historyAt(l.seq.history, ids, at, m), l.draft != null, l.seq.heads)) |p| { diff --git a/zig/src/families/flashnext/cuda_moe_native.zig b/zig/src/families/flashnext/cuda_moe_native.zig index 3c5402bfcc0..d6b58e3d57c 100644 --- a/zig/src/families/flashnext/cuda_moe_native.zig +++ b/zig/src/families/flashnext/cuda_moe_native.zig @@ -23,7 +23,7 @@ pub fn run(self: anytype, native: *const mixed.Owned, n: usize, pairs: usize, pl const side = try shared.fork(self, native, n); switch (owned.format) { .nvfp4 => { - const pt = nvfp4_tile.size(n); + const pt = nvfp4_tile.size(self.k, n); try self.k.router.route(self.stream, picks, pairs, e, pt, plan); const items = cuda.grouped.maxItems(pairs, e, pt); try nvfp4_tile.run(self.k, pt, self.stream, .up, .{ .x = s.mixed, .stride = dims, .slots = slots }, owned.view(), plan, s.moe_act, items, skip); @@ -53,7 +53,7 @@ fn ownPicks(self: anytype, picks: u64, out: u64, pairs: usize, first: usize, cou pub fn fp8(k: *const Kernels, stream: cuda.Stream, picks: u64, x: u64, layer: cuda.experts.Layer, plan: cuda.grouped.Plan, pairs: usize, n: usize, out: u64, act: u64) !void { if (layer.format != .fp8g) return error.UnsupportedQuantization; const e = experts_n + 1; - const prompt = nvfp4_tile.size(n) != 16; + const prompt = nvfp4_tile.size(k, n) != 16; const tile: usize = if (prompt) cuda.experts.promptTile(.fp8g) else 16; try k.router.route(stream, picks, pairs, e, tile, plan); const items = cuda.grouped.maxItems(pairs, e, tile); diff --git a/zig/src/families/flashnext/cuda_nvfp4_tile.zig b/zig/src/families/flashnext/cuda_nvfp4_tile.zig index 1340c1c8ebc..075b30ea327 100644 --- a/zig/src/families/flashnext/cuda_nvfp4_tile.zig +++ b/zig/src/families/flashnext/cuda_nvfp4_tile.zig @@ -2,20 +2,15 @@ const std = @import("std"); const cuda = @import("cuda"); -var fact_rows: ?usize = null; - -/// Rows from which NVFP4 experts take the prompt tiles (TF_FLASHNEXT_FACT_ROWS, 0 never): same bits, only speed. -fn factRows() usize { - if (fact_rows == null) { - const r = if (std.c.getenv("TF_FLASHNEXT_FACT_ROWS")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch 64 else 64; - fact_rows = if (r == 0) std.math.maxInt(usize) else r; - } - return fact_rows.?; +/// Rows from which NVFP4 experts take the prompt tiles (TF_FLASHNEXT_FACT_ROWS, 0 never), read once at load. +pub fn factRows() usize { + const r = if (std.c.getenv("TF_FLASHNEXT_FACT_ROWS")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch 64 else 64; + return if (r == 0) std.math.maxInt(usize) else r; } /// Pairs a routed item holds for an n-row pass: the prompt tile's, an expert's weights read once an item, or 16. -pub fn size(n: usize) usize { - return if (n >= factRows()) cuda.experts.promptTile(.nvfp4) else 16; +pub fn size(k: anytype, n: usize) usize { + return if (n >= k.forms.fact_rows) cuda.experts.promptTile(.nvfp4) else 16; } /// Prompt tiles may select the K32 pipeline; decode calls take the decode form in equal waves; same bits. diff --git a/zig/src/families/glm/prompt.zig b/zig/src/families/glm/prompt.zig index 4c15ae0c6ef..d2f8e748395 100644 --- a/zig/src/families/glm/prompt.zig +++ b/zig/src/families/glm/prompt.zig @@ -560,10 +560,9 @@ pub fn mtp(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, h: Ref, n fwd.inject(x, e, p.m_emb, M, pos + 1); // the head reads each row's next token: an image's rows one place on fwd.rms(x, e, p.m_emb, m.enorm, p.m_eh, M, D, D, 2 * D, c.eps); fwd.rms(x, e, h, m.hnorm, p.m_eh.at(@as(usize, D) * 2), M, D, D, 2 * D, c.eps); - // eh_proj defaults to the tile kernel (glm_rows_bf16_nax, fp64 receipt eh_check); GLM_EHPROJ_NAX=0 selects scalar. - const eh_nax = if (std.c.getenv("GLM_EHPROJ_NAX")) |v| v[0] != '0' else true; + // eh_proj on the tile kernel (glm_rows_bf16_nax, receipt eh_check); scalar where the load built none (wide.zig) if (m.eh_bf16) |eh| { - if (eh_nax) wide.bf16Nax(&p.mm.wide.?, e, eh, D, 2 * D, .{ .in = p.m_eh, .ldx = 2 * D, .out = p.m_x, .ldo = D, .rows = M }) else wide.bf16(&p.mm.wide.?, e, eh, D, 2 * D, .{ .in = p.m_eh, .ldx = 2 * D, .out = p.m_x, .ldo = D, .rows = M }); + wide.bf16Nax(&p.mm.wide.?, e, eh, D, 2 * D, .{ .in = p.m_eh, .ldx = 2 * D, .out = p.m_x, .ldo = D, .rows = M }); } else qmm(p, e, p.m_eh, m.eh_proj, p.m_x, M); fwd.rms(x, e, p.m_x, L.in_norm, p.m_xn, M, D, D, D, c.eps); qmm(p, e, p.m_xn, L.attn.mla.x_proj, p.xp, M); diff --git a/zig/src/families/glm/wide.zig b/zig/src/families/glm/wide.zig index 336b5199216..67e391e8b4b 100644 --- a/zig/src/families/glm/wide.zig +++ b/zig/src/families/glm/wide.zig @@ -31,7 +31,7 @@ pub const Pipes = struct { moe_glu: [nw]mtl.Pipeline, // the same through gate and up, SwiGLU'd gather: [2]mtl.Pipeline, // four gathered rows sharing the sorted row arithmetic bf16: mtl.Pipeline, // an unquantized matrix (the MTP head's eh_proj, scalar path; decode-side path keeps this) - bf16_nax: ?mtl.Pipeline, // bf16 GEMM on tensor units: prefill-side eh_proj replacement for `bf16` + bf16_nax: ?mtl.Pipeline, // bf16 GEMM on tensor units: prefill-side eh_proj replacement for `bf16` (null: `bf16` serves) kda_pre: mtl.Pipeline, // kda_rows reading f_b's and g_b's products made apart (any width but 4/64) kda_fg: [nw]mtl.Pipeline, // kda_rows making f_b's and g_b's dots of one width (g64) as glm_rows does: .pre's bits embed: [2]mtl.Pipeline, // the embedding at 6 and 8 bits, groups of 64 @@ -141,6 +141,7 @@ fn build(gpa: std.mem.Allocator, device: mtl.Device, kda: []const u8, made: *Mad const pool = mtl.objc.Pool.push(); defer pool.pop(); var p: Pipes = undefined; + const eh_tile = try @import("sys").environment.read(bool, "GLM_EHPROJ_NAX", true); // 0: no tile pipeline, `bf16` serves var h = std.hash.Wyhash.init(0x77); const rows_src = try gpa.dupe(u8, gather_source); defer gpa.free(rows_src); @@ -161,7 +162,7 @@ fn build(gpa: std.mem.Allocator, device: mtl.Device, kda: []const u8, made: *Mad } p.bf16 = try made.add(device, l, "glm_rows_bf16"); for (gather.names, &p.gather) |name, *pipe| pipe.* = try made.add(device, l, name); - p.bf16_nax = made.add(device, l, "glm_rows_bf16_nax") catch blk: { + p.bf16_nax = if (!eh_tile) null else made.add(device, l, "glm_rows_bf16_nax") catch blk: { std.log.warn("glm: the eh_proj tile kernel cannot build here; eh_proj serves on the scalar path", .{}); break :blk null; }; diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index f026411d516..5c5f3360fc3 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -77,6 +77,7 @@ pub const Metal = struct { masks: ?Masks = null, // structured output's bits (grammar.zig), made at the first structured request living: ?@import("adapters.zig").Sites = null, // the saved lessons' gated blocks, until a learner takes them trace: bool = false, // TF_SLIDE_TRACE: each reply's lesson scores logged (dev) + coop_split: bool = true, // TF_COOP_SPLIT as forward.zig resolves it at load: in, out and eh K slices a threadgroup residency: ?mtl.ResidencySet.Follow = null, kv_arena: ?mtl.Buffer = null, // TF_NEMOTRON_METAL_KV_PAGES: every page, in the residency set kv_tables: ?mtl.Buffer = null, // and every lane's page table @@ -98,6 +99,7 @@ pub const Metal = struct { .prompt = try m.device.buffer(@max(o.capacity, 16) * 4, opts), .fence = try Fence.init(m.device), .trace = platform.c.getenv("TF_SLIDE_TRACE") != null, + .coop_split = fwd.splitOn(), }; if (o.chunk > fused_rows) b.wide = try prefill.Prefill.init(m, @min(o.chunk, o.capacity)); if (o.drafts and m.weights.mtp != null) b.head = try mtp.Head.init(m.device, m.config, &m.kernels, &m.weights, &b.pool, max_lanes, o.capacity); diff --git a/zig/src/families/nemotron/cuda_engine.zig b/zig/src/families/nemotron/cuda_engine.zig index b3ea1b2c268..34de99beea9 100644 --- a/zig/src/families/nemotron/cuda_engine.zig +++ b/zig/src/families/nemotron/cuda_engine.zig @@ -78,7 +78,7 @@ pub const Engine = struct { b: state.Buffers, c: Config, max_len: usize, - nch: usize = 0, // attention chunk programs a row: a captured _chunk variant's NCH covering max_len (bits ignore it) + nch: usize = 0, // attention chunk programs a row: a captured _chunk variant's NCH covering max_len (keyed then) pinned: cuda.HostBuffer, history: cuda.HostBuffer, // mapped: a serial round's kernel writes its token here, by position history_dev: u64 = 0, diff --git a/zig/src/families/nemotron/forward.zig b/zig/src/families/nemotron/forward.zig index f8d1d5da397..c7ba192df0d 100644 --- a/zig/src/families/nemotron/forward.zig +++ b/zig/src/families/nemotron/forward.zig @@ -439,8 +439,8 @@ fn splits(comptime key: []const u8) bool { var split_mode: enum(u8) { unread, on, off } = .unread; -/// TF_COOP_SPLIT=0 keeps one threadgroup a column tile, as the Python engine dispatches. -fn splitOn() bool { +/// TF_COOP_SPLIT=0 keeps one threadgroup a column tile, as the Python engine dispatches (read once a process). +pub fn splitOn() bool { if (split_mode == .unread) { const v = platform.c.getenv("TF_COOP_SPLIT"); split_mode = if (v != null and v.?[0] == '0') .off else .on; diff --git a/zig/src/families/qwen3_5/cuda_disk.zig b/zig/src/families/qwen3_5/cuda_disk.zig index 690a01d43ef..b1b18befaf9 100644 --- a/zig/src/families/qwen3_5/cuda_disk.zig +++ b/zig/src/families/qwen3_5/cuda_disk.zig @@ -148,9 +148,17 @@ pub fn probe(a: Allocator, io: std.Io, backend: lanes.backend.Backend, t: *Targe return .{ .hash = h.final(), .rate = @as(f64, @floatFromInt(toks.len)) / (@as(f64, @floatFromInt(@max(ns, 1))) / 1e9) }; } -/// What else the states depend on: the cache format, whether a drafter set the target's taps, int8 prompt projections. -pub fn facts(t: *const Target) [3]u64 { - return .{ @backingInt(reuse.formatOf(t.e)), @intFromBool(t.e.n_taps > 0), @intFromBool(t.e.int8.on) }; +/// What else the states depend on: the cache format, target taps, int8 projections and rotary inputs. +pub fn facts(t: *const Target) [4]u64 { + var rope = std.hash.Wyhash.init(0x726f7065); + switch (t.e.g.rope) { + .plain => rope.update("plain"), + .yarn => |y| { + rope.update("yarn"); + rope.update(std.mem.asBytes(&y.table)); // the actual kernel inputs, independent of a finite probe + }, + } + return .{ @backingInt(reuse.formatOf(t.e)), @intFromBool(t.e.n_taps > 0), @intFromBool(t.e.int8.on), rope.final() }; } test { diff --git a/zig/src/native/cuda_disk.zig b/zig/src/native/cuda_disk.zig index 982ebc4abd2..4ff1ee1e14b 100644 --- a/zig/src/native/cuda_disk.zig +++ b/zig/src/native/cuda_disk.zig @@ -5,6 +5,7 @@ const api = @import("engine_api"); const lanes = @import("lanes"); const nemotron = @import("nemotron"); const disk_identity = @import("disk_identity.zig"); +const persistence_policy = @import("persistence_policy.zig"); const kept = nemotron.native.kept_states; const rows = api.prompt_cache.rows; const Target = kept.Target; @@ -91,7 +92,42 @@ fn whole(_: *anyopaque, saved: api.prompt_cache.Saved) bool { /// What disk states are read under: the checkpoint, kernels (ours or a captured set), driver, device, a probe's bits. pub fn identity(a: Allocator, io: std.Io, g: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, backend: lanes.backend.Backend, t: *Target, family: []const u8) !struct { id: u64, rate: f64 } { const p = try probe(a, io, backend, t); - return .{ .id = try identityOf(a, io, g, dir, kernels, &[_]u64{@intFromBool(t.head != null)}, p.hash, .{ .family = family, .backend = "cuda" }), .rate = p.rate }; + const id = try identityOf(a, io, g, dir, kernels, &[_]u64{@intFromBool(t.head != null)}, p.hash, .{ .family = family, .backend = "cuda" }); + return .{ .id = withPolicy(id, t.e), .rate = p.rate }; +} + +/// Nemotron's key past its probe: the checkpoint math, expert ranks and kernel choices the load resolved. +pub fn withPolicy(legacy: u64, e: anytype) u64 { + const k = &e.k; + var grids = std.hash.Wyhash.init(0); // resident blocks a grid takes, from this GPU's SM count + grids.update(std.mem.asBytes(&k.experts.resident)); + if (k.modelopt) |m| grids.update(std.mem.asBytes(&m.experts.resident)); + if (k.ck) |c| { + grids.update(std.mem.asBytes(&c.resident)); + grids.update(std.mem.asBytes(&c.prompt_resident)); + } + return persistence_policy.extend(legacy, "nemotron-cuda-policy-v1", &.{ + // --precision checkpoint's FP4 and FP8 math, and the expert ranks of TF_NEMOTRON_WORLD + @intFromBool(e.c.ck), + e.c.world, + // a ModelOpt checkpoint's NVFP4 decode form (TF_NVFP4_DECODE_WARPS) + if (k.modelopt) |m| m.experts.warps else 0, + grids.final(), + // TF_QMMF_HALF_BELOW on a ModelOpt checkpoint's lane: the 32-column tile for passes of 16 rows or fewer + if (k.modelopt) |m| m.lane.half_below else 0, + // --context: the captured _chunk and _merge variant whose NCH covers it (our merge reads a row's own chunks) + if (k.triton != null) e.nch else 0, + }); +} + +/// A disk module's key: the shared identity over its facts, extended with its resolved policy when it declares one. +pub fn keptKey(comptime K: type, a: Allocator, io: std.Io, g: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, owner: anytype, probed: u64, profile: disk_identity.Profile) !u64 { + const facts = K.facts(owner); // an array, or a slice + const list: []const u64 = if (@typeInfo(@TypeOf(facts)) == .pointer) facts else &facts; + const id = try identityOf(a, io, g, dir, kernels, list, probed, profile); + if (comptime !@hasDecl(K, "policy")) return id; + const resolved = K.policy(owner); + return persistence_policy.extend(id, K.policy_domain, &resolved); } /// The identity's hash: the checkpoint, kernels, device, driver, a family's facts, then its probe's hash. @@ -173,10 +209,8 @@ pub fn attachKept(comptime K: type, name: []const u8, a: Allocator, io: std.Io, if (comptime @hasDecl(K, "attach")) return K.attach(a, io, ctx, o, root, kernels, loaded, store) else { if (@hasDecl(K, "bind")) K.bind(loaded.target, ctx); // the context the store's copies make current const p = try K.probe(a, io, loaded.backend, loaded.target); - const facts = K.facts(loaded.target); // an array, or a slice - const list: []const u64 = if (@typeInfo(@TypeOf(facts)) == .pointer) facts else &facts; const staging = stagingOf(K, loaded.target); - try open(o, root, try identityOf(a, io, ctx, o.dir, kernels, list, p.hash, .{ .family = name, .backend = "cuda" }), p.rate, store, name, staging); + try open(o, root, try keptKey(K, a, io, ctx, o.dir, kernels, loaded.target, p.hash, .{ .family = name, .backend = "cuda" }), p.rate, store, name, staging); } } diff --git a/zig/src/native/cuda_disk_identity_test.zig b/zig/src/native/cuda_disk_identity_test.zig index 559151f0986..107fd664053 100644 --- a/zig/src/native/cuda_disk_identity_test.zig +++ b/zig/src/native/cuda_disk_identity_test.zig @@ -264,3 +264,7 @@ test "disk identity: DeepSeek values hash their exact bytes and leave every othe }; } } + +test { + _ = @import("cuda_disk_policy_test.zig"); +} diff --git a/zig/src/native/cuda_disk_policy_test.zig b/zig/src/native/cuda_disk_policy_test.zig new file mode 100644 index 00000000000..bfb77eb73b6 --- /dev/null +++ b/zig/src/native/cuda_disk_policy_test.zig @@ -0,0 +1,300 @@ +//! The actual CUDA family facts and shared key reopen real disk states without a GPU. +const std = @import("std"); +const cuda = @import("cuda"); +const qwen = @import("qwen35"); +const disk = @import("cuda_disk.zig"); +const fixture = @import("persistence_fixture.zig"); +const t = std.testing; + +const Driver = struct { + fn name(out: [*]u8, _: c_int, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + @memcpy(out[0..5], "fake\x00"); + return 0; + } + fn attribute(out: *c_int, _: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = 12; + return 0; + } + fn version(out: *c_int) callconv(.c) cuda.abi.Result { + out.* = 13000; + return 0; + } +}; + +fn ropeMiss(comptime F: type) !void { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator); + defer t.allocator.free(dir); + try tmp.dir.writeFile(t.io, .{ .sub_path = "config.json", .data = "{}" }); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + var driver: cuda.Driver = undefined; + driver.api.cuDeviceGetName = Driver.name; + driver.api.cuDeviceGetAttribute = Driver.attribute; + driver.api.cuDriverGetVersion = Driver.version; + const gpu: cuda.Context = .{ .d = &driver, .device = 0, .handle = null }; + var e: qwen.Engine = undefined; + e.kv8 = false; + e.n_taps = 0; + e.int8.on = false; + e.g.rope = .plain; + var target: qwen.reuse.Target = .{ .e = &e, .caches = undefined, .seen = undefined }; + const profile: @import("disk_identity.zig").Profile = .{ .family = F.model_type, .backend = "cuda" }; + const before = try disk.identityOf(arena.allocator(), t.io, &gpu, dir, null, &F.kept_disk.facts(&target), 42, profile); + const matching = try disk.identityOf(arena.allocator(), t.io, &gpu, dir, null, &F.kept_disk.facts(&target), 42, profile); + e.g.rope = .{ .yarn = .{ .factor = 4, .trained = 262144, .table = @splat(1) } }; + const scaled = try disk.identityOf(arena.allocator(), t.io, &gpu, dir, null, &F.kept_disk.facts(&target), 42, profile); + e.g.rope.yarn.table[17] = 2; + const changed_table = try disk.identityOf(arena.allocator(), t.io, &gpu, dir, null, &F.kept_disk.facts(&target), 42, profile); + try fixture.misses(before, matching, &.{ scaled, changed_table }); + try t.expect(scaled != changed_table); +} + +test "disk identity: dense Qwen CUDA rotary policy misses with the same probe" { + try ropeMiss(qwen.native); +} + +test "disk identity: MoE Qwen CUDA rotary policy misses with the same probe" { + try ropeMiss(qwen.native_moe); +} + +fn indexedMiss(comptime family: []const u8) !void { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a); + try tmp.dir.createDirPath(t.io, "tensors"); + try tmp.dir.writeFile(t.io, .{ .sub_path = "config.json", .data = "{}" }); + try tmp.dir.writeFile(t.io, .{ .sub_path = "model.safetensors.index.json", .data = "{\"weight_map\":{\"unprobed.weight\":\"tensors/native-QB.safetensors\"}}" }); + const header = "{\"unprobed.weight\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,4]}}"; + var shard: [8 + header.len + 4]u8 = @splat(0); + std.mem.writeInt(u64, shard[0..8], header.len, .little); + @memcpy(shard[8..][0..header.len], header); + try tmp.dir.writeFile(t.io, .{ .sub_path = "tensors/native-QB.safetensors", .data = &shard }); + var driver: cuda.Driver = undefined; + driver.api.cuDeviceGetName = Driver.name; + driver.api.cuDeviceGetAttribute = Driver.attribute; + driver.api.cuDriverGetVersion = Driver.version; + const gpu: cuda.Context = .{ .d = &driver, .device = 0, .handle = null }; + const profile: @import("disk_identity.zig").Profile = .{ .family = family, .backend = "cuda" }; + const before = try disk.identityOf(a, t.io, &gpu, dir, null, &.{1}, 42, profile); + const same = try disk.identityOf(a, t.io, &gpu, dir, null, &.{1}, 42, profile); + shard[shard.len - 1] = 1; + try fixture.rewrite(tmp.dir, "tensors/native-QB.safetensors", &shard); + try fixture.misses(before, same, &.{try disk.identityOf(a, t.io, &gpu, dir, null, &.{1}, 42, profile)}); + try tmp.dir.deleteFile(t.io, "tensors/native-QB.safetensors"); + try t.expectError(error.IndexedShardMissing, disk.identityOf(a, t.io, &gpu, dir, null, &.{1}, 42, profile)); +} + +test "disk identity: Nemotron CUDA indexed shard misses with the same probe" { + try indexedMiss("nemotron_h"); +} +test "disk identity: dense Qwen CUDA indexed shard misses with the same probe" { + try indexedMiss("qwen3_5"); +} +test "disk identity: MoE Qwen CUDA indexed shard misses with the same probe" { + try indexedMiss("qwen3_5_moe"); +} +test "disk identity: Flash Next CUDA indexed shard misses with the same probe" { + try indexedMiss("qwen4_exp"); +} + +/// A checkpoint folder and a recording device: what the shared key reads besides a family's words. +const Fixture = struct { + tmp: std.testing.TmpDir, + arena: std.heap.ArenaAllocator, + dir: []const u8, + driver: cuda.Driver, + + fn init(x: *Fixture) !void { + x.tmp = t.tmpDir(.{}); + x.arena = .init(t.allocator); + x.dir = try x.tmp.dir.realPathFileAlloc(t.io, ".", x.arena.allocator()); + try x.tmp.dir.writeFile(t.io, .{ .sub_path = "config.json", .data = "{}" }); + x.driver.api.cuDeviceGetName = Driver.name; + x.driver.api.cuDeviceGetAttribute = Driver.attribute; + x.driver.api.cuDriverGetVersion = Driver.version; + } + fn deinit(x: *Fixture) void { + x.arena.deinit(); + x.tmp.cleanup(); + } + fn gpu(x: *Fixture) cuda.Context { + return .{ .d = &x.driver, .device = 0, .handle = null }; + } +}; + +const flash = @import("flashnext").native; + +fn flashKey(x: *Fixture, c: *flash.Cuda) !u64 { + const g = x.gpu(); + const profile: @import("disk_identity.zig").Profile = .{ .family = flash.model_type, .backend = "cuda" }; + return disk.keptKey(flash.kept_disk, x.arena.allocator(), t.io, &g, x.dir, null, @as(*anyopaque, c), 42, profile); +} + +test "disk identity: Flash Next CUDA resolved prompt rows, kernel forms and expert grids miss with the same probe" { + var x: Fixture = undefined; + try x.init(); + defer x.deinit(); + var e: @typeInfo(@FieldType(flash.Cuda, "engine")).pointer.child = undefined; + e.chunk = 8192; + e.busy_chunk = 1536; + const k = &e.batch_k; + k.forms = .{}; + k.expert_tile = null; + k.native_lane.prompt = null; + k.native_lane.prompt_sms = 0; + k.native_lane.half_below = cuda.qmmf.half_below_default; + k.nvfp4.warps = 4; + k.nvfp4.resident = @splat(48); + k.fp8.resident = @splat(@splat(48)); + var c: flash.Cuda = undefined; + c.engine = &e; + c.head = null; + c.set = null; + c.glue.mixed = 0; + c.depth = 6; + c.parts.on = true; + const before = try flashKey(&x, &c); + var changed: std.ArrayList(u64) = .empty; + defer changed.deinit(t.allocator); + inline for (.{ "chunk", "busy_chunk" }) |field| { // another chunk height, solo or beside a decoding stream + @field(e, field) += 512; + try changed.append(t.allocator, try flashKey(&x, &c)); + @field(e, field) -= 512; + } + inline for (.{ "gdn_fused", "hc_fuse", "in_pass" }) |field| { + @field(k.forms, field) = false; + try changed.append(t.allocator, try flashKey(&x, &c)); + @field(k.forms, field) = true; + } + inline for (.{ "readout_rows", "fact_rows" }) |field| { + @field(k.forms, field) = std.math.maxInt(usize); // 0 set: never the tiles + try changed.append(t.allocator, try flashKey(&x, &c)); + @field(k.forms, field) = 64; + } + k.expert_tile = .{ .mod = undefined, .fns = undefined, .resident = .{ 64, 64 }, .selection = .up }; + const up = try flashKey(&x, &c); + k.expert_tile.?.selection = .both; // the same grids: the selection alone moves the key + const both = try flashKey(&x, &c); + try t.expect(up != both); + try changed.appendSlice(t.allocator, &.{ up, both }); + k.expert_tile = null; + k.native_lane.prompt = @as([2][2]cuda.Function, undefined); // TF_FLASHNEXT_PROMPT_BF16's tiles loaded + const tiles = try flashKey(&x, &c); + k.native_lane.prompt_sms = 48; // the SMs those tiles' blocks are weighed against, on the same expert grids + const weighed = try flashKey(&x, &c); + try t.expect(tiles != weighed); + try changed.appendSlice(t.allocator, &.{ tiles, weighed }); + k.native_lane.prompt = null; + k.native_lane.prompt_sms = 0; + k.native_lane.half_below = 0; // TF_QMMF_HALF_BELOW=0: a short pass's BF16 and MXFP8 rows on the 64-column tile + try changed.append(t.allocator, try flashKey(&x, &c)); + k.native_lane.half_below = cuda.qmmf.half_below_default; + k.nvfp4.warps = 1; + try changed.append(t.allocator, try flashKey(&x, &c)); + k.nvfp4.warps = 4; + k.nvfp4.resident[0] = 47; // another SM count under the same device name + try changed.append(t.allocator, try flashKey(&x, &c)); + k.nvfp4.resident[0] = 48; + c.glue.mixed = 3; // without a captured set our glue runs every entry anyway + try t.expectEqual(before, try flashKey(&x, &c)); + c.set = @as(cuda.aot.Set, undefined); + try changed.append(t.allocator, try flashKey(&x, &c)); + c.glue.mixed = 0; + try changed.append(t.allocator, try flashKey(&x, &c)); + c.set = null; + c.depth = 3; // a draft chain's length and lane buffers' reuse touch no prompt pass + c.parts.on = false; + try fixture.misses(before, try flashKey(&x, &c), changed.items); +} + +test "disk identity: Flash Next CUDA prompt forms take each setting's value at load" { + const env = @import("sys").env; + const Engine = @typeInfo(@FieldType(flash.Cuda, "engine")).pointer.child; + const Forms = @FieldType(@FieldType(Engine, "batch_k"), "forms"); + const names = [_][:0]const u8{ "TF_FLASHNEXT_GDN_FUSED", "TF_FLASHNEXT_HC_FUSE", "TF_FLASHNEXT_KEEP_INPASS", "TF_FLASHNEXT_READOUT_ROWS", "TF_FLASHNEXT_FACT_ROWS" }; + for (names) |n| _ = env.unsetenv(n); + defer for (names) |n| { + _ = env.unsetenv(n); + }; + try t.expectEqualDeep(Forms{}, Forms.resolve()); + for (names) |n| _ = env.setenv(n, "0", 1); + const never = std.math.maxInt(usize); + try t.expectEqualDeep(Forms{ .gdn_fused = false, .hc_fuse = false, .in_pass = false, .readout_rows = never, .fact_rows = never }, Forms.resolve()); + _ = env.setenv("TF_FLASHNEXT_READOUT_ROWS", "128", 1); + _ = env.setenv("TF_FLASHNEXT_FACT_ROWS", "32", 1); + try t.expectEqual(@as(usize, 128), Forms.resolve().readout_rows); + try t.expectEqual(@as(usize, 32), Forms.resolve().fact_rows); +} + +const nemotron = @import("nemotron"); + +fn nemotronKey(x: *Fixture, e: anytype) !u64 { + const g = x.gpu(); + const profile: @import("disk_identity.zig").Profile = .{ .family = nemotron.native.model_type, .backend = "cuda" }; + return disk.withPolicy(try disk.identityOf(x.arena.allocator(), t.io, &g, x.dir, null, &.{0}, 42, profile), e); +} + +test "disk identity: Nemotron CUDA resolved checkpoint math, expert ranks and grids miss with the same probe" { + var x: Fixture = undefined; + try x.init(); + defer x.deinit(); + const Target = nemotron.native.kept_states.Target; + var e: @typeInfo(@FieldType(Target, "e")).pointer.child = undefined; + e.c.ck = false; + e.c.world = 1; + e.k.experts.resident = @splat(48); + e.k.modelopt = null; + e.k.ck = null; + e.k.triton = null; + e.segments = 1; + e.nch = 32; + const before = try nemotronKey(&x, &e); + var changed: std.ArrayList(u64) = .empty; + defer changed.deinit(t.allocator); + e.c.ck = true; // --precision checkpoint + try changed.append(t.allocator, try nemotronKey(&x, &e)); + e.c.ck = false; + e.c.world = 2; // TF_NEMOTRON_WORLD=2: the experts' sums over two ranks + try changed.append(t.allocator, try nemotronKey(&x, &e)); + e.c.world = 1; + e.k.experts.resident[2] = 47; + try changed.append(t.allocator, try nemotronKey(&x, &e)); + e.k.experts.resident[2] = 48; + var m: @typeInfo(@FieldType(@TypeOf(e.k), "modelopt")).optional.child = undefined; + m.experts.warps = 4; + m.experts.resident = @splat(48); + m.lane.half_below = cuda.qmmf.half_below_default; + e.k.modelopt = m; + const four = try nemotronKey(&x, &e); + e.k.modelopt.?.experts.warps = 1; // TF_NVFP4_DECODE_WARPS=1 on the same grids + const one = try nemotronKey(&x, &e); + try t.expect(four != one); + try changed.appendSlice(t.allocator, &.{ four, one }); + e.k.modelopt.?.experts.warps = 4; + e.k.modelopt.?.lane.half_below = 0; // TF_QMMF_HALF_BELOW=0: a short pass's rows on the 64-column tile + const full_tile = try nemotronKey(&x, &e); + try t.expect(four != full_tile); + try changed.append(t.allocator, full_tile); + e.k.modelopt = null; + var ck: @typeInfo(@FieldType(@TypeOf(e.k), "ck")).optional.child = undefined; + ck.resident = @splat(@splat(48)); + ck.prompt_resident = @splat(48); + e.k.ck = ck; + try changed.append(t.allocator, try nemotronKey(&x, &e)); + e.k.ck = null; + e.k.triton = @as(cuda.aot.Set, undefined); // a captured set: its NCH variant follows --context + const short = try nemotronKey(&x, &e); + e.nch = 64; + const long = try nemotronKey(&x, &e); + try t.expect(short != long); + try changed.appendSlice(t.allocator, &.{ short, long }); + e.k.triton = null; + e.segments = 4; // staggered segments run only passes that keep no state + e.nch = 64; // a longer --context on our glue: more chunk programs a row, whose merge reads only its own + try fixture.misses(before, try nemotronKey(&x, &e), changed.items); +} diff --git a/zig/src/native/disk_identity.zig b/zig/src/native/disk_identity.zig index 451a6411d79..3126a14864b 100644 --- a/zig/src/native/disk_identity.zig +++ b/zig/src/native/disk_identity.zig @@ -3,29 +3,42 @@ const std = @import("std"); const api = @import("engine_api"); const Allocator = std.mem.Allocator; -/// A checkpoint folder: its config and index files whole, then each safetensors file's name, size, inode and times. +/// Config/index bytes, stamps of every indexed shard (IndexedShardMissing if absent) and top-level safetensors. pub fn checkpoint(h: *std.hash.Wyhash, a: Allocator, io: std.Io, dir: []const u8) !void { + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const scratch = arena.allocator(); + var indexed: std.StringArrayHashMapUnmanaged(void) = .empty; for ([_][]const u8{ "config.json", "model.safetensors.index.json" }) |name| { - const path = try std.fs.path.join(a, &.{ dir, name }); - const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 26)) catch |e| switch (e) { + const path = try std.fs.path.join(scratch, &.{ dir, name }); + const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, scratch, .limited(1 << 26)) catch |e| switch (e) { error.FileNotFound => continue, else => return e, }; h.update(name); h.update(bytes); + if (std.mem.eql(u8, name, "model.safetensors.index.json")) { + const parsed = try std.json.parseFromSliceLeaky(std.json.Value, scratch, bytes, .{}); + const map = try @import("checkpoint_config").index.weightMap(parsed); + for (map.values()) |value| try indexed.put(scratch, value.string, {}); + } } + var names: std.ArrayList([]const u8) = .empty; + try names.appendSlice(scratch, indexed.keys()); var d = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); defer d.close(io); - var names: std.ArrayList([]const u8) = .empty; var it = d.iterate(); - while (try it.next(io)) |e| if (std.mem.endsWith(u8, e.name, ".safetensors")) try names.append(a, try a.dupe(u8, e.name)); + while (try it.next(io)) |e| if (std.mem.endsWith(u8, e.name, ".safetensors")) + try names.append(scratch, try scratch.dupe(u8, e.name)); std.mem.sort([]const u8, names.items, {}, struct { fn lt(_: void, x: []const u8, y: []const u8) bool { return std.mem.lessThan(u8, x, y); } }.lt); - for (names.items) |name| { - const info = try d.statFile(io, name, .{}); + for (names.items, 0..) |name, i| { + if (i > 0 and std.mem.eql(u8, name, names.items[i - 1])) continue; + const info = d.statFile(io, name, .{}) catch |e| + return if (e == error.FileNotFound and indexed.contains(name)) error.IndexedShardMissing else e; const stamp = [4]i128{ info.size, info.inode, info.mtime.nanoseconds, info.ctime.nanoseconds }; h.update(name); h.update(std.mem.sliceAsBytes(&stamp)); diff --git a/zig/src/native/flashnext_disk.zig b/zig/src/native/flashnext_disk.zig index b69ecfbfbf4..b2ce19010f4 100644 --- a/zig/src/native/flashnext_disk.zig +++ b/zig/src/native/flashnext_disk.zig @@ -145,7 +145,7 @@ pub fn identity(gpa: Allocator, io: std.Io, dir: []const u8, eng: *fx.Engine) !s h.update(api.prompt_imprint.osBuild(&os)); h.update(std.mem.span(eng.r.device.name())); @import("disk_identity.zig").profile(&h, .{ .family = "qwen4_exp", .backend = "metal" }); - return .{ .id = try @import("disk_identity.zig").scoped(gpa, io, dir, h.final()), .rate = 4143.0 / (@as(f64, @floatFromInt(@max(ns, 1))) / 1e9) }; + return .{ .id = try @import("disk_identity.zig").scoped(gpa, io, dir, try withInputs(withPolicy(h.final(), eng.r), gpa, io, eng.r)), .rate = 4143.0 / (@as(f64, @floatFromInt(@max(ns, 1))) / 1e9) }; } /// --learn-conversations or --spill-gib: the store under `l.root`, attached to the cache (Imprint's cut files unread). @@ -155,3 +155,28 @@ pub fn attach(gpa: Allocator, store: *api.prompt_cache.Store, id: anytype, l: an std.log.info("flash next: conversation states on disk in {s} ({d} states, {d} MiB of {d} MiB)", .{ r.dir, r.states.items.len, r.held() >> 20, l.cap >> 20 }); return r; } + +/// Extend a probe identity with the loaded execution policy (`serial` orders launches, not arithmetic: not keyed). +pub fn withPolicy(legacy: u64, run: anytype) u64 { + return @import("persistence_policy.zig").extend(legacy, "flash-metal-policy-v1", &.{ + @intFromBool(run.fused_xsum), @intFromBool(run.dense), @intFromBool(run.dense_target), + @intFromBool(run.split), @intFromBool(run.gdn_step), @intFromBool(run.hc_mma), + @intFromBool(run.grouped), @intFromBool(run.xpack), @intFromBool(run.xfused), + @intFromBool(run.xsx), @intFromBool(run.copy), @intFromBool(run.prefetch), + @intFromBool(run.lane_new), @intFromBool(run.rotary_enabled), run.skip, + run.hcskip, run.gskip, run.lane_pf, + // fz_gdn and its kept-state form write the DeltaNet state and conv rows a snapshot copies (snapshot.zig) + @intFromBool(run.gdn_pipe != null), @intFromBool(run.gdn_kept != null), @intFromBool(run.gx != null), + if (run.gx) |g| g.min_rows else 0, @intFromBool(run.tp != null), if (run.tp) |tp| tp.rank else 0, + }); +} + +/// Indexed weight files include the actual pack outside the source checkpoint. +pub fn withFiles(legacy: u64, a: Allocator, io: std.Io, files: []const c_int) !u64 { + return @import("persistence_policy.zig").files(legacy, a, io, files); +} + +/// The loaded weight files and metadata, including a supplied reference outside the checkpoint. +pub fn withInputs(legacy: u64, a: Allocator, io: std.Io, run: anytype) !u64 { + return @import("persistence_policy.zig").mapped(try withFiles(legacy, a, io, run.files.items), a, run.maps.items); +} diff --git a/zig/src/native/glm_disk.zig b/zig/src/native/glm_disk.zig index 688bdb6ce7e..efa9574e10d 100644 --- a/zig/src/native/glm_disk.zig +++ b/zig/src/native/glm_disk.zig @@ -99,5 +99,33 @@ pub fn identity(a: Allocator, io: std.Io, dir: []const u8, eng: *const glm.engin h.update(api.prompt_imprint.osBuild(&os)); h.update(std.mem.span(eng.device.name())); @import("disk_identity.zig").profile(&h, .{ .family = "glm5_next", .backend = "metal" }); - return .{ .id = try @import("disk_identity.zig").scoped(a, io, dir, h.final()), .rate = 4143.0 / (@as(f64, @floatFromInt(@max(ns, 1))) / 1e9) }; + return .{ .id = try @import("disk_identity.zig").scoped(a, io, dir, withPolicy(h.final(), eng)), .rate = 4143.0 / (@as(f64, @floatFromInt(@max(ns, 1))) / 1e9) }; +} + +/// Whether a prompt pass's MTP eh_proj runs on the tile kernel: a bf16 head and the pipeline the load built. +pub fn ehTile(eng: anytype) bool { + const head = eng.w.mtp orelse return false; + return eng.pr != null and head.eh_bf16 != null and eng.k.wide != null and eng.k.wide.?.bf16_nax != null; +} + +/// Extend a probe identity with the resolved execution policy; another chunk height (pr.rows) starts cold. +pub fn withPolicy(legacy: u64, eng: anytype) u64 { + const c = eng.c; + return @import("persistence_policy.zig").extend(legacy, "glm-metal-policy-v1", &.{ + c.run, + c.tp, + c.tp_rank, + c.own[0], + c.own[1], + c.inter[0], + c.inter[1], + c.dense_inter, + c.kda_heads, + c.mla_heads, + @intFromBool(eng.fused_route), + @intFromBool(eng.pr != null), + if (eng.pr) |p| p.rows else 0, // prompt windows and chunks sum in different orders + if (eng.pr) |p| @intFromBool(p.sparse_nax) else 0, + @intFromBool(ehTile(eng)), + }); } diff --git a/zig/src/native/metal_identity.zig b/zig/src/native/metal_identity.zig index e89564d1fa8..1e99aae1c4e 100644 --- a/zig/src/native/metal_identity.zig +++ b/zig/src/native/metal_identity.zig @@ -9,10 +9,6 @@ const Allocator = std.mem.Allocator; pub fn learned(a: Allocator, io: std.Io, dir: []const u8, b: *nemotron.backend.Metal) !struct { id: u64, rate: f64 } { var h = std.hash.Wyhash.init(0x6e65); try @import("sys").file_identity.current(&h, a, io); - for ([_][]const u8{ "config.json", "model.safetensors.index.json" }) |name| { - const path = try std.fs.path.join(a, &.{ dir, name }); - h.update(try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 26))); - } try shardStamps(&h, a, io, dir); if (b.head != null) h.update(try safetensorsHeader(a, dir, "mtp-4bit.safetensors")); const t0 = std.Io.Clock.awake.now(io).toNanoseconds(); @@ -25,27 +21,18 @@ pub fn learned(a: Allocator, io: std.Io, dir: []const u8, b: *nemotron.backend.M h.update(api.prompt_imprint.osBuild(&os)); h.update(std.mem.span(b.m.device.name())); @import("disk_identity.zig").profile(&h, .{ .family = "nemotron_h", .backend = "metal" }); - return .{ .id = h.final(), .rate = 4143.0 / (@as(f64, @floatFromInt(@max(ns, 1))) / 1e9) }; + return .{ .id = withPolicy(h.final(), b), .rate = 4143.0 / (@as(f64, @floatFromInt(@max(ns, 1))) / 1e9) }; } -/// Each safetensors file's name, size, inode and change times: a weight written in place (--slide) moves the identity. -fn shardStamps(h: *std.hash.Wyhash, a: Allocator, io: std.Io, dir: []const u8) !void { - var d = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); - defer d.close(io); - var names: std.ArrayList([]const u8) = .empty; - var it = d.iterate(); - while (try it.next(io)) |e| if (std.mem.endsWith(u8, e.name, ".safetensors")) try names.append(a, try a.dupe(u8, e.name)); - std.mem.sort([]const u8, names.items, {}, struct { - fn lt(_: void, x: []const u8, y: []const u8) bool { - return std.mem.lessThan(u8, x, y); - } - }.lt); - for (names.items) |name| { - const info = try d.statFile(io, name, .{}); - const stamp = [4]i128{ info.size, info.inode, info.mtime.nanoseconds, info.ctime.nanoseconds }; - h.update(name); - h.update(std.mem.sliceAsBytes(&stamp)); - } +/// Extend the key with the coop K-slice split the load resolved: on or off, and the scratch rows a split must fit. +pub fn withPolicy(legacy: u64, b: anytype) u64 { + const rows: u64 = if (b.coop_split) b.scratch.rows else 0; // with no split, the rows decide nothing + return @import("persistence_policy.zig").extend(legacy, "nemotron-metal-policy-v1", &.{ @intFromBool(b.coop_split), rows }); +} + +/// The checkpoint's current stamps, including validated indexed subfolders and auxiliary top-level files. +pub fn shardStamps(h: *std.hash.Wyhash, a: Allocator, io: std.Io, dir: []const u8) !void { + try @import("disk_identity.zig").checkpoint(h, a, io, dir); } /// A safetensors file's header (its tensors' names, shapes and offsets), in `a`. @@ -61,7 +48,7 @@ fn safetensorsHeader(a: Allocator, dir: []const u8, name: []const u8) ![]const u return head; } -test "a shard rewritten in place, same size and bytes, gives the learned states a new identity" { +test "persistence identity: a Nemotron Metal shard rewritten in place, same size and bytes, gets a new identity" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -80,12 +67,15 @@ test "a shard rewritten in place, same size and bytes, gives the learned states var notes = std.hash.Wyhash.init(0); try shardStamps(¬es, a, io, dir); try std.testing.expectEqual(first.final(), notes.final()); - std.Io.sleep(io, .fromMilliseconds(5), .awake) catch {}; - const path = try std.fmt.allocPrintSentinel(a, "{s}/model-00001-of-00001.safetensors", .{dir}, 0); + const shard = "model-00001-of-00001.safetensors"; + const was = (try tmp.dir.statFile(io, shard, .{})).mtime; + const path = try std.fmt.allocPrintSentinel(a, "{s}/" ++ shard, .{dir}, 0); const fd = platform.c.open(path, .{ .ACCMODE = .WRONLY }, @as(platform.c.mode_t, 0)); try std.testing.expect(fd >= 0); try std.testing.expectEqual(@as(isize, 7), platform.c.pwrite(fd, "weights", 7, 0)); // as Sliding Weights writes a tensor of the same size _ = platform.c.close(fd); + // a coarse clock can leave the pwrite's mtime unchanged: move it a second on, as a later write would + try tmp.dir.setTimestamps(io, shard, .{ .modify_timestamp = .{ .new = was.addDuration(.fromSeconds(1)) } }); var moved = std.hash.Wyhash.init(0); try shardStamps(&moved, a, io, dir); try std.testing.expect(first.final() != moved.final()); diff --git a/zig/src/native/persistence_fixture.zig b/zig/src/native/persistence_fixture.zig new file mode 100644 index 00000000000..04a80b98cf1 --- /dev/null +++ b/zig/src/native/persistence_fixture.zig @@ -0,0 +1,97 @@ +//! Real conversation files for host namespace regressions; the eight-byte image uses no device. +const std = @import("std"); +const builtin = @import("builtin"); +const pc = @import("engine_api").prompt_cache; +const rows = pc.rows; +const a = std.testing.allocator; +const value: u64 = 0x123456789abcdef0; +const tokens = [_]u32{ 5, 7, 11 }; + +fn bytes(_: *anyopaque, _: u32) u64 { + return 8; +} +fn save(_: *anyopaque, _: ?*anyopaque, _: u32) !pc.Saved { + const p = try a.create(u64); + p.* = value; + return p; +} +fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) !void {} +fn drop(_: *anyopaque, saved: pc.Saved) void { + a.destroy(@as(*u64, @ptrCast(@alignCast(saved)))); +} +fn parts(_: *anyopaque, _: u32, out: *std.ArrayList(rows.image.Part), allocator: std.mem.Allocator) !void { + try out.append(allocator, .{ .bytes = 8 }); +} +fn blank(ptr: *anyopaque, at: u32) !pc.Saved { + const saved = try save(ptr, null, at); + @as(*u64, @ptrCast(@alignCast(saved))).* = 0; + return saved; +} +fn copyOut(_: *anyopaque, saved: pc.Saved, ranges: []const rows.image.Range, out: []u8) !void { + const p: *u64 = @ptrCast(@alignCast(saved)); + var at: usize = 0; + for (ranges) |range| { + const n: usize = @intCast(range.len); + @memcpy(out[at..][0..n], std.mem.asBytes(p)[@intCast(range.off)..][0..n]); + at += n; + } +} +fn copyIn(_: *anyopaque, saved: pc.Saved, ranges: []const rows.image.Range, in: []const u8) !void { + const p: *u64 = @ptrCast(@alignCast(saved)); + var at: usize = 0; + for (ranges) |range| { + const n: usize = @intCast(range.len); + @memcpy(std.mem.asBytes(p)[@intCast(range.off)..][0..n], in[at..][0..n]); + at += n; + } +} +const image: rows.Image = .{ .parts = parts, .gather = copyOut, .blank = blank, .scatter = copyIn }; +const vtable: pc.Snapshots.VTable = .{ .bytes = bytes, .save = save, .restore = restore, .drop = drop, .rows = &image }; + +/// `data` over `sub_path` in place, then its mtime one second on: a coarse clock cannot hide the rewrite. +pub fn rewrite(dir: std.Io.Dir, sub_path: []const u8, data: []const u8) !void { + const io = std.testing.io; + const before = (try dir.statFile(io, sub_path, .{})).mtime; + try dir.writeFile(io, .{ .sub_path = sub_path, .data = data }); + // Zig 0.17's std can't set timestamps on Windows; NTFS's write time moves by itself, so only an unmoved one skips + if (builtin.os.tag == .windows) { + if ((try dir.statFile(io, sub_path, .{})).mtime.nanoseconds == before.nanoseconds) return error.SkipZigTest; + return; + } + try dir.setTimestamps(io, sub_path, .{ .modify_timestamp = .{ .new = before.addDuration(.fromSeconds(1)) } }); +} + +/// Plant a file, reopen and read it, then reject changed keys without destroying the matching state. +pub fn misses(before: u64, matching: u64, changed: []const u64) !void { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try tmp.dir.realPathFileAlloc(std.testing.io, ".", a); + defer a.free(root); + var context: u8 = 0; + const family: pc.Snapshots = .{ .ptr = &context, .vtable = &vtable }; + var options: rows.Options = .{ .root = root, .identity = before, .cap = 1 << 20, .floor = 0, .daily = 1 << 20, .lookahead = 1, .sync_writes = true }; + { + const disk = try rows.Rows.open(a, family, options); + defer disk.deinit(); + var store = pc.Store.init(a, family, .{ .lookahead = 1 }, 1 << 20); + defer store.deinit(); + store.disk = disk; + try std.testing.expect(store.keep(&tokens, 2, null, &.{}, &.{})); + while (rows.write.step(disk)) {} + try std.testing.expectEqual(@as(u64, 1), disk.counts.writes); + } + options.identity = matching; + const same = try rows.Rows.open(a, family, options); + defer same.deinit(); + const i = same.best(&tokens, &.{}, &.{}, 0) orelse return error.ExpectedMatchingDiskState; + const saved = try rows.read.read(same, i); + defer drop(&context, saved); + try std.testing.expectEqual(value, @as(*u64, @ptrCast(@alignCast(saved))).*); + for (changed) |identity| { + options.identity = identity; + const stale = try rows.Rows.open(a, family, options); + defer stale.deinit(); + try std.testing.expect(stale.best(&tokens, &.{}, &.{}, 0) == null); + try std.testing.expect(same.best(&tokens, &.{}, &.{}, 0) != null); + } +} diff --git a/zig/src/native/persistence_policy.zig b/zig/src/native/persistence_policy.zig new file mode 100644 index 00000000000..d3f168256d7 --- /dev/null +++ b/zig/src/native/persistence_policy.zig @@ -0,0 +1,47 @@ +//! Resolved runtime facts and opened weight files extend a probe key without changing a state's image. +const std = @import("std"); + +pub fn extend(legacy: u64, domain: []const u8, words: []const u64) u64 { + var h = std.hash.Wyhash.init(legacy); + h.update(domain); + h.update(std.mem.sliceAsBytes(words)); + return h.final(); +} + +/// The descriptors the loader indexed, including a pack outside the checkpoint folder; order is immaterial. +pub fn files(legacy: u64, a: std.mem.Allocator, io: std.Io, descriptors: []const c_int) !u64 { + const stamps = try a.alloc([4]i128, descriptors.len); + defer a.free(stamps); + for (descriptors, stamps) |fd, *stamp| { + if (fd < 0) return error.IdentityFileUnavailable; + const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; + const stat = try file.stat(io); + stamp.* = .{ stat.size, stat.inode, stat.mtime.nanoseconds, stat.ctime.nanoseconds }; + } + std.mem.sort([4]i128, stamps, {}, struct { + fn less(_: void, x: [4]i128, y: [4]i128) bool { + for (x, y) |left, right| if (left != right) return left < right; + return false; + } + }.less); + var h = std.hash.Wyhash.init(legacy); + h.update("loaded-weight-stamps-v1"); + h.update(std.mem.sliceAsBytes(stamps)); + return h.final(); +} + +/// Loaded metadata and shader documents are already mapped; hash only their used bytes, independent of map order. +pub fn mapped(legacy: u64, a: std.mem.Allocator, maps: anytype) !u64 { + const digests = try a.alloc([32]u8, maps.len); + defer a.free(digests); + for (maps, digests) |m, *digest| std.crypto.hash.sha2.Sha256.hash(m.bytes[0..m.size], digest, .{}); + std.mem.sort([32]u8, digests, {}, struct { + fn less(_: void, x: [32]u8, y: [32]u8) bool { + return std.mem.lessThan(u8, &x, &y); + } + }.less); + var h = std.hash.Wyhash.init(legacy); + h.update("loaded-metadata-v1"); + h.update(std.mem.sliceAsBytes(digests)); + return h.final(); +} diff --git a/zig/src/native/qwen27_disk.zig b/zig/src/native/qwen27_disk.zig index 9174f6df79f..cd73f2cad48 100644 --- a/zig/src/native/qwen27_disk.zig +++ b/zig/src/native/qwen27_disk.zig @@ -89,7 +89,7 @@ pub fn identity(h: *Host, io: std.Io, a: Allocator, dir: []const u8, drafter: ?[ w.update(std.mem.sliceAsBytes(&words)); disk_identity.machine(&w, std.mem.span(h.model.device.name())); disk_identity.profile(&w, .{ .family = if (h.model.config.moe()) "qwen3_5_moe" else "qwen3_5", .backend = "metal" }); - return .{ .id = w.final(), .rate = p.rate }; + return .{ .id = withPolicy(w.final(), h), .rate = p.rate }; } /// A fixed prompt's state through slot 0 (whole 128-row chunks, a decoded span, a short tail), hashed, and its rate. @@ -141,3 +141,11 @@ pub fn attach(h: *Host, io: std.Io, a: Allocator, o: Learn) !void { /// --learn-conversations' settings, as the server read them (--spill-gib's too, and --checkpoint-slots beside them). pub const Learn = struct { root: []const u8, dir: []const u8, drafter: ?[]const u8, cap: u64, floor: u64, daily: u64, spill: rows.Spill = .off, slots: ?usize = null }; + +/// Extend a probe identity with the ANE columns and the chunk height; another chunk height starts cold. +pub fn withPolicy(legacy: u64, h: anytype) u64 { + return @import("persistence_policy.zig").extend(legacy, "qwen-metal-policy-v1", &.{ + if (h.model.ane) |share| share.columns else 0, + h.back.chunk, // not frame.capacity: it only sizes buffers and bounds a pass's rows + }); +} diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 3dc4bacc787..022632984d5 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -56,6 +56,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_HEAD_GEOMETRY", .scope = .metal, .kind = .size, .forms = "a whole nonnegative native-size geometry count" }, .{ .name = "TF_PROMPT_ROWS", .scope = .metal, .kind = .prompt, .forms = "a multiple of 16 from 128 to 2048 for native serving" }, .{ .name = "TF_ANE_COLUMNS", .scope = .metal, .kind = .u32, .forms = "a whole column count from 0 to 4294967295 (0 disables the share)" }, + .{ .name = "GLM_EHPROJ_NAX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 serves GLM's MTP eh_proj on the scalar kernel)" }, .{ .name = "XPU_A8_BITS", .scope = .xpu, .kind = .bit_width, .forms = "4 or 8" }, .{ .name = "LFM3_FUSE", .scope = .xpu, .kind = .u32, .forms = "a whole fusion mask from 0 to 4294967295" }, .{ .name = "TF_SLIDE_POCKET_KEY", .scope = .slide, .kind = .word, .words = &.{ "auto", "reply", "subject", "both" }, .forms = "auto, reply, subject or both" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 67c26fd6bc6..1148f748d0a 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -81,6 +81,8 @@ const valid = [_]Case{ .{ .name = "TF_PROMPT_ROWS", .raw = "2048", .n = 2048 }, .{ .name = "TF_ANE_COLUMNS", .raw = "0", .n = 0 }, .{ .name = "TF_ANE_COLUMNS", .raw = "3072", .n = 3072 }, + .{ .name = "GLM_EHPROJ_NAX", .raw = "0", .n = 0 }, + .{ .name = "GLM_EHPROJ_NAX", .raw = "1", .n = 1 }, .{ .name = "XPU_A8_BITS", .raw = "4", .n = 4 }, .{ .name = "XPU_A8_BITS", .raw = "8", .n = 8 }, .{ .name = "LFM3_FUSE", .raw = "7", .n = 7 },